text:
Q: Algorithm for matching partially filled words I am writing a game which when given a partially filled word, searches a dictionary and returns all the matching words. To that effect, I am trying to find an algorithm that can be used for the said purpose. For example, given - - a -, the algorithm will search a dictionary for all the words which have length 4 and have 'a' as the third letter.
Is there such an algorithm already? If not, can somebody given a rough idea of how to design such an algorithm?
Thanks in Advance.

A: Well, it does not already exists, but it's been researched on SO already, for crosswords problems.
The gist of the solution I proposed was to index by letter and indexes, which is Python gives:
class Index:
  def __init__(self, list):
    self.data = defaultdict(set)
    for word in list: self.add(word)

  def add(self, word):
    for l in range(0, len(word)):
      self.data[(l, word[l])].insert(word)

  def look(self, letters):
    """letters is a list of tuples (position, letter)"""

    result = None
    for (p,l) in letters:
      set = self.data[(p,l)]
      if result == None: result = set
      else: result = result.insersection(set)

    return result

The idea is simple: you have a large index which has a set of words for each couple (position,letter). It could be extended, in your case, to have one index per word length, which would dimish the size of the sets of words and thus be faster.
For retrieval, you simply intersect all the sets to have the common set of word that matches all the known letters.

A: another solution could be to structure your dictionary as a prefix tree. Then your algorithm will just have to go trough that tree. For each node you know which letter is associated and the position in the word so you know if it matches the letter you are looking for. If it doesn't you stop and don't go through its children. You also know when you go over the length of your query. Each leaf you reach can be added to the results list.
This solution may be quite efficient as far as the memory consumption is concerned.

A: test = '--a-';

for each (words as word)
{
    if ((word.length == test.length)
        && (test.index(0) == '-' || (word.index(0) == test.index(0)))
        && (test.index(1) == '-' || (word.index(1) == test.index(1)))
        && (test.index(2) == '-' || (word.index(2) == test.index(2)))
        && (test.index(3) == '-' || (word.index(3) == test.index(3))))
    {
        // match
    }
}

Is that what you need? Obviously it needs modified a little to work for different lengths.

A: From what I understood,can't you use a regex query? in the example above the pattern is something like ??a?
Then you need to loop through all the words and check if there is a match.

A: If you're running on a reasonably powerful computer (compared to the load), then PierrOz has a good answer: store the dictionary as a prefix tree.  Then you can do a breadth-first search, pruning only when you reach a level where you actually know the letter.
If you need an even faster solution, you need a way of constraining your search depth.  One possibility is to bin the answers.  For example, you can start by grouping the words by length; then you only have to look through lists of words of a certain length.  Then you could subgroup by words containing specific letters--all letter pairs is probably enough.  This gives you an array of something like 13000 elements that you can rapidly index into: count the number of letters in your word, then pick the rarest letter or two in the word and use that to index into a mini-prefix-tree that only holds words of that length with those letter(s).  This strategy should get you down to a couple hundred words per bin in most cases, and the prefix tree search should be fast even if you pick out most of the breadth of the tree.


text:
Q: Flask how to redirect @login_required to specific route? I am building a small web application as a project and i am using the decorator @login_required at the moment it redirects to an unexisting route /login how can i manually set the route?
This is my code:
@auth.route('/logout', methods=['POST'])
@login_required
def logout():
    session.pop("user", None)
    return redirect(url_for('index'))

A: You didn't mention which library you were using, so I'm assuming it's a package that contains Flask Login. You can alter the login view by changing the config value for the login_manager.login_view as seen here

A: Use flask-login to handle user sessions.
(venv)$ pip3 install flask-login && pip3 freeze > requirements.txt

Add this package to your application instance. This is either the __init__.py file or the file that has:
from flask import Flask

app = Flask(__name__)

if __name__ == '__main__':
    app.run(host='0.0.0.0')

This is how you add it:
# __init__.py

from flask import Flask
from flask_login import LoginManager

app = Flask(__name__)

login = LoginManager(app)
login.login_view = 'login'

from app import routes

I have passed the login view function to the login object. This function is the one that handles user logins.
from app import app
from flask_login import login_required

