text:
Q: Typecasting of pointers in C I know a pointer to one type may be converted to a pointer of another type. I have three questions:

*

*What should kept in mind while typecasting pointers?

*What are the exceptions/error may come in resulting pointer?

*What are best practices to avoid exceptions/errors?

A: In plain C you can cast any pointer type to any other pointer type. If you cast a pointer to or from an uncompatible type, and incorrectly write the memory, you may get a segmentation fault or unexpected results from your application.
Here is a sample code of casting structure pointers:
struct Entity {
  int type;
}

struct DetailedEntity1 {
  int type;
  short val1;
}

struct DetailedEntity2 {
  int type;
  long val;
  long val2;
}

// random code:
struct Entity* ent = (struct Entity*)ptr;

//bad:
struct DetailedEntity1* ent1 = (struct DetailedEntity1*)ent;
int a = ent->val; // may be an error here, invalid read
ent->val = 117; // possible invali write

//OK:
if (ent->type == DETAILED_ENTITY_1) {
  ((struct DetailedEntity1*)ent)->val1;
} else if (ent->type == DETAILED_ENTITY_2) {
  ((struct DetailedEntity2*)ent)->val2;
}

As for function pointers - you should always use functions which exactly fit the declaration. Otherwise you may get unexpected results or segfaults.
When casting from pointer to pointer (structure or not) you must ensure that the memory is aligned in the exact same way. When casting entire structures the best way to ensure it is to use the same order of the same variables at the start, and differentiating structures only after the "common header". Also remember, that memory alignment may differ from machine to machine, so you can't just send a struct pointer as a byte array and receive it as byte array. You may experience unexpected behaviour or even segfaults.
When casting smaller to larger variable pointers, you must be very careful. Consider this code:
char* ptr = malloc (16);
ptr++;
uint64_t* uintPtr = ptr; // may cause an error, memory is not properly aligned

And also, there is the strict aliasing rule that you should follow.

A: A program well written usually does not use much pointer typecasting. There could be a need to use ptr typecast for malloc for instance (declared (void *)malloc(...)), but it is not even necessary in C (while a few compilers may complain).
  int *p = malloc(sizeof(int)); // no need of (int *)malloc(...)

However in system applications, sometimes you want to use a trick to perform binary or specific operation - and C, a language close to the machine structure, is convenient for that. For instance say you want to analyze the binary structure of a double (that follows thee IEEE 754 implementation), and working with binary elements is simpler, you may declare
  typedef unsigned char byte;
  double d = 0.9;
  byte *p = (byte *)&d;
  int i;
  for (i=0 ; i<sizeof(double) ; i++) { ... work with b ... }

You may also use an union, this is an exemple.
A more complex utilisation could be the simulation of the C++ polymorphism, that requires to store the "classes" (structures) hierarchy somewhere to remember what is what, and perform pointer typecasting to have, for instance, a parent "class" pointer variable to point at some time to a derived class (see the C++ link also)
  CRectangle rect;
  CPolygon *p = (CPolygon *)▭
  p->whatami = POLY_RECTANGLE; // a way to simulate polymorphism ...
  process_poly ( p );

But in this case, maybe it's better to directly use C++!
Pointer typecast is to be used carefully for well determined situations that are part of the program analysis - before development starts.
Pointer typecast potential dangers

*

*use them when it's not necessary - that is error prone and complexifies the program

*pointing to an object of different size that may lead to an access overflow, wrong result...

*pointer to two different structures like s1 *p = (s1 *)&s2; : relying on their size and alignment may lead to an error

