text:
Q: 'et al' not inserted after first author in case of multiple articles by the same authors in the same year (apacite + natbib) I am using apacite with the natbibapa option and I encountered some interesting behaviour regarding the use of et al. The MWE below shows that normally, 'firstauthor et al' is used in citiation call-outs to pieces with six or more authors. However, when another entry by (a few of) the same authors in the same year is added, the 'et al' only appears after the fourth author (uncomment \citep{article2} to see this result).
My question is: how do I get apacite to employ 'et al' in citation call-outs in case of more than six authors, regardless of the presence of other articles by the same authors?
\documentclass{article}
\usepackage[natbibapa]{apacite}
\bibliographystyle{apacite}

\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}
@misc{article1,
  title  = {Article title},
  author = {Author, Anna and Buthor, Bertha and Cuthor, Christine
            and Duthor, Donna and Euthor, Erica and Futhor, Fay},
  year   = 2019,
}
@misc{article2,
  title  = {Article title},
  author = {Author, Anna and Buthor, Bertha and Cuthor, Christine},
  year   = 2019,
}
\end{filecontents}

\begin{document}
\citep{article1}

%\citep{article2}

\bibliography{\jobname}
\end{document}

A: (too long for a comment, hence posted as an answer)
Here's an excerpt from p. 13 of the user guide of the apacite package:

When citing a work with one or two authors, all authors are included in each citation [call-out]. When citing a work with six or more authors, only the first author's
  name is included in the text, followed by "et al.". With three to five authors, the
  full list is included the first time the work is cited, and only the first with "et al."
  in subsequent citations.
There are some special cases, where some of the authors and the year are the same, but not the whole author list, in which more names are retained on subsequent
  citations as well. Section 13 includes some examples of complex situations
  and how to deal with them. All of this is automatically handled by apacite.

In short, the behavior you've documented in your query is exactly what apacite is meant to be doing. If you deviate from any of the settings of the apacite package, you are also automatically non-compliant as far as the APA style and formatting guide is concerned.
If you do not like this setting, you must provide some explicit suggestions for how one (or BibTeX) should distinguish between a piece published by "Author, Anna and Buthor, Bertha and Cuthor, Christine" in 2019 and another piece, by "Author, Anna and Buthor, Bertha and Cuthor, Christine and Duthor, Donna and Euthor, Erica and Futhor, Fay", also published in 2019. A commonly chosen solution is to affix "a", "b", etc to the year; however, you've made no such indication, and I certainly do not wish to be presumptuous.
Rather than engage in an almost certainly very complicated hack of the apacite package and the apacite bibliography style, I suggest you switch to a different bibliography style altogether. A candidate alternative might be elsarticle-harv, which requires the natbib citation management package.

\RequirePackage{filecontents}
\begin{filecontents}{\jobname.bib}
@misc{article6,
  title  = {Further thoughts},
  author = {Author, Anna and Buthor, Bertha and Cuthor, Christine
            and Duthor, Donna and Euthor, Erica and Futhor, Fay},
  year   = 2019,
}
@misc{article3,
  title  = {Thoughts},
  author = {Author, Anna and Buthor, Bertha and Cuthor, Christine},
  year   = 2019,
}
\end{filecontents}

\documentclass{article}
\usepackage{geometry,parskip} %optional
\usepackage[authoryear]{natbib}
\bibliographystyle{elsarticle-harv}

\begin{document}
\citet{article6}

\citet{article3}
\bibliography{\jobname}
\end{document}


text:
Q: I have one query in android coding about button linking I am new to the android and I have to link four buttons to different social sites like facebook twitter youtube and instagram also shown below in the image
I have already created  buttons and I am linking all buttons to different xml files but I want to ask you friends that for linking xml files I am creating different activity like
socialactivityf.java for facebook
socialactivityt.java for twitter
socialactivityy.java for youtube etc.
so I am thinking to create one socialactivity.java and link all the four button to different xml files is it possible
If possible I have written the code for facebook and can I edit this code and send it to twitter from this file itself
I have to add for twitter,youtube  in the same file or should I compulsory add another file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: find the annual per capita spending for personal consumption in doller? Total annual spent of a country is $ \ \$ 9 \ $ trillion for personal consumption . If total population is $ 250 \ $ million , then find the annual per capita spending for personal consumption  in doller ?
Answer:
total expenditure= $ \ 9 \ $ trillion= $ \ 9 \times 10^6 \ $ million
Total population =$ 250 \ million \ $ .
Hence annual per capita for personal spending = $ \frac {9 \times 10^6}{250}=  ? \ \ person /year $
I am just unable to find the result in $ person/year $ unit .
Is there any help ?

A: The unit for per capita spending is $\frac {dollars}{person \cdot year}$ because it is the amount each person spends in one year.  The annual total spending is $9 \cdot 10^{12} \frac {dollars}{year}$  divided by $250 \cdot 10^6 persons$ giving units of $\frac {dollars}{person\cdot year}$


text:
Q: How to fix java.lang.module.FindException: Module java.se.ee not found? I have an error, How to fix it in linux elemetary os?
I install JDK 11 on my os
when i type ./sdkmanager show this error
I install android studio but not running because require sdk
Error occurred during initialization of boot layer
java.lang.module.FindException: Module java.se.ee not found

A: I'm using Mint 19 and openJDK11 installed.
After a lot of searches and failures, I finally made these things(thanks to the contributors):
1) Download
openjdk10... wget from this link
2) Alternate /bin/java and javac
sudo update-alternatives --install /usr/bin/java java \    .../jdk-10.0.2/bin/java 1

sudo update-alternatives --install /usr/bin/javac javac \    .../jdk-10.0.2/bin/javac 1

sudo update-alternatives --config java

sudo update-alternatives --config javac

java --version

javac --version

.../jdk-10.0.2/bin/java --version

3) REPLACE
../jdk-10.0.2/lib/security/cacerts FOR /usr/lib/jvm/default-java/lib/security/cacerts
4) Export
JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee

5) Now the following works
.../tools/bin/sdkmanager

A: please try to switch to JDK 8, this solved my issue.
Double check here as well.
Hope it helps.

A: The only option we have is to downgrade the java version.
My java version is 12.
I wasted a few hours trying to resolve flutter doctor --android-licenses.
After a ton of SO, github, googling I found this article regarding the deprecation of
Java EE modules
I had to downgrade my java version to 1.8.


text:
Q: Authenticating users if they have a cookie I need assistance with letting users access a page (.hbs) if they have a cookie. I have listed an image of my file hierarchy with my files and some of my code. If you could provide any insight or assistance that would be very helpful.
I am trying to create an account registration and login system in which data goes into a MySQL Database. I already have the data saving properly in my database, I just need help redirecting to the dashboard page after registering / logging in.
Image of my hierarchy / files (PLEASE VIEW)
page.js (Under routes folder)
// Express Setup
const express = require('express');
const router = express.Router()

// Login (Main) Page
router.get('/', (req, res) => {
    res.render('index');
});

// Login Page
router.get('/login', (req, res) => {
    res.render('login');
})

// Register Page
router.get('/register', (req, res) => {
    res.render('register');
});

// Dashboard
router.get('/dashboard', (req, res) => {
    res.render('dashboard');
})

module.exports = router;

auth.js (Under routes folder)
// Express Setup
const express = require('express');
const router = express.Router()

// Misc
const authController = require('../controllers/auth')

// Auth / Register
router.post('/register', authController.register);

// Auth / Login
router.post('/login', authController.login);

// Auth / Dashboard
router.post('/dashboard', authController.dashboard);

module.exports = router;

auth.js (Under controllers folder)
// Database
const mysql = require('mysql');

const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')

// Misc

// Get Database
const db = mysql.createConnection({
    host: process.env.DATABASE_HOST,
    user: process.env.DATABASE_USER,
    password: process.env.DATABASE_PASSWORD,
    databse: process.env.DATABASE

});

// Get Login
exports.login = async (req, res) => {
    try {
        const { email, password } = req.body;

        if ( !email || !password ) {
            return res.status(400).render('login', {
                message: 'Please enter all fields.'
            });
        }

        // Find User
        db.query('SELECT * FROM users WHERE email = ?', [email], async (err, results) => {
            if ( !results || !(await bcrypt.compare(password, results[0].password))) {
                res.status(401).render('login', {
                    message: 'Information is invalid'
                });
            } else {
                const id = results[0].id;

                const token = jwt.sign({ id: id }, process.env.JWT_SECRET, {
                    expiresIn: process.env.JWT_EXPIRES_IN
                });

                const cookieOptions = {
                    expires: new Date(
                        Date.now() + process.env.JWT_COOKIE_EXPIRES * 24 * 60 * 60 * 1000
                    ),

                    httpOnly: true
                }

                res.cookie('loginC', token, cookieOptions);
                res.status(200).redirect('dashboard'); (Apart of my issue)

            }
        });

    } catch (err) {
        console.log(err);
    }
}

// Users Page (Where I'm somewhat confused at. I want them to access this dashboard page if they have the cookie.)
exports.dashboard = (req, res) => {
    if ( res.cookie.user == 'loginC' || id ) {
        res.render('dashboard')
    } else {
        res.status(401).redirect('register')
    }
}

// Run Register Module
exports.register = (req, res) => {
    console.log(req.body);

    // Body Variable(s)
    const { name, email, password } = req.body;

    // Database Query
    db.query('SELECT email FROM users WHERE email = ?', [email], async (err, results) => {
        if (err) {
            console.log(err);
        }

        if ( results.length > 0 ) {
            return res.render('register', {
                message: 'That email has already been registed.'
            });
        }

        // Hashing Passwords
        let hashedPass = await bcrypt.hash(password, 8);
        console.log(hashedPass);

        db.query('INSERT INTO users SET ? ', {name: name, email: email, password: hashedPass}, (err, results) => {
            if (err) {
                console.log(err);
            } else {
                return res.render('login', {
                    message: 'User Registered'
                });
            }
        })

    });

}

Please note, I don't want users to have the ability to go to www.DOMAINNAME.com/dashboard without having the cookie.
If you have any questions, please let me know.