@app.route('/')
@app.route('/index')
@login_required
def index():
    return render_template('index.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        # Your code
    return render_template('login.html', form=form)

I have passed the login_required decorator to the index() view function. Every time a user want to access the index page, they will be redirected to the login page for authentication, which is rendered by the login view function. After a successful login, only then will this person access the index page.
Feel free to pass the login_required decorator to any other function that can be anonymously accessed. I have seen that you are using blueprints. My example does not make use of blueprints, though it should be fairly easy for you to update the code to use your blueprints.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Formulas for the (top) coefficients of the characteristic polynomial of a matrix The characteristic polynomial of a matrix $A$ is defined as:
$$\chi(A) = \det(xI-A) = \sum_{i=0}^n (-1)^i\cdot \operatorname{tr}^{(i)}(A) \cdot x^{n-i}$$
The trace is the sum of the eigenvalues of a matrix, tr(A) = tr(1)(A).  It is also the sum of the diagonal entries:
$$\operatorname{tr}(A) = \sum_{i=1}^n A_{ii}$$
The sum of the products of pairs of eigenvalues is like the next trace.
Is this formula valid?
$$\operatorname{tr}^{(2)}(A) = \sum_{1 \leq i < j \leq n } A_{ii} A_{jj} - A_{ij} A_{ji}$$
What about this one?
$$\operatorname{tr}^{(2)}(A) = \tfrac12(\operatorname{tr}(A)^2 - \operatorname{tr}(A^2))$$
Are there corresponding formulas for the next one, tr(3)?

A: I thought I might add a bit on the background of what we are talking about.
Consider a vector space $V$ with a linear operator $A$, and lets choose a basis $e_i$.  Let $A\otimes A$ be the linear operator on $V\otimes V$ given by $A\otimes A (e_i\otimes e_j)=Ae_i\otimes Ae_j$.  It is easy to see that $tr(A\otimes A)=tr(A)^2$.
Let $\theta$ be the automorphism of $V\otimes V$ given by $\theta(e_i\otimes e_j)=e_j\otimes e_i$.  We can define $Sym^2(V)$, the Symmetric Square to be the set of all elements in $V\otimes V$ which are annihilated by $\theta -Id$, and $Alt^2(V)$, the Alternating Square, to be the set of all elements that are annihilated by $\theta + Id$.  Then, $V\otimes V$ decomposes into $Sym^2(V)\oplus Alt^2 (V)$ and what you are then looking for is the Trace of $A\otimes A$ when restricted to the alternating square.  (Note: restriction to an invariant subspace gives a linear operator, so we can take its Trace)
Why is this Trace the sum of $\lambda_i \lambda_j$?  First, the set of all $e_i\otimes e_j+e_j\otimes e_i$ is a basis for $Sym^2(V)$ and the set of all $e_i\otimes e_j - e_j\otimes e_i$ is a basis for $Alt^2(V)$.  To see this, write a vector in either subspace in the basis for $V\otimes V$ and consider the fact that it is annihilated by either $\theta +Id$ or $\theta -Id$.  Applying these operators gives and equation, and allows us to write the original vector in one of the bases I mentioned above.
Now lets do the case where $A$ is diagonalizable, and the $e_i$ above form an eigenbasis.  Then $$A\otimes A (e_i\otimes e_j - e_j\otimes e_i)= \lambda_i\lambda_j(e_i\otimes e_j - e_j\otimes e_i)$$  Hence $\lambda_i\lambda_j$ are exactly the eigenvalues of $A\otimes A$ when restricted to $Alt^2(V)$.
In more generality, the sum of the products of $n$ distinct eigenvalues will be the Trace of $A\otimes \cdots \otimes A$ restricted to the intersection of all subspaces annihilated by $\theta_\pi +Id$ where $\theta_\pi $ is some automorphism given by an odd permutation.  This subspace is sometimes called the Exterior Power.
Now, how do we actually calculate a formula for these Traces based on the original matrix $A$?  That is supplied in Qiaochu's Answer.

A: We want a "simple" formula for the coefficients of the characteristic polynomial in terms of the entries of the matrix, at least for the top few coefficients.
The characteristic polynomial can be written in terms of the eigenvalues:
$$
\chi(A) = (x-\lambda_1)(x-\lambda_2)\cdots(x-\lambda_n)
$$
$$= x^n - (\lambda_1 + \dots + \lambda_n) x^{(n-1)} + (\lambda_1 \lambda_2 + \lambda_1 \lambda_3 + \dots + \lambda_{n-1} \lambda_n) x^{(n-2)} - \dots + (-1)^n \lambda_1 \lambda_2 \cdots \lambda_n
$$
Each coefficient tr(k) is just (±) the sum of the product of all k-sets of the eigenvalues λi.  We'd like to use the regular trace to write this sum down, and so we try to find some crazy matrix Λ(k)(A) whose eigenvalues are exactly those products!
For k=1 this is easy: just use A itself.  For k=0, this is degenerate: just use [1].  For k=n, there is a sneaky trick: use [ det(A) ].  That is basically cheating, but it turns out to be part of a larger pattern.
To define B = Λ(k)(A) we consider all k-subsets K of {1,2,…,n} and use those to index the rows and columns of B.  For two such k-subsets K,L define the (K,L)th entry of B to be the determinant of the submatrix of A formed by taking only the rows from K and the columns from L.  In other words, B is the matrix formed of the k-minors of A.
For instance if K={i,j} and L={i,j}, then the (K,L)th entry is AiiAjj−AijAji.  The trace of this matrix is just the sum of the (K,K)th entries as K varies over all k-subsets of {1,2,…,n}.  For k=2, this is exactly the first formula given:
$$\operatorname{tr}^{(2)}(A) = tr(B) = \sum_{1 \leq i < j \leq n} A_{ii}A_{jj}-A_{ij}A_{ji}$$
Now for k=3, the formula is a little bit awful, but primarily because the formula for a 3×3 determinant is a little awful.
$$\operatorname{tr}^{(3)}(A) = tr(B) = \sum_{1\leq i<j<k \leq n} \left|\begin{array}{rrr}A_{ii} & A_{ij} & A_{ik} \\ A_{ji} & A_{jj} & A_{jk} \\ A_{ki} & A_{kj} & A_{kk} \end{array}\right|$$
$$= \sum_{1 \leq i < j < k \leq n} A_{ii}A_{jj}A_{kk}+A_{ij}A_{jk}A_{ki}+A_{ik}A_{ji}A_{kj}-A_{ik}A_{jj}A_{ki}-A_{ij}A_{ji}A_{kk}-A_{ii}A_{jk}A_{kj}$$

Now relating Eric Naslund's answer:
The Kronecker product of two matrices, M⊗N is another related construction.  Its rows are indexed by pairs (i1,i2) of row indices (i1 from M, and i2 from N), its columns are indexed by pairs (j1,j2) of column indices (j1 from M, and j2 from N), and the ((i1,i2),(j1,j2))th entry is just the the product of the (i1,j1)st entry of the first matrix with (i2,j2)nd entry of the second matrix.  In other words, one gets a block matrix where one the first matrix decides a common multiplier on the (i1,j1)st block, and the second matrix simply provides that block.
For instance
$$\begin{pmatrix} 0 & 1 \\ -1 & 0 \end{pmatrix} \otimes \begin{pmatrix} 5 & 6 & 7 \\ 8 & 9 & 10 \\ 11 & 12 & 13 \end{pmatrix} =
\left(\begin{array}{rrr|rrr}0&0&0&5&6&7\\0&0&0&8&9&10\\0&0&0&11&12&13\\\hline
-5 & -6 & -7 & 0&0&0 \\  -8 & -9 & -10 & 0&0&0 \\ -11&-12&-13&0&0&0 \end{array}\right)
$$
The Kronecker product has the nice feature that its eigenvalues are the products of eigenvalues, one from the first matrix and one from the second.  In particular, for A⊗A, one gets all products of eigenvalues, even λ1λ1 and both λ1λ2 and λ2λ1.
The Kronecker product of the two matrices acts on V⊗W, the vector space whose basis consists of pairs of basis vectors, one from V and one from W, and where M acts on V and N acts on W.
This vector space V⊗V is too large, it gives not only the products of 2-sets of eigenvalues, but also any ordered 2-tuple, including (1,1) and both (1,2) and (2,1).  However, there is a nice subspace called the exterior power which is the intersection of the kernels of all those coordinate switchers mentioned by Eric Naslund.  The matrix of A acting on the k'th exterior power Λ(k)(V) is just the matrix of k-minors, Λ(k)(A).
The eigenvalues divide up nicely in the second tensor power: the subspace spanned by x⊗x is called the symmetric power Sym2(V) and it gets one copy of each of the products λiλj for i ≤ j, including all of the repeats λiλi, so it has dimension n(n+1)/2.  The space spanned by all x⊗y−y⊗x is called the exterior power Alt2(V) and it gets the leftover eigenvalues, one copy each of the λiλj for i < j, so it has dimension n(n-1)/2.
For higher tensor powers the eigenvalues still have to be divided up, and one still has spaces Symk(V) and Altk(V)=Λ(k)(V), and these get their corresponding eigenvalues: all products of non-decreasing k-tuples of eigenvalues λi⋯λj with 1≤i≤…≤j≤n for Symk(V) and all products of increasing k-tuples (or just plain k-sets) of eigenvalues for Altk(V).  Weirdly though, that doesn't add up to the total dimension, and there still other subspaces left!  These are called Schur functors and apparently don't have too direct a relation on this question, but you can see they have to exist by looking at the third tensor power of a three dimensional space (a vector space of dimension 3×3×3=27): Sym3 has (1,1,1), (1,1,2), (1,2,2), (1,2,3), (1,3,3), (2,2,2), (2,2,3), (2,3,3), (3,3,3) for a total of 9.  Alt3 has only (1,2,3) for a total of 1.  Where did the other 17 dimensions go?  For instance, who got λ3λ2λ1?

A: Regarding your last question on $\text{tr}^{(3)}$, there is a kind of recursive definition for all $\text{tr}^{(k)}$ given by:
$$
\text{tr}^{(k)}=-(1/k)\left(\sum_{j=1}^k (-1)^{j} \text{Tr}(A^j)\text{tr}^{(k-j)}\right).
$$

A: The first guess is correct and follows directly from the permutation expansion of the determinant. The second guess is also correct. The generalization is
$$\text{tr}^{(n)}(A) = \text{tr } \Lambda^n(A) = \frac{1}{n!} \sum_{\pi \in S_n} \text{sgn}(\pi) \text{tr}_{\pi}(A)$$
where $\Lambda^n(A)$ is the action of $A$ on the exterior power $\Lambda^n$, $\text{tr}_n(A) = \text{tr}(A^n)$ and, for a permutation $\pi$ with cycle type $(\lambda_1, ... \lambda_k)$, we define $\text{tr}_{\pi} = \text{tr}_{\lambda_1} ... \text{tr}_{\lambda_k}$.
For example, $S_3$ has one element with cycle type $(1, 1, 1)$, three elements with cycle type $(1, 2)$, and two elements with cycle type $(3)$. It follows that
$$\text{tr}^{(3)}(A) = \frac{1}{6} \left( \text{tr}(A)^3 - 3 \text{tr}(A^2) \text{tr}(A) + 2 \text{tr}(A^3) \right).$$
This identity is really an identity of symmetric functions expressing the elementary symmetric functions in terms of the power symmetric functions. It can be deduced from Newton's identities or the exponential formula. You can find a more thorough exposition in Stanley's Enumerative Combinatorics, Vol. II, Chapter 7.

Some exposition is in order regarding what this has to do with exterior powers. Suppose that $A$ is diagonalizable with eigenvalues $\lambda_1, ... \lambda_n$ and eigenvectors $e_1, ... e_n$. Then of course $\text{tr}(A) = \sum \lambda_i$. More generally $\text{tr}^{(k)}(A) = \sum_{i_1 < ... < i_k} \lambda_{i_1} ... \lambda_{i_k}$ is the $k^{th}$ elementary symmetric polynomial in the eigenvalues.
Now, if $A$ acts on a vector space $V$, then the exterior power $\Lambda^k(V)$ inherits an action of $A$ by functoriality. In this basis, it is particularly easy to describe: it is given by
$$\Lambda^k(A)(e_{i_1} \wedge ... \wedge e_{i_k}) = \lambda_{i_1} ... \lambda_{i_k} e_{i_1} \wedge ... \wedge e_{i_k}.$$
Hence the wedges of all possible ordered $k$-tuples of distinct eigenvectors of $A$ forms an eigenbasis for $\Lambda^k(A)$ acting on $\Lambda^k(V)$. It follows that $\text{tr } \Lambda^k(A) = \text{tr}^{(k)}(A)$ for all diagonalizable $A$, hence for all $A$ by continuity. Of course you can ignore all of this if you want to, but I thought I would mention it because it is a precise sense in which the other coefficients of the characteristic polynomial encode "higher traces."


text:
Q: Please help me with table/nested JOIN optimization: Way too slow!

I have about 250 tables in my database, each with exactly 439340 rows.
mysql> SHOW CREATE TABLE data.b50d1 ;
+-------+--------------------------------------------------------------------------------------------
CREATE TABLE `b50d1` (
      `pTime` int(10) unsigned NOT NULL,
      `Slope` double NOT NULL,
      `STD` double NOT NULL,
      PRIMARY KEY (`pTime`),
      KEY `Slope` (`Slope`) USING BTREE
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 MIN_ROWS=43940 MAX_ROWS=43940 PACK_KEYS=1 ROW_FORMAT=FIXED |
+-------+--------------------------------------------------------------------------------------------

As you can see, there are three columns in each table:

*

*pTime: POSIX timestamp. This column (and all of its values) is exactly the same in each table. This is my PRIMARY KEY

*Slope

*STD
The columns Slope and STD have 'signed double' values that differ from row-to-row and from table-to-table.
Here is a small sample from one of the tables:
mysql> SELECT * FROM data.b50d1 limit 10;
+------------+------------+-------------+
| pTime      | Slope      | STD         |
+------------+------------+-------------+
| 1104537600 | 6.38733032 | -1.13387667 |
| 1104537900 | 5.58733032 | -0.93810617 |
| 1104538200 | 5.30135747 | -0.51912757 |
| 1104538500 |  5.4678733 | -0.54460575 |
| 1104538800 | 5.58190045 | -0.46369055 |
| 1104539100 | 5.50226244 | -0.46712018 |
| 1104714000 | 5.31221719 | -0.25210485 |
| 1104714300 | 4.72941176 |  0.00321249 |
| 1104714600 | 5.19638009 |  0.64116376 |
| 1104714900 | 5.12941176 |  0.39599099 |
+------------+------------+-------------+

Using these tables I run a stored procedure. This procedure consists of the following steps:
STEP 1) CREATE TEMPORARY TABLE MainList...
STEP 2) INSERT the results of a SELECT statement into the table. The resulting dataset is a filtered composite of the original tables.
STEP 3) SELECT statement with nested JOINs iterates through each MainList.STD value of the TEMPORARY table (MainList), and returns the first row from one of the original tables that matches certain specified conditions (example below).
STEP 4) JOIN the results to MainList and output them to the user.
The following is the procedure itself:
DELIMITER $$

CREATE DEFINER=`root`@`localhost` PROCEDURE `GetTimeList`(t1 varchar(7),t2 varchar(7),t3 varchar(7),inp1 float,inp2 float,inp3 float,inp4 float,inp5 float,inp6 float,inp7 float,inp8 float,inp9 float,inp10 float)
    READS SQL DATA
BEGIN
DROP TABLE IF EXISTS MainList;

CREATE TEMPORARY TABLE MainList(
  `pTime` int unsigned NOT NULL,
  `STD` double NOT NULL,
  PRIMARY KEY (`pTime`),
    KEY (`STD`) USING BTREE
    ) ENGINE = MEMORY;

SET @s = CONCAT('INSERT INTO MainList(pTime,STD)  SELECT DISTINCT t1.pTime, t1.STD FROM ',t1,' AS t1 JOIN (',t2,' as t2 ,',t3,' as t3 )',
' ON (( t1.Slope >= ', inp1,
' AND t1.Slope <= ', inp2,
' AND t1.STD  >= ', inp3,
' AND t1.STD  <= ', inp4,
' AND t2.Slope  >= ', inp5,
' AND t2.Slope  <= ', inp6,
' AND t3.Slope  >= ', inp7,
' AND t3.Slope  <= ', inp8,
' ) OR ( t1.Slope <= ', 0-inp1,
' AND t1.Slope >= ', 0-inp2,
' AND t1.STD  <= ', 0-inp3,
' AND t1.STD  >= ', 0-inp4,
' AND t2.Slope  <= ', 0-inp5,
' AND t2.Slope  >= ', 0-inp6,
' AND t3.Slope  <= ', 0-inp7,
' AND t3.Slope  >= ', 0-inp8,
' ) ) AND ((t1.Slope < 0 XOR t1.STD < 0) AND t1.pTime = t2.pTime AND t2.pTime = t3.pTime AND t1.pTime >= ', inp9,
' AND t1.pTime <= ', inp10,' ) ORDER BY t1.pTime'
);

PREPARE stmt FROM @s;
EXECUTE stmt;

SET @q= CONCAT('SELECT m.pTime as OpenTime, CASE WHEN m.STD < 0 THEN 1 ELSE -1 END As Type, mu.pTime As CloseTime from MainList m LEFT JOIN ',t1,' mu ON mu.pTime = ( SELECT DISTINCT md.pTime FROM ',t1,' md WHERE md.pTime>m.pTime',' AND md.pTime <= ', inp10,
                            ' AND SIGN (md.STD)!= SIGN (m.STD) AND ABS(md.STD) >= ABS(m.STD) ORDER BY md.pTime LIMIT 1 )');

PREPARE stmt FROM @q;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
DROP TABLE MainList;
END

For ease of testing I have broken up the above procedure into two individual queries. Here are those queries accompanied by 'EXPLAIN EXTENDED' statements (the temp table was generated beforehand) :
FIRST QUERY

INSERT INTO MainList(pTime,STD)
SELECT
  t1.pTime,
  t1.STD
 FROM
  b50d1 AS t1
 JOIN(b75d1 AS t2, b100d1 AS t3)ON(
  (
          t1.Slope >= 2.3169
          AND t1.Slope <= 7.0031
          AND t1.STD >= - 2.068
          AND t1.STD <= - 0.972
          AND t2.Slope >= 0.3179
          AND t2.Slope <= 5.7221
          AND t3.Slope >= 2.6466
          AND t3.Slope <= 35.7534
  )
  OR(
          t1.Slope <= - 2.3169
          AND t1.Slope >= - 7.0031
          AND t1.STD <= 2.068
          AND t1.STD >= 0.972
          AND t2.Slope <= - 0.3179
          AND t2.Slope >= - 5.7221
          AND t3.Slope <= - 2.6466
          AND t3.Slope >= - 35.7534
  )
 )
 AND(
  (t1.Slope < 0 XOR t1.STD < 0)
  AND t1.pTime = t2.pTime
  AND t2.pTime = t3.pTime
  AND t1.pTime >= 1104710000
  AND t1.pTime <= 1367700000
 )
 ORDER BY
  t1.pTime;