(But to be fair, a skilled C programmer wouldn't commit the above mistakes...)
Best practice

*

*use them only if you do need them, and comment the part well that explains why it is necessary

*know what you are doing - again a skilled programmer may use tons of pointer typecasts without fail, i.e. don't try and see, it may work on such system / version / OS, and may not work on another one

A: You probably need a look at ... the C-faq maintained by Steve Summit (which used to be posted in the newsgroups, which means it was read and updated by a lot of the best programmers at the time, sometimes the conceptors of the langage itself).
There is an abridged version too, which is maybe more palatable and still very, very, very, very useful. Reading the whole abridged is, I believe, mandatory if you use C.


text:
Q: Unable to create netlink socket in centOS — protocol not supported I am using a CentOS Linux release 7.0.1406 (Core)
I  am using kernel version 3.10.0-123.el7.x86_64
When I am creating a netlink socket,it fails.
int sock_fd = socket(PF_NETLINK, SOCK_RAW, 1)
 value of sock_fd is -1

When I was using 3.1 kernel version of CentOS,above socket function was working.
I want to create netlink socket on kernel version 3.10.0
I am getting "Unable to create netlink socket — protocol not supported"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Covariance for three variables I am trying to understand how covariance matrix works. So let's suppose we have two variables: $X, Y$, where $\text{Cov}(X,Y) = \mathbb{E}[(x -\mathbb{E}[X])(y-\mathbb{E}[Y])]$ gives the relation between the variables, ie how much one depends on the other.
Now, three variable case it is less clear for me. An intuitive definition for covariance function would be $\text{Cov}(X,Y,Z) = \mathbb{E}[(x -\mathbb{E}[X])(y-\mathbb{E}[Y])(z-\mathbb{E}[Z])]$, but instead the literature suggests using covariance matrix that is defined as two variable covariance for each pair of variables.
So, does the covariance include full information about variable relations? If so, what is the relation to my definition of $\text{Cov}(X,Y,Z)$?

A: To expand on Zachary's comment, the covariance matrix does not capture the "relation" between two random variables, as "relation" is too broad of a concept. For example, we'd probably want to include the dependence of two variables on each other to be include in any measure of their "relation".
However, we know that $cov(X,Y)=0$ does not imply that they are independent, as for example is the case with two random variables X~U(-1,1) and Y=X^2 (for a short proof, see: https://en.wikipedia.org/wiki/Covariance#Uncorrelatedness_and_independence).
So if we'd think that the covariance includes full information about variable relations, as you ask, zero covariance would suggest no dependence. This is what Zachary means when he says that there can be non-linear dependences that the covariance does not capture.
However, let $X:=(X_{1},...,X_{n})'$ be multivariate normal, X~$N(\mu,\Sigma)$. Then $X_{1},...,X_{n}$ are independent iff $\Sigma$ is a diagonal matrix with all off-diagonal elements = 0 (if all covariances = 0).
To see that this condition is sufficient, observe that the joint density factors,
\begin{equation} f(x_{1},...,x_{n}) =
\dfrac{1}{ \sqrt{(2 \pi)^{n} | \Sigma |}}   exp(- \dfrac{1}{2} (x - \mu)' \Sigma^{-1} (x - \mu))= \Pi^{n}_{i=1} \dfrac{1}{\sqrt{2 \pi \sigma_{ii}}} exp(- \dfrac{(x_{i}-\mu_{i})^{2}}{2 \sigma_{ii}})=f_{1}(x_{1})...f_{n}(x_{n})\end{equation}.
To see that the condition is necessary, recall the bivariate case. If $X_{1}$ and $X_{2}$ are independent, then $X_{1}$ and $X_{1}|X_{2} = x_{2}$ must have the same variance, so
\begin{equation} \sigma_{11}=\sigma_{11|2}=\sigma_{11}-\sigma^{2}_{12} \sigma^{-1}_{22} \end{equation}
which implies $\sigma_{12}=0$. By the same argument, all off-diagonal elements of $\Sigma$ must be zero.
(source: prof. Geert Dhaene's Advanced Econometrics slides)


text:
Q: How can I convert from big.Rat to a string without specifying precision? I have an endpoint implemented in golang that can receive amounts with different precision length, ie:
"123"
"123.12"
"123.123123"

I'm using big.Rat internally to deal with these numbers as follows:
import (
    "encoding/json"
    "math/big"
)

type MyStruct struct {
    Amount   big.Rat `json:"amount"`
}

func (mystr *MyStruct) MarshalJSON() ([]byte, error) {
    type Alias MyStruct

    return json.Marshal(&struct {
        Amount json.Number `json:"amount"`
        *Alias
    }{
        Amount: json.Number(mystr.Amount.FloatString(2)),
        Alias:  (*Alias)(mystr),
    })
}

func (mystr *MyStruct) UnmarshalJSON(data []byte) error {
    type Alias MyStruct

    aux := &struct {
        Amount json.Number `json:"amount"`
        *Alias
    }{
        Alias: (*Alias)(mystr),
    }

    if err := json.Unmarshal(data, &aux); err != nil {
        return err
    }

    mystr.Amount = mystr.toRat(aux.Amount.String())

    return nil
}

func (mystr *MyStruct) toRat(val string) big.Rat {
    ratAmount := new(big.Rat)
    ratAmount.SetString(val)

    return *ratAmount
}

My problem & question is related to the Marshal method, in particular with this line:
Amount: json.Number(mystr.Amount.FloatString(2)),
Because if the amount in the json has a number with more than two decimal places a rounding takes place and I don't want that, I just want to mantain exactly the same number that was
received when I did the Unmarshal method.
This is an example of rounding: https://play.golang.org/p/U6oi_aGc8lE
Is there a way to convert from big.Rat to string without defining the precision?
Thank you very much in advance!

A: This should be help:
package main

import (
    "fmt"
    "math/big"
    "strconv"
)

func main() {
    n := new(big.Rat)

    n.SetString("34.999999")
    x,_ := n.Float64()
    fmt.Println("Result: "+strconv.FormatFloat(x, 'f', -1, 64))
}


text:
Q: react-native How to judge if it is a directory?     import RNFS from 'react-native-fs';

    const dirs = await RNFS.readdir(RNFS.ExternalDirectoryPath + '/data');
    for (let i = 0; i < dirs.length; i++) {
      // How to judge if it is a directory ?
      // fs.lstatSync(dirs[i]).isDirectory() // Similar to this effect
    }

How to judge if it is a directory ?
Similar to this effect: fs.lstatSync(dirs[i]).isDirectory()

A: Here's a code snippet that might help, it is in the documentation as well.
https://github.com/itinance/react-native-fs#readdirdirpath-string-promisereaddiritem
componentWillMount() {
    RNFS.readDir(RNFS.ExternalDirectoryPath + '/data')
        .then((result) => {
            console.warn('result: ', result); // debug

            for (var i = 0; i < result.length; i++) {
                if(result[i].isDirectory()) {
                    // It is a directory
                } else if(result[i].isFile()) {
                    // It is a file
                } else {
                    // I don't know what it is
                }
            }
        })
        .catch((err) => {
            console.log(err.message, err.code);
        });
}


text:
Q: Use DOSBox's SB16 Emulation in real DOS? So I've been thinking, is it potentially possible to use DOSBox's sound emulation software in real DOS on machines with AC97/IHDA chips so that you can use audio properly? I've been using the PC Speaker for sound effects, and I love the general feel of the bleep bloop waaaamp sound effects, I've even been using MIDIPlayer to listen to MIDI versions of game soundtracks when I'm not actively playing them, however there is one giant caveat: many DOS games can only play FX through the PC Speaker and not music. I've searched far and wide to find a solution to this, and I finally thought "I may not have a SB, or an AdLib, or a Covox... but could I emulate them?".
And that is the question of the day: would it be possible to compile and run DOSBox's SB/AdLib/GeneralMIDI emulators and run them on actual DOS that I can keep my 8 bit MIDI sound effects but use a virtual SB for piping the music to my AC97/IHDA? (And no, switching to DOSBox or a VM is not an option, I like to keep things authentic, and would sooner just buy a sound card than do that, so please don't suggest it.)
Alternatively would it be possible to build/run DOSBox inside of DOS as to get the hardware-emu environment without having to use DOSBox exclusively? Say by launching DOSBox with game specific configs through the DOS prompt?

A: DOS programs expect to access the hardware directly.
Emulating such direct hardware accesses would require some kind of virtualization (DOSBox or a VM), or that the actual hardware has built-in support for emulation (modern chipsets typically can do this to allow to redirect PS/2 keyboard/mouse accesses to USB, but not for anything else).

A: There are some software emulators for SB (and other sound cards) for DOS like VSB (Virtual Sound Blaster), TEMU (Tandy sound chip emulator) and remus.
http://board.flatassembler.net/topic.php?t=9524


text:
Q: Tapestry getting started All goes OK until mvn jetty:run which ends with [ERROR] Failed to execute goal org.mortbay.jetty:maven-jetty-plugin:6.1.16:run (default-cli) on project newapp: Failure: Address already in use: bind
That is no surprise as I have Tomcat running on 8080 with my own site (that can not be changed). Did mvn indeed install jetty and tries running it? May I configure Jetty to a different port or maybe use Tomcat instead?

A: You can configure Jetty to use another port by setting the system property jetty.port.
The jetty.port property can be set in the command line when running Maven:
mvn -Djetty.port=9090 jetty:run

Or it can be set in the project's pom.xml, as part of the maven-jetty-plugin configuration:
<plugin>
    <groupId>org.mortbay.jetty</groupId>
    <artifactId>maven-jetty-plugin</artifactId>
    <version>6.1.16</version>
    <configuration>
        <systemProperties>
            <systemProperty>
                <name>tapestry.execution-mode</name>
                <value>development</value>
            </systemProperty>
            <systemProperty>
                <name>jetty.port</name>
                <value>9090</value>
            </systemProperty>
        </systemProperties>
    </configuration>
</plugin>

In both examples Jetty is configured to listen to port 9090.


text:
Q: Single line comment continuation From the C++ standard (going back to at least C++98) § 2.2, note 2 states:

Each instance of a backslash character (\) immediately followed by a new-line character is deleted, splicing physical source lines to form logical source lines. Only the last backslash on any physical source line shall be eligible for being part of such a splice. Except for splices reverted in a raw string literal, if a splice results in a character sequence that matches the syntax of a universal-character-name, the behavior is undefined. A source file that is not empty and that does not end in a new-line character, or that ends in a new-line character immediately preceded by a backslash character before any such splicing takes place, shall be processed as if an additional new-line character were appended to the file.

And, section § 2.7 states:

The characters /* start a comment, which terminates with the characters */. These comments do not nest. The characters // start a comment, which terminates with the next new-line character. If there is a form-feed or a vertical-tab character in such a comment, only white-space characters shall appear between it and the new-line that terminates the comment; no diagnostic is required. [Note: The comment characters //, /*, and */ have no special meaning within a // comment and are treated just like other characters. Similarly, the comment characters // and /* have no special meaning within a /* comment. ]

I would take these two together to mean that the following:
// My comment \
is valid

// My comment \ still valid \
is valid

are legal in C++98. In GCC 4.9.2, these both compile without any diagnostic messages. In MSVC 2013, these both produce the following:
warning C4010: single-line comment contains line-continuation character

If you have warnings as errors enabled (which, I do), this causes the program to not compile successfully (without warnings-as-errors, it works just fine). Is there something in the standard that disallows single-line comment continuations, or is this a case of MSVC non-compliance with the standard?

A: It's not a question of compliance. You've specifically asked the compiler to treat a valid construct as an error, so that's what it does.
GCC will give the same warning (or error, if requested) if you specify -Wcomment or -Wall.

A: I'd say it's MS being sensitive to the fact that if you do something like:
#define macro() \
    some stuff \
    // Intended as comment \
    more stuff

then you get VERY interesting errors when you use macro() in the code.
Or other simply accidentally typing a comment like this:
// The files for foo-project are in c:\projects\foo\
int blah;

(Strange errors for "undefined variable blah" occurs)
I would NEVER use line continuation in a single-line comment, but if you have some good reason to, just turn THAT warning off in MSVC.
Also as Mike says: Warnings are not even covered by the standard - it only says what needs to be an error. If you enable "warnings are errors", you will have to either be selective about what warnings you enable, or accept that some constructs that are technically valid (but dubious) will be unacceptable in the build, because the compiler maker has decided to warn about it. Try writing if (c = getchar()) in gcc or clang and see how far you get with much -Werror and warnings on "high". Yet it is perfectly valid according to the standard.


text:
Q: Servlet-database connection issue I am trying to connect a servlet with mysql database...but in the servlet code..
the statement:
Class.forName(driver) shows an error with red underline on tooltip-
 Syntax error on token-"driver",VariableDeclaratorId expected after this token.

I just can't get it why this happens..
here is the servlet code:
package Servlets;

import java.io.IOException;
import java.sql.*;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet
{

    private static final long serialVersionUID = 1L;

    public LoginServlet()
    {
        super();
    }
   Connection con = null;

   String url = "jdbc:mysql://localhost:3306/";

   String db = "abc";

   String driver = "com.mysql.jdbc.Driver";

   Class.forName(driver);

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

    {
        String username= request.getParameter("username");
        String password= request.getParameter("password");
        con = DriverManager.getConnection("url+db","root","root");
        Statement st = con.createStatement();
        int val = st.executeUpdate("INSERT login values("+username+","+password+")");
        System.out.println("1 row affected");

        response.sendRedirect("login.jsp");

    }

}

A: I'd put the
Class.forName("com.mysql.jdbc.Driver").newInstance();

line just above
con = DriverManager.getConnection("url+db","root","root");

Bear in mind that the servlet needs to be multi-threaded so that your
Connection con = null;

Will probably cause you problems when two users try to login at the same time.
Also, you need to close the connection properly
try {
    if(con != null)
      con.close();
      } catch(SQLException e) {}

and finally you will need to handle any exception that the database access may cause so wrap it in a try catch block.
package Servlets;

import java.io.IOException;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet
{

private static final long serialVersionUID = 1L;

public LoginServlet()
{
    super();
}

String url = "jdbc:mysql://localhost:3306/";
String db = "abc";
String driver = "com.mysql.jdbc.Driver";

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

{
   try{
    Connection con = null;
    String username= request.getParameter("username");
    String password= request.getParameter("password");
    Class.forName(driver).newInstance();
    con = DriverManager.getConnection("url+db","root","root");
    Statement st = con.createStatement();
    int val = st.executeUpdate("INSERT login values("+username+","+password+")");
    System.out.println("1 row affected");

    response.sendRedirect("login.jsp");
  }catch(SQLException e){}
  finally{
    try {
      if(con != null)
       con.close();con=null;
       } catch(SQLException e) {}
  }

}
}

Or something like that.
As a final note it is much better to use a "connection pool".

A: add a mysql connector 5.1.0 bin jar file.. add the jar file in your project library.
link http://www.java2s.com/Code/Jar/m/Downloadmysqldatabase1610jar.htm

A: Class.forName( "com.mysql.jdbc.Driver" );
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/rental","root","root" ) ;
Statement st = conn.createStatement();
String sql = "select * from login";
ResultSet rs = st.executeQuery(sql);

A: Class.forName( "com.mysql.jdbc.Driver" );
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/rental","root","root" ) ;


text:
Q: Family of (Semi)norms? Let $\mathcal{D}_K(\Omega)$ denote the smooth functions with compact support, $\mathrm{supp}(u) \subset K \subset \Omega \subset \mathbb{R}^n$ with $K$ compact. When studying this space, many texts provide a family of seminorms, given by:
$$
\|\phi\|_{K,j} = \max_{|\alpha| \leq j}\max_{x\in K} \left|\frac{\partial^{\alpha}\phi}{\partial x^\alpha}\right|
$$
My question is, why are these seminorms instead of proper norms? If we have $\|\phi\|_{K,j} = 0$, is it not then the case that for $\alpha$ with  $|\alpha| = 0$ (i.e $\alpha = 0$ so that we may consider the function itself) that:
$$
\max_{x\in K}\left|\frac{\partial^0\phi}{\partial x^0}\right| = \|\phi\|_\infty = 0
$$
which only happens if $\phi$ is identically $0$. Am I missing something here?

A: A norm is a particular case of seminorm. So calling the $||\cdot||_{K,j}$ seminorms is perhaps not optimal in precision but is not meant to deny that these are norms for the space $\mathcal{D}_{K}(\Omega)$ which they are. The reason I think one refers to them as seminorms is because in the general theory of (locally convex) topological vector spaces the basic input for defining the topology is a set of seminorms which may or may not be norms. This distinction comes to the forefront when discussing whether the space is Hausdorff separated or not. For this one needs the collection ofs eminorms as a whole to be able to separate points. Asking one of the seminorms to do this by itself is asking it to be a norm.


text:
Q: Disable startup program in registry; There are a lot of programs which manage startup application. They get some programs list and allow user to enable/disable program in startup.
I can get some program list from registry (like HKLM/Software/Microsoft/Windows/CurrentVersion/Run and others)
How they perform enabling/disabling? If I delete registry key then this program will disappear from startup list.
How can I disable program from startup without deleting registry key? Is there some flag in registry key for it?
I don't have any code because I don't how I can do this.
Thanks in advance.

A: You can set a program at startup like that:
    private void SetStartup()
    {
        RegistryKey rk = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
        rk.SetValue("Notepad", "c:\windows\notepad.exe");
    }

Now if you want to remove it then just edit the path slightly.
    rk.SetValue("Notepad", "c:\windows\notepad.exe_");

Later on if you want to reset it, just remove the underscore.


text:
Q: How can I accurately compute $\sqrt{x + 2} −\sqrt{x}$ when $x$ is large? How can the values of the function $f(x) = \sqrt{x + 2} −\sqrt{x}$ be computed accurately when $x$ is large?
I have tried using Matllab. I am not able to understand when $x$ will be large.

A: Recall that when $t$ is small, $\sqrt{1+t}\approx 1 + t/2$. It follows that, for $x$ large and positive,
$$
f(x)= \sqrt{x}(\sqrt{1+2/x}-1)\approx 1/\sqrt{x},
$$
in the sense that $f(x)\sqrt{x}\rightarrow 1$ as $x\rightarrow \infty$.

A: In fact, an asymptotic expansion of $f(x) = \sqrt{x+a} - \sqrt{x}$ about $x = \infty$ is $$f(x) \approx \frac{a}{2} x^{-1/2} - \frac{a^2}{8} x^{-3/2} + \frac{a^3}{16} x^{-5/2} - \frac{5a^4}{128} x^{-7/2} + \frac{7a^5}{256} x^{-9/2} - \frac{21a^6}{1024} x^{-11/2} + \cdots.$$  We can calculate this via the generalized binomial theorem $$(a+x)^r = \sum_{k=0}^\infty \binom{r}{k} a^k x^{r-k},$$ for $r = 1/2$, so that in particular, $$\begin{align*} \binom{1/2}{k} &= \frac{(1/2)(1/2-1)\cdot \ldots \cdot(1/2-k+1)}{k!} \\ &= \frac{1(-1)(-3)\cdot \ldots \cdot(3-2k)}{2^k k!} \\ &=  (-1)^{k-1} \frac{(2k-2)!}{2^{2k-1} k! (k-1)!} \\ &= \frac{(-1)^{k-1}}{2^{2k-1}k } \binom{2k-2}{k-1}, \quad k = 1, 2, \ldots,\end{align*}$$ and $\binom{1/2}{0} = 1$.

A: If directly computing $\sqrt{x+2}-\sqrt{x}$ is giving you problems, you can instead try using
$\sqrt{x+2}-\sqrt{x} = \dfrac{(\sqrt{x+2}-\sqrt{x})(\sqrt{x+2}+\sqrt{x})}{\sqrt{x+2}+\sqrt{x}} = \dfrac{(x+2)-x}{\sqrt{x+2}+\sqrt{x}} = \dfrac{2}{\sqrt{x+2}+\sqrt{x}}$.
For large $x$, this is approximately $\dfrac{2}{\sqrt{x}+\sqrt{x}} = \dfrac{1}{\sqrt{x}}$.
EDIT: I just tried this for $x = 10^{18}$ using MATLAB R2013b.
For $\sqrt{x+2}-\sqrt{x}$ it gives $0$, but for $\dfrac{2}{\sqrt{x+2}+\sqrt{x}}$, it gives $1.0000 \times 10^{-9}$.

A: This is a variant of heropup's answer; hopefully the useful technique it illustrates
justifies the partial duplication.
We may factor $\sqrt{x+2} -\sqrt{x} = \sqrt{x}( \sqrt{1 + 2/x} - 1).$
Now if $x \to \infty,$ then $|2/x| < 1,$ so we can compute $\sqrt{1 + 2/x}$ via
the binomial theorem, to get
$$\sqrt{1+ 2/x} - 1 = \sum_{n = 1}^{\infty} {{1/2} \choose n } \dfrac{2^n}{x^n}
= \sum_{n = 1}^{\infty} (-1)^{n-1}\dfrac{(2n-3)\cdot (2n - 5) \cdots 3 \cdot 1 }{n!} x^{-n},$$
so that
$$\sqrt{x+2} - \sqrt{x} = \sum_{n = 1}^{\infty} (-1)^{n-1}\dfrac{(2n-3)\cdot (2n - 5) \cdots 3 \cdot 1 }{n!} x^{-\frac{2n-1}{2}}.$$
Of course this is the same series as in heropup's answer, derived in essentially the same way.  But one thing we see, by applying the binomial theorem to $1 + 2/x,$
is that this series converges for $|2/x| < 1,$ i.e. for $x > 2,$ which
might be helpful.  (And of course one can use the usual theory of Taylor series
to estimate the rate of convergence, if necessary.)

The general technique this illustrates is doing a division by the term that
is going to infinity, so that instead one has a term which is going to zero.


text:
Q: QuickFIX/n: FieldNotFoundException when querying group I'm currently using QuickFIX/n to build an acceptor service, and I've built an initiator to test the acceptor. I suspect the error I get is due to a bug in the acceptor because the same error occurs with a message that someone else is sending to the service.
In the initiator I build and send an AllocationInstruction as follows:
var fix44Message = new QuickFix.FIX44.AllocationInstruction(
    new AllocID(request.Info.AllocationID), EnumHelpers.ParseAllocationTransactionType(request.Info.AllocationTransactionType), EnumHelpers.ParseAllocationType(request.Info.AllocationType),
    new AllocNoOrdersType(AllocNoOrdersType.EXPLICIT_LIST_PROVIDED), EnumHelpers.ParseSide(request.Info.Side), new Symbol(request.Info.Symbol), new Quantity(request.Info.Quantity),
    new AvgPx(request.Info.AveragePrice), new TradeDate(request.Info.TradeDate.ToString("yyyyMMdd")))
    {
        SecurityID = new SecurityID(request.Info.SecurityID),
        SecurityIDSource = new SecurityIDSource(request.Info.SecurityIDSource),
        SecurityExchange = new SecurityExchange(request.Info.SecurityExchange),
        Issuer = new Issuer(request.Info.Issuer),
        Currency = new Currency(request.Info.Currency),
        TransactTime = new TransactTime(request.Info.TransactTime),
        SettlDate = new SettlDate(request.Info.SettlementDate.ToString("yyyyMMdd")),
        GrossTradeAmt = new GrossTradeAmt(request.Info.GrossTradeAmount),
        NetMoney = new NetMoney(request.Info.NetMoney)
    };

var group = new QuickFix.FIX44.AllocationInstruction.NoOrdersGroup
{
    ClOrdID = new ClOrdID(order.ClOrdID),
    OrderID = new OrderID(order.OrderID),
    OrderQty = new OrderQty(order.Quantity)
};
fix44Message.AddGroup(group);

In this specific case the message is created with exactly one order group.
In the acceptor I try get the order-groups as follows:
public void OnMessage(QuickFix.FIX44.AllocationInstruction allocation, SessionID sessionID)
{
    Console.WriteLine("Order count: " + allocation.NoOrders.getValue());
    var orderGroup = new QuickFix.FIX44.AllocationInstruction.NoOrdersGroup();
    allocation.GetGroup(1, orderGroup);
    info.Orders.Add(new AllocationInstructionOrder
    {
        ClOrdID = orderGroup.ClOrdID.getValue(),
        OrderID = orderGroup.OrderID.getValue(),
        Quantity = orderGroup.OrderQty.getValue()
    });
}

allocation.NoOrders has a value of 1 as expected. However, when GetGroup() is called with an index of 1 (first group), I get
QuickFix.FieldNotFoundException occurred
  HResult=-2146232832
  Message=field not found for tag: 73
  Source=QuickFix
  Field=73
  StackTrace:
       at QuickFix.FieldMap.GetGroup(Int32 num, Int32 field)
       at QuickFix.FieldMap.GetGroup(Int32 num, Group group)
       at FIX.FixAcceptorService.AcceptorExchange.OnMessage(AllocationInstruction allocation, SessionID sessionID) in c:\Projects\AdHoc\FIX\FIX\FIX\FixAcceptorService\AcceptorExchange.cs:line 82
  InnerException:

This is the FIX message log:
20151008-06:03:57.410 : 8=FIX.4.4 9=65 35=A 34=1 49=TEST 52=20151008-06:03:57.388 56=BAOBAB 98=0 108=30 10=225
20151008-06:03:57.444 : 8=FIX.4.4 9=65 35=A 34=1 49=BAOBAB 52=20151008-06:03:57.440 56=TEST 98=0 108=30 10=214
20151008-06:04:04.162 : 8=FIX.4.4 9=258 35=J 34=2 49=TEST 52=20151008-06:04:04.158 56=BAOBAB 6=9.175 15=ZAR 22=4 48=ZAE0007990962 53=506 54=1 55=R 60=20151008-08:04:04.141 64=20151008 70=080404139 71=0 75=20151008 106=ABC 118=4642.56 207=XJSE 381=4642.56 626=2 857=1 73=1 11=18122977 37=118 38=506 10=251
20151008-06:04:10.876 : 8=FIX.4.4 9=110 35=j 34=2 49=BAOBAB 52=20151008-06:04:10.876 56=TEST 45=2 58=Conditionally Required Field Missing 372=J 380=5 10=127
20151008-06:04:34.890 : 8=FIX.4.4 9=53 35=0 34=3 49=TEST 52=20151008-06:04:34.890 56=BAOBAB 10=176
20151008-06:04:40.894 : 8=FIX.4.4 9=53 35=0 34=3 49=BAOBAB 52=20151008-06:04:40.894 56=TEST 10=177
20151008-06:05:04.909 : 8=FIX.4.4 9=53 35=0 34=4 49=TEST 52=20151008-06:05:04.908 56=BAOBAB 10=175
20151008-06:05:10.910 : 8=FIX.4.4 9=53 35=0 34=4 49=BAOBAB 52=20151008-06:05:10.910 56=TEST 10=165
20151008-06:05:34.921 : 8=FIX.4.4 9=53 35=0 34=5 49=TEST 52=20151008-06:05:34.920 56=BAOBAB 10=173
20151008-06:05:40.924 : 8=FIX.4.4 9=53 35=0 34=5 49=BAOBAB 52=20151008-06:05:40.924 56=TEST 10=174

And finally, the acceptor settings:
[DEFAULT]
SenderCompID=BAOBAB
UseDataDictionary=N
StartTime=00:00:00
EndTime=00:00:00
FileStorePath=C:\Users\bernhard.haussermann\AppData\Local\Temp\FIX_BAOBAB
FileLogPath=C:\Users\bernhard.haussermann\AppData\Local\Temp\FIX_BAOBAB_log
ConnectionType=acceptor
SocketAcceptPort=8030
ResetOnLogon=N
ResetOnLogout=N
ResetOnDisconnect=N
[SESSION]
BeginString=FIX.4.4
TargetCompID=TEST
[SESSION]
BeginString=FIXT.1.1
DefaultApplVerID=FIX.5.0
TargetCompID=TEST

The C# code above is based on the example on the QuickFIX/n site.
Any ideas?

A: After downloading the source code for quickfix/n and debugging against it I finally found the cause of the problem!
The acceptor did not interpret the message properly because it did not create a group for the NoOrders (73) tag. The data-dictionary map for looking up group tags was empty, because I used UseDataDictionary=N in my settings.
Changing the acceptor to use a data dictionary solved the problem.
Here is my updated settings string:
[DEFAULT]
SenderCompID=BAOBAB
UseDataDictionary=Y
DataDictionary=C:\Users\bernhard.haussermann\AppData\Local\Temp\FIX44.xml
StartTime=00:00:00
EndTime=00:00:00
FileStorePath=C:\Users\bernhard.haussermann\AppData\Local\Temp\FIX_BAOBAB
FileLogPath=C:\Users\bernhard.haussermann\AppData\Local\Temp\FIX_BAOBAB_log
ConnectionType=acceptor
SocketAcceptPort=8030
ResetOnLogon=N
ResetOnLogout=N
ResetOnDisconnect=N
[SESSION]
BeginString=FIX.4.4
TargetCompID=TEST


text:
Q: Fatal Exception: java.lang.UnsatisfiedLinkError couldn't find lib.so Recently Crashlytics has reported a crash from a HTC One A9 Android 7.0 device for an app that I'm working on.
Fatal Exception: java.lang.UnsatisfiedLinkError  nativeLibraryDirectories=[/data/app/com.app.test-1/lib/arm64, /system/lib64, /vendor/lib64]]] couldn't find lib.so

I looked everywhere specially similar questions but could not find a proper solution to my case because the app supports 64 bit version of the native library too. (See cmake config below)
This is the first time that someone with this device has installed the app and I did not see any linkage error on any other devices before.
I'm actually not sure if it is looking for the native-lib in the mentioned paths in the posted error? If that's the case, why it does't look for the lib in the lib/arm64-v8a path based on my abiFilters?
Here is my cmake config inside the app gradle:
cmake {
    abiFilters "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
}

How can this issue be solved?

A: First off: If it is one crash incident, I wouldn't worry about it. Only if multiple users crash on it, I would prioritize it. Freak errors on Android happen, especially if you consider the quality of some of the devices.
I do not think it is a missing library on your end.
The actual problem is the really strange library name: lib.so
This is not a valid name you would expect in an Android NDK application. You always expect it to look for libxxx.so
The fact that it does not, means that the library name got mangled, or not properly specified in the manifest file.
Look in AndroidManifest.xml inside the activity tag, for a line like this:
<meta-data android:name="android.app.lib_name" android:value="xxx" />

Next, in your apk file, you will want to see the library listed as such:
lib/arm64-v8a/libxxx.so
lib/armeabi-v7a/libxxx.so

With xxx, as your app name, of course.
If the entries in APK or AndroidManifest are missing, the fault is on your end. If they are there, I would just suspect a bogus customer device, maybe suffering from running out of file storage, or something.


text:
Q: Como funcionam protótipos em JavaScript? Parece-me que o conceito de protótipo é fundamental em JavaScript e inclusive em vários lugares tenho lido que é um de seus pontos fortes. Entretanto, esse não parece um conceito tão simples de entender para quem vem de outras linguagens.
Assim, pergunto: como funcionam protótipos em JavaScript?

A: A cadeia de protótipos
É bem simples na verdade. Cada objeto possui uma referência a um protótipo, que é sempre outro objeto, ou null. Esse objeto, por sua vez, também possui um protótipo. Forma-se então uma cadeia de protótipos.
E para que serve isso? O funcionamento é semelhante ao conceito de herança. Considere o seguinte exemplo: você tem um objeto que representa um veículo, vamos chamá-lo de veiculo. Suponha ainda outros dois outros objetos, carro e onibus, que tenham veiculo como protótipo. E suponha que veiculo possua um método buzinar. A cadeia de protótipos torna possível invocar esse método em carro e onibus:
carro.buzinar();
onibus.buzinar();

E como isso funciona? Ao invocar o método, o interpretador verifica se o objeto em questão (carro ou onibus) possui um método com esse nome. Neste caso, os objetos não possuem esse método. Então o interpretador verifica se o protótipo de cada objeto possui o método, e neste caso ele encontra e invoca o método buzinar. Caso o método não fosse encontrado, o interpretador continuaria a verificação subindo na cadeia de protótipos, até encontrar o método ou propriedade desejado, ou até chegar a um objeto que possua null como protótipo.
É importante saber que essa invocação funciona como se o método pertencesse ao próprio objeto; ou seja, qualquer referência a this dentro do método buzinar irá apontar para carro ou onibus neste exemplo.
Atribuição de protótipo
A linguagem não oferece nenhuma maneira oficial de se trocar o protótipo de um objeto on-the-fly. O protótipo é atribuído somente no momento da criação do objeto, e isso pode ser feito de duas maneiras.
1. Atribuição via construtor
Toda função possui uma proprieade chamada prototype (funções são objetos em JavaScript, portanto podem possuir propriedades). Quando uma função é invocada como construtor, é criado um novo objeto cujo protótipo é o valor da propriedade prototype da função. Por exemplo:
function Veiculo() {}
Veiculo.prototype.buzinar = function() {
    alert('Fom');
}
var carro = new Veiculo(); // invocação como construtor
carro.buzinar();           // dispara o alert

2. Atribuição direta
A partir do ECMAScript 5, a linguagem oferece outra maneira de se criar um objeto com determinado protótipo, a função Object.create. Repare que ela é um método do construtor Object, portanto pode ser considerada um método estático. O que essa função faz é criar um novo objeto cujo protótipo é o que tiver sido passado como primeiro argumento:
var veiculo = {
    buzinar: function() {
        alert('Fom');
    }
};
var carro = Object.create(veiculo); // veiculo será o protótipo de carro
carro.buzinar();                    // dispara o alert

3. Atribuição on-the-fly
Oficialmente, JavaScript não permite alterar o protótipo de objetos já existentes, porém as principais implementações (incluindo todos os browsers que eu conheço) permitem isso por meio da propriedade não-padrão __proto__. Usando essa propriedade é possível fazer algo assim:
var veiculo = {
    buzinar: function() {
        alert('Fom');
    }
};
var carro = {};             // carro ganha protótipo padrão (Object.prototype)
carro.__proto__ = veiculo;  // troca protótipo
carro.buzinar();            // dispara o alert

Notas sobre a especificação
A explicação acima é bem informal, e similar ao que a especificação da linguagem descreve, também informalmente. Porém a descrição contida na especificação pode parecer um pouco confusa, pois há duas coisas chamadas "prototype": a propriedade prototype dos objetos do tipo função, e o [[Prototype]], que é o nome oficial da propriedade interna dos objetos. Quando a especificação usa o termo prototype sem formatação de código nem colchetes, refere-se geralmente ao [[Prototype]], da mesma maneira que usei o termo protótipo na descrição acima.
No que diz respeito ao acesso à cadeia de protótipos, o ponto crucial na especificação é a função interna [[GetProperty]], invocada quando você tenta acessar uma propriedade de um objeto. Trata-se de uma função recursiva, que retorna a propriedade solicitada de determinado objeto, esteja ela no próprio objeto ou em um dos membros de sua cadeia de protótipos.


text:
Q: Linq SubQuery for Unrelated entity variable Is it possible to convert/duplicate the following with Linq?
DECLARE @UserID INT = 1, @ViewerUserID INT = 1002;

SELECT UGR.*,
CASE
WHEN (
    SELECT subR.[Level]
    FROM UserGameRanks subUGR WITH (NOLOCK)
    INNER JOIN Ranks subR WITH (NOLOCK) ON (subUGR.RankId = subR.Id)
    INNER JOIN Games subG WITH (NOLOCK) ON (subUGR.GameId = subG.Id)
    INNER JOIN Users subU WITH (NOLOCK) ON (subUGR.UserID = subU.Id)
    WHERE subUGR.IsDeleted = 0 AND subU.Id = @ViewerUserID AND subUGR.GameID = UGR.GameId
) > R.[Level] THEN 1
ELSE 0
END AS CanEdit
FROM UserGameRanks UGR WITH (NOLOCK)
INNER JOIN Ranks R WITH (NOLOCK) ON (UGR.RankId = R.Id)
INNER JOIN Games G WITH (NOLOCK) ON (UGR.GameId = G.Id)
INNER JOIN Users U WITH (NOLOCK) ON (UGR.UserID = U.Id)
WHERE UGR.IsDeleted = 0 AND U.Id = @UserID
AND
(
    (
        (@ViewerUserID <> - 1)
        AND
        (UGR.VisibilityId = 1)
    )
    OR
    (
        (UGR.VisibilityId = 2)
    )
    OR
    (
        (UGR.VisibilityId = 0)
        AND
        (@UserID = @ViewerUserID)
    )
)

Specifically the CASE SubQuery? I added a [NotMapped] CanEdit value to the Users entity class, however I'm unsure how to populate it with one sql query instead of doing the initial get first after which looping through and updating the CanEdit.
I've had a look through StackOverflow.
Any assistance would be appreciated.
EDIT: Looking at your answers I see how how to do it, but I realized I made a stuff up in the question. I orignally created the above query as an example to my issue, but I see now it doesn't directly relate to my issue. I have updated the SQL part...
The idea is that we might have many Ranks with the lowest rank being "Unset" Which would be level 0. So If I play a Game that another user plays and I my Rank set on Level 2, I can assign the Rank to this user to 1. But on a different Game I might also be "Unset" (level 0) and thus wouldn't be able to edit his/her rank.
@CodingYoshi: This is what I've attempted
var viewerQuery = from ugr in context.UserGameRanks
                               join r in context.Ranks on ugr.RankId equals r.Id
                               join g in context.Games on ugr.GameId equals g.Id
                               join u in context.Users on ugr.UserId equals u.Id
                               where (!ugr.IsDeleted) && (ugr.UserId == viewerUserId)
                               select new { UserGameRank = ugr };

            var query = from ugr in context.UserGameRanks
                        join r in context.Ranks on ugr.RankId equals r.Id
                        join g in context.Games on ugr.GameId equals g.Id
                        join u in context.Users on ugr.UserId equals u.Id
                        where (!ugr.IsDeleted) && (ugr.UserId == userId) &&
                        (
                            (viewerUserId != -1 && ugr.VisibilityId == Visibility.RegisteredUsers)
                            ||
                            (ugr.VisibilityId == Visibility.Public)
                            ||
                            (ugr.VisibilityId == Visibility.Hidden && userId == viewerUserId)
                        )
                        select new { GameName = g.Name, Username = ugr.Username, RankName = r.Name, CanEdit = (viewerQuery.Rank.Level > r.Level ? 1 : 0) };

A: Perhaps something like this:
var users = new List<User>
{
    new User { Id = 1, UserName = "User1", UserTypeId = 1 },
    new User { Id = 2, UserName = "User2", UserTypeId = 2 },
    new User { Id = 3, UserName = "User3", UserTypeId = 2 },
};

var userTypes = new List<UserType>
{
    new UserType { Id = 1, Type = "Admin", Security = 1 },
    new UserType { Id = 2, Type = "User", Security = 2  }
};

var userId = 1;

var ViewerUserID = 2;
var viewerSecurity =
    (from u in users
    join ut in userTypes on u.UserTypeId equals ut.Id
    where u.Id == ViewerUserID
    select ut.Security).FirstOrDefault();

var res =
    (from u in users
    join ut in userTypes on u.UserTypeId equals ut.Id
    where u.Id == userId || u.Id == -1
    select new
    {
        Id = u.Id,
        UserName = u.UserName,
        CanEdit = viewerSecurity > ut.Security ? 1 : 0
    });
}