A: you will need to implement middleware that check's your cookie before accessing the route. first install https://www.npmjs.com/package/cookie-parser and add it to your server init process
var cookieParser = require('cookie-parser'); //add it in your app init
app.use(cookieParser() // this will let you to parse the cookie and use it.

router.get('/dashboard',middlewareFunction, (req, res) => {
res.render('dashboard');
})

example for basic middleware:
const middlewareFunction = (req , res ,next) => {
  const { loginC } = req.cookies;
  const isValidAuth = true/false - verify your cookie if it valid or not..
  if(isValidAuth) {
     next();
  }
  next('Error.....')// to return error
  res.redirect('/login') // if you want instead to redirect to login page
}

you can read about it more here :https://expressjs.com/en/guide/using-middleware.html


text:
Q: Problem (perhaps trivial) with the continued-fraction approach to (generalized) Pell-solutions I've seen some Q&A's here which put light on the continued-fractions approach to finding solutions for the Pell-equation. I'm trying to get familiar with this method to apply it to my style of generalized Pell-equations $$ a^2 + b^2 = D \cdot c^2 \qquad \qquad \text{always with }D=u^2+v^2 \tag 1$$
For many of combinations of $(u,v)$ my understanding suffices to get the correct set of solutions from the convergents of the cont.frac, of $\sqrt D$ , but some combinations give problems, and while the brute-force search gives solutions, my cont.-frac. search gives nothing.
The problematic cases seem to be those when $u=v$.
I start with the ansatz $a=u$ and thus look at solutions of (eq 1)
with the constant parameters $(u,v)$ used for some set of solutions
$$u^2 + b^2 = (u^2+v^2) \cdot c^2 \qquad \text{solving for integer $b$ and $c$} \tag 2 $$
(Of course, I ignore cases where $(u,v)$ are part of of a pythagorean triple)
For instance, with $(u,v)=(2,2)$ I get the c.f.-convergents for $\sqrt D$
  2  3  14  17  82  99  478  577
  1  1   5   6  29  35  169  204

and the solutions of the (eq.2)
$$\small \begin{array} {rrr|r}
 a& b& c& \text{iteration-height} \\ \hline
 2 & 2 & 1 & 0.0 \\
 2 & 14 & 5 & 1.00000000000 \\
 2 & 82 & 29 & 2.00000000000 \\
 2 & 478 & 169 & 3.00000000000 \\
 2 & 2786 & 985 & 4.00000000000 \\
 2 & 16238 & 5741 & 5.00000000000 \\
 2 & 94642 & 33461 & 6.00000000000 \\
 2 & 551614 & 195025 & 7.00000000000
 \end{array}$$
(here "iteration-height" is the exponent to which I have to take the power of the iteration-matrix to arrive at the solution given in the row).
We see, that the values in $(b,c)$ can be found in the c.f.-convergents above.
This worked for all tested (small combinations) of $(u,v)$ until suddenly just the very small problemparameter $(u,v)=(3,3)$ breaks.
The c.f.-convergents are
  4  17  140  577  4756  19601  161564  665857
  1   4   33  136  1121   4620   38081  156944

The list of solutions for (eq.2) found by brute-force is
$$\small \begin{array} {rrr|r}
 a& b& c& \text{iteration-height} \\ \hline
 3 & 3 & 1 & 0.0 \\
 3 & 21 & 5 & 0.500000 \\
 3 & 123 & 29 & 1.00000 \\
 3 & 717 & 169 & 1.50000 \\
 3 & 4179 & 985 & 2.00000 \\
 3 & 24357 & 5741 & 2.50000 \\
 3 & 141963 & 33461 & 3.00000 \\
 3 & 827421 & 195025 & 3.50000 \\
 3 & 4822563 & 1136689 & 4.00000
 \end{array}
$$
but I can't see any relation to the convergents of the continued fraction of $\sqrt D$...
(The existence of half-integer values in the iteration-heights indicate that we have actually 2 separate lists of solutions and don't matter much here).

Update
Just found the/a relation using the generalized convergents. Using (in my notation) the "upper gen. cvgts" which occur as list:
***                                ***                                           ***                                                        ***
  4  21  38  55  72  89  106  123  140  717  1294  1871  2448  3025  3602  4179  4756  24357  43958  63559  83160  102761  122362  141963  161564  827421  1493278  2159135  2824992  3490849  4156706  4822563
  1   5   9  13  17  21   25   29   33  169   305   441   577   713   849   985  1121   5741  10361  14981  19601   24221   28841   33461   38081  195025   351969   508913   665857   822801   979745  1136689
     *                         *         *                                   *           *                                            *              *                                                    *

Here the entries marked with *** are true convergents, and the entries marked with * the solutions found by brute-force.
end-update

One more example which is working: $(u,v)=(3,7), D=58$.
The first few c.f.-convergents:
  7  8  15  23  38  61  99  1447  1546  2993  4539  7532  12071  19603  286513  306116
  1  1   2   3   5   8  13   190   203   393   596   989   1585   2574   37621   40195

The first few solutions,
$$ \small \begin{array} {rrr|r}
 a& b& c& \text{iteration-height} \\ \hline
 3 & 7 & 1 & 0.0 \\
 3 & 297 & 39 & 0.350284 \\
 3 & 12071 & 1585 & 0.700567 \\
 3 & 286513 & 37621 & 1.00000 \\
 3 & 11644479 & 1528995 & 1.35028 \\
 3 & 473255633 & 62141509 & 1.70057 \\
 3 & 11233028671 & 1474968925 & 2.00000 \\
 3 & 456533443377 & 59945777931 & 2.35028
 \end{array}
$$
Some solutions are found assuming they have common factor $a=u=3$ and multiples of $3$ in the convergents are tested (for instance $(279,39) = 3\cdot (99,13)$).
(Again, the fractional iteration-heights indicate, that we have three intertwined subsequences of solutions here)

The problem seems to occur with all cases $(u,v)$ with $u=v$ except for $u=v \in [2,5,25,???]$

Q: Is there any (possibly obvious) reason for this inconvenient behave and some remedy?

A: The problem of finding the sequences of solutions for the "problematic cases" - in my question focused to cases of $u^2+v^2=D$ and $u=v$ such that $D=2u^2$  - seems to be intractable with the tools shown so far.
With the help of heuristics we can find some suggestive scheme which at least reduces the complexity.
Of course, for the combination $(u,v)=(u,u), D=2 u^2$ and the "keys" $[a,b_k,c_k]=[u,b_k,c_k]$ with $u^2+b^2 = D c^2= 2 u^2 c^2$ we find, using brute force, some solutions in small numbers. The first is of course trivial; we must have a first solution as $[a,b,c]=[u,u,1]$ and need only a second one to generate an initial transfer-matrix $T$ which allows then to create the sequence of solutions by $[u,u,1] \cdot T^k$ .
Heuristics gave a simple scheme to compute $T$ directly from the value $u$:
$$ \begin{matrix}T_u=\begin{bmatrix}1 & .& .\\. & 3& \frac2u\\. & 4  u& 3 \end{bmatrix} & \to & R_u=\begin{bmatrix} 3& \frac2u\\ 4  u& 3 \end{bmatrix}  \end{matrix} \tag 1$$
In the following I reduce the notation to the $2x2$-matrix $R_u$ which contains only the nontrivial part of $T_u$ : $R_u=T_u[2..3,2..3]$
So, having some initial key $[u,1]$ we can construct all further solutions by $$[b_k,c_k] = [u,1] \cdot R_u^k \tag 2$$
Now, by basic assumptions, we do not allow transfer-matrices $R_u$ with fractional values. But, again heuristically, we find, that each $u$-parameter produces a $R_u$ matrix, having fractional entries, but whose $ex$'th-power gives a full integer matrix:
$$ R_u ^{ex_u} = S_u \qquad \text{ having $ex_u$ such that $S_u$ is an integer matrix} \tag 3$$
This is a pattern which gives consistent results (which means: solutions of the associated generalized Pell-equation) without referring to very likely intractable compositions of generalized convergents of the continued fraction for $\sqrt D$.
However, still I don't have an analytic formula for the results involved, but a pattern that emerges and helps to reduce the searchspace for solutions.
Here is a subset of solutions which I got by heuristics. The matrices $R_u$ are created following my mentioned heuristic.
For $u=v=2$ we have
u=2 D=   8 ex=1   R=[3, 1; 8, 3]        S=R^ex=[3, 1; 8, 3]

Note: the matrix-notation is that of Pari/GP, which means that a ";" indicates beginning of a new row.
for $u=v \in [2,3,4,6,12]$ we have
 2 D=   8 ex=1   R=[3, 2/ 2;   8, 3]   S=R^ex=[3, 1; 8, 3]
 -----------------------------------------------------------------
 3 D=  18 ex=2   R=[3, 2/ 3;  12, 3]   S=R^ex=[17, 4; 72, 17]
 4 D=  32 ex=2   R=[3, 2/ 4;  16, 3]   S=R^ex=[17, 3; 96, 17]
 6 D=  72 ex=2   R=[3, 2/ 6;  24, 3]   S=R^ex=[17, 2; 144, 17]
12 D= 288 ex=2   R=[3, 2/12;  48, 3]   S=R^ex=[17, 1; 288, 17]
=========================================================================

for $u=v \in [2,5,7,10,14,35,70]$ we have
 2 D=   8 ex=1   R=[3, 1; 8, 3]        S=R^ex=[3, 1; 8, 3]
-----------------------------
 5 D=  50 ex=3   R=[3, 2/ 5;  20, 3]   S=R^ex=[99, 14; 700, 99]      --> krit=5*14=70
 7 D=  98 ex=3   R=[3, 2/ 7;  28, 3]   S=R^ex=[99, 10; 980, 99]
10 D= 200 ex=3   R=[3, 2/10;  40, 3]   S=R^ex=[99, 7; 1400, 99]
14 D= 392 ex=3   R=[3, 2/14;  56, 3]   S=R^ex=[99, 5; 1960, 99]
35 D=2450 ex=3   R=[3, 2/35; 140, 3]   S=R^ex=[99, 2; 4900, 99]
70 D=9800 ex=3   R=[3, 1/35; 280, 3]   S=R^ex=[99, 1; 9800, 99]
=========================================================================

Here we find the pattern, that after we have heuristically found the $ex$ for $u=v=5$ we can immediately conclude the transfermatices for all that $u$ which are divisors of $5 \cdot 14$ where $14$ is the entry $S[1,2]$ and we have for all that $u$ a constant product of $u \cdot S[1,2]$
The next block for illustration is longer, but I'll not continue that more.
We find (for $u \in $ divisors of $408 = 8 \cdot 3 \cdot 17$) for $ex=4$
  2 D=   8 ex=1   R=[3, 1; 8, 3]        T2^ex=[3, 1; 8, 3]
-----------------------------
  3 D=  18   ex=2   R=[3, 2/ 3;  12, 3]    S=R^ex=[17, 4;  72, 17]
  4 D=  32   ex=2   R=[3, 2/ 4;  16, 3]    S=R^ex=[17, 3;  96, 17]
  6 D=  72   ex=2   R=[3, 2/ 6;  24, 3]    S=R^ex=[17, 2; 144, 17]
 12 D= 288   ex=2   R=[3, 2/12;  48, 3]    S=R^ex=[17, 1; 288, 17]
-----------------------------
  8 D= 128   ex=4   R=[3, 2/ 8;   32, 3]   S=R^ex=[577, 51;  6528, 577]   --> krit=8*51=8*3*17=408
 17 D= 578   ex=4   R=[3, 2/17;   68, 3]   S=R^ex=[577, 24; 13872, 577]
 24 D=1152   ex=4   R=[3, 1/12;   96, 3]   S=R^ex=[577, 17; 19584, 577]
 34 D=2312   ex=4   R=[3, 1/17;  136, 3]   S=R^ex=[577, 12; 27744, 577]
 51 D=5202   ex=4   R=[3, 2/51;  204, 3]   S=R^ex=[577, 8;  41616, 577]
 68 D=9248   ex=4   R=[3, 1/34;  272, 3]   S=R^ex=[577, 6;  55488, 577]
102 D=20808  ex=4   R=[3, 1/51;  408, 3]   S=R^ex=[577, 4;  83232, 577]
136 D=36992  ex=4   R=[3, 1/68;  544, 3]   S=R^ex=[577, 3; 110976, 577]
204 D=83232  ex=4   R=[3, 1/102; 816, 3]   S=R^ex=[577, 2; 166464, 577]
408 D=...    ex=4   R=[3, 1/204;1632, 3]   S=R^ex=[577, 1; 332928, 577]
=========================================================================

Well, this is an interesting and not too complex pattern. Unluckily it still does not allow to determine the sequences of solutions for some pair $(u,v=u)$ for that type of generalized Pell-equations which are considered here without heuristical search.
So the question is still unresolved, and I hope someone steps in and has possibly a more productive idea...


text:
Q: DPDK MLX5 PMD driver probe issue I'm not able to use the mlx5 pmd driver with some Mellanox NICs I have installed on my server. The error I'm receiving during EAL initialization is:
et_mlx5: no Verbs device matches PCI device 0000:03:00.0, are kernel drivers loaded?
The DPDK version I'm currently using is: DPDK-STABLE-18.11
I have installed the OFED latest version:
mlnx-en-4.5-1.0.1.0-ubuntu16.04-x86_64
I have performed modprobe of the ib_uverbs kernel module
Here's the kernel version I'm using
moragalu@server:~$ uname -r
4.4.0-143-generic

Here are the NIC models:
moragalu@server:~$ lspci | grep Mell
03:00.0 Ethernet controller: Mellanox Technologies MT27710 Family [ConnectX-4 Lx]
03:00.1 Ethernet controller: Mellanox Technologies MT27710 Family [ConnectX-4 Lx]
06:00.0 Ethernet controller: Mellanox Technologies MT27710 Family [ConnectX-4 Lx]
06:00.1 Ethernet controller: Mellanox Technologies MT27710 Family [ConnectX-4 Lx]

The firmware version that the NICs are using:
moragalu@eridium03:~$ ethtool -i eridium25-03
driver: mlx5_core
version: 4.5-1.0.1
firmware-version: 14.24.1000 (MT_2420110034)
expansion-rom-version:
bus-info: 0000:06:00.1
supports-statistics: yes
supports-test: yes
supports-eeprom-access: no
supports-register-dump: no
supports-priv-flags: yes

The complete output is of the eal initialization is:
EAL: Detected 16 lcore(s)
EAL: Detected 1 NUMA nodes
EAL: Multi-process socket /var/run/dpdk/rte/mp_socket
EAL: No free hugepages reported in hugepages-1048576kB
EAL: Probing VFIO support...
EAL: PCI device 0000:03:00.0 on NUMA socket 0
EAL:   probe driver: 15b3:1015 net_mlx5
net_mlx5: no Verbs device matches PCI device 0000:03:00.0, are kernel drivers loaded?
EAL: Requested device 0000:03:00.0 cannot be used
EAL: PCI device 0000:03:00.1 on NUMA socket 0
EAL:   probe driver: 15b3:1015 net_mlx5
net_mlx5: no Verbs device matches PCI device 0000:03:00.1, are kernel drivers loaded?
EAL: Requested device 0000:03:00.1 cannot be used
EAL: PCI device 0000:06:00.0 on NUMA socket 0
EAL:   probe driver: 15b3:1015 net_mlx5
net_mlx5: no Verbs device matches PCI device 0000:06:00.0, are kernel drivers loaded?
EAL: Requested device 0000:06:00.0 cannot be used
EAL: PCI device 0000:06:00.1 on NUMA socket 0
EAL:   probe driver: 15b3:1015 net_mlx5
net_mlx5: no Verbs device matches PCI device 0000:06:00.1, are kernel drivers loaded?
EAL: Requested device 0000:06:00.1 cannot be used
EAL: PCI device 0000:03:00.1 on NUMA socket 0
EAL:   probe driver: 15b3:1015 net_mlx5
net_mlx5: no Verbs device matches PCI device 0000:03:00.1, are kernel drivers loaded?
EAL: Driver cannot attach the device (03:00.1)
EAL: Failed to attach device on primary process

Current modules loaded in the kernel:
moragalu@eridium03:~$ lsmod | grep ib
mlx5_ib                16384  0
mlx_compat             24576  4 mlx4_en,mlx5_ib,mlx4_core,mlx5_core
ib_uverbs              61440  0
ib_iser                49152  0
rdma_cm                49152  1 ib_iser
ib_cm                  49152  1 rdma_cm
ib_sa                  36864  2 rdma_cm,ib_cm
ib_mad                 49152  2 ib_cm,ib_sa
ib_core               106496  7 rdma_cm,ib_cm,ib_sa,iw_cm,ib_mad,ib_iser,ib_uverbs
ib_addr                20480  2 rdma_cm,ib_core

A: I've had the same problems when using the RDMA-core libraries for the ibverbs dependency. In the past I've managed to find a bug in mlx5_core.c (hardcoded the no of queues to 8 in the probe function and it magically worked), but I'm not sure it's the same issue for you.
Either way, the problem went away when I installed the latest Mellanox OFED Drivers, so it's a good idea to try that. Just remember to install it using the command:
mlnxofedinstall --dpdk --upstream-libs

edit: Just noticed you have the drivers installed - make sure you did the installation as above. One more thing you can do: check the output of this (compiled with -libverbs):
#include <infiniband/verbs.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main() {
        struct ibv_device ** devices;
        int num;
        struct ibv_context * ctx;
        devices = ibv_get_device_list(&num);
        int i;
        if(devices[0] == NULL)
                printf("devices is null\n");
        printf("got %d devices\n", num);
        for (i=0;i<num;i++) {
                printf(ibv_get_device_name(devices[i]));
                printf("\n");
                ctx = ibv_open_device(devices[i]);
                if (ctx == NULL)
                        printf("ctx is null \n");
                else
                        printf("device opened\n");
        }
        if (errno)
                printf("ERROR: %s\n", strerror(errno));
        ibv_free_device_list(devices);
return 0;
}

If it lists no devices at least you'll know it's an issue with the verbs drivers and not DPDK itself.


text:
Q: ASP .NET MVC with ADO .NET causing issues? I'm new to both ADO .NET and MVC, and I am trying to do something simple where I am editting a "DailyReport", which is basically representing a work-report.
Here's my relevant controller pattern:
    //
    // GET: /DailyReport/Edit/5

    public ActionResult Edit(int id, int weeklyReportID, int day)
    {

        WeeklyReport weeklyReport = (
                                      from WeeklyReport wr in db.WeeklyReports
                                      where wr.Id == weeklyReportID select wr)
                                      .FirstOrDefault();

        ViewBag.Week = weeklyReport.Week;
        ViewBag.Day = day;

        return View();
    }

    //
    // POST: /DailyReport/Edit/5

    [HttpPost]
    public ActionResult Edit(DailyReport dailyReport, int weeklyReportID, int day)
    {

        if (ModelState.IsValid)
        {

            db.SaveChanges();

            if (dailyReport == null)
            {

                dailyReport = new DailyReport();
                dailyReport.StartTime = new TimeSpan(7, 0, 0);
                dailyReport.EndTime = new TimeSpan(7 + 8, 0, 0);
                dailyReport.Day = day;

                db.DailyReports.AddObject(dailyReport);
                db.SaveChanges();

            }

            WeeklyReport weeklyReport = (
                                         from WeeklyReport wr in db.WeeklyReports
                                         where wr.Id == weeklyReportID select wr)
                                         .FirstOrDefault();

            if (!weeklyReport.DailyReport.Any(dr => dr.Id == dailyReport.Id))
            {
                weeklyReport.DailyReport.Add(dailyReport);
            }

            dailyReport.WeeklyReport = weeklyReport;

            db.SaveChanges();

            return RedirectToAction("Edit",
                                    "WeeklyReport",
                                     new {
                                           id = weeklyReportID,
                                           week = weeklyReport.Week,
                                           year = weeklyReport.Year
                                         });

        }

        return View(dailyReport);
    }

When I am editting the datetime value, it doesn't get saved. In the HttpPost section when I debug it, the object is indeed changed to reflect these changes, but calling db.SaveChanges() doesn't commit it to the database.
Edit "db" in this case is my ADO .NET context, declared in the following way:
    ActivesEntities db = new ActivesEntities();

ActivesEntities has this declaration:
    public partial class ActivesEntities : ObjectContext { ... }

A: First of all, I would recommend you to not call the db.SaveChanges until you really need to save an Entity object in the middle of the series of Transactional Steps..
Because Entity Framework support saving all the EntityContext object in a single shot !
And I think you may try changing the code like this,
[HttpPost]
public ActionResult Edit(DailyReport dailyReport, int weeklyReportID, int day)
{

    if (ModelState.IsValid)
    {

        if (dailyReport == null)
        {
            dailyReport = new DailyReport();
            dailyReport.StartTime = new TimeSpan(7, 0, 0);
            dailyReport.EndTime = new TimeSpan(7 + 8, 0, 0);
            dailyReport.Day = day;

            db.DailyReports.AddObject(dailyReport);
        }

        WeeklyReport weeklyReport = (from WeeklyReport wr in db.WeeklyReports where wr.Id == weeklyReportID select wr).SingleOrDefault();
        if (!weeklyReport.DailyReport.Any(dr => dr.Id == dailyReport.Id))
        {
            weeklyReport.DailyReport.Add(dailyReport);
        }

        dailyReport.WeeklyReport = weeklyReport;

        db.SaveChanges();

        return RedirectToAction("Edit", "WeeklyReport", new { id = weeklyReportID, week = weeklyReport.Week, year = weeklyReport.Year });

    }

I think using if you are Updating the entity object then you need to call SingleOrDefault and not FirstOrDefault. I do it like this on Linq2Sql..

A: you are using entity framework right? it's a bit different from ADO.NET (it uses it but those are not 100% same thing), we should add the tag EF to the question.
said so, why do you call db.SaveChanges twice? I would not call it at the top of your Edit method.
also, as I see in some EF examples, you can use Add and not AddObject.
check this one:
How to: Add, Modify, and Delete Objects
last thing, your StartTime and EndTime properties of the object are of type TimeSpan and not datetime?


text:
Q: Text in  different in Firefox Does anyone know of any fixes/workarounds for Firefox (3 and 4) handling text slightly differently than other browsers, specifically:

*

*Character-spacing (Firefox sometimes slightly wider with positive character-spacing defined in px)

*Non-splitting of hyphenated words (in, say, Safari, if "co-operate" appears at the end of a line it may be split into "co-" and "operate" ... but in Firefox it is not, and the whole word appears on a new line).
Not sure whether the two are related. Any tips? Thanks in advance.

A: You can use reset stylesheets (for example Eric Meyer's reset.css)
And for 2nd , you can check CSS's word-wrap attr.
Thereby, you can reset everything for every browser and set again as you want.

A: If you want to override the default browser setting for word-spacing, you can use the following in your main CSS file:
* { word-spacing:0px; }

Just note that not all browser support the wildcard. If you don't want to use a wildcard, you can use just a normal select:
div { word-spacing:0px; }

Word-spacing on W3Schools contains more information on word-spacing.
About your second problem, I am not getting the same symptom as you are. In Firefox 3.6.13 any word with a hyphen in it at the end of the line is breaking up in my computer.
Doesn't matter what the Word-wrap value is, Firefox in my computer will break the word up if necessary.


text:
Q: Social Engine Get Logged In User from custom php page I have seen and used the methods of obtaining the logged in user is for social engine pages.  I am wondering how can I pull the logged in user into a custom php page created outside the social engine network. I link to a few custom pages from my social engine site but want to tie into the existing Zend Frameworks session and grab those session variables.  Is this possible and how is it done?
Thanks
Shaun Roos

A: Ideally you should keep within SocialEngine and the Zend framework in order to access the session state etc. However you could possibly create an api or make a call to the database and select the sessions data for the user that is currently using the site. I'd store this externally in a cookie (perhaps the user's id encrypted in a format that allows you to decrypt it) then use the user_id in the cookie to select that data from the db.
Another way if you are on the same server and the same php instance is to use $_SESSION variables and store the required data in there and access it externally from your social engine installation.


text:
Q: Даны числа N и K, вычислите количество правильных K-ичных чисел, состоящих из N цифр Как решить указанную задачу?

Рассмотрим N-значные числа в системе счисления с основанием K. Будем
  считать число правильным, если его K-ичная запись не содержит двух
  подряд идущих нулей.
Например:

*

*1010230 — правильное 7-значное число;

*1000198 не является правильным числом;

*0001235 — не 7-значное, а 4-значное число.

  Даны числа N и K, вычислите количество правильных K-ичных чисел,
  состоящих из N цифр.
Ограничения: 2 ≤ K ≤ 10; N ≥ 2; N + K ≤ 18.

A: Пишу сразу идею нормального решения (идея, т.к. считаю что задачи с тимуса самим водить надо). Нормального это значит сразу в полных ограничениях а не урезанные версии (которые кстати и должны подвести к этому решению).

*

*Первая цифра нам по большому счёту совсем не нужна.

*Нам по большому счёту все равно какая цифра, главное 0 это или нет.

Решение этой задачи - сгенериуем маску 0/не 0. (2 ^ 16 вариантов в худшем случае). Дальше для каждой маски нужно к ответу добавить 9^(число 1 не маске). Не забудьте что первый элемент в маске всегда 1.

*Предположим мы расставили i цифр, для расстановки i+1 нам надо знать только значение i цифры, останые нам никак не мешают.

Решение более сложной задачи - динамика F[i][d] - число способов составить i первых цифр, чтобы последняя цифра была d (мы помним что нам важно только 0 там или нет). Пересчёт очевиден (с 0 только в 1 и k-1 способ, с 1 в 1 тоже k-1 и с 1 в 0 1 способ). База F[1][1] = K-1. Сложность O(N).
Дальше можно все это упаковать в формулу, вывести не сложно, формула сведется к быстрому возведению в степень и сложность падает до O( log N).


text:
Q: Tuple works with nullptr but doesnt with NULL I have the below code where std::tuple works with nullptr but not with NULL.
#include <iostream>
#include <tuple>

int main()
{
tuple<int*> t1, t2;

t1 = std::make_tuple(NULL);
t2 = std::make_tuple(nullptr);
}

When compiled with C++11, the code works when nullptr is used, but it gives the below error where NULL is used.
In file included from tuple.cpp:2:
/usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../../include/c++/5.4.0/tuple:447:8: error: assigning to 'int *' from incompatible type 'long'
            = std::forward<_UHead>(_Tuple_impl<_Idx, _UHead>::_M_head(__in));
              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../../include/c++/5.4.0/tuple:575:36: note: in instantiation of function template specialization 'std::_Tuple_impl<0, int *>::operator=<long>' requested here
          static_cast<_Inherited&>(*this) = std::move(__in);
                                          ^
tuple.cpp:13:8: note: in instantiation of function template specialization 'std::tuple<int *>::operator=<long, void>' requested here
    t1 = std::make_tuple(NULL);
       ^
1 error generated.

Here, the type of NULL is long int and the tuple is strict enough and doesn't accept it.
How can we make it work using NULL as well, as our client says it works when used with nvcc compiler (when they use the above snippet in the CUDA code), but its not working otherwise.

A:
How can we make it work using NULL as well

You can use either std::make_tuple<int*>(NULL) or simply std::tuple<int*>(NULL). But prefer using nullptr instead.
The problem that you face is the reason why nullptr was introduced to the language. Prior to its introduction, the only standard null pointer literal was 0 (also 0L etc. are valid), and that is what NULL expands1 to.
The problem is that 0 is not only a pointer literal, but also in fact an integer literal. And it is the integer nature of the literal that takes precedence in template type argument deduction and std::make_tuple(NULL) may result in std::tuple<int> or std::tuple<long> depending on exact definition of NULL. And those tuples aren't implicitly convertible to std::tuple<int*>.

1 Technically, now that nullptr is in the language, NULL could expand to that as well. But that's unlikely to happen.

A: One of the reasons why nullptr has its own type std::nullptr_t is that the literal 0 is special:

[conv.ptr]/1
A null pointer constant is an integer literal ([lex.icon]) with value zero or a prvalue of type std::nullptr_t.
  A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type ([basic.compound]) and is distinguishable from every other value of object pointer or function pointer type. [...]

You can convert 0 (or 0l) to any pointer type, but you can't convert 1 (or 1l) or any other integer to any pointer type (without an explicit cast, that is).
This works fine as long as you define NULL as a macro for the literal (#define NULL 0l) and use it directly in places where this conversion is necessary. But this makes perfect forwarding impossible: A function (such as std::make_tuple) taking T&& will deduce the type as long when passed NULL, losing the special properties of the 0 literal.
As a solution, nullptr was created and given its own type std::nullptr_t, with implicit conversions like those of the 0 literal. This means that perfect forwarding of nullptr (but not NULL) preserves this "specialness".
Bottom line: Use nullptr instead of NULL (or 0) if you want to use C++11 features (in particular perfect forwarding) like std::make_X.
There is no "making it work". In a standard-conforming compiler (see [support.types.nullptr]/2 and footnote) using NULL with make_tuple will result in this exact problem. Don't use NULL or don't use make_tuple, that's the only answer to your question.

A: It seems that the used compiler defines the macro NULL as a null-pointer constant 0L.
So in this statement
t1 = std::make_tuple(NULL);

the type of the right expression is std::tuple<long>.
Try to run the following demonstrative program
#include <iostream>
#include <iomanip>
#include <tuple>
#include <type_traits>

int main()
{
    auto t = std::make_tuple( NULL );

    std::cout << std::boolalpha
              << std::is_same<std::tuple<long>, decltype( t )>::value << '\n';

    return 0;
}

Its output is
true

So the deduced parameter type of the tuple is long.
In fact this statement
t1 = std::make_tuple(NULL);

semantically is equivalent to the following code
#include <iostream>

int main()
{
    int *p;
    long v = 0L;

    p = v;

    return 0;
}

the compiler can issue an error similar to this
prog.cpp:8:6: error: invalid conversion from 'long int' to 'int*' [-fpermissive]
  p = v;
      ^

You need explicitly to cast NULL to the type int *. For example
t1 = std::make_tuple( ( int * )NULL);

Though in any case it is better to use nullptr. It is the reason why the pointer literal nullptr was introduced in C++.
Then you are using the pointer literal nullptr then it is implicitly can be converted to the type int *. In this case the assignment is correct. Consider
#include <iostream>

int main()
{
    int *p;
    std::nullptr_t v = nullptr;

    p = v;

    return 0;
}

A: Is it mandatory that t1 and t2 are objects of the same type?
a) case YES
t2 = std::make_tuple(static_cast<int*>(NULL));

b) case NO
std::tuple<decltype(NULL)> t2;


text:
Q: Is there a way to create an exception in django 1.0 csrf protection? I know there is in the development version of Django, but I don't see this in Django 1.0. I took a look of the code and such an exception is definitely not built in. I need to have this ability as I can't add the csrf middleware token to a third party flash app I am using which needs to make a POST request back to django. :(
Anyone have any ideas?

A: The answer to this problem is simply recreate the token using the middleware and add it into the view and then making it accessible in the template for JavaScript/Flash.


text:
Q: Feedback model for two rails models I have two models - Customer and Contractors. I have setup a simple app, where they interact on an activity. Now at the end of it, I would like for them to leave each other feedbacks. Nothing complex just a database field of comment.
I am wondering what is the right model association to have here?
I tried this
class Customer
  has_many :feedbacks
end

class Contractor
  has_many :feedbacks
end

class Feedback
  belongs_to :customer
  belongs_to :contractor
end

But the problem here is identifying who commented who.
For instance, if I do
customer = Customer.find(1)
contractor = Contractor.find(1)
customer.feedbacks.create(:comment => "Contractor 1 sucks", :contractor_id => 1)

The problem is, its accessible by both contractor.feedbacks and customer.feedbacks. And I dont know who commented who now.
Any guidance is appreciated. Am i missing something?
Thanks

A: The way to do this would be to use polymorphic associations.
This way, you could have a commenter relationship, and a commentable relationship.
Like so:
class Customer
  has_many :feedbacks, as: commenter
  has_many :feedbacks, as: commentable
end

class Contractor
  has_many :feedbacks, as: commenter
  has_many :feedbacks, as: commentable
end

class Feedback
  belongs_to :commenter, polymorphic: true
  belongs_to :commentable, polymorphic: true
end

Now, Feedback will require four new columns:

*

*commentable_type:string

*commentable_id:integer

*commenter_type:string

*commenter_id:integer
All four should be indexed, so write your migrations appropriately. The type columns will store a String value of the model name associated ("Customer" or "Contractor").
So you can do things like:
  @feedback = Feedback.find 3
  @feedback.commenter
    => # Some Customer

  @feedback.commentable
    => # Some Contractor

And vise versa. You would build like:
@customer = Customer.find 1
@contractor = Contractor.find 1
@feedback = Feedback.new comment: "This is a great Contractor"
@feedback.commenter = @customer  # You can reverse this for a contractor giving feedback to a customer
@feedback.commentable = @contractor
@feedback.save!


text: Q: How to choose good pass and stop band frequency for my low pass filter? I have a noisy signal length of 512 points with sampling frequency 5 Hz. And my task is the pull out 0.2 Hz component form  main signal using LPF. How can i choose good pass and stop band frequencies? Is there any rule or requirements related to the input data for choosing that parameters?


text:
Q: How to solve concurrent read + write update to the document in MongoDB? I have an application that runs multiple instances and that needs to perform this:

*

*Read the document

*Check a value of the timestamp field

*If an incoming document is newer, then update (including the timestamp field).

Even if I use transactions, two parallel operations would be able to perform 1 and 2 simultaneously and then both will write to the database, potentially writing the "older" document last (since it will check the timestamp of the original document, rather than a "new" one)
So what I am looking for is some kind of a read lock on the document or some other mechanism that will be able to solve this.


text:
Q: Shared-Key Signature I know that most uses of cryptographic signatures are with public/private keys, but I need to sign information using a pre-shared key.
I know I can just encrypt the data, but I prefer signing it..
Is it possible in C#?

A: HMAC is the usual shared key signing algorithm, and it is doable in c#
How to generate HMAC-SHA1 in C#?

A: there are plenty of schemes (involving HMAC) to perform message signature with symmetric (pre-shared) key material.
possible duplicate:
Using symmetric key (AES -128) to sign and verify a message


text:
Q: Hibernate needs to fail in order to succeed next time I am writing two methods to re-initialize database in my application.
First should dynamically list all tables and then truncate them. Second one is responsible for data re-filling.
Truncate method uses native query:
public void truncate() throws Exception {
    List<String> names = getAllTableNames();

    names.forEach(tableName -> {
            entityManager.createNativeQuery("TRUNCATE TABLE " + tableName + " CASCADE").executeUpdate();
    });

//        entityManager.setFlushMode(FlushModeType.COMMIT);
//        entityManager.getEntityManagerFactory().getCache().evictAll();
        entityManager.flush();
}

Second method for data re-init just parses some documents, creates entities and saves them in bulk.
Both methods are located in service which is marked @Transactional.
I have two endpoints to be able to call them separately.
Now what happens is that after I truncate tables (ends without error) I call re-init and I get:
WARNING: org.springframework.dao.DataIntegrityViolationException: A different object with the same identifier value was already associated with the session : [com.nws.vedica.model.entity.DocType#ACCOUNTCONTRACTCANCEL]; nested exception is javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [com.nws.vedica.model.entity.DocType#ACCOUNTCONTRACTCANCEL]

as if the entities were still present in EM's cache.
the same happens after evicting after EM's cache (commented line).
Now two observations:
1.- the SECOND request to re-create entities is always successfull.
2.- re-create request is successful RIGHT AFTER truncate operation if I run re-create twice (first success, second fail) then truncate and then re-create. --very weired
Please guide me on what's happening and how to make this work properly.
Thanks!
EDIT:
I noticed that after calling
            truncateDatabaseSrv.truncate();

program hangs when I try to query collection:
        List<DocType> docTypes = docTypeDAO.getAllDocTypes();

so I put
        entityManager.createNativeQuery("COMMIT;").executeUpdate();

into the truncate method.
Now it won't hang and will return empty array as expected. But still when I call for the DocType collection re-init in the next request I get the same error as mentioned above.
Also I have noticed diry-checking is going on after truncate:
2:05:04,200 DEBUG AbstractFlushingEventListener:132 - Processing flush-time cascades
12:05:04,202 DEBUG AbstractFlushingEventListener:174 - Dirty checking collections
12:05:04,203 DEBUG Collections:189 - Collection found: [com.nws.vedica.model.entity.DocType.fieldValidities#ACCOUNTCONTRACTCANCEL], was: [com.nws.vedica.model.entity.DocType.fieldValidities#ACCOUNTCONTRACTCANCEL] (initialized)
12:05:04,203 DEBUG Collections:189 - Collection found: [com.nws.vedica.model.entity.DocType.keywords#ACCOUNTCONTRACTCANCEL], was: [com.nws.vedica.model.entity.DocType.keywords#ACCOUNTCONTRACTCANCEL] (initialized)
12:05:04,204 DEBUG Collections:189 - Collection found: [com.nws.vedica.model.entity.DocType.fieldValidities#ACCOUNTDEBTSLIENCONTRACT], was: [com.nws.vedica.model.entity.DocType.fieldValidities#ACCOUNTDEBTSLIENCONTRACT] (initialized)

that (initialized) seems suspicious to me, but that's all I have to this time...

A: I'm not sure how you're doing it so I'm making some assumptions here and suggesting something as how I did it.
I was using Spring/hibernate and my transactional annotations were present on both business methods on the spring bean. Something like this -
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class, isolation = Isolation.DEFAULT)

After 1st spring method is returned transaction is committed since it was container managed (not user managed which I believe is the case here). Then you go back to controller and call another method in the same Service.
If you don't want to go back to your controller then I'd suggest to have this annotation on your 2nd method and call it from 1st method (or however way you are managing your transactions) -
@Transactional(readOnly = false, propagation = *Propagation.REQUIRES_NEW*, rollbackFor = Exception.class, isolation = Isolation.DEFAULT)

I think this should work. Worth giving a try.


text:
Q: Weighting country-year based data I need to run a regression analysis using a data set on incidents of war. Data are collected on a country-year format, and go back hundreds of years.
My question is: some countries have gone to war only once, whereas others fought 10 or more. Under the circumstances, it feels wrong to run the analysis without any weights, as some countries will be over-represented.
Can appropriate weighting be a solution to this problem? If so, how should I apply the weights? Is it okay for a country that fought 10 times (and thus has 10 rows in the data set) to have a corresponding weight of 1/10 for each row? Accordingly, a country that fought 7 times would have a weight for 1/7 for each row, and so on. Is this the right approach?


text:
Q: Assign rendered value using javascript Folks,
below is my code,
<apex:inputtext value="{Account.Name}" rendered="True"/>

<apex:commandbutton>

am not using controller here, so i want to change the value to rendered="False" using javascript. is it possible to change rendered="False" using javascript?

A: Yes you can do it using java script. For you solution you can follow this post.


text:
Q: Stored Procedure in Oracle and IDataReader.Read() in VB.NET I have a Stored Procedure that seems to be very slow.
Executing it in Oracle SQL Developer;
SET TIMING ON;

DECLARE
  CUR_OUT UTILS.T_CURSOR;
  P_ARTTYID NUMBER;
  P_ORDERST VARCHAR2(200);
  P_DRUMNO VARCHAR2(200);
  P_SHIPPINGNO VARCHAR2(200);
  P_DELIVERYDATEFROM DATE;
BEGIN
  P_ARTTYID := 2;
  P_ORDERST := '3';
  P_DRUMNO := '611-480';
  P_SHIPPINGNO := NULL;
  P_DELIVERYDATEFROM := '2005-01-01';

  C_T_ORDER_GETOVERVIEW(
    CUR_OUT => CUR_OUT,
    P_ARTTYID => P_ARTTYID,
    P_ORDERST => P_ORDERST,
    P_DRUMNO => P_DRUMNO,
    P_SHIPPINGNO => P_SHIPPINGNO,
    P_DELIVERYDATEFROM => P_DELIVERYDATEFROM
  );

  --DBMS_OUTPUT.PUT_LINE('CUR_OUT = ' || CUR_OUT); -- Doesn´t work ;|
END;

Gives the "Statement output"
anonymous block completed
139ms elapsed

Now the problem is when I call it from my VB.NET application using
Microsoft.Practices.EnterpriseLibrary.Data.Database.ExecuteReader() that returns a System.Data.IDataReader and the following function to convert the IDataReader to a DataSet.
    Public Shared Function ConvertIDataReaderToDataSet(ByVal reader As IDataReader) As DataSet
        Dim schemaTable As DataTable = reader.GetSchemaTable()
        Dim dataTable As DataTable = New DataTable

        For intCounter As Integer = 0 To schemaTable.Rows.Count - 1
            Dim dataRow As DataRow = schemaTable.Rows(intCounter)
            Dim columnName As String = CType(dataRow("ColumnName"), String)
            Dim column As DataColumn = New DataColumn(columnName, CType(dataRow("DataType"), Type))
            dataTable.Columns.Add(column)
        Next

        Dim dataSet As DataSet = New DataSet
        dataSet.Tables.Add(dataTable)

        'dataSet.Load(reader, LoadOption.OverwriteChanges, dataTable) ' DEBUG
        While reader.Read()
            Dim dataRow As DataRow = dataTable.NewRow()
            For intCounter As Integer = 0 To reader.FieldCount - 1
                dataRow(intCounter) = reader.GetValue(intCounter)
            Next
            dataTable.Rows.Add(dataRow)
        End While

        Return dataSet
    End Function

Debugging and stepping through the function ends at the line for "While reader.Read()".
Also tried another version using DataSet.Load() but with the same result.
Found this thread on MSDN where others with the same problem seems to have solved it by tuning their queries by adding indexes.
How can I continue investigating the issue when it seems like the procedure works (responds within ~100 - 200ms) and the IDataReader.Read() just ends (or continues in the background?)

*

*Can I time the procedure in another (better) way?

*Can there be any table or transaction locks involved?

All advices are highly appreciated :)

A: Your test in SQL Developer is simply measuring the time required to open the cursor.  Opening the cursor does not cause Oracle to actually execute the query-- that does not happen until you fetch data from the cursor and each time you fetch, Oracle will continue processing the query to get the next set of rows.  Oracle does not, in general, need to execute the entire query at any point in time.  To be a comparable test, your PL/SQL block would need to fetch all the data from the cursor.  Something like
DECLARE
  CUR_OUT UTILS.T_CURSOR;
  P_ARTTYID NUMBER;
  P_ORDERST VARCHAR2(200);
  P_DRUMNO VARCHAR2(200);
  P_SHIPPINGNO VARCHAR2(200);
  P_DELIVERYDATEFROM DATE;
BEGIN
  P_ARTTYID := 2;
  P_ORDERST := '3';
  P_DRUMNO := '611-480';
  P_SHIPPINGNO := NULL;
  P_DELIVERYDATEFROM := '2005-01-01';

  C_T_ORDER_GETOVERVIEW(
    CUR_OUT => CUR_OUT,
    P_ARTTYID => P_ARTTYID,
    P_ORDERST => P_ORDERST,
    P_DRUMNO => P_DRUMNO,
    P_SHIPPINGNO => P_SHIPPINGNO,
    P_DELIVERYDATEFROM => P_DELIVERYDATEFROM
  );

  LOOP
    FETCH cur_out
     INTO <<list of variables to fetch data into>>;

    EXIT WHEN cur_out%notfound;
  END LOOP;

  --DBMS_OUTPUT.PUT_LINE('CUR_OUT = ' || CUR_OUT); -- Doesn´t work ;|
END;

Are you saying that in your .Net code, the reader.Read() line never returns?  Or are you saying your code aborts at that point?


text:
Q: how can I rewrite this line? In my code I have the following line:
something = next((s for s in something if s.rect.collidepoint(pygame.mouse.get_pos())), None)

My question is, how can I rewrite this sentence spreaded over a few lines, so it will make my code more clear ?

A: def next_something(something):
    for s in something:
        if s.rect.collidepoint(pygame.mouse.get_pos()):
            return s
    return None

something = next_something(something)

A: You could start by naming your variables more descriptively, and perhaps using an intermediate variable.
Even though I do it, too, I find it unreadable when a variable on the right-hand side has the same name as the variable on the left-hand side.
filtered_something = (s
                      for s in something
                      if s.rect.collidepoint(pygame.mouse.get_post())
first_something = next(filtered_something, None)

A: This is pep8 compatible
something = next((
    s for s in somethin
    if s.rect.collidepoint(pygame.mouse.get_pos())),
    None)


text:
Q: Why do we study Cameron-Martin Space and what is the motivation behind it? I'm reading about Gaussian Measures and the chapters always define the Cameron-Martin space shortly after.
Typically they'll define a covariance operator first.  Let $U$ be a separable Banach space, and $\mu$ be a centered Gaussian measure on $U$. $U^*$ is the dual.  The Covariance operator $C:U^*\times U^*\to\mathbb{R}$ is first given by
$$C_{\mu}(f)(g):= \int_Uf(x)g(x)\mu(dx)$$
First define $|x|_{H(\mu)} = \sup_{l\in U^*}\{ l(x) : C_{\mu}(l)(l)\leq 1\}.$  The Cameron-Martin space is then defined as $$H(\mu) := \{x \in U : |x|_{H(\mu)} < \infty \}.$$
(At least that's one of a couple definitions)
Intuitively, I've also heard that the Cameron-Martin space is the set of all elements that make the null sets of $\mu$ translation-invariant (ie you can shift a null-set by that element and it will still be a null set). But I still feel like I'm missing a broader perspective.

A: The infinite-finite dimension dichotomy , and Fourier coefficients
When we study (multivariate) normal random variables on $\mathbb R^d$, we often have equivalent ways of understanding them. One famous result is that any normal random variable can be specified by providing its mean and covariance matrix. While extending these concepts to infinite dimensions on separable Banach spaces, something analogous occurs : every Gaussian measure $\mu$ on $\mathcal{B}$ is determined by its "mean vector" (an element of $\mathcal{B}$) and a "covariance matrix" (a linear functional on $\mathcal{B}^* \times \mathcal{B}^*$). It is the "covariance matrix" that makes all the difference.
The proof goes via the "Fourier transform" and covers the finite dimensional case as well : let's assume that the mean vector is $0$ (one can easily carry over the argument to anywhere else) and suppose that the covariance operator is given by $C_{\mu}$.
One defines the Fourier transform of $\mu$, called $\hat{\mu} : \mathcal B^* \to \mathbb R$ by $$
\hat{\mu}(l) = \int_{\mathcal{B}}e^{il(x)}d\mu(x)
$$
Now, because $\mu$ is a Gaussian measure, it turns out that one can write $$
\hat{\mu}(l) = \exp\left(-\frac{1}{2} C_{\mu}(l,l)\right)
$$
[This in fact characterizes Gaussian measures on separable Banach spaces] Therefore, one sees that the map $\phi(l) = C_{\mu}(l,l)$ determines $\mu$, since it determines the Fourier transform of $\mu$ via the above formula, and Fourier transforms uniquely determine measures on separable Banach spaces.
The big difference, however, comes as follows. In finite dimensions, if $C_{\mu}$ is the covariance matrix of $\mu$, then the map $\phi$ is determined by the vectors $e_i^TC_{\mu}$ where $e_i$ are the standard basis vectors. But that's true of every other matrix as well : we didn't really use the fact that $C_{\mu}$ is special in any way ,we just used the fact that every finite matrix (and not just positive semidefinite ones) is determined by its rows. So knowing the map $\phi$ still reduces to knowing every single entry of $C_{\mu}$. To put it another way, you're using every possible bit of information you know about $C_{\mu}$, to determine $\mu$.
However, in infinite dimensions, $\phi(l)$ is determined by knowing the maps $l' \to \phi(l, l')$ from $B^*$ to $\mathbb R$ because these will give us the "rows" of $\phi$, hence a description of $C_{\mu}$. These maps belong to $B^{**}$ (linear functionals of $B^*$). It turns out, however, that because the speciality of $C_{\mu}$ counts for something in infinite dimensions, these maps in fact belong to $\mathcal{B}$ (i.e. they belong in the image of the map $\xi : \mathcal B \to \mathcal B^{**}$ given by $[\xi(x)](l) = l(x)$), and not just that : even as elements of $B$, they are very, very special.
That is, thanks to the special properties of $C_{\mu}$, not every element of $B$ comes from a map of the form $l' \to \phi(l, l')$. Only some of them do. A very , very small number of them. And YET, because of what we've said before, these very small number of elements determine $C_{\mu}$ and hence determine $\mu$.
Those elements, they form (i.e. are dense in a specific norm in) the Cameron-Martin space corresponding to $\mu$. A very small space, but a very powerful one, because the elements required to determine $\mu$ come from this space.

Definition and rigorous result

Definition : Given a Gaussian measure $\mu$ with covariance operator $C_{\mu} : \mathcal{B}^* \times \mathcal{B}^* \to \mathbb R$, we already saw that $\hat{C}_{\mu} \in B^{**}$ defined by $[\hat{C}_{\mu}(l)](l') = C_{\mu}(l,l')$ can be interpreted as an element of $B$. The closure of all such elements under the norm $\|h\|^2_{\mu} = C_{\mu}(h^*,h^*)$ (where $h^*\in B$ is any element such that $C_{\mu}(h^*,l) = l(h)$ for all $l \in B^*$) is called the Cameron-Martin space corresponding to $\mu$ and is denoted $\mathcal{H}_{\mu}$.

That is, given $\mu$, we collect all possible values in $B$ that the map $l' \to C_{\mu}(l,l')$ can correspond to, and close it under a norm corresponding to $\mu$. The closure is essentially done to ensure that the Cameron-Martin space obtains a Hilbert-space structure. Note that $\mathcal H_{\mu} \subset \mathcal{B}$ because of the relation $\|h\|_{\mu} \geq \|C_{\mu}\|^{-1} \|h\|^2$ for $h \in \mathcal B$, so the completion continues to have elements of finite $\mathcal B$ norm.
By making everything before a little more rigorous, we obtain the following result.

If $\mathcal B$ is a Banach space and $\mu,\nu$ are two Gaussian measures such that $\mathcal H_{\mu} = \mathcal H_{\nu}$ and $\|h\|_{\mu} = \|h\|_{\nu}$ for every $h \in \mathcal H_{\mu}$, then $\mu=\nu$ as measures on $\mathcal {B}$. In other words, a Gaussian measure is determined by its Cameron-Martin space and the norm on that space.

This is perhaps the most "broad" motivation for the Cameron-Martin space. How it ties in with the rest of the theory is also fascinating.

An equivalent description of $\mathcal {H}_{\mu}$
Recalling the Bochner integral, let $L^2(\mathcal B, \mu) = \{l : \int_{\mathcal B} (l(x))^2\mu(dx) < \infty\}$, where $l$ isn't an element of $B^*$, but instead is a $\mu$-a.e. equivalence class of functionals (i.e. $l_1 = l_2$ $\mu$-a.e. precisely when $l_1(x) \neq l_2(x)$ has $\mu$ measure zero).
While defining the CM space, we showed that every $h\in \mathcal H_{\mu}$ corresponded to some $h^* \in B^*$ in the way that $C_{\mu}(h^*,l) = l(h)$ for every $l\in B^*$. It's true that the map $h \to h^*$ is not unique. However, if we identify functionals up to $\mu$ a.e. equivalence, we have the following result.

$\mathcal H_{\mu}$ is isomorphic to the closure of $\mathcal{B}^*$ in $L^2(\mathcal{B},\mu)$. The latter space is called the reproducing kernel Hilbert space, or RKHS.

That is, the Cameron-Martin space can also be identified with the set of all ($\mu$ a.e. equivalence classes of) linear functionals $l$ such that knowing $C_{\mu}(l,l)$ is enough to determine $C_{\mu}$ completely.
The upshot of both the sections I've just written, is that one can associate to every Gaussian measure on a separable Banach space, another Hilbert space whose elements and their norms "capture" all possible entries of the covariance matrix $C_{\mu}$, thereby determining $C_{\mu}$. That space can either interpreted as a vector space in $\mathcal B$ under a different norm, or as a subspace of $L^2(\mathcal{B},\mu)$.
Another remarkable result which shows how important the Cameron Martin space is, lies in the pushforward of Gaussian measures. As Gaussian measures are determined by the Cameron-Martin space, one can specify how to push forward a Gaussian measure onto another Banach space, simply by specifying how the Cameron-Martin space is pushed forward under some linear map. The formal result is

Let $\mu$ be a Gaussian measure on $\mathcal B_1$ with CM space $\mathcal H_{\mu}$. Let $A : H_{\mu} \to \mathcal B_2$ be a bounded linear operator such that for some Gaussian measure $\nu$ on $\mathcal B_2$, it is true that $C_{\nu}(h,k) = \langle A^*h,A^*k\rangle_{\mu}$. Then, there exists a measurable map $\hat{A} : \mathcal B_1 \to \mathcal B_2$ such that $\nu$ is the pushforward of $\mu$ under $A^*$, $\hat{A} = A$ on $\mathcal H_{\mu}$, and $A$ is linear on a subspace of $\mu$-measure $1$. Furthermore, $\hat{A}$ is unique $\mu$ a.e.

That is, a linear map from the Cameron-Martin space that produces a covariance operator on the other Banach space, leads to a (unique) map which pushes forward the Gaussian measure. This is perhaps the broadest interpretation of the CM space : a space that is used not only to determine a Gaussian measure, but is used to push it forward onto other spaces.
Remember, the Hahn-Banach theorem tells you that there can be many, many possible extensions of a linear map $A$ on $\mathcal H_{\mu}$ to the domain $\mathcal B_1$. The Cameron-Martin space is so specially linked with $\mathcal B_1$, that defining how it transforms under a particular linear map is tantamount to saying how the entire Gaussian measure is pushed forward according to a particular extension of that map.
I hope I have provided a more "high-level" demonstration of how the CM space is linked very, very deeply with the underlying Gaussian measure. It is possible to deduce some other interesting properties of the CM space (including the Cameron-Martin theorem), but these are a little more specific compared to the above "by definition" exposition of the CM space.

A: As far as I know the reasoning goes as follows: a multivariate normal vector with non singular covariance matrix is absolutely continuous wrt to Lebesgue. If we translate this law we get a new law absolutely continuous to the original law.
This concept is then extented to the Brownian Motion by Girsanov Theorem. Through this we can prove the Cameron-Martin formula which tells us by translating  the Wiener measure $\mathcal{W}$ with a function $f \in D[0,T]$, we get a measure $\tilde{\mathcal{W}}$ absolutely continuous wrt $\mathcal{W}$. Here we have defined the following space: $D[0,T] := \{ f:[0,T] \to \mathbb{R}: \exists g \in L^2[0,T]: f(t) = \int_{0}^{t}g(s) ds, \quad \forall t \in [0,T] \}$.
Hence CM gives the infinite-dimensional counterpart of the Gaussian Measures.
Hope this helps.


text:
Q: How to load AngularJS content via jQueryUI AJAX? Our teams have inherited a jQuery Mobile project from another office and now we are trying to implement new features using AngularJS. The idea is also to migrate the whole jQuery website to AngularJS, step by step. Ideally, we would star the project from scratch in AngularJS, but that's not feasible for the time being.
The thing is, we have a jQuery tabs control which loads its tabs content via AJAX. All the current tabs are jQuery and we need to implement a new one, wrapping AngularJS code around it. But this is not working...
I've created a simple example to demonstrate the problem.
The live example can be found here:
http://ricardoamaral.net/jquery/
Click the "Ajax Loaded" tab and see for yourself that the Angular variable is not updated with the value defined in the Angular controller.
The following is code from the example above:
index.html
<!doctype html>

        <meta charset="utf-8">
        <title>jQuery UI Tabs</title>

        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">

Preloaded

Ajax Loaded

Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.

Script:

ajax.html

This content was loaded via ajax.

{{demoText}}

A: The problem you have importing templates with angular expressions is angular is not aware of the new content in DOM. Whenever you insert html from outside angular, you need to use $compile so that angular can process all expressions and directives ( including the ng-directives)`
Here's a very simple example of integrating jQueryyUI tabs into a directive to make your demo do what you expect
HTML

JS
app.directive('jqTabs', function($compile, $timeout) {
  return function(scope, elem, attrs) {
    elem.tabs({/* initalize UI tabs*/
      /* using jQueryUI tabs API, compile angular content in load event callback*/
      load: function(event, ui) {
        $timeout(function() {
          $compile($(ui.panel).contents())(scope)
        });
      }

    });
  }
})

DEMO


text:
Q: Lists not resetting after loop has been executed I am trying create a loop that resets all the data inside of it every iteration but somewhere the data is not resetting even though I am initializing values inside of the loop.
Here is my code:
import time , sys , string
import serial

ser = serial.Serial("/dev/ttyUSB0", baudrate=9600,
                   parity=serial.PARITY_NONE,
                   stopbits=serial.STOPBITS_ONE,
                   bytesize=serial.EIGHTBITS
                   )
print (ser.name)
ser.write(b'U')
#print ('test1')

time.sleep(2)

b=0
while (b <= 2):

    time.sleep(0.25)

    ser.write(b'R')
    #print ('test2')

    d = [] # establishes an empty list to iterate through all the incoming data
    i=0 # beginning of the buffer
    time.sleep(0.5)

    while (i<=11):
        d.append(str(ord(ser.read()))) #adding each incoming bit to the list
        #print (d[i])
        #print ('^ is the ' + str(i) + 'th term')  // these two lines help establish where the useful information begins for the lidar.

        i+=1

    #establishing a better way to write the data out / gd = good distance
    gd = []
    a = 0
    for a in range(8):
        gd.append(str(chr(int(d[a+4]))))
    print (gd)

    print (gd[0] + gd[1] + gd[2] + gd[3] + gd[4] + gd[5] + gd[6] + gd[7] + ' mm')

    ser.flush()
    b+=1

The reason i do d[a+4] is because the first few bits of information are nonsense so I need it to start from that bit every time.
The program works in the first loop and correctly prints it out, however, in subsequent loops it begins to start from different points when I try to print out the values again. I am unsure if I am missing something and would love a second opinion.
My outputs are:
D = 0609 mm
\r:\rD = 0 mm
mm \r:\rD mm

so it's looping around the lists I'm creating somewhere and since it's taking in the string from the print statement I wonder if that has something to do with the issue.

A: I cannot add a comment, so here is a little suggestion. At the end of your main loop, after
b+=1
add the following line
d, gd = [], []
if they are no longer useful after the loop has ended (which I suspect is the case). It'll reset any value the both variables hold in them and you'll be able to start from empty lists again.


text:
Q: Image calling from external server hangs IE6 I Have Table with multiple columns and rows,
Example,

   Head 1
   Head 2
   Head 3

   Data 1

      //Image is loaded from external URL.

   Data 3

Problem: This is working fine in all the browser but in IE6 browser hangs. My Table just having 10 records. (If I remove the image then working fine.)
Please some one give me some ideas on this issue.

A: It is a cross-browser issue. Have you tried to not close the img tag? I mean try this,

BTW, it should not matter, actually.


text:
Q: Any negatives using a Triac to transmit square wave? I want to use a TRIAC as a switch to open a gate to transfer a 9600 baud rate square wave (for a uart communication between two avrs).
Currently I'm using dc relay, but I'd like to use the Triac to reduce the power consumption and increase the components durability. But I'm not sure if the Triac will have any side effects.Please advice.Thx

A: Yes, I can think of a good alternative that is better than both a relay and a triac.
You seem to want to be able to select a unidirectional (slave to master) logic level bitstream.from 2 different sources. If you were to connect them together, you will get undefined results because of the output type (not open-drain).
You can use a number of different devices like transmission gates, discrete bipolars, and many other solutions but I suggest a digital switch (multiplexer/demultiplexer). Since you do not need linearity, these should exist in a standard logic catalog. Here are a few examples of analog multiplexers:

*

*TS5A9411 - 10 ohm SPDT up to 5 volts

*SN74LV4051A-Q1 - 1:8 MUX if you have 8 desired input sources

*Let's Go Shopping on Maxim-IC's site!

*Obligatory 74-series logic example
All of these options have multi-megahertz bandwidths so you should be good to at least 100kbaud

A: I assume (hope?) that your communication protocol ensures that the two clients don't transmit at the same time. If that were there case, there would be no way for the master to receive the sum of what the slaves are transmitting.
When one slave UART is transmitting and the other is not you want your master to receive the transmitted signal. Idem when the other slave is transmitting.
A UART output in the idle situation is high. Hence you can combine the two UART signals using an AND port. The very common 74HC00 chip contains 4 NANDs. You could use one to combine the signals, one to invert the output back, and leave two unused (but tie their inputs to gound or power).
PS a TRIAC is NOT a good component in this situation. A bit like a power grinder is not the right tool for cutting a birthday cake.


text:
Q: Android get Resource Identifier for a resource that doesn't belong to my app This is how we get a resource identifier for a drawable that belongs to our app
int resID = getResources().getIdentifier("resourceName",
"drawable", "myPackageName");

But how do we do it when the drawable is not ours?
1. It belongs to android

2. It belongs to another app (I'm guessing that this is done by just using the other app's package name)

A: This is my solution and it works for me..Assuming that the iconResName is in the form of: packageName+":drawable/"+drawableName;
I get the resources Id with the following function i wrote. And then we can use this resId to get the drawable.
public static int getResIdFromResEntryName(String iconResName,Context con){
  try{
    String packageName = iconResName.split(":")[0];
    Context otherAppContext = con.createPackageContext(packageName,Context.CONTEXT_INCLUDE_CODE|Context.CONTEXT_IGNORE_SECURITY);
    Resources resources = otherAppContext.getResources();
    int resId = resources.getIdentifier(iconResName, null, null);
    return resId;
  }catch(Exception e){return 0;}
}


text:
Q: iOS: What is the best way to display a lot of text in a UITextView? I have a lot of text in a UITextView, but because of this the App slows down and text don't even show up and the the App crashes. Is there an effective way to show a lot of text in a UITextView? Is there some alternative way to show all of this text? Any tips or suggestions is appreciated. The crash is just from memory leak.
The text has over 17000 characters.


text:
Q: How to get length of array for each row in pandas (python)? I've an json array with data like
[{
    'Id': 2837
    'Date': datetime.date(2020, 01, 01),
    'Caption': 'asdf'
}, {
    'Id': 2838
    'Date': datetime.date(2020, 01, 01),
    'Caption': 'fasd'
},{
    'Id': 2839
    'Date': datetime.date(2020, 01, 04),
    'Caption': 'sdfa'
}]

and a dataframe with a row for each date
  DATE       LEN
0 2020-01-01 NaN
1 2020-01-02 NaN
2 2020-01-03 NaN
3 2020-01-04 NaN
4 2020-01-05 NaN
5 2020-01-06 NaN

Now I would like to count the elements in the json array and write them into the dataframe. I tried
df['LEN'] = len([x for x in jsonArray if x['Date'] == df['DATE']])

but it's not working. I get an error
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
What am I doing wrong?

A: You can parse jsonArray into a dataframe and use groupby to count the rows for each date.
Sample data
import datetime

jsonArray = ([
    {'Id': 2837, 'Date': datetime.date(2020, 1, 1), 'Caption': 'asdf'},
    {'Id': 2838, 'Date': datetime.date(2020, 1, 1), 'Caption': 'fasd'},
    {'Id': 2839, 'Date': datetime.date(2020, 1, 4), 'Caption': 'sdfa'},
])
df_dates = pd.DataFrame({
    'DATE': pd.date_range('2020-01-01', '2020-01-06'),
    'LEN': float('nan')
})

The code
# parse jsonArray to dataframe
df = pd.DataFrame(jsonArray)

# count rows for each Date
df = df.groupby('Date').size().rename('LEN')

# set DATE to index so `df.update` can align
df_dates.set_index('DATE', inplace=True)
df_dates.update(df)

Output
            LEN
DATE
2020-01-01  2.0
2020-01-02  NaN
2020-01-03  NaN
2020-01-04  1.0
2020-01-05  NaN
2020-01-06  NaN

A: # necessary imports
import datetime
import pandas as pd

Lets say you have this list:
ourlist = \
[{
    'Id': 2837,
    'Date': datetime.date(2020, 1, 1),
    'Caption': 'asdf'
},{
    'Id': 2838,
    'Date': datetime.date(2020, 1, 1),
    'Caption': 'fasd'
},{
    'Id': 2839,
    'Date': datetime.date(2020, 1, 4),
    'Caption': 'sdfa'
}]

and a dataframe, for example:
df = pd.DataFrame([datetime.datetime(2020,1,1),
                   datetime.datetime(2020,1,2),
                   datetime.datetime(2020,1,3),
                   datetime.datetime(2020,1,4)],
                  columns=['DATE'])

Then you can do:
df['LEN'] = df['DATE'].apply(lambda datetimeobject: sum(datetimeobject == dates for dates in [eachdict['Date'] for eachdict in ourlist]))

or, more concisely, using How can I count the occurrences of a list item?:
df['LEN'] = df['DATE'].apply(lambda datetimeobject: [eachdict['Date'] for eachdict in ourlist].count(datetimeobject))

(In both cases, I am using a list comprehension to get the Date entries from ourlist, a list of dictionaries.)
Both of them will result in a df:
    DATE        LEN
0   2020-01-01  2
1   2020-01-02  0
2   2020-01-03  0
3   2020-01-04  1

A: You can do it easily with join and groupby
Code
df_json = pd.DataFrame(jsonArray)
df_json['Date'] = df_json['Date'].astype(str)

df = df.set_index('Date').join(df_json.set_index('Date'), how='left', on='Date')

grp_df = df.reset_index().groupby('Date', as_index=False)['Id'].count()
grp_df.rename(columns={'Id': 'Len'}, inplace=True)

Output
         Date  Len
0  2020-01-01    2
1  2020-01-02    0
2  2020-01-03    0
3  2020-01-04    1
4  2020-01-05    0
5  2020-01-06    0


text:
Q: CORDOVA BUILDING APP WARNING ABOUT ANDROIDX Im trying to build the cordova app in terminal and this one shows up.
[Gradle Properties] Detected Gradle property "android.useAndroidX" with the value of "true", Cordova's recommended value is "false"
[Gradle Properties] Detected Gradle property "android.enableJetifier" with the value of "true", Cordova's recommended value is "false"


text:
Q: How to subset a vector, based on the condition "contains" a character? If I have a vector:
Months = month.abb[1:12]

I want to extract all the months that start with Letter J (in this case, Jan, Jun, and Jul).

*

*Is there a wildcard character, like * in Excel, which lists all elements of vectors which you search for J*?

*How do I extract elements that start with either letter 'M' or 'A'. The expected output would be Mar,May,Apr,Aug?

A: Try:
 grep("^J", Months,value=TRUE)
 #[1] "Jan" "Jun" "Jul"

grep("^A|^M", Months,value=TRUE)
#[1] "Mar" "Apr" "May" "Aug"

A: You'll find the glob2rx function helpful for converting wildcard constructions to regular expressions:
> glob2rx("J*")
[1] "^J"
> grep(glob2rx("J*"), Months, value=TRUE)
[1] "Jan" "Jun" "Jul"

A: If you happen to have stringr loaded you could do:
library(stringr)

str_subset(Months, "^J")
[1] "Jan" "Jun" "Jul"


text:
Q: How to clock operations in iOS - Measure performance speed? I recently tried to answer a question here that was based on speed and required some way to measure how long various operations work.  I see people referring to speed of different coding methods occasionally and I was wondering, What is the best way to measure speed performance in Objective-C?
Here is what I've been using:
NSDate* operation = [NSDate date];

// Code you want to measure goes here

NSLog(@"Time: %f", -[operation timeIntervalSinceNow]);

Is this an acceptable, useful measurement, and are there better alternative methods?

A: Sure, that works. I tend to use NSTimeInterval variables, and the
-[NSDate timeIntervalSinceReferenceDate]
method, since that gives me a scalar constant that I can do math with directly (end time interval - start time interval = elapsed time)
That's only really useful if you have a specific block of code who's performance you want to measure. The Instruments tool lets you globally monitor the amount of time your program spends in different blocks of code, which is more generally useful. It lets you find the "bottlenecks" in your code, which help you find the best candidates for optimization.

A: Stephen Canon's answer (23 upvotes) in this thread How to log a method's execution time exactly in milliseconds? is more accurate.


text:
Q: How to get body of Cosmos DB Stored Procedure request? When querying my Cosmos DB Stored Procedure from Postman I get the following error and I don't understand why:
{
   "code": "BadRequest",
   "message": "Message: {\"Errors\":[\"Encountered exception while executing Javascript. Exception = TypeError: Object doesn't support property or method 'getBody'\\r\\nStack trace: TypeError: Object doesn't support property or method 'getBody'\\n   at storedProcedure (Test.js:7:9)\\n   at __docDbMain (Test.js:13:5)\\n   at Global code (Test.js:1:2)\"]}\r\nActivityId: f01827c0-4992-4560-bec1-e015b5678cf8, Request URI: /apps/ce1979d6-d776-4e39-bc44-85912cdd1c9f/services/95b9183f-4865-4ddb-933b-1869cb325207/partitions/b7168d10-e69f-4dae-87d8-91a07e5d6cfd/replicas/131638498361729976p/, RequestStats: , SDK: Microsoft.Azure.Documents.Common/1.20.0.0"
}

The SP I've created is really simple:
function storedProcedure(){

        var context = getContext();
        var response = context.getResponse();

        var item = context.getRequest().getBody();

        response.setBody(item);
}

It seems like the getRequest method is unable to find the request as other request methods (found here http://azure.github.io/azure-documentdb-js-server/) fail as well.

A: The body is available as the argument to the stored procedure. For example, if you change the definition to the following, you can get the case:
function storedProcedure(body){
    var context = getContext();
    var response = context.getResponse();
    response.setBody(body);
}


text:
Q: Find unique value from the array and sort the array I have one array. I want to find unique value of fk_section_id and other fields(section_name & fk_section_id) associated with it. I also want to sort this array by fk_section_id. How to get this array from the original one?
Array
 Array
(
[0] => Array
    (
        [fk_field_id] => 1
        [fk_section_id] => 1
        [section_order] => 1
        [field_order] => 1
        [field_name] => Title
        [section_name] => Your Detail
        [fk_field_type_id] => 4
    )

[1] => Array
    (
        [fk_field_id] => 2
        [fk_section_id] => 1
        [section_order] => 1
        [field_order] => 2
        [field_name] => Name
        [section_name] => Your Detail
        [fk_field_type_id] => 1
    )

[2] => Array
    (
        [fk_field_id] => 3
        [fk_section_id] => 2
        [section_order] => 2
        [field_order] => 1
        [field_name] => Road
        [section_name] => Address For Correspondence
        [fk_field_type_id] => 1
    )
)

Expected Output
  Array
(
[0] => Array
    (
        [fk_section_id] => 1
        [section_order] => 1
        [section_name] => Your Detail
    )

[1] => Array
    (
        [fk_section_id] => 2
        [section_order] => 2
        [section_name] => Address For Correspondence
    )
)

I tried below
 $i=0;
    foreach($formFields as $val){
        $i++;
        $allSections[$i]['section_name'] = $val['section_name'];
        $allSections[$i]['fk_section_id'] = $val['fk_section_id'];
        $allSections[$i]['section_order'] = $val['section_order'];
    }

And it gives
Array
(
[0] => Array
    (
        [section_name] => Your Detail
        [fk_section_id] => 1
        [section_order] => 1
    )

[1] => Array
    (
        [section_name] => Your Detail
        [fk_section_id] => 1
        [section_order] => 1
    )

[2] => Array
    (
        [section_name] => Address For Correspondence
        [fk_section_id] => 2
        [section_order] => 2
    )

)

A: You can try this:
$data = array(
    array(
        'fk_field_id' => 1,
        'fk_section_id' => 1,
        'section_order' => 1,
        'field_order' => 1,
        'field_name' => 'Title',
        'section_name' => 'Your Detail',
        'fk_field_type_id' => 4,
    ),
    array(
        'fk_field_id' => 2,
        'fk_section_id' => 1,
        'section_order' => 1,
        'field_order' => 2,
        'field_name' => 'Name',
        'section_name' => 'Your Detail',
        'fk_field_type_id' => 1,
    ),
);

$temp = array();

foreach($data as $key => $value) { //Make an new array using fk_field_id as key
    if (!in_array($value['fk_field_id'], $temp)) {
        $temp[$value['fk_field_id']] = $value;
    }
}
ksort($temp); //Sort the array by key

var_dump($temp);

Result:
array (size=2)
  1 =>
    array (size=7)
      'fk_field_id' => int 1
      'fk_section_id' => int 1
      'section_order' => int 1
      'field_order' => int 1
      'field_name' => string 'Title' (length=5)
      'section_name' => string 'Your Detail' (length=11)
      'fk_field_type_id' => int 4
  2 =>
    array (size=7)
      'fk_field_id' => int 2
      'fk_section_id' => int 1
      'section_order' => int 1
      'field_order' => int 2
      'field_name' => string 'Name' (length=4)
      'section_name' => string 'Your Detail' (length=11)
      'fk_field_type_id' => int 1

Also now you can use:
echo $temp[1]['field_name'];

Result:
Title


text:
Q: How to link to a tvOS app page on the Apple TV App Store I want to link to my own app or other apps store page from inside my app (for example to rate my app). Could be in a way this page is opened inside my app and not directly open the App Store app with app page (it is possible on iOS).
Can't find a way to do that. Methods that works on iOS doesn't work here apparently.
Tried:

*

*itms-apps://itunes.apple.com/app/id

*https://itunes.apple.com/app/id
I know it could be done because I saw apps on the App Store that does exactly that.


text:
Q: Brain Computer Interface Stack Exchange I have a suggestion to make a Brain Computer Interface Stack Exchange. What is the requirement to do that?

A: For suggesting sites, use Area 51 (read the FAQ to know how it works). First, do a search to check whether your proposal is already proposed. If that's not the case, then at the left sidebar, select the category for your proposed site (in this case, Technology). Scroll to the bottom and click "Propose a new Technology site", and fill in the form there to propose a site.


text:
Q: Laravel, Eloquent. Вывести из таблицы записи с определенным ключом (датой) Имеется база данных с датой, которая в формате 11/2020 (месяц/год). Мне необходимо выводить данные скажем от 09/2020 по 03/2022. Каким способом это можно реализовать? Eloquent отдельно, без Laravel. В другой формат даты переделать невозможно.

A: Например так:
$start = '12/2020';
$end = '03/2022';

Model::whereIn('date', datesArray($start, $end))->get();

function datesArray($start, $end): array
{
    $startDate = \Carbon\Carbon::parse(str_replace('/', '.', "01/$start"));
    $endDate = \Carbon\Carbon::parse(str_replace('/', '.', "01/$end"));

    $datesArray = [];
    for($startDate, $endDate; $startDate->lessThanOrEqualTo($endDate); $startDate->addMonth()) {
        $format = $startDate->format('m/Y');
        array_push($datesArray, $format);
    }
    return $datesArray;
}


text:
Q: Unable to perform scatter execution in python I am planning to use MPI scatter and gather for one of my requirement.
I have to include MPI scatter and gather in python to parse a json file and then scatter the data and use that to to filter out the required properties.
I have no issues in parsing the json.
if rank == 0 :
   for x in newData1:
        for j in range(size):
            result[j].append(x)
    data = result
    print(data)
else:
    data = None

chunks = comm.scatter(chunks, root=0)

newData is a list of dictionaries in python.
 cntr = fuction_name(chunks)

is the function call to manipulate the scattered data.
when I tried to print the scattered data I am getting below output:
rank 0
chunks 0
rank 1
chunks 1

Below is the error I get when I try to run my program

Traceback (most recent call last):
  File "mpi.py", line 192, in <module>
    cntr = function_name(chunks)
  File "mpi.py", line 60, in make_grid_list
    for i in range(len(data)):
TypeError: object of type 'int' has no len()
Traceback (most recent call last):
  File "mpi.py", line 192, in <module>
    cntr = function_name(chunks)
  File "mpi.py", line 60, in make_grid_list
    for i in range(len(data)):
TypeError: object of type 'int' has no len()


text:
Q: Pin-board effect with CSS Take a look at this fiddle
I want div 4 to be higher so it's closer to div 1, but with the margins intact, sort of like the Pinterest pin-board style layout, does anyone know how to do that?
HTML:

1
1

2

3

4

5

CSS:
div {
  display:inline-block;
  background-color:#CCC;
  float:left;
  width:200px;
  margin:10px 20px;
}

body { width:500px; }

Div 4 doesn't fit in snuggly like the rest. See the fiddle for details.
What I want is something like this link provided by j08691 in an answer below.

A: You can do something like the Pinterest layout in most current browsers using CSS multi-column layouts, it will break in IE9 and older versions.
Here's a jsFiddle. I have added some more div's for demonstration purposes.
html, body {
    height: 100%;
}
body {
    width: 420px;
    -webkit-column-count: 2;
    -webkit-column-gap: 20px;
    -moz-column-count: 2;
    -moz-column-gap: 20px;
    column-count: 2;
    column-gap: 20px;
    margin: 20px;
}
div {
    display: inline-block;
    background-color:#CCC;
    width:200px;
    margin-bottom: 20px;
}

The width of the body is set to 420px, that value is currently derived from twice the width of a div + the width of the column gap, you could play with this value and the column gap value to add more or less space between the columns of div's.
If you need to support older browsers, you could have a look at the Columnizer jQuery Plugin.

A: You can use JavaScript to accomplish this but it can't be done with CSS floats alone. A library like jQuery masonry will do it well. The reason? The specs on floats. In particular #5 which says, "The outer top of a floating box may not be higher than the outer top of any block or floated box generated by an element earlier in the source document.".

A: You can float every second div to the right:
div:nth-child(even) {
    float: right;
}


text:
Q: Cannot style a LineString I'm trying to style a LineString, but it doesn't seem to work. This is my code:
function connectStationFeatures(feat1, feat2){
    var lineLayer = getLinesLayer();
    var point1 = feat1.geometry;
    var point2 = feat2.geometry;
    var style = new OpenLayers.StyleMap({
        'fillColor':"#FF8C00",
        'strokeWidth':10,
        'strokeDashstyle':"dashdot"
    });
    var line = new OpenLayers.Geometry.LineString([point1, point2]);

    lineLayer.addFeatures([new OpenLayers.Feature.Vector(line, {styleMap:style})]);
}

Alternatively I tried:
function connectStationFeatures(feat1, feat2){
    var lineLayer = getLinesLayer();
    var point1 = feat1.geometry;
    var point2 = feat2.geometry;
    var style = new OpenLayers.StyleMap({
        'fillColor':"#FF8C00",
        'strokeWidth':10,
        'strokeDashstyle':"dashdot"
    });
    var line = new OpenLayers.Geometry.LineString([point1, point2]);
    var lineFeat = new OpenLayers.Feature.Vector(line);
    lineFeat.styleMap = style;
    lineLayer.addFeatures([lineFeat]);
 }

Any help is greately appreciated! THX

A: You have to add StyleMap to layer, not to feature
vectorLayer = new OpenLayers.Layer.Vector('Foo', {styleMap: style});

http://jsfiddle.net/HqQ6V/
There are several different ways to define style - with hash, Style or StyleMap objects; you can attatch them to feature or to layer. This is quite good explanation: http://docs.openlayers.org/library/feature_styling.html


text:
Q: Real Analysis, Folland Problem 5.3.32 The Baire Category Theorem
Problem 5.3.32 - Let $\lVert x \rVert_{1}$ and $\lVert x \rVert_{2}$ be norms on the vector space $\mathscr{X}$ such that $\lVert x \rVert_{1}\leq \lVert x \rVert_{2}$. If $\mathscr{X}$ is complete with respect to both norms, then the norms are equivalent.

I know that $0\in \mathscr{X}$ and also I know that the norms are equivalent if there exists a $C_1,C_2 > 0$ such that $$C_1\lVert x \rVert_{1} \leq \lVert x \rVert_{2} \leq C_2\lVert x \rVert_{1}$$ but I am not sure how to show this, any suggestions is greatly appreciated.

A: As you have said, you have to prove that there exist $C_1,C_2 > 0$ such that $$C_1\lVert x \rVert_{1} \leq \lVert x \rVert_{2} \leq C_2\lVert x \rVert_{1}$$
By hypothesis, we have
$$C_1\lVert x \rVert_{1} \leq \lVert x \rVert_{2}\tag{1},$$
where $C_1=1$. So, it's enough to prove that there exists $C_2 > 0$ such that $$\lVert x \rVert_{2} \leq C_2\lVert x \rVert_{1}$$
In other words, you have to prove that the mapping $F:(\mathscr{X},\|\cdot\|_1)\to (\mathscr{X},\|\cdot\|_2)$ given by $F(x)=x$ is continuous.
Note that the mapping $F$ is the inverse of the mapping $T:(\mathscr{X},\|\cdot\|_2)\to (\mathscr{X},\|\cdot\|_1)$ given by $T(x)=x$.
Because of $(1)$, $T$ is continuous. So, by Corollary 5.11 of Folland, $F$ is continuous as desired.


text:
Q: Two way data binding.. Display the objects in the component based on condition I am very new to LWC and javascript.I have a requirement as follows:
Declare array of object which represents employee (name,salary,position)
loop the employee array and display the employee information.
create input box to enter the salary amount.
display only the objects above the salary entered in the input box.
I tried like below code: but getting error. can anyone pls help
js
Employees=[
    {
        name: 'E1',
        salary: 20000,
        position: 'p1',
    },
    {
        name: 'E2',
        salary: 50000,
        position: 'p2',
    },
    {
        name: 'E3',
        salary: 100000,
        position: 'p3',
    },
    {
        name: 'E4',
        salary: 1000000,
        position: 'p4',
    },
    {
        name: 'E5',
        salary: 7000,
        position: 'p5',
    }

]
empsal
newArray=[]
empdetails(event){
    this.empsal=parseInt(event.target.value)
   this.newArray=this.Employees.filter((employee)=>employee.salary>this.empsal)
console.log(newArray)
}

html
<template>
<lightning-input label="Enter the salary" onchange={empdetails}></lightning-input>
{newArray}
</template>

A: *

*@track is the decorator that helps us to track a private property's value and re-render a component when it changes.

*Its helps us to achieve two-way data binding.

For more you can refer : https://developer.salesforce.com/docs/component-library/documentation/en/lwc/reference_decorators

A: The error was actually your console.log line. You forgot to include this, so it tried to access the top-level scope for newArray, which isn't defined, thus the error. You can fix that with:
console.log(this.newArray);

Note that your current code will show only [object Object], because of how toString works; you'll want to set up a table to see all the values.
Demo.