EXPLAIN EXTENDED:
+----+-------------+-------+--------+---------------+---------+---------+---------------+--------+----------+-----------------------------+
| id | select_type | table | type   | possible_keys | key     | key_len | ref           | rows   | filtered | Extra                       |
+----+-------------+-------+--------+---------------+---------+---------+---------------+--------+----------+-----------------------------+
|  1 | SIMPLE      | t1    | ALL    | PRIMARY,Slope | NULL    | NULL    | NULL          | 439340 |    25.79 | Using where; Using filesort |
|  1 | SIMPLE      | t2    | eq_ref | PRIMARY,Slope | PRIMARY | 4       | data.t1.pTime |      1 |   100.00 | Using where                 |
|  1 | SIMPLE      | t3    | eq_ref | PRIMARY       | PRIMARY | 4       | data.t1.pTime |      1 |   100.00 | Using where                 |
+----+-------------+-------+--------+---------------+---------+---------+---------------+--------+----------+-----------------------------+

SECOND QUERY

SELECT
    m.pTime AS OpenTime,
    CASE WHEN m.STD < 0 THEN 1 ELSE - 1 END AS Type,
  mu.pTime AS CloseTime;
FROM
    MainList m
LEFT JOIN b50d1 mu ON mu.pTime =(
    SELECT DISTINCT
        md.pTime
    FROM
        b50d1 md
    WHERE
        md.pTime > m.pTime
    AND md.pTime <= 1367700000
    AND SIGN(md.STD)!= SIGN(m.STD)
    AND ABS(md.STD)>= ABS(m.STD)
    ORDER BY
        md.pTime
    LIMIT 1
);

EXPLAIN EXTENDED:
+----+--------------------+-------+--------+---------------+---------+---------+------+--------+----------+-------------+
| id | select_type        | table | type   | possible_keys | key     | key_len | ref  | rows   | filtered | Extra       |
+----+--------------------+-------+--------+---------------+---------+---------+------+--------+----------+-------------+
|  1 | PRIMARY            | m     | ALL    | NULL          | NULL    | NULL    | NULL |     16 |   100.00 |             |
|  1 | PRIMARY            | mu    | eq_ref | PRIMARY       | PRIMARY | 4       | func |      1 |   100.00 | Using index |
|  2 | DEPENDENT SUBQUERY | md    | range  | PRIMARY       | PRIMARY | 4       | NULL | 439338 |   100.00 | Using where |
+----+--------------------+-------+--------+---------------+---------+---------+------+--------+----------+-------------+

The query works and returns the right results, but it is orders of magnitude slower than what I need. I recognize that the type: ALL statement present in both EXPLAIN statements indicates that my indices are likely suboptimal.
I have only used MYSQL for the past week, and I am starting to feel like I am in over my head. I would really appreciate some help.
I made a SQL file with CREATE TABLE and INSERT statements so that anyone kind enough to try to help me could create smaller versions of my tables in the"Test" database:
slowtables.SQL
For completeness here is the my.ini settings file - perhaps it is a bottleneck?
[client]
pipe
socket=mysql
[mysql]
default-character-set=latin1
[mysqld]
skip-networking
enable-named-pipe
socket=mysql
basedir="C:/Program Files/MySQL/MySQL Server 5.5/"
datadir="C:/ProgramData/MySQL/MySQL Server 5.5/Data/"
character-set-server=latin1
default-storage-engine=MYISAM
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
max_connections=100
query_cache_size=189M
table_cache=256
tmp_table_size=192M
key_buffer_size=594M
read_buffer_size=64K
read_rnd_buffer_size=256K
sort_buffer_size=256K

A: Trying to work with your first query sample, and all tables have ... as you mentioned ... the exact same "pTime" value, I might alter the query to the following...  I don't know for sure if the math XOR is faster than a direct multiplication of the slope * STD.  If only ONE of them can be negative, the only result WOULD be a negative as two negatives = positive (so too are two positives)...
However, I've moved the WHERE clause up-front to explicitly qualify the query time range first even before it tries to complete the joining to tables 2 and 3...
I wasn't sure about the multiplication vs the XOR call, but I'll bet that did have a factor in the longer time.  Additionally, trying to pre-emptively use an ABS() check on the slope too.  That being said, I would do it as a UNION since slope too is key on the table, utilize it as exact part of the key and NOT via an evaluated function in ABS().  I can do a UNION ALL since one criteria is checking for slope negative and the other where positive, each unique SQL will never include the other's result set.  Additionally, we can throw out the XOR check since the rest of your AND clauses are explicitly qualifying slope as opposite sign of the std.
THEN, tack on your other considerations of slope and std
INSERT INTO MainList(pTime,STD)
SELECT STRAIGHT_JOIN
      t1.pTime,
      t1.STD
   FROM
      b50d1 AS t1
         JOIN b75d1 AS t2
            ON t1.pTime = t2.pTime
         JOIN b100d1 AS t3
            ON t1.pTime = t3.pTime
   where
          t1.pTime >= 1104710000
      AND t1.pTime <= 1367700000
      AND t1.Slope >= 2.3169
      AND t1.Slope <= 7.0031
      AND t1.STD >= - 2.068
      AND t1.STD <= - 0.972
      AND t2.Slope >= 0.3179
      AND t2.Slope <= 5.7221
      AND t3.Slope >= 2.6466
      AND t3.Slope <= 35.7534
   ORDER BY
      t1.pTime
UNION ALL
SELECT STRAIGHT_JOIN
      t1.pTime,
      t1.STD
   FROM
      b50d1 AS t1
         JOIN b75d1 AS t2
            ON t1.pTime = t2.pTime
         JOIN b100d1 AS t3
            ON t1.pTime = t3.pTime
   where
          t1.pTime >= 1104710000
      AND t1.pTime <= 1367700000
      AND t1.Slope >= - 7.0031
      AND t1.Slope <= - 2.3169
      AND t1.STD >=  0.972
      AND t1.STD <=  2.068
      AND t2.Slope >= - 5.7221
      AND t2.Slope <= - 0.3179
      AND t3.Slope >= - 35.7534
      AND t3.Slope <= - 2.6466;

A THIRD version would be to pre-query for the qualifying entries, then continue to rest of the join... (inner, building "PQ" PreQuery resultset)
INSERT INTO MainList(pTime,STD)
SELECT STRAIGHT_JOIN
      pq.pTime,
      pq.STD
   FROM
      ( select
              t1.pTime,
              t1.slope,
              t1.std
           from
              b50d1 t1
           where
                  t1.pTime >= 1104710000
              AND t1.pTime <= 1367700000
              AND (( t1.slope between 2.3169 and 7.0031
                    AND t1.std between -2.068 and -.972 )
                  OR
                   ( t1.slope between -7.0031 and -2.3169
                    AND t1.std between .972 and 2.068 )) ) PQ
         JOIN b75d1 AS t2
            ON p1.pTime = t2.pTime
         JOIN b100d1 AS t3
            ON p1.pTime = t3.pTime
   where
          (     pq.slope > 0
            AND t2.Slope >= 0.3179
            AND t2.Slope <= 5.7221
            AND t3.Slope >= 2.6466
            AND t3.Slope <= 35.7534
          )
       OR
          (     pq.slope > 0
            AND t2.Slope >= -5.7221
            AND t2.Slope <= -0.3179
            AND t3.Slope >= -35.7534
            AND t3.Slope <= -2.6466
          )
   ORDER BY
      t1.pTime

A: I see two improvements possible here that have more to do with MySQL's optimizer (or weakness thereof). In the second query, the DISTINCT in the subquery is redundant given the LIMIT 1. A ORDER BY  LIMIT 1 query should be done by searching the index until a record matching the other criteria is found. (Do you really need a LEFT JOIN??)
In the first query, MySQL is apparently unable to optimize an OR into a UNION. However, if you do that by hand, it may choose much better plans for the two halves of the UNION query.
HTH. I can look again later.


text:
Q: Next.js build command gets stuck sometimes in Ubuntu 20.04 AWS When I run next build in my server, it gets stuck here, and the website also crashes and turns into a 504 Gateway Timeout error:
info  - Loaded env from /home/ubuntu/MYPROJECT/.env
info  - Using webpack 4. Reason: future.webpack5 option not enabled https://nextjs.org/docs/messages/webpack5
info  - Checking validity of types
info  - Using external babel configuration from /home/ubuntu/MYPROJECT/.babelrc
info  - Creating an optimized production build..

This does not happen all the time, maybe 1 time every 5 to 10 deployments.
I then have to stop and start the EC2 instance. Right after the build command always runs very quick. Which could mean I have memory issues in the server? How could I resolve this?
I have a t2.micro instance with 8GB of storage.
Usage of /:   76.2% of 7.69GB
Memory usage: 50%

Could be that upgrading resolves this issue?


text:
Q: Problem with fscanf not reading inputs correctly I'm having problems using a fscanf function. It never reads it correctly and always results in blanks.
fscanf(f, " %[^;];%[^;];%d;%d;%d;%d;%[^;];%d;%[^\n]",
            arr[i].loc1, arr[i].loc2, &arr[i].price, &arr[i].rooms,
            &arr[i].bathroom, &arr[i].carpark, arr[i].type, &arr[i].area, arr[i].furnish);

The code above always outputs "  0 0 0 0  0". But when I try using a scanf and manually input one of the lines, it works perfectly.
The file it's reading from is a .csv file. Here is the contents:
Mont-Kiara;Kuala-Lumpur;1000000;2;2;0;Built-up;1000;Partly

Cheras;Kuala-Lumpur;310000;3;2;0;Built-up;1000;Partly

Kepong;Kuala-Lumpur;358000;3;3;0;Built-up;1000;Partly

Taman-Desa;Kuala-Lumpur;455000;2;2;0;Built-up;1000;Partly

Kepong;Kuala-Lumpur;358000;3;3;0;Built-up;1000;Partly

Kepong;Kuala-Lumpur;358000;3;3;0;Built-up;1000;Partly

And here is the full code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct houseData {

    char loc1[101];
    char loc2[101];
    int price[101];
    int rooms[101];
    int bathroom[101];
    int carpark[101];
    char type[101];
    int area[101];
    char furnish[101];

} arr[1001];

int read() {

    int i = 0;
    struct houseData arr[800];
    char temp1[100];

    FILE *f = fopen("file.csv", "r");

    while(!feof(f)){

        fscanf(f, " %[^;];%[^;];%d;%d;%d;%d;%[^;];%d;%[^\n]"
        , &arr[i].loc1, &arr[i].loc2, &arr[i].price, &arr[i].rooms,
        &arr[i].bathroom, &arr[i].carpark, &arr[i].type, &arr[i].area, &arr[i].furnish);
        i++;
    }

    fclose(f);
}

int main() {

    read();

    printf("%s %s %d %d %d %d %s %d %s", arr[i].loc1, arr[i].loc2, *arr[i].price, *arr[i].rooms, *arr[i].bathroom, *arr[i].carpark, arr[i].type, *arr[i].area, arr[i].furnish);

    return 0;
}

