text:
Q: Probability of being poisoned
You are playing a game in which you have $100$ jellybeans, $10$ of them are poisonous (You eat one, you die). Now you have to pick $10$ at random to eat.
Question: What is the probability of dying?

How I tried to solve it:
Each jellybean has a $\frac{1}{10}$ chance of being poisonous. Since you need to take $10$ of them, I multiply it by $10$ which gave $1$ (Guaranteed death).
How other people tried to solve it:
Each jellybean is picked out separately. The first jellybean has a $\frac{10}{100}$ chance of being poisonous, the second -- $\frac{10}{99}$, the third -- $\frac{10}{98}$ and so on.. which gives a sum of roughly $\sim 1.04$ (More than guaranteed death!)
Both these results make no sense since there are obviously multiple possibilities were you survive since there are $90$ jellybeans to pick out of.
Can someone explain this to me?

A: The other answers are great, but with a slightly different approach from your attempt (I presume you edited in your attempts after some of the answers are posted). I'd like to point out some important things in your post:
"And" vs. "Or"
One fundamental flaw in both approaches is that you are adding probabilities instead of multiplying them.
When you are looking for either of a set of independent events, you can add their probabilities. For example, suppose that you roll a die. The probability for a 1 is 1/6, for a 2 is 1/6, etc. The probability that you roll an even number is the probability of either 2 or 4 or 6 so you can add the probability for these events: 1/6 + 1/6 + 1/6 = 1/2. This probably corresponds to you intuition: half of the possible outcomes are even.
Now suppose you throw a single die three times (or three dice at once). What is the probability that all rolls are even? We just saw that the probability for any of them to be even is 1/2. But if you try 1/2 + 1/2 + 1/2 = 3/2 > 1. Clearly this cannot be right. Indeed, what you are after is a  combination of events: you want the first roll to be even and the second to be even and the third. What you need to do is multiply the probabilities: 1/2 * 1/2 * 1/2 = 1/8.
You can check this by writing out all possible outcomes: let E denote even and O denote odd, then all possibilities for three dice rolls are
EEE                  - 1 with only evens
EEO, EOE, OEE,       - 3 with 2 evens, 1 odd
EOO, OEO, EOO        - 3 with 1 even, 2 odds
OOO                  - 1 with only odds

Do this systematically, and you will find 8 possible outcomes, of which only one is EEE -- 1/8.
With vs without replacement
There is a difference whether you pick with replacement or without replacement. Suppose you pick a marble from an urn with 5 white and 5 black marbles. Clearly the probability of drawing a white marble is 1/2. Now what is the probability that the next one will be white again? Well, this depends on what you do with the first one! If you put it back in the urn after you draw it, the probability that the second one is white is 1/2 again! But if you don't put it back, then you only have 4 out of 9 whites left, so the probability is 4/9 -- less than 1/2!
In your example with the jelly beans, you are eating them, so it is an experiment without replacement. Once you had a non-poisonous one (with probability 90/100), the chances that the next one also won't kill you are not 90/100 anymore, they are 89/99.
All possibilities or complement rule?
There are now two ways to arrive at your answer:

*

*Enumerate all the possibilities. You are asked for the probability of dying. There are a number of ways this can happen: either the first bean kills you, or (it doesn't and the second one kills you), or (the first two don't kill you but the third one does), or ....

