Library for model helpers

Question: I want to keep EntityFramework model class clean and only present database structure,
So if it needs helper methods, I may add a seperate class, example:
public class Book{
    public string Name { get; set; }
}

public class BookHelper{
    public Book Entity;
    public List<Book> OtherSeries(){
        var books =  Entity.Author.Books;
        books.remove(Entity);
        return books;
    }
}

Is any Library to standalize this?
Answer: There are some ways to do this. But I don't think they are called/considered standard. It's just your own preference. But whatever you choose to do, don't put so many methods into 1 class, it breaks the Single Responsibility.
First, Use extension method
public static class BookExntensions
{
    public static List<Book> OtherSeries(this Book book)
    {
        var books =  book.Author.Books;
        books.remove(Entity);
        return books;
    }
}

Second, Use Helper class like the way you did.
Third, Use Helper with generic type, so you can reuse some of the code.
public class EntityHelper<T>
{
    private T Entity;
}
public class BookHelper : EntityHelper<Book>
{
    public List<Book> OtherSeries()
    {
       var books =  Entity.Author.Books;
       books.remove(Entity);
       return books;
    }
}

There are still more ways to do, but I'll leave them out.

Library for model helpers


Uniform convergence of $\frac{1}{1+nz}$

Question: $\bigg(\dfrac{1}{1+nz}\bigg)$ converges pointwise to $f(z) = 0$ on $\mathbb{C}- \{0\}$.

What is the region of uniform convergence of $\bigg(\dfrac{1}{1+nz}\bigg)$ to $f(z) = 0$?

For any $r>0$ , let $D_r = \{|z|>r\}$.
For any $\epsilon >0,\ $ let N be an integer larger than $\frac{1}{r\epsilon}$.
Then $\forall n\geq N, \forall z\in D_r$,
$|\frac{1}{1+nz}| \leq |\frac{1}{nz}|<\frac{1}{nr} < \epsilon$.
Hence, the region of uniform convergence is $|z|>r$ for any $r>0$. $\ \ \ \square$
Is this the correct region of uniform convergence?
If we let $z=\frac{1}{n}$, then $\frac{1}{1+nz} = \frac{1}{2}$, which contradicts the above result.
Where did i go wrong? Help please.

Furthermore, i want to prove that $(\frac{1}{1+nz})$ converges uniformly on any compact subset of the complex plane that does not contain the origin.

Suppose that $K$ is a compact subset of $\mathbb{C}$. I want to show that there exists $\delta>0$ such that $\forall z\in K, |z| \geq \delta$.
I was given the following topological result (without proof) in the introductory course:

If $f:K\to \mathbb{C}$ is continuous, then $|f|$ is continuous and $\max_{z\in K} |f(z)|$ exists.

Let $f(z) = \frac{1}{z}$, where $f$ is continuous on $K$. Then, $\exists m = \max_{z\in K} \frac{1}{|z|}$. Hence, $\min_{z\in K} |z|= \frac{1}{m}$ and let $\delta = \min_{z\in K} |z|$.
Is this correct?
Comment: I don't think $\frac{1}{|1+nz|}\leq\frac{1}{|nz|}$ is correct, it's only correct for $Re(z) \geq 0$.
Comment: @BCLC Yes, that's the book I was looking at.
Comment: Note: @Nan and I got that from [Exer 7.22(c)](https://math.stackexchange.com/questions/2610950/) of [A First Course in Complex Analysis by Matthias Beck, Gerald Marchesi, Dennis Pixton, and Lucas Sabalka](http://math.sfsu.edu/beck/complex.html)
Answer: There's not "the" region, but any of the $D_r$ sets with $r>0$ is a region of uniform convergence. That is: once you fix an $r>0$ you have $D_r$ a region of u.c. But is not true that $\bigcup_{r>0}D_r=\mathbb{C}\setminus\{0\}$ is a region of u.c.: your example actually disproves it. But your example doesn't work on a fixed $D_r$ since only finitely many points of the form $\tfrac1n,\, n\in\mathbb{N},$ are in $D_r$.
Comment: You mean $\tfrac1{n+z}$ or $\tfrac1{1+nz}$ as in the question?
Comment: I think we have infinite $\frac{1}{n}$ on the ball $|z-1|<1$
Comment: Do you disagree with Nan? Nan says $D_r$ works only for $\Re(z) \ge 0$. I guess we could modify to union = $\Re(z) \ge 0 \setminus \{0\}$
Comment: We do have infinite points of $\{\frac1n\in\mathbb C \colon n\in \mathbb N\}$ on the ball $\{z\in\mathbb C\colon |z-1|<1\}$, but this is none of the $D_r$ regions mentioned in the question or in this answer...
Answer: Regarding your last two questions, I believe they are not about $\mathbb{C}$ but about $\mathbb{C} \setminus \{0\}$.
First, you're own counterexample shows that convergence of $\tfrac1{1+nz}$ to its pointwise limit cannot be uniform in any set containing a neighborhood of $z=0$.
And second, your last statement is just not true. Any compact set containing $z=0$ (for instance any zero-centered closed disc, just to mention a few infinity number of examples) will clearly fail to satisfy the desired $\delta$ property.
Comment: Sorry i mean any compact subset that does not contain the origin.

Uniform convergence of $\frac{1}{1+nz}$


Bank conflict in parallel reduction using interleaved addressing method

Question: I was reading the presentation on Optimizing Parallel Reduction in CUDA by Mark Harris. Here is a slide I have problem in:

It says there is bank conflict problem in this method. But why? All threads are accessing two consecutive memory cell which are in different banks. Neither of them accesses a specific memory cell concurrently.
Answer: This presentation dates from the very early days of CUDA, and applies to first generation hardware.
That hardware had shared memory arranged in 8 32 bit banks. Because every eighth entry in the shared array resides in the same bank, there are bank conflicts at a number of levels of that reduction tree.
This problem was addressed in newer hardware, where the number of banks was expanded to 32, meaning that this sort of bank conflict cannot occur.
Comment: Doesn't it still occur when the threads are all reading from addresses at multiples of 32 (* 4 bytes)?
Comment: @mirgee: The solution is to use sequential addressing instead of interleaved addressing. So all the 8 writes will be into different banks and is totally conflict-free. See slide 14 of https://developer.download.nvidia.com/assets/cuda/files/reduction.pdf.


Asking for a proof for the number of free variables in a consistent linear system

Question: Given any system of linear equations, we can represent it by an augmented matrix and turn the matrix into (reduced) row echelon form.

Let $p$ denote the number of pivots in the (reduced) row echelon form and $n$ denote the number of unknowns in the system. If the system is consistent, then there are $n-p$ unknowns whose value can be assigned arbitrarily, and in particular, we can always be sure that if column $i$ of the (reduced) row echelon matrix does not contain a pivot, then we can choose to assign arbitrary value to the unknown $x_i$.

It's quite obvious to "see" that the above statement is true whenever we have an example of (reduced) row echelon matrix representing a consistent linear system. But may I ask how to prove the above statement in a rigorous manner?
Thanks in advance!
Comment: Updated the answer if you have any questions let me know.
Comment: Hi JAS! Is there any way I can expand my answer to help you better?
Comment: @AlexD Hi Alex, thank you for your reply, sorry I was on something else and just saw your answer. I'll read it now and come back to you if I have any question related. Thanks again :)
Answer: Suppose you have the $n$ by $n$ matrix $A$, and that you were trying to find a vector $x$ such that $Ax=b,$ for some vector $b$ in $\mathbb{R}^{n}$.
Also suppose you were able to find a solution, call it $x_{p}$, by putting the augmented matrix $A|b$ in reduced row echelon form. This is only one solution. The complete solution $\hat x$ is given by $$\hat{x}=x_{p}+x_{n},\tag{$\star$}$$ where $x_{n}$ is ANY vector in the null space of $A$.
Remember that the null space is the set of all vectors $x$ such that $Ax=0$. Then $\hat{x}$ is indeed the complete solution since we have
$$
     \begin{alignat*}{2}
          A\hat{x}&=A(x_{p}+x_{n})\\
                  &=Ax_{p}+Ax_{n}\\
                  &=(b)+(0)\\
                  &=b.
     \end{alignat*}
$$

To answer your question:
Having $p$ column pivots means you have $p$ linearly independent column vectors, so the dimension of the column space of the matrix is $p$.
The dimension of the null space must then be $(n-p)$, so a list of $(n-p)$ independent vectors span the null space.
Suppose $x_{1},x_{2},...,x_{n-p}$ is such a list of $(n-p)$ independent vectors spanning the null space of A. Since the null space is a vector space, it is closed under addition and scalar multiplication. This means that any linear combination of $x_{1},x_{2},...,x_{n-p}$ will be in the null space of A. That is to say, the vector $$x_{n}=a_{1}x_{1}+a_{2}x_{2}+...+a_{n-p}x_{n-p}$$ is in the null space, for arbitrary coefficients $a_{i}$.
Then the complete solution from $(\star)$ becomes
$$
     \begin{alignat*}{2}
          \hat{x}&=x_{p}+x_{n}\\
                 &=x_{p}+(a_{1}x_{1}+a_{2}x_{2}+...+a_{n-p}x_{n-p}),
     \end{alignat*}
$$
where we can pick arbitrary values for $a_{1},...,a_{n-p}$. These are the $(n-p)$ arbitrary unknowns you mention in your question.
Comment: Thanks Alex, the answer is good by far I can see. The only thing is that I guess I need to recap some linear algebra to see why every solution is included in the form $\hat{x}=x_{p}+x_{n}$ and why the dimension of null space is related to the dimension of the column space by $n-p$. If you could include some hints for them that would be great :) Also, may I ask if similar argument could be used for generalisation to arbitrary field (other than $\mathbb{R}$)?


