Entropy of an Image?

Question: In a previous question (Entropy of an image) and in various sources on the web, the Shannon entropy of an image is considered to be the entropy of the frequency distribution of the grayscale values.
In this way a random image where the pixels take the values 0 or 1 with the same probability has an entropy equal to a single coin toss: we have 50% white and 50% black so the entropy is 1. This does not vary with the dimension of the image.

What I am not able to understand is why each pixel is not considered as a separate random variable.
In my opinion, in my example, is more correct to consider an image with $n$ pixels as a sequence of $n$ coin tosses, resulting finally in an entropy of $n$:
$$H(I)= -2^n  2^{-n}  \log_2 2^{-n} = n$$
In the case of an 8-bit image (256 possible pixel values), the final result would be $8*n$. This measure of entropy is dependent on the number of pixels on the image. Something that makes sense to me. Moreover, it solves the problem presented in the previously linked question (Entropy of an image) of the spatial correlation of the pixels.

In this case, the number of free pixels would be decreased because each line is completely dependent on the value of its first pixel. This would decrease the entropy.
What am I doing wrong?
Comment: Shannon entropy is defined for discrete random variables in general. There is no 'the' entropy of an image since you can define a variety of discrete random variables pertaining to images that will all have their own entropy. Of course you can have separate pixel-wise entropies!
Answer: There is no such a thing as the "entropy of an image". Entropy is about the random variable. If you want to be talking about entropy, you need to think of the image in terms of a random variable(s). There are many ways how you can think of an image as a random variable. For example, it can be a random variable with two states "image contains cat" and "image does not contain a cat" with associated probabilities. Another way could be to consider the image recorded as an $m \times n$ random matrix (assuming black-and-white, for colors you would have additional dimensions) where each pixel is a separate random variable. For white noise images, the random variables would be independent and identically distributed, so their joint distribution would be $p(x_1, x_2, \dots, x_{m\times n}) = \prod_i p(x_i)$, but for any other images, the pixels would be non-independent and not necessarily identically distributed. For any of the random variables (univariate, multivariate), you can calculate the entropy using the regular formula.
Answer: A single image doesn't have the property of information entropy.
It is the probability distribution of images that has the property of information entropy.

When the entropy of a single image is considered, then it can be about a probability distribution of images that are conditioned on having the same properties as that single image.
This is related to physics where one considers macrostates and microstates. The latter, a microstate, has no entropy in itself, but in a way you could consider the entropy of the related macrostate and some model for it's distribution.

So when you consider the entropy of an image, and consider all $k^n$ states equally possible, then an image is indeed just like a discrete uniform distribution with entropy $\Omega = \log_2 k^n = n  \log_2 k$.
It is not wrong to consider the entropy of an image like that. However, one may consider also other uses of entropy (that are more useful).
For example, when one considers images according to a model that entails a non-uniform distribution, where certain values are more/less likely, then one can have lossless image compression by encoding the more likely patterns with fewer bits (at the cost of the less likely patterns requiring more bits), such that on average less bits are needed to encode the image.

Entropy of an Image?


Need to do union all in Hive on all table names coming from python list

Question: I have n number of tables names coming in a python list like this:
tb_name = ['table A1', 'table A2', 'table A3', ....., 'table An']
Is there a way in Hive QL (using explode, lateral view etc) to create a Hive query like:
Select *
From table A1
UNION ALL
Select *
From table A2
UNION ALL
Select *
From table A3
UNION ALL
.
.
Select *
From table An

I can use python3 to read from list and create query in string format first and then pass it to Hive to run it though using below code:
query = "Select * From {} ".format(tb_name[0])
for t in tb_name:
    if t != tb_name[0]
        query = query + " UNION ALL Select * From {} ".format(t)

But I am just looking for a way to handle this list of table names in Hive itself.
Answer: You can try the following, assuming that the 'tb_name' list is passed as a comma-separated string. For example: tb_name = 'table A1,table A2,table A3,...,table An'
SET hivevar:table_names='table A1,table A2,table A3,...,table An';
SELECT split('${hivevar:table_names}', ',') AS table_name_array;
SET hivevar:table_names='table A1,table A2,table A3,...,table An';
SELECT CONCAT('SELECT * FROM ', table_name) AS hive_query
FROM (SELECT explode(split('${hivevar:table_names}', ',')) AS table_name) t;
SET hivevar:table_names='table A1,table A2,table A3,...,table An';
SELECT CONCAT('SELECT * FROM ', table_name) AS hive_query
FROM (SELECT explode(split('${hivevar:table_names}', ',')) AS table_name) t
JOIN ${hivevar:table_name}
ON 1=1;


Can you make default client key length larger for ssh-keygen?

Question: When users employ ssh-keygen to create RSA key pairs, the default key length is 2048 bits.
You can override that on the command line with the -b argument, but few users will bother.
As mentioned in this article, it is recommended to use key lengths of 3072 or greater if you need security beyond 2030.  Is there a way to cause 3072 (or 4096) to be the default length for all keys generated?  I don't see it in the ssh_config or sshd_config manual pages.  Or does it require recompilation of the program?
Comment: You're talking of SSH keys, which implies that they're be use for authentication when connecting to a running machine, not for message encryption. Is 2030 really a concern in this case? If the hardware still runs by then, it's quite likely that the version of the OS you're currently running will no longer be supported (and possibly have a number of other security holes). It's probably better practice to make your users change their keys once in a while (you're rarely in control of how they store them anyway), definitely a few times in the next 20 years or so.
Answer: I don't think there is any way to do this via a configuration file. You could set up an alias and put it in a shell initialisation file. This won't stop the user from deleting the alias and running their own command though.
<code>alias ssh-keygen='ssh-keygen -b 3072'
</code>
then
<code>$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/iain/.ssh/id_rsa): /tmp/testkey
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /tmp/testkey.
Your public key has been saved in /tmp/testkey.pub.
The key fingerprint is:
47:3a:03:c8:ac:63:1c:bf:9d:44:1d:4b:b4:0e:66:04
$ ssh-keygen -lf /tmp/testkey
3072 47:3a:03:c8:ac:63:1c:bf:9d:44:1d:4b:b4:0e:66:04 /tmp/testkey.pub
</code>
You could put it in each (existing) user's ~/.bashrc and in /etc/skel/.bashrc so new user's get it too.
Comment: it is also possible there are tools out there to enforce a minimum key length for ssh access... that way you can educate your users to create keys with a length > 3072, and if they don't, their keys won't be accepted... i don't know the logistics behind this, but it's something i'm interested in finding more information about.
Comment: The alias method only works if people are using a centralized computer, not distributed as in our case.
Comment: Enforcing minimum length to operate would at least provide security - at the cost of turning people off.


Partition an infinite set into countable sets

Question:
Let $X$ be an infinite set. Find a partition of $X$ where each element in the partition is countable.

Let $Y$ be the set of all families $\{F_i\mid i\in I\}$ in which each family satisfies 3 below conditions:

$F_i\subseteq X$ for all $i\in I$
$F_{i_1}\cap F_{i_2}=\emptyset$ for all $i_1,i_2\in I$ and $i_1\neq i_2$.
$|F_i|=\aleph_0$ for all $i\in I$