Note how I emphasized "or" and "and"? Replace them by + and x as explained above, and you will get a long calculation:
P(first kills you)
     + P(first doesn't kill you) * P(second kills you)
     + P(first doesn't kill you) * P(second doesn't kill you) * P(third kills you)
     + ....
Plugging in the numbers, keeping in mind you are working without replacement, you get
10/100
  + 90/100 * 10/99
  + 90/100 * 89/99 * 10/98
  + ...

*Use the complement rule. Sometimes it is easier to calculate the probability of the event you are not interested in. You know that either the 10 beans kill you or they don't, so
P(you die) + P(you live) = 1
hence
P(you die) = 1 - P(you live).

We have seen that P(you die) is a long calculation, but P(you live) is easier:
P(you live) = P(the first one doesn't kill you)
                 * P(the second one doesn't kill you)
                 * P(the third one doesn't kill you)
                 * ...

Note that I used multiplication, convince yourself why (is there an implicit "and")?
Now I suggest you complete both calculations (1) and (2) and check that they give the same answer. It will be a lot of work but it will give you confidence that the basic rules I laid out work, and that there is not one right way.

A: Both probablyme and carmichael561 have given a good approach to the problem, but I thought I'd point out why the solutions given by you and your classmates (?) are erroneous.
The problem common to both approaches is that they neglect the probability that you die from earlier jelly beans.  You take the first jelly bean, and you have a $1/10$ probability of dying; that is all right.  But although your classmates are almost right (and you are not) that the second jelly bean has a $10/99$ chance of killing you, that is only true if the first jelly bean didn't already kill you.
In other words, the probability that you are killed by the first jelly bean is $1/10$, and the probability that you survive to eat a second jelly bean and it kills you is $9/10 \times 10/99 = 1/11$.  Each succeeding jelly bean does, in truth, have a higher probability of killing you if you survive to eat it, but the decreasing probability that you do in fact survive conspires to make its overall effect smaller, so the numbers do not add up to anywhere near $1$, complete certainty.
It is possible to continue along in a similar vein: You can add $1/10+1/11 = 21/110$ to obtain the probability that the first two jelly beans kill you; the remainder, $89/110$, is the probability that you survive to eat the third jelly bean, which kills you with probability $10/98$.  Your probability of surviving the first two jelly beans only to be killed by the third is then $89/110 \times 10/98 = 89/1078$.  You would then have to add up $1/10+1/11+89/1078$ to find the probability that the first three jelly beans kill you, etc.
I think you can see that the solutions provided by the other answerers are much more straightforward; this way of approaching the problem by considering its inverse is a common tactic when there are multiple ways to satisfy the conditions of the problem, but only one way to violate them.

A: So you live if you do not choose a deadly jellybean :)
And we die if we select at least one deadly bean, so I think it goes as follows
$$P(\text{Die}) = 1-P(\text{Live}) = 1-\frac{\binom{10}{0}\binom{90}{10}}{\binom{100}{10}}=0.6695237889.$$
In this case, we literally have good beans and bad beans, and we select without replacement. Then the number of bad beans selected follows a hypergeometric distribution. So for completeness, there are $\binom{10}{0}$ ways to choose a zero bad beans, $\binom{90}{10}$ ways to choose 10 good beans, and finally $\binom{100}{10}$ ways to choose 10 beans from the total.
Note: $\binom nk = \frac{n!}{k!(n-k)!}$, the binomial coefficient.

A: It's easier to find the complementary probability; i.e. the probability that all $10$ jellybeans are safe. There are ${90\choose 10}$ ways to choose $10$ safe jellybeans, and ${100\choose 10}$ to choose any $10$ jellybeans, so the probability that you survive is
$$ \frac{{90\choose 10}}{{100\choose 10}}=\frac{90\cdot 89\cdots 81}{100\cdot 99\cdots 91}$$
The probability that you die is therefore
$$ 1-\frac{90\cdot 89\cdots 81}{100\cdot 99\cdots 91}\approx 0.67$$

A: Another way to look at it, from the point of view of a dumb engineer who is not wise in mathematics is that a ballpark approximation to living is $(1-\frac{1}{10})^{10}$.  This looks a lot like $\frac{1}{e}$.  So a crude guess of the probability of dying might be $1-\frac{1}{e}\approx0.632$.  Yeah, that's sorta in the ballpark.

A: This answer looks at population probabilities and uses an iterative procedure to find the probability of living. Calculation of permutations and combinations are not used.
// multiply the probability of being alive at the start (P=1)
// by the probability of picking a non fatal jelly bean from
// the remaining jellybean population 10 times.
//
// at each iteration the initial jelly bean population (100)
// and the non fatal jelly bean population (90) both reduce by 1:
//

var P = 1;
for( var n = 0; n < 10; n = n+1)
   P = P * (90-n)/(100-n);

// complement the probability of living to get P of dying:
P = 1 - P;

// display P to eight decimal places: 0.66952379

Basically posted to show calculating the result is not difficult.

A: The solutions mentioned above are absolutely correct but here is an alternative approach.
We have to choose $10$ balls, there are ($100*99*98*97*96*95*94*93*92*91$) ways to do that but if you have to choose the non-poisonous balls there are ($90*89*88*87*86*85*84*83*82*81$) ways to do that.
Dividing the terms, you get the probability of living which comes out to be $0.33$ thus probability of dying being close to $0.67$


text:
Q: How to call figures automatically for print and web with different file namings but in the same Art folder I'm using 2 types of figures; colour figures for web and black & white for print.
But, both these files are in the same folder with the namings mentioned below.
abcdef.eps          for Print figures
abcdef_online.eps   for Web figures
During, web PDF I need to call abcdef_online.eps and for printer abcdef.eps.
Is there any automation script to pick the figures automatically for different stages from the same folder?
Please note that for web PDF, not all the figures will be in colour, for example out of 6 figures only 3 figures (1,3, and 5) are in colour.
one_online.eps
two.eps
three_online.eps
four.eps
five_online.eps
six.eps

Could any one guide me on this?

A: If you are only working with a compilation sequence that uses EPS images and supplying the image names without extension, the following redefinition of \includegraphics would work:
\usepackage{graphicx}% http://ctan.org/pkg/graphicx
\let\oldincludegraphics\includegraphics
\makeatletter
\renewcommand{\includegraphics}[2][]{%
  \IfFileExists{#2_online.eps}{\oldincludegraphics[#1]{#2_online.eps}}{% 1 Online/colour
    \oldincludegraphics[#1]{#2.eps}% 2 Regular
  }% 3
}

where you would use
\includegraphics{abcdef}
to include an image (no extension). The updated version of \includegraphics will check whether abcdef_online.eps exists, and include it, otherwise it will default to abcdef.eps. Commenting out lines 1 & 3 will remove the colour option altogether (for printed media).
The above restriction limits you to a specific compilation sequence (like LaTeX > dvips > epstopdf, for PDF output). If you wish to use pdflatex and have supplied corresponding PDF images, you can change the appropriate lines in the redefinition of \includegraphics. If you wish for the above technique to be more general in nature (and therefore work for any sequence automatically), you would have to search for the existence of files based on their extensions as indicated by the graphics driver - a little more expensive but doable.

A: It depends on how you produce the documents. Here's how I would proceed.
\documentclass{article}
\usepackage{graphicx}

\newcommand{\cincludegraphics}[2][]{%
  \ifdefined\onlineversion
    \IfFileExists{#2_online.eps}%
      {\includegraphics[#1]{#2_online}}%
      {\includegraphics[#1]{#2}}%
  \else
    \includegraphics[#1]{#2}%
  \fi
}

\begin{document}

Something with a picture

\cincludegraphics{abcdef}

\end{document}

If I compile this file, say one.tex, as
latex one

the file abcdef.eps would be loaded. If I call it with
latex -jobname one-online "\def\onlineversion{}\input{one}"

then abcdef_online.eps would be loaded (or, if non existent, abcdef.eps).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular drop down - Selected values at the top of multiselect dropdown I have a requirement to keep selected values at the top of dropdown list of a multiselect. I have kept selected values in one array (for each selected item), the original option list in another array, compared the index values and concatenated selected values to the top of array. Its working when i choose one value and not working for multiple values
html
<div>
  <ng-multiselect-dropdown  class ="ng-multiselect" [placeholder]="'Users'"
[data]="userList" [(ngModel)]="selectedUsers"  [settings]="multiSelect"
name="user" (onSelect)="onItemSelect($event)" (click)="userSelectedAtTopOnClick()">
  </ng-multiselect-dropdown>
</div>

ts
onItemSelect(user: User) {
  this.userData = user;
}

userSelectedAtTopOnClick(): void {
    this.isUserDropDownWidgetHidden = document.querySelector('.dropdown-list').hasAttribute("hidden");
    if(this.isUserDropDownWidgetHidden ) {
      this.sortUserListAfterEachSelection(this.userData);
    }
}

sortUserListAfterEachSelection(user: User) {
    let arrPartner: Partner[];
    if(origInst) {
      const index = this.userList.findIndex(element => element.partnerId === user.partnerId);
      const item: Partner = this.userList[index];
      if (index > -1) {
        arrPartner = this.userList.splice(index, 1);
        arrPartner = arrPartner.concat(this.userList);
        this.userList = arrPartner;
      }
    }
  }


text:
Q: Two way binding on attribute, knockout.js I have a button with a data-status attribute that is bind to a observable property in a viewmodel. When I click on the button the data-status attribute is changed. But it does not affect the viewmodel. How to do if I want the viewmodel to be updated with the new value?
<button id="changeStatus" data-status="0" data-bind="attr: {'data-status', Status}" />

$("#changeStatus").attr("data-status",1);

A: When working with KO, the idea is to change the viewModel and then the presentation will be changed.
So when the user clicks on the button you should change the VM:
if your VM looks like this:
var vm = function () {
var self = this;
self.status=ko.observable(false);
self.toggleStatus=function(){ self.status(!self.status()); }

}

your html should look like this:
<button id="changeStatus" data-bind="click: toggleStatus" />

if you have several buttons, you can change the function to get the obj:
var vm = function () {
var self = this;
self.status=ko.observable(false);
self.flag=ko.observable(false);
self.toggleStatus=function(data,event,obj){ self[obj](!self[obj]()); }

}

<button data-bind="click: function(d,e){ togglebutton(d,e,'status');}" />
<button data-bind="click: function(d,e){ togglebutton(d,e,'flag');}" />

let me know if you need more info


text:
Q: Was it mandatory to put a "distinct" field as the first field in a query? Just out of curiosity, looks like a distinct field must be placed ahead of any other fields, am I wrong?
See this example in SQLite,
sqlite> select ip, distinct code from parser; # syntax error?
Error: near "distinct": syntax error
sqlite> select distinct code, ip from parser; # works

Why is that? Do I really have a syntax error?

A: There is no such thing as a "distinct field".
distinct applies to all fields in the query and therefore must appear immediately after select.
In other words, select distinct code, ip is really
select distinct
code,
ip

rather than
select
distinct code,
ip

It selects all distinct pairs of (code, ip). Thus the result set could include repeated values of code (each with a different value of ip).
It is not possible to apply distinct to a single field in the way you're trying to (group by might be a useful alternative, but we need to understand what it is exactly that you're trying to achieve).


text:
Q: How to write the following MongoDB query Suppose I have the following foobar collection:
{
  "foobar": [
    {
      "_id": "abc",
      "history": [
        {
          "type": "foo",
          "timestamp": 123456789.0
        },
        {
          "type": "bar",
          "timestamp": 123456789.0
        }
      ]
    },
    {
      "_id": "dfg",
      "history": [
        {
          "type": "baz",
          "timestamp": 123456789.0
        },
        {
          "type": "bar",
          "timestamp": 123456789.0
        }
      ]
    },
    {
      "_id": "hij",
      "history": [
        {
          "type": "foo",
          "timestamp": 123456789.0
        },
        {
          "type": "bar",
          "timestamp": 123456789.0
        },
        {
          "type": "foo",
          "timestamp": 123456789.0
        }
      ]
    }
  ]
}

How can I query ($gte/$lte) the foobar items based on the timestamp prop inside their history items, but using the timestamp from the item where type: "foo"?
If there is no subdocuments with type equals to foo, the entire document is filtered out, if there is more than one subdocument with type equals to foo then it could match anyone.

A: You can try below aggregation:
var threshold = 123456788;
db.foobar.aggregate([
    {
        $addFields: {
            foobar: {
                $filter: {
                    input: "$foobar",
                    as: "doc",
                    cond: {
                        $let: {
                            vars: {
                                foo: {
                                    $arrayElemAt: [
                                        {
                                            $filter: {
                                                input: "$$doc.history",
                                                as: "history",
                                                cond: {
                                                    $eq: [ "$$history.type", "foo" ]
                                                }
                                            }
                                        },
                                        0]
                                }
                            },
                            in: {
                                $gt: [ "$$foo.timestamp", threshold ]
                            }
                        }
                    }
                }
            }
        }
    }
])

$addFields can be used to overwrite existing field (foobar). To filter out all subdocuments not matching your condition you can use $filter (the outer one). For each foobar document you can use $let to define temporary variable foo. You need inner $filter to get all history elements where type is foo and then $arrayElemAt to get first one. Then you just need $gt or $lt to apply your comparison.
For those subdocuments where there's no foo there will be undefined returned which will be then filtered out on $gt stage.


text:
Q: How do I create and persist a SQLite DB from scratch in code using System.Data.SQLite and C#? I have a database creation tool and am creating a database from scratch. This is done the same way as mentioned Here. It creates a temporary DB and I can add data to it.
When I close the database it is deleted, which is the expected behavior, but I do not want it deleted.
I cannot find a Save or Create method in System.Data.SQLite and creating one with System.IO.File.Create(myDBFilename); creates a file that SQLite cannot connect to.
How do I create and persist a database in code from scratch?

A: Try this one,
SQLiteConnection.CreateFile("c:\mydatabasefile.db3");
if all else fails, here is command line stuff as well

sqlite3 test.db
  sqlite>CREATE TABLE cars ( id INTEGER PRIMARY KEY AUTOINCREMENT, model text, year integer );
  sqlite>insert into cars( model, year ) values( "Ford 350″, 2007 );
  sqlite>insert into cars( model, year ) values( "Buick Skylark", 1953 );
  sqlite>insert into cars( model, year ) values( "Honda Civic", 2002 );
  sqlite>Select * from cars;
  1|Ford 350|2007
  2|Buick Skylark|1953
  3|Honda Civic|2002
  sqlite>.quit

A: You don't need to call the SQLiteConnection.CreateFile method.
Assuming you are opening a connection like this:
using (var connection = new SQLiteConnection("Data Source=C:\\database.db"))
{
    // foo
}

It will try to open the database file C:\\database.db if it exists, and if it doesn't exist, it will be created.

A: Assuming the use of c#-sqlite,
when you create the connection, using the appropriate API, you actually pass in tbe name of the file to use as a parameter. If the file does not exist, then it is created (by default). e.g.
new SQLiteDatabase("c:\\foo.db")

Of course, because you'll need to escape the backslashes (this is because it's a string). Creating a file beforehand does not work, because the resultant file is not an sqlite database, and therefore is not usable (so, I'm assuming you're getting an error in this case).


text:
Q: Partial derivatives + Taylor's Formula in several variables Given a function $f(x) = (x_1+...+x_n)^k$, how do we show that $$D_1^{j_1}\cdots D_n^{j_n}f(x) = k!$$
if $j_1+...+j_n = k$?

A: Simplify the problem: let $f_k(x) = x^k, g(x_1,\dots x_n) = \sum_{l=1}^n x_l$.
$\left(\sum_{l=1}^n x_l\right)^k = f\circ g(x_1,\dots,x_n)$.
Now $$
D_j  f_k\circ g(x_1,\dots,x_n) = f_k'\circ g(x_1,\dots,x_n) \times 1
=k f_{k-1}\circ g(x_1,\dots,x_n) \\= \frac{k!}{(k-1)!}
f_{k-1}\circ g(x_1,\dots,x_n)
\\
D_{1}^{j_1} \dots D_{n}^{j_n}  f_k\circ g(x_1,\dots,x_n)
=\frac{k!}{(k-\sum_{l=1}^n j_l)!}
f_{k-\sum_{l=1}^n j_l}\circ g(x_1,\dots,x_n)
$$
with an easy induction.
Now if $\sum_{l=1}^n j_l=k$ this becomes, as $f_0 = 1$:
$$
D_{1}^{j_1} \dots D_{n}^{j_n} (f_k\circ g)= k!
$$


text:
Q: Slow mail server in looking up host name Hello my mail server is very slow to accept SMTP connections.
I found a tutorial to make a stop in my Exim4 and run the command below to see where it takes.
exim -bd -d -oX 587

Follow the exit, and where is more downtime. Can you help me figure out why it is so slow.

29136 Connection request from 187.23.45.188 port 61995
29136 search_tidyup called
29136 1 SMTP accept process running
29136 Listening...
29141 sender_fullhost = [187.23.45.188]
29141 sender_rcvhost = [187.23.45.188]
29141 Process 29141 is handling incoming connection from [187.23.45.188]
29141 host in host_lookup? yes (matched "*")
29141 looking up host name for 187.23.45.188 -----> VERY SLOW HERE

A: I'am solved this problem.
I edited a file /etc/exim4/exim4.conf.template and modified this lines:
#host_lookup = *
rfc1413_hosts = *
rfc1413_query_timeout = 0s


text:
Q: Dll missing from bin for website project I have a solution , for that I am referencing to Newstonsoft Dll(reference location is a separate reference folder in side the website). Each time I delete the Bin folder & Re-build it, Newstonsoft Dll is not generating .
Tried by adding from NuGet Manager even, same case for both. Ultimately solution file is not taking the reference. can you please suggest any good way to resolve this?
N.B-->This is a Website


text:
Q: What secondary status icons are in Trillian Astra? Im using trillian astra. A secondary status icon annoys me. I have not idea what the meaning is of it. Its like a triangle, and its white-yellow. Can anyone help me to find out what it is exactly?

A: Secondary icons can be block/alert/warnings.  Perhaps you added a notification for when that user signs on - right click the contact and look for menu options to modify/delete notifications.  You may also have blocked that user.
Include a picture and it will be easier to diagnose.
You can hide all secondary icons by unchecking Trillian Prefs > Contact List > Show secondary status icons.


text:
Q: babel problems: "Unknown option `danish'" have problems with the babel options. I use Texmaker and:
\usepackage[danish]{babel}

and get this failure:
! Package babel Error: Unknown option `danish'. Either you misspelled it

What to do?
ok, I have tried this:
\documentclass[10pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[danish]{babel}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{makeidx}
\usepackage{graphicx}
\usepackage{lmodern}
\usepackage{kpfonts}
\usepackage{fourier}
\usepackage[left=2cm,right=2cm,top=2cm,bottom=2cm]{geometry}

\author{test}
\title{test}
\begin{document}
\maketitle
This is an example
\end{document}

and I got that:
LOG FILE :
This is pdfTeX, Version 3.1415926-2.5-1.40.14 (TeX Live 2013/Debian) (format=pdflatex 2014.4.26) 26 APR 2014 19:42
entering extended mode
restricted \write18 enabled.
%&-line parsing enabled.
**skanbelon.tex
(./skanbelon.tex
LaTeX2e <2011/06/27>
Babel <3.9f> and hyphenation patterns for 2 languages loaded.
(/usr/share/texlive/texmf-dist/tex/latex/base/article.cls
Document Class: article 2007/10/19 v1.4h Standard LaTeX document class
(/usr/share/texlive/texmf-dist/tex/latex/base/size10.clo
File: size10.clo 2007/10/19 v1.4h Standard LaTeX file (size option)
)
\c@part=\count79
\c@section=\count80
\c@subsection=\count81
\c@subsubsection=\count82
\c@paragraph=\count83
\c@subparagraph=\count84
\c@figure=\count85
\c@table=\count86
\abovecaptionskip=\skip41
\belowcaptionskip=\skip42
\bibindent=\dimen102
)
(/usr/share/texlive/texmf-dist/tex/latex/base/inputenc.sty
Package: inputenc 2008/03/30 v1.1d Input encoding file
\inpenc@prehook=\toks14
\inpenc@posthook=\toks15
(/usr/share/texlive/texmf-dist/tex/latex/base/latin1.def
File: latin1.def 2008/03/30 v1.1d Input encoding file
))
(/usr/share/texlive/texmf-dist/tex/generic/babel/babel.sty
Package: babel 2013/05/16 v3.9f The Babel package
! Package babel Error: Unknow option `danish'. Either you misspelled it
(babel) or the language definition file danish.ldf was not found
.
See the babel package documentation for explanation.
Type H <return> for immediate help.
...
l.293 \ProcessOptions*
Valid options are: shorthands=..., KeepShorthandsActive,
activeacute, activegrave, noconfigs, safe=, main=, math=
headfoot=, strings=, config=, or a language name.
! Package babel Error: You haven't specified a language option.
See the babel package documentation for explanation.
Type H <return> for immediate help.
...
l.326 ...ry to proceed from here, type x to quit.}
You need to specify a language, either as a global option
or as an optional argument to the \usepackage command;
You shouldn't try to proceed from here, type x to quit.
) (/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsmath.sty
Package: amsmath 2013/01/14 v2.14 AMS math features
\@mathmargin=\skip43
For additional information on amsmath, use the `?' option.
(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amstext.sty
Package: amstext 2000/06/29 v2.01
(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsgen.sty
File: amsgen.sty 1999/11/30 v2.0
\@emptytoks=\toks16
\ex@=\dimen103
))
(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsbsy.sty
Package: amsbsy 1999/11/29 v1.2d
\pmbraise@=\dimen104
)
(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsopn.sty
Package: amsopn 1999/12/14 v2.01 operator names
)
\inf@bad=\count87
LaTeX Info: Redefining \frac on input line 210.
\uproot@=\count88
\leftroot@=\count89
LaTeX Info: Redefining \overline on input line 306.
\classnum@=\count90
\DOTSCASE@=\count91
LaTeX Info: Redefining \ldots on input line 378.
LaTeX Info: Redefining \dots on input line 381.
LaTeX Info: Redefining \cdots on input line 466.
\Mathstrutbox@=\box26
\strutbox@=\box27
\big@size=\dimen105
LaTeX Font Info: Redeclaring font encoding OML on input line 566.
LaTeX Font Info: Redeclaring font encoding OMS on input line 567.
\macc@depth=\count92
\c@MaxMatrixCols=\count93
\dotsspace@=\muskip10
\c@parentequation=\count94
\dspbrk@lvl=\count95
\tag@help=\toks17
\row@=\count96
\column@=\count97
\maxfields@=\count98
\andhelp@=\toks18
\eqnshift@=\dimen106
\alignsep@=\dimen107
\tagshift@=\dimen108
\tagwidth@=\dimen109
\totwidth@=\dimen110
\lineht@=\dimen111
\@envbody=\toks19
\multlinegap=\skip44
\multlinetaggap=\skip45
\mathdisplay@stack=\toks20
LaTeX Info: Redefining \[ on input line 2665.
LaTeX Info: Redefining \] on input line 2666.
)
(/usr/share/texlive/texmf-dist/tex/latex/amsfonts/amsfonts.sty
Package: amsfonts 2013/01/14 v3.01 Basic AMSFonts support
\symAMSa=\mathgroup4
\symAMSb=\mathgroup5
LaTeX Font Info: Overwriting math alphabet `\mathfrak' in version `bold'
(Font) U/euf/m/n --> U/euf/b/n on input line 106.
)
(/usr/share/texlive/texmf-dist/tex/latex/amsfonts/amssymb.sty
Package: amssymb 2013/01/14 v3.01 AMS font symbols
)
(/usr/share/texlive/texmf-dist/tex/latex/base/makeidx.sty
Package: makeidx 2000/03/29 v1.0m Standard LaTeX package
)
(/usr/share/texlive/texmf-dist/tex/latex/graphics/graphicx.sty
Package: graphicx 1999/02/16 v1.0f Enhanced LaTeX Graphics (DPC,SPQR)
(/usr/share/texlive/texmf-dist/tex/latex/graphics/keyval.sty
Package: keyval 1999/03/16 v1.13 key=value parser (DPC)
\KV@toks@=\toks21
)
(/usr/share/texlive/texmf-dist/tex/latex/graphics/graphics.sty
Package: graphics 2009/02/05 v1.0o Standard LaTeX Graphics (DPC,SPQR)
(/usr/share/texlive/texmf-dist/tex/latex/graphics/trig.sty
Package: trig 1999/03/16 v1.09 sin cos tan (DPC)
)
(/usr/share/texlive/texmf-dist/tex/latex/latexconfig/graphics.cfg
File: graphics.cfg 2010/04/23 v1.9 graphics configuration of TeX Live
)
Package graphics Info: Driver file: pdftex.def on input line 91.
(/usr/share/texlive/texmf-dist/tex/latex/pdftex-def/pdftex.def
File: pdftex.def 2011/05/27 v0.06d Graphics/color for pdfTeX
(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/infwarerr.sty
Package: infwarerr 2010/04/08 v1.3 Providing info/warning/error messages (HO)
)
(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/ltxcmds.sty
Package: ltxcmds 2011/11/09 v1.22 LaTeX kernel commands for general use (HO)
)
\Gread@gobject=\count99
))
\Gin@req@height=\dimen112
\Gin@req@width=\dimen113
)
! LaTeX Error: File `lmodern.sty' not found.
Type X to quit or <RETURN> to proceed,
or enter new name. (Default extension: sty)
Enter file name:
! Emergency stop.
<read *>
l.10 \usepackage
{kpfonts}^^M
*** (cannot \read from terminal in nonstop modes)
Here is how much of TeX's memory you used:
1796 strings out of 495031
21907 string characters out of 6181531
72089 words of memory out of 5000000
5027 multiletter control sequences out of 15000+600000
3640 words of font info for 14 fonts, out of 8000000 for 9000
14 hyphenation exceptions out of 8191
27i,0n,24p,241b,36s stack positions out of 5000i,500n,10000p,200000b,80000s
! ==> Fatal error occurred, no output PDF file produced!

I use Linux Mint Cinammon Petra 16 and have installed LaTeX so:
sudo apt-get install texmaker
sudo apt-get install texlive-full

Ok, i tried this at the very beginning:
    sudo apt-get install texlive-base
And after that I intalled texlive-full
Thanks for the useful solutions (see answers).
SOLUTION:
sudo apt-get install update


text:
Q: Event with function components I have just started learning REACT and has taken some courses online. I have created a very simple function component, and I want to implement an event, that the parent components can consume. I can find a lot of samples and articles on the net on how to do this using bind (int the constructor) with class components. However I have not found any articles on function components. Anyone has a simple sample or article on how to do this? In general I see many recommendations on using function components over class components, but much more articles and frameworks where people are using class components. Are function components fairly new?
import React, { useState } from "react";
import {
  Dropdown,
  DropdownToggle,
  DropdownMenu,
  DropdownItem,
  Button
} from "reactstrap";

const DropdownPaging = props => {
  const [selectedValue, setSelectedValue] = useState(10);
  const [dropdownOpen, setDropdownOpen] = useState(false);

  const toggle = () => setDropdownOpen(prevState => !prevState);

  function dropDownChanged(val) {
    setSelectedValue(val);
  }

  return (

            <Button outline color="dark">
              <
            </Button>

            <Button outline color="dark">
              >
            </Button>

            <Dropdown isOpen={dropdownOpen} toggle={toggle}>
              <DropdownToggle caret outline color="dark">
                {selectedValue}
              </DropdownToggle>
              <DropdownMenu>
                <DropdownItem onClick={() => dropDownChanged(10)}>
                  10
                </DropdownItem>
                <DropdownItem onClick={() => dropDownChanged(25)}>
                  25
                </DropdownItem>
                <DropdownItem onClick={() => dropDownChanged(50)}>
                  50
                </DropdownItem>
                <DropdownItem onClick={() => dropDownChanged(100)}>
                  100
                </DropdownItem>
              </DropdownMenu>
            </Dropdown>

  );
};

export default DropdownPaging;

A: No, functional components are there from a long back, One of the feature that functional components got new  is handling the state and life cycle method
So before the version of 16.8, functional components were purely used to render the presentational part, so it can't handle state or handle life cycle methods
So when dealing with big applications the problem was if you need to have a single state variable you need to change the functional components to class components
So then after the release of 16.8 react team introduced hooks, so now you can handle state and life cycle methods with the help of hooks
How it came to hooks is basically

*

*Render Props - Sharing Code between components - here

*Hoc Components - Reusing component logic - here
You can read more on here about hooks.
Example of using hooks

*

*Async data loading - here

*Using state - here

*Rendering table data and disabling the row based on state key - here

*Custom Hook - window resize - here
If you are updating and trying above codesandbox fork it and update. (It will be helpful for others :) )


text:
Q: Can a conditional statement apply to part of a slug? Is there a way (and if so, 'how?') to apply a conditional to a page/post for which the slug contains a specific word.
In the case of the Codex example of:
is_single( 'beef-stew' )

The condition will still apply if the slug contains 'beef', rather than being 'beef-stew'.
UPDATE: In response to a request for context...
I have a nav-menu which uses a conditional statement (example below) to apply a css class to an item when it's the page being viewed.
 <?php if (is_single('mon')) { echo " class=\"current\""; }?>

In the example above 'mon' is 'monday', with similar for other days in a weekly schedule. By adding to a template, it can be used for any day provided I set an appropriate slug... an example of which is to use 'mon' instead of 'Monday April 4'.
I want to apply the condition to just part of the slug, thus saving the time of manually modifying the slug prior to saving... and also removing the situation of mis-function if I forget to do so.

A: WordPress has no conditional for substring testing but you can do this using PHPs built-in function: strpos()
global $post;

if( false !== strpos( $post->post_name, 'beef' ) ) {
    // Do Things
}

The above returns true if beef is found somewhere in the post slug.

A: In a similar way as @Howdy_McGee, we might try to construct an helper function:
/**
 * @param $s String
 * @return bool
 */
function queried_post_name_contains_wpse247782( $s )
{
    $obj = get_queried_object();

    return     $obj instanceof \WP_Post // Make sure it's a post object
            && false !== strpos( $obj->post_name, $s ); // post name contains it
}

and use it like:
if( is_single() && queried_post_name_contains_wpse247782( 'beef' ) )
{
    // ...
}

Hope you can extend it futher to your needs!


text:
Q: Centering elements with margin/padding using .outerWidth()/.outerHeight(). Function returns different values for margin and padding i am attempting to center elements both laterally and vertically in their parent elements by calculating the difference in width and height of parent and child element and the using difference as either margin or padding.
I am calculating the necessary space using this formula:
($outerElement.outerWidth() - $innerElement.outerWidth() / 2;
($outerElement.outerHeight() - $innerElement.outerHeight() / 2;

I then loop over an array of directions using a function that allows me to change css applied to the child element using a function argument. Basically the function allows me to choose if i want to use margin or padding.
The Problem
While my code returns the expected values for top, right, left, and bottom it does not do so using padding? Any idea what is causing this?
HTML

CSS
    html {
      box-sizing: border-box;
    }
    *, *:before, *:after {
      box-sizing: inherit;
    }

.outer {
      width:500px;
      height:200px;
      border:1px solid black;
      margin:20px;
    }

    .inner {
      width:100px;
      height:100px;
      background-color:grey;
    }

JAVASCRIPT
var $outer = $(".outer");
var $inner = $(".inner");

var getSpace = function(axis)  {

  if (axis.toLowerCase() == "x") {

    return ($outer.outerWidth() - $inner.outerWidth()) / 2;

  } else if (axis.toLowerCase() == "y") {

    return ($outer.outerHeight() - $inner.outerHeight()) / 2;

  }

}

var renderStyle = function(spacingType) {

  $.each(["top", "right", "bottom", "left"], function(index, direction) {

    if (direction == "top" || direction == "bottom") {

      $inner.css(spacingType + "-" + direction, getSpace("y"));

      console.log(getSpace("y"));

    } else if (direction == "right" || direction == "left") {

      $inner.css(spacingType + "-" + direction, getSpace("x"));

      console.log(getSpace("x"));

    }

  });

};

renderStyle("padding");

CODEPEN LINK - link

A: This is happening because you are setting padding to the inner box instead of the outer one.
You can set it using an if condition.
Here's the working snippet. You can test it for both renderStyle("margin"); and renderStyle("padding");

var $outer = $(".outer");
var $inner = $(".inner");

var getSpace = function(axis)  {
  if (axis.toLowerCase() == "x") {
    return ($outer.outerWidth() - $inner.outerWidth()) / 2;
  }
  else if (axis.toLowerCase() == "y") {
    return ($outer.outerHeight() - $inner.outerHeight()) / 2;
  }
}

var renderStyle = function(spacingType) {
  var xi = getSpace("x");
  var yi = getSpace("y");
  if (spacingType == "padding") {
      var $ei = $outer;
  } else if (spacingType == "margin") {
      var $ei = $inner;
    }
  $.each(["top", "right", "bottom", "left"], function(index, direction) {
    if (direction == "top" || direction == "bottom") {
      $ei.css(spacingType + "-" + direction, yi);
    }
    else if (direction == "right" || direction == "left") {
      $ei.css(spacingType + "-" + direction, xi);
    }
  });
};

renderStyle("padding");
.outer {
  width:400px;
  height:200px;
  border:1px solid black;
  margin:20px;
  box-sizing:border-box;
}
.inner {
  width:100px;
  height:100px;
  background-color:grey;
}


text:
Q: Implementing custom atomic_add() which works with floats I'm trying to follow the B.12 section of https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html for atomic add, which works with floats. Simply copying and pasting the code from there and changing the types to floats does not work because I can't perform the casting pointer casting from GLOBAL to PRIVATE, required for the atomicCAS operation. To overcome this I decided to use atomic_xchg() because it works with floats, with additional if statement to achieve same functionality as atomicCAS. However, this returns me varying answer when I perform addition on large float vector every time i run the program.
I've tried figuring out how to overcome the explicit conversion from GLOBAL to PRIVATE, but I honestly don't know how to do it so that when I perform addition, the address argument is changed instead of some temp variable.
kernel void atomicAdd_2(volatile global float* address, float value)
{
    float old = *address, assumed;

    do {
        assumed = old;
        if (*address == assumed) {
            old = atomic_xchg(address, value + assumed);
        }
        else{
            old = *address;
        }
        // Note: uses integer comparison to avoid hang in case of NaN (since NaN != NaN)
    } while (assumed != old);
}

This is my implementation of atomicAdd for floats.
kernel void reduce_add(global const float* input, global float* output) {
         float temp = 242.23f;
         atomicAdd_floats(&output[0], temp);
         printf(" %f ", output[0]);

}

This is the function where I supply the arguments to the atomicAdd_floats. Note that my input argument contains a vector of floats and output argument is simply where I want to store the result, specifically in the first element of the output vector output[0]; but instead when i printf(" %f ", output[0]); it shows my default initialisation value 0.

A: First of all, i'd suggest to remove the "kernel" keyword on the atomicAdd_2 function. "kernel" should be used only on functions you intend to enqueue from the host. 2nd, there are OpenCL implementations of atomic-add-float on the net.
Then, i'm a bit confused as to what you're trying to do. Are you trying to sum a vector and while having the sum in a private variable ? if so, it makes no sense to use atomicAdd. Private memory is always atomic, because it's private. Atomicity is only required for global and local memories because they're shared.
Otherwise i'm not sure why you mention changing the address or the GLOBAL to PRIVATE.
Anyway, the code from the link should work, though it's relatively slow. If the vector to sum is large, you might be better off using a different algorithm (wtth partial sums). Try googling "opencl parallel sum" or such.


text:
Q: TextBox.SelectAll() does not work with TAB I am using maskedTextBox.SelectAll() to highlight the text in the MaskedTextBox in the Enter and MouseDown events.
It works when I use the mouse, but I go to that textbox by pressing the Tab key, it does not work.
What am I missing here?

A: Have you tried the GotFocus event?

When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order:

It then goes on to list the events that are fired. It looks like this fires when the mouse is used so you might only need this handler.


text:
Q: TypeError: evaluate_model() missing 1 required positional argument: 'n_input'     enterscores=evaluate_model(test,14)

TypeError                                 Traceback (most recent call last)
<ipython-input-68-c17f426490bf> in <module>()
----> 1 scores=evaluate_model(test,14)

TypeError: evaluate_model() missing 1 required positional argument: 'n_input'


text:
Q: Unable to render navigation menu in angular 1 using nested json data I want to implement a navigation bar using json data which is fetched by angular service. I ave my service and controller working great, but I am unable to render the nested json data into my view.
Below is my json data:
{
    "menu": [
        {
            "name": "Electronics",
            "link": "1",
            "sub": [
                {
                    "name": "Mobiles",
                    "link": "1.1",
                    "sub": [
                        {
                            "name": "Samsung",
                            "link": "1.1.1",
                            "sub": null
                        },
                        {
                            "name": "Apple",
                            "link": "1.1.2",
                            "sub": null
                        },
                        {
                            "name": "Motorola",
                            "link": "1.1.3",
                            "sub": null
                        },
                        {
                            "name": "Lenovo",
                            "link": "1.1.4",
                            "sub": null
                        },
                        {
                            "name": "Mi",
                            "link": "1.1.5",
                            "sub": null
                        },
                        {
                            "name": "Micromax",
                            "link": "1.1.6",
                            "sub": null
                        },
                        {
                            "name": "Oppo",
                            "link": "1.1.7",
                            "sub": null
                        },
                        {
                            "name": "Vivo",
                            "link": "1.1.8",
                            "sub": null
                        },
                        {
                            "name": "HTC",
                            "link": "1.1.9",
                            "sub": null
                        }
                    ]
                },
                {
                    "name": "Mobile Accessories",
                    "link": "1.2",
                    "sub": [ ]
                },
                {
                    "name": "Laptop",
                    "link": "1.3",
                    "sub": [ ]
                },
                {
                    "name": "Laptop Accessories",
                    "link": "1.4",
                    "sub": [ ]
                },
                {
                    "name": "Appliances",
                    "link": "1.5",
                    "sub": [ ]
                }
            ]
        },
        {
            "name": "Men",
            "link": "2",
            "sub": [ ]
        },
        {
            "name": "Women",
            "link": "3",
            "sub": [ ]
        },
        {
            "name": "Baby & Kids",
            "link": "4",
            "sub": [ ]
        },
        {
            "name": "Home & Furniture",
            "link": "5",
            "sub": [ ]
        },
        {
            "name": "Books & More",
            "link": "6",
            "sub": [ ]
        }
    ]
}

I am getting all the data in the console successfully, I just want help in rendering the data in the view using ng-repeat.
For reference, below is the controller and Factory
Factory:
( function ()
{
    angular.module( "myApp" )
    .factory( "navService", function ( $http )
    {
        function getNavItems()
        {
            return $http.get( '../data/navData.json' );
        };
        return {
            getNavItems: getNavItems
    };
} );
}()

Controller:
( function ()
{
    angular.module( "myApp" )
    .controller( "NavController", function ( $scope, $http, navService )
    {
        navService.getNavItems().then( function ( menu )
        {
            $scope.menu = menu.data;
            console.log( menu.data );
        } );
    } );
} ());

Thanks.

A: It should be,
  navService.getNavItems().then( function ( response)
  {
       $scope.menu = response.data.menu;
  });

A: I have produce the same issues in my local and i am getting the error. but i tried to solve it and i have done.
you are using the controller name with camel case. so it's necessary to define use strict; at top of the controller and services JavaScript file.
Here is solution code.
Json Data file : navData.json
{
    "menu": [
        {
            "name": "Electronics",
            "link": "1",
            "sub": [
                {
                    "name": "Mobiles",
                    "link": "1.1",
                    "sub": [
                        {
                            "name": "Samsung",
                            "link": "1.1.1",
                            "sub": null
                        },
                        {
                            "name": "Apple",
                            "link": "1.1.2",
                            "sub": null
                        },
                        {
                            "name": "Motorola",
                            "link": "1.1.3",
                            "sub": null
                        },
                        {
                            "name": "Lenovo",
                            "link": "1.1.4",
                            "sub": null
                        },
                        {
                            "name": "Mi",
                            "link": "1.1.5",
                            "sub": null
                        },
                        {
                            "name": "Micromax",
                            "link": "1.1.6",
                            "sub": null
                        },
                        {
                            "name": "Oppo",
                            "link": "1.1.7",
                            "sub": null
                        },
                        {
                            "name": "Vivo",
                            "link": "1.1.8",
                            "sub": null
                        },
                        {
                            "name": "HTC",
                            "link": "1.1.9",
                            "sub": null
                        }
                    ]
                },
                {
                    "name": "Mobile Accessories",
                    "link": "1.2",
                    "sub": [ ]
                },
                {
                    "name": "Laptop",
                    "link": "1.3",
                    "sub": [ ]
                },
                {
                    "name": "Laptop Accessories",
                    "link": "1.4",
                    "sub": [ ]
                },
                {
                    "name": "Appliances",
                    "link": "1.5",
                    "sub": [ ]
                }
            ]
        },
        {
            "name": "Men",
            "link": "2",
            "sub": [ ]
        },
        {
            "name": "Women",
            "link": "3",
            "sub": [ ]
        },
        {
            "name": "Baby & Kids",
            "link": "4",
            "sub": [ ]
        },
        {
            "name": "Home & Furniture",
            "link": "5",
            "sub": [ ]
        },
        {
            "name": "Books & More",
            "link": "6",
            "sub": [ ]
        }
    ]
}

index.html

        <title>Angular js</title>

Stackover flow Answer

Example use $scope out side from controller.

app.js
"use strict";
var app = angular.module("myApp", []);

app.controller("NavController", function($scope, $http, navService){
    navService.getNavItems().then( function ( menu ){
        $scope.menu = menu.data;
        console.log( menu.data );
    });
});

services.js
"use strict";
app.factory( "navService", function ( $http ){
    function getNavItems(){
        return $http.get( 'data/navData.json' );
    };
    return {
        getNavItems: getNavItems
    };
});


text:
Q: Javascript element visible in viewport WITHOUT margins I am using the following JavaScript to determine wether an element is visible in the current viewport or not. However, this does not take margins and paddings into account.   Can someone help me to modify this to return true, if the 'real' element is visible so margins and paddings are ignored?
Actual JS:
(function ($) {
        $.fn.visible = function (partial) {

            var $t = $(this),
                $w = $(window),
                viewTop = $w.scrollTop(),
                viewBottom = viewTop + $w.height(),
                _top = $t.offset().top,
                _bottom = _top + $t.height(),
                compareTop = partial === true ? _bottom : _top,
                compareBottom = partial === true ? _top : _bottom;

            return compareBottom <= viewBottom && compareTop >= viewTop;
        };
    })(jQuery);

    var win = $(window);

    var allModifications = $(".animation-listener");

    //make all elements visible that are directly visible
    allModifications.each(function (i, el) {
        console.log("loaded js");
        var el = $(el);
        if (el.visible(true)) {
            el.find(".half-width-text").addClass("open");
        }
    });

    //make elements visible that get scrolled into the viewport
    win.scroll(function (event) {
        var current = 1;
        allModifications.each(function (i, el) {
            var el = $(el);
            if (el.visible(true)) {
                el.addClass("animate");
            }
        });
    });

A: Instead of using height() use outerHeight(true). This method returns the current computed outer height (including padding, border, and optionally margin) for the first element in the set of matched elements or set the outer height of every matched element.
http://api.jquery.com/outerheight/


text:
Q: Redis periodically stops responding on high load I am using a simple redis server setup to store some values in my PHP application. Yesterday I installed phpredis module to use redis as PHP Session backend, which increased request rate on redis DB form 100 to 2000, and DB size from 60Mb to 200Mb.
And after this, redis is not avalable on every 10th request - just not responding. Log file does not show anything that could explain this.
I have more than 50% of memory free. Here are the resources used by redis:
  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
31075 root      20   0  170m 161m  936 S   41  2.0  11:10.52 redis-server

What can be the cause of this? Maybe I should tweak some redis settings for higher load?
Here is my redis.conf:
# Redis configuration file example

# Note on units: when memory size is needed, it is possible to specifiy
# it in the usual form of 1k 5GB 4M and so forth:
#
# 1k => 1000 bytes
# 1kb => 1024 bytes
# 1m => 1000000 bytes
# 1mb => 1024*1024 bytes
# 1g => 1000000000 bytes
# 1gb => 1024*1024*1024 bytes
#
# units are case insensitive so 1GB 1Gb 1gB are all the same.

# By default Redis does not run as a daemon. Use 'yes' if you need it.
# Note that Redis will write a pid file in /var/run/redis.pid when daemonized.
daemonize no

# When running daemonized, Redis writes a pid file in /var/run/redis.pid by
# default. You can specify a custom pid file location here.
pidfile /var/run/redis.pid

# Accept connections on the specified port, default is 6379.
# If port 0 is specified Redis will not listen on a TCP socket.
port 6379

# If you want you can bind a single interface, if the bind option is not
# specified all the interfaces will listen for incoming connections.
#
# bind 127.0.0.1

# Specify the path for the unix socket that will be used to listen for
# incoming connections. There is no default, so Redis will not listen
# on a unix socket when not specified.
#
# unixsocket /tmp/redis.sock

# Close the connection after a client is idle for N seconds (0 to disable)
timeout 300

# Set server verbosity to 'debug'
# it can be one of:
# debug (a lot of information, useful for development/testing)
# verbose (many rarely useful info, but not a mess like the debug level)
# notice (moderately verbose, what you want in production probably)
# warning (only very important / critical messages are logged)
loglevel debug

# Specify the log file name. Also 'stdout' can be used to force
# Redis to log on the standard output. Note that if you use standard
# output for logging but daemonize, logs will be sent to /dev/null
logfile /var/log/redis/redis.log

# To enable logging to the system logger, just set 'syslog-enabled' to yes,
# and optionally update the other syslog parameters to suit your needs.
# syslog-enabled no

# Specify the syslog identity.
# syslog-ident redis

# Specify the syslog facility.  Must be USER or between LOCAL0-LOCAL7.
# syslog-facility local0

# Set the number of databases. The default database is DB 0, you can select
# a different one on a per-connection basis using SELECT <dbid> where
# dbid is a number between 0 and 'databases'-1
databases 16

################################ SNAPSHOTTING  #################################
#
# Save the DB on disk:
#
#   save <seconds> <changes>
#
#   Will save the DB if both the given number of seconds and the given
#   number of write operations against the DB occurred.
#
#   In the example below the behaviour will be to save:
#   after 900 sec (15 min) if at least 1 key changed
#   after 300 sec (5 min) if at least 10 keys changed
#   after 60 sec if at least 10000 keys changed
#
#   Note: you can disable saving at all commenting all the "save" lines.

save 900 1
save 300 10
save 60 10000

# Compress string objects using LZF when dump .rdb databases?
# For default that's set to 'yes' as it's almost always a win.
# If you want to save some CPU in the saving child set it to 'no' but
# the dataset will likely be bigger if you have compressible values or keys.
rdbcompression yes

# The filename where to dump the DB
dbfilename dump.rdb

# The working directory.
#
# The DB will be written inside this directory, with the filename specified
# above using the 'dbfilename' configuration directive.
#
# Also the Append Only File will be created inside this directory.
#
# Note that you must specify a directory here, not a file name.
dir /backups/redisdumps

################################# REPLICATION #################################

# Master-Slave replication. Use slaveof to make a Redis instance a copy of
# another Redis server. Note that the configuration is local to the slave
# so for example it is possible to configure the slave to save the DB with a
# different interval, or to listen to another port, and so on.
#
# slaveof <masterip> <masterport>

# If the master is password protected (using the "requirepass" configuration
# directive below) it is possible to tell the slave to authenticate before
# starting the replication synchronization process, otherwise the master will
# refuse the slave request.
#
# masterauth <master-password>

# When a slave lost the connection with the master, or when the replication
# is still in progress, the slave can act in two different ways:
#
# 1) if slave-serve-stale-data is set to 'yes' (the default) the slave will
#    still reply to client requests, possibly with out of data data, or the
#    data set may just be empty if this is the first synchronization.
#
# 2) if slave-serve-stale data is set to 'no' the slave will reply with
#    an error "SYNC with master in progress" to all the kind of commands
#    but to INFO and SLAVEOF.
#
slave-serve-stale-data yes

################################## SECURITY ###################################

# Require clients to issue AUTH <PASSWORD> before processing any other
# commands.  This might be useful in environments in which you do not trust
# others with access to the host running redis-server.
#
# This should stay commented out for backward compatibility and because most
# people do not need auth (e.g. they run their own servers).
#
# Warning: since Redis is pretty fast an outside user can try up to
# 150k passwords per second against a good box. This means that you should
# use a very strong password otherwise it will be very easy to break.
#
# requirepass foobared

# Command renaming.
#
# It is possilbe to change the name of dangerous commands in a shared
# environment. For instance the CONFIG command may be renamed into something
# of hard to guess so that it will be still available for internal-use
# tools but not available for general clients.
#
# Example:
#
# rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52
#
# It is also possilbe to completely kill a command renaming it into
# an empty string:
#
# rename-command CONFIG ""

################################### LIMITS ####################################

# Set the max number of connected clients at the same time. By default there
# is no limit, and it's up to the number of file descriptors the Redis process
# is able to open. The special value '0' means no limits.
# Once the limit is reached Redis will close all the new connections sending
# an error 'max number of clients reached'.
#
# maxclients 128

# Don't use more memory than the specified amount of bytes.
# When the memory limit is reached Redis will try to remove keys with an
# EXPIRE set. It will try to start freeing keys that are going to expire
# in little time and preserve keys with a longer time to live.
# Redis will also try to remove objects from free lists if possible.
#
# If all this fails, Redis will start to reply with errors to commands
# that will use more memory, like SET, LPUSH, and so on, and will continue
# to reply to most read-only commands like GET.
#
# WARNING: maxmemory can be a good idea mainly if you want to use Redis as a
# 'state' server or cache, not as a real DB. When Redis is used as a real
# database the memory usage will grow over the weeks, it will be obvious if
# it is going to use too much memory in the long run, and you'll have the time
# to upgrade. With maxmemory after the limit is reached you'll start to get
# errors for write operations, and this may even lead to DB inconsistency.
#
# maxmemory <bytes>

# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory
# is reached? You can select among five behavior:
#
# volatile-lru -> remove the key with an expire set using an LRU algorithm
# allkeys-lru -> remove any key accordingly to the LRU algorithm
# volatile-random -> remove a random key with an expire set
# allkeys->random -> remove a random key, any key
# volatile-ttl -> remove the key with the nearest expire time (minor TTL)
# noeviction -> don't expire at all, just return an error on write operations
#
# Note: with all the kind of policies, Redis will return an error on write
#       operations, when there are not suitable keys for eviction.
#
#       At the date of writing this commands are: set setnx setex append
#       incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd
#       sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby
#       zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby
#       getset mset msetnx exec sort
#
# The default is:
#
# maxmemory-policy volatile-lru

# LRU and minimal TTL algorithms are not precise algorithms but approximated
# algorithms (in order to save memory), so you can select as well the sample
# size to check. For instance for default Redis will check three keys and
# pick the one that was used less recently, you can change the sample size
# using the following configuration directive.
#
# maxmemory-samples 3

############################## APPEND ONLY MODE ###############################

# By default Redis asynchronously dumps the dataset on disk. If you can live
# with the idea that the latest records will be lost if something like a crash
# happens this is the preferred way to run Redis. If instead you care a lot
# about your data and don't want to that a single record can get lost you should
# enable the append only mode: when this mode is enabled Redis will append
# every write operation received in the file appendonly.aof. This file will
# be read on startup in order to rebuild the full dataset in memory.
#
# Note that you can have both the async dumps and the append only file if you
# like (you have to comment the "save" statements above to disable the dumps).
# Still if append only mode is enabled Redis will load the data from the
# log file at startup ignoring the dump.rdb file.
#
# IMPORTANT: Check the BGREWRITEAOF to check how to rewrite the append
# log file in background when it gets too big.

appendonly no

# The name of the append only file (default: "appendonly.aof")
# appendfilename appendonly.aof

# The fsync() call tells the Operating System to actually write data on disk
# instead to wait for more data in the output buffer. Some OS will really flush
# data on disk, some other OS will just try to do it ASAP.
#
# Redis supports three different modes:
#
# no: don't fsync, just let the OS flush the data when it wants. Faster.
# always: fsync after every write to the append only log . Slow, Safest.
# everysec: fsync only if one second passed since the last fsync. Compromise.
#
# The default is "everysec" that's usually the right compromise between
# speed and data safety. It's up to you to understand if you can relax this to
# "no" that will will let the operating system flush the output buffer when
# it wants, for better performances (but if you can live with the idea of
# some data loss consider the default persistence mode that's snapshotting),
# or on the contrary, use "always" that's very slow but a bit safer than
# everysec.
#
# If unsure, use "everysec".

# appendfsync always
appendfsync everysec
# appendfsync no

# When the AOF fsync policy is set to always or everysec, and a background
# saving process (a background save or AOF log background rewriting) is
# performing a lot of I/O against the disk, in some Linux configurations
# Redis may block too long on the fsync() call. Note that there is no fix for
# this currently, as even performing fsync in a different thread will block
# our synchronous write(2) call.
#
# In order to mitigate this problem it's possible to use the following option
# that will prevent fsync() from being called in the main process while a
# BGSAVE or BGREWRITEAOF is in progress.
#
# This means that while another child is saving the durability of Redis is
# the same as "appendfsync none", that in pratical terms means that it is
# possible to lost up to 30 seconds of log in the worst scenario (with the
# default Linux settings).
#
# If you have latency problems turn this to "yes". Otherwise leave it as
# "no" that is the safest pick from the point of view of durability.
no-appendfsync-on-rewrite no

################################## SLOW LOG ###################################

# The Redis Slow Log is a system to log queries that exceeded a specified
# execution time. The execution time does not include the I/O operations
# like talking with the client, sending the reply and so forth,
# but just the time needed to actually execute the command (this is the only
# stage of command execution where the thread is blocked and can not serve
# other requests in the meantime).
#
# You can configure the slow log with two parameters: one tells Redis
# what is the execution time, in microseconds, to exceed in order for the
# command to get logged, and the other parameter is the length of the
# slow log. When a new command is logged the oldest one is removed from the
# queue of logged commands.

# The following time is expressed in microseconds, so 1000000 is equivalent
# to one second. Note that a negative number disables the slow log, while
# a value of zero forces the logging of every command.
slowlog-log-slower-than 10000

# There is no limit to this length. Just be aware that it will consume memory.
# You can reclaim memory used by the slow log with SLOWLOG RESET.
slowlog-max-len 1024

################################ VIRTUAL MEMORY ###############################

### WARNING! Virtual Memory is deprecated in Redis 2.4
### The use of Virtual Memory is strongly discouraged.

# Virtual Memory allows Redis to work with datasets bigger than the actual
# amount of RAM needed to hold the whole dataset in memory.
# In order to do so very used keys are taken in memory while the other keys
# are swapped into a swap file, similarly to what operating systems do
# with memory pages.
#
# To enable VM just set 'vm-enabled' to yes, and set the following three
# VM parameters accordingly to your needs.

vm-enabled no
# vm-enabled yes

# This is the path of the Redis swap file. As you can guess, swap files
# can't be shared by different Redis instances, so make sure to use a swap
# file for every redis process you are running. Redis will complain if the
# swap file is already in use.
#
# The best kind of storage for the Redis swap file (that's accessed at random)
# is a Solid State Disk (SSD).
#
# *** WARNING *** if you are using a shared hosting the default of putting
# the swap file under /tmp is not secure. Create a dir with access granted
# only to Redis user and configure Redis to create the swap file there.
vm-swap-file /tmp/redis.swap

# vm-max-memory configures the VM to use at max the specified amount of
# RAM. Everything that deos not fit will be swapped on disk *if* possible, that
# is, if there is still enough contiguous space in the swap file.
#
# With vm-max-memory 0 the system will swap everything it can. Not a good
# default, just specify the max amount of RAM you can in bytes, but it's
# better to leave some margin. For instance specify an amount of RAM
# that's more or less between 60 and 80% of your free RAM.
vm-max-memory 0

# Redis swap files is split into pages. An object can be saved using multiple
# contiguous pages, but pages can't be shared between different objects.
# So if your page is too big, small objects swapped out on disk will waste
# a lot of space. If you page is too small, there is less space in the swap
# file (assuming you configured the same number of total swap file pages).
#
# If you use a lot of small objects, use a page size of 64 or 32 bytes.
# If you use a lot of big objects, use a bigger page size.
# If unsure, use the default :)
vm-page-size 32

# Number of total memory pages in the swap file.
# Given that the page table (a bitmap of free/used pages) is taken in memory,
# every 8 pages on disk will consume 1 byte of RAM.
#
# The total swap size is vm-page-size * vm-pages
#
# With the default of 32-bytes memory pages and 134217728 pages Redis will
# use a 4 GB swap file, that will use 16 MB of RAM for the page table.
#
# It's better to use the smallest acceptable value for your application,
# but the default is large in order to work in most conditions.
vm-pages 134217728

# Max number of VM I/O threads running at the same time.
# This threads are used to read/write data from/to swap file, since they
# also encode and decode objects from disk to memory or the reverse, a bigger
# number of threads can help with big objects even if they can't help with
# I/O itself as the physical device may not be able to couple with many
# reads/writes operations at the same time.
#
# The special value of 0 turn off threaded I/O and enables the blocking
# Virtual Memory implementation.
vm-max-threads 4

############################### ADVANCED CONFIG ###############################

# Hashes are encoded in a special way (much more memory efficient) when they
# have at max a given numer of elements, and the biggest element does not
# exceed a given threshold. You can configure this limits with the following
# configuration directives.
hash-max-zipmap-entries 512
hash-max-zipmap-value 64

# Similarly to hashes, small lists are also encoded in a special way in order
# to save a lot of space. The special representation is only used when
# you are under the following limits:
list-max-ziplist-entries 512
list-max-ziplist-value 64

# Sets have a special encoding in just one case: when a set is composed
# of just strings that happens to be integers in radix 10 in the range
# of 64 bit signed integers.
# The following configuration setting sets the limit in the size of the
# set in order to use this special memory saving encoding.
set-max-intset-entries 512

# Active rehashing uses 1 millisecond every 100 milliseconds of CPU time in
# order to help rehashing the main Redis hash table (the one mapping top-level
# keys to values). The hash table implementation redis uses (see dict.c)
# performs a lazy rehashing: the more operation you run into an hash table
# that is rhashing, the more rehashing "steps" are performed, so if the
# server is idle the rehashing is never complete and some more memory is used
# by the hash table.
#
# The default is to use this millisecond 10 times every second in order to
# active rehashing the main dictionaries, freeing memory when possible.
#
# If unsure:
# use "activerehashing no" if you have hard latency requirements and it is
# not a good thing in your environment that Redis can reply form time to time
# to queries with 2 milliseconds delay.
#
# use "activerehashing yes" if you don't have such hard requirements but
# want to free memory asap when possible.
activerehashing yes

################################## INCLUDES ###################################

# Include one or more other config files here.  This is useful if you
# have a standard template that goes to all redis server but also need
# to customize a few per-server settings.  Include files can include
# other files, so use this wisely.
#
# include /path/to/local.conf
# include /path/to/other.conf

A: We found if you use aof persistance along with rdb snapshots, sometimes the rdb updating can delay the aof being updated, which in turn causes writes to redis to block. Turning off aof persistance cured the intermittant latency we were having, which was ok for us as loosing the latest few keys due to a crash was not to important.

A: Seems that I have found a solution here: http://redis4you.com/articles.php?id=012&name=redis
On linux you should change kernel settings, to optimize TCP operations for high load:
echo 1 > /proc/sys/net/ipv4/tcp_tw_reuse
echo 1 > /proc/sys/net/ipv4/tcp_tw_recycle

And also, make those changes persistant after reboot by adding fallowing to /etc/sysctl.conf:
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1

Additionaly, it helped to set timeout to 0 in redis.conf:
# Close the connection after a client is idle for N seconds (0 to disable)
timeout 0


text:
Q: Can't start activity from class I am trying to start an activity from a normal class and I can't figure out how it is done, if it can be done. On an itemClick I want to start an activity that extends the ListView class to show a list of options.
Also the class that receives the onItemClick is not an activity. I will post the code to try to visualize what i mean.
This is my onClick method in the class that wants to start a an activity.
public void onClick(View v) {
        if (v.equals(this)) {
            notifyObservers(this.getId());
        } else if(v.equals(editButton) || v.equals(deleteButton)) {
            This is where I want to start the activity to show my ListView...
        }

}

This is my class that extends the ListView class.
public class ProfileSettings extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String[] mainSettings = getResources().getStringArray(R.array.mainSettings);

        setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, mainSettings));

        ListView lv = getListView();
        lv.setTextFilterEnabled(true);

        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // Do something
            }
        });
    }
}

Thanks in advance!

A: I think this may help you:
"Pass the context of the activity via constructor to your class or make a static context in your activity.
With the context you can start activities like you would start them within the activity class."
    class First extends Activity {
    ...
    Second test = new Second(this);
    test.start();
    ...
}

class Second {
    private Context mContext;
    ...
    public Second(Context c) { this.mContext = c; }
    ...
    public start() { mContext.startActivity(...); }
}

for more detail check
http://www.anddev.org/view-layout-resource-problems-f27/starting-an-activity-from-a-non-activity-class-t14483.html

A: Try this in your onClick
Intent i = new Intent(this, ProfileSettings.class);
startActivity(i);

EDIT:
Also dont forget to add the activity to your manifest.


text:
Q: Adding Users By Phone Number To Custom Audiences As stated in documentation, it is possible to add users to Facebook Custom Audiences using emails, phone numbers, facebook id or even app user id. But only email option is documented on https://developers.facebook.com/docs/reference/ads-api/custom-audience-targeting/
We can use "email_hash" key while adding users by emails. What are the keys to use while adding users by phone number or facebook ids?

A: Well, I posted random names and in response i found correct key names for other options:

(#100) Users must use one of id, partner_token, email_hash, phone_hash, custom_audience_third_party_id.


text:
Q: Fatal error: Index out of range when filling cells I am getting the this error: Index out of range when trying to fill cells out of a table, any idea why this happens?
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: VCInstanciasCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! VCInstanciasCell

        cell.siteLabel.text = String?([arrayItinerario[indexPath.section]][indexPath.row].ubicacion!) ?? ""

        cell.txtLabel.text = String?([arrayItinerario[indexPath.section]][indexPath.row].maquinaTipo!) ?? ""
        cell.orderLabel.text = String?([arrayItinerario[indexPath.section]][indexPath.row].fma!) ?? ""

        cell.codeLabel.text = String?([arrayItinerario[indexPath.section]][indexPath.row].iso!) ?? ""
        cell.newLabel.text = String?([arrayItinerario[indexPath.section]][indexPath.row].instanciaID!) ?? ""
        cell.setLeftUtilityButtons(self.leftButtons(), withButtonWidth: 50.0)

        return cell
    }

the error is at cell.siteLabel.text = String?([arrayItinerario[indexPath.section]][indexPath.row].ubicacion!) ?? ""  in  indexPath.Row

A: It is quite hard to answer this question without seeing how arrayItinerario is defined, and what triggers the cellForRow (when is the timing you're calling reloadData)
But first of all, I'd try to simplify your code, it will make it easier to understand where the crash comes from, as you're using force unwrapped and also cannot know in which of the row/section you get the index out of range.
I added some checks + guards + prints, it will explain my answer + make your testing easier:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: VCInstanciasCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! VCInstanciasCell

    if let value = value(for: indexPath) {
        cell.siteLabel.text = ""
        if let ubicacion = value.ubicacion {
            cell.siteLabel.text = String(ubicacion)
        }

        // and so on
    } else {
        print("couldn't get value for indexPath:\(indexPath)")
    }

    return cell
}

func value(for indexPath: IndexPath) -> SomeObject? {
    let section = indexPath.section
    let row = indexPath.row

    guard section < arrayItinerario.count else {
        print("section \(section) is out of range for list with count: \(arrayItinerario.count)")
        return nil
    }

    let list = arrayItinerario[section]
    guard row < list.count else {
        print("row \(row) is out of range for list with count: \(list.count)")
        return nil
    }

    return list[row]

}


text:
Q: How to test my code I'm having trouble getting the output I want for my code. I want to test a class and the functions defined in the class. This is my code:
class Book:
    # the class constructor
    def __init__(self, author, title, book_id):
        self.title = title
        self.author = author
        self.book_id = book_id
    def __str__(self):
        s = "Books("+self.author+", "+self.title+", "+self.book_id+")"
        return s
    def __repr__(self):
        return str(self)

What I did to try to attempt to test it is this:
 >>> author="Dr. Suess"
>>> title="The Cat in the Hat"
>>> book_id="12345"
>>> Book
<class '__main__.Book'>
>>>

the output I get is the last line. I'm probably doing it wrong but I don't know how to test it. If someone can show me that would be great!

A: When you type Book into the interpreter, you're getting the actual Book class' representation as output. __repr__ and __str__ both refer to the instance of a Book, not to the class itself. So to test this, you have to instantiate a Book:
>>> b = Book("Dr. Suess", "The Cat in the Hat", "12345")
>>> b
"Books(Dr. Suess, The Cat in the Hat, 12345)"

Remember - a class is like a blueprint for an instance. In this case, Book defines what it means to be a Book, but it doesn't actually define an actual Book object - to do that, you need to make a Book instance using the code I did.

A: >>> Book
<class '__main__.Book'>

When one does the above in the console, it does not call the __repr__ method created on instance. Let me explain, Book is merely a class object, its not an instance, because you have not called any arguments to it, however, if you do call arguments, this is what you get:
>>> from Books import Book
>>> Book
<class Books.Book at 0x027B0AE8>
>>> Book("Hello", "World", '1234')
Books(Hello, World, 1234)

As you can see, because we created an instance of a method, we were able to get the __repr__ to be called.


text:
Q: KeyboardAvoidingView methods' description I am trying to tailor KeyboardAvoidingView to my app. The documentation of this component is rather horrible and I am having difficulties understanding what each method described on the page does, since there is literally no description on how to use them.
If you have used this Component, could you explain what do the methods above do and how to use them?


text:
Q: Fill empty values in running sum I've to calculate a ratio between several categories everytime one some category gets a value change.
If I have the following table:

Block
Category
Value

1
A
30

1
B
20

1
C
50

2
A
40

4
B
10

I'd need a way to get the running sum filling empty values (Category A without changes since block 1) with the nearest preceding one:

Block
Category
Value

1
A
30

1
B
20

1
C
50

2
A
70

2
B
20

2
C
50

4
A
70

4
B
30

4
C
50

I'm using a query like the following one:
SELECT category, block_number
  SUM(block_sum) OVER(PARTITION BY category ORDER BY block_number)
  FROM block_table

But in the case there's no value from a given category in a block_number, then I won't get that row in the results.

A: Generate the rows using a cross join.  Use a left join to bring in the values that exist and then use window functions:
select b.block, bc.category,
       sum(bt.value) over (partition by c.category order by b.block) as value
from (select distinct block from block_table) b cross join
     (select distinct category from block_table) c left join
     block_table bt
     on b.block = bt.block and c.category = bt.category;


text:
Q: MAX and COUNT function doesn't work together I want to count id_r and then return the maxim value of count using
 MAX(COUNT(id_r))

but shows me this error
the error
Thanks :)

A: You can only use one aggregation function at a time.
The ANSI standard way to do what you want is:
select count(*)
from t
group by ?
order by count(*) desc
fetch first 1 row only;

Or alternatively a subquery:
select max(cnt)
from (select count(*) as cnt
      from t
      group by ?
     ) x;

Note that you want a group by of something, perhaps id_r.

A: Try this:
SELECT MAX(e1) as Expr1 FROM (
SELECT COUNT(id_r) as e1
FROM Angajat) as t1

COUNT(id_r) wil return only 1 result since there is no group by clause. Hence, there is no use of max.
You need to add a group by clause in subquery:
SELECT MAX(e1) as Expr1 FROM (
SELECT column1, COUNT(id_r) as e1
FROM Angajat
GROUP BY column1
) as t1


text:
Q: Running Python scripts like PHP There are Apache 2 + mod_wsgi + Python 2.6 on server.
I would like to run scripts from Python like PHP scripts. The idea may seem silly, but I'm so accustomed (at least at first learning Python).
Example:
PHP - http://example.com/script.php
Python - http://example.com/script.py
P.S. I know about mod_rewrite and other similar tricks that can do that. But it is only a disguise, and not a direct run.
UPD: My .htaccess file. index.py works, but other python scripts get 404 error.
<Files *.py>
SetHandler wsgi-script
Options ExecCGI FollowSymLinks
</Files>
 DirectoryIndex index.py

A: That doesn't look as cool as having a wsgi app running, so I recommend that you use the flask framework which is as simple as can be a sane framework.
Here's a link describing the install procedure on mod_wsgi.
Later on, you might want to consider a cool framework like Django, Pyramid, Grok ...
If you really want to use mod_wsgi like mod_php check Graham Dumpleton's great answer.

A: Technically what you are doing should work, but see AddHandler method for configuring mod_wsgi in:
http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#The_Apache_Alias_Directive
That way you don't have to fiddle with Files directive.
SetHandler does similar thing but all files in context are treated as WSGI script files even if they may be static HTML or PHP files. You got away with it because qualified with Files, but better to just use AddHandler.
Do note that code reloading will not work like you are used to with PHP. See:
http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode

A: I run Python scripts like PHP using  mod_cgi
Here is a tutorial by Apache.  And the cgi interface to use is here by Python.org
A second good tutorial that I used is here once your up and running.
I would add that there is a simiplier way to configure Apache.
Step 1: The first step is not mentioned in the guides above is to enable CGI processing in apache.

sudo a2enmod cgi

This will automatically enable mod_cgid if your server is configured with a multi-threaded MPM, which was the case for me.
Step 2: Edit your httpd.conf or whatever it is named in /etc/apache2/sites-enabled
in Linux Mint 19.2.
Enable a script for / with an index.py
<VirtualHost *:80>
   DocumentRoot /your/www/html
   DirectoryIndex  index.py
</VirtualHost>

Step 3:  Enable other python scripts so they can also run in the same folder or in subdirectories.
<Directory "/your/www/html/*">
    AllowOverride None
    Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
    Order allow,deny
    Allow from all
    AddHandler cgi-script .py
    AddHandler default-handler .jpg .png .gif .css .js .ico
</Directory>

ScriptAlias /   /your/www/html/

There are two caveats that I have encountered that must be adhered to to run python scripts successfully.

*

*When running in linux, make sure the line endings of each python file.py are
unix line endings.  Otherwise the python script will not run.  For example,
Notepad++ has Edit, EOL Conversion, Linux (LF) in its menu,tool bar.

*Ensure that the permission of each python file.py has execute permissions.
In Linux Mint 19.2 I right click the file, go to Properties, go to Permissions,
then check the checkbox at Execute: Allow executing program as file.  Or just
run the command:

chmod a+x python_script.py


text:
Q: How do I show the the integral exists? How do I prove the limit of Lebesgue integral exists and find its value: $\lim_{n \rightarrow \infty} \int_{0}^{\infty} f_n(x)\,dx. $ where $f_n(x)=e^{-x}\cos(x/n)$.
My attempt: I try to apply the Dominated convergence theorem:
i) $|f_{n}(x)|=|e^{-x}\cos(\frac{x}{n})|\leq e^{-x}$.
ii) $\lim_{n \rightarrow \infty} f_n(x)=\lim_{n \rightarrow \infty} e^{-x}\cos(\frac{x}{n})= e^{-x}$.
Then $f$ is integrable, and $\lim_{n \rightarrow \infty} \int_{0}^{\infty} f_n(x)\,dx=\lim_{n \rightarrow \infty} \int_{0}^{\infty} f(x)\,dx$.
$\lim_{n \rightarrow \infty} \int_{0}^{\infty} e^{-x}\cos(\frac{x}{n})\,dx= \lim_{n \rightarrow \infty} \int_{0}^{\infty} e^{-x}\, dx=1$.
Is this attempt correct? Can I say the integral exist because $f$ is integrable?

A: You are correct. As a remark, you can solve this (and verify your solution) explicitly.
Let $I_n=\int_0^\infty f_n(x)\,dx=\int_0^\infty e^{-x}\cos(x/n)\,dx$. You can actually evaluate this using the bounce back technique. Let $u=\cos(x/n)$, $dv=e^{-x}dx \implies v=-e^{-x}$. Then
\begin{align}
I_n&=uv\Big|_{0}^\infty-\int_0^\infty v\,du \\
&=1-\frac{1}{n}\int_0^\infty \sin(x/n)e^{-x}\,dx \\
&\stackrel{IBP}{=}1-\frac{1}{n^2}\int_0^\infty\cos(x/n)e^{-x}\,dx \\
&=1-\frac{1}{n^2}I_n
\end{align}
This implies
$$
I_n=\frac{1}{1+1/n^2}.
$$


text:
Q: Using cmake for SDL2 I am exploring SDL and wrote the following simple code
#include <SDL2/SDL.h>

int main() {
    if (SDL_Init(SDL_INIT_VIDEO) < 0){
        return 0;
    }
    SDL_Window* window = SDL_CreateWindow("Hello World",
                                          SDL_WINDOWPOS_UNDEFINED,
                                          SDL_WINDOWPOS_UNDEFINED,
                                          600,
                                          400,
                                          SDL_WINDOW_SHOWN);
    if (window == nullptr) {
        return 0;
    }
    SDL_Surface* surface = SDL_GetWindowSurface(window);
    SDL_FillRect(surface,
                 nullptr,
                 SDL_MapRGB(
                         surface->format,
                         0xFF,
                         0xFF,
                         0xFF));
    SDL_UpdateWindowSurface(window);
    SDL_Delay(9000);
    SDL_DestroyWindow(window);
    return 0;
}

And have the following cmake file for Clion
cmake_minimum_required(VERSION 3.9)
project(LazyFoo)

set(CMAKE_CXX_STANDARD 14)

find_package(SDL2 REQUIRED)
include_directories(${SDL2_INCLUDE_DIR})

add_executable(LazyFoo main.cpp)
target_link_libraries(LazyFoo ${SDL2_LIBRARY})

The problem is that when I am building my main.cpp directly from the command line without using cmake, then the code compiles and a nice window is shown, but when I use clion to build the code then it throws undefined reference to the all the SDL functions which I used above.
I know that the problem lies with my cmake file and have googled for the same but all was in vain.
How should I change my cmake file to be able to build the project from the  CLion itself.
EDIT
My clion build message
/home/tarptaeya/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/173.4674.29/bin/cmake/bin/cmake --build /home/tarptaeya/DevGames/LazyFoo/cmake-build-debug --target LazyFoo -- -j 2
Scanning dependencies of target LazyFoo
[ 50%] Building CXX object CMakeFiles/LazyFoo.dir/main.cpp.o
[100%] Linking CXX executable LazyFoo
CMakeFiles/LazyFoo.dir/main.cpp.o: In function `main':
/home/tarptaeya/DevGames/LazyFoo/main.cpp:4: undefined reference to `SDL_Init'
/home/tarptaeya/DevGames/LazyFoo/main.cpp:12: undefined reference to `SDL_CreateWindow'
/home/tarptaeya/DevGames/LazyFoo/main.cpp:16: undefined reference to `SDL_GetWindowSurface'
/home/tarptaeya/DevGames/LazyFoo/main.cpp:17: undefined reference to `SDL_MapRGB'
/home/tarptaeya/DevGames/LazyFoo/main.cpp:23: undefined reference to `SDL_FillRect'
/home/tarptaeya/DevGames/LazyFoo/main.cpp:24: undefined reference to `SDL_UpdateWindowSurface'
/home/tarptaeya/DevGames/LazyFoo/main.cpp:25: undefined reference to `SDL_Delay'
/home/tarptaeya/DevGames/LazyFoo/main.cpp:26: undefined reference to `SDL_DestroyWindow'
collect2: error: ld returned 1 exit status
CMakeFiles/LazyFoo.dir/build.make:94: recipe for target 'LazyFoo' failed
make[3]: *** [LazyFoo] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/LazyFoo.dir/all' failed
make[2]: *** [CMakeFiles/LazyFoo.dir/all] Error 2
CMakeFiles/Makefile2:79: recipe for target 'CMakeFiles/LazyFoo.dir/rule' failed
make[1]: *** [CMakeFiles/LazyFoo.dir/rule] Error 2
Makefile:118: recipe for target 'LazyFoo' failed
make: *** [LazyFoo] Error 2


text:
Q: Input not being registered / registered too slowly in pygame I'm trying to make a snake game in python (I'm quite bad at python, just starting with pygame so my code isn't the most effective) and the game is not responding to any keyboard inputs, I don't remember what I changed (shouldn't have been anything important enough to cut off keyboard inputs) but before I did this change, the code would run through the for statement 3 times before registering the keyboard input
Another problem I an having with the code which I haven't looked into much (so it's probably an easy fix which I'll find if I scan through my code) is that the snake spawns on the screen in the wrong pattern, it should be 3 blocks in a row, but is instead 2 blocks, 1 block space and 1 block
I realise that I have not implemented the fact that the snake tail should follow the head so please do not make a note of that in the comments, thanks
Here is my code (Just the snake class, I don't want to clutter up the screen with too much over-complicated, terrible code)
Under the code is a small explanation of some of the variables as they may not be too obvious
Thank you to anyone who helps out
class Snake:
    def __init__():
        Snake.Movement = "R"
        Snake.Front = 5
        Snake.Back = 3
        Apple.newPos()
        Snake.Move()
    def Move():
        while True:
            for event in p.event.get():
                if event.type == p.KEYDOWN:
                    #print("aaaaaaAAAAAAAAAAAAA")
                    #if len(Snake.Movement) == 0:
                    if event.key == p.K_UP or event.key == p.K_w:
                        if Snake.Movement != "D":
                            print("DIRECTION UP")
                            Snake.Movement = "U"
                    elif event.key == p.K_DOWN or event.key == p.K_s:
                        if Snake.Movement != "U":
                            print("DIRECTION DOWN")
                            Snake.Movement = "D"
                    elif event.key == p.K_LEFT or event.key == p.K_a:
                        if Snake.Movement != "R":
                            print("DIRECTION LEFT")
                            Snake.Movement = "L"
                    elif event.key == p.K_RIGHT or event.key == p.K_d:
                        if Snake.Movement != "L":
                            print("DIRECTION RIGHT")
                            Snake.Movement = "R"
                t.sleep(1)
                for x in range(1,17):
                    for y in range(1,17):
                        if Setup.Screen[y][x] == 2:
                            p.draw.rect(Bg,(255,0,0),p.Rect(x*25,y*25,25,25),0,0)
                        elif Setup.Screen[y][x] != 0 and Setup.Screen[y][x] != 2:
                            if Setup.Screen[y][x] == Snake.Back:
                                p.draw.rect(Bg,(0,0,0),p.Rect(x*25,y*25,25,25),0,0)
                            elif Setup.Screen[y][x] == Snake.Front:
                                Snake.Front += 1
                                print(Snake.Movement)
                                if Snake.Movement == "U":
                                    if Setup.Screen[y+1][x] == 1:
                                        exit()
                                    else:
                                        p.draw.rect(Bg,(0,255,100),p.Rect(x*25,(y-1)*25,25,25),0,0)
                                        headX = x
                                        headY = y-1
                                elif Snake.Movement == "D":
                                    if Setup.Screen[y-1][x] == 1:
                                        exit()
                                    else:
                                        p.draw.rect(Bg,(0,255,100),p.Rect(x*25,(y+1)*25,25,25),0,0)
                                        headX = x
                                        headY = y+1
                                elif Snake.Movement == "L":
                                    if Setup.Screen[y][x-1] == 1:
                                        exit()
                                    else:
                                        p.draw.rect(Bg,(0,255,100),p.Rect((x-1)*25,y*25,25,25),0,0)
                                        headX = x-1
                                        headY = y
                                else:
                                    if Setup.Screen[y][x+1] == 1:
                                        exit()
                                    else:
                                        p.draw.rect(Bg,(0,255,100),p.Rect((x+1)*25,y*25,25,25),0,0)
                                        headY = y
                                        headX = x+1
                            else:
                                p.draw.rect(Bg,(0,255,100),p.Rect(x*25,y*25,25,25),0,0)
                            Snake.Back += 1
                            p.display.flip()
                try:
                    Setup.Screen[headY][headX] = Snake.Front
                except:
                    pass

*

*Setup.Screen[][] is a 2 dimensional array with numbers in the lists to associate with the different objects on screen (1 is a wall, 2 is an apple, 3+ is the snake).

*Snake.Front is an integer showing which number in Setup.Screen[][] the front of the snake is, as it changes each iteration.

*Snake.Back is the same as Snake.Front but for the back of the snake and isn't fully implemented yet.

*All of the print lines are from me trying to locate errors, they aren't needed