A: There are a lot of issues in your code.  Here's a version that may help.  The error messages in this version are far from ideal (this does not distinguish between an input format error and a error reading data, for example, nor does it provide much detail on the location of the error), and there is still the possibility of undefined behavior on certain inputs, (see Is `scanf("%d", ...)` as bad as `gets`?) but this should point you in the right direction.  Well, at least it may help to improve your use of scanf, but a very reasonable argument can the be made that the "right direction" is to stop using scanf completely.  It is very difficult to get things right with scanf, and attempting to do so winds up being much more complex that just using fgets.  But for simple use cases it is ... still pointless to use scanf.  See http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html and many other resources that explain why scanf is a terrible choice.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct houseData{
        char loc1[101];
        char loc2[101];
        int price;
        int rooms;
        int bathroom;
        int carpark;
        char type[101];
        int area;
        char furnish[101];
};

int
read(FILE * f, struct houseData *h)
{
        return 9 == fscanf(f, " %100[^;]; %100[^;]; %d; %d; %d; %d; "
                "%100[^;]; %d; %100[^\n]", h->loc1, h->loc2, &h->price,
                 &h->rooms, &h->bathroom, &h->carpark, h->type, &h->area,
                 h->furnish);
}

int
main(int argc, char **argv)
{
        int rv;
        FILE *f = argc > 1 ? fopen(argv[1], "r") : stdin;
        if( f == NULL ){
                perror(argv[1]);
                return EXIT_FAILURE;
        }
        struct houseData h;
        int i = 0;
        while( read(f, &h) ){
                printf("%d: %s %s %d %d %d %d %s %d %s\n", ++i,
                         h.loc1, h.loc2, h.price, h.rooms, h.bathroom,
                         h.carpark, h.type, h.area, h.furnish);
        }
        if( ! feof(f) ){
                fprintf(stderr, "Error near line %d\n", i);
        }
        fclose(f);
}


text:
Q: Can't connect to port 80 on localhost I fire up sudo nc -l 127.0.0.1 80. There's no errors.  I then try telnet 127.0.0.1 80. It won't connect.
Same thing with port 81 works fine.
As far as I know, there's no firewalls running.
https://img.skitch.com/20120228-t8h98sccsde3w1jnf2tb55xdny.png shows the commands I'm using. (the numbers are the order in which the commands are run)
I'm on OS X 10.7.3.

A: FINALLY figured it out.  I had installed Pow (http://pow.cx). It runs this script: http://get.pow.cx. The script installs some firewall rules. Even though I had disabled pow, the firewall rules were still in place. Running the pow uninstall script fixed it.

A: I have several suggestions.  First, check to make sure the packet filter firewall is off.  Here's an example on my Mac, with the firewalls off:
$ sysctl net.inet.ip.fw.enable
net.inet.ip.fw.enable: 1
$ sudo ipfw show
Password:
65535 0 0 allow ip from any to any

The sysctl command shows the firewall is actually enabled, but the second shows that its rules allow all traffic.  The symptoms aren't consistent with the application firewall, but check it anyway just to be sure:
$ defaults read /Library/Preferences/com.apple.alf globalstate
0

Here 0 means off, 1 means on, and 2 means "Block all incoming connections" mode.  If neither of those shows an active firewall, the next things I'd do is run tcpdump to see what's going on between telnet and nc.  Here's a successful connection:
$ sudo tcpdump -ilo0 port 80
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on lo0, link-type NULL (BSD loopback), capture size 65535 bytes
20:35:28.193217 IP localhost.49531 > localhost.http: Flags [S], seq 1937962870, win 65535, options [mss 16344,nop,wscale 3,nop,nop,TS val 7494959 ecr 0,sackOK,eol], length 0
20:35:28.193286 IP localhost.http > localhost.49531: Flags [S.], seq 1740947472, ack 1937962871, win 65535, options [mss 16344,nop,wscale 3,nop,nop,TS val 7494959 ecr 7494959,sackOK,eol], length 0
20:35:28.193298 IP localhost.49531 > localhost.http: Flags [.], ack 1, win 65535, options [nop,nop,TS val 7494959 ecr 7494959], length 0
20:35:28.193307 IP localhost.http > localhost.49531: Flags [.], ack 1, win 65535, options [nop,nop,TS val 7494959 ecr 7494959], length 0

This obviously won't solve the problem, but might give a good clue what's going on.

A: Without nc listening, does netstat -an show anything listening to tcp on port 80?
Do you have "Web Sharing" enabled under System Preferences -> Sharing?  That runs Apache...

A: I've had this problem before, with an older version of Skype, that also uses port 80. To start Apache, i had to stop Skype, start Apache, then restart Skype. Seems to be fine in more recent versions though.


text:
Q: Azure Bicep - Best practice with regards to noisy what-if output I am creating a deployment on Azure from scratch consisting of various resources, e.g., Application Gateway, AKS cluster, Managed Identities. When checking az what-if after deploying, I can see some unexpected noise. I know that the team is working on eliminating as much noise as they can from the what-if output, but what is good practice with regards to this in the mean time?

*

*replicate the changes in the template, such that they don't appear?

*keep track of the previous 'what-if' output, then compare with the next one to see what actually changed?

*deploy in stages, such that the noisy part can be separated from the clean part?

*...

I spotted various types of noise, easy or difficult to deal with:

*

*default properties that were not specified in the template. For example, properties.networkProfile.ipFamilies == 'IPv4 for a managedCluster. I could add this in the template to make it more complete, which would eliminate the noise.

*external influences such as vnet peerings made by external parties. When outside parties peer with my vnet, it changes its definition too, which then pops up as noise (properties.virtualNetworkPeerings). When re-applying, as far as I understood, it fortunately doesn't eliminate these peerings. However, it would be nice to know when it doesn't overwrite such changes. Is this described somewhere?

*references such as properties.principalId:   "a09185a3d" => "[reference(resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', parameters('test-mi')), '2018-11-30').principalId]". I've seen this described as a bug/issue on the tracker, yet to be resolved.

*bidirectional information (don't have an example at hand), like allowing a resource access to the vnet, which would modify the vnet but would also show a reference to the vnet in the resource. This is superfluous information, and adding it to the template to make sure the what-if remains clean seems wrong.

So, generally speaking, I'm looking for some tips and tricks to get the cleanest workflow possible. Having proper feedback on the upcoming changes on a template is crucial to prevent mistakes.


text:
Q: PHP - can't add objects into array I've created a simple class:
class Event {

   var $a;
   var $b;
   var $c;

   function __construct($a, $b, $c)
   {
      $this->a= $a;
      $this->b = $b;
      $this->c= $c;
   }

  }

Then I've created another class which extends Thread:
class WorkerThread extends Thread
{
    private $myUrl;
    private $eventsArr;
    private $counterDebug;
    private $postdata;

    public function __construct($myUrl, $postdata)
    {
        $this->myUrl = $myUrl;
        $this->postdata = $postdata;
        $this->eventsArr = array();
        $this->counterDebug=0;
    }

    public function run()
    {
          $flag=false;

          foreach ($json as $key => $value) {

                    $this->counterDebug++;
                    /* Death event */
                    $event= new Event($a, $b, $c);
                    array_push($this->eventsArr, $event);

                }
              }

            }
          }
          echo (count($this->eventsArr));
          echo (json_encode($event));
          echo ("\n" . $this->counterDebug);

    if($flag && count($this->events)>0){
    ...

When trying to add new created objects into the array, it stays empty.
What I've figured from debugging:
1) The objects are created.
2) neither eventsArr[]= $event, nor array_push are working.
3) I've set a counter that verifies the objects are being created and should be added to the array.
What am I doing wrong?
p.s-
I've removed irrelevant parts of code in order to simplify things.

A: i think you should create temp array which have all your events and then give it to $eventsArr like this.
$temp = array();
foreach ($json as $key => $value) {
    $this->counterDebug++;
    /* Death event */
    $event= new Event($a, $b, $c);
    $temp[] = $event;
}
$this->eventsArr = $temp;

OR
foreach ($json as $key => $value) {
    $this->counterDebug++;
    /* Death event */
    $event= new Event($a, $b, $c);
    $this->eventsArr[] = $event;
}


text:
Q: Proof by Induction for $\sum_{i = 1}^{n - 1} \frac{1}{i(i+1)}$ $$\sum_{i = 1}^{n - 1} \frac{1}{i(i+1)} = \frac{n- 1}{n}$$
How would you go about proving this by induction? the base case $n=1$ gives you $1/2 = 0$
The only thing I can think of using is $\sqrt{2}$, but that is not a natural number.

A: Your understanding of the base case is incorrect.  When $n = 1$, the sum on the left-hand side is empty, because the upper index is $n - 1 = 0$, meaning there are no terms to add.  This gives $0 = 0$ as desired.
The induction step is straightforward.  If we let $$S_n = \sum_{i=1}^{n-1} \frac{1}{i(i+1)},$$ then $$S_{n+1} = S_n + \frac{1}{n(n+1)}.$$  So if the induction hypothesis $$S_n = \frac{n - 1}{n}$$ is true, what does that say about $S_{n+1}$?

A: When $n = 1$, the sum on the left  side is empty, because the upper index is $n - 1 = 0$, that is  there are no terms to add.  This gives $0 = 0$ as desired.
Suppose that  $$S_n = \sum_{i=1}^{n-1} \frac{1}{i(i+1)},$$ then we have to prove $$S_{n+1} =   \frac{n}{ (n+1)}.$$  So if the induction hypothesis $$S_n = \frac{n - 1}{n}$$ is true,  we have:
$$S_{n+1} = S_n+  \frac{1}{n (n+1)}.$$ that is $$S_{n+1} =\frac{n-1}{n}+  \frac{1}{n (n+1)}=\frac{n}{n+1}.$$
The proof is compelete.

A: The $2$ answers above are indeed excellent, and should be sufficient for your problem. Below I offer a different way of proving this result:
$$\begin{align}\sum_{i=1}^{n-1}\frac{1}{i(i+1)}&=\sum_{i=1}^{n-1}\frac{1}{i}-\frac{1}{i+1}\\
&=\frac{1}{1}-\frac{1}{2}\\
&+\frac{1}{2}-\frac{1}{3}\\
&+\frac{1}{3}-\frac{1}{4}\\
&~~\vdots\\
&+\frac{1}{n-1}-\frac{1}{n}\end{align}$$
You should be able to see that all terms cancel out other than $1$ and $-\frac{1}{n}$
Hence,
$$\sum_{i=1}^{n-1}\frac{1}{i(i+1)}=1-\frac{1}{n}=\frac{n-1}{n}$$
as required.


text:
Q: async observable for two different api calls -Angular 8 i have a function that filters a list on add and delete and calls the respective api and binds to the async observable contact$
below is my
html

<ng-container *ngIf="contact$ | async as data; else loader">
</ng-container>