class User {
    public int Id {get; set;}
    public string UserName {get; set;}
    public int UserTypeId {get; set;}
}

class UserType {
    public int Id {get; set;}
    public string Type {get; set;}
    public int Security {get; set;}
}

UPDATE:
First of all, no need to edit your question because other people answered your initial question and now their and my initial response make no sense. You should have started a new question or updated this one.
Here is the code for your edited question:
var res =
    (from ugr in userGameRanks
    join r in ranks on ugr.RankId equals r.Id
    join g in games on ugr.GameId equals g.Id
    join u in users on ugr.UserId equals u.Id
    where !ugr.IsDeleted    // assuming IsDeleted is of type BIT in your DB
        && u.Id == userId
        && (
                (ViewerUserID != -1 && ugr.VisibilityId == 1)
                || ugr.VisibilityId == 2
                || (ugr.VisibilityId == 0 && userId == ViewerUserID)
            )
    let level =
        (from subUGR in userGameRanks
        join subR in ranks on subUGR.RankId equals subR.Id
        join subG in games on subUGR.GameId equals subG.Id
        join subU in users on subUGR.UserId equals subU.Id
        where !subUGR.IsDeleted
            && subU.Id == ViewerUserID
            && subUGR.GameId == ugr.GameId
        select subR.Level).FirstOrDefault()

    select new
    {
        ugr.RankId,
        ugr.UserId,
        ugr.GameId,
        ugr.IsDeleted,
        ugr.VisibilityId,
        CanEdit = level > r.Level ? 1 : 0
    });