How do I evaluate string lists in Python

Question: I'm trying to make a script that evaluates a word to see whether or not its parts add up to 23 in any way (all four operations).
I've gotten it down to creating a string list of possible equations:
answerList = [12+15+12,12+15-12,12+15/12,...]

The problem I'm now getting is that I cannot get them back out of the lists in integer format to see whether or not they actually equal 23/32.
Comment: Are you trying to index into a list? `answerList[index]` will do that. I can't say much more without knowing what a word is and how it is evaluated
Comment: a word is any word whatsoever. I input a word, it breaks it down into its pieces, and then is supposed to evaluate them. So, for instance, I'd type in 'lol', it'd place it into a list of ['l', 'o', 'l'], then it would match that against an alphabet to number list for its number equivalent, then put that into a different list giving me ['12', '15', '12']. I'd take that list, use a nested for list to add operations, and get a third list filled with the iterations of operations (like ++, +-, +/, +*, --,...). I just didn't have a way of taking them out of that list. Eval() worked.
Answer: Check out the eval() function
>>> eval("12+15+12")
39
>>> eval("12+15/12")
13

Then, you can just loop through the list, calling eval on each while doing something with the result.
Answer: If you store your data like your example it will automatically convert them to integer anyway
e.g. :
>>> answerList = [12+15+12,12+15-12,12+15/12, ...]
>>> answerList
[39, 15, 13, ...]

However, if you want to store it and print it out which equation has result 23, your need to store them as a string then use eval to convert them to int to check that it equal to 23 or not then print out the equation.
answerList = ['12+15+12','12+15-12','12+15/12']
for equation in answerList :
  if eval(equation) == 23 :
    print equation

Comment: You know, I thought it'd do that too, but it actually wasn't auto converting them. I had seen that type of behavior before, so I was fairly certain I wouldn't run into any problems doing it that way. Apparently I must of done something weird, but at least I got the job done eventually. Haha


Parâmetro chegando de maneira truncada em requisição Ajax

Question: Tenho uma requisição Ajax que obtém os dados que preciso a partir de um WebMethod. O problema é que o parâmetro utilizado para a requisição está "chegando" truncado no WebMethod o comprimento do parâmetro é de 44 dígitos.
Parâmetro enviado: 31161102996615000145550000000413281487877818.
Como está chegando: 3.1161102996615E+43
Código Ajax:
var valorCampo= $(this).attr('data-clipboard-text');
var content = "parametroConsulta=" + encodeURIComponent(valorCampo);

$.ajax({

        type: "GET",
        dataType: 'json',
        async: false,
        contentType: "application/json; charset=utf-8",
        url: "myPage.aspx/ObtenhaDados",
        data: content,
        success: function (data) { dadosObtidos(data); },
        error: function (data) { falhaConsulta(data); }

});