ts file

 userChanges(contactList: any[]) {

    let contactsToDel: { pubType: string, masterOutlineId: number, idsv: number, idVariant: number, fn: string, ln: string, cid: string, role: string }[] = [];
    contactList.filter(c => c.mode == 'delete').forEach(contact => {
      if (contact.masterOutlineId === this.masterOutlineId && contact.idVariant === this.idVariant && contact.procuid === this.procuid) {

        let idsv = this.idSVList.find(x => x.idv === contact.idVariant).idsv;
        this.idSV = idsv;
        contactsToDel.push({ pubType: this.pubType, masterOutlineId: contact.masterOutlineId, idsv: idsv, idVariant: contact.idVariant, fn: contact.fn, ln: contact.ln, cid: contact.cid, role: contact.role })
        this.contact$ = this.contactService.removeBulkContact(this.pubType, this.procuid, this.variantid, idsv, contactsToDel.filter(c => c.masterOutlineId === this.masterOutlineId && c.idVariant === this.idVariant && contact.procuid === this.procuid));

      }
    });
    let contactsToAdd: { pubType: string, masterOutlineId: number, idsv: number, idVariant: number, fn: string, ln: string, cid: string, role: string }[] = [];
    contactList.filter(c => c.mode == 'add').forEach(contact => {
      if (contact.masterOutlineId === this.masterOutlineId && contact.idVariant === this.idVariant && contact.procuid === this.procuid) {

        let idsv = this.idSVList.find(x => x.idv === contact.idVariant).idsv;
        this.idSV = idsv;
        contactsToAdd.push({ pubType: this.pubType, masterOutlineId: contact.masterOutlineId, idsv: idsv, idVariant: contact.idVariant, fn: contact.fn, ln: contact.ln, cid: contact.cid, role: contact.role })
        this.contact$ = this.contactService.saveContact(this.pubType, this.procuid, this.variantid, idsv, contactsToAdd.filter(c => c.masterOutlineId === this.masterOutlineId && c.idVariant === this.idVariant && contact.procuid === this.procuid));

      }
    });

  }

service file
  saveContact(pubType: any, procuid: number, variantid: number, idsv: number, contactsToAdd: any): Observable<any> {
    const body = JSON.stringify({ searchType: 'save-contact', pubType: pubType, procuid: procuid, variantid: variantid, idsv: idsv, contactsToAdd });
    console.log("body:",body);
    const endpoint = environment.endpointContacts;
    return this.http
      .post<any>(endpoint, body)
      .pipe(map(data => { return data[0] }), catchError((error) => {
        return of([{ contacts: [], proclist: [], status: error, isError: true }]);
      })
      );
  }

  removeBulkContact(pubType: any, procuid: number, variantid: number, idsv: number, contactsToDelete: any): Observable<any> {
    const body = JSON.stringify({ searchType: 'contact-remove', pubType: pubType, procuid: procuid, variantid: variantid, idsv: idsv, contactsToDelete });
    console.log("body:",body);
    const endpoint = environment.endpointContacts;
    return this.http
      .post<any>(endpoint, body)
      .pipe(map(data => { return data[0] }), catchError((error) => {
        return of([{ contacts: [], proclist: [], status: error, isError: true }]);
      })
      );
  }

issue is i am only able to either save or only delete.. if both calls are made , only save is done and not delete. how do i make sure delete is completed before the save is called ? What am i doing mistake here?

A: Have one variable and setting both calls to that this.contact$. So the second forEach loop is overriding the value from the previous loop. If you want to use async for this, you will need some refactoring.
  userChanges(contactList: any[]) {

    const obsArray$ = [];

    let contactsToDel: { pubType: string, masterOutlineId: number, idsv: number, idVariant: number, fn: string, ln: string, cid: string, role: string }[] = [];
    contactList.filter(c => c.mode == 'delete').forEach(contact => {
      if (contact.masterOutlineId === this.masterOutlineId && contact.idVariant === this.idVariant && contact.procuid === this.procuid) {

        let idsv = this.idSVList.find(x => x.idv === contact.idVariant).idsv;
        this.idSV = idsv;
        contactsToDel.push({ pubType: this.pubType, masterOutlineId: contact.masterOutlineId, idsv: idsv, idVariant: contact.idVariant, fn: contact.fn, ln: contact.ln, cid: contact.cid, role: contact.role })
        const obs$ = this.contactService.removeBulkContact(this.pubType, this.procuid, this.variantid, idsv, contactsToDel.filter(c => c.masterOutlineId === this.masterOutlineId && c.idVariant === this.idVariant && contact.procuid === this.procuid));
        obsArray$.push(obs$);
      }
    });
    let contactsToAdd: { pubType: string, masterOutlineId: number, idsv: number, idVariant: number, fn: string, ln: string, cid: string, role: string }[] = [];
    contactList.filter(c => c.mode == 'add').forEach(contact => {
      if (contact.masterOutlineId === this.masterOutlineId && contact.idVariant === this.idVariant && contact.procuid === this.procuid) {

        let idsv = this.idSVList.find(x => x.idv === contact.idVariant).idsv;
        this.idSV = idsv;
        contactsToAdd.push({ pubType: this.pubType, masterOutlineId: contact.masterOutlineId, idsv: idsv, idVariant: contact.idVariant, fn: contact.fn, ln: contact.ln, cid: contact.cid, role: contact.role })
        const obs$ = this.contactService.saveContact(this.pubType, this.procuid, this.variantid, idsv, contactsToAdd.filter(c => c.masterOutlineId === this.masterOutlineId && c.idVariant === this.idVariant && contact.procuid === this.procuid));
        obsArray$.push(obs$);
      }
    });

   this.contacts$ = forkJoin(obsArray$);
  }


text:
Q: Angular2: ts - Supplied parameters do not match any signature of call target Below is the code that has the logic that changes the rows, cols, according to my business needs. When I keep this code, in my Angular2 ts code, I am getting  Supplied parameters do not match any signature of call target error at .forEach(...
var data = [{ Id: "a", ColumnLocation: "0", RowLocation: "0" }, { Id: "b", ColumnLocation: "0", RowLocation: "1" }, { Id: "4", ColumnLocation: "0", RowLocation: "3" }, { Id: "c", ColumnLocation: "1", RowLocation: "0" }, { Id: "d", ColumnLocation: "1", RowLocation: "2" }, { Id: "e", ColumnLocation: "2", RowLocation: "0" }, { Id: "e", ColumnLocation: "2", RowLocation: "2" }];

data.forEach(function (col, row) {
                return function (o) {
                    if (col !== o.ColumnLocation) {
                        col = o.ColumnLocation;
                        row = 0;
                    }
                    if (+o.RowLocation !== row) {
                        o.RowLocation = row.toString();
                    }
                    row++;
                }
            }());

A: As others mentioned in order to use self executing function with parameters you need to provide those parameters.
let myCol; // or you can set this to an initial value
let myRow;

data.forEach(function (col, row) {
            return function (o) {
                // your logic here
            };
        }(myCol, myRow));

Your typescript compiler is complaining because your function takes two parameters col and row but you are invoking it without any parameter.


text:
Q: Jinja nested template inside variable in template I want to do custom notification system. Right now i have table in database, that have html code, what i put on my page.
But if I insert jinja expressions into this code, they are displayed as plain text.
Example:
def render():
    hidden_variable = "world"
    example = "Hello {{hidden_variable}}!"

    return {'example': example, 'hidden_variable': hidden_variable}

template.html
<div>
{{example}}
</div>

What i get:
Hello {{hidden_variable}}!

What i want:
Hello world!

A: That example is being stored as string because you are using jinja syntax inside a python function.
Jinja is a web template engine for the Python.
Instead:
example = f"Hello {hidden_variable}!"

A: Maybe you need to use nested jinja templates:
nested_template = 'my_custom_template'
hidden_variable = 'hello world'

base_template.html.j2
{% include 'nested/' + nested_template + '.html.j2' %}

nested/my_custom_template.html.j2
{{ hidden_variable }}


text:
Q: Distributed A/B-like testing with Locust I need to compare network latency for 2 clients half the globe away from each other and visualize the response time history for each location the request comes from side-by-side. I've been researching load and performance testing tools and found Locust to be very convenient. Is there a way I can achieve my goal with Locust in a quick/standard/non-hacky way?

A: Whether you mean you need 2 clients in different locations running the same task to compare or 2 clients in 2 different locations running 2 different tasks, Locust can handle either of those scenarios.
Check out the Tasks section of the documentation for details about how to write tasks. You can write a single task that does both of what you need, two different tasks that are randomly selected for each user that starts, write two tasks and have them be weighted in their randomness (including making one weighted at 0 so it's never run, effectively turning one task off so only the other one is run at that time), and many other options. Which method is best will depend on exactly what you need and how you want to do it. It may take some experimentation to determine what's best.
As for running in multiple locations, you can run the test separately in different places and compare results, or Locust can run distributed so you can have workers in multiple locations running at the same time. You may also want to look at using Docker, which in some ways can make running in different locations easier if you use AWS, Azure, GCP or whatever other cloud provider to spin up instances to run on.


text:
Q: How to efficiently read a battery voltage level with ADC There is a circuit powered by a battery (3V button cell) and another circuit with a microcontroller (Attiny85 in my case) reading perfectly the battery level (through ADC3 pin) each 5 minutes interval.
                              --------------------
                              | *                |
                          -----                  -----
  Circuit+                | 1 |                  | 8 |------------- +5V
     |                    -----                  -----
     |              ADC3  -----                  -----
     +--------------------| 2 |                  | 7 |
     |                    -----     ATTINY85     -----
     | BAT+               -----                  -----
     |                    | 3 |                  | 6 |
 /-------\                -----                  -----
/         \          GND  -----                  -----
|   3V    |     +---------| 4 |                  | 5 |
|  Cell   |     |         -----                  -----
\         /     |             |                  |
 \-------/      |             --------------------
     |          |
     | BAT-     |
     |          |
     +----------+-------------------------------------------------- GND
     |
     |
  Circuit-

As commented bellow by @michael-karas, according to datasheet, the Attiny85 has an input leakage current of 0-1 µA.
So, the question: Is there any circuit configuration or software tip to minimize the battery consumption by the Attiny85?

A friend of mine suggested this solution where R should be higher enough to minimize RTC circuit overvoltage and allow ADC readings to vary proportionally to the cell battery voltage:

simulate this circuit – Schematic created using CircuitLab

A: @rdtsc has removed his answer which IMO raises a valid concern. I don't think the OP can rely on +5V to always be present (else, they wouldn't need the battery, would they?), and when that +5V is removed, the MCU will be powered via the pin's clamping diodes.
It is therefore recommended to either add a significant series resistor to the measurement pin which will reduce the leakage current to a minimum, or add an active circuit which connects the battery to the MCU only when a measure must be taken:

Depending on the expected intervals the system will spend without +5V power, the schematic above may be an overkill, but at least a series resistor should be there.

A: As long as the ATTINY85 is powered from a separate power source and not from the "Circuit+" node that you have labeled in your diagram then the only load on the battery will be as defined in the data sheet that you had linked. Here is the relevant data for input pin leakage:

You will want to make sure that you do not have that pin configured as a digital pin, output or try turning on the pullup resistor:


text:
Q: cakephp validation in model on two fields being unique I am trying to amend my validation in my Model.
I need to check to see if (FIELD1 and FIELD2) are unique. For example
FIELD1 = "mattfacer" //username
FIELD2 = "1192" //chosen display ID
I need to check the database to see if the FIELD1 and FIELD2 have been used. If not, it should pass validation. If that display ID of 1192 and the username "mattfacer" has been used, return false for validation.
Is that possible? I was thinking of a custom validation function but not sure where I'd call it?
Thank you.
[edit]
The username and display ID are not unique in them selves.. it's the combination of the two which need to be unique. So there could be the following which is allowed
username = mattfacer
displayid = 6609
username = suziefacer
displayid = 6609
Those would be allowed.
[/edit]

A: // you may be use this
<?php
 public $validate = array('FIELD1' => array('beta' => array(
                                            'rule' => 'isUnique',
                                            'message' => 'This FIELD1 alreay exists!',
                                         )),
     'FIELD2'=> array('beta' => array(
                                            'rule' => 'isUnique',
                                            'message' => 'This FIELD2 alreay exists!',
                                         )
                        );
?>


text:
Q: Any way to avoid using gsub! for replacement I am running in issue, where I used following code.
  def replace_variables(url, project)
    variables = define_variables(project)
    variables.each do |key, value|
      url.gsub!(key, value_encode(value))
    end
    url
  end

And issue was coming due to gsub! usage it was going up and effecting all data, where I just wanted to change data here. so I came to following solution but it is not good, any other way to do it. As it is too much variable definitions. This is working fine, but seem extra variable definitions!
  def replace_variables(url, project)
    variables = define_variables(project)
    temp_url = url
    variables.each do |key, value|
      temp_url = temp_url.gsub(key, value_encode(value))
    end
    temp_url
  end

More explaination Code creating some variables and replacing it from url and change values of it, but I have array of forms and if this runs first it changes those forms value too! which I don't want. The above code working fine but look bad as I am defining accumulator variable and iteration, is there any other way to do it elegantly. I have following define method
  def define_variables(project)
    {
        'TODAYS_DATE' => Date.current.to_s,
        'USER_NAME' => username,
        'PROJECT_NAME' => project.name || '',

    }
  end

A: If #define_variables returns a key/value hash then something like this should work.
def replace_variables(url, project)
  define_variables(project).inject(url) do |memo, (key, value)|
    memo.gsub(key, value_encode(value))
  end
end


text:
Q: EJB3.1 Timer cancel issue I have a problem with EJB3.1 Timer service. I find this issue quite strange! I have a stateless session bean like below deployed on JBoss7.1.1 application server.
import javax.annotation.Resource;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;
import javax.interceptor.Interceptors;

@Stateless
@Local(HelloUserLocal.class)
@Remote(HelloUserRemote.class)
public class HelloUserBean implements HelloUserRemote {

@Resource
private TimerService timerService;

@Interceptors({SayHelloMethodLoggingInterceptor.class})
public String sayHello(String name) {
    System.out.println("In sayHello(name)");
    String customName = "Hello " + name + " welcome to EJB 3 In Action!";
    System.out.println("Before returning, register Timer service");

    timerService.createTimer(10000, 2000, "Hey! Good Night!");

    return customName;
}

@Timeout
public void activateTimer(Timer timer){
    System.out.println(timer.getInfo());
    //timer.cancel();
}

}

I registered a Timer with initialDuration and intervalDuration as above. After I deployed my bean, it works fine. Okay, I got the thing and I don't want my server console to clutter. So, I commented out timerService.createTimer(..) line of code and redeployed. But, I still see the message being printed. Okay, I know EJB Timers are persisted and survive server restarts. The only way I can stop my Timer Service is to use timer.cancel() method and then redeploy. But, how can I stop or de-register my Timer from the container without using timer.cancel()?
How much time timer.cancel(); take to cancel the Timer? When I use timer.cancel() and then redeployed my application, I can see "Hey! Good Night!" being printed two times before stopping, which means certainly timer.cancel() is taking more than 2000ms?

A: you could use @Schedule instead and configure your timer with persistent=false. If a persistent timer has already been created, looks like the only non-programmatic way to remove it is by deleting JBOSS_HOME/server/<servername>/data/timer-service-data, it's not nice and for what I remember, in the JBoss4 days this could be done through the JMX console, but a lot has changed since those days, good luck.


text:
Q: error in my Times Table app in swift I get the following error when I run my app:

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet var slider: UISlider!
    @IBOutlet var table: UITableView!

    internal func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 50
    }

    internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")
        cell.textLabel?.text = String((Int(slider.value * 20)) * (indexPath.row + 1))
        return cell
    }
}