We define a partial order $<$ on $Y$ by $$\{F_i\mid i\in I\}<\{F_i\mid i\in J\}\iff\{F_i\mid i\in I\}\subseteq\{F_i\mid i\in J\}$$
For any chain $Z$ in $Y$, let $T=\bigcup_{F\in Z}F$, then $T\in Y$ and $T$ is an upper bound of chain $Z$. Thus the requirement of Zorn's Lemma is satisfied. Hence $Y$ has a maximal family $\bar{F}$.
Let $F'=X\setminus\bigcup_{F\in\bar{F}}F$, then $F'$ is finite. If not, $F'$ is infinite. Then there exists $F^\ast\subseteq F'$ such that $|F^\ast|=\aleph_0$. Thus $\bar{F}\cup\{F^\ast\} \in Y$ and $\bar{F} \subsetneq \bar{F}\cup\{F^\ast\}$, which clearly contradicts the maximality of $\bar{F}$. Hence $F^\ast$ is finite.
To sum up $\bar{F}\cup\{F'\}$ is the required partition of $X$ where each element is either finite or countable infinite.

Does this proof look fine or contain gaps? Do you have suggestions? Many thanks for your dedicated help!
Comment: (If you don't insist that the pieces of the partition should be infinite, as your final paragraph suggests, then the problem is trivial, as you can partition any set into singletons. So the last paragraph should be modified as well.)
Comment: It has some issues, which may very well be typos, but they are issues anyway. First, note the typo in your second condition when defining the family. Second, is it obvious that $Y$ is a set? Third, if $F^*$ is infinite, it is not necessarily countable, so what you did there needs to be modified. Also, it is maximality rather than minimality that is contradicted. Fourth, if $F^*$ is finite but nonempty, you must modify what you did, since your third condition in the definition of $Y$ asks all pieces of the partition to be infinite.
Comment: Well, write that down on the body of the question, not in comments.
Comment: Hi @AndrésE.Caicedo I have fixed the all issues. I only require my partition to contain countable sets ^^ Please have a check!
Comment: Again, unless you require all pieces of the partition to be infinite, the problem is trivial, and it would be ridiculous to use this approach. You must fix what you do when $F'$ is finite.
Comment: @AndrésE.Caicedo please check my reasoning: For all pieces in the partition to be infinite, we replace $F_i$ with $F_i\cup F'$ for some $i\in I$.
Comment: Many thanks @AndrésE.Caicedo !
Comment: Note that it you denote $F_0$ as an element of $\bar F$ then you can define $\bar{\bar F}=(\bar F\setminus \{F_0})\cup \{F_0\cup F'\}$. In other words, add the finite element you have left to arbitrary element, this way the partition doesn't hold any finite sets
Comment: Hi @AndrésE.Caicedo, I seem to find a simpler way to partition $X$ into countably infinite sets. I have posted it as an answer below. Could you please have a check to confirm my attempt? Thank you so much!
Answer: Alternate proof:
Well order the set so that it is order isomorphic to an initial ordinal $k$.
$$X = \{ x_i \mid 0 \le i < k \}$$
For each limit ordinal $j$, let $j'$ be the next limit ordinal. Let $F_0 = \{ x_i \mid i \text{ is non-negative integer}\}$.
For each limit ordinal $j < k$, let  $F_j = \{ x_i \mid j \le i < j' \}$.
Comment: Just one minor suggestion, I would be better if you use Mathjax to format your answer.
Answer: Assuming Axiom of Choice, $|X|=|X\times\Bbb N|$ if $|X|\ge\aleph_0$.
Thus there is a bijection $f:X\times\Bbb N\to X$. We define a family $(X_i\mid i\in X)$ by $X_i=f[\{i\}\times\Bbb N]$ for all $i\in X$.
Since $f$ is bijective, $X_{i_1}\cap X_{i_2}=\emptyset$ for all $i_1,i_2\in X$ and $i_1\neq i_2$, and $\bigcup\limits_{i\in X}X_i=\bigcup\limits_{i\in X}f[\{i\}\times\Bbb N]=f[\bigcup\limits_{i\in X}\{i\}\times\Bbb N]=f[X\times\Bbb N]=X$.
Furthermore, $|X_i|=|f[\{i\}\times\Bbb N]|=|\{i\}\times\Bbb N|=|\Bbb N|=\aleph_0$ since $f$ is bijective.
Hence $\{X_i\mid i\in X\}$ is a partition of $X$ in which each element is countably infinite.


Three domain names for a multi-site installation

Question: We are currently developing a website on Drupal 8.
This site will be in three versions. The differences between each site is minimal.

Different logo
Different colors CSS (HTML structure remains the same)
Some content is filtered according to the domain name. For this, we created a selection field in the content type to know on which domain name the content appears (Site A, Site B, Site C).

What is the best way to manage this type of project with Drupal 8?
We are aware that this could cause problems with the Drupal cache if we do a simple detection via preprocess to load a particular CSS or content.
Comment: https://www.drupal.org/project/domain
Answer: I am doing something very similar to migrate some D5, D6 and D7 sites to one D8 site.
Currently I have this solution:
(1) Have one master domain that serves all content (i.e. proreos.de).
(2) Have some paths (routes) that serve special content for different domains (i.e. /asde/* -> serve content for anwalt-seiten.de/*)
(3) Have ThemeNegotiatiors (ThemeNegotiatorInterface) watching for that special routes to set the 'other' theme (like asde-theme).
(4) Have inverse proxies (apache2 mod_proxy) on the "other" domains that deliver the subcontent from the master domain (i.e. anwalt-seiten.de/index.html -> proreos.de/asde/index.html)
The advantage I hope to have from this approach:
(a) Have all data in one place (proreos)
(b) Have presentation separated from model (special themes)
(c) Have scalability (by inverse proxies).
But I don't have real experience cause I am still developing. Hope it helps anyway.
Comment: After searching a solution more "Drupal way", I think it's possible to handle this with ThemeNegociator Class for the CSS, and somes hook for filtering the content. I've read that Drupal's page cache take the whole absolute URL, so there is no risk of conflict.


Printing HTML Form using window.print()

Question: I was charged with the task of building a HTML Form link to a DB. Here no problem.
The problem is I need the user to be able to print that form.
So I build a "Print button" using a HTML button and I put some JQuery behind it so the form would format correctly (remove some borders, background-images and such) and I use window.print() to print my form.
Here is the problem:
My form is 6 to 7 pages long.
But has expected It print fine on Google Chrome (All the section are on separate pages) but In IE (latest version) some field and some sections are "cut in half" on some pages.
I think the problem is how IE use margins and paddings.
I also checked for any parameter I could pass to window.print() on Google thinking maybe it could help but did'nt find anything.
Can someone provide another way or another function I could use so my form look the same on both browser when print?? Or maybe someone could point If I made a mistake.
Here is my code:
HTML:

Codes de sécurité des ascenseurs

            <input type="radio" id="B442007" name="CodeSecurite" value="B44-2007"/>
            B44-2007
            <input type="radio" id="B442010" name="CodeSecurite" value="B44-2010"/>
            B44-2010
            <input type="radio" id="ASME1712007" name="CodeSecurite" value="ASME 17.1-2007"/>
            ASME 17.1-2007
            <input type="radio" id="ASME1712010" name="CodeSecurite" value="ASME 17.1-2010"/>
            ASME 17.1-2010

            Autre:
            <input type="text" id="CodeSecuriteAutre" name="CodeSecuriteAutre"/>

            Ville d'installation:
            <input type="text" id="VilleInstallation" name="VilleInstallation"/>

Type de contôle

                Modèle:
            <input type="radio" id="JHD1000" name="JHD1000" value="JHD-1000"/>
            JHD-1000 (Avec automate)

            <input type="radio" id="JHD2000" name="JHD2000" value="JHD-2000"/>
            JHD-2000 (Carte de communication Canbus)

Notes: I put only a sample of my code. I have several time this lenght. The

 is what I used to try and put all the
 on one page each.
CSS:

Notes: I remove the code that was not directly needed for the question if I remove something that was needed please say so I will Edit and Add the missing code.
FYI: dont look for .divspacer. It does not exist, it is use only in my JQuery (see below).
JQUERY:
function ImprimerForm()
        {
            $("#divBgd").removeClass('Border');//This remove the border
            $("#divValidationEnvois").css('display', 'none');//This hide all the button so they dont print
            $(".divspacer").removeClass('Spacers');//Make spacers visible

            window.print();//Print form

            $("#divBgd").addClass('Border');//Put everything back has it was!!
            $("#divValidationEnvois").css('display', 'block');
            $(".divspacer").addClass('Spacers');
        }

So Just to be clear:
Probelm: I can't get IE and Chrome to print my form the same way. Some field are cut in two and some
 are on two different pages.
Looking for: A way to make them print my form the same way on both browser OR an error a made with the layout.
What I already did: Look for parameters for window.print() AND Tried adding some SPACERS (see code above).
Thank you all for the help!
Comment: Could you post screenshots of the print previews?
Comment: Set a `max-width` CSS property on your containing element in the `print` stylesheet.
Comment: You can style the form with a stylesheet for print only, and you could even add such a stylesheet in conditional comments for IE only.
Comment: @Pietu1998-Unfortunatly I cant post a screenshots because I dont know where or how maybe you could provide a way I could post a screenshot ??
Comment: @adeneo- I checked those conditionnal comment and was thinking that this might work. But It seems a I have the same problem with FireFox (all the browser print differently some add margins, other dont my form look different on all 3 browser) Is there a way to do the same thing (conditionnal comment) for FireFox ??
Answer: Instead of trying to hide unwanted divs using jQuery, you should use a print specific css instead. By hiding elements with jQuery you could bump into unwanted side effects. By adding a print css, you specify a ruleset only used when the printer is trying to print the page. So nothing is added to your visible css rules. In this CSS you can for example set certain elements to display:none;.
Example of adding an IE specific print css:

You can remove the if IE / endif tags if you want to apply to rules to all browsers.
Another option to create print rules is to use a css @media print section like so (using it this way also applies it to all browsers, which is actually not a bad idea):

Comment: As mentionned in a comment on the question is there a way to do the same with FireFox(conditionnal comments)??
Comment: Just remove the if IE, and it works for all browsers. It is actually not so bad to have your print.css to work for all browsers. Since you want the margins gone everwhere your users print.
Comment: Also, to have a conditional CSS for FireFox specificly you would have to use Javascript to detect the browser. Since there is no IF tag for FireFox like there is for IE
Comment: This is not quite the answer I was hoping (was looking for a magic answer that would resolve everything easily :P) but It provide all the informations needed to make things work. I will work this out with all the usefull informations you provided. Thanks everyone!
Comment: Sometimes there is no magic solution and you just have to put some work in. I do believe this is the most solid solution to the problem. Good luck!
Answer:                 stmt1="SELECT DISTINCT a.ro_code,a.ro_name,b.REGCODE,b.ROLLNUM,b.USERTYPE,b.NAME FROM regionmaster a INNER JOIN security_couser b ON TRIM`enter code here`(a.ro_code) = TRIM(b.REGCODE)  Order By b.REGCODE";
                    rs2 = st.executeQuery(stmt1);
                    out.println("

Region Code	Region Name	Roll Number	Name	User Type
");
                    String Countrun="";
                    while(rs2.next())
                    {
                        String reg = rs2.getString("REGCODE");
                        String regname=rs2.getString("RO_NAME");
                        String ROLLNUM= rs2.getString("ROLLNUM");
                        String USERTYPE= rs2.getString("USERTYPE");
                        String NAME= rs2.getString("NAME");
                        //Count = rs2.getString("NAME");
                        out.println("
"+reg+"	"+regname+"	"+ROLLNUM+"	"+NAME+"	"+USERTYPE+"
");
                    }
                    out.println("
");
                    rs2.close();
           %>
                        <input id ="printbtn" type="button" value="Print" onclick="window.print();" >

Printing HTML Form using window.print()


The $+$-construction on a homology $n$-sphere

Question: I am working on Weibel's K-Book and when defining higher K-Theory for a ring via $BGL(R)^+$, I have encountered a question concerning a homology $n$-sphere.
The statement I want to show is the following:

Let $X$ be a homology $n$-sphere, i.e., a space with
  $$H_\ast (X) = H_\ast (S^n). $$
  Show that there is a homotopy equivalence $S^n \rightarrow X^+$, when $X \rightarrow X^+$ is the $+$-construction on $X$ relative the perfect radical
  of $\pi_1 (X)$.

For $n \neq 1$ this is not much of a problem, since from
$$0 = H_1 (X) \cong \pi_1 (X) / [\pi_1 (X), \pi_1 (X)]$$
I can conclude that $\pi_1(X)$ is a perfect group and hence $X^+$ is simply connected since I am interested in the $+$-construction relative the perfect radical of $\pi_1 (X)$.
Is there a similar way I get information about the fundamental group of $X^+$ for $n = 1$?
Thank you.
Comment: For $n = 1$ what do you even mean by $X^{+}$? You need to pick a perfect normal subgroup of $\pi_1(X)$ for this to make sense, but a priori $\pi_1(X)$ may not have one.
Comment: I am interested in the +-construction relative the perfect radical of $\pi_1(X)$. In one of the exercises one shows that every group has a unique largest perfect normal subgroup, called perfect radical.
Answer: A homology $n$-sphere is a smooth closed $n$-dimensional manifold $X$ with $H_*(X) = H_*(S^n)$. In particular, a homology $1$-sphere is a smooth closed one-dimensional manifold, but the only such manifold is $S^1$. As $\pi_1(S^1) = \mathbb{Z}$ is abelian, the perfect radical is $\{0\}$ so $(S^1)^+ = S^1$.


Store axios (JSON) response in array

Question: I have an array which is being used by another file to map out the contents. I originally hard coded values into this array, but now I'd like to integrate an axios get call to retrieve data, and then store the info from the response into the array. I can successfully get the JSON response with the correct data, but I am stuck on getting the JSON response data into the array. Any help would be greatly appreciated
let theArray = [
{
id: '',
name: '',
},]

useEffect(() => {
        axios
            .get(`/api/data`)
            .then(res => {
                //? need to store res.data.id to theArray.id, and res.data.name to theArray.name
            })
    }, [])

Comment: I think this Sylens proposed a good solution, I just posted a new structure below. but is just a matter of different structure @reef
Answer: You can simply push the response to the array, but you'd have to begin with an empty array, otherwise, the first element you have hardcoded will not have any data.
let theArray = []

useEffect(() => {
        axios
            .get(`/api/data`)
            .then(res => {
                const newItem = {
                  id: res.data.id,
                  name: res.data.name,
                };
                theArray.push(newItem);
             })
    }, [])

Comment: I think this is a good solution, I just posted a new structure below. but is just a matter of different structure
Comment: Hello, I am quite new to React and was wondering, if you wanted to print this data under render(), could you do  "theArray[0].id" ? Also, is useEffect simply just an additional function?
Comment: Is it possible I use this method in app.get(....) in expressjs also? is there any conflict with res.render or not?
Answer: Here another solution, I think @Sylens solution is a good one, this is just a matter of structuring your code as you want
let theArray = []

useEffect(() => {
        axios
            .get(`/api/data`)
            .then(res => {
                // object destructuring
                const { id, name } = res.data;
                theArray.push({ id, name })
            })
    }, [])

Comment: Hello, I am quite new to React and was wondering, if you wanted to print this data under render(), could you do "theArray[0].id" ? If not, how would I access this information?
Answer: If your data is in json format you should wait for the info to get parsed, something like this:
let theArray = [
    {
        id: '',
        name: '',
    },
];

useEffect(() => {
    axios
        .get(`/api/data`)
        .then(res => res.json())
        .then((result) => {
            theArray[0].id = result.id;
            theArray[0].name = result.name;
        })
}, []);

Edit: if you want to add the new data just push it to the array
theArray.push({
    id: result.id,
    name: result.name,
})

Comment: Hello, I am quite new to React and was wondering, if you wanted to print this data under render(), could you do "theArray[0].id" ? If not, how would I access this information?
Answer: If it's only modifying first element:
let theArray = [{ id: '',  name: '',},]

useEffect(() => {
        axios
            .get(`/api/data`)
            .then(res => {
                theArray[0].id = res.data.id
                theArray[0].name = res.data.name
            })
    }, [])

Comment: Hello, I am quite new to React and was wondering, if you wanted to print this data under render(), could you do "theArray[0].id" ? If not, how would I access this information?
Comment: You can do ```render () { return {theArray[0].name} }``` or ```render () { return theArray[0].map(d => {d.name})  }```

Store axios (JSON) response in array


Inserir cidades no banco de dados

Question: Olá, estou criando uma base de dados, e nela terei informações dos municípios brasileiros, imagino que eu certamente não sou o primeiro a necessitar essas informações, porem eu não tenho conhecimento se existe alguma forma de fazer isso automaticamente, algum lugar que eu possa baixar essa base, ou algum script SQL que insira as informações no banco, porque fazer isso manualmente não é o mais aconselhável.
Estou utilizando o postgreSQL 9.3, não criei as tabelas para as cidades ainda.
Comment: Você pode usar o projeto open source que eu criei, ele busca diretamente na API do ibge e monta a lista mais atualizada possível de acordo com esses dados, segue o link
http://ibge-sql.herokuapp.com
Comment: Eu tenho um sql que eu uso, porém está para o `MySql`, mas acredito que com poucas alterações você poderá atingir seu objetivo. O arquivo está disponível em: [https://github.com/RichardSDias/SQL](https://github.com/RichardSDias/SQL/blob/master/Estados%20e%20cidades%20brasileiras.sql)
Comment: Todos os Estados e Municipios (ou quase todas...) do Brasil, com possibilidade de inserir novos paises, distritos/estados e municipios. (Colunas com prefixo para facilitar os JOINs e manter organização...).

**Caso dê problema nos caracteres acentuados, abra o arquivo em um editor de texto qualquer e salve com codificação UTF-8, que resolve, ou copie e cole o código direto no MySQL (sem usar importação...)**

Vou deixar o link do projeto do **Github**: https://github.com/chinnonsantos/sql-paises-estados-cidades
Comment: O site do IBGE fornece todas as cidades por meio de alguns tipos de arquivo. Dê uma olhada nesse link, que já tem os sqls para postgre http://www.ferreiramauricio.com/sql-das-5565-cidades-brasileiras-segundo-dados-ibge-2010
Answer: Código de cadastramento do IBGE
https://ferreiramauricio.s3.amazonaws.com/files/resource/24/brasil.mysql.sql
Copia tudo a partir do
<code>CREATE TABLE cidades (
    id integer NOT NULL AUTO_INCREMENT,
    nome varchar(250),
    codigo_ibge integer,
    estado_id integer,
    populacao_2010 integer,
    densidade_demo numeric(10, 2),
    gentilico varchar(250),
    area numeric(10, 3),
    PRIMARY KEY (`id`)
);
</code>
e executa no seu Postgre

copiar também o CREATE TABLE citado acima
Comment: No link tem mysql, ele funcionara da mesma forma? não conheço as diferenças entre um e outro
Comment: @LucasMotta Sim, mysql e sql a maioria dos comandos são iguais

Inserir cidades no banco de dados


why the quotient space is finite $X/\ker T$

Question: Let $T:X\rightarrow Y$ be a linear operator from Banach space to Banach space, if $Y$ is finite dimensional, show $X/\ker T$ is finite dimensional, moreover has same dimension with $Y$.
Any help is appreciated.
Comment: For one, $\;X/ker T\cong H\le Y\;$ and you already have finite dimension
Comment: See the first isomorphism theorem for vector spaces (or modules). The dimensions are equal only if $T$ is surjective.
Comment: I know there's isomorphism between $X/\text{ker}T$ and $Y$, but I want to know why?
Comment: @Benjamin : Please: Write \ker T, not \text{ker} T.  Look at $A\ker B$ and $A\ker(B)$, coded as A\ker B and A\ker(B), and notice that the space to the right of $\ker$ is different in those two expressions, and the spacing in both cases is different from what it would be if you write A\text{ker} B, which looks like this: $A\text{ker}B$.  The same applies to \log, \exp, \sin, \det, \max, \sup, \gcd etc. $\qquad$
Answer: If you remember the Theorem of dimensions for linear transformation between finite dimension vector spaces, then the proof is quite similar. Maybe the equality
$$\dim X = \dim \ker{(T)} + \dim \operatorname{Im}{(T)}$$
does not make sense since the dimension of $X$ could be infinite. But the quotient
$$\frac{X}{\ker{(T)}}\cong \operatorname{Im}{(T)}$$
holds, and if the image in contained in $Y$ finite dimensional Banach space, then the quotient is finite dimensional.
Answer: What you seem to be looking for is a proof of the first isomorphism theorem.
Let $\{k_i\}_{i \in I}$ be a basis of $\ker T$. This extends to a basis $\{k_i\}_{i \in I} \cup \{x_j\}_{j \in J}$ of $X$ (where $\operatorname{span} \{k_i\}_{i \in I} \cap \operatorname{span} \{x_j\}_{j \in J} = \{0\}$). Hence $\{ x_j + \ker T\}_{j \in J}$ is a basis of $X / (\ker T)$. We write $[x_j]$ for the element $x_j + \ker T$ of the quotient space, and we get an induced operator $T' \colon X / (\ker T) \to Y$ via $T'[x_j] = T x_j$. The heart of the proof is the following statement:

Since $\{[x_j]\}_{j \in J}$ is linearly independent in $X / (\ker T)$, so is $\{T'[x_j]\}_{j \in J}$ in $Y$.
Proof: By definition of linear independence, we must show that if any finite linear combination of vectors in $\{T'[x_j]\}_{j \in J}$ is the $0$ vector, then the coefficients are all $0$. We have $a_1 T'[x_{j_1}] + \cdots + a_n T'[x_{j_n}] = 0 \implies T\left( a_1 x_{j_1} + \cdots + a_n x_{j_n} \right) = 0$, which implies that $a_1 x_{j_1} + \cdots + a_n x_{j_n} \in \ker T = \operatorname{span} \{k_i\}_{i \in I}$. Since $\operatorname{span} \{k_i\}_{i \in I} \cap \operatorname{span} \{x_j\}_{j \in J} = \{0\}$, we must have $a_1 = \cdots = a_n = 0$, completing the proof.

Since $Y$ is finite dimensional, the above statement implies that $J$ is finite, and hence $X / (\ker T)$ is finite dimensional.
As @Mathematician42 says, it's not necessarily the case that $\dim\left( X / (\ker T) \right) = \dim Y$; we could have some basis vector of $Y$ which is never hit by $T$ (or $T'$).


Represent the three element chain as a subdirect product of subdirectly irreducible lattices.

Question: Represent the three element chain as a subdirect product of subdirectly irreducible lattices.
I know the two element chain as either a Boolean algebra or a semilattice,is subdirectly irreducible.In fact , a distributive lattice subdirectly irreducible if and only if it has exactly two elements.
Any finite chain with two or more elements,as a Heyting algebra,is subdirectly irreducible.(This is not case for chain of three or more elements as either lattices or semilattices,which are subdirectly reducible to the two-element chain.)
Now I want given an example for the three element chain as a subdirect product of subdirectly irreducible lattices.
please help me.
thanks.
Comment: I dont have enough time,please help me as soon as possible. Thanks.
Answer: The 3-element chain $C$ has just two non-trivial congruences, namely one that identifies the middle element with the top and one that identifies the middle element with the bottom.  The projections of $C$ into the two quotients combine to give you an embedding of $C$ into the (4-element) product of the two quotients, and the image of that embedding is the subdirect product you want.


Help understanding a step in proving that $\Delta 1/|x| = \delta(x)$, in $\mathcal{D}'(\mathbb{R}^3)$.

Question: So, I'm currently taking a module in linear partial differential equations, and in said module we're taught much about the calculus (or theory) of distributions. There's a particular example that we study, in which we prove that $\Delta 1/|x| = \delta(x)$, in  $\mathcal{D}'(\mathbb{R}^3)$ (the set of distributions on the set of test functions on $\mathbb{R}^3$). I've included below a screenshot of some of the working seen in said example, and just below it I've elaborated on a question that I have from said working.

Here is my interpretation of the working shown above. In proving the desired claim, we arrived at the conclusion that
$$
\bigg{\langle}\Delta\frac{1}{|x|},\phi\bigg{\rangle} = \lim_{\varepsilon\to0}\int_{\mathbb{R}^{3}\setminus B_\varepsilon}\frac{\Delta\phi(x)}{|x|}~dx
$$
(for $\phi\in\mathcal{D}(\mathbb{R}^{3})$), and up to this point the working makes perfect sense. From here, we note that since $\phi\in\mathcal{D}(\mathbb{R}^{3})$, $\mathrm{supp}(\phi)$ is a compact set, meaning that we may instead integrate over a bounded subset of $\mathbb{R}^{3}\setminus B_\varepsilon$. In particular, we may let $R>0$ be sufficiently large so that
\begin{equation}
\bigg{\langle}\Delta\frac{1}{|x|},\phi\bigg{\rangle} = \lim_{\varepsilon\to0}\int_{B_R\setminus B_\varepsilon}\frac{\Delta\phi(x)}{|x|}~dx\tag{1}\label{1}
\end{equation}
Again, this makes perfect sense. From here, it is said that we apply Green's formula to arrive at the conclusion that
$$
\bigg{\langle}\Delta\frac{1}{|x|},\phi\bigg{\rangle} = \lim_{\varepsilon\to0}\bigg{(} \int_{B_R\setminus B_\varepsilon}\phi(x)\Delta|x|^{-1}~dx + \int_{\partial(B_R\setminus B_\varepsilon)}\frac{1}{|x|}\partial_n\phi(x) - \phi(x)\partial_n|x|^{-1}~dS\bigg{)}\tag{2}\label{2}
$$
where $n = -x/|x|$. It's at this point that I lose the plot somewhat. I'll try to include in the following list all the questions that I have regarding this working.
Question 1
I'll be completely honest: I'm not even completely sure which Green's formula is being referenced here. I assume it's the formula found in the statement of the conventional Green's theorem (the one of which Stokes' theorem is a generalization), but I have no idea how we might extract the above expression from any variation of the statement of Green's theorem. I understand that in order for us to actually be able to apply Green's theorem, we require that the domain of integration be bounded, hence why the observation that precedes \eqref{1} is important, but beyond that I'm rather lost. I had thought that maybe we're actually meant to apply Gauss' theorem (or the divergence theorem, rather) here, since $\Delta\phi(x) = \mathrm{div}(\nabla\phi(x))$, and this makes particular sense since:

The divergence theorem requires integration over a compact domain, and we know that $B_R\setminus B_\varepsilon$ can be made compact.
The derivative $\partial_n$, in addition to the fact that $n = -x/|x|$, seems to indicate that we are, in some way or another, evaluating the outward unit normal to the surface $B_\varepsilon$, which is an important quantity to bear in mind when applying the divergence theorem.

Although ultimately, I was once again unsure of how I was meant to proceed. In truth, it's primarily the first of the terms listed in \eqref{2} that's throwing me off, because both the application of Green's theorem, and the application of the divergence theorem, requires some-or-other manipulation of the domain of integration, and yet the first term listed in \eqref{2} demonstrates no manipulation in the domain of integration at all, so I remain rather lost in this regard.
Question 2
I'm not sure how we're meant to apply the derivative operator $\partial_n$. Particularly since $n = -x/|x|$, and $x\in\mathbb{R}^{3}$. It's mentioned in a subsequent claim that $n = -x/|x|\implies \partial_n = -\partial_r$, which makes intuitive sense, but I'm sure how to either show that this is rigorously true, or how to proceed, given this information.
These are the aspects of this working that confuse me at the moment. I've tried to cross-reference the working I've mentioned above with the working found in the mark scheme of past examination papers containing similar questions, and I've managed to posit that, in general, given an appropriate function, $f:\mathbb{R}^{3}
    \to\mathbb{R}$
$$
\lim_{\varepsilon\to0}\int_{\mathbb{R}^{3}\setminus B_\varepsilon}f(x)\Delta\phi(x)~dx = \lim_{\varepsilon\to0}\bigg{(} \int_{B_R\setminus B_\varepsilon}\phi(x)\Delta f(x)~dx + \int_{\partial(B_R\setminus B_\varepsilon)}f(x)\partial_n\phi(x) - \phi(x)\partial_nf(x)~dS \bigg{)}
$$
$\forall\phi\in\mathcal{D}(\mathbb{R}^{3})$, although, firstly, I don't know what constitutes an "appropriate" function in this case, and secondly, I don't imagine it'll be sufficient to simply commit this fact to memory in order to excel in the exam (I'm currently studying this problem as part of preparation for an exam).
Any advice in this regard is greatly appreciated. Also please do not hesitate to ask for any clarification as far as notation is concerned, I understand that this field is rather notation-centric, so I have no problem with clarifying what is meant by the symbols seen in this question.
Answer: Question 1:
See https://en.wikipedia.org/wiki/Green%27s_identities (Green's Second Identity - $\varepsilon = 1$ case). To derive this Green's Second Identity, this is nothing but a divergence theorem + product rule (which is basically what we call "integration by parts in $\mathbb{R}^n$") applied twice.
When a book says Green's formula, it could really mean a lot of things. For instance, from the same Wikipedia page, you can find Green's first and second identities (which could mean Green's formula), and Green's theorem (like you have mentioned), or even divergence theorem!
By applying Green's second identity directly, you should see $\partial_n$ and the terms in $\partial(B_R \setminus B_\varepsilon)$ almost immediately. (See that (2), by considering terms on the left and right, are a total of 4 terms, which you can see from Green's second identity.)
Question 2:
The intuitive picture that you have is absolutely correct, since the normal direction along the inner ball $B_\varepsilon$ should be pointing towards the origin (since the actual region is the annulus of radius $\varepsilon$ to $R$, as represented by $B_R \setminus B_\varepsilon$).
To be more rigorous, $\partial_n u$ is defined as the directional derivative (https://en.wikipedia.org/wiki/Directional_derivative) of the function $u$ in the $\mathbf{n}$ direction, where $\mathbf{n}$ is a unit vector. The formula is given by
$$\frac{\partial u}{\partial n} = \mathbf{n}\cdot \nabla u $$
for any $u$ (with the appropriate regularity).
Thus, we can look at this equation in the operator sense, ie
$$\frac{\partial}{\partial n} = \mathbf{n} \cdot \nabla. $$
You can then compute this, with $\mathbf{n} = -\frac{x}{|x|} \cdot \nabla $
Note that this is $\frac{x}{|x|} = \hat{\mathbf{r}}$. Furthermore, we can write the gradient in spherical coordinates as (see https://en.wikipedia.org/wiki/Del_in_cylindrical_and_spherical_coordinates)
$$\hat{\mathbf{r}}\frac{\partial}{\partial r} +  \hat{\boldsymbol{\theta}}(...) + \hat{\boldsymbol{\phi}}(...)$$
where $(...)$ are some expressions that do not really matter since we know that at each point, the basis vectors $\mathbf{r}, \hat{\boldsymbol{\theta}},$ and $\hat{\boldsymbol{\phi}}$ are orthonormal.
Thus, we have
$$-\hat{\mathbf{r}} \cdot [\hat{\mathbf{r}}\frac{\partial}{\partial r} +  \hat{\boldsymbol{\theta}}(...) + \hat{\boldsymbol{\phi}}(...)] = -\frac{\partial}{\partial r}.$$
Note that the part on spherical coordinates and orthonormality of these unit vectors can be computed directly through really tedious computations. (They are intuitively true; $\hat{\mathbf{r}}$ refers to the unit vector pointing in the direction of increasing $\mathbf{r}$, $\hat{\boldsymbol{\theta}}$ in increasing $\theta$, and so on)
Disclaimer: There might be an easier way to derive this, but this is the way I understand it.
Hope this helps!
Comment: You've saved a man's life today, I hope you know that! Thank you! I'm going to dissect this answer a bit, and I'll post any comments/questions here, in the meanwhile I'm going to mark your answer as correct. Thank you, again!
Comment: Sure, no problem!


Dividir array bidimensional em 2 arrays simples - PHP

Question: Estou realizando adaptações num sistema antigo e preciso criar uma nova rotina para dividir um array bidimensional em 2 arrays simples.
Digamos que a variável $query receba o array abaixo:
$query = array("SELECT * FROM teste WHERE nome in (?) and id in (?)", array('aaa', 1));

Meu objetivo é dividir esse array e fazer com que uma variável $sql receba:
SELECT * FROM teste WHERE nome in (?) and id in (?)
E outra, chamada $arg, receba:
array('aaa', 1)
Já tentei fazer essa divisão com implode, mas o retorno não foi o esperado.
E com explode sempre obtenho NULL.
Existe alguma função nativa do PHP que faça essa divisão? Ou pelo menos alguma rotina que possa fazer isso por meio da força bruta?
Obrigado desde já.
Answer: Você pode fazer isso usando o construtor void list ( mixed $varname [, mixed $... ] )
PHP:
$query = array("SELECT * FROM teste WHERE nome in (?) and id in (?)", array('aaa', 1));

list($sql, $arg) = $query;

echo $sql;
echo PHP_EOL.'-----------------------'.PHP_EOL;
var_dump($arg);

Resultado:
SELECT * FROM teste WHERE nome in (?) and id in (?)
-----------------------
array(2) {
  [0]=>
  string(3) "aaa"
  [1]=>
  int(1)
}

Comment: Era exatamente isso que eu precisava, obrigado!


Update RHEL Servers without Internet Connection

Question: I plan to have a few servers installed with RHEL, but the servers will not have Internet connection.
Is it possible to update RHEL servers without Internet connection?
Can I download the updated RPM packages from RHN and install them manually on the servers?
Comment: short answer: yes, you can. Might want to use yum local install to install the packages to sort the dependencies.
Comment: Where can I download the packages?
Comment: You get the downloads from [RHN](https://rhn.redhat.com/). You have to sign in with your account.
Answer: I answered this similar question on Stack Overflow. This is how I update offline machines.
I used to work on DOE classified systems that could never touch the public internet. There is a very easy way to do this as mentioned. Just use the ISO as a repo, and for my example to work, it needs to be a DVD image. (The way around that using disk {1,2,3} is to copy the files from each disk onto the local disk or a storage device)
You will need to install createrepo which for me involved two dependencies.
createrepo
deltarpm
python-deltarpm

mkdir -p /mnt/iso/rhel54
mount -o loop /path/to/rhel5.4.iso /mnt/iso/rhel54
cd /mnt/iso
createrepo .

It will look like this: [root@hostname iso]# createrepo .

44/20586 - rhel54/HighAvailability/Packages/PyQt4-4.6.2-8.el6.x86_64.rpm

Create /etc/yum.repos.d/shane.repo and add

[shane-repo]
baseurl=file:///mnt/iso/
enabled=1
gpgcheck=0

Then run yum update

Answer: A usual setup would be a proxy which downloads the updates from Red Hat and provides them to your local servers. This way only one server has to be connected to the internet. Your question is not clear, whether there is generally no internet access or only the mentioned servers are not allowed to access the internet.
Some proxy solutions also allow to download the patches with your desktop PC or whatever, put them on a proxy server and then publish them to your local network.
The Red Hat specific products are spacewalk and the Red Hat Network commercial products. This page has also some more explanations about the topic.
This is easier and more scalable as installing it manually on each server.
You could also search serverfault for patch management, spacewalk, rhel updates and get some more info on the topic.
EDIT:
Found this in another forum:
To update packages to a system without Internet connectivity, you need to download the ISO and then mount it locally. To download iso's, please check below given steps:

Log into your RHN account.
select your desired channel under the "Channels" tab.
then click "Easy ISOs" on the left or the "Download" link inside your selected channel.
For details, please follow the below kbase, http://kbase.redhat.com/faq/FAQ_58_1500.shtm
http://kbase.redhat.com/faq/FAQ_80_594.shtm

Once you download the iso's, follow the below given steps:

Create directories to mount the iso file.
mkdir -p /cdrom/iso
Mount the iso as loopback device.
mount -o loop <iso-name> /cdrom/iso
Replace  with the iso file.
Create a repository. The createrepo package needs to be installed on the system in order to run the following commands. createrepo is an optional package and is not installed by default.
cd /cdrom
createrepo .
yum clean all
Create a file /etc/yum.repos.d/file.repo as follows:
cat /etc/yum.repos.d/file.repo
[RHEL 5 Repository]
baseurl=file:///cdrom
enabled=1

Running yum should now work with the iso file as the source.
For details, please check following kbase, http://kbase.redhat.com/faq/FAQ_103_10415.shtm (as archived by Wayback machine).
Let us know if you have any further queries.
Comment: Just to clarify, the servers are not allowed to access the Internet at all.  So, I cannot do update using yum.
Comment: Take a look at my additions to my answer. This might help you, as it is a way to install the updates with no internet connection.
Answer: yum update doesn't always pull the repo immediately.  I have had to use rhn_register if you have no internet connection, and if you do have an internet connection you can use rhn_check instead in certain cases to draw from the newly create local cdrom repo.


Parametrization of probability in a limit for a random graph

Question:

I don't understand the part where the authot exchanges $p$ for $c/n$. This can only work if $c$ is a function of $n$ namely $pn$.
I hope somebody can tell me what the author is doing here and why he is allowed to first take $n\rightarrow\infty$ and then $c\rightarrow 0$ even though if $n\rightarrow \infty$ then automatically $c\rightarrow \infty$.
Can also someone tell me how the author comes to the conclusion that if $p=10^{-6}/n$ then $G(n,p)$ is unlikely to have a triangle and also how the second conclusion that if $p=10^6/n$ then $G(n,p)$ is likely to have a triangle  is even possible ? For example if $n<10^6$ then $p>1$ but this is not possible because $p$ is a probability ranging from 0 to 1.
Answer: Lots to explain here. Hope the following helps.
First, the parametrization of $G(n,p)$ as $p=c/n$ is a standard parametrization, sometimes called the coarse parametrization if $c$ is a constant. It just means that we define $c=pn$ and we will study different regimes of $G(n,p)$ depending on the value of $c$. For instance, its common to look for properties of $G(n,p)$ depending on the three cases $c<1$, $c=1$ and $c>1$. In general $c$ will be a function of $n$ indeed, but studying the case where $c$ is a constant often helps us understand how the general case behaves.
It is not true that $c\to\infty$ automatically when $n\to\infty$. For instance you could have :

$p=\frac{\log n}{n}$ and $c(n)=\log n$, then $c\to\infty$ when $n\to\infty$
$p=1/ n^2$ and $c(n)=1/n$, then $c\to 0$ when $n\to\infty$
$p=2/n$, then $c$ is a constant.

But in here, the author does not assume the asymptotic of $c(n)$. When he states the two different cases ($c\to 0$ and $c\to\infty$), it is to present the following fact :

If you have $p=c/n$, with $c$ a constant, then you know that the limit probability of having no triangle is exactly $e^{-c^3/6}$. Therefore if $p=c/n$ where $c$ is a very small constant, then the limit probability of having no triangle will be very close to $1$. If $c$ is very large, then the limit probability of having no triangle will be very close to $0$.

The author does not value
$$\lim_{n\to\infty} \lim_{c\to } \mathbb{P}[X=0]$$
He says, assume $p=c/n$, then
$$\lim_{c\to 0} \lim_{n\to\infty} \mathbb{P}[X=0] = 1$$
and
$$\lim_{c\to \infty} \lim_{n\to\infty} \mathbb{P}[X=0] = 0$$
This is why the author say that if $p=10^{-6}/n$, then the probability of no triangle is almost 1 : $$\lim_{n\to\infty} \mathbb{P}[X=0]=e^\frac{-c^3}{6}\approx 1$$
This helps concluding on the other cases as follow. Assume that $p=n^{-0.9}$. You can take $c$ a constant as large as you want, for $n$ large enough you will have $p>c/n$. Therefore because we know the limit probability when $c$ is constant is $e^{-c^3/6}$ which tends to $0$ when $c\to\infty$, then we know $\lim_{n\to\infty} \mathbb{P}[X=0]=1$. (caveat : we need some details on the monotonicity of the probability to make this argument formal.)
You conclude on the other case $p=1/(n \ln n)$ in the same way with $p<c/n$ for $c$ as small as you want.
Regarding your last remark, it's true that $p$ is ill-defined if $n<10^6$, but we are only interested in asymptotic ($n\to\infty$), so you can assume " $n$ is large enough".
Comment: Thank you so much I have to write a seminar report about the 0-1 laws and this helped me tremendously


Gostaria de conectar rails ao Intel xdk

Question: Meu objetivo final é  criar um app no xdk que interaja com o rails. Se ninguém souber exatamente como funciona mas der uma luz de como acessar o sqlite com ruby e javascript já ajuda muito. Tenho algumas dúvidas da maneira correta de se fazer isso. Por exemplo o ideal é criar um initialize no rails? Não posso acessar só com javascript por causa da segurança certo? Existe gem para isso? Obrigado.
Answer: Uma alternativa é você criar uma API REST com o rails , utilizando por exemplo a gem grape, e consumir esses dados via JSON na sua aplicação Intel XDK. Quanto a questão de segurança será necessário que vc configure os CORS no rails para ele permitir acesso externo. No exemplo do link ele permite acesso apenas via get mas vc pode implementar os outros métodos put, delete, post....

Gostaria de conectar rails ao Intel xdk


WPF DataGrid - Virtualised - select all

Question: With a WPF virtualised DataGrid I need to employ a 'select all' method. Iterating though the grid itself won't work as it will only select the records that at visible in the UI - but of course if they are selected using the mouse they are retained. I'm guessing that something must change in the DataTable, but what? If so can it be manipulated so that all the records are selected in the DataGrid?
Thanks
======================== ADDED===========================
Eran - thanks for your reply but having a job wiring this up

Create DataGrid
 Dim DGV As New CustomControl.DGVx
    With DGV
        .Name = "Invoice_AdHoc_DGV"
        .AutoGenerateColumns = False
        .SelectionMode = SelectionMode.Multiple
    End With
    RegisterControl(Invoice_AdHoc_Grid, DGV)
    RightGrid.Children.Add(DGV)

Bind to DataTable
DGV.ItemsSource = AdHocDT.DefaultView

Created the class from your answer
Public Class ObjectSelectAll
Implements System.ComponentModel.INotifyPropertyChanged
Public Property Name() As String
Private vIsSelected As Boolean
Public Property IsSelected() As Boolean
Get
    Return vIsSelected
End Get
Set(value As Boolean)
    vIsSelected = value
    RaiseEvent PropertyChanged(Me, New System.ComponentModel.PropertyChangedEventArgs("IsSelected"))
End Set
End Property

Public Event PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged

End Class
Comment: i would use a select all logic on my .cs objects and not on the visual objects , what do you mean by selected , do you have a chekcbox column bound to some IsSelected property ?
Comment: Clicking on the row selects it (IsSelected = True) - I would like to do the same thing if the user clicks a 'select all' button. Is there a way to do this with the DataTable?
Comment: you could create a row style which indicates a value from your  objects bound to a rows IsSelected and them when clicking select all
update the bound propertyin your objects .
as for the UI only the "Realized" objects would be viewably "Selected"
Comment: I can iterate though the DataTable and get the required result, but it would be great if the change in colour/font could also be replicated in the DataGrid as though it was a mouse selected row - everything I have tried only works for the visible part of the UI.
Comment: the answer iv'e given you selectes the rows , and is visible in the UI .
Comment: I am assuming (and this may be where I have it all wrong) that something changes in the backend DataTable when the user selects a row - so that when it scrolls back into view it is still showing as selected?
Comment: the bound object that gets visulaized updates the IsSelected state of the row via binding.
Comment: What are the objects (obj1, obj2, obj3...) that you are referring to?
Comment: they are my grid's ItemsSource
Comment: If the ItemsSource is a DataTable how do I wire that in?
Answer: cs :
    private List<MyObject> _items;
    public List<MyObject> Items
    {
        get
        {
            if(_items == null)
                _items = new List<MyObject> { new MyObject { Name = "obj1" }, new MyObject { Name = "obj2" }, new MyObject { Name = "obj3" }, new MyObject { Name = "obj4" } };
            return _items;
        }
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        foreach (var item in Items)
        {
            item.IsSelected = true;
        }
    }
}

public class MyObject : INotifyPropertyChanged
{
    public string Name { get; set; }

    private bool _isSelected;
    public bool IsSelected
    {
        get { return _isSelected; }
        set
        {
            _isSelected = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("IsSelected"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

xaml :
    <Button Click="Button_Click_1" Content="Select All"/>

    <DataGrid Grid.Row="1" AutoGenerateColumns="False" ItemsSource="{Binding Items}">
        <DataGrid.RowStyle>

        </DataGrid.RowStyle>

        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Name}"/>
        </DataGrid.Columns>

    </DataGrid>

Answer: Finally managed to resolve this issue
Added another column to the DataTable
 With AdHocDT.Columns
                 .Add("Selected", GetType(Boolean))
            End With

When 'Select All' is clicked set this to True for all rows and in the Grid the value is updated to true as well, then add this to ensure that the Grid shows it as selected when the virtual data is scrolled into view
Private Sub Invoice_AdHoc_DGV_ItemsChanged(sender As Object, e As EventArgs)
    Try
        Dim DGV As CustomControl.DGVx = Invoice_AdHoc_Grid.FindName("Invoice_AdHoc_DGV")
        Dim i As Integer = 0
         For Each Row As DataRowView In DGV.Items
            Dim vRow As DevComponents.WPF.Controls.AdvGridRow = CType(DGV.ItemContainerManager.ContainerFromItem(DGV.Items(i), False), DevComponents.WPF.Controls.AdvGridRow)
            If Not vRow Is Nothing Then
                If Row("Selected") = True Then
                    vRow.IsSelected = True
                End If
            End If
            i += 1
        Next

    Catch ex As Exception
        EmailError(ex)
    End Try
End Sub

and handle the event
AddHandler DGV.ItemContainerManager.VisibleContainersChanged, AddressOf Invoice_AdHoc_DGV_ItemsChanged

Now the Grid shows all the rows as selected :-)

WPF DataGrid - Virtualised - select all


Background Image is not showing in Laravel

Question: I am trying to show background image in my Laravel project from css.
But image is not showing. I have checked the image path and it is correct.
I am using Voyager Admin Panel.
I am saving image path from config/filesystems.php
'public' => [
        'driver' => 'local',
        'root' => public_path('images'),
        'url' => env('APP_URL').'/public/images',
        'visibility' => 'public',
    ],

html

banner_image }}')">

And my image path is public\images\image_name.
In console I have found the below error

Actual path is public/images/banners/March2019/image_name
But here shown public/images/bannersMarch2019image_name.
No slash.
Comment: Take a look in F12-->style and see what happend there..
Comment: yes I have checked from `inspect element` too. Path is shown correctly
Comment: Do you have any error in console? Also try to set `height/width` to div
Comment: yes I have found error in console. And there is no `slash` between folder and image name ! But why !
Comment: Are you using Voyager admin panel ?
Comment: Can you please update how are you saving image path into database ?
Comment: @AbhinavVerma...yes voyager admin panel
Comment: if your files are stored in storage folder then no need to add public in image url
Comment: @ViperTecPro...I have updated my post
Answer: Try this code in your html:

banner_image}}');">

Using asset helper function to reach your actual path. I hope it would helpful.
Answer: This is not a laravel issue but a bootstrap issue. Have a look at bootstrap > components > carousel
Try this:

        banner_image) }}" class="d-block">

Comment: where is the close of `'`
Comment: @Dimitri Mostrey....... in my carousel I have to set image as background not `img src`.
Comment: {{ ? {{ ? why two times ?
Comment: If this `$banner[0]->banner_image` contains proper path then `{{ url( $banner[0]->banner_image) }}` would be enough, i suggest save only file name to database this should only return `$banner[0]->banner_image` ...`some_filename`
Comment: I admit there was a mistake in the code, I have corrected it. In any case, it is better to make use of Laravel's integrated file system (https://laravel.com/docs/5.7/filesystem). In this case it would be `Storage::url('images/' . $banner[0]->banner_image);`
Answer: you shouldn't add public in your url method, webserver root is at public, therefore your code should be:

banner_image }}')">

Answer: Your screenshot suggest/folder structure that you might be using Voyager Admin panel, if that is the case then you can use your image in below manner :

banner_image) }}')">

This should help you, i would suggest please read voyager docs carefully.
Answer: lets say this is your div tag in views file

other pages wont access it since its limited to give path,
add / before images
eg


Choosing 4 people from 5 pairs

Question: My question is this:

$4$ students are chosen at random from $5$ pairs of $2$ students (i.e. $10$ students). What is the probability that no students are chosen from the same pair (each of the 4 chosen students is selected from a different group of two)?

I am very stuck on this question. I think it is $10C4$ - ways that both students of one group are chosen - ways that both students of $2$ groups are chosen, but I cannot figure out how to find the probability that both students of one group are chosen.
Any guidance would be helpful.
Comment: Do you know the principle of inclusion and exclusion?
Comment: Instead of using a subtraction approach, try just counting the number of "good" outcomes. Choosing a good outcome amounts to choosing 4 different pairs from the 5 pairs and then choosing one of 2 people from each of the 4 chosen pairs.
Answer: Method 1: Ordered selections.
There are $10 \cdot 9 \cdot 8 \cdot 7$ ways to make an ordered selection of four of the ten students.
There are $10 \cdot 8 \cdot 6 \cdot 4$ ways to make an ordered selection of four students from different pairs.
Hence, the probability that no two students from the same pair are selected is
$$\frac{10 \cdot 8 \cdot 6 \cdot 4}{10 \cdot 9 \cdot 8 \cdot 7}$$
Method 2: Unordered selections.
There are $\binom{10}{4}$ ways to select four of the ten students.
There are $\binom{5}{4}$ ways to select four of the five pairs from which to select a student.  For each such pair, there are two ways to select a student from that pair.  Hence, the number of ways to select a student from four different pairs is
$$\binom{5}{4}2^4$$
Hence, the probability that no students from the same pair are selected is
$$\frac{\dbinom{5}{4}2^4}{\dbinom{10}{4}}$$
Method 3: Complementary counting.
As mentioned above, there are
$$\binom{10}{4}$$
ways to select four of the ten people.
We count selections in which both members of at least one pair of people are selected.
Both members of a pair are selected:  There are five ways to select the pair from which both members are selected and $\binom{8}{2}$ ways to select two of the other eight people.  Hence, there are
$$\binom{5}{1}\binom{8}{2}$$
such selections.
However, if we subtract this amount from the total, we will have subtracted too much since we will have subtracted each selection in which both members of two pairs are selected twice, once for each way we could have designated one of those two pairs as the pair from which both members were selected.  We only want to subtract such cases once, so we must add the cases in which both members of two pairs are selected to our total.
Both members of two pairs are selected:  There are
$$\binom{5}{2}$$
ways to select the two pairs from which both members are selected.
Hence, by the Inclusion-Exclusion Principle the number of favorable cases is
$$\binom{10}{4} - \binom{5}{1}\binom{8}{2} + \binom{5}{2}$$
Therefore, the probability that no two students from the same pair are selected is
$$\frac{\dbinom{10}{4} - \dbinom{5}{1}\dbinom{8}{2} + \dbinom{5}{2}}{\dbinom{10}{4}} = 1 - \frac{\dbinom{5}{1}\dbinom{8}{2} - \dbinom{5}{2}}{\dbinom{10}{4}}$$
Comment: A very comprehensive answer !

Choosing 4 people from 5 pairs


conntrack -L does not show any connection

Question: I am writing a utility which will use Conntrack commands to show the connection states. I am a beginner and I wanted to play with the Conntrack before I could start my work. So, when I tried conntrack -L conntrack, I get the output which says there are no flows. But, I do have a telnet and one ssh connection to the machine, which is seen in netstat as in ESTABLISHED state.
I also did tail -f /proc/net/ip_conntrack but didn't see any output.
Am I missing something?
Answer: You can use iptables module 'conntrack' to do something, then conntrack -L will have output.
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

Answer: You'll have to modprobe nf_conntrack and it's ipv4/ipv6 modules.

modprobe nf_conntrack
modprobe nf_conntrack_ipv4
modprobe nf_conntrack_ipv6
Comment: It seems there's no nf_conntrack_ipv4 nor nf_conntrack_ipv6 modules in Fedora 31 stock kernel (I have installed conntrack-tools and libnetfilter-conntrack packages). I have exactly the same problem but I just have nf_conntrack and nf_conntrack_netlink loaded. I don't know what can be...My Nftables version (0.9.1) or Kernel (5.5.9) isn't compatible?
Answer: If /proc/net/ip_conntrack is empty, you may have conntrack modules not loaded. Try
modprobe nf_conntrack

Comment: I did lsmod | grep nf_conntrack. It shows that conntrack is loaded already. Do I need to configure firewall or something for this to work? As per my understanding, it is not needed for basic testing.
Comment: I dont know how but it started to work, thanks!!


How do I properly delete a field collection?

Question: I added a new field (houses) to user accounts. This field is a list of a collection fields.
I need to list all the fields in a user field collection (I can via the FieldCollectionItem::loadMultiple(array(12,45,...)) and remove all of them.
This is my code:
$array_of_fieldcollection = get_array_of_fieldcollection_of_user();

$fieldscollection = FieldCollectionItem::loadMultiple($array_of_fieldcollection);

foreach($fieldscollection as $fieldcollection){
  $fieldcollection->delete();
}

When I execute it and go to the user profile edit page, I get this error:

The website encountered an unexpected error. Please try again later.
  More detail in the Apache log.
TypeError: Argument 1 passed to Drupal\Core\Entity\Entity\EntityFormDisplay::buildForm() must implement interface Drupal\Core\Entity\FieldableEntityInterface, null given, called in /var/www/www.orlengine.com/modules/contrib/old_field_collection/src/Plugin/Field/FieldWidget/FieldCollectionEmbedWidget.php on line 71 in drupaldirectory/core/lib/Drupal/Core/Entity/Entity/EntityFormDisplay.php on line 159, referer: https://192.168.1.45/user/9

Isn't my code the proper way to delete all the field of a field collection?
Answer: The code you've shared is correct. The problem is that when we attach a Field Collection field to "User" entity the Host Entity of Field Collection is not set.
Because of which when we delete a Field Collection Entity programmatically the Host Entity field value (i.e. User in this case) is not updated with deletion. This causes Drupal to load Field collection which doesn't exists in system.
Rewriting the deletion code below:
use Drupal\field_collection\Entity\FieldCollectionItem;

// Load all field collections to delete.
$field_collections = FieldCollectionItem::loadMultiple(array(1, 2));
foreach($field_collections as $field_collection){
  // Delete field collection.
  $field_collection->delete();
}

Comment: but in the code source, the delete method of a fieldCollectionItem contains "$this->deleteHostEntityReference();". So, if I delete a FieldCollectionItem, the hos entity reference (here the user) must be delete no ? (file field_collection/src/Entity/FieldCollectionItem.php ) However, if I user the delete method of the FieldCollectionItem, I have the error I show in my fisrt post
Comment: You're right, and that works fine with node, but not with user entity. Because when we attach field collection to user entity, and save user the host entity is not set properly of field collection, check my comment above.
Comment: So, you confirm me the solution is to load the user entity and delete manually the field who contain the fieldcollection reference ? (no properly way ..)
Comment: Yes, until we've a proper fix for host entity when using with user entity
Answer: I encountered the same error when deleting field collection items on User entities. Below some code to unset the field manually on the User entity.
$id = 'Your FC field id';
$field = 'Your FC field name';

public function getFieldDelta($id, $field) {
  $fields = $this->get($field);

  foreach ($fields as $delta => $item) {
    if ($item->value == $id) {
      return $delta;
    }

  }
}

$delta = $this->getFieldDelta($id, $field);
unset($user->$field[$delta]);
$user->save();

The code sample above has a function getFieldDelta() that returns the delta of a field collection item if the provided item id matches one in the fields. With the delta the item in the user field is unset.


Como trocar uma palavra entre um limite criado por dois pontos específicos dentro de uma string?

Question: Entre a palavra fogo e a palavra gelo existe um conteúdo, e o objetivo é mudar esse conteúdo por sobrenatural
código:
s = "1 fogo bom dia gelo 2 fogo boa tarde gelo 3 fogo boa noite gelo 4"

s = s.replace('\n\n','\t')
start = 'fogo'
end = 'gelo'

for i in range(len(s)): #1 fogo sobrenatural gelo 2 fogo sobrenatural gelo 3 fogo sobrenatural gelo 4
  if s[i:i+len(start)] == start:
    for j in range(i+len(start), len(s)):
      if s[j:j+len(end)] == end:
        g = s[i + len(start):j]
        v=s.replace(g,' sobrenatural ')
        print(v)
        break

O print como está saindo:
1 fogo sobrenatural gelo 2 fogo boa tarde gelo 3 fogo boa noite gelo 4
1 fogo bom dia gelo 2 fogo sobrenatural gelo 3 fogo boa noite gelo 4
1 fogo bom dia gelo 2 fogo boa tarde gelo 3 fogo sobrenatural gelo 4

O print correto seria:
1 fogo sobrenatural gelo 2 fogo sobrenatural gelo 3 fogo sobrenatural gelo 4

Answer:
Edit:
Conforme lembrado nos comentários pelo usuário hkotsubo foi adicionado o padrão \b que corresponde a string vazia, apensado ao inicio e ao final de padrão determinando um limite formal da palavra a ser correspondida assim evitando a captura de "Botafogo .... gelol", "fogos ... congelou",...

Ao invés de vasculhar uma string, em um conjunto de laços, caractere por caractere buscando as strings delimitadores para então fazer a substituição em uma atividade propensa a erros. Substitua um conjunto de caracteres delimitados por duas palavras específicas utilizando expressões regulares, que em Python são usada através do módulo re.
No seu caso específico, uma string delimitada pelas palavras fogo e gelo, pode ser feita com o padrão de correspondência (?<=\bfogo\b).+?(?=\bgelo\b), onde:

(?<=\bfogo\b): padrão de correspondência lookbehind. Faz a correspondência apenas se a string for precedida pela string fogo.
.+? :  corresponde a um ou mais caracteres quaisquer de forma não gananciosa, ou seja fará a menor correspondência possível.
(?=\bgelo\b): padrão de correspondência lookahead. Faz a correspondência apenas se a string for seguida pela string gelo.

Para fazer a substituição pode ser usado o método re.sub(pattern, repl, string, count=0, flags=0). No caso o exemplo utilizou a flag re.IGNORECASE que faz a correspondência não diferenciando maiúsculas de minúsculas:
import re

s = "1 fogo bom dia gelo 2 fogo boa tarde gelo 3 fogo boa noite gelo 4"

p = r'(?<=\bfogo\b).+?(?=\bgelo\b)'                       #Determina o padrão de captura.

r = re.sub(p, " sobrenatural ", s, flags=re.IGNORECASE)  #Faz capturas e substituições.

print(r)
# 1 fogo sobrenatural gelo 2 fogo sobrenatural gelo 3 fogo sobrenatural gelo 4

Teste no Repl.it
Comment: Eu só acrescentaria o `\b` para evitar casos como "Botafogo etc gelol", "fogos etc congelou", etc - não ficou claro se é pra tratar esses casos, mas enfim...


Google Sheets API POST request

Question: I am always getting -1 as a response from the httpClient.POST method, don't you know why? If I try to POST to another endpoint (not Google API), everything works fine.
void sendMeasuredData() {
  Serial << "Sending data to Google Sheets" <<endl;
  StaticJsonBuffer<250> JSONBuffer;
  JsonObject& JSONencoder = JSONBuffer.createObject();

  JSONencoder["range"] = "Measurements!A1:C1";
  JSONencoder["majorDimension"] = "ROWS";

  JsonArray& values = JSONencoder.createNestedArray("values"); //JSON array
  values.add("TIMESTAMP"); //Add value to array
  values.add(temperature); //Add value to array
  values.add(humidity); //Add value to array

  char JSONmessageBuffer[250];
  JSONencoder.prettyPrintTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
  Serial << JSONmessageBuffer << endl;

  HTTPClient httpClient;
  httpClient.begin("https://sheets.googleapis.com/v4/spreadsheets/SPREADSHEET_ID/values/Measurements!A1:C1:append?valueInputOption=USER_ENTERED","F9:C3:81:B3:84:13:E8:94:87:B1:87:6D:8A:15:75:27:09:56:93:BE");

  httpClient.addHeader("Content-Type", "application/json");
  httpClient.addHeader("Authorization", "Bearer "+access_token);

  int httpCode = httpClient.POST(JSONmessageBuffer);
  String payload = httpClient.getString();
  Serial << "GoogleSheets Response: " << httpCode << endl;
  Serial << payload << endl;

  httpClient.end();
}

Comment: Can you read from the sheet?
Comment: Actually yes, i can even write into the sheet, but only via Postman. And when I use another endpoint in my code (for example zapier webhook), everything works properly.
Comment: Been playing with this and think it's because of https:// not http:// Try an http enpoint and see if that works maybe?
Answer: You might have to add ?key at the end.

Google Sheets API POST request


iOS 7 upgrade makes annotation call out accessories stay open after clicked

Question: With the new iOS 7 update, my custom annotation call out accessories stay open forever unless I restart the app, or refresh the annotations. For example, if a user pick's a location in New York and returns to the map to continue their search after viewing the location, the New York location's call out accessory would remain open until I restart the app. It becomes an issue when multiple locations have been viewed because numerous call outs are open on the map. My question is 1, how can I prevent this from happening? And 2, why do the annotation call outs stay open now that iOS 7 has been introduced, this was never an issue before? Thanks for your time with this, any help is greatly appreciated, thanks!
<code>-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:     (id<MKAnnotation>)annotation
{
MKAnnotationView *vw = [[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"boardwalk"];

Annotation *myant = (Annotation *)annotation;

//show custom annotation for user loc
if (annotation == mapView.userLocation)
{
    [mapView.userLocation setTitle:@"I am here!"];
    NSString *latitude = [NSString stringWithFormat:@"%f", mapView.userLocation.coordinate.latitude];
    NSString *longitude = [NSString stringWithFormat:@"%f", mapView.userLocation.coordinate.longitude];
    NSString *userLocDisplay = [NSString stringWithFormat:@"@ Lat: %@ / Lon: %@", latitude, longitude];
    [mapView.userLocation setSubtitle:userLocDisplay];
    return nil;
}
else if([myant.typeIdentifier isEqualToString:@"park"])
{
    vw.image =[UIImage imageNamed: @"prkmarker.png"];
}

    //set up annotation view
    vw.enabled = YES;
    vw.canShowCallout = YES;

    UIImageView *imgView = [[UIImageView alloc]
                   initWithImage:[UIImage imageNamed: @"GTAIcon.png"]];
    vw.leftCalloutAccessoryView = imgView;
    vw.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

    return vw;
}
</code>
Comment: can you post the code?
Comment: are you implement setSelected: method?
Comment: Thanks for the response! I updated the comment with the code.
Answer: Implement this delegate method,
<code>- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view
{
    [view.leftCalloutAccessoryView removeFromSuperview];
    [view.rightCalloutAccessoryView removeFromSuperview];
}
</code>
Comment: I was finally able to test this method in my app and it did not work. I appreciate the effort but I am still searching for the solution.
Comment: Now I have a MKMapView that has a number of annotations. Selecting the pin displays the callout and pressing the accessory pops a new view controller onto the stack. However when I press back from the new VC, the callout accessory remains open. How do I close it?
Comment: Remove the callout in viewWillAppear


User Specific Php.ini When php is ran as a module?

Question: I have a php setting that can only be changed in the ini file. I can't change this setting in the global php.ini due to conflicts, so I'll need to have this user specific. Can this be done if php is ran as a module? Or must I change php run as a cgi?
Seems like the best answer is "not really", but you can sneak around changing some parameters using tricks below.
Answer: I'm not aware of any way to specify a separate php.ini when using PHP as an Apache module, only when using PHP as a CGI. That said any of the configuration options in the php.ini can be changed in the .htaccess file as shown at http://php.net/configuration.changes so long as you have AllowOverride set in the Apache config set to Options or All.
I've done this on many of my sites to change common PHP configurations. I would assume that you're not needing to change every setting so the number should be easily managed by adding the options to your .htaccess file within the directory you need the changes in.
The following is one I use on a couple sites to change the include_path as well as set the auto_prepend_file and auto_append_file settings. For boolean flag items just use php_flag instead of php_value.
<IfModule mod_php5.c>
    php_value auto_prepend_file 'header.inc.php'
    php_value auto_append_file 'footer.inc.php'
    php_value include_path '/path/to/private/includes:/usr/share/pear'
</IfModule>

Comment: This is good, but the value I need to change is a php.ini only
Answer: I overrode the handler for php for a php cgi wrapper and was able to specify a php.ini file
To do this:
create a htaccess file in the folder you wish to modify with something like this:
Action php5-cgi /cgi-bin/php5-cgi.cgi
AddHandler php5-cgi .php

Then create a file 'php5-cgi.cgi' with something like this:
#!/bin/sh
exec /usr/bin/php-cgi "$@" -c "/home/user/php.ini"

Set Permissions on this file to execute as the "user". Then run a test file with phpinfo(1); to see if you have your ini file loaded.
Thanks for everyones help!!
Answer: All details are here : http://php.net/configuration.changes
Comment: That is helpful for changing php.ini settings, but it doesn't say if one would be allowed to change the ini file itself. I'm trying to change a setting that is php.ini only
Comment: What is the setting you want to change ?
Comment: Well really what I'm trying to do is use two different 'zend_extension' settings which conflict with each other (xdebug & zend optimizer). I would like to use the xdebug globally and only the zend optimizer in the account that requires it
Comment: Ok, I see, you can run php as cgi but it will be slow. I would suggest to start 2 instance of apache (eg. one running on port 8080 and the other on 8081) each one with the php settings you want. Then use another apache (or any other software than can do reverso proxy) instance on port 80 acting as a reverse proxy to both apache.
Of course this is a less easy things to setup.
Comment: Well, that sounds crazy, but i'll look into that. Since you know your stuff, is is possible to reassociate php files with a different handler which runs a could be a cgi version of php? I was reading this online but didn't really understand if it would even apply.
Comment: Yes you can add something like :
 AddHandler php-as-cgi .cgiphp
 Action php-as-cgi /cgi-bin/php
Answer: Basically, no.
From the PHP manual:

The configuration file (php.ini) is
  read when PHP starts up. For the
  server module versions of PHP, this
  happens only once when the web server
  is started. For the CGI and CLI
  version, it happens on every
  invocation.
Answer: You may use Apache "php_admin_value" per vhost/user.
IIRC, you may redefine every php.ini value using this command


How to add two buttons in a bar in linear view in Android?

Question: I have two buttons in a linear view and I want to add them to a bar.
How can I create a bar that appears at the bottom with the buttons in it?
Answer: You can use a relativelayout to make a bar appear bottom always like
<RelativeLayout android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:layout_alignParentBottom="true">

    </LinearLayout>
</RelativeLayout>

Answer: You also can use

a FrameLayout: http://xjaphx.wordpress.com/2011/06/25/create-floating-view-using-framelayout/
a RelativeLayout: http://xjaphx.wordpress.com/2011/06/25/ui-design-keep-the-bar-floating/


Drupal 7 - HTTP/AJAX/JSON responses at same URL with Accept Header (like D8)

Question: Drupal 8 has this new amazing in-built functionality for handling requests from browsers and via AJAX at the same URL using the Accept header, which makes the CTools way of adding "nojs" to URLs, and then changing that to "js" in the JavaScript seems like a clever but antiquated hack.
Is there a cleaner way to do this, that could be considered a "best practice" for Drupal 7 going forward, that is more inline with how things are now done in Drupal 8?   Also, how does a traditional ajax response versus a json response factor into this?
Code examples would be highly useful here.
Comment: Probably not a small job - off the top of my head...you'd need to provide JSON versions of everything you want JSON representations of (I guess you could have something generic for, say, entities, but again, lots of code), and override all the relevant page delivery callbacks to become accept-header-sensitive. I think (only think, haven't checked) there'd be at least one core patch required. As far as AJAX/JSON goes, presumably you'd want to return the same data for both, so AJAX requests should include an accept header too. But, hey, it's Drupal - maybe someone's already done it :)
Answer: I am not sure whether this is clean or "best practice" but I am currently using something like this:
<code>  // If the request has the header 'Accept: application/json'
  // return the output in JSON format and stop.
  if ($_SERVER['HTTP_ACCEPT'] == 'application/json') {
    drupal_add_http_header('Content-Type', 'application/json; utf-8');
    print json_encode($strings);
    exit;
  }
</code>
To see it in the context, here is the whole function:
<code><?php
/**
 * Menu callback: translations/search.
 *
 * Search strings and translations using various filters.
 *
 * If the request header 'Accept: application/json' is set, then
 * the output will be in JSON, otherwise it will be an HTML page.
 * For example:
 *   curl -k -i -H 'Accept: application/json' \
 *        'https://dev.l10n.org.xx/translations/search?lng=sq&words=space'
 */
function btrClient_search() {
  // Get the search parameters from the GET request.
  $params = btrClient_get_search_params();

  // Get the strings that match the search params.
  $btr = btr_user_is_authenticated() ?
    wsclient_service_load('btr') :
    wsclient_service_load('public_btr');
  $result = $btr->search($params);
  $filter = $result['filter'];
  $pager = $result['pager'];
  $strings = $result['strings'];

  // If the request has the header 'Accept: application/json'
  // return the output in JSON format and stop.
  if ($_SERVER['HTTP_ACCEPT'] == 'application/json') {
    drupal_add_http_header('Content-Type', 'application/json; utf-8');
    print json_encode($strings);
    exit;
  }

  // Add the CSS and JS files.
  drupal_add_css(drupal_get_path('module', 'btrClient') . '/editor/editor.css');
  drupal_add_js(drupal_get_path('module', 'btrClient') . '/editor/jquery.worddiff.js');
  drupal_add_js(drupal_get_path('module', 'btrClient') . '/editor/editor.js');

  // Add RTL style if the current language's direction is RTL.
  $languages = btrClient_get_languages();
  $lng = btrClient_get_translation_lng();
  if ($languages[$lng]['direction'] == LANGUAGE_RTL) {
    drupal_add_css(drupal_get_path('module', 'btrClient') . '/editor-rtl.css');
  }

  // Set the title.
  drupal_set_title(t('Search Translations'));

  // Add the filter form.
  $output = array(
    drupal_get_form('btrClient_filter_form', $filter),
  );

  // Output the strings.
  if (empty($strings)) {
    drupal_set_message(t('No strings found. Try adjusting the filter options.'));
  }
  else {
    pager_default_initialize($pager['number_of_items'], $pager['items_per_page']);
    $output[] = drupal_get_form('btrClient_translate_form', $strings, $lng);
  }

  return $output;
}
</code>
(Or check it out here: http://cgit.drupalcode.org/btrclient/tree/includes/search.inc
Comment: Thanks. This might be a good way to get going.  I'm wondering now if its only part of the puzzle going on what @Clive said in his comment above.


Help with view filters

Question: I have a view using one content type: fee_schedule
The view contains fields for species, keywords (hidden), and the title.
The filters need to show ALL species except when searching by keywords.  The keywords field and the title field are combined using Global Combine fields filter that is exposed.
Here's the issue:  When someone uses the exposed species drop down, it works as expected.  It shows the 'All' species and which ever species they selected.  But when they put in keywords (like 'bulk') then it still shows All species (even though these species do not have 'bulk' as a keyword), along with the species that do have the keyword 'bulk'.  When searching using keywords, I need the view to display ONLY the species with the keyword.  When searching by species, I need it to show the content with All species and the specific species they selected.
Here's the link to the view: https://vdl-dev.umn.edu/services-fees
I am using and/or filtering as follows:
Content Published: yes AND
Content Type: Fee Schedule AND
Global Combined fields filter exposed (title and keywords) AND
Content Species (each specific species but not All)
OR
Content Species (All is only selected)
Maybe I can't do what I need to do using views.  Any help much appreciated.
Comment: It sounds like all filters need to be AND. Otherwise you need faceted search.
Answer: Your description is very confusing, I hope I was able to understand your problem in the end.
You've framed it as if you're applying the exposed filters and then looking at the views results. But in the end you're looking back at the Exposed filters.
The module that can help you is Views Selective Filters.

you get dynamic dependent filters, that is, when the value of one filter is changed, the list of options of the selective filters are updated accordingly to the trimmed down result set.

Help with view filters


VBScript to copy text from a specific field from Web Page

Question: I have a vbscript code that opens a webpage, inserts a query and runs the query.  What I need is a way to extract the results of that query to an Excel spreadsheet.
Here is my code so far:
    Call Main
Function Main
    Set IE = WScript.CreateObject("InternetExplorer.Application", "IE_")
    IE.Visible = True
    IE.Navigate "http://www.paymentscouncil.org.uk/resources_and_publications/sort_code_checker/"

Set xl = CreateObject("Excel.application")
xl.Application.Workbooks.Open "U:\Test\Test2.xlsm"
xl.Application.Visible = True

loopCount = 2

Do while not isempty(xl.Cells(loopCount, 1).Value)
  Dim i
  Dim value

    a = xl.Cells(loopCount, 1).Value
    b = xl.Cells(loopCount, 2).Value
    c = xl.Cells(loopCount, 3).Value

Wait IE
    IE.Document.All.Item("sortcode1").value = a
    IE.Document.All.Item("sortcode2").value = b
    IE.Document.All.Item("sortcode3").value = c
    IE.Document.getElementsByName("Check Sort Code").Item(0).Click

loopCount = loopCount + 1
Loop

End Function

Sub Wait(IE)
  Do
    WScript.Sleep 500
  Loop While IE.ReadyState < 4 And IE.Busy
End Sub

Can anyone tell me how to extract the results?
Answer: Since they are nested under a
 tag with a class name, you can utilize the paragraph class to find the html of the results.
Class Name: scv_success_untick

Institution: <textarea readonly="">HALIFAX (A TRADING NAME OF BANK OF SCOTLAND PLC)</textarea>

Class Name: scv_success_untick_branch

Branch/Office: <textarea readonly="">EASTCOTE</textarea>

With these class names, we can iterate through all the
's and check the classname and collect the innerHTML once found.
    Dim result
    Set objElms = IE.Document.getElementsByTagName("p")
    For Each objElm In objElms
        If objElm.className = "scv_success_untick" Then
            result = objElm.innerHTML
        End If
    Next

Since we can't target the textarea directly, we'll have to parse out the HTML to do so. To fix this, I wrote a small replace() function that strips out all html tags in a string.
            Do While InStr(result, ">") > 0
                result = Replace(result, Mid(result, InStr(result, "<"), InStr(result, ">") - InStr(result, "<") + 1), "")
            Loop

Now that we have stripped the results, all we have is the following result:
Institution: HALIFAX (A TRADING NAME OF BANK OF SCOTLAND PLC)
Updated Code Below.
Main
Function Main
    Set IE = WScript.CreateObject("InternetExplorer.Application", "IE_")
    IE.Visible = True
    IE.Navigate "http://www.paymentscouncil.org.uk/resources_and_publications/sort_code_checker/"

    Set xl = CreateObject("Excel.application")
    xl.Application.Workbooks.Open "U:\Test\Test2.xlsm"
    xl.Application.Visible = True

    loopCount = 2

    Do While Not IsEmpty(xl.Cells(loopCount, 1).Value)
        Dim i
        Dim value

        a = xl.Cells(loopCount, 1).Value
        b = xl.Cells(loopCount, 2).Value
        c = xl.Cells(loopCount, 3).Value
        Wait IE
        IE.Document.All.Item("sortcode1").value = a
        IE.Document.All.Item("sortcode2").value = b
        IE.Document.All.Item("sortcode3").value = c
        IE.Document.getElementsByName("Check Sort Code").Item(0).Click
        Wait IE
        Dim result, result2
        Set objElms = IE.Document.getElementsByTagName("p")
        For Each objElm In objElms
            If objElm.className = "scv_success_untick" Then
                result = objElm.innerHTML
                Do While InStr(result, ">") > 0
                    result = Replace(result, Mid(result, InStr(result, "<"), InStr(result, ">") - InStr(result, "<") + 1), "")
                Loop
            ElseIf objElm.className = "scv_success_untick_branch" Then
                result2 = objElm.innerHTML
                Do While InStr(result2, ">") > 0
                    result2 = Replace(result2, Mid(result2, InStr(result2, "<"), InStr(result2, ">") - InStr(result2, "<") + 1), "")
                Loop
            End If
        Next
        xl.Cells(loopCount, 4).Value = result
        xl.Cells(loopCount, 5).Value = result2
        loopCount = loopCount + 1
    Loop

End Function
Sub Wait(IE)
    Do
        WScript.Sleep 500
    Loop While IE.ReadyState < 4 And IE.Busy
End Sub

Resultant Screen Shot.
Comment: That's excellent Rich, works great.  The only thing that I need to iron out is when there is a sort code that's not found, it just takes the previous results.
Comment: @BrianG Oh ok, that's simple enough, just use `result="":result2=""` after `xl.Cells(loopCount, 4).Value = result : xl.Cells(loopCount, 5).Value = result2` so that it clears the variables after saving them to the excel sheet.
Comment: Works perfectly again.


What other processes exist?

Question: I would like to know if there are other processes apart from stochastic and weiner.
I have looked for information and nothing
Comment: Don't worry about the number of processes. There are enough processes that you would not be able to finish studying all of them in your whole lifetime. Firstly, you may narrow down what type of processes you are interested in.
Answer: I believe the processes you're talking about are stochastic processes. Stochastic just means random. A Weiner process is a type of stochastic process, as are Poisson processes, Markov processes, etc. You can find more examples using by searching the term stochastic process. The Wikipedia article is a good place to start as it lists a number of processes under examples and further examples. https://en.m.wikipedia.org/wiki/Stochastic_process

What other processes exist?


AWS CrossAccount Pipeline build from Codecommit source code

Question: I am currently in confusion for a rather complex but yet brilliant way of managing CI/CD flows with with AWS Multi-account strategy.
AWS accounts: A(DevOps) B(development)
This whole process is build upon Cloudformation templates. My questions is that I want to build a docker image from the source code of Account A to account B. But how do I get cross access to the codecommit repository from Account A?
So the source code is in Account A. The pipeline is working and building fine into Account B But the CI/CD flow can't continue here as the source code is in Account A Not sure if its possible to crate the build flow from the source code in account A
Alternative: Create the docker image in Account A where the source code is and push the Image to ECR in account B.
I rather do the first approach as it in my opinion more convenient as the stack can just be deleted within the Dev account(B) and then the whole pipeline is deleted without the DevOps (account A) need to interfere.
Answer: it is possible to get the source and use it in another account.
I have this experience when working cross-account codepipelines using KMS and storing the output artifact in S3.
I followed this link and hope its helpful for you.
Building a Secure Cross-Account Continuous Delivery Pipeline
Video version
Also, pull image from ECR stay in account A into Account B is possible.
allow a secondary account to push or pull images in my Amazon ECR image repository


Large var_dump when looking at $variables

Question: This might not be the correct place to ask this question, please remove if it is wrong...
But, when I do a var_dump($variables) in one of my nodes I get a very large output that repeats several times... Is this just the way Drupal normally acts or might this indicate that there is something wrong with my site?
Thanks
Comment: Instead of using var_dump(), try enabling the Devel module and doing a `dpm($variables);` - I think you'll like it :)
Comment: Thanks, dpm does work, but I just wanted to make sure I wasn't including lots of unnecessary variables (looks like I don't...)
Answer: Yes, it is normal as Drupal pass enormous amount of data trough functions and hooks using array. But for better answer you should provide more information.


Dynamic Resources

Question: What would be the best way to "fill in" the dynamic properties of a resource file.
Ex.
PhraseId1: "he was going {speed} {unit}"
where speed and unit are determined at runtime.
Currently, I am doing a string replace within my code for each variable. But this feels somewhat cheap (although it works).
In the example, I show two variables, however, in reality, there are over 100 different values that could be substituted in different phrases.
Is there a better approach?
Comment: `"he was going {0} {1}"` `String.Format`
Comment: You might also be interested in [this answer](https://stackoverflow.com/questions/29068194/c6-0-string-interpolation-localization) which allows you to use more readable placeholders.
Answer: Nevermind, I found parametrized localization using String.format to solve this issue.

Dynamic Resources


Postgresql stops working for remote clients after some time

Question: First of all, sorry if there is a similar question. I haven't found anyone that solves my problem.
I have 3 computers set in a local network. Computer 1 is the master computer who has the database in local and runs the desktop application I'm working with. Computer 2 and Computer 3 run the same desktop application, and they connect to the database in Computer 1.
Postgresql is set to accept connections, the other parameters of the postgresql configuration are the default ones.
Everything seems to work fine, but after some hours have passed, Computer 2 and 3 cannot connect to Computer 1. However, Computer 1 can still work fine with the database.
<code>2014-XX-XX 13:33:33 CET FATAL: connection to client lost
2014-XX-XX 13:33:33 CET LOG: cannot send data to client. No connection could be made because the target machine actively refused it.
</code>
If I reboot Computer 2 and 3, everything works again, but I can't keep rebooting the computers many times every day.
Does anyone knows where the problem lies? For what I've searched maybe is a memory issue, but I'm no database expert and I'm not sure what parameters of the postgresql configuration I have to modify.
Thanks!
Comment: i think that is not the right place for your problem, perhaps [ServerFault](http://serverfault.com/) ?
Answer: It is highly likely that the issue here is a connection tracking firewall,r router or NAT device that's expiring connection tracking entries.
Enable TCP keepalives, either server-side, or if your client supports it, client-side.


Probability greater than mean

Question: What is the probability of a value to be greater than the mean plus three times the standard deviation (assuming a normal distribution)? What is this probability for an arbitrary distribution?
Comment: The first question (about the normal) sounds like it may be for a class exercise. How does the issue arise? In the case of an arbitrary distribution the proportion can be anything between 0 and 1/9. See https://en.wikipedia.org/wiki/Chebyshev%27s_inequality. There are many questions on site about it.
Comment: Please check https://stats.stackexchange.com/tags/self-study/info and add a `[self-study]` tag.
Comment: https://en.wikipedia.org/wiki/Chebyshev%27s_inequality
Answer: Compute $1 - F(μ + 3σ)$, where $F$ is the cumulative distribution function, $μ$ the mean, and $σ$ the standard deviation. When the distribution is normal, this comes out to .00135.
Answer: For an arbitrary distribution the one-tailed Chebyshev inequality is $$P\left[ X \geq \mu + k \sigma \right] \leq \frac{1}{k^2+1} \ .$$
So for $3 \sigma,$ the probability is less than or equal to $1 \over 10 .$

Probability greater than mean