WebMethod:
 [WebMethod]
 [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
 public static DadosPessoais ObtenhaDados(string valoPesquisa)
 { .... }

Url exibida no FireBug:
http://localhost:61187/ps/myPage.aspx/ObtenhaDados?valoPesquisa=31161102996615000145550000000413281487877818
Comment: `content` na requisição Ajax é uma string? Tente usar número para `content` e `float` para assinatura do método `ObtenhaDados`
Comment: Sim `content` é uma `string`...
Comment: Tente mudar o método de envio no jQuery para "POST", ficando assim: `var content = "{ parametroConsulta: " + encedURIComponent(valorCampo) + " }"`
Comment: Número grande demais, ele está sendo convertido para uma base legível. Se você der um `alert(31161102996615000145550000000413281487877818);` a saída será `3.1161102996615E+43`. Ele está sendo convertido para notação cientifica.
Comment: Isso mesmo, é isso que estou tentando resolver, por isso ele esta como `string` rsrsrsrsr
Comment: Com essa quantidade de número não creio que funcione. O que você poderia usar com uma quantidade menor de número seria `Number` e `toPrecision` ou `toFixed`. 44 dígitos é muita coisa, até para um computador.
Answer: Consegui resolver o problema colocando o parâmetro entre "'". Código abaixo:
var valorCampo = $(this).attr('data-clipboard-text');
var content = {valorPesquisa: "'" + valorCampo + "'"};

Answer: Dessa forma irá passar o valor como uma string e concatenar com o parametroConsulta, mas você poderia fazer isso no c#
var valorCampo= $(this).attr('data-clipboard-text');
var content = "parametroConsulta=" + valorCampo.toString();

$.ajax({

        type: "GET",
        dataType: 'json',
        async: false,
        contentType: "application/json; charset=utf-8",
        url: "myPage.aspx/ObtenhaDados",
        data: content,
        success: function (data) { dadosObtidos(data); },
        error: function (data) { falhaConsulta(data); }

});

Comment: Só uma coisa, no caso ele já vem como string quando você pega o attr. Só verificar usando typeOf.
Comment: o `toString()` não funfou... :(
Comment: @JcSaint você está enviando como String e recebendo como string ?
Comment: Envio como `string` e recebo um `Json`


I'm trying to read this text file

Question: I made a two classes, one text file, and a code that should print everything out, but it still becomes null no matter what I do? I'm trying to read the code from the text file by using the toString method from the Book class and the printInventory from the Inventory class in the InventoryTester.
My first code derives on what should be printed. I made a constructor and I used setters and getters to make this. Then ended it with a toString() method. I made a Book class that should print everything to the printInventory in the InventoryTester.
Book class:
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.lang.*;
public class Book {

   // Initiate variables
   // Note: I used the DecimalFormat so every price is always going to have 2 decimal spaces
   private static DecimalFormat df2 = new DecimalFormat("#.##");
   private String ISBN;
   private String author;
   private String title;
   private int edition;
   private String pubCode;
   private int quantity;
   private double price;

   //constructor
   public Book(String isbn, String auth, String ti, int ed, String pc, int qty, double pr)
   {
      ISBN = isbn;
      author = auth;
      title = ti;
      edition = ed;
      pubCode = pc;
      quantity = qty;
      price = pr;
   }

   //getters
   public String getTitle(){return title;}
   public String getAuthor(){return author;}
   public double getPrice(){return price;}
   public int getEdition(){return edition;}
   public String getISBN(){return ISBN;}
   public String getpubCode(){return pubCode;}
   public int getQuantity(){return quantity;}

   //setters
   public void changePrice(double newPrice){price = newPrice;}
   public boolean changeQuantity(int changeAmt){
   changeAmt = quantity + changeAmt;
   if (changeAmt < 0) {
   return false;
   }
   else {
   return true;
   }
   }

   //This prints out all of the information once the object 'Book' is used
   public String toString()
   {
      String subAuthor = "";
      String subTitle = "";
      subAuthor = author.substring(0,16);
      subTitle = title.substring(0,32);
      return "ISBN: " +ISBN + "\nAuthor: " + subAuthor + "\nTitle: " + subTitle + "\nEdition: " + edition + "\nPublisher Code: " + pubCode +"\nQuantity: " +quantity+ "\nPrice: $ " +df2.format(price) + "\n\n";
   }
}

Then I made a class called Inventory to manage instances of the Book class. However, I'm still not sure if most of my code is correct since I compiled it without any errors. What I mean is the constructor itself, the addBook method and the changeQuantity method.
The constructor takes one argument, which is the size of the books array. It should create the empty array of the specified size, and initializes the nextEntry field to be 0. I use the printInventory method here. This method should print the entire inventory from the Book class, using the toString()method on each book.
Inventory class:
import java.math.RoundingMode;
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import java.util.Arrays;

public class Inventory {

   private Book[] books;
   private int nextEntry;
   int questionAmt;

   public Inventory(int size){
      size = 7;
      books = new Book[size];
      nextEntry = 0;
   }

   public boolean addBook(Book theBook) {
   if (nextEntry > 27)
   { return false;}
   else{
   nextEntry++;
   books[nextEntry] = theBook;
   return true;
   }
  }

   public boolean changeQuantity(String isbn, int changeAmt) {
      if (changeAmt < 0) {
         return false;
      }
      else {
         return true;
      }
      }
   public void printInventory()
   {
   for  (int i=0; i<books.length; i++) {
   System.out.println(books[i].toString());

   return;
   }
   }

Then I added the text file, which is called inventory. This is what should be shown in the code and I should be able to edit the quantity it inside the console. I also added a 28 because it needs 28 Books.
inventory.txt:

28
013478796X_Tony Gaddis_Starting Out with Java: From Control Structures through Data Structures_4_PE_10_121.75
0321409493_John Lewis_Java Software Solutions: Foundations of Program Design_5_AW_12_94.05
0023606924_Richard Johnsonbaugh_Algorithms_1_PH_1_109.00
0134743350_Harvey Dietel_Java: How to Program, Early Objects_12_PE_12_134.84
0131474340_Ralph Morelli_Java, Java, Java, Object-Oriented Problem Solving_3_PH_4_95.25
0596100469_Alex Martelli_Python in a Nutshell_2_OR_6_39.99
0134802217_Tony Gaddis_Starting Out with Java: From Control Structures through Objects_7_PE_8_118.67
1403946876_Sally Fincher_Studying Programming_1_PM_3_26.59
0596510047_Andy Oram_Beautiful Code: Leading Programmers Explain How They Think_1_OR_5_44.99
0143037889_Ray Kurzweil_The Singularity is Near: When Humans Transcend Biology_1_PG_20_17.70
0135205972_John Lewis_Java Foundations: Introduction to Program Design and Data Structures_5_PE_5_129.99
0131872893_Wanda Dann_Learning to Program with Alice_1_PH_12_47.50
159413962X_Dave Eggers_The Circle_1_AW_4_3.99
1887902996_John Zelle_Python Programming: An Introduction to Computer Science_1_FB_2_26.40
0133356728_Rafael Gonzales_Digital Image Processing_4_PE_3_248.17
1592400876_Lynne Truss_Eats, Shoots & Leaves_1_PG_5_17.70
0072823798_William Collins_Data Structures and the Java Collections Framework_2_MH_6_105.57
0072866098_Allen Tucker_Programming Languages: Principles and Paradigms_2_MH_1_127.50
0534950973_Michael Sipser_Introduction to the Theory of Computation_2_CT_3_98.90
0131496710_Francis Hill_Computer Graphics Using OpenGL 3rd Edition_3_PH_4_112.00
0321173486_Dave Shreiner_OpenGL Programming Guide_5_AW_1_24.00
0072865512_Steven Schach_Object Oriented and Classical Software Engineering_6_MH_9_123.44
0321228383_Michael Kifer_Database Systems: An Application-Oriented Approach_2_AW_3_112.86
1416587787_Cliff Stoll_The Cuckoo's Egg_1_PG_3_13.32
1400032717_Mark Haddon_The Curious Incident of the Dog in the Night-Time_1_VI_10_13.95
006025492X_Maurice Sendak_Where the Wild Things Are_1_HC_6_17.95
0694003611_Margaret Brown_Goodnight Moon_1_HC_138_8.99
069401298X_Arnold Lobel_Frog and Toad Together_1_HC_27_11.55

Last, but not least, I made an InventoryTester file to read the text file and print it using the code from both classes.
InventoryTester:
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import java.awt.Font;
import java.util.Scanner;
import java.io.*;
public class InventoryTester {
   public static void main(String[] args) throws IOException {
      Scanner inFile= new Scanner(new File("inventory.txt"));
      Book books;
      String inLine= inFile.nextLine();
      int size= Integer.parseInt(inLine);
      Inventory myInventory= new Inventory(size);

      while (inFile.hasNext()) {
      inLine= inFile.nextLine();
      String ISBN = inFile.next();
      String author = inFile.next();
      String title = inFile.next();
      int edition = inFile.nextInt();
      String pubCode = inFile.next();
      int quantity = inFile.nextInt();
      double price = inFile.nextDouble();
      myInventory.addBook(new Book(ISBN, author, title, edition, pubCode, quantity, price));
      String[] tokens  = inLine.split("_");
      myInventory.printInventory();
      }

      inFile.close();
      }
      }

I was trying to make Java understand that there are strings, ints, and doubles. I'm trying to convert the text file using arrays into Strings, ints, and doubles. It should print, but the code considers it to be null. Am I missing something?
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Book.toString()" because "this.books[i]" is null
    at Inventory.printInventory(Inventory.java:42)
    at InventoryTester.main(InventoryTester.java:28)

 ----jGRASP wedge2: exit code for process is 1.

Comment: Use something better than an array for your book inventory, an ArrayList is a very good option that is easy to use. Regarding the error, you add 1 book and then you try to print 7 books.
Comment: Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it)
Comment: If you use an ArrayList to hold your Inventory, you don't need the magic number 28.
Answer: You could make a class to manage your inventory with an arraylist containing books. And then save that class in a binary file.
The class could look like this:
public class BookList implements Serializable
{
  private ArrayList<Book> books;

  public BookList()
  {
    books = new ArrayList<>();
  }

  public void addBook(Book book)
  {
    this.books.add(book);
  }

  public void removeBook(Book book)
  {
    this.books.remove(book);
  }

  public ArrayList<Book> getAllBooks()
  {
    return books;
  }

And then save and load the file like this.
File file = new File("inventory.bin")

public void save(BookList bookList){
        FileOutputStream out = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(out);
        oos.writeObject(bookList);
}

public BookList load(){
        BookList bookList = null;

        FileInputStream in = new FileInputStream(file);
        ObjectInputStream ois = new ObjectInputStream(in);

        bookList = (BookList) ois.readObject();
        in.close();
        ois.close();
    }

Then you shouldn't have any trouble reading from the file.
REMEMBER! Both the list class and book class needs to implement Serializable.

I'm trying to read this text file


Power BI data refresh - deleted columns in Excel still present as Fields

Question: I have a simple Power BI dashboard which links to just one spreadsheet.  The spreadsheet contains superfluous Columns, which I have now deleted.
However, when I refresh the data in Power BI, the Fields which were created from those Columns still exist on the right hand side.
How do I get Power BI to recognise that those Columns / Fields no longer exist?
I can delete them manually but I would expect there to be a sleeker option.
Thanks
Comment: Go to power query editor and open the table in Advance Query Editor mode. Remove all deleted columns from their and refresh everything.
Answer: Click on the "Transform Data" icon and you will end up in the PowerQuery designer (which is where you are deleting the columns). First refresh your preview (the circled option below).
If that does not work, then right click your table and select advanced editor.
Remove the columns from the Transform
Answer: Another reason can be when you've deleted a column you have previously renamed. This triggers an identical error as there's nothing to be renamed.
Its just a different type of error and thus different line in Murray Foxcroft's reply.
Solution: Avoid the field to be part of any logical expression in "Advanced Editor" view.


Multiple layouts for tablet and phone

Question: I am developing an android app for tablet and phone. So to achieve that I created two folders on for phone(layout) and one for tablet layouts(layout-sw600dp).
As per my previous questions comment I assumed that only tablets would pick up layouts from layout-sw600dp. But it does not seem to work.
For nexus 4, nexus 5, nexus 6, nexus 7 devices it is taking layout-sw600dp layout.
What am I missing here? How do I calculate phone/tablet size to proper DP layouts?
Required designs for tablet and phone:

Another retirement to use two separate layouts:
Phone design:

Tab design:

In response to the answered post belowanswer, I have a linear layout like this:
  <LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/linearLayouttest">
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_gravity="center_horizontal"
        android:textColor="@color/black"
        android:gravity="left"
        android:text="LabelFirstName"
        android:layout_marginTop="@dimen/_8sdp"
        android:textSize="@dimen/_13sdp"
        android:id="@+id/firstNameLabel"
        android:layout_marginLeft="@dimen/_15sdp"
        android:layout_marginRight="@dimen/_15sdp" />
    <EditText
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:id="@+id/firstName"
        android:layout_marginTop="@dimen/_3sdp"
        android:background="@drawable/edt_bg"
        android:textColor="@color/black"
        android:layout_marginRight="@dimen/_15sdp"
        android:layout_marginLeft="@dimen/_15sdp"
        android:padding="@dimen/_5sdp"
        android:textSize="@dimen/_14sdp"
        android:textColorHint="@color/textColor" />
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_gravity="center_horizontal"
        android:textColor="@color/black"
        android:gravity="left"
        android:text="LabelLastName"
        android:layout_marginTop="@dimen/_3sdp"
        android:textSize="@dimen/_13sdp"
        android:id="@+id/lastNameLabel"
        android:layout_marginLeft="@dimen/_15sdp"
        android:layout_marginRight="@dimen/_15sdp" />
    <EditText
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:id="@+id/lastName"
        android:layout_marginTop="@dimen/_3sdp"
        android:background="@drawable/edt_bg"
        android:textColor="@color/black"
        android:layout_marginRight="@dimen/_15sdp"
        android:layout_marginLeft="@dimen/_15sdp"
        android:padding="@dimen/_5sdp"
        android:textSize="@dimen/_14sdp"
        android:textColorHint="@color/textColor" />
</LinearLayout>

When I change the orientation the textviews are not visible. Any solution to this?
Comment: instead of creating multiple layout you can achieve that thing by using different dimens file..Try [this](https://stackoverflow.com/questions/47524010/can-we-make-one-layout-type-for-all-screen-size/47524265#47524265).
Comment: I tried that, but it would not work because I have different designs for phone and table. Please check my edited question.
Answer: You can use https://github.com/intuit/sdp library to set view dimensions as per all devices (phone & tablet). It will automatically resize as per device screen size. set it as below :
<TextView
    android:id="@+id/tv_username"
    android:layout_width="@dimen/_45sdp"
    android:layout_height="@dimen/_45sdp"
    android:text="@string/chat"
    android:textColor="@color/colorPrimary"/>

UPDATE
First Check device is whether a phone or tablet using Determine if the device is a smartphone or tablet?
or you can use below method to determine
public boolean isTablet() {
try {
    // Compute screen size
    DisplayMetrics dm = context.getResources().getDisplayMetrics();
    float screenWidth  = dm.widthPixels / dm.xdpi;
    float screenHeight = dm.heightPixels / dm.ydpi;
    double size = Math.sqrt(Math.pow(screenWidth, 2) + Math.pow(screenHeight, 2));
    // Tablet devices should have a screen size greater than 6 inches
    return size >= 6;

} catch(Exception e) {
    e.printStackTrace();
    return false;
}

}
Then set parent LinearLayout orientation programatically as below :
boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
if (tabletSize) {
    LinearLayout ll = (LinearLayout) findViewById(R.id.linearLayout);
    ll.setLayoutParams(LinearLayout.WRAP_CONTENT, LinearLayout.WRAP_CONTENT);
    ll.setOrientation(LinearLayout.HORIZONTAL);
} else {
    LinearLayout ll = (LinearLayout) findViewById(R.id.linearLayout);
    ll.setLayoutParams(LinearLayout.WRAP_CONTENT, LinearLayout.WRAP_CONTENT);
    ll.setOrientation(LinearLayout.VERTICAL);
}

XML CORRECTION
Your layout must like below:
<LinearLayout
    android:id="@+id/linearLayouttest"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/firstNameLabel"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginLeft="@dimen/_15sdp"
            android:layout_marginRight="@dimen/_15sdp"
            android:layout_marginTop="@dimen/_8sdp"
            android:gravity="left"
            android:text="LabelFirstName"
            android:textColor="@color/black"
            android:textSize="@dimen/_13sdp" />

        <EditText
            android:id="@+id/firstName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/_15sdp"
            android:layout_marginRight="@dimen/_15sdp"
            android:layout_marginTop="@dimen/_3sdp"
            android:background="@drawable/edt_bg"
            android:padding="@dimen/_5sdp"
            android:textColor="@color/black"
            android:textColorHint="@color/black"
            android:textSize="@dimen/_14sdp" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/lastNameLabel"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginLeft="@dimen/_15sdp"
            android:layout_marginRight="@dimen/_15sdp"
            android:layout_marginTop="@dimen/_3sdp"
            android:gravity="left"
            android:text="LabelLastName"
            android:textColor="@color/black"
            android:textSize="@dimen/_13sdp" />

        <EditText
            android:id="@+id/lastName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/_15sdp"
            android:layout_marginRight="@dimen/_15sdp"
            android:layout_marginTop="@dimen/_3sdp"
            android:background="@drawable/edt_bg"
            android:padding="@dimen/_5sdp"
            android:textColor="@color/black"
            android:textColorHint="@color/black"
            android:textSize="@dimen/_14sdp" />

    </LinearLayout>
</LinearLayout>

Comment: Lets guess you are set 25sdp of editText textSize for HDPI device then It will automatically resize your layouts as per other device size
Comment: Please check my edited question. I need different design for phone and tablet
Comment: Will two texViews fit in one row for tablet using this?
Comment: Thanks for the answer but what if I have two textviews? If in a phone layout the textvies should line one below other center aligned and in tab layout one has to align at left and one to right?
Comment: please check new update "XML CORRECTION" for your XML file correction
Answer: Basically xxhdpi and xhdpi is for 5" to 5"5' devices. For Tablets you can use

sw600dp
sw600dp-tvdpi
sw720dp
sw720dp-mdpi
sw720dp-xhdpi

. I have been working on this and these are the values which tabs takes. Try once. hope it will work.
Comment: Does that mean I have to create sw600dp,sw600dp-tvdpi,sw720dp,sw720dp-mdpi,sw720dp-xhdpi folders?
Comment: yes you have to create directory like values-sw600dp-tvdpi,values-sw600dp etc. and then you have to put dimens...
Comment: one more thing these values directory must be created under res directory, not under values or layout.
Comment: I am confused. I need to create dimens xml in all these folders? That I have created already. My question was for tablet layout which folder I need to put layout?
Comment: listen you need to create dimen.xml under all this folder. suppose in your value's folder dimen you have a key like  150dp , then put same key on every dimen.xml which you are using in rest of the dimen.xml and set the values accordig to your need

Multiple layouts for tablet and phone


Listen to two ports simultaneously in java

Question: I am working on a chat application using java. One of the functionality that I want to implement is that beside client1 chat with client 2(which works fine), client1 will send secondary information (data from an Arduino) to client2. The idea that I have is listening to two ports on the server, one for the chat, the other for the secondary info, I used two ServerSockets and of course two accept() statements and they keep blocking. My question is how can I open two ports simultaneously in java?
I started with something like this:
<code>new Thread() {
            public void run() {

                while(true) {
                    try {
                        Socket client1 = server.accept();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    //handle client1
                }
            }}.start();
            new Thread() {
                public void run() {

                    while(true) {
                        try {
                            Socket client2 =arduinoServer.accept();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        //handle client1
                    }
                }}.start();
</code>
But I got Exception in thread "pool-1-thread-1" java.lang.NullPointerException
Thanks.
Comment: A solution with a [Selector](http://docs.oracle.com/javase/7/docs/api/java/nio/channels/Selector.html) will probably be the best.
Answer: Of course they keep blocking. accept() is a blocking method.
You need two accept() loops, in two threads.
Comment: Didn't think of using threads, I am going to try this now, can you explain to me what is an accept() loop? you mean writing the accept() statement in an infinite loop so it never blocks, if it is the case, isn't it a bad approach to use infinite loops?
Comment: No, I don't mean 'writing the accept() statement in an infinite loop so it never blocks'. It *does* block, and I already said so. You have to put it in a loop *so you can accept more than one connection.* I don't know where you got your strange theory about infinite loops from.
Comment: Didn't really understood what you mean, I saw examples on the internet on how putting it in a loop, but there is only one accept statement, once I add another accept it blocks, for the theory, I read it in this book "Refactoring: Improving the Design of Existing Code" by Martin Fowler in which he discourage the usage of infinite loops.
Comment: I edited my code to know if you meant something like it
Comment: Could you possibly try reading what I wrote? 'Two accept loops in two threads'. Not two accept() calls in one loop in one thread.


Conditional probability, how to find P(A)

Question: The conditional probability Pr[B|A] is 4/5; the conditional probability P[B|not A] is 2/5, and the unconditional probability of B is 1/2. What is the probability of A?
Answer: I would use the law of total probability, which implies that
$$\Pr[B] = \Pr[B \, | \, A] \Pr[A] + \Pr[B \, | \, \text{not } A] \Pr[\text{not } A].$$


Double Harmonic (Ultraphrygian) Examples

Question: Around 2 years ago i accidentally discovered Phrygian #3 #7 while jamming and found out with some research, that it apears to be called https://en.wikipedia.org/wiki/Double_harmonic_scale. Since then i am adicted to it and use it heavily in nearly all of my compositions.
I can not find any use of this scale (except a few metal bands). Does anyone know composers/pieces that use this scale? I would like to get more input :)
Answer: Claude Debussy used it in some pieces, as did Richie Blackmore. Miles Davis used in Nardis. See the links hereunder for more pieces.
Here at the bottom are listed a few pieces, as well as here near the top.
Comment: Thanks for the link. Its a little bit weird, that i missed the pieces in the wiki-article ;)
Answer: (I would like only post a comment but I have no enough reputation for that.)
A similar question war raised in Phrygian dominant scale with a major seventh. Matt L. answers that Misirlou of Dick Dale us that scale.


Literature on bounds of Fubini's numbers

Question: If anybody can suggest where I can find a literature for a known upper and lower bounds on Fubini numbers https://en.wikipedia.org/wiki/Ordered_Bell_number
Answer: QING ZOU, "THE LOG-CONVEXITY OF THE FUBINI NUMBERS", http://toc.ui.ac.ir/article_21835_684378fec55e5c66c7fccd4321a84637.pdf
gives the bounds on $f_n$, the $n^{\text{th}}$ Fubini number:
$$  2^n < f_n < \frac{n!}{(\ln 2)^{n+1}} < (n+1)^n  \text{.}  $$
The lower bound holds for $n \geq 3$ and the upper for $n \geq 1$.
(Zou cites Barthelemy, "AN ASYMPTOTIC EQUIVALENT FOR THE NUMBER OF TOTAL PREORDERS ON A FINITE SET ",    from which we determine the intended base of the logarithm.)


Why might the means estimated by GLM ANOVA differ from those calculated by hand?

Question: I'm currently analysing some EEG data using a repeated measures general linear model, and I've run into a problem. I have three within-subject factors; Scalp area (3), condition (2) and word (2). When I run a three-way analysis I get mean values for Word (separated by condition) which don't match up to the means I've calculated for myself, for condition 1 (those for condition 2 seem fine). When I take the relevant columns of data and enter them into a two-way analysis for just one condition (so Scalp area (3) x Word (2)), I get the correct means, and those for condition 1 don't match the ones from the three-way analysis.
I've tried this in SPSS and Statistica with identical results; I've checked the data, and I'm pretty sure it's not an input error. I've checked the order in which I'm entering the variables (slowest-changing first), and that seems fine. So either I'm doing something wrong in the analysis, or I've misunderstood the output, or... something else?
I may well be staring straight past an obvious error, but I've spent all afternoon tearing my hair out, so I'm hoping someone might be able to offer some insight!
Thanks in advance!
Answer: The first thing to look for in a situation like this is missing values.  With listwise missing value handling, for example, some cases will be knocked out that would show up in a calculation not affect by missing data in a different variable.
Comment: Thanks JKP, I knew it had to be something obvious I was overlooking; excluding cases with missing data seems to bring everything back in line. Much appreciated!
Comment: To clarify for future readers, this doesn't mean that excluding cases with missing data is the right way to handle the analysis, only that the two methods agree when there is no missing data.  The method you choose should depend on what kind of missing data you have and what kind of inferences you want to make.


How to display a large XML file (>21MB) in a tree view quickly

Question: I need to display a large XML file (>21MB) in a tree view control in a C# Windows Form application. I have written the code which is working for small XML files but when i am trying to open a BIG XML file (>1 MB), its taking too much of time.
 Can anyone suggest how i can optimise this and suggest me any changes or alternatives to achieve this.
Below is the code snippet:
private void CreateTreeViewFromATXML(string strSrcFileName)
        {
            XmlDataDocument xmldoc = new XmlDataDocument();
            XmlNode xmlnode ;
            FileStream fs = new FileStream(strSrcFileName, FileMode.Open, FileAccess.Read);
            xmldoc.Load(fs);
            xmlnode = xmldoc.ChildNodes[1];
            XMLTreeView.Nodes.Clear();
            XMLTreeView.Nodes.Add(new TreeNode(xmldoc.DocumentElement.Name));
            TreeNode tNode ;
            tNode = XMLTreeView.Nodes[0];
            AddNode(xmlnode, tNode);
        }

    private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)
    {
        //XmlNode xNode ;
        TreeNode tNode ;
        XmlNodeList nodeList ;
        int i = 0;
        if (inXmlNode.HasChildNodes)
        {
            nodeList = inXmlNode.ChildNodes;

            foreach (XmlNode XNode in inXmlNode.ChildNodes)
            {
                tNode = new TreeNode(XNode.Name);
                inTreeNode.Nodes.Add(tNode);
                AddNode(XNode, tNode);
            }
        }
        else
        {
            inTreeNode.Text = inXmlNode.InnerText.ToString();
        }
    }

Comment: Instead of building the entire treeview up-front, build it lazily. When the user clicks a node, build its children.
Comment: I would also consider using a worker/background thread for parsing and generating tree nodes, as it isn't desirable to lockup the UI thread processing considerable chunks of data like this.
Answer: I would wrap your code like this:
XMLTreeView.BeginUpdate();
try
{
    CreateTreeViewFromATXML(strSrcFileName);
}
catch (Exception e)
{
    //Handle any error
}
finally
{
    XMLTreeView.EndUpdate();
}

If you're not in an update block it's repainting the GUI on every node add and that's expensive.  You also have recursion in AddNode but if the XML isn't too deeply nested it shouldn't be an issue.
Answer: I would suggest using XDocument and XML to Linq for a faster parsing. You can use the following code to parse the XML:
using System.Xml;
using System.Xml.Linq;
using System.Data;

            XDocument xdoc = XDocument.Load(XMLFile);

var item = from items in xdoc.Element("EPICORTLOG").Descendants("POS")
                       where (string)items.Element("Id") == strSelectedPOSID
                       select items.Elements("TRADE").Elements("ITEM").ToList().ToList();

You can then follow the explanation in the following link to parse the XML:
http://www.dotnetcurry.com/showarticle.aspx?ID=564
The article above will explain the XML to LINQ programming. Using the above method you can load XML files as big as 10MB in a short time.
Answer: Recently, I used TreeView component to implement my HTML editor in C#, I used serialized data structure to impove the performance to open and save a XML file.
From my experience , using this structure and serialize read and write file can open  file up to 20M byes within 2 seconds in my computer. This solution can open a XML file over 2G bytes in my C# application. Hope this solution can help you better.
Example to define Serializable Structure for TreeView and TreeNode
[Serializable]
public class TreeViewData
{
    public TreeNodeData[] Nodes;
    public TreeViewData(){ }
    public TreeViewData(TreeView treeview)
    {
       //your code
    }
    public TreeViewData(TreeNode treenode)
    {
       //your code
    }
    public void PopulateTree(TreeView treeview)
    {
        //your code
    }
    public void PopulateSubTree(TreeNode treenode)
    {
         //your code
    }
}
[Serializable]
public class TreeNodeData
{
    public string Text;
    public int ImageIndex;
    public int SelectedImageIndex;
    public string Tag;
    public TreeNodeData[] Nodes;
    public TreeNodeData() {}
    public TreeNodeData(TreeNode node)
    {
          // your code
    }
    public TreeNode ToTreeNode()
    {
     // your code
    }
}

Example to serialize read XML file
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(TreeViewData));
System.IO.FileStream file = new System.IO.FileStream(strFilename, FileMode.Open);
System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(file);
TreeViewData treeData = (TreeViewData)ser.Deserialize(reader);
treeData.PopulateTree(TreeView1);

Example to serialize write XML file
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(TreeViewData));
System.IO.FileStream file = new System.IO.FileStream(strFilename,   System.IO.FileMode.Create);
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(file, null);
ser.Serialize(writer, new TreeViewData(TreeView1));

Comment: Actually, I want to ask the same question as you did.  but my question is how to display a large xml file over 1G bytes in treeview. that is the reason I found your post.


Algebra help, complex numbers and sine

Question: I have
$$ x = 1-\frac{p}{2}(e^{iw}-e^{-iw}) + \frac{p^2}{2}( e^{iw} -2 + e^{-iw}) $$
$$ x = 1- \frac{p}{2}(2 i \sin w)   +\frac{p^2}{2}(-4\sin^{2}\frac{w}{2}) $$
$$ |x^{2}|  = ( 1 - ip\sin w -2p^{2}\sin^2{w/2}) (   1 + ip\sin w -2p^{2}\sin^2{w/2} )         $$
after doing all the algebra i get
$$ 1 + p^{2} \sin^{2}w - 4p^{2}\sin^{2}w/2 + 4p^{4}\sin^{4}w/2$$
but the correct answer is
$$1 + 4p^{2}(p^2-1)\sin^{4}w/2$$
which i can seem to get, can anyone show me how? Thanks
Comment: the brackets dont mean anything, i am sure it some trick with sines and cosines which i cant figure out !
Comment: Isn't there an error in the last term of the first line?
Comment: if you asking about the omega term i fixed it
Comment: I also wondered  whether it was actually the expansion of $(e^{iw}-e^{-iw})^2$?
Comment: yes its the modulus squared
Comment: It looks like you did everything correctly.... In the picture, do those brackets $[e^{i\omega}-e^{-i\omega}]$ mean anything other than parentheses? Perhaps "Real part"?
Comment: Well the modulus squared isn't the same thing as the square.
Comment: i edited it, i forgot to include the modulus.
Comment: Interpreting $[u]$ as $\text{Re}(u)$ seems to give the correct result*, but it doesn't make sense; $\xi$ would be Real then. *No, it would have $\sin^2$ instead of $\sin^4$.
Answer: Double-angle identity:
$$\sin 2\theta = 2\sin\theta\cos\theta$$
$$\sin\omega = 2\sin\frac\omega2\cos\frac\omega2$$
$$\sin^2\omega = 4\sin^2\frac\omega2\cos^2\frac\omega2$$
$$\sin^2\omega-4\sin^2\frac\omega2 = 4\sin^2\frac\omega2\Big(\cos^2\frac\omega2-1\Big) = 4\sin^2\frac\omega2\Big(-\sin^2\frac\omega2\Big) = -4\sin^4\frac\omega2$$
Therefore
$$1+p^2\sin^2\omega-4p^2\sin^2\frac\omega2+4p^4\sin^4\frac\omega2$$
$$= 1+p^2\Big(\sin^2\omega-4\sin^2\frac\omega2\Big)+4p^4\sin^4\frac\omega2$$
$$= 1+p^2\Big(-4\sin^4\frac\omega2\Big)+4p^4\sin^4\frac\omega2$$
$$= 1+\big(-4p^2+4p^4\big)\sin^4\frac\omega2$$
$$= 1+4p^2(p^2-1)\sin^4\frac\omega2$$
Comment: I added a step in between. Do you follow?
Comment: Thank you, but I don't understand the last line
Comment: Yes thank you so much!

Algebra help, complex numbers and sine


R - aggregate factor/character variable

Question: I have this kind of data frame :
df<- data.frame(cluster=c('1','1','2','3','3','3'), class=c('A','B','C','B','B','C'))

I would like to get for each cluster (1,2,3), the class which appears the most often. In case of a tie, it would also be great to get an info, as for example the combination of the classes (or if not possible just have NA).
So for my example, I would like to have something like this as result:
 cluster  class.max
   1        'A B' (or NA)
   2         'C'
   3         'B'

Maybe I should use aggregate()  but don't know how.
Answer: rank has ways of dealing with ties:
aggregate(class~cluster,df,function(x) paste(names(table(x)[rank(-1*table(x),ties.method="min")==1]),collapse=" "))
  cluster class
1       1   A B
2       2     C
3       3     B

R - aggregate factor/character variable


Push notifications not working - Firebase Cloud Messaging

Question: I've checked my code and im not sure if im missing anything when I send a message threw firebase it sends but on my simulator it doesn't show the notification.Im using apnsKey I really have no idea what's going wrong is there anyway to trouble shoot or find outlive been stuck on this for a little while now
<code>import UIKit
import Firebase
import Stripe
import UserNotifications
import FirebaseMessaging

 @UIApplicationMain
 class AppDelegate: UIResponder ,UIApplicationDelegate {

var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    FirebaseApp.configure()

    initializeStripe()

    Messaging.messaging().delegate = self

    //=============================
    if #available(iOS 10.0, *) {
      // For iOS 10 display notification (sent via APNS)
      UNUserNotificationCenter.current().delegate = self

      let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
      UNUserNotificationCenter.current().requestAuthorization(
        options: authOptions,
        completionHandler: {_, _ in })
    } else {
      let settings: UIUserNotificationSettings =
      UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
      application.registerUserNotificationSettings(settings)
    }

    Messaging.messaging().delegate = self
    application.registerForRemoteNotifications()

    //==========================

    return true
}

//MARK:STRIPE
//=====================================================================
func initializeStripe(){
    STPPaymentConfiguration.shared().publishableKey = Constants.publishableKey

    stripeClient.sharedClient.baseUrlString = Constants.baseUrlString

}

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
  // If you are receiving a notification message while your app is in the background,
  // this callback will not be fired till the user taps on the notification launching the application.
  // TODO: Handle data of notification

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // Messaging.messaging().appDidReceiveMessage(userInfo)

  // Print message ID.
  if let messageID = userInfo[gcmMessageIDKey] {
    print("Message ID: \(messageID)")
  }

  // Print full message.
  print(userInfo)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  // If you are receiving a notification message while your app is in the background,
  // this callback will not be fired till the user taps on the notification launching the application.
  // TODO: Handle data of notification

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // Messaging.messaging().appDidReceiveMessage(userInfo)

  // Print message ID.
  if let messageID = userInfo[gcmMessageIDKey] {
    print("Message ID: \(messageID)")
  }

  // Print full message.
  print(userInfo)

  completionHandler(UIBackgroundFetchResult.newData)
}

  }
   @available(iOS 10, *)
  extension AppDelegate : UNUserNotificationCenterDelegate {

// Receive displayed notifications for iOS 10 devices.
 func userNotificationCenter(_ center: UNUserNotificationCenter,
                          willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo

// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)

// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
  print("Message ID: \(messageID)")
}

// Print full message.
print(userInfo)

// Change this to your preferred presentation option
completionHandler([])
  }

   func userNotificationCenter(_ center: UNUserNotificationCenter,
                          didReceive response: UNNotificationResponse,
                          withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
  print("Message ID: \(messageID)")
}