A: You should not be creating a new cell in each call to cellForRowAt. You should be using dequeueReusableCellWithIdentifier to try to recycle a cell. That's not the cause of your problem, but it's important nevertheless.
It's hard to be sure why you are crashing. Can you post the declaration of slider? My guess is that it's an implicitly unwrapped optional (declared with an !)
Does the declaration look something like this:
@IBoutlet var slider: UISlider!

If so, set a breakpoint at the line that's crashing and check to see if slider is nil. (Although you usually get a different error about attempting to unwrap a nil optional when that's the cause.)


text:
Q: How to set spark standalone master url in play-framework conf/application.conf file? plugging the play application with spark standalone cluster it executes well on    dev mode but when trying to deploy in production mode it gives following error:
 Caused by: org.apache.spark.SparkException: A master URL must be set in your configuration

I am using spark-2.1 here is the snippet
lazy val spark = SparkSession.builder().appName("Spark_with_Play").master("spark://ip:7077").config("spark.executor.memory", "2g").config("spark.deploy.defaultCores",8).getOrCreate()

So how can i  set spark master in conf/appliaction.conf file in production mode ?

A: After many trials able to find typesafe config  which is used to read the configurations from application.conf file and pass those into code.
here is the content of application.conf file:
spark.master = "spark://ip:7077"

here is the line which is added to build.sbt
"com.typesafe"%"config"%"1.2.0"

in controller  here is code the snippet:
import com.typesafe.config._
val conf = ConfigFactory.load()
val sparkMaster = conf.getString("spark.master")

val spark= SparkSession.builder().master(sparkMaster).getOrCreate()


text:
Q: How can i group items in SharePoint based on an input? I currently have a SharePoint site set up that contains a status field. Based on the status (opened or closed), the items will be grouped by status.
I want to remove the status field and have a closed date field. Once the closed date field is populated, the closed items will be grouped into a closed group. If the item is not populate, it will remain in an open.
Anyone?

A: List > List Settings > Create View
Call your view whatever your want - perhaps "open items"

Under the filter heading, choose your date heading, select 'is equal to' and leave the field blank.

A: What it sounds like to me is that when your closed date field is populated, you want the status to automatically change to 'Closed', and then your items would automatically be grouped into the correct Open/Closed group based upon the status.
I would build a quick workflow in SPD for this to run on an item change. If you haven't already, set the default value of Status to 'Open'. Then, using the workflow, change the Status to 'Closed' when the 'Closed Date' field is not blank.
In your view, group by the 'Status' field, and make sure your Status field is hidden (unchecked) within the view.
This way, you'll have an 'Open' and 'Closed' group, and when the closed date is populated, the item will automatically move from the 'Open' to 'Closed' group.


text:
Q: Learning C# with exercises, questions and puzzles I learned Java with the help of the book 'Java how to program'. The book had lots of questions and exercises that helped me a lot.
I am now looking for a  website or preferably a book that has similar programming questions/exercises that will help me learn C#/.NET and become a better programmer. Could someone suggest a book or point me to a website ?
Thanks
Edit: I should add that I am not looking for advanced stuff like Project Euler, but basic stuff

A: This isn't a bad site:
http://www.fincher.org/tips/Languages/csharp.shtml
Starts off with console applications doing "Hello World" and reading files and goes on to hit a long list of important concepts including database access using Parameters.

A: The Sphere online Judge has a good collection of programming problems, ranging from tutorial problems to challenge problems.

A: If you like working through exercises, solving puzzles, etc. while learning, you'll love the Head First book on C#.

A: APress Pro C# 2010 and the .NET 4 Platform by Andrew Troelsen is the single best book I've read to quickly get into the language. It suggests concise relevant examples and code samples for the reader to try, and I recommend following them. It's a 1700 page book - very exhaustive and reasonably priced for the amount of content.

A: While it's specifically aimed at algorithmic programming, Project Euler can only do good things for getting well-acquainted with a language! Work through as many problems as you can, solving them in C#, and you'll have fun at the same time as learning the language.


text:
Q: Regarding preorder tree traversal I have written the following code snippet for recursive Binary Tree Preorder Traversal:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    std::vector<int> myVec;
public:
    vector<int> preorderTraversal(TreeNode* root) {
        if(root==NULL)
            return vector<int>();

        myVec.push_back(root->val);
        preorderTraversal(root->left);
        preorderTraversal(root->right);

        return myVec;
    }
};

While this code runs and produces the expected output, I am not totally sure if this is correct; because when I call preorderTraversal(root->left); and preorderTraversal(root->right); I am not using the values that they return (vector<int>s).  So,

*

*Is this correct?

*If no, then how can I rectify this code?

A: Yes, it is correct if you call it once. If not, myVec vector is not cleared.
In fact, each call to preorderTraversal, except the top one and path from it to the left, return some intermediate state which doesn't make much sense. If I were you, I would refactor this code to hide the intermediate value inside the class:
class Solution {
private:
    std::vector<int> myVec;

    void traverse(TreeNode* root) {
        if (root == NULL)
            return;

        myVec.push_back(root->val);
        preorderTraversal(root->left);
        preorderTraversal(root->right);
    }

public:
    vector<int> preorderTraversal(TreeNode* root) {
        myVec.clear();
        traverse(root);
        return myVec;
    }
};


text:
Q: What is the difference between shelve and check in in TFS? What is the concept of each?
When is it ok to shelve your changes instead of checking in?

A: Other users can download your shelvesets by searching for them, so it is a good way to pass code around for reviews.  however you will get an error if you try to unshelve code files that you already have checked out, so you need a clean environment ready.
I often shelve my changes at the end of the day if I'm working on something big that I can't check in.  That way, if my PC dies overnight, I've got a backup on the server.

A: Shelved means the changes are set aside for you to work on later.
Checked in means that the changes are made available to the rest of the team, will be in the build and will eventually ship.
Very different.  Think of shelving as a tool for context switching when you're not done with a task.  Checking in means you're done (at least a part of it).

A: Darcy gets it spot on.  You can also think of shelving as a private branch that is not publicly visible for the most part.  Shelvesets can also be deleted completely, not like deleting checked in code.  If you delete a shelfset it is gone forever.

A: Shelve your changes when you want to save the changes that you have made, but need to go back to the previous version to make other changes (perhaps, bug fixes) that you want to deploy without the updates you are currently working on.  Since you're usually checking in pretty regularly, I find this to be a rare occurence -- like I just deployed to the QA box and an error was immediately found.  I'll shelve that day's changes bringing me back to the QA deployed version, make the update, then unshelve my changes -- merging the two as necessary.  Any longer than that and you'll probably be looking to check out a previous version and branch instead.  I'd be happy to hear of other experiences where shelving has proved more useful, though.

A: Everyone above has said so much true and I learned allot from it.
Just to add my experience, correct me if I am wrong. In a project, we have a configuration file mypc.json specific to each PC of the developer. We usually override it when running server locally. Other team members have the same file name with different configurations in it. No one wants their file to be pushed with the same name to the development branch. So I use shelve to save these type of changes. Whenever I need these configurations I can easily apply changes from shelve and my environment configurations are back in my project.


text:
Q: Wiring two LDOs in parallel with only one diode between i know the traditional wiring of two power sources with two diodes. But can it also work only with one?
Please take a look at the attached schematic:
The TPS706 pmos LDOs have build in reverse current protection so no current can flow from output to input. In my system i have three power sources:
1) Battery 3.6V
2) LiPo 3.7V (which can also be charged by the sources under 3)
3) 4.5V-6V external Supply (e.g. USB or solar panel for charging the LiPo)
If the power-good signal (#PG, meaning external supply > 4.5V) is asserted i want to disconnect the battery (1) and power the system (VCC) via the external supply while (eventually) charging the LiPo. The same becomes true even if PG is not asserted but i instruct my lipo charger (MCP73871, CE pin high) to connect the LiPO to Vout.
My question:
Is this schematic smart if one of the two jumpers in the upper right corner is closed. I want to implement this way some sort of power supply priority. But this approch leads to have two LDOs connected with only one of it isolated by a diode...Iam not quite sure if this is too clever ;-) Or is it possible to connect both LDO directly together? Have some doubts about the control loops inside...
Thank you for any comments!