Hope this helps

A: I modeled the database as classes to get syntax correct.  Not sure is I got everything correct but it is close
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int UserID = 1;
            int ViewerUserID = 2;

            DataBase db = new DataBase();

            var resutls = (from subU in db.subU
                           join subUt in db.subUT on subU.Id equals subUt.UserTypeID
                           select new { subU = subU, subUt = subUt })
                           .Where(x => ((x.subU.Id == ViewerUserID) && (x.subUt.Security > x.subU.Security)) || x.subU.Id == -1)
                           .ToList();
        }
    }
    public class DataBase
    {
        public List<Users> subU { get; set; }
        public List<UserTypes> subUT { get; set; }

    }
    public class Users
    {
        public int Id { get; set; }
        public int Security { get; set; }
    }
    public class UserTypes
    {
        public int UserTypeID { get; set; }
        public int Security { get; set; }
    }
}

A: A few problems:
1) What's with all the joins?  You should have navigation properties set up properly in your model configurations.
2) Your resulting query's CanEdit property relies on the game rank level for a specified viewerUserId but it appears that specifying the viewerUserId is optional.  What's the default behavior if no viewer user is specified or found?  I'll assume CanEdit should be false.
public class YourResultClass()
{
    public string GameName { get; set; }
    public string UserName { get; set; }
    public string RankName { get; set; }
    public bool CanEdit { get; set; }
}