// Print full message.
print(userInfo)

completionHandler()
}
}

 extension AppDelegate : MessagingDelegate {

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
    print("token fcm: \(fcmToken) boom")

    let dataDict: [String : String] = ["token" : fcmToken]
    NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil,  userInfo: dataDict)

  }

func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    print("messae data  :\(remoteMessage.appData)")
}

   }
</code>
Answer: As of Xcode stable release 11.3.*, to test push notification on iOS you need a real device. It is not possible to test on simulator. However, you can download Xcode 11.4 beta if you do not have a real device handy.
You can find the following in the official release notes of Xcode 11.4 under the section Simulator -> New Features

Simulator supports simulating remote push notifications, including
  background content fetch notifications. In Simulator, drag and drop an
  APNs file onto the target simulator. The file must be a JSON file with
  a valid Apple Push Notification Service payload, including the "aps"
  key. It must also contain a top-level "Simulator Target Bundle" with a
  string value that matches the target application's bundle identifier.
Comment: AHH thank you for letting me know I do have an iPhone but I  mistakenly updated it to iOS 13.4 and now Xcode won't allow me to connect it because its too ahead of it. it suggests upgrading Xcode but I have the most recent version of Xcode meaning apple hasn't released the version that allows iOS 13.4


A question related to the completion of a complete metric space