A: Electronic industry has a solution for this case. It is solved by a special class of devices called "power distribution switch", within PMIC group of IC.
Search Digi-key for this type, "PMIC - Power Distribution Switches, Load Drivers", then select, say, "2:1" in the column "Ratio - Input:Output".
Essentially these are switches based on FETs, as "ideal diodes". Here is an example, FPF1320UCX.

A: One diode won't work if you have two sources on because the voltage drop from the diode will cause one the current to be sourced more from one regulator than the other.
Another way that this could be done is a detection scheme with a microcontroller (if its on and has power all the time) or comparators that select specific voltage regulators that have a power enable pin. The power enable pins allows the regulator to be switched on. To prevent current leaking in from other regulators they would also need to support reverse current protection.


text:
Q: Permission denied in creating a database in ASP MVC I am trying to store a session state into SQL Server using the following command in order to generate the database :

aspnet_regsql.exe -S localhost -E -ssadd -sstype p

but I recieve an error  which mention that the permission is denied in database 'master' :

SQL Exception: System.Data.SqlClient.SqlException (0x80131904): CREATE
  DATABASE permission denied in database 'master'.    at
  System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
  Boolean breakConnection, Action`1 wrapCloseInAction)

A: Your application tries to CREATE DATABASE in some way.
It can be RESTORE DATABASE or sp_attach or explicit CREATE DATABASE statement.
It can be even parameter in connection string that indicates database to be attached.
You can use SQL Server Profiler to see the exact code that cause this error.
You should find what login tries to execute this code and grant him CREATE ANY DATABASE permission or include him to sysadmin role


text:
Q: 4GB of RAM on Windows 7 32-bit
Possible Duplicates:
Windows XP and RAM 3.5GB+
Is there way to enable 4 GB RAM in 32-bit Windows OS?

I installed 4GB of RAM on my Windows 7 Ultimate 32-bit (it used to have only 2GB).
But it says only 3GB usable, and I still often get a "Not enough memory" problem on Photoshop.

Is there any way to make it utilise the full 4GB?

A: Quite simply, you can't use it, 32bit cannot access above 3gig due to limitations of the 32bit addressing, only 64bit OS with a 64bit CPU can access above this.

A: You have a 64 bits CPU, why did you bough a 32 bit operating system ?
You need Windows 7 64 bits and you can use much more memory and
it will run faster.

A:
Is there any way to make it utilise the full 4GB?

Install 64-bit Windows. In X86 Windows virtual address space for each 32-bit process limit 3Gb.

A: See if PAE can help you:
How can I enable PAE on Windows 7 (32-bit) to support more than 3.5 GB of RAM?

A: 32bit use above 3gig due to limitation of 32bit addressing; only a 64 bit os can unless you run a server edition with PAE. Do you have a x64 CPU?


text:
Q: prevent email-2-case from creating new cases Is there any way to prevent email2Case from creating new cases?
While i need the functionality of all emails being tracked on an already existing case, but i dont want the functionality of new cases being created when the threadId is absent.
If anyone has a suggestion that involves getting rid of email2case altogether, it is also acceptable. At the end of the day, i need the ability to track all emails on a case, but dont want new cases to be created via emails

A: Check this : https://developer.salesforce.com/page/An_Introduction_To_Email_Services_on_Force.com
This involves writing custom code to handle inbound email services ( that means getting rid of out of the box email2case). If you implement custom code you will have lot of flexibility over normal email2case.

A: If you use the thread of in your subjectand body, duplicates shouldn'tbe created. You might want to replace the send email button on the related list with a custom button that auto adds the thread id in both places to keep new emails in sync too


text:
Q: Integration -- can't figure out the substitution I need to evaluate the integral
$$ \int_0^1 \frac{6\pi}{\lvert{2 - 3e^{2\pi i t}}\rvert^2} \,\mathrm{d}t.$$
The problem I am having is that I can't find a nice way to re-write the denominator to invoke a substitution. Perhaps I can view this as a contour integral in the complex plane? Any ideas appreciated.

A: An idea:
$$2-3e^{2\pi it}=2-3\cos2\pi t-3i\sin2\pi t\implies |2-3e^{2\pi it}|^2=13-12\cos2\pi t\implies$$$${}$$
$$\int_0^1\frac{6\pi}{|2-3e^{2\pi it}|^2}dt=\int_0^1\frac{6\pi}{13-12\cos2\pi t}dt$$
You can now try some trigonometric substitution.

A: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
\int_{0}^{1}{6\pi \over \verts{2 - 3\expo{2\pi\ic t}}^{2}}\,\dd t & =
{2\pi \over 3}\int_{0}^{1}
{\dd t\over \pars{1- 2\expo{-2\pi\ic t}/3}\pars{1- 2\expo{2\pi\ic t}/3}}
\\[5mm] & =
{2\pi \over 3}\sum_{k = 0}^{\infty}\sum_{j = 0}^{\infty}
\pars{2 \over 3}^{k + j}\
\overbrace{\int_{0}^{1}\expo{-2\pars{k - j}\pi\ic t}\,\dd t}^{\ds{\delta_{kj}}} =
{2\pi \over 3}\sum_{k = 0}^{\infty}\pars{4 \over 9}^{k}
\\[5mm] & =
{2\pi \over 3}\,{1 \over 1 - 4/9} = \bbx{\ds{6\pi \over 5}}
\end{align}


text:
Q: Copying Mobile Me Gallery photos into empty iPhoto My hard drive died so I lost all of my data.  However, I'd uploaded all my photos to Mobile Me Gallery.  How do I bring them back from Mobile Me into my now empty iPhoto so they are restored back onto my Macbook Air?

A: This KB article should tell you how to do it
Make sure that your MobileMe account is properly configured in Mac System Preferences and that you are using a broadband Internet connection.
Launch iPhoto and determine which version of iPhoto you are using by choosing iPhoto > About iPhoto.
If you use iPhoto '11 (version 9):
1 Open iPhoto.
2 Choose iPhoto > Preferences.
3 Click Accounts at the top of the preferences window and make sure that your MobileMe
account is visible on the left. If not, add your account by clicking the plus sign
and entering your MobileMe username and password.
4 Select your MobileMe account under the Web section of the iPhoto source list.
5 Double-click on each individual album in your Gallery and wait for any new photos
in the album to download to your computer.  A photo is completely downloaded when
the word "pending" no longer appears on the bottom of the photo.
6 Once all photos have been downloaded you can drag and drop photos from each of your
galleries to Photos in the left hand column to ensure that they are in your main iPhoto library.

If you use iPhoto '08 (version 7) or iPhoto '09 (version 8):
1 Open iPhoto.
2 Choose iPhoto > Preferences.
3 Click Web at the top of the preferences window.
4 From the "Check for new published photos menu", choose Automatically
and then click the Check Now button. Then, dismiss the window.
5 In the left hand pane of iPhoto, expand MobileMe Gallery and click on each album, one
by one.  As you click each album, a spinning icon will indicate that iPhoto is checking
MobileMe for any photos that have not yet been synced to your computer. If any photos
are found, they will be downloaded automatically.
6 Once all photos have been downloaded you can drag and drop photos from each of your
galleries to Photos in the left hand column to ensure that they are in your main
iPhoto library.


text:
Q: Java Servlet Reloading How to turn on servlet reloading so you don't have to stop and restart Tomcat every time you want to change and test a servlet? Any help will be greatly appreciated. Thank you.

A: turn on Hot code replacement feature of your IDE. or install JRebel.


text:
Q: Is there any difference between both of these codes? Assuming that I have a method that will always return a list with 0 or 1 objects: (never returns null)
public List<Object> getList() {

    List<Object> list = new ArrayList<Object>();
    if (someCriteria) {
        list.add("1");
    }
    return list;
}

Is there any difference between both of these codes?
public Object getFirstElement() {
    List<Object> list = getList();
    return(getList().get(0));
}

versus
public Object getFirstElement() {
    List<Object> list = getList();
    if (!CollectionUtils.isEmpty(list)
        return list.get(0);
    return null;
}

A: Yes there is.
In first case, if some creteria is false, list is an empty List:
import java.util.List;
import java.util.ArrayList;
public class Test {

    boolean someCriteria = false;

    public static void main(String[] args) {
        new Test().getFirstElement();
    }

    public List<Object> getList() {

        List<Object> list = new ArrayList<Object>();
        if (someCriteria) {
            list.add("1");
        }
        return list;
    }

    public Object getFirstElement() {
        List<Object> list = getList();
        return(getList().get(0));
    }
}

You get an exception:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at Test.getFirstElement(Test.java:29)
    at Test.main(Test.java:13)

in second case the funtion returns null.
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;

public class Test {

    boolean someCriteria = false;

    public static void main(String[] args) {
        System.out.println(new Test().getFirstElement());
    }

    public List<Object> getList() {

        List<Object> list = new ArrayList<Object>();
        if (someCriteria) {
            list.add("1");
        }
        return list;
    }

        public Object getFirstElement() {
            List<Object> list = getList();
            if (!CollectionUtils.isEmpty(list))
                return list.get(0);
            return null;
        }
}

OUTPUT:
null


text:
Q: Is there a way to format alternating lines (not paragraphs) without tables? I've got a bunch of code I want to present clearly, and since code paper is practically impossible to get now I'd like to format alternating lines to improve legibility. It's easily done in a table, of course, or at a paragraph level with a lot of manual work, but is there any way of doing it per line and without using tables?
Tried to add an example, but my office computer has decided it doesn't like loading pages any more. So hey, I'll improvise...
Any way of getting a per-line banding without resorting to manual line breaks?

A: How about creating a couple of paragraph styles and using a small VBA routine to apply them to the currently selected text, e.g.
Sub applystripestoselection()
' create paragraph styles called banded1 and banded0
' with the characteristics you want
Const StylenamePrefix As String = "banded"
Dim i As Integer
For i = 1 To Selection.Paragraphs.Count
 Selection.Paragraphs(i).Style = StylenamePrefix & CStr(i Mod 2)
Next
End Sub

If you need to be able to re-apply to numerous separate blocks in the document, I suppose you could do that by bookmarking the blocks in some way - e.g. use a name such as "codeblock" and append the next number every time you insert a new bookmark, to give you codeblock1, codeblock2, codeblock3 etc., then modify the above VBA to apply the styles to every paragraph in every range "covered" by a codeblock ref. Then you'd probably still have to do a bit of manual sorting out (Undo can be your friend at this point!)


text:
Q: What is HHOJSID URI path parameter used for? I was testing a site with cookies disabled and I noticed HHOJSID parameter in URL path.
It could be a session ID encoded in URL like jsessionid for J2EE web applications.
I searched Google and found a lot of examples but no technical description.

A: Since this parameter seems to appear exclusively in URLs for HP's Home and Home Office online store, I suggest it stands for "Home and Home Office Java Session ID".
I'm sure you're right when you say it's a URL-based session ID - it's just that HP have modified its name for their online store.


text:
Q: What does the expression int(2.5) produce? Does it equate to any of the following, eg. 72 or "72"?
Have tried typing the expression in python but to no avail.

A: int(2.5) will convert 2.5 to an integer, so the output will be 2.
You can test it yourself by starting python3 in a shell, and then typing int(2.5)


text:
Q: near-api-js does not return contract method response I'm working on testnet with using near-api-js (Nextjs) to call contract method.
When I call the method without Approve Transaction (No deposit or Call from the contract was deployed by current account), near-api-js return the result of contract method but when I call from another Near Account (It require to change to wallet screen to approve transaction), near-api-js will return the transactionHash. I used this transactionHash to check on Explorer and got the result is my contract still return the correct result but it seems not to send this result to my client.
Anyone can tell me what happened and how to resolve it?
Here is my sample transactionHash: 8NHCjNkM6VDnSyMg43gzwngNPNZJTDCnvDSTtQj5QsM
There is no problem when call method from near-cli or near-api-js without deposit option.
Below is my code on front-end
contract?.init_new_event?.(
    {
     title: event_name,
     location: 'Hanoi',
     description: des,
     privacy: [],
     cover_image: rootCid,
     type: parseInt(event_type),
     start_date,
     end_date,
    },
    100000000000000,
    depositAmount,
    ).then((res) => {
     if (res) {
      router.push(`/event/event-detail?id=${res}`);
     } else {
      onShowResult({
       type: 'error',
       msg: 'Creat event failure',
      });
     }
    }).catch((err) => {
     onShowResult({
      type: 'error',
      msg: String(err),
     });
   });

And when I call from owner account of this contract, I received a response like
"nMX4ZeyxLTK9ZYyJmA9FhR7Y8zgieLsvnc9VeJhGtRVsAm82tnzMG"

But when call from another account, I just received transactionHash such as
transactionHashes=EgSmzhmtMHr6WNmtLpJaa7W9qLn6PzdHEzK2ST13vGgA

You can see on near explorer, the contract method still working correctly:
https://explorer.testnet.near.org/transactions/BQVMve8FtgQ8sqBDyzS3FrTR5buYy4qmuCWcCVD7K8KE

A: When you call api (attach deposit) you can only check txHash to know tx success or not,  you can't check response from smart contract.
=> The solution : Separate deposit api from your main-action api, user must deposit before call main api then you can get response on main-action normally


text:
Q: Detecting cookie authentication in ASP.NET CORE / MVC with Identity I'm using ASP.NET Core with EntityFramework backed Identity.
I'm able to log users when they use the login-form of the site, but I have a situation where I also need to detect user authentication via the "remember me" cookie mechanism, i.e. this line of code, which sets the isPersistant flag to true if the user cheks "remember me" in the login form:
result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, lockoutOnFailure: false);

In the old system this was done in Global.asax by overriding these methods:
protected void Application_AuthenticateRequest() { }
protected void Application_PostAuthenticateRequest() { }
protected void Application_AuthorizeRequest() { }

... but I assume I'll need to implement this as some kind of middleware component in CORE, but I'm not sure what to look for after that.
Ultimately, in this scenario, I need to log "Last Login Time", so I don't want to detect authentication for every request.  Perhaps it is necessary to somehow tie this to the active session?
Any help is appreciated.  Thanks!


text:
Q: What is the difference between GRASP information expert and GRASP cohesion? Both concepts are very similar it is hard to tell which is which.
Please give an example of how you would differentiate them.

A: All GRASP concepts are linked, so you should consider them all together:

*

*"information expert" - question is "Which object should have needed
behavior?" (Please see
http://en.wikipedia.org/wiki/Domain-driven_design) like one of
the answers for this question.

*"cohesion" - question is "How many different behaviors object have"
http://en.wikipedia.org/wiki/GRASP_(object-oriented_design)
You should not learn these concepts without coding practice, write code/make refactoring - and you will get it.

A: GRASP Design Patterns, as very rightly said here (Is Information Expert from GRASP and Modell from MVC the same?) are design principles and support you to evaluate your design decisions and  implementation.
"Cohesion" in GRASP is an evaluative design pattern alongside "coupling". Thus you have to use them to analyse your design to figure out how cohesive and loosely coupled it is, which directly enhance re-usability and  extensibility.
On the other hand, "Information Expert" can assist you in identifying which class should be given a particular responsibility. It tells you to assign a certain responsibility to the class which has the most information about it. |
Therefore in a simple shopping cart use case, you would give, A ShoppingItem to calculateItemPrice() based on quantity and unit price, and ShoppingCart to calculateTotalPrice().
This becomes a crucial factor, and note that most GOF design patterns actually are supporting this GRASP concept.
Most importantly. If you applied Information Expert pattern in your design, it should provide you with high cohesion in terms evaluating your design. Thats how Information Expert and Cohesion would go hand in hand, just like all other GRASP patterns.
Resources: http://www.cs.bgu.ac.il/~oosd051/uploads/stuff/ApplyingUMLandPatterns.pdf


text:
Q: Angular directive: Dynamic change img background on hover Looking at the screenshot, I have a background image for the page and two thumbnails below the text. I want to be able to change the background image of the page to the image of the thumbnail when the mouse hovers the thumbnail.
Below is my directive. I can get the src of the thumbnail but I am stuck as to how I could inject that to the element so the page background changes. Also I am already getting the error Expected 2 arguments, but got 1. from the ViewChild line.

import { Directive, ElementRef, HostListener, ViewChild } from '@angular/core';

@Directive({
  selector: '[dynamicBackgroundImg]'
})
export class DynamicBackgroundImgDirective {
  thumbSRC : string;
  @ViewChild('tourBackgroundImg') tourBackgroundImg:ElementRef;

  constructor(private el: ElementRef) {}

  @HostListener('mouseover') onMouseOver() {
    this.ChangeBackgroundImg();
  }

  @HostListener('mouseleave') onMouseLeave() {

  }

  ChangeBackgroundImg() {
    this.thumbSRC = this.el.nativeElement.getAttribute('src');
    alert(this.thumbSRC);
    this.tourBackgroundImg.nativeElement.setAttribute(this.thumbImgSrc);
  }

}

Here is my minified version of my HTML:

{{pageTitle}}

      <picture>
        <source srcset="{{ toursImageUrl }}?fm=webp" type="image/webp">
        <source srcset="{{ toursImageUrl }}?fm=png" type="image/png">

      </picture>

              <picture>

              </picture>

Below is a screenshot that I hope will help you understand what I am trying to achieve:

Chances are I am approaching the whole thing wrongly, any input is appreciated.

A: You could use an event listener on your image to do it : Repro on Stackblitz
Here is the code:
html:

App Component

  hover this image to change the background:

css (Just setup the image to change):
.app-component{
  background-image: url("https://img.maxisciences.com/s3/frgsd/1024/coronavirus/default_2020-02-28_2bbef01b-f63a-4a59-b31e-788da4e402bb.jpeg");
}

and TS :
import {
  Component,
  OnInit,
  ElementRef,
  ViewChild,
  Renderer2,
AfterViewInit
} from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements AfterViewInit {
  @ViewChild("myImage") myImage: ElementRef;
  globalInstance: any;

  constructor(private renderer: Renderer2) {}

  ngAfterViewInit() {

    this.globalInstance = this.renderer.listen(
      this.myImage.nativeElement,
      "mouseover",
      () => {
        this.renderer.setStyle(
          document.body.querySelector('.app-component'),
          "background-image",
          `url(${this.myImage.nativeElement.src})`
        );
      }
    );
  }
}

As you can see, the idea is to bind and listen to an event on the image (here on 'mouseover' event) and change the background of your target (here appComponent) when triggered.

A: There is no need to use @ViewChild in your directive.
The following code should work:
import { Directive, ElementRef, HostListener, Input, Renderer2 } from '@angular/core';

@Directive({
  selector: '[dynamicBackgroundImg]'
})
export class DynamicBackgroundImgDirective {
  // use the @Input to pass the target image
  @Input() target: HTMLImageElement;

  constructor(private el: ElementRef<HTMLImageElement>, private renderer: Renderer2) {}

  @HostListener('mouseover') onMouseOver() {
    this.ChangeBackgroundImg();
  }

  @HostListener('mouseleave') onMouseLeave() {

  }

  ChangeBackgroundImg() {
     // use the Renderer2 service to set the attribute
     this.renderer.setAttribute(this.target, 'src', this.el.nativeElement.src);
     // Add fade-in css class
    this.renderer.addClass(this.target, 'fade-in');
  }

}

In the component template:
<- add a template variable for the image that you want to display it ->

....

<- When you hover this image the tourBackgroundImage will change the source ->

The error Expected 2 arguments, but got 1 from the ViewChild line makes me believe that your working with Angular 8. If so, you need to pass a configuration object in the @ViewChild like so:
@ViewChild('element', { static: false })

If it's used in OnInit life cycle hook, the static property must be true, else false. In previous versions as well in Angular 9, the second argument is optional unless it's not used in ngOnInit.
Update - animation
For animating the image you can use Angular animation or simple css like below:
.fade-in {
  animation: fadeIn ease 1s;
}

@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

I've added in the directive the code for adding the fade-in class when the thumbnail is hovered.


text:
Q: When I installed Ubuntu to replace Windows 7, I could nolonger see my Backup disk D and all my data seems to be lost. Can I recover the data? I first installed Ubuntu and I used it alongside Windows and it was okey! Later my windows got issues and I installed again windows 7. After this I could no longer boot with ubuntu. So I decided to installed again hoping it would again work peacefully alongside windows. This time however ubuntu did not give me the option of co-existing with windows, but I went on with the installation any way. After installation I discovered I could nolonger see my Backup disk D. All my data was gone. I tried using testdisk but it can't install. What Can I do.Please help me; the data I lost is too much!!!!!!!
Djosh

A: During the installation, did you choose the option-
'Erase Everything and install'?
If you did that, then i think your data may be lost.
I dont know much about data recovery, but you should not operate ubuntu from your hard drive to minimise disk changes, and boot from the ubuntu installation disk.
When you boot from it, open the Gparted application, and in the menu bar there is an option -> device -> recover partition table
try that option, maybe it recovers your partitions.

A: There is a gparted live CD http://gparted.sourceforge.net/livecd.php
Maybe you will find the tools you need.
I don't know if gparted still uses "TestDisk" for recovering partition. But in any cases here is the link to the TestDisk documentation. cgsecurity.org/wiki/TestDisk . The "Recovery examples" are worth to read.
As AAditya Baqqa said don't use the Ubuntu you just install, there are chances that you data on D: are untouched. Until recovery uses only live CD.

A: You may boot your machine with a Ubuntu livecd. After the desktop appears, you will see some disk icons on it. Check the icons to see whether it is the original Windows partition. If so, you can open the icon and recover the data from the partition to another USB disk.


text:
Q: Case Then statement for several columns SQL How can I set values for two colums, using Case-Then?
I have next script:
  UPDATE [dbo].[operation_data]
SET block_status = CASE
WHEN sd.status = 'X' THEN 'F'
WHEN sd.status != 'X' and od.block_status = 'F' THEN NULL
ELSE block_status
END
FROM operation_data od
JOIN sales_data sd on sd.operation_data_id = od.operation_data_id
GO

But I want to do something like this
  WHEN sd.status = 'X' THEN 'F' AND main_comment = 'Expired'

'main_comment' is column at the operation_data.
As I know CASE can return only single column. Is it some good solution for it?

A: You have to repeat this for the other column as well:
UPDATE [dbo].[operation_data]
SET block_status = CASE
WHEN sd.status = 'X' THEN 'F'
WHEN sd.status != 'X' and od.block_status = 'F' THEN NULL
ELSE block_status
END
, main_comment = CASE
WHEN sd.status = 'X' THEN 'expired'
ELSE main_comment
END
FROM operation_data od
JOIN sales_data sd on sd.operation_data_id = od.operation_data_id