var targetUserGameRanksQuery = context.Users
    .Where(u => !u.IsDeleted
        && u.UserId == userId)
    // flatten for use in subsequent join
    .SelectMany(u => u.UserGameRanks);

IQueryable<YourResultClass> query = null;

if(viewerUserId.HasValue)
{
    var viewerGameRanksQuery = context.Users
        .Where(u => !u.IsDeleted
            && u.UserId == viewerUserId)
        // flatten for use in subsequent join
        .SelectMany(u => u.UserGameRanks);

    var joinQuery = targetUserGameRanksQuery // outer source `o`
        .Join(viewerGameRanksQuery, // inner source `i`
            o => o.GameId,
            i => i.GameId,
            (o, i) => new
            {
                GameName = o.Game.Name,
                TargetUserName = o.Username,
                TargetRankName = o.Rank.Name,
                CanEdit = i.Rank.Level > o.Rank.Level,
                Visibility = o.VisibilityId
            });

    query = joinQuery
        .Where(at =>
            at.Visibility == Visibility.RegisteredUsers

            || (at.Visibility == Visibility.Hidden
                && userId == viewerUserId.Value)

            || at.Visibility == Visibility.Public )
        .Select(at =>
            new YourResultClass()
            {
                GameName = at.GameName,
                UserName = at.UserName,
                RankName = at.RankName,
                CanEdit = at.CanEdit,
            });
}
else
{
    query = targetUserGameRanksQuery
        .Where(ugh => ugr.VisibilityId == Visibility.Public)
        .Select(ugh => new YourResultClass()
        {
            GameName = ugr.Game.Name,
            UserName = ugr.Username,
            RankName = ugr.Rank.Name,
            CanEdit = false,
        });
}


text:
Q: Read battery status bluetooth headset linux I use Bluetooth headset that use Bluetooth version 4.1. When I connect with android it shows the battery status. But with Linux (Ubuntu 18.04) I cannot get battery status. I tried with bluetoothctl, looking file in /sys/class/power_supply as in other questions, But they didn't help me.
askubuntu.com/questions/53880/is-there-any-way-to-check-the-battery-percentage-of-apple-wireless-peripherals
stackoverflow.com/questions/49078659/check-battery-level-of-connected-bluetooth-device-on-linux
My bluetooth device don't use GATT profile. It uses A2DP sink for streaming audio.
I looked Bluez documentation. They all said is do with GATT profile and get the attributes.
Is there a way to read battery status even with pragmatically in Linux properly? How does android device get the battery status? Is it a weakness of Linux Bluetooth stack?

A: Since this pull request by Dmitry Sharshakov, PipeWire has support for reporting battery status (with devices that use Apple HFP AT commands). It uses bluez's Battery Provider API, which is still experimental and is only available if bluetoothd is started with the -E flag.
On Arch Linux, it should be enough to run
cp /usr/lib/systemd/system/bluetooth.service /etc/systemd/system/
sed -i -r 's/ExecStart=.+/& -E/' /etc/systemd/system/bluetooth.service
systemctl daemon-reload
systemctl restart bluetooth

And the headset battery level should appear. To get the battery level programatically, you can then use UPower's DBus API.


text:
Q: Python TSP Held-Karp algorithm I'm trying to implement Held-Karp in Python but it doesn't seem to be working. There are two differences in my problem from the classical TSP problem (as used in the description of the H-K algorithm I found in the web):
- I don't need to return to the original node. I think this is called a Hamiltonian cycle but I'm not very familiar with graph algorithms so I'm not entirely sure. Each city needs to be visited once as in TSP
- Some edges in the graph are missing
I used networkx and created this function:
def hk(nodes,Graph,start_node, total_ops, min_weight = 9999999,min_result = []):
nodes.remove(start_node)
# removes the current node from the set of nodes
for next_node in nodes:

    total_ops += 1
    current_weight = 0
    try:
        current_weight += Graph[start_node][next_node]["weight"]
        # checks if there's an edge between the current node and the next node
# If there's an edge, adds the edge weight
    except:
        continue
    sub_result = []
    if len(nodes) > 1:
        new_nodes = set(nodes)
        sub_result,sub_weight,total_ops = hk(new_nodes,Graph,next_node, total_ops)
#calculates the minimum weight of the remaining tree
        current_weight += sub_weight
    if current_weight < min_weight:
# if the weight of the tree is below the minimum weight, update minimum weight
        min_weight = current_weight
        min_result = [next_node] + sub_result
return min_result,min_weight,total_ops

But something is clearly wrong as I'm expecting O(n ** 2 * 2 ** n) complexity but am getting O(n!) instead, same as for the brute force method (trying all combinations one by one). Clearly, there's an error in my implementation.
Thank you.


text:
Q: jQuery finding descendant by ID not working I'm trying to change the value of a jQuery datepicker input element in a form to the first date in the week of the user-selected date once the submit button is clicked but before the form is actually submitted.
I'm finding that the following Javascript works (using a class selector in .find()):
$("form").submit( function(event) {
    $(this).closest('form').find('.week-picker').datepicker( "setDate", startDate );
    var current_date = $(this).closest('form').find('.week-picker').datepicker( "getDate" );
    return;
});

startDate is a Date object.
But this code does not work (using an ID selector in .find()):
$("form").submit( function(event) {
    $(this).closest('form').find("#week-picker").datepicker( "setDate", startDate );
    var current_date = $(this).closest('form').find('.week-picker').datepicker( "getDate" );
    return;
});

console.log($(this).closest('form').find(".week-picker").datepicker( "setDate", startDate ).val()); produces a proper date, like 06/27/2018.
console.log($(this).closest( 'form' ).find('#week-picker').val()); produces undefined.
Why is this happening? Isn't an ID a valid selector?
HTML:
<form action="/checkin" method="post">

            <input class="week-picker form-control" type="text" id="week-picker" name="week_start" placeholder="Select week" style="opacity: 0;position: absolute;">

            <button type="submit" class="btn btn-primary btn-lg">Submit</button>

</form>

The datepicker portion of my JS:
var startDate;
var endDate;

var selectCurrentWeek = function() {
    window.setTimeout(function () {
    $('.week-picker').find('.ui-datepicker-current-day a').addClass('ui-state-active')
                }, 1);
    }

    $('.week-picker').datepicker( {
        showOtherMonths: true,
        selectOtherMonths: true,
        onSelect: function(dateText, inst) {
            var date = $(this).datepicker('getDate');
            startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
            endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
            var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
            $(this).closest( 'form' ).find('#startDate').text($.datepicker.formatDate( dateFormat, startDate, inst.settings ));
            $(this).closest( 'form' ).find('#endDate').text($.datepicker.formatDate( dateFormat, endDate, inst.settings ));
                    selectCurrentWeek();
         },
         beforeShowDay: function(date) {
                    var cssClass = '';
                    if(date >= startDate && date <= endDate)
                        cssClass = 'ui-datepicker-current-day';
                    return [true, cssClass];
         },
         onChangeMonthYear: function(year, month, inst) {
                    selectCurrentWeek();
         }
     });

   $(document).on( 'mousemove','.week-picker .ui-datepicker-calendar tr',function() {$(this).find('td a').addClass('ui-state-hover'); });
   $(document).on('mouseleave','.week-picker .ui-datepicker-calendar tr',function() {$(this).find('td a').removeClass('ui-state-hover'); });

A: #week-picker is a valid selector, as long as your input has that ID assigned. What is happening in your case is that there is JS turning your input into a datepicker, and it changes the ID of the element when it loads. As you posted from your element inspector, your input no longer has the week-picker ID, it is now dp1529862475978.

This is not uncommon, and the behavior you're getting is the expected one. If you need to make sure that you're targeting this datepicker instead of another one with the same class, you can use the name attribute:
$("input[name='week_starting']")

You should never have 2 inputs with the same name on the same page, so it's as unique as an ID. The ID you're seeing in the element inspector is probably randomly generated, so you don't want to use that.


text:
Q: Изменение элемента в нескольких списках по его индексу в Python У меня есть список со списками. Нужно в каждом из подcписков заменить одно значение по индексу на другое значение. Покажу на примере:
list = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]

for podlist in list:
    for i in podlist:
        if podlist.index(i) == 0:
            i = 2
print(list)

Что я получаю:
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]

Желаемый результат:
[[2, 2, 3, 4, 5, 6, 7, 8, 9, 10], [2, 2, 3, 4, 5, 6, 7, 8, 9, 10], [2, 2, 3, 4, 5, 6, 7, 8, 9, 10]]

A: for podlist in list:
    podlist[0] = 2


text:
Q: Writing numbers as a sum of cubes and an application of CRT Suppose I could write every numbers as a sum of $3$ cubes in (mod $a_1$) and I could write every number as a sum of 3 cubes (mod $a_2$), where $a_1$ and $a_2$ are coprime. Can we show that every number in (mod $a_1a_2$) can be written as a sum of $3$ cubes?
It seems to me that this will be an application of CRT somehow but I could not quite see how to apply CRT here. I have thought about taking every element in (mod $a_1a_2$) and project onto (mod $a_1)$ and (mod $a_2$) separately. In particular, every element after the projection can be written as a sum of $3$ cubes but I am not sure how to proceed further.
Many thanks!

A: CRT works. If $n\equiv b^3+c^3+d^3\bmod{a_1}$ and $n\equiv r^3+s^3+t^3\bmod{a_2}$ and $\gcd(a_1,a_2)=1$ then you can find $u,v,w$ such that $u\equiv b\bmod{a_1}$, $u\equiv r\bmod{a_2}$ and similarly for $v,c,s$ and $w,d,t$. Then you'll have $u^3+v^3+w^3\equiv n\bmod{a_1a_2}$.


text:
Q: npm run build is adding "build" in the URL We are using Laravel 9 and Vue 3. On our app.js we have.
import './bootstrap';
import { createApp } from 'vue';
import { createRouter, createWebHistory } from 'vue-router';

const app = createApp({});

import ExampleComponent from './components/ExampleComponent.vue';
import ExampleComponent2 from './components/ExampleComponent2.vue';

const routes = [
    { path: '/', component: ExampleComponent },
    { path: '/about', component: ExampleComponent2 },
]

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes,
});

app.use(router);

app.mount('#app');

When we do npm run dev, we getting

*

*http://127.0.0.1:8000/

*http://127.0.0.1:8000/about
Which is correct.
The issue is when we do the npm run build for deployment, the URL showing is:

*

*http://127.0.0.1:8000/build/

*http://127.0.0.1:8000/build/about
There is "build" in the URL which is something we dont prefer. Is there a way to remove this?
Any help would be appreciated.

A: Just incase someone is having same issues.
It is an issue with the router. Update it to:
const router = createRouter({
    history: createWebHistory(),
    routes, // short for `routes: routes`
});


text:
Q: Is using webpack alongside wagtail for transpiling scss and es7+ script a good practice? I'm new to the django wagtail ecosystem and I was wondering what was the prefered way to add SCSS or ES7 javascript to my project.
For now what I plan to do is creating a webpack build pipeline that will output my transpilled files to the static folders.
Is this a good practice ?
Is there a better way to do this while keeping the hot-reloading feature?
Thanks for your answers.