Question: This question is going to sound very trivial, but given a complete metric space $(X,d)$, how does one show that its completion via Cauchy sequences $(X^*,d^*)$ is itself?
I know that $X$ is dense in its completion $X^*$. So how can I make use of this fact to prove the above claim?
Any help/hint will be appreciated. Thanks in advance.
Comment: Every cauchy sequence in a complete metric space can be identified with its limit.
Comment: The completion of a complete space is isometric to the space itself. If $X$ is complete, then any Cauchy sequence converges, so any two equivalent Cauchy sequences converge to a mutual limit and you can identify that limit with the equivalence class of equivalent Cauchy sequences. This identification is an isometry, so the completeness of $X^*$ follows directly from the completeness of $X$.
Answer: Let $i:X \to X^*$ be the canonical inclusion. As stated in the comments $i$ is an isometry, in particular it is injective. $X$ is complete by assumption, so $\overline{i(X)}=i(X)=X^*$.
(Any element in the closure of $i(X)$ is a limit $i(x_n)_n$. Since $i$ is an isometry, the sequence $(x_n)_n$ is Cauchy in $X$. Thus, converges.)
Thus, $i$ is bijective. One can show that $i$ is closed (not hard). Hence, $i$ is a homeomorphism.


On the approximate of an infinite series