A: Don't have anything for JS, but for SASS I'm using django-libsass. Been working well so far. Here is a walkthrough for setting it up: Link

A: It's indeed a common practice to have a webpack build pipeline to output transpilled files into the static folders.
It seems that is is possible to get hot-reloading with django-webpack-loader (see also this usage example article) or django-webpacker, although I haven't tried myself so I can't guarantee it.
As a side note, and this is just my personal opinion, it's not a bad practice but I wouldn't call it a good practice either, more the best-we've-got practice. Today, Django is very much in the same situation that Rails was before v5, trying to handle assets with its own pipeline which hasn't kept up with the recent JavaScript evolution. The packages linked above try to do something similar to Rails 5 but it still feels a bit awkward.


text:
Q: Get position of object in opengl after transforms I would like to get the coordinates of an object in OpenGL. I draw a quad. And after that I do some transforms like GL11.glTranslatef() and GL11.glRotatef().
GL11.glBegin(GL11.GL_QUADS); // draw independent triangles
GL11.glColor3f(0.0f, 1.0f, 0.0f);
GL11.glVertex3f(-0.2f, 0.0f, -2.0f);    // lower left vertex
GL11.glVertex3f( 0.2f, 0.0f, -2.0f);    // upper vertex
GL11.glVertex3f( 0.2f, 0.4f, -2.0f);    // lower right verte
GL11.glVertex3f( -0.2f, 0.4f, -2.0f);
GL11.glEnd();

Is it possible to get the position of the vertices after the transformation?

A: Sure. Apply the same transforms (translations and rotations) to a position vector, that holds the position of your object. The result will be the position of your object after the transform. You may need to do some scaling at some point if you want to convert the 3d co-ords to 2d screen co-ords. But this is very much doable. It involves scaling based on the z-depth of the object.
EDIT:
 private final FloatBuffer buffer = EngineUtil.createBuffer( 16 );

      /**
    * @return Current modelview matrix (column-major)
    */
   public Matrix getModelviewMatrix() {
      return getMatrix( GL11.GL_MODELVIEW_MATRIX );
   }

   /**
    * @return Current projection matrix (column-major)
    */
   public Matrix getProjectionMatrix() {
      return getMatrix( GL11.GL_PROJECTION_MATRIX );
   }

   /**
    * Retrieves the specified matrix.
    * @param name Matrix name
    */
   private Matrix getMatrix( int name ) {
      // Retrieve specified matrix buffer
      buffer.rewind();
      GL11.glGetFloat( name, buffer );

      // Convert to array
      final float[] array = new float[ 16 ];
      buffer.get( array );

      // Convert to matrix
      return new Matrix( array );
   }

But you may want to simply use something more complete than LWJGL. Google vecmath, processing, unity. 3D is tricky and it seems there are no real short cuts, so just keep trying, you will get it.

A: this is not possible... opengl sends your vertex data to the GPU and only on GPU you can get them after the transformation.
to get transformed vertices you have to multiply them by the matrix
for each vertex:
   vertex_transformed = matrix * vertex

some more advanced ways is to use transform feedback and store those transformed vertices into a buffer (but still this buffer will be stored on the GPU).


text:
Q: How can I convert instance to dictionary with model method and relationship? Below is the implementation of model class 'Customer'
class Customer(models.Model):
    uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=50,,null=True,blank=True)
    birthdate = models.DateField(max_length=100,null=True,blank=True)
    status = models.ForeignKey('status ',on_delete=models.CASCADE)
    something = models.ManyToManyField('Something',blank=True)

    def get_age(self):
        diff = relativedelta(datetime.date.today(),self.birthdate )
        return diff

I want to convert the django model class instance to a dictionary, somewhat like -
{
  uuid : "value",
  name : "value",
  birthdate = "value",
  status = {
      status_id : "value"
      status_text : "value"
  },
  something : [{
       something_id : "value",
       something_value : "value"
  },{
       something_id : "value",
       something_value : "value"
  }],
get_age : "value"
}

thanks!

A: The short answer
You should use serializers, in your case the best option is ModelSerializer.
The long answer
Firstly, you should add @property decorator to get_age function (I renamed it for age):
@property
def age(self):
    diff = relativedelta(datetime.date.today(),self.birthdate )
    return diff

Then create serializers:
class StatusSerializer(serializers.ModelSerializer):
    class Meta:
        model = Status
        fields = ['status_id', 'status_value']

class SomethingSerializer(serializers.ModelSerializer):
    class Meta:
        model = Something
        fields = ['something_id', 'something_value']

class CustomerSerializer(serializers.ModelSerializer):
    status = StatusSerializer()
    something = SomethingSerializer(many=True)
    class Meta:
        model = Customer
        fields = ['uuid', 'name', 'birthdate', 'status', 'something', 'age']

And then you use serializer to convert your model instance to dict:
customer_dict = CustomerSerializer(customer_model).data


text:
Q: Why there is no output when I do R Pattern Matching with For loop This is the first time I wrote a R function. What I want to do is for example I have a R data.frame like this
                             Vars        match
1                             A_m          0
2                             B_m          0
3                               C          0
4                               D          34
5                               E_m        0

This is the result I got after matching two dataframes. In the match column, if the number is 0, it means there is no match for the value in the Vars column. For example in first row, A_m has 0 in match column. This means A_m doesn't have a match. So my function is to find those values in Vars column that has no match (has 0 in match column). After that if the value I found ends with "_m" then it is the value I want, and I want to print them out.
This is the code I wrote. Because I have never written R function before, there can be lots of problems with my code. I want to use data.frame as my function's argument and use for loop to check the whole dataframe. In the for loop I want to use if to decide whether it is the target value or not. Really appreciate for your help and Patience.
varsConvert <- function(x){
  for(i in 1:nrow(x)){
    #x[i,1]is the cordinate of the value in that dataframe, can I write like this?
    if(x[i,1] == 0){
      #I want to match ends with _m by *_m
      if(x[i,0] == "*_m"){
        print(x[i,0])
      }
      else if(x[i,0] == "E"){
          print(x[i,0])
        }
      else{
        stop("this is an error")
      }

    }
  }
}

In my example the values I want to print should be A_m, B_m and E_m

A: While it is possible to write "classic" for loops in R, it's often best to use other functions which will be shorter/cleaner/faster. Here is your data (I named it df) :
df<-structure(list(Vars = c("A_m", "B_m", "C", "D", "E_m"), match = c(0L,
0L, 0L, 34L, 0L)), .Names = c("Vars", "match"), class = "data.frame", row.names = c(NA,
-5L))

You can do :
temp<-df$Vars[df$match==0] # find the names of Vars for which match is equal to 0
temp[grep('_m',temp)] # only select those with _m
# [1] "A_m" "B_m" "E_m"

An other option is to select the indexes of the intersection of match==0 and _m in Vars :
df$Vars[intersect(grep('_m',df$Vars),which(df$match==0))]
# [1] "A_m" "B_m" "E_m"

And yet another approach (using Boolean arithmetic rather than set operations):
df$Vars[ grepl('_m',df$Vars) & df$match==0 ]

If you want a function with a data.frame in input you can do this (I used column numbers this time to show other possibilities) :
f<-function(data){
    temp<-data[,1][data[,2]==0]
    temp[grep('_m',temp)]
}

To use it, call f(nameOfYourData) :
f(df)
# [1] "A_m" "B_m" "E_m"


text:
Q: Classic ASP routine calling a page on same server I'm moving an old ASP application from a Windows Server 2012R2 to a new Windows Server 2016 Standard Edition:
Old server had IIS 8, new server uses IIS 10
this application has some routines that makes an MSXML2.ServerXMLHTTP.6.0 call to a page hosted on the same server:
the problem is that this routine works on the old server, but does not work on the new server
I build this small routine to make the test
<%
  Dim xmlhttp
  Dim payload
  payload="OID="&Timer*100
  Set xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP.6.0")
  xmlhttp.setTimeouts 30,500,1000,1000
  xmlhttp.Open "GET", "http://sameserver.com/test.asp?"&payload , false
  On Error Resume Next
  xmlhttp.Send
  If Err.Number Then
    response.write "ERROR: Could Not Retrieve Remote Server
  Error Number: "&Err.Number&"
Error Description: "&Err.Description
    Err.Clear
  Else
    response.write = "OK: "&xmlhttp.ResponseText
  End If
  On Error Goto 0
  Set xmlhttp = nothing
%>

that works on the old server but on the new server returns
Error Number: -2147012894
Error Description: Operation Timeout

I thought there were some bad/missing settings on new server, perhaps in IIS Settings, but I also tried a very simple test in PHP, that works fine:
<?php
    $timer= new DateTime();
    $payload='OID='.$timer->format('Y-m-d%20H:i:s');
    $url='http://sameserver.com/test.asp?'.$payload;
    echo file_get_contents($url);
?>

Clearly I can change these routine and use PHP, but I'm afraid that this error could create also other, at present, undisclosed issues
Can suggest the possible reason, or, at least, which checks has to be made?
Thanks

A: Your answer is here. Microsoft recommends not making ServerXMLHTTP to the same server. There are probably alternatives; it's hard to tell what you're trying to do from the code you posted.


text:
Q: Notification System Design for Multi User Application I have a requirement to design a notification system for multi-user(~1000 users) application, here are the high level requirements.

*

*System event gets triggered on specific operations.

*On event trigger, individual notification for all(or sometimes only for relevant) users gets generated and stored in database.

*While user logs in, all unread notifications for him will be pulled and displayed in ui.

*While user reads the notification, we capture the read status.

*A scheduler in background evicts all the stale notifications.

This seems like a very typical use case and straight forward to implement with the database.
But my doubt is, is there any way we can replace the Database with the Queue based messaging system? The reason I think this way is because, the use case I have seems like asynchronous in nature(like events, notifications and timely eviction of messages).
While I replace the Database with Queues, the first 2 points from above fits well, but on later part I have some doubts -

*

*In General, are queues flexible to store and query notifications based on user ids ?

*Consider this scenario - Notifications gets generated and stored in the queue, and the user is not logged in, what is the best way to handle consumer messages.
a. Should the consumer constantly listen for the messages ?, If so should the messages be stored in application memory(does not seems to be good option) ?
b. Or the consumers should be created for each users dynamically on user login? Is this a regular pattern ?
Any other recommended ways ?
Thanks

A: Your use-case is suited to a database, not a message queue. While conceptually similar to the use case, a message queue is intended for extremely short-duration storage (i.e. to buffer data moving between running processes). Since you have no control over when users log in, these notifications will potentially be stored for minutes, hours, maybe even weeks. You need a persistent storage mechanism.


text:
Q: Escaping special characters in lucene and query using wildcard I have an issue when I try to query using wildcard in a term that has a special character in it.
As an example if I index "Test::Here",I search using this using wildcard ? for "TE?T\:\:Here" (NOTE: I escaped ':'). I do not get any results. I use standard analyser and queryparser for indexing and searching.
Anyone encountered similar issue?

A: StandardAnalyzer uses StandardTokenizer, so Test::Here is seen as two tokens: Test and Here. Wildcard queries are not run through an analyzer, so you end up matching colons against the terms that do not contain them. You need to use different tokenizer, for example WhitespaceTokenizer.

A: You can't search what you haven't indexed. Below is a code to see what you index.
var analyzer = new AnyAnalyzer();
TokenStream tokensTream = analyzer.TokenStream("", new StringReader("Test::Here"));
Lucene.Net.Analysis.Token token = tokensTream.Next();
while (token != null)
{
    Console.Write("[" + token.TermText() + "] ");
    token = tokensTream.Next();
}

A: Artur is right, but there is another issue to consider which is that wildcard terms are not analyzed at all in Lucene, so you will have to make sure that the case of your query term matches the case of the indexed term (after analysis).


text:
Q: How to pass down a callback from a parent component to a nested routed component? I have the following format where I have a global component that has 3 nested components that are activated based on a given route:
  $stateProvider
    .state('create-goal', {
      url: '/create-goal',
      component: 'createGoal',
      redirectTo: 'create-goal.step-1'
    })
    .state('create-goal.step-1', {
      url: '/step-1',
      component: 'step1'
    })
    .state('create-goal.step-2', {
      url: '/step-2',
      component: 'step2'
    })
    .state('create-goal.step-3', {
      url: '/step-3',
      component: 'step3'
    });

Inside of the main create-goal html file, I have the following:
  <ui-view goal="$ctrl.goal"
           goalInfo="$ctrl.goalInfo"
           processStep1="$ctrl.processStep1">
  </ui-view>

The goal and goalInfo work great as they are data that is one way data bound. However, when I want to pass down a function, such as processStep1 to compute some action on step-1 and so forth, that function does not show up in the step-1 component even though the goal and goalInfo do.
export default {
  name: 'step1',
  restrict: 'E',
  bindings: {
    goal: '<',
    processStep1: '&'
  },
  template,
  controller
};

Thoughts?

A: There a few ways you could go about doing this.

*

*Access the function using $parent (I recommend against this, as it is relative and can cause problems

*Pass it down using attributes to inject it into each child function using the '=function' or '&function' depending on your use case

*Set the function in a helper service that can be injected anywhere.  This is great if you plan on using this a lot and if it is just for data manipulation it really belongs in a service anyways to avoid bloated controllers.

*The last way would be use models.  This would be good for if it is a function to be run on a certain type of object like users that can easily be modeled.  Such as a .save or .update function.

https://docs.angularjs.org/guide/directive
http://fdietz.github.io/recipes-with-angular-js/controllers/sharing-code-between-controllers-using-services.html
https://www.sitepoint.com/tidy-angular-controllers-factories-services/
http://www.webdeveasy.com/angularjs-data-model/


text:
Q: JQuery Uncaught TypeError In Chrome debugger I get an Uncaught TypeError: undefined is not a function when it parses this bit of code:
var pay = '{{payt}}';

if (pay.contains('visa')){
 $('#visa').prop('checked', true);
}

However this causes no problems in Firefox and executes the code. What woould cause this error?
EDIT: indexOf() works -
if (pay.indexOf("visa")!=-1){
 $('#visa').prop('checked', true);
}

A: As per MDN Documentation, the .contains function is not supported in chrome yet.

A: As the "undefined" user said, a polyfill is your best bet for ECMAScript functions that do not yet exist in the standard browsers.
if ( !String.prototype.contains ) {
  String.prototype.contains = function() {
    return String.prototype.indexOf.apply( this, arguments ) !== -1;
  };
}

Source:
MDN for String.prototype.contains()


text:
Q: -[UIImage resizableImageWithCapInsets] stretching wrong So, I have a .png image that is (640, 960) pixels in dimension. I'm trying to create a resizable image from the .png in order to stretch that image vertically and fit an iPhone 5's (640, 1096) pixel view.
I'm loading the image using +[UIImage imageNamed:], which is works fine. I then create a resizable image via -[UIImage resizableImageWithCapInsets:] using (480, 320, 479, 320) insets.
I then set the image to UIImageView. On an iPhone 4 & 4S it looks great (duh). On an iPhone 5, it appears to simply stretch the whole image vertically to 1096px, completely ignoring cap insets.

A: Turns out, when you're using a (640, 960) pixel image, it needs to be an @2x.png.
Also, @bill-williams project was super helpful: https://github.com/asmallteapot/ImageStretchDemo


text:
Q: How to compare two strings of a file match the strings of another file using AWK? I possess 2 huge files and I need to count how many entries of file 1 exist on file 2.
The file 1 contains two ids, source and destination, like below:
11111111111111|22222222222222
33333333333333|44444444444444
55555555555555|66666666666666
11111111111111|44444444444444
77777777777777|22222222222222
44444444444444|00000000000000
12121212121212|77777777777777
01010101010101|01230123012301
77777777777777|97697697697697
66666666666666|12121212121212

The file 2 contains the valid id list, which will be used to filter file 1:
11111111111111
22222222222222
44444444444444
77777777777777
00000000000000
88888888888888
66666666666666
99999999999999
12121212121212
01010101010101

What I am struggling to achieve is find a way to count how many entries in file one possess the entry in file 2.  Only when both numbers in the same line
exist in file 2 will the line be counted.
On file 2:
11111111111111|22222222222222 — This will be counted because both entries exist on file 2, as well as 77777777777777|22222222222222 because both entries exist on file 2.
33333333333333|44444444444444 — This will not be counted because 33333333333333 does not exist on file 2 and the same goes to 55555555555555|66666666666666, the first does not exist on file 2.
So in the examples I mentioned in the beginning it should count 6, and printing this should be enough, better than editing one file.

A: awk -F'|' 'FNR == NR { seen[$0] = 1; next }
           seen[$1] && seen[$2] { ++count }
           END { print count }' file2 file1

Explanation:
1) FNR == NR (number of record in current file equals number of record) is only true for the first input file, which is file2 (the order is important!). Thus for every line of file2, we record the number in seen.
2) For other lines (which is file1, given second on the command line) if the |-separated fields (-F'|') number 1 and 2 were both seen (in file2), we increment count by one.
3) In the END output the count.
Caveat: Every unique number in file2 is loaded into memory. But this also makes it fast instead of having to read through file2 over and over again.

A: Don't know how to do it in awk but if you are open to a quick-and-dirty bash script that someone can help make efficient, you could try this:
searcher.sh
-------------
#!/bin/bash

file1="$1"
file2="$2"

-- split by pipe
while IFS='|' read -ra line; do

    -- find 1st item in file2. If found, find 2nd item in file2
    grep -q ${line[0]} "$file2"
    if [ $? -eq 0 ]; then

        grep -q ${line[1]} "$file2"
        if [ $? -eq 0 ]; then

            -- print line since both items were found in file2
            echo "${line[0]}|${line[1]}"

        fi

    fi

done < "$file1"

Usage
------
bash searcher.sh file1 file2

Result using your example
--------------------------
$ time bash searcher.sh file1 file2
11111111111111 | 22222222222222
11111111111111 | 44444444444444
77777777777777 | 22222222222222
44444444444444 | 00000000000000
12121212121212 | 77777777777777
66666666666666 | 12121212121212

real    0m1.453s
user    0m0.423s
sys     0m0.627s

That's really slow on my old PC.


text:
Q: Android FusedLocationProvider returns null if no internet connection available The Title says most of it:
I use the FusedLocationProvider which works perfect if there is a internet connection.
If no connection is present (no sim card, no wifi connection but wifi turned on) everything returns null, even the getLastLocation().
The Api-connection for the request is successful.
Is there a solution or do i have to use the old location manager?

A: I found the answer myself and it is pretty obvious.
I am using my phone indoor and the GPS-receiver just has a serious problem to get a location fix -> of course, it is indoor. It CAN get a location fix, but it is not always possible.
So it is not the problem of the FusedLocationProvider, it does works offline as well, but then without cell-tower or wifi location.


text:
Q: The value property in reactive forms does not initializes the form control name I am using reactive forms in which I want two way data binding, therefore i used "value" property to initialize the default values of form group. because form group is in ngFor loop but when I tried to get the form I only get edited values and can't get the default i seems that "value" property does not initializes the form control, It only display in the DOM.
TS:
 userForm: FormGroup;

 constructor(private fb: FormBuilder){}

 ngOnInit(){
    this.userForm = this.fb.group({
  userName: [''],
  fullName: [''],
  email: [''],
 });
   }

OnUpdateClick() {

 console.log(this.userForm.get('userName').value);
 console.log(this.userForm.get('fullName').value);
 console.log(this.userForm.get('email').value);

 }

HTML:
   <div *ngFor="let agent of agents">

    <form [formGroup]="userForm" >

                    <mat-form-field >
                      <mat-label>Name</mat-label>
                      <input matInput id="Name" name="name" value="
                     {{agent.username}}" formControlName="userName">
                    </mat-form-field>

                    <mat-form-field >
                      <mat-label>Name</mat-label>
                     <input matInput id="FName" name="Fname" value="
                     {{agent.fullName}}" formControlName="fullName">
                    </mat-form-field>

                      <mat-form-field >
                      <mat-label>Name</mat-label>
                     <input matInput id="email" name="email" value="
                     {{agent.email}}" formControlName="email">
                    </mat-form-field>

              <button (click)="OnUpdateClick()"> SAVE </button>

   </div>

When i try to get the form fields in "OnUpdateClick" function, I only get those values which i made dirty, the untouched controls should also returns their default values

A: Raza, At first, say that, using ReactiveForm, really we are not binding data, we create a form so in form.value we have the data. You can see write in your .html -just for check-
{{userForm?.value|json}}

I like create a function like
constructor(private fb: FormBuilder){}

createForm(data:any):FormGroup
{
   return this.fb.group({
      userName: [data?data.userName:null],
      fullName: [data?data.fullName:null],
      email: [data?data.email:null],
   });
}

If you has a unique agent you can do, when has an agent
ngOnInit(){
    this.userForm = this.createForm(agent);
}

If your agents are from a call to a service
ngOnInit(){
    this.mayService.getAgent().subscribe(data=>
    {
        this.userForm = this.createForm(data);
    })
}

Well, you has an array of Agents, and I don't know what do you want to get in userForm .value. If you want to get and array of object, take account Dhara's response and my comment
myArrayForm:ArrayForm; //declare an array Form
ngOnInit(){
    this.myArrayForm= this.fb.array(agents.map(a=>this.createForm(a));
    //Its a abreviate way to say
    //this.myArrayForm=[];
    //for (let i = 0; i < this.agents.length; i++) {
    //     this.userDataArray.push(agents[i]);
    //}
}

And the .html
<form [formGroup]="myArrayForm" (submit)="save(myArrayForm)" >
      <div *ngFor=" let agent of myArrayForm.controls;let i = index"
           [formGroupName]="i">
         <mat-form-field >
             <mat-label>User Name</mat-label>
             <input matInput id="Name" name="name"  formControlName="userName">
         </mat-form-field>
         <mat-form-field >
              <mat-label>Full Name</mat-label>
              <input matInput id="FName" name="Fname"  formControlName="fullName">
         </mat-form-field>
         <mat-form-field >
              <mat-label>E-mail</mat-label>
              <input matInput id="email" name="email" formControlName="email">
         </mat-form-field>
      </div>
    </div>
    <button> SAVE </button>
</form>

save(myForm)
{
   console.log(myForm.value)
}

But you can want to have an array of FormGroup
myArray:FormGroup[] //declare an array of FormGroup
ngOnInit(){
    this.myArray= agents.map(a=>this.createForm(a));
    //Its a abreviate way to say
    //this.myArray=[];
    //for (let i = 0; i < this.agents.length; i++) {
    //     this.myArray.push(this.createForm(agents[i]));
    //}
}

And the .html
<form *ngFor="let form of myArray" [formGroup]="form">
     <mat-form-field >
         <mat-label>User Name</mat-label>
         <input matInput id="Name" name="name"  formControlName="userName">
     </mat-form-field>
     <mat-form-field >
          <mat-label>Full Name</mat-label>
          <input matInput id="FName" name="Fname"  formControlName="fullName">
     </mat-form-field>
     <mat-form-field >
          <mat-label>E-mail</mat-label>
          <input matInput id="email" name="email" formControlName="email">
     </mat-form-field>
</form>
<button (click)"save()"> SAVE </button>

save()
{
    myArray.forEach(form=>{
        console.log(form.value)
    }
}

A: you need to create formarray and patch the formcontrolname values.
       userForm: FormGroup;

          constructor(private fb: FormBuilder){}
       ngOnInit(){
          this.userForm = this.fb.group({
              userData: this.fb.array([])
           });
          this.addUserData();
       }
       get userDataArray() {
           return this.userForm.get('userData') as FormArray;
        }
       addUserData() {
         for (let i = 0; i < this.agents.length; i++) {
            const datas =  this.fb.group({
                 userName: [this.agents[i].userName],
                  fullName: [this.agents[i].fullName],
                  email: [this.agents[i].email],
                 });
      this.userDataArray.push(datas);
        }
            }
OnUpdateClick() {

 console.log(this.userForm.value);

 }

change your html like below; ngfor for reacctive form array and add formarray
   name.don't need to bind values.
    <form [formGroup]="userForm" >
 <div formArrayName="userData">
      <div *ngFor=" let agent of userDataArray.controls;let i = index" [formGroupName]="i">
                        <mat-form-field >
                          <mat-label>Name</mat-label>
                          <input matInput id="Name" name="name"  formControlName="userName">
                        </mat-form-field>

                        <mat-form-field >
                          <mat-label>Name</mat-label>
                         <input matInput id="FName" name="Fname"  formControlName="fullName">
                        </mat-form-field>

                          <mat-form-field >
                          <mat-label>Name</mat-label>
                         <input matInput id="email" name="email"  formControlName="email">
                        </mat-form-field>

                       </div>
            </div>
          <button (click)="OnUpdateClick()"> SAVE </button>
             </form>


text:
Q: Mixed Effects Nesting I have a simple model with mixed effects. I asked subjects ten questions, five easy and five hard, and saw how much they relied on advice, based on who their advisor was (algorithm or peer) and how hard the question was (easy or hard). The model is predicting how much an individual responds to advice. The simplified model is below. AmountOfAdvice is a percentage, between 0 and 100. AdviceSource is a dummy, 0 or 1. Difficulty is a dummy, 0 (easy), 1 (hard). The R code is below.
model11 <- lmer(WOA ~ AlgoGroup*difficulty + (1| ResponseId), data=df)

I want to account for question-level variations as well. If I simply add a Question factor, like in the model below, where question is a factor with ten levels, then I believe I run into a problem because all questions are either easy or hard. E.g. Question 1, 3, 5, 7, and 9 are always easy. Thus, this means my matrix no longer has an inverse. What is the best solution?
    model11 <- lmer(WOA ~ AlgoGroup*difficulty + Question + (1| ResponseId), data=df)

A:
AmountOfAdvice is a percentage, between 0 and 100. AdviceSource is a dummy, 0 or 1

This doesn't seem to correspond to the variables in the models. I don't see AmountOfAdvice or AdviceSource in either of your models. Notwithstanding that, this seems to be a crossed design, not nested. All subjects answered the same 10 questions. There are repeated measures in subjects and also in question, but a particular question does not belong to a particular subject, nor vice versa. You could fit fixed effects for QuestionID but with 10 of them, and them being plausibly samples from a wider population of questions, they are more naturally modelled as random effects.
Your model:
model11 <- lmer(WOA ~ AlgoGroup*difficulty + (1| ResponseId), data=df)

does not make sense if ResponseId is the unit-level measurement. That is, if it is the ID for a particular answer, because there are no repeated measures at that level. The repeated measures are within subjects and questions (crossed).
So an appropriate model would be:
lmer(WOA ~ AlgoGroup * difficulty + (1|QuestionID) + (1| SubjectID), data=df)


text:
Q: Integrate WhatsApp Business API with WhatsApp Product Catalogue We are building a e-retail bot on WhatsApp platform. I would like to understand if there is a possibility to integrate the Whatsapp Business Api with the product catalog option they provide in the WhatsApp for Business App.

WhatsApp Business API - https://www.whatsapp.com/business/api/?lang=en
WhatsApp for Business - https://www.whatsapp.com/business

The flow that I am looking for is

*

*We will list all the products available on the WhatsApp for Business App

*Build a conversation bot which uses WhatsApp Business API

*Using API from WhatsApp Business API, open a product catalog or send a message with a call to button which will open product description or cart.

Is this something that is possible?

A: Short answer, not right now.
Catalog is not available for WhatsApp Business API.
However, it's been announced on the last F8 that they are working on that.

Small Update Dec. 2021:
Catalogs are now available but only for WhatsApp Business API phone numbers. This means that regular WhatsApp Business Catalogs cannot be integrated.
A new FB Catalog must be created and connected to the WABA line via FBM.
A new kind of message is available for the /messages endpoint and the CoreApp version needs to be upgraded to the latest.


text:
Q: Why do People secure selective Pages only using SSL in their Websites? When People buy SSL Certificates for their websites, they can use it for all Pages in the domain. Why then they use it for selective pages only.
Typically you will find that all E-Commerce Solutions like Magento, ZenCart etc will have settings for Secure Page and Insecure Page.
They will typically have their Checkout and Payment Processing related pages secured using https while all other parts of the site will remain insecure.
Does using SSL in all Pages has a Performance Overhead? As in the Load on Server will increase if you used SSL in all Pages?
How will a Customer, Vendor, Payment Processor gain Confidence in your site if you didn't use SSL in your Home Page? As they will probably land in your Home Page only.

A: While it's true that encrypting public information is not as valuable, it's not the case that it's worthless because it provide authenticity.
Consider the New York Times website. It's not encrypted because all the information is public. However, if you were to MITM the WiFi network at a major financial conference and inject stories about a market crash, that could be an effective attack against the authenticity of the page.
Additionally, if forms are on unencrypted pages then it hardly matters if they submit over HTTPS because the attacker can rewrite the action URL and the user is none the wiser.

A: Basically, you only need to use SSL when you post and get data from the server which are sensitive.
There is no benefits to be SSL on a static web site that only throw general and public information to the browser.
SSL encrypt the data on the Request and response so yes, your performance can suffer for nothing on the static part of your web site.


text:
Q: Verify HTML Table using Selenium Can someone let me know which approach is good for verifying HTML Table.  I have to write test case related to adding/deleting/editing HTML table using selenium.
Table looks like this

Name and Branch could be duplicate, the only way to uniquely Identify the row is using id (First column).
I am using the page object pattern, so I need to write the function for adding/editing/deleting and verifying that row exist or not.

*

*how should I write a function to add record and then a separate function to verify that record has been added successfully. As the name could be duplicate I can not verify if name exist in the table or not. The other way is, I return the ID of last row once I add the record. And then I can verify if name on last id is same as I recently added. However this approach has some glitch as well.

is there any better approach for this situation.

A: For add test case, you could create a function in your PageObject that returns the count of rows that have the same value in the Name field.
In your test case,

*

*Store this number in a variable

*Add a record

*Back to the grid screen, invoke the row counting function again, comparing it with the stored value

*It must be the stored value + 1, otherwise something is wrong.

As an additional check, you could also store the total number of rows in the table prior adding, and check if that value has also increased by one after edition (ensuring  no record has been replaced in the process).
Note: If you're using PageFactory, you could also create an IList with the rows in the table, and use its count property instead of creating a counting function.
Edit:Your add method can be stored inside your PageObject, so that you have it separated from assertion. Even if you return the id, without knowing what was in the table prior adding your record, a separated individual verification won't be of much use.

A: So without seeing the html for this table, I'll have to make some assumptions.  It looks like the ID column are hyperlinks, so the xpath for those will be slightly different from the other cells.  Okay, so onto the solution.
We first need to think about how we're going to store the data from the table. You want some kind of 2 dimensional object that is easy to work with.  I like to use HashMap to store the individual rows.  HashMap stores information in un-ordered, key-value pairs.  They Key would be the name of the column, and the Value would be the value of that cell for that row.
To store a table's worth of data, I would then put each of those rows that are stored in separate HashMaps and put that into an ArrayList.
Now onto how to scrape the data, the fastest solution is always the one that does the least number of lookups and calls to Selenium.  In this case since you have all kinds of weirdness going on with the table, I would target all of the data cells with one lookup.
Without seeing the HTML, my xpath would look something like //table[@id='something']/tbody/tr/td[1]/a|//table[@id='something']/tbody/tr/td[not(./a[./text()='View' or ./text()='Edit' or ./text()='Delete'])]
The Pipe symbol conjoins the 2 xpaths together so it will target both types of cells in the correct order.
Here's my generic TableData class.  You create an instance of this class to store the data.  The data itself gets stored in the _data object.
public class TableData {

public ArrayList<HashMap<String, String>> _data;

public TableData(ArrayList<HashMap<String, String>> data) {
    _data = data;
}

    public static TableData get_SiteTable_ByCell(WebDriver driver, By tableCells, String[] headerValues) {
    ArrayList<WebElement> tableCellElements = new ArrayList<WebElement>(driver.findElements(tableCells));

    ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();

    int numberRows = tableCellElements.size() / headerValues.length;

    for (int i = 0; i < numberRows; ) {

        HashMap<String, String> newRow = new HashMap<>();
        for (int j = 0; j < headerValues.length; j++, i++) {
            newRow.put(headerValues[j], tableCellElements.get(i).getText());
        }
        data.add(newRow);
    }

    return new TableData(data);
}
}

So now that we have our method for getting the data, the values that I need to pass in are...
public TableData getTable(WebDriver driver)
{
    String[] headers = {"ID", "Name", "Branch"};
    By cellsBy = By.xpath("//table[@id='something']/tbody/tr/td[1]/a|//table[@id='something']/tbody/tr/td[not(./a[./text()='View' or ./text()='Edit' or ./text()='Delete'])]");
    return TableData.get_SiteTable_ByCell(driver, cellsBy, headers);

}

Okay, so now we want to get a specific row. I need to write a method that will return a HashMap for the given criteria.  This will also go in the TableData class from earlier.
public HashMap<String, String> returnRow(String columnName, String columnValue){
    for(HashMap<String, String> row : _data){
        if(row.get(columnName).equals(columnValue)){
            return row;
        }
    }
    return null;
}

So now that I have all that, my code would look something like...
@Test
public void newTest1()
{
    TableData customerTable = getTable(driver);
    HashMap<String, String> rowWeWant = customerTable.returnRow("ID", "1");
    String valueWeWant = rowWeWant.get("Name");

}


text:
Q: Rabbitmq queue is always blocked after running for a while (using Docker ) In normal conditions,everything is right,but when we put our service in the docker,
it is always blocked after running for a while ,I wonder if there is something different configuration when using docker?or Could you give me a clue to solver this problems?

A: You should check https://www.rabbitmq.com/memory.html
By default, when the RabbitMQ server uses above 40% of the available RAM, it raises a memory alarm and blocks all connections that are publishing messages
You can try setting more rabbitmq memory limit inside docker by command:
docker exec <your_container_id> rabbitmqctl set_vm_memory_high_watermark 0.8

Or increase memory limit (cgroup) for your docker instance if memory limit is set too low