Question: So we already know that the following series converges for all parameter range:
$$F_{U_i}(y)=\sum_{n=0}^\infty \frac {2(-1)^nR^{k\alpha+n\alpha}y^{k+n}}{\Gamma(k)n!\theta^{k+n}(k+n)(k\alpha+n\alpha+2)}$$
where $k$, $R$, $\alpha$, and $\theta$ are positive real.
However, I got strange result while trying to to approximate the above infinite series by only the first $K+1$ terms so the sum becomes from 0 to $K$ instead of $\infty$.
I've done a Matlab code to test my infinite series and I've got strange result for the following parameters:
$k=20, \alpha=2, y=100, R=10, \theta=55$

which shows that the series does not converge. Why did that happen? How can I figure the value of $K$ that best approximate the series.
Answer: Considering $$S_p=2\sum_{n=0}^p(-1)^n\frac {R^{(k+n)\alpha}y^{k+n}}{\Gamma(k)\,n!\,\theta^{k+n}(k+n)\,((k+n)\alpha+2)}$$ let
$x=\frac{y }{\theta }R^{\alpha }$ to make
$$S_p=\frac 2{\Gamma(k) }\sum_{n=0}^p(-1)^n\frac {x^{(k+n)}}{\,n!\,(k+n)\,((k+n)\alpha+2)}$$ which make
$$S_\infty=1-\frac{\Gamma (k,x)}{\Gamma (k)}+\frac{\Gamma \left(k+\frac{2}{\alpha },x\right)-\Gamma \left(k+\frac{2}{\alpha
   }\right)}{\Gamma (k)}\,x^{-2/\alpha }$$ Using your numbers, this give $S_\infty=0.89$ (with $55$ trailing $0$'s).
Now, $S_p$ write in terms of $\, _2F_2(.)$ hypergeometric functions and probably this is the difficulty from a numerical point of view. The terms are extremely oscillating from the beginning (they are negative for odd values of $p$ and positive for even values of $p$). For the first ones
$$\left(
\begin{array}{cc}
p & S_p \\
 0 & +3.05072\times 10^{25} \\
 1 & -5.01200\times 10^{27} \\
 2 & +4.13536\times 10^{29} \\
 3 & -2.28392\times 10^{31} \\
 4 & +9.49546\times 10^{32} \\
 5 & -3.16900\times 10^{34} \\
 6 & +8.84121\times 10^{35} \\
 7 & -2.12041\times 10^{37} \\
 8 & +4.46180\times 10^{38} \\
 9 & -8.36644\times 10^{39} \\
 10 & +1.41526\times 10^{41}
\end{array}
\right)$$
Continuing with even values of $p$, we shall notice that they start to decrease
$$\left(
\begin{array}{cc}
 10 & 1.41526\times 10^{41} \\
 20 & 4.48410\times 10^{51} \\
 30 & 9.94112\times 10^{59} \\
 40 & 8.48485\times 10^{66} \\
 50 & 6.33071\times 10^{72} \\
 60 & 6.71603\times 10^{77} \\
 70 & 1.39937\times 10^{82} \\
 80 & 7.21169\times 10^{85} \\
 90 & 1.09282\times 10^{89} \\
 100 & 5.57116\times 10^{91} \\
 110 & 1.06427\times 10^{94} \\
 120 & 8.32196\times 10^{95} \\
 130 & 2.86727\times 10^{97} \\
 140 & 4.63325\times 10^{98} \\
 150 & 3.70455\times 10^{99} \\
 160 & 1.53530\times 10^{100} \\
 170 & 3.43503\times 10^{100} \\
 180 & 4.30083\times 10^{100} \\
 190 & 3.11128\times 10^{100} \\
 200 & 1.33820\times 10^{100} \\
 300 & 1.19093\times 10^{86}  \\
 400 & 2.52084\times 10^{57}  \\
 500 & 6.78163\times 10^{17}  \\
 600 & 0.89000
\end{array}
\right)$$
To explain that,we need, for your numbers, to compute $p$ such that
$$Q_{p+1}=\frac{\left(\frac{2000}{11}\right)^{p+21}}{20! (p+21) (p+22) (p+1)!} \leq \epsilon$$
The $Q_{p+1}$ term goes through a maximum at $p=179.5$ (have a look at the table !) and for this value $Q_{p+1}=8.61902\times 10^{100}$.
For $\epsilon=10^{-20}$,we need $p=581$ (even for $\epsilon=10^{-2}$, $p=544$).
A crude estimate of $p$ is given by
$$p=-\frac{\log (\epsilon )}{W\left(-\frac{11 }{2000 e}\log (\epsilon )\right)}$$ where $W(.)$ is Lambert function.
For the most general case and a better approximation, taking logarithms and using Stirling approximation for the very first term, we end with the equation
$$\color{blue}{p \log (ex)- \left( p+\frac32\right) \log (p)=K} \qquad\text{where} \quad \color{blue}{K=\log \left(\frac{\sqrt{{\pi }} \,\epsilon \, x^{-(k+1)}\, \Gamma (k)}{\alpha \,\sqrt 2}\right)}$$ Since $p$ is large, we could approximate the equation by
$$\color{blue}{\left(p+\frac{3}{2}\right) \log (e x)-\left(p+\frac{3}{2}\right) \log
   \left(p+\frac{3}{2}\right)=K}$$ for which the solution is given in terms of Lambert function
$$\color{blue}{p=-\frac{K}{W\left(-\frac{K}{e x}\right)}-\frac 32}$$
 Applied to the working case, this gives $p=599$ for $\epsilon=10^{-20}$.
I think that all is explained.
Edit
Considering the general term
$$a_n=\frac {x^{(k+n)}}{\,n!\,(k+n)\,((k+n)\alpha+2)}$$ and using logarithmic differentiation we have
$\frac{\partial a_n}{\partial n}=0$ if
$$-2 \alpha  (k+n)-(k+n) \psi (n+1) (\alpha  (k+n)+2)+(k+n) \log (x) (\alpha
   (k+n)+2)-2=0$$ Assuming that $n$ is large, the expansion of the above quantity is
$$\alpha  \log \left(\frac{x}{n}\right)n^2 + \left(2 (\alpha  k+1) \log \left(\frac{x}{n}\right)-\frac{5 \alpha }{2}\right)n+\cdots$$ So $a_n$ is maximized for $n \sim x$.
Using your numbers, a rigorous maximization of $a_n$ shows that it happens at $n=179.5$ (remember that $x=\frac{2000}{11}=181.8$) for which $a_n=5.24\times 10^{117}$.
Comment: @AymenKareem. You face an alternating series. $Q_n$ is the general term. $W$ is Lambert function. I shall probably add somr stuff today. In your problem, the value of $x\sim 200$ is at origin of many of the problems.
Comment: That's not the same as what I got in Matlab figure. Can you explain that?
Comment: @AymenKareem. No idea ! Are you working with exact arithmetic ? Could you provide your numbers for $p=1,2,\cdots,10$ ?
Comment: mine is n instead of p which is the horizontal line in the figure
Comment: In Matlab, i can get identical result up to $p=116$ it becomes -Inf at $p=117$. Why is that?
Comment: Another question, what is $Q$ and $W$?


How to pay payment of particular rows of the gridview emoloyee salary when click on pay button my gridview code is mentioned below

Question:

              <asp:Label runat="server" text="Search"></asp:Label>

              <asp:TextBox runat="Server" placeholder="Enter EmpId" id="txtSearch">
              </asp:TextBox>

              <asp:Button ID="btnGo" runat="server" Text="Go" onclick="btnGo_Click"/>

             <asp:Button ID="btnShowAll" runat="server" Text="ShowAll"
                    onclick="btnShowAll_Click" />

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
       <Columns>
          <asp:BoundField  HeaderText="EmpId" DataField="EmpId"/>
          <asp:BoundField  HeaderText="Employee Name" DataField="EmpName"/>
          <asp:BoundField  HeaderText="Designation" DataField="EmpDesgn"/>
          <asp:BoundField  HeaderText="Salary" DataField="Sal"/>
          <asp:TemplateField HeaderText="Salary Status">
            <ItemTemplate>
               <asp:Button runat="Server" id="btnPay" text="Pay" CommandName="Pay"
                  Visible='<%#Eval("Status").Equals("Paid")?false:true %>' />
            </ItemTemplate>
          </asp:TemplateField>
       </Columns>
    </asp:GridView>

I want to pay the salary of unpaid employees on clicking the pay button as pay button is showing only for unpaid salaries.
Answer: You can do this using OnRowCommand event. Add the event handler to the gridview
OnRowCommand="GridView1_RowCommand"

Bind the command argument to your button
<asp:TemplateField HeaderText="Salary Status">
     <ItemTemplate>
         <asp:Button runat="Server" id="btnPay" text="Pay" CommandName="Pay"
              Visible='<%#Eval("Status").Equals("Paid")?false:true %>'
              CommandArgument = '<%#Eval("EmpId")%>'
              />
     </ItemTemplate>
</asp:TemplateField>

Then in the RowCommand event you can catch the EmpId from the command argument, pay the salary and rebind the grid view
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if(e.CommandName=="Pay")
    {
        // get the command argument.
        string empId = e.CommandArgument as string;
        //you code here to pay the salary
        //ReBind Gridview to refresh
    }
}