Q: How to configure a Daphne server to invite clients to add the Certificate Authority that issued my certificate if they hadn't done it yet? If I make a request to my Daphne/Django server in Postman or the Android app we're developing, Daphne serves the certificate, but it's rejected. If I first make a simple get request to https://letsencrypt.org/ and then make a request to my server, the certificate is accepted.
How can I make sure a client will trust my certificate, even if it's the first time this client is seeing a certificate issued by this CA?
Everything bellow can serve as a history of how I studied the problem.
Original title: SSL Certificate works in browser but can't be verified by Postman
I have an AWS EC2 instance running Ubuntu 18.04, with python 3, Django, a bunch of project dependencies, Daphne running with ASGI, with a certificate by Let's Encrypt. Daphne is using port 8000 for HTTP and por 4430 for HTTPS, iptables is configured to redirect requests from port 80 to 8000 and from port 443 to 4430. Django is configured to enforce secure connections with SECURE_SSL_REDIRECT=True in the settings.py file.
There's a "Site in Construction" temporary page being served, and it's properly accessible from every browser and every device I tested so far. If I explicitly type http, I get redirected to https and the certificate is accepted. Every browser I tested (Firefox, Brave, Chrome, Chrome for Android) says cert is good.
Curl outputs the HTML content returned from the server. I don't know if it accepts the certificate or ignores it.

The Problem
Postman, however, says "Error: unable to verify the first certificate". Only works when I disable "SSL certificate verification", which doesn't answer my question: why Postman is unable to verify my Let's Encrypt certificate?
I'm building an API that runs on the same server, using the same domain, and it's meant to be consumed by a mobile app. Currently, the Android app is throwing a "TypeError: Network request failed", which I suspect could be caused by the same thing Postman is complaining about.
When I spin the server locally and configure 1) the app to use http://localhost:8000 and 2) the server not to enforce SSL, it works in browsers, Postman and in the Android app.
I've being looking for answers in many places for days, so any clue will be very welcome.
EDIT
Interesting clue:
If I make a request to my Daphne/Django server, it servers the certificate, which is rejected. But if I first make a request to https://letsencrypt.org/ and then make a request to my server, it works!
This pattern holds true in both Postman and our Android app.
It also happens when I first make a request to https://alloy.city (instead of letsencrypt.org), which is served by a Node.js app, and uses a certificate also issued by the Let's Encrypt CA.
So maybe the question should be: how to configure my server to politely invite clients to add the CA that issued my certificate if they hadn't done it yet?.
Apparently, that's what my Node.js server does.

A: Yes, in settings, tap ssl verification off
File > Settings > General > SSL Certificate Verification > off


Q: Python XML Parser not Returning XML Elemements I am trying to find a way to use Python to parse data from several .xml files that contain part numbers and descriptions for a system my team is working on. Here's what the files look like:
Note: Actual data sanitized for confidentiality reasons.
<DOCUMENT>
<config>
<lruname>NFS</lruname>
<swpn>123-A-456-7890</swpn>
<swname>00 NFS ABC DEFGHI XYZ JKL</swname>
<swver>Appid: abc-defghi-xyz  PN: 123-A-456-7890</swver>
</config>
</DOCUMENT>

I'd like to pull the  and  datatypes from several of these files into .csv format. My initial thought was to try to parse these data types out into a dictionary using the built in xml.etree library, but for some reason it's not finding the elements:
import xml.etree.ElementTree as ET

data = '''
<DOCUMENT>
<config>
<lruname>NFS</lruname>
<swpn>123-A-456-7890</swpn>
<swname>00 NFS ABC DEFGHI XYZ JKL</swname>
<swver>Appid: abc-defghi-xyz  PN: 123-A-456-7890</swver>
</config>
</DOCUMENT>
'''

tree = ET.fromstring(data)
PartNo = tree.find('swpn')
Desc = tree.find('swname')

print(PartNo)

The above code returns 'None' for some reason, but I would expect it to return the xml element I'm calling.

A: I think you're missing the config level in your XML hierarchy, you could do:
part_number = tree.find('config').find('swpn').text
part_desc = tree.find('config').find('swname').text

Alternately you can loop through all the elements if you don't want to have to know the structure and use conditionals to find the elements you care about with tree.iter.
for e in tree.iter():
    if e.tag == 'sqpn':
        part_number = e.text
    if e.tag == 'swname':
        part_desc = e.text

A: ElementTree and etree's find functionality searchers for direct children.
You can still use it by specifying the entire branch:
tree.find('config').find('swpn')
tree.find('config/swpn')

If you always want to look for swpn, but disregard the structure (e.g. you don't know if it's going to be a child of config), you might find it easier to use the xpath functionality in etree (and not in ElementTree):
tree = etree.fromstring(data)
tree.xpath('//swpn')

In this case, the // basically mean that you are looking for elements in tree, no matter where they are
If the xml files are small, and you don't care about performance, you can use minidom which IMHO is more convenient compared to lxml. In this case, your code could be something like this:
from xml.dom.minidom import parseString
xml = parseString(data)
PartNo = xml.getElementsByTagName('swpn')[0]
Desc = xml.getElementsByTagName('swname')[0]
print(PartNo.firstChild.nodeValue)


Q: what does "Out of Silence" mean? It is the name of a Yanni album. Is this equal to "brouhaha" and "noise"? What is the general rule to understand the meaning of "out of"? Sometimes it means "lack of something", like in "out of gas", but sometimes it means "because of", like in "out of jealousy". I got a bit confused!

A: No, it does not imply noise, just the opposite.  The title Out of Silence suggests the creative impulse for this music emerged from a meditative state of mind.
But we can be "out of eggs", which means we have no eggs.
A person could say, "I'm all out of peace and quiet since little Johnny turned two. He is such an imp." but that would be a figurative use, suggesting that peace and quiet is something one can have on hand, on a shelf in the pantry. But peace and quiet doesn't come in a can.
So you can usually figure this out by asking yourself, is the noun quantifiable? Is it available by the pound, by the kilo, by the ounce, by the dozen?  If yes, then "out of" means "there is no more of it, it is gone, consumed".  If the noun is not quantifiable then, barring some figurative use, it will probably mean "emerging from" or the similar "arising from".
I'm out of patience.   I am emerging from patience? or I have no patience left?


Q: Location of css file in a GWT project I have css file named Sample.css which contain the below contents.
         .bandit-report{
       margin-left: 20px;
          }
         .bandit-report1{
         margin-left: 50px;
          }

I have the ABCD.gwt.xml where I have made the below entry for the css file
    <stylesheet src='Sample.css' />

I set the style name using setStyleName(String) method. However the margin-left changes are not getting reflected. I dont know where to place the Sample.css file. I have currently place both ABCD.gwt.xml and Sample.css in the same directory.
Kindly Help.

A: Relative paths in <stylesheet> in a gwt.xml files are relative to the "module base URL" (returned by GWT.getModuleBaseURL() on the client-side code; this is the folder into which GWT will generate the nocache.js file and everything else). Having a file output in this directory is as easy as putting it in your public path, which by default is a public subfolder of your GWT module (next to your client subpackage). It's worth noting that public paths are inherited from modules you <inherit>; this is how GWT's built-in themes work.
If you put your stylesheet in your war folder, then you shouldn't inject it from your gwt.xml, you should rather load it with a <link rel=stylesheet> in your HTML host page.

A: I changed the entry made in ABCD.gwt.xml to as below. Now its working.
     <stylesheet src='/Sample.css' />

A: Use your browser developer panel to find out the location of css file.

A: You should create a folder named public in the same place where your client, server and shared folders are and put it in there, that's the default location it will look.


Q: Compiling .xsl files into .class files I'm currently working on a Java web project (Spring) which involves heavy use of xsl transformations. The stylesheets seldom change, so they are currently cached. I was thinking of improving performance by compiling the xsl-s into class files so they wouldn't have to be interpreted on each request.
I'm new to Java, so I don't really know the ecosystem that well. What's the best way of doing this (libraries, methods etc.)?
Thanks,
Alex

A: You might not have to compile to .class to achieve your goal, you can compile the xsl once per run and re-use the compiled instance for all transformations.
To do so you create a Templates object, like:
TransformerFactory factory = TransformerFactory.newInstance();
factory.setErrorListener(new ErrorListener( ... ));
xslTemplate = factory.newTemplates(new StreamSource( ... ));

and use the template to get a transformer to do the work:
Transformer transformer = xslTemplate.newTransformer();

Depending on the XSL library you use your mileage may vary.

A: You'll need a Template and a stylesheet cache:
http://onjava.com/pub/a/onjava/excerpt/java_xslt_ch5/index.html?page=9
Do be careful about thread safety, because Transformers aren't thread safe.  Best to do your transformations in a ThreadLocal for isolation.

A: Consider using Gregor/XSLT compiler


Q: netlink on ClearOS 7.3 issue I am trying following simple program on ClearOS 7.3, 64 bit
#include <sys/socket.h>
#include <linux/netlink.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>

int main()
{
    int flags =0;
    int bus = NETLINK_NETFILTER;

    int sock_fd = socket(AF_NETLINK, SOCK_RAW | flags, bus);
    if(sock_fd<0)
    {
        printf("\nsocket failed with error no = %d and error msg = %s\n",
                                errno, strerror(errno));

        return -1;
    }

    printf("\nOP completed successfully..!\n");
    return 0;
}

I am getting following error:

socket failed with error no = 93 and error msg = Protocol not
  supported

My OS details are:

*

*ClearOS release 7.3.0 (Final)

*Linux 3.10.0-514.26.2.v7.x86_64 #1 SMP Wed Jul 5 10:37:54 MDT 2017
x86_64 x86_64 x86_64 GNU/Linux

Please help.

A: Works for me.
The NETLINK_NETFILTER protocol is registered by the nfnetlink module.
In my case, the kernel registers the module automatically since this code uses it, but if yours doesn't, try inserting it manually:
$ sudo modprobe nfnetlink

And then try opening the socket again.


Q: Copying a dynamic array of structs to another dynamic array of structs I am trying to copy the contents of a dynamic array of structs to another dynamic array of structs, but I am getting the error, 'invalid array assignment' and was hoping someone could point me in the right direction.
Here is my struct:
struct Agent
{
    char name[C_STRING_SIZE];
    int idNum;
    double years;
    char location[C_STRING_SIZE];
};

My function:
Agent *copyEncryptArray(Agent *agentArr, int numOfAgents)
{
    Agent *encryptArr = new Agent[numOfAgents];

    for (int i = 0; i < numOfAgents; i++)
    {
        encryptArr[i].name = agentArr[i].name;
        encryptArr[i].idNum = agentArr[i].idNum;
        encryptArr[i].years = agentArr[i].years;
        encryptArr[i].location = agentArr[i].location;
    }

    return encryptArr;
}

Ultimately, I am trying to encrypt the contents of the agentArr then copy it to encryptArr but I am just trying to figure out how to copy for now. This is for a course and we have not covered memcpy yet so that is not an option.

A: It's easier than you think.
for (int i = 0; i < numOfAgents; i++)
    encryptArr[i] = agentArr[i];

Each value in the array is something that meets all requirements of an "object", and can be copied/moved as a whole. No need to bother copying each member of the struct.

A: You should use std::string instead of char arrays. It is assignable and there are more merits including almost unlimited length of string.
struct Agent
{
    std::string name;
    int idNum;
    double years;
    std::string location;
};

If you are unfortunately forced to use arrays for some reason, you will have to assign each elements.
If it is guaranteed that the contents of the arrays will always be strings (sequences of characters terminated by null-character), you can use strcpy() to copy them.
(I will show only code for name, but location should also be treated like this)
        strcpy(encryptArr[i].name, agentArr[i].name);

If you cannot guarantee this, you should use memmove() (because memcpy() is banned here).
        memmove(encryptArr[i].name, agentArr[i].name, sizeof(encryptArr[i].name));

If memmove() is also unfortunately banned, the last option will be assigning the elements one-by-one.
        for (int j = 0; j < C_STRING_SIZE; j++)
        {
            encrypyArr[i].name[j] = agentArr[i].name[j];
        }


Q: Convert Java loop to Kotlin I'm studying implementation with Kotlin. When I implement Kotlin version by below situation, I can't imagine cool way.
for(i = 0 ; i + 8 <= table.size; i++){
 for(j = 0 ; j + 8 <= table[0].size; j++{
  whatever
 }
}

Above code is Java version
for(i in 0 until table.size){
 if(i+8 > table.size)break
  for(j in until table[0].size){
    if(j+8 > table[0].size)break
      whatever
   }
}

Above is Kotlin version which I think.
Is this fine way?

A: You can just move the -8 into the upper limit, and since you include (<=) the upper limit you shouldn't be using until, but the regular range expansion with two dots.
So it becomes:
for (i in 0..table.size-8){
    for (j in 0..table[i].size-8){}
}

(I imagine you would also want to replace the magical number eight with a variable with a meaningful name)


Q: Why if for all x, p(x) and for all x not p(x) is not a contradiction? $\forall x: p(x) \equiv1$ and $\forall x: \neg p(x) \equiv 1$ is not a contradiction?
I have this doubt after a logic contest, and I cant see why. My thoughs was that this is not a contradiction because maybe the TRUE set of these two proposition may be the empty set, but Im not sure if this is the right answer.
I will appreciatte any coment.

A: The answer may depend on the universe of discourse. If $x$ is a variable for unicorns, then "All unicorns have blue eyes" and "all unicorns have non-blue eyes" are both true. However, we paractically always assume a nonempty universe of discourse (and some rules of natural deduction rely on that). In that case, from $\forall x p(x)\equiv 1$ we infer $p(a)\equiv 1$, from $\forall x \neg p(x)\equiv 1$ we infer $\neg p(a)\equiv 1$, and these two are in contradiction.

A: I think that there is a "terminological" issue here ...
In "modern practice", we say that :

a formula $\phi$ is a contradiction, or inconsistent, if it is unsatisfiable.

This definition can be easily applied to a set of formulae.
In this sense, the two formulae $\forall x p(x)$ and $\forall x \lnot p(x)$ form an unsatisfiable set of formulae (in the "usual" semantics that does not admit empty universes).
But there is an "older" meaning of contradictory : see The Traditional Square of Opposition :

Two propositions are contradictory iff they cannot both be true and they cannot both be false.
Two propositions are contraries iff they cannot both be true but can both be false.

According to these definitions, the two sentences are contraries, because they can be both false.

A: Well I suppose, in First-order logic one could consider an empty universe (or domain of discourse). In this case, any statement over an $\forall$ quantifier is true. So you could say that there exists a universe such that both statements are true and thus they are no contradictions.
This, however, relies very strongly on which definition one uses since mostly universes are assumed to be non-empty...


Q: Uploading in IE fails while using jQuery to click on the input tags for file and submit in a form So I am trying to get this uploading script to work inside of IE.  It works fine in other browsers but when I try it in IE the form doesn't submit.  I am using jQuery and CSS to build my own form instead of using what the  and  tags show, and then i use jQuery to click on those  tags.  However in IE when I select a file and submit the form, IE says there is nothing in the file input and doesn't run the PHP script specified in the action attribute of the form.  Any ideas?  I haven't been able to find any help for this just by searching.


Q: Exponential of matrix, taylor series Compute $ exp(X) $for $X=$\begin{bmatrix}t&0\\0&s\end{bmatrix}, \begin{bmatrix}0&t\\-t&0\end{bmatrix} $ and $\begin{bmatrix}0&t\\t&0\end{bmatrix}
The first part of the question I calculated the Taylor series at 0 of $sinh(t), cosh(t), sin(t)$ and $cos(t)$ at $t=0$ so I think I may need to use some of this information for the question. For example I know that $exp(x)=sinh(x)+cosh(x)$
Any help would be much appreciated

A: Since the first matrix you are dealing with is diagonal, it would be easier to use the formula $exp(X) = \sum_{n=0}^{\infty}\frac{X^n}{n!}$
The diagonal entries will be to the power of n in this sum. Hope this helps.


Q: How to repeat an html element n number of times using javascript I'm trying to print an element, in my case an hr tag some number of times according to the length of a word. This code is for a hangman game I'm trying to recreate. I have looked up similar questions and its not quite what I'm lookin for.
This is my javascript code so far.
var words = ['Quaffle', 'Bludger', 'Golden Snitch', 'Time-Turner',
'Pensieve', 'Mirror of Erised'];

function getRandomWord(){
   var randomIndex = words[Math.floor(Math.random()* words.length)];
   alert(randomIndex);
}

function printDashes(){
   var dashes = document.getElementById("dash")
}

getRandomWord()
printDashes()

I'm not sure what to add after retrieving the element. Can someone guide me on how to go about this?

A: You can also create div's so you can enter letters when the user inputs a character. I've attached an example below.
UPDATE: Added example code to update the dashes with letters based on word

var elem = document.getElementById('container');
var guess = document.getElementById('guess');
var word = "Hello";

// draw empty dashes
var drawDashes = function(numberOfDashes) {
  for (var i = 0; i < numberOfDashes; i++) {
    var el = document.createElement('div');
    el.classList = 'dash';

    // we draw an empty character inside so that the element
    // doesn't adjust height when we update the dash later with a
    // letter inside
    el.innerHTML = ' ';

    elem.appendChild(el);
  }
}

// update dash with a letter based on index
var updateDash = function(index, letter) {
  elem.children[index].innerHTML = letter;
}

guess.addEventListener('keyup', function(evt) {

  // split the word up into characters
  var splitWord = word.split('');

  // check to see if the letter entered matches any of the
  // words characters
  for (var i = 0; i < splitWord.length; i++ ) {

    // it is important we convert them to lowercase or
    // else we might get a mismatch because of case-sensitivity
    if (evt.key.toLowerCase() === splitWord[i].toLowerCase()) {

      // update dash with letter based on index
      updateDash(i, evt.key.toLowerCase());
    }
  }

  // clear out the value
  this.value = '';
});

drawDashes(word.length);
body {
  font-family: sans-serif;
}

.dash {
  height: 50px;
  width: 50px;
  margin: 0 10px;
  display: inline-block;
  border-bottom: 2px solid black;
  font-size: 32px;
  font-weight: bold;
  text-align: center;
}

#guess {
  height: 50px;
  width: 50px;
  padding: 0;
  font-size: 32px;
  text-align: center;
}

Type a letter

<input id="guess" type="text"/>

A: Say your word is in some variable named myWord.
Get the length of the word by doing:
var myWordLen = myWord.length;

Then you can create HTML elements using Javascript createElement method and appending child elements, information etc as needed. But since you want as many elements as the length of a word, use a loop. Eg:
for(var i=0; i < myWordLen; i++)
{
    var tr1 = document.createElement("hr");
    var someEle = document.getElementById("someID");
    someEle.appendChild(tr1);
}

A: What about this way?
myElement.innerHTML = `<...>`.repeat(words.length)


Q: $\mathcal{B}$ being the collection of all open intervals $(a,b)$ in $\mathbf{R}$ with $a,b\in\mathbf{Q}$ is a basis for $\mathbf{R}$ Is the following argument correct ?

Proposition. Let $\mathcal{B}$ be the collection of all open intervals $(a,b)$ in $\mathbf{R}$ with $a<b$ and $a$ and $b$ are
  rationals. Prove that $\mathcal{B}$ is a basis for the euclidean
  topology on $\mathbf{R}$.

Proof. Let $\mathcal{A}$ be the collection of all open intervals $(x,y)$ where $x,y\in\mathbf{R}$, since we know beforehand that $\mathcal{A}$ is a basis for $\mathbf{R}$, consequently given an arbitrary open set $O$ in $\mathbf{R}$, we have, for some indexed subset $J$ of $\mathcal{A}$.
$$O = \bigcup_{j\in J}(a_j,b_j)$$
Now let $j\in J$. We show that $(a_j,b_j)$ can be written as a union of intervals found in $\mathcal{B}$. We begin by defining sequences $\{x_n\}_{n=0}^{\infty}$ and $\{y_n\}_{n=0}^{\infty}$ as follows
$$x_0  = y_0 = \frac{a_j+b_j}{2}$$
$$x_{n+1} = \frac{a_j+x_n}{2}\ \text{ and }\ \ y_{n+1} = \frac{y_n+b_j}{2}$$
Given thh definition of the above sequences it is evident that $\{x_n\}_{n=0}^{\infty}$ is monotonically decreasing and bounded below by $a$ and $\{y_n\}_{n=0}^{\infty}$ is monotonically increasing and bounded above by $b$ consequently the converge with the limits in question being
$$r_1 = \lim_{n\to\infty}x_{n+1} = \frac{a_j+\lim_{n\to\infty}x_n}{2} = \frac{a_j+r_1}{2}$$
$$r_2 = \lim_{n\to\infty}y_{n+1} = \frac{\lim_{n\to\infty}y_n+b_j}{2} = \frac{r_2+b_j}{2}$$
which imply that $r_1=a_j$ and $r_2 = b_j$, given this the following inferences are immediate (for the following sequences $n\ge 1$).
$$\lim_{n\to\infty}x_{2n} = a_j \ \ \ \ \lim_{n\to\infty}x_{2n-1} = a_j\ \ \ \ \lim_{n\to\infty}y_{2n} = b_j \ \ \ \ \lim_{n\to\infty}y_{2n-1} = b_j$$
Now given the density of $\mathbf{Q}$ in $\mathbf{R}$ we have sequences of rationals $\{p_n\}_{n=1}^{\infty}$ and $\{q_n\}_{n=1}^{\infty}$ such that
$x_{2n}<p_n<x_{2n-1}$ and $y_{2n}<q_n<y_{2n-1},\forall n\ge 1$, the squeeze theorem then yields that
$$\lim_{n\to\infty}p_n = a_j$$
$$\lim_{n\to\infty}q_n = b_j$$
consequently
$$(a_j,b_j) = (p_1,q_1)\cup\bigcup_{n=1}^{\infty}(p_n,x_0)\cup(y_0,q_n)$$
the claim in question is then evident.
$\blacksquare$

A: No, it is not correct, since you have no reason to suppose that $x_0,y_0\in\mathbf Q$. So, your last expression is not necessarily an union of elements of $\mathcal B$.
Given an interval $(a,b)$ of real numbers, you could simply take a decreasing sequnce $(x_n)_{n\in\mathbb N}$ of elements of $\left(a,\frac{a+b}2\right)\cap\mathbf Q$ and an increasing sequence $(y_n)_{n\in\mathbb N}$ of elements of $\left(\frac{a+b}2,b\right)\cap\mathbf Q$ such that $\lim_{n\to\infty}x_n=a$ and that $\lim_{n\to\infty}y_n=b$. Then$$(a,b)=\bigcup_{n=1}^\infty(x_n,y_n)$$and each $(x_n,y_n)$ belongs to $\mathcal B$.


Q: about $l^p$ space and qoutient space Let $Y=\{x\in l^p:x_{2n}=0\}$, $1\leq p \leq \infty$. It can be proved that $Y$ is closed subspace of $l^p$. Define the quotient space $l^p/Y=\{x+Y:x\in l^p\}$. Then, by the fact that $Y$ closed, a norm on $l^p/Y$ can be defined by $||x+Y||=\inf\{\|x-y\|_p : y\in Y\}$.
prove that $l^p/Y$ is isometrically isomorphic $l^p$ .
I think we have :$\|x + Y\| = \left( \sum_{j} |x_{2j}|^p \right)^{1/p}$ but how we can show $l^p/Y$ is isometrically isomorphic $l^p$ ?

A: We start be defining the map $T:\ell^p\to\ell^p$ by
$$T(x_1,x_2,\dots)=(x_2,x_4,x_6\dots)$$
This is a linear operator and obviously $\|Tx\|_p\leq\|x\|_p$. The kernel of this map is exactly $Y$ and it can easily be shown that its image is all of $\ell^p$: if $a=(a_n)\in\ell^p$, consider $b=(0,a_1,0,a_2,0,a_3,\dots)$. Then $b\in\ell^p$ and $Tb=a$. By elementary linear algebra, we have that
$$\ell^p/Y\cong\ell^p$$
as vector spaces via the isomorphism of vector spaces $\bar{T}$ that is defined by $\bar{T}(a+Y)=Ta$.
But $\bar{T}$ is isometric; as you observed, $\|a+Y\|=\bigg(\sum_{j}|a_{2j}|^p\bigg)^{1/p}=\|Ta\|_p=\|\bar{T}(a+Y)\|_p$.
The case $p=\infty$ works in a very similar way.

A: Consider the map $T : \ell^p \to \ell^p/Y$ given by
$$Tx = (0,x_1,0,x_2,0,x_3\ldots) + Y, \quad x = (x_n)_n \in \ell^p.$$
Then $T$ is isometric:
$$\|Tx\| = \|(0,x_1,0,x_2,0,x_3\ldots) + Y\| = \left(\sum_{n=1}^\infty |x_n|^p\right)^{\frac1p} = \|x\|_p.$$
Also $T$ is surjective since for every $y + Y \in \ell^p/Y$ we have
$$T(y_{2n})_n = (0,y_2,0,y_4,0,y_6\ldots) + Y = y + Y.$$
Therefore $T$ is the desired isometric isomorphism.


Q: Using find, xargs, etc. to output similarly named files I have a folder full of HTML files:
001.htm
002.htm
003.htm
…

I want to run Pandoc on them to convert them to similarly named Markdown files:
001.md
002.md
003.md

This command works on one of them:
pandoc -f html -t markdown 001.htm -o 001.md

And I want to use find and xargs to automatically run a similar command on every file in the folder.
I got as far as this:
find *.htm | xargs -I {} -n 1 pandoc -f html -t markdown -o {}

…which truncates every file in the directory, so now I'm asking before I really break something.
What is wrong with my command above, and/or what's a completely different / more efficient way to do this?

A: I managed to do that with this 1 liner. If you are flexible about the xargs and find part.
for f in ./*.htm; do pandoc -f html -t markdown "$f" -o "${f%.htm}.md"; done

If you want to act recursively (so: all .htm files in the current directory, and all subdirectories), then (assuming bash 4+) you can use the globstar shell option:
shopt -s globstar
for f in ./**/*.htm; do pandoc -f html -t markdown "$f" -o "${f%.htm}.md"; done

A: Using {} isn't flexible enough for some situations. This appears to be one of those.
A possible workaround would be to -execa script from find, like so:
find . -name '*.htm' -exec ./convert-to-md.sh {} \;

The script file should look similar to this, depending on the exact pandoc command line:
#!/bin/bash
pandoc -f html -t markdown -o "${1/.htm/.md}" "${1}"

If you don't want to create and save a script file for this, you can always inline the bashscript code:
find . -name '*.htm' | xargs -n 1 bash -c 'pandoc -f html -t markdown -o "${1/.htm/.md}" "${1}"' -

The additional -at the end serves to fill $0in bash, which usually includes the name of the shell script, positional arguments starting at $0.
This allows you to keep using find(even with -print0and xargs -0 if you're handling weird file names), but doesn't require creation of a separate file.

A: You appear to be missing a {} in the pandoc command
find . -name \*.htm | xargs -I {} -n 1 pandoc -f html -t markdown {} -o {}.md

But then you'll have files named 001.htm.md -- you'll have to decide if this is a problem.


Q: HTML content encoded, started with '' sign I have received an email and the body is formed in HTML format. However, I was wondering how can I decode the encoded content as following:
<a href=3Dhttp://０．ｇｇ/DFt2U>
Could anyone tell me how to decode the string? The transfer encoding is Qouted-printable, and the charset is big5. However, I tried to decode the content with qp-decoder and nothing works. Thanks.

A: Try the link below:
http://toolswebtop.com/text/process/decode/BIG-5
I tried your link and got 3Dhttp://０．ｇｇ/DFt2U


Q: How can I get my templated function to see other global methods defined later? (Oktalist gave a great answer below, check it out and the comments under it, to help demonstrate everything we've discussed, I've added a full, compiling solution at the bottom of my question that demonstrates everything discussed.)
I have a collection of namespace global methods and templated methods like the following:
namespace PrettyPrint
{
    String to_string(bool val);
    String to_string(char val);
    String to_string(int val);
    String to_string(uint val);
    // ETC...

    template <typename T> String to_string(const T* val)
    {
        if (! val) return U("NULL");
        return String().copy_formatted("(%p)-> %S", (const void*)val, to_string(*val).uchars());
    }

    // ... and more templates to help with containers and such
}

The "String" type is not the C++ string, it's a special class derived off of IBM's ICU library, but not really relevant for this question.  Point is, I have a bunch of namespace global methods called to_string and also some templated functions that override them.  So far, so good, everything works great.  But, now I have another header where I have something like the following defined:
namespace User
{
    struct Service {
        int code;
        String name;
    }
    //...
}
namespace PrettyPrint
{
    String to_string(const User::Service& val) { return val.name; }
}

So, now I have defined some other type somewhere else, and I've also defined another to_string override in my PrettyPrint namespace to indicate how to convert my new type to a String.  Toss both headers into a file, something like this:
#include <the to_string and templates header>
#include <the User::Service header>

main() {
    User::Service s = {1, U("foo")};
    User::Service *p = &s;
    PrettyPrint::to_string(s);
    PrettyPrint::to_string(p);
}

(Yes, the to_string methods should actually be returning a value somewhere, not the point.) The point is that the second call gives a compiler error (gcc, btw) saying that in the templated to_string method there is no matching function for call to 'to_string(const User::Service&)', which of-course exactly matches my method that is defined and included. If I reverse the #include ordering it works just fine.
So, I surmise that the template is only looking at methods defined ahead of it.  Is there any fix for this?  Given the scope of my project and number of complicated #include's, simply saying "always make sure they come in the right order" is not a tractable solution, and would introduce too much complicated fragility in the code.  The base to_string defintions is one of those files that will tend to get included high up in a lot of places, so making sure that any other random type definitions that happen to include a to_string override come first just isn't going to work.
The other solution I have that works in some places is that I've defined a Printable interface in the base file:
namespace PrettyPrint
{
    class Printable {
    public:
        virtual String pretty_print_to_string() const = 0;
    }

    String to_string(const Printable& obj) { return obj.pretty_print_to_string(); }
}

That definition comes before the template methods in the same file.  So, that works great for classes where I can simply add in that interface and implement it.  Short of any great solutions here, I'm going to simply try to always use that, but there are places where it is not convenient and I'd also just like to understand if there is any way to get the method overloading solution to work without being dependent on #include ordering to work.
Anyhow, what do you all think of these options?  Is there an approach that I haven't thought of that might work nicely?
Solution inspired from answer Oktalist gave
This code actually does compile so you can copy it off and play with it, I think I've captured all the relevant use cases along with what works and what doesn't and why.
#include <iostream>

using namespace std;

namespace PrettyPrint
{
    void sample(int val) { cout << "PrettyPrint::sample(int)\n"; }
    void sample(bool val) { cout << "PrettyPrint::sample(bool)\n"; }
    template<typename T> void sample(T* val) { cout << "PrettyPrint::sample(pointer); -> "; sample(*val); }
}

namespace User
{
    struct Foo {
        int i;
        bool b;
    };

    void sample(const Foo& val) {
        //below doesn't work un-qualified, tries to convert the int (val.i) into a Foo to make a recursive call.
        //meaning, it matches the User namespace version first
        //sample(val.i); doesn't work, tries to call User::sample(const Foo&)

        cout << "User::sample(const Foo&); -> {\n";
        cout << '\t'; PrettyPrint::sample(val.i); //now it works
        cout << '\t'; PrettyPrint::sample(val.b);
        cout << "}\n";
    }
}

namespace Other
{
    void test(User::Foo* fubar) {
        cout << "In Other::test(User::Foo*):\n";
        //PrettyPrint::sample(*fubar); //doesn't work, can't find sample(const User::Foo&) in PrettyPrint
        PrettyPrint::sample(fubar); //works, by argument-dependent lookup (ADL) from the template call
        sample(*fubar); //works, finds the method by ADL
        //sample(fubar); //doesn't work, only sees User::sample() and can't instantiate a Foo& from a Foo*
    }

    void test2(User::Foo* happy) {
        using PrettyPrint::sample; //now both work! this is the way to do it.
        cout << "In Other::test2(User::Foo*):\n";
        sample(*happy);
        sample(happy);
    }
}

int main() {
    int i=0, *p = &i;
    bool b=false;
    User::Foo f = {1, true}, *pf = &f;

    //sample(i);  <-- doesn't work, PrettyPrint namespace is not visible here, nor is User for that matter.
    PrettyPrint::sample(i); //now it works
    //PrettyPrint::sample(f); //doesn't work, forces search in PrettyPrint only, doesn't see User override.

    using namespace PrettyPrint;  // now they all work.
    sample(p);
    sample(b);

    sample(f);
    sample(pf);

    Other::test(pf);
    Other::test2(pf);

    return 0;
}

This results in the following output:
PrettyPrint::sample(int)
PrettyPrint::sample(pointer); -> PrettyPrint::sample(int)
PrettyPrint::sample(bool)
User::sample(const Foo&); -> {
    PrettyPrint::sample(int)
    PrettyPrint::sample(bool)
}
PrettyPrint::sample(pointer); -> User::sample(const Foo&); -> {
    PrettyPrint::sample(int)
    PrettyPrint::sample(bool)
}
In Other::test(User::Foo*):
PrettyPrint::sample(pointer); -> User::sample(const Foo&); -> {
    PrettyPrint::sample(int)
    PrettyPrint::sample(bool)
}
User::sample(const Foo&); -> {
    PrettyPrint::sample(int)
    PrettyPrint::sample(bool)
}
In Other::test2(User::Foo*):
User::sample(const Foo&); -> {
    PrettyPrint::sample(int)
    PrettyPrint::sample(bool)
}
PrettyPrint::sample(pointer); -> User::sample(const Foo&); -> {
    PrettyPrint::sample(int)
    PrettyPrint::sample(bool)
}

A: During the first phase of two phase lookup, when the template is defined, unqualified lookup looks for dependent and non-dependent names in the immediate enclosing namespace of the template and finds only those to_string overloads which appear before the template definition.
During the second phase of two phase lookup, when the template is instantiated, argument-dependent lookup looks for dependent names in the namespaces associated with any class types passed as arguments to the named functions. But because your to_string(const User::Service&) overload is in the PrettyPrint namespace, it will not be found by argument-dependent lookup.
Move your to_string(const User::Service&) overload into the User namespace to make use of argument-dependent lookup, which will find any overloads declared at the point of template instantiation, including any declared after the point of template definition.
See also http://clang.llvm.org/compatibility.html#dep_lookup

A: What the compiler does when instantiating a template is essentially expanding it (more or less like a macro), and compiling the result on the fly. To do that, any functions (or other stuff) mentioned must be visible at that point. So make sure any declarations used are mentioned beforehand (in the same header file, most probably).

A: I don't entirely understand what's going on here, but it appears that if you want the later defined methods to be used, then they need to be template specializations.  The compiler won't see function overrides later in the program.
First off, we reproduce the problem.  I do so with this program in gcc-4.8.2:
// INCLUDE FILE 1
template <class T> void to_string (T const * a) {
  to_string (*a);
}
// INCLUDE FILE 1 END

// INCLUDE FILE 2
// How do we make this program work when this is necessarily declared after to_string(T const * A)?
void to_string(int const & a) {
  return;
}
// INCLUDE FILE 2 END

int main (void) {
  int i = 5;
  int * p = &i;

  to_string(i);
  to_string(p);
  to_string(&i);

  return 0;
}

In order to get it working, we need to do this...
// INCLUDE FILE 1
// The pointer version needs something to call...
template <class T> void to_string (T const & a);

// This can't be T const * a.  Try it.  So weird...
template <class T> void to_string (T * a) {
  foo (*a);
}
// INCLUDE FILE 1 END

// INCLUDE FILE 2
// This has to specialize template<> void to_string.  If we just override, we get a linking error.
template<> void to_string <int> (int const & a) {
  return;
}
// INCLUDE FILE 2 END

int main (void) {
  int i = 5;
  int * p = &i;

  to_string(i);
  to_string(p);
  to_string(&i);

  return 0;
}


Q: LiveData Duplicate Observers Concern I won't explain why this code is needed, but my question is whether the following code will lead to duplicate Observers or not:

  override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initializeRecyclerView()
        viewModel = ViewModelProvider(this).get(TestViewModel::class.java)

        updateUI()

        viewModel.getNewItems().observe(viewLifecycleOwner, {
            if (it != null && it == true){
                updateUI()
            }
        })
    }

    fun updateUI(){
        viewModel.getItems().observe(viewLifecycleOwner, Observer {
            adapter.values = it
            adapter.notifyDataSetChanged()
        })
    }

    fun initializeRecyclerView() {
        recyclerView.adapter = adapter
    }
}

As updateUI() gets called multiple times, does this create duplicate observers of viewmodel.getItems()??


Q: Azure Redis Cache vs Redis Cloud service on Azure I need to use it in a .NET (webapi) app & using stackexchange.redis nuget package.
Appreciate if someone please point me to appropriate resources for following -
1) Can I choose any of Azure Redis cache or Redis cloud service if I interface through stackexchange.redis nuget?
2) Azure Redis Cache vs Redis Cloud - differences & implications of choosing one over the other - if this info already available.
Thanks

A: Disclaimer: I work for Redis Labs, the company providing Redis Cloud.

1) Can I choose any of Azure Redis cache or Redis cloud service if I interface through stackexchange.redis nuget?

Yes - both Azure Redis and Redis Cloud provide a Redis database that you can use with the StackEchange.Redis client from your app.

2) Azure Redis Cache vs Redis Cloud - differences & implications of choosing one over the other - if this info already available.

While both are essentially a hosted Redis service, there are several differences between them. Most notably, Azure Redis Cache is deeply integrated in the Azure platform so you have everything (management, metrics, etc...) accessible from your management portal. OTOH, Redis Cloud is cloud-agnostic (it is available on multiple clouds) and offers more features than any other Redis-as-a-Service service. I think that the fact that Redis Cloud is the only service that can scale infinitely and w/o downtime/migration is perhaps the strongest differentiator, but feel free to refer to this comparison table for a high level overview: https://redislabs.com/redis-comparison


Q: Evaluation of the indefinite integral $\int \frac{\operatorname{sech}^2(x)}{ \operatorname{sech} ^2(x)+1} \,dx$ $\newcommand{\sech}{\operatorname{sech}}$I have simplied $$\int \frac{\sech^2(x)}{ \sech ^2(x)+1} \, dx$$ to $$\int\frac 2 {\cosh(2x)+3} \,dx$$ and am wondering if this is the most efficient way of answering the question and where to go from here.

A: hint
using the substitution
$$t=\tanh (x) $$
with
$$dt=(1-t^2)dx $$
and
$$\cosh(2x)=\frac {1+t^2}{1-t^2} $$
the integrale becomes
$$\int \frac {dt}{2-t^2} $$
to finish, put $t=u\sqrt {2} $ and observe that
$$\frac{2}{1-u^2}=\frac {1}{1-u}+\frac {1}{1+u} $$


Q: Select JSON records as an Excel table I have an internal map service that serves up GIS records via JSON objects.

For the purpose of this question, instead of using my internal/private
data, we can use the JSON data on ESRI's public Sample Server 6.

*

*https://sampleserver6.arcgisonline.com/arcgis/rest/services/LocalGovernment/Events/MapServer/0/query?where=1%3D1&outFields=*&f=pjson

Question:
I want to select the JSON data and insert it into an Excel table.
In other words, I want to take the JSON data:

And put it into a tab in an Excel spreadsheet as rows:

How can this be done in Excel 2016?

A: I can use Excel Power Query.
The steps are pretty unintuitive, so I'll spell them out for future reference:

*

*Excel 2016 >> Data tab >> From Other Sources >> From Web

*Paste the URL

*Click Edit

*Remove the Changed Type step

*In the Source step's settings, change Open file as from CSV to Json

*Click the features row

*Click Into Table

*Click the List hyperlink in the features row

*Click To Table

*Click Ok

*In the header for Column1, click the arrows icon:

*Unselect geometry, if applicable.

*Click Ok

*In the header of Column1.attributes, click the arrows icon:

*Unselect Use original column name as prefix, if applicable.

*Click Ok

*Change/correct the data types for the columns. Note: I couldn't figure out how to display the dates correctly.

*This is what the resulting data/table looks like in the Power Query window:

*Click Close & Load

*This is what the resulting table in the Excel spreadsheet looks like.

*The query can be refreshed anytime: Data tab >> Refresh All.

*Additionally, the refresh settings can be set so that the query refreshes when the spreadsheet file is opened.

For more details, see the answers in this post: Select JSON records as Excel table via Power Query

A: The 1min job using OGR/GDAL command line. I've changed f=pjson to f=json in your url. You will just need to open the CSV.
ogr2ogr -f CSV localgovernment_events.csv "https://sampleserver6.arcgisonline.com/arcgis/rest/services/LocalGovernment/Events/MapServer/0/query?where=1%3D1&outFields=*&f=json" -lco GEOMETRY=AS_WKT

For points, you may prefer an output with X and Y columns instead of WKT
ogr2ogr -f CSV localgovernment_events.csv "https://sampleserver6.arcgisonline.com/arcgis/rest/services/LocalGovernment/Events/MapServer/0/query?where=1%3D1&outFields=*&f=json" -lco GEOMETRY=AS_XY

You can also use QGIS by using f=geojson like below. It will load as a layer. Then, you will right click on the layer "Export" -> "Save Features As...", choose to export to CSV format or Excel or OpenDocument (LibreOffice format). Be aware that output format does not always keep geometry in the output file.


Q: Use Intl.NumberFormat to format square foot units I'm trying to use Intl.NumberFormat to format numbers with units and I have some units of square feet.
When I try
new Intl.NumberFormat('en-US', { useGrouping: true, style: "unit", unit: "square-foot" }).format(56)

Uncaught RangeError: Invalid unit argument for Intl.NumberFormat() 'square-foot'

The MDN documentation links to small list of approved units which were taken from a much larger list. The larger list has square feet but the smaller list does not, so that all makes sense.
I see they allow compound units though.

Pairs of simple units can be concatenated with "-per-" to make a compound unit. This suggests that it's only ratios of simple units, not products of two units.

new Intl.NumberFormat('en-US', { useGrouping: true, style: "unit", unit: "foot-per-second" }).format(56)
outputs --> "56 ft/s"

Again, a link from MDN I see this page which suggests this is possible with this type="power2" argument but that's in some XML implementation of this which is not Javascript not totally clear on the relationship between unicode.org and what's implemented in a browser)
Is there some way to get square feet as a the unit?


Q: Awk, Shell Scripting I have a file which has the following form:
#id|firstName|lastName|gender|birthday|creationDate|locationIP|browserUsed
111|Arkas|Sarkas|male|1995-09-11|2010-03-17T13:32:10.447+0000|192.248.2.123|Midori

Every field is separated with "|". I am writing a shell script and my goal is to remove the "-" from the fifth field (birthday), in order to make comparisons as if they were numbers.
For example i want the fifth field to be like |19950911|
The only solution I have reached so far, deletes all the "-" from each line which is not what I want using sed.
i would be extremely grateful if you show me a solution to my problem using awk.

A: If this is a homework writing the complete script will be a disservice.  Some hints: the function you should be using is gsub in awk. The fifth field is $5 and you can set the field separator by -F'|' or in BEGIN block as FS="|"
Also, line numbers are in NR variable, to skip first line for example, you can add a condition NR>1

A: An awk one liner:
awk 'BEGIN { FS="|" } { gsub("-","",$5); print }' infile.txt

A: To keep "|" as output separator, it is better to define OFS value as "|" :
... | awk 'BEGIN { FS="|"; OFS="|"} {gsub("-","",$5); print $0 }'


Q: How can i match the exact text in XML I want to match the exact text "puts" in the (xml file) for a .tmTheme file for sublime text but I've come here as my last resort. I don't really know about regex please help.
i'm trying to match the puts Ruby print keyword. for example:
puts "cat"

output
cat

My main aim is to only highlight the puts keyword as i can't find any other way to highlight its scope. It's for a syntax highlighting package.
the seventh line with the --- <> --- is where i'm struggling with. Any help will be greatly appreciated.
<dict>
    <key>name</key>
    <string>output</string>
    <key>scope</key>
    <string>source.ruby</string>
    <key>match</key>
    --- <string>>p[\'"]?([^\'" >]+)s</string> ---
    <key>settings</key>
    <dict>
        <key>foreground</key>
        <string>#ff0</string>
    </dict>
</dict>


Q: Network operation could not be completed - Alamofire I am using Alamofire in a Swift app I am developing. Recently whenever I try to perform a network call in the simulator iPhone5 8.1 (or any simulator 8.1) I am getting:
Optional(Error Domain=NSURLErrorDomain Code=-1005 "The operation couldn’t be completed. (NSURLErrorDomain error -1005.)" UserInfo=0x7f9d148ac2c0 {NSErrorFailingURLStringKey=https:[URL REMOVED], NSErrorFailingURLKey=https:[URL REMOVED], _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=57, NSUnderlyingError=0x7f9d1273f0a0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1005.)"})

This use to work fine up until about a day ago. The only things I have changed are the servers are now sitting on Windows/IIS EC2 instances behind a load balancer and the request is no longer a HTTP but it is HTTPS.
I had app transport configured when using HTTP but removed now everything is over HTTPS. I tried putting it back but still nothing.
I have disabled keepalive headers on IIS but I can't seem to get any connection to go through.
I have read through the comments here https://github.com/AFNetworking/AFNetworking/issues/2314 but nothing in that post works.
Help please?!?!


Q: Won't boot after upgrade from 16.04 to 18.04 (xubuntu) Towards the end of the boot process, amongst the actions that are OK is one that's not, i.e.
Failed to start MDM.service

Am I correct in thinking that MDM is the Mate Desktop Manager? If so why in a XFCE4 desktop environment?
At the end of the boot process, I get a logon prompt in a tty screen. Internet access has been started so was able to fix broken packages (there weren't any) and complete the latest updates.
Edit (2018/08/18 17:00).
Ran the following commands:
sudo service mdm disable

sudo dpkg-reconfigure lightdm

and then rebooted (after installing lightdm). Exactly the same result as above.
Outputs requested:
dpkg-query: no path found matching pattern *MDM.service*

● mdm.service                        loaded failed failed  mdm.service

I have now removed mdm (purged) and the message 'Failed to start MDM.service' no longer appears during boot, but still only boots to a tty command line screen.
I enquired on lightdm status via:
sudo systemctl status lightdm

(sorry, I can't remember if that's absolutely correct, but I'm sure you'll get the popint). Output:
● lightdm.service - Light Display Manager
   Loaded: loaded (/lib/systemd/system/lightdm.service; indirect; vendor preset: enabled)
   Active: failed (Result: exit-code) since Sat 2018-08-18 17:31:37 CEST; 1min 53s ago
     Docs: man:lightdm(1)
  Process: 1500 ExecStart=/usr/sbin/lightdm (code=exited, status=1/FAILURE)
  Process: 1497 ExecStartPre=/bin/sh -c [ "$(basename $(cat /etc/X11/default-display-manager 2>/dev/null))" = "lightdm" ] (code=exited, status=0/SUCCESS)
 Main PID: 1500 (code=exited, status=1/FAILURE)

Aug 18 17:31:37 fuentedelucas systemd[1]: lightdm.service: Service hold-off time over, scheduling restart.
Aug 18 17:31:37 fuentedelucas systemd[1]: lightdm.service: Scheduled restart job, restart counter is at 5.
Aug 18 17:31:37 fuentedelucas systemd[1]: Stopped Light Display Manager.
Aug 18 17:31:37 fuentedelucas systemd[1]: lightdm.service: Start request repeated too quickly.
Aug 18 17:31:37 fuentedelucas systemd[1]: lightdm.service: Failed with result 'exit-code'.
Aug 18 17:31:37 fuentedelucas systemd[1]: Failed to start Light Display Manager.


Q: "sequenced before" and "Every evaluation in the calling function" in c++ Every evaluation in the calling function (including other function calls) that is not otherwise specifically sequenced before or after the execution of the body of the called function is indeterminately sequenced with respect to the execution of the called function.
In other words, function executions do not interleave with each other.
what is the meaning of "Every evaluation".
#include <iostream>
using namespace std;
int a = 0;
ing b = 0;
int f(int,int)
{
    cout << "call f, ";
    cout << "a=" << a << ", ";
    cout << "b=" << b << ", ";
    return 1;
}

int g()
{
    cout << "call g, ";
    cout << "a=" << a << ", ";
    cout << "b=" << b << ", ";
    return 1;
}

int main()
{
    f(a++, b++) + g();
    return 0;
}

*

*it menas evaluation of function call expression f(a++, b++), so evaluation of a++, evaluation of b++, and execution of f are all sequenced before or after the execution of g.
In this case, there are two kinds of results. If evaluation of expression f(a++, b++) is sequenced before the execution of g:
call f, a=1, b=1, call g, a=1, b=1,
If execution of g issequenced before evaluation of expression f(a++, b++):
call g, a=0, b=0, call f, a=1, b=1,
2.It means evaluation of a++, evaluation of b++, or execution of f.
So evaluation of a++ may be sequenced before execution of g, evaluation of b++ and execution of f may be sequenced after execution of g.
call g, a=1, b=0, call f, a=1, b=1,

*It means value computation or side effect.

So value computation of a++ may be sequenced before execution of g, side effect of a++, evaluation of b++ and execution of f may be sequenced after execution of g.
call g, a=0, b=0, call f, a=1, b=1,

In this case,
f(a++, b++) + (a = g());
1.value computation of a++
2.execution of g
3.side effect of a++
4.side effect of = (a = 0)
5.evaluation of b++
6.execution of f

call g, a=0, b=0, call f, a=0, b=1,

Which one is right? Or other answer?
I'm not an English speaker, and I'm not very good at English.
I hope you can understand what i say
f(h1(), h2()) + g(h3(), h4())
h1 and h2 are sequenced before f, h3 and h4 are sequenced before g.
Is it possible:

*

*h1

*h4

*h2

*f

*h3

*g

A:
[expr.post.incr]/1 ... The value computation of the ++ expression is sequenced before the modification of the operand object. With respect to an indeterminately-sequenced function call, the operation of postfix
  ++ is a single evaluation. [ Note: Therefore, a function call shall not intervene between the lvalue-to-rvalue conversion and the side effect associated with any single postfix ++ operator. —end note ]...

My reading of this is that the side effects of a++ and b++ must complete before the body of f is executed, and therefore within f it must be that a==1 and b==1. Your examples #2 and #3 are not possible with a conforming implementation.
A call to g is indeterminately sequenced with a call to f, and thus can observe either pre-increment or post-increment values.

A: f(a++, b++) + g();

Compiler can decide the order of execution of f() and g() in the above statement.
These are only 2 possibilities not 3.
Either f() will call first and modifies variables a and b
OR
g() will get call first.


Q: Find files with different inodes in same directory structure We have a slight problem with our backups. Our setup is as follows:

*

*We create a backup using the rsync command.

*The backup uses the option --link-dest option, to create incremental backups with hardlinks to older backups, for all the files that have not changed.

All looks well, every file we have checked so far that hasn't changed since the last backup gets hardlinked correctly (same inode number as the file in the older backup).
However, the last two weeks there has been a massive increase in storage need on the backup server. We suspect that either somthing is going wrong in our backup process, or massive files have been added (and/or changed) by users on the normal server.
We want to check (some of) the files that have been changed since the last backup; this means checking all files in the same directory structure with different inodes (no hard links).
How to find these files?
(Ubuntu 12.04 LTS)

A: I can think of two ways off the top of my head:

*

*Use find and limit the number of links
find -type f -links 1

The command above will find all files whose inode is only pointed to by a single link. This means that any files that point to the same inode as another will not be printed.

*List all inodes and show only the unique ones
ls -1i | awk '{print $1}' | sort | uniq -u

Note that the above will not print file names, only inodes. This is because i) it's the inodes that we need to sort/uniq and ii) file names can contain strange characters such as newlines which would break the sorting/uniqing. If you are confident that your file names are sane, you can use this approach to print file names:
ls -1i | awk '{c[$1]++;l[$1]=$0;} END{for(i in c){if(c[i]==1){print l[i]}}}'


Q: Reverse Indexing in Python? I know that a[end:start:-1] slices a list in a reverse order.
For example
a = range(20)
print a[15:10:-1] # prints [15, ..., 11]
print a[15:0:-1] # prints [15, ..., 1]

but you cannot get to the first element (0 in the example). It seems that -1 is a special value.
print a[15:-1:-1] # prints []

Any ideas?

A: In Python2.x, the simplest solution in terms of number of characters should probably be :
>>> a=range(20)

>>> a[::-1]
[19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Though i want to point out that if using xrange(), indexing won't work because xrange() gives you an xrange object instead of a list.
>>> a=xrange(20)
>>> a[::-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence index must be integer, not 'slice'

After in Python3.x, range() does what xrange() does in Python2.x but also has an improvement accepting indexing change upon the object.
>>> a = range(20)
>>> a[::-1]
range(19, -1, -1)
>>> b=a[::-1]
>>> for i in b:
...     print (i)
...
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
>>>

the difference between range() and xrange() learned from source: http://pythoncentral.io/how-to-use-pythons-xrange-and-range/
by author: Joey Payne

A: You can assign your variable to None:
>>> a = range(20)
>>> a[15:None:-1]
[15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>>

A: Omit the end index:
print a[15::-1]

A: >>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> print a[:6:-1]
[19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7]
>>> a[7] == a[:6:-1][-1]
True
>>> a[1] == a[:0:-1][-1]
True

So as you can see when subsitute a value in start label :end: it will give you from start to end exclusively a[end].
As you can see in here as well:
>>> a[0:2:]
[0, 1]

-1 is the last value in a:
>>> a[len(a)-1] == a[-1]
True

A: EDIT: begin and end are variables
I never realized this, but a (slightly hacky) solution would be:
>>> a = range(5)
>>> s = 0
>>> e = 3
>>> b = a[s:e]
>>> b.reverse()
>>> print b
[2, 1, 0]

A: If you use negative indexes you can avoid extra assignments, using only your start and end variables:
a = range(20)
start = 20
for end in range(21):
    a[start:-(len(a)+1-end):-1]


Q: How to create a XY chart in Java which reads data from two variables? I have difficulties understanding how to add my data to the chart object. I am simulating a supermarket activity in java program. After the simulation time is up. I have two variables
 time and customers. What should I use if I want the data to be added to an XY chart in java.
Thanks, in advance. I have looked at JFreeChart but it seems overly complicated.

A: JFreeChart is not overcomplicated. You have to try Time Series chart in your case. See here the example of how they use it.
Although they leave behind the scene the main thing, which should create the data source for chart: see line
 final TimeSeries eur = DemoDatasetFactory.createEURTimeSeries();
I used this TimeSeries charts before, and as I remember you have to create this object and put there series of your values (probably iterating over your own values and inserting them one by one in cycle)


Q: jQuery .fadeIn() setup I have a few elements which I want to $('.hidden_item').fadeIn() when the button is clicked.
So in order to do that I need to first hide them. I tried using
$(document).ready(function(){
    $('.hidden_item').hide();
});

But sometimes page onload sends heartbeat and my elements hidden_elements stay visible for some time. So I would like to hide them with CSS.
What styling I should use to correctly hide them for later $('.hidden_item').fadeIn()?

A: use
.hidden_item{
  display:none;
}


Q: xpdf (pdftotext) with language pack call from different directory I am experimenting with xpdf (pdftotext) on a macOS Terminal. I use one language package (Japanese). Everything works fine if I call the executable like this (from the lib directory):
lib kelly$ ./p2t -enc UTF-8 jp.pdf

and my data structure
files/lib/pdftotext
files/lib/xpdfrc
files/lib/jp.pdf #file to convert
files/options/Enc/jp/ # Here I have the language package files

and the following edited xpdfrc configuration file:
#----- begin Japanese support package (2011-sep-02)
cidToUnicode    Adobe-Japan1    ../options/Enc/jp/Adobe-Japan1.cidToUnicode
unicodeMap  ISO-2022-JP ../options/Enc/jp/ISO-2022-JP.unicodeMap
unicodeMap  EUC-JP      ../options/Enc/jp/EUC-JP.unicodeMap
unicodeMap  Shift-JIS   ../options/Enc/jp/Shift-JIS.unicodeMap
cMapDir     Adobe-Japan1    ../options/Enc/jp/CMap
toUnicodeDir            ../options/Enc/jp/CMap
#----- end Japanese support package

the problem I have is to call 'pdftoext' from a different directory, for example from 'files'. In this case, the files that the configuration files is pointing to are not seen.
files kelly$ ./lib/p2t -enc UTF-8 ./lib/jp.pdf

I get the following error:
Syntax Error: Unknown character collection 'Adobe-Japan1'

And the generated file is garbage.
Any idea on how the configuration file needs to be changed?

A: I was able to solve a similar problem.
I installed pdftotext with a brew cask.
The installation was done with the following command
$ brew cask install pdftotext
$ pdftotext -v
pdftotext version 3.03
Copyright 1996-2011 Glyph & Cog, LLC

and place the xpdfrc/language support packages in the following directory I did.
ls /usr/local/etc/xpdfrc
/usr/local/etc/xpdfrc

I downloaded the Japanese Language Pack from here.
https://www.xpdfreader.com/download.html
$ tree /usr/local/share/xpdf
/usr/local/share/xpdf
└── japanese
    ├── Adobe-Japan1.cidToUnicode
    ├── CMap
    │   ├── 78-EUC-H
    │   ├── 78-EUC-V
    │   ├── 78-H
    │   ├── 78-RKSJ-H
    │   ├── 78-RKSJ-V
    │   ├── 78-V
    │   ├── 78ms-RKSJ-H
    │   ├── 78ms-RKSJ-V
    │   ├── 83pv-RKSJ-H
    │   ├── 90ms-RKSJ-H
    │   ├── 90ms-RKSJ-UCS2
    │   ├── 90ms-RKSJ-V
    │   ├── 90msp-RKSJ-H
    │   ├── 90msp-RKSJ-V
    │   ├── 90pv-RKSJ-H
    │   ├── 90pv-RKSJ-UCS2
    │   ├── 90pv-RKSJ-UCS2C
    │   ├── 90pv-RKSJ-V
    │   ├── Add-H
    │   ├── Add-RKSJ-H
    │   ├── Add-RKSJ-V
    │   ├── Add-V
    │   ├── Adobe-Japan1-0
    │   ├── Adobe-Japan1-1
    │   ├── Adobe-Japan1-2
    │   ├── Adobe-Japan1-3
    │   ├── Adobe-Japan1-4
    │   ├── Adobe-Japan1-5
    │   ├── Adobe-Japan1-6
    │   ├── Adobe-Japan1-UCS2
    │   ├── EUC-H
    │   ├── EUC-V
    │   ├── Ext-H
    │   ├── Ext-RKSJ-H
    │   ├── Ext-RKSJ-V
    │   ├── Ext-V
    │   ├── H
    │   ├── Hankaku
    │   ├── Hiragana
    │   ├── Katakana
    │   ├── NWP-H
    │   ├── NWP-V
    │   ├── RKSJ-H
    │   ├── RKSJ-V
    │   ├── Roman
    │   ├── UniJIS-UCS2-H
    │   ├── UniJIS-UCS2-HW-H
    │   ├── UniJIS-UCS2-HW-V
    │   ├── UniJIS-UCS2-V
    │   ├── UniJIS-UTF16-H
    │   ├── UniJIS-UTF16-V
    │   ├── UniJIS-UTF32-H
    │   ├── UniJIS-UTF32-V
    │   ├── UniJIS-UTF8-H
    │   ├── UniJIS-UTF8-V
    │   ├── UniJIS2004-UTF16-H
    │   ├── UniJIS2004-UTF16-V
    │   ├── UniJIS2004-UTF32-H
    │   ├── UniJIS2004-UTF32-V
    │   ├── UniJIS2004-UTF8-H
    │   ├── UniJIS2004-UTF8-V
    │   ├── UniJISPro-UCS2-HW-V
    │   ├── UniJISPro-UCS2-V
    │   ├── UniJISPro-UTF8-V
    │   ├── UniJISX0213-UTF32-H
    │   ├── UniJISX0213-UTF32-V
    │   ├── UniJISX02132004-UTF32-H
    │   ├── UniJISX02132004-UTF32-V
    │   ├── V
    │   └── WP-Symbol
    ├── EUC-JP.unicodeMap
    ├── ISO-2022-JP.unicodeMap
    ├── README
    ├── Shift-JIS.unicodeMap
    └── add-to-xpdfrc

2 directories, 76 files

The contents of xpdfrc are as follows
$ cat /usr/local/etc/xpdfrc
cidToUnicode    Adobe-Japan1    /usr/local/share/xpdf/japanese/Adobe-Japan1.cidToUnicode
unicodeMap  ISO-2022-JP /usr/local/share/xpdf/japanese/ISO-2022-JP.unicodeMap
unicodeMap  EUC-JP      /usr/local/share/xpdf/japanese/EUC-JP.unicodeMap
unicodeMap  Shift-JIS   /usr/local/share/xpdf/japanese/Shift-JIS.unicodeMap
cMapDir     Adobe-Japan1    /usr/local/share/xpdf/japanese/CMap
toUnicodeDir            /usr/local/share/xpdf/japanese/CMap


Q: Scrapy Response Changes After Visiting Page in Web Browser Below is a spider I wrote to crawl an RSS feed and extract the first link and image title, and save them to a text file:
import scrapy

class artSpider(scrapy.Spider):
    name = "metart"

    start_urls = ['https://www.metmuseum.org/art/artwork-of-the-day?rss=1']

    def parse(self, response):
        title = response.xpath('//item/title/text()').extract_first().replace(" ", "_")
        description = response.xpath('//item/description/text()').extract_first()

        lnkstart = description.find("https://image")
        lnkcut1 = description.find("web-highlight")
        lnkcut2 = lnkcut1 + 13
        lnkend = description.find(".jpg") + 4

        link = description[lnkstart:lnkcut1] + "original" + description[lnkcut2:lnkend]

        ttlstart = description.find("who=") + 4
        ttlend = description.find("&rss=1")

        filename = "/path/to/save/folder/" + description[ttlstart:ttlend].replace("+", "_") + "-" + title + ".jpg"

        print(filename)
        print(link)

        filename_file = open('filename_metart.txt', 'w')
        filename_file.write(filename)
        filename_file.close
        link_file = open('link_metart.txt', 'w')
        link_file.write(link)
        link_file.close

It goes over the Met Museum "Artwork of the Day" RSS feed and finds the newest artwork. Then parses the title and the link to the original (the link in the RSS feed is for a thumbnail) and saves them to individual text files. The title is used to generate a filename when downloading the image.
I know the parse function is a mess and that the way I am saving the links and filenames is ugly. I am just starting out with Scrapy and just wanted to get the spider working because it is only a part of the broader project I am working on.
The project itself draws from artwork/image/photo of the day feeds and websites, downloads the images and sets them as a desktop background slideshow.
My issue is that when I set the spider off it comes back with a response of "NoneType". BUT if I go to the RSS feed in a browser (https://metmuseum.org/art/artwork-of-the-day?rss=1) AND THEN run the spider it works correctly.
Process that fails

*

*Call scrapy crawl metart

*

*Output shows that the variable title has the type NoneType

*Repeating step 1 results in the same output

Process that works

*

*Open https://metmuseum.org/art/artwork-of-the-day?rss=1 in a web browser

*Call scrapy crawl metart

*

*Successfully saves the link and filename to the relevant text files

Some troubleshooting I have already done
I have used a Scrapy shell to replicate exactly the process that the spider goes through and this worked fine. I went through each step that the spider goes through starting with:
fetch("https://metmuseum.org/art/artwork-of-the-day?rss=1")

Then typing in each line of the parse function. This works fine and results in the correct link and filename being saved WITHOUT having to open the URL in a web browser first.
Just for completeness below is my Scrapy project settings.py file:
BOT_NAME = 'wallpaper_scraper'

SPIDER_MODULES = ['wallpaper_scraper.spiders']
NEWSPIDER_MODULE = 'wallpaper_scraper.spiders'

# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'cchowgule for a wallpaper slideshow'

# Obey robots.txt rules
ROBOTSTXT_OBEY = True

I am very confused as to how the act of opening the URL in a web browser could possibly affect the response of the spider.
Any help cleaning up my parse function would also be lovely.
Thanks
Update
At 0535 UTC I ran scrapy crawl metart and got the following response:
2018-06-23 11:02:54 [scrapy.utils.log] INFO: Scrapy 1.5.0 started (bot: wallpaper_scraper)
2018-06-23 11:02:54 [scrapy.utils.log] INFO: Versions: lxml 4.2.1.0, libxml2 2.9.8, cssselect 1.0.3, parsel 1.4.0, w3lib 1.19.0, Twisted 17.9.0, Python 2.7.15 (default, May  1 2018, 05:55:50) - [GCC 7.3.0], pyOpenSSL 17.5.0 (OpenSSL 1.1.0h  27 Mar 2018), cryptography 2.2.2, Platform Linux-4.16.0-2-amd64-x86_64-with-debian-buster-sid
2018-06-23 11:02:54 [scrapy.crawler] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'wallpaper_scraper.spiders', 'SPIDER_MODULES': ['wallpaper_scraper.spiders'], 'ROBOTSTXT_OBEY': True, 'USER_AGENT': 'cchowgule for a wallpaper slideshow', 'BOT_NAME': 'wallpaper_scraper'}
2018-06-23 11:02:54 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.memusage.MemoryUsage',
 'scrapy.extensions.logstats.LogStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.corestats.CoreStats']
2018-06-23 11:02:54 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2018-06-23 11:02:54 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2018-06-23 11:02:54 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2018-06-23 11:02:54 [scrapy.core.engine] INFO: Spider opened
2018-06-23 11:02:54 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2018-06-23 11:02:54 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2018-06-23 11:02:56 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.metmuseum.org/robots.txt> (referer: None)
2018-06-23 11:02:56 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.metmuseum.org/art/artwork-of-the-day?rss=1> (referer: None)
2018-06-23 11:02:56 [scrapy.core.scraper] ERROR: Spider error processing <GET https://www.metmuseum.org/art/artwork-of-the-day?rss=1> (referer: None)
Traceback (most recent call last):
  File "/home/cchowgule/.local/lib/python2.7/site-packages/twisted/internet/defer.py", line 653, in _runCallbacks
    current.result = callback(current.result, *args, **kw)
  File "/home/cchowgule/WD/pyenvscrapy/wallpaper_scraper/wallpaper_scraper/spiders/metart.py", line 9, in parse
    title = response.xpath('//item/title/text()').extract_first().replace(" ", "_")
AttributeError: 'NoneType' object has no attribute 'replace'
2018-06-23 11:02:57 [scrapy.core.engine] INFO: Closing spider (finished)
2018-06-23 11:02:57 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 646,
 'downloader/request_count': 2,
 'downloader/request_method_count/GET': 2,
 'downloader/response_bytes': 1725,
 'downloader/response_count': 2,
 'downloader/response_status_count/200': 2,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2018, 6, 23, 5, 32, 57, 65104),
 'log_count/DEBUG': 3,
 'log_count/ERROR': 1,
 'log_count/INFO': 7,
 'memusage/max': 52793344,
 'memusage/startup': 52793344,
 'response_received_count': 2,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'spider_exceptions/AttributeError': 1,
 'start_time': datetime.datetime(2018, 6, 23, 5, 32, 54, 464466)}
2018-06-23 11:02:57 [scrapy.core.engine] INFO: Spider closed (finished)

I ran scrapy crawl metart 5 times with the same result.
Then I opened a browser, went to https://metmuseum.org/art/artwork-of-the-day?rss=1 and ran scrapy crawl metart again. This time it worked correctly...... I just don't get it.


Q: Как сделать multiprocessing для одной функции запущенной несколько раз Есть одна функция, её нужно запустить 4 раза с разными данными так, чтобы все эти 4 раза функция запускались одновременно, с максимальной производительностью, а не поочерёдно. Буду благодарен любой помощи.
    def func(a1, a2, a3):
        a1 * 200 / 30
        a2 * 200 / 30
        a3 * 200 / 30
        print(a1, a2, a3)

func(32, 34, 54)
func(55, 64, 88)
func(12, 54, 98)
func(11, 23, 35)

A: Самый банальный вариант:
import multiprocessing

def func(a1, a2, a3):
    a1 * 200 / 30
    a2 * 200 / 30
    a3 * 200 / 30
    print(a1, a2, a3)

args = ((32, 34, 54), (55, 64, 88), (12, 54, 98), (11, 23, 35))

if __name__ == '__main__':
    for arg in args:
        multiprocessing.Process(target=func, args=arg).start()

A: Вы можете использовать библиотеку multiprocessing для параллельного запуска функций в Python.
import multiprocessing

def print_func(a1, a2, a3):
    a1 * 200 / 30
    a2 * 200 / 30
    a3 * 200 / 30
    print(a1, a2, a3)

if __name__ == '__main__':

    procs = []
    def run_process(a1, a2, a3):
        p = multiprocessing.Process(target=print_func, args=(a1, a2, a3,))
        procs.append(p)
        p.start()
        return p

    run_process(32, 34, 54)
    run_process(55, 64, 88)
    run_process(12, 54, 98)
    run_process(11, 23, 35)

    # complete the processes
    for proc in procs:
        proc.join()

A: args = ((32, 34, 54), (55, 64, 88), (12, 54, 98), (11, 23, 35))
with multiprocessing.Pool(processes=4) as p:
    p.starmap(func, args)


Q: How to create a floating widget hovering other widgets on Windows? Assume we have a wxWebView control in both window hierarchy and sizer hierarchy. How do we create a static text "loading" hovering above the wxWebView on Windows? Thanks.
It's straightforward on Linux. Create a wxStaticText of which the parent/owner is the same as the wxWebView and that's all. Unfortunately, it won't work on Windows. The wxStaticText is invisible because it is covered by the wxWebView. I've tried many ways, including calling their method Lower and Raise to adjust their z-orders, but in vain.
I also tried putting the text into a wxFrame and use samples/shaped/ as an example, but on the second thought, the new top-level frame may cover the GUI of other processes. So it isn't a good design.
Any suggestion? Thanks.

A: wxWidgets doesn't support overlapping child controls, so you would need to use a different top level window for your floating control, typically a wxPopupWindow -- then you could either draw your text in it or make wxStaticText its child.


Q: How to calculate probability that an event a occurs before an event b In the daily production of a certain kind of metal beam, the number of defects per foot on each beam, Y, follows a Poisson distribution with mean 0.5. The profit per foot on a beam when it is sold is given by X, where X = 30 – 2Y – $3Y ^2$.
In the daily production of a certain kind of metal beam, the number of defects per foot on each beam, Y, follows a Poisson distribution with mean 0.5. The profit per foot on a beam when it is sold is given by X, where X = 30 – 2Y – $3Y^2$.
Suppose a bunch of 2-foot metal beams are to be inspected one at a time. What is the probability the inspector will find a perfect beam before one with at least two defects?
I'm not sure how to approach this? I know lambda would be equal to 1 instead of 0.5 and I know P(X=0) = 0.3679 but I don't understand how to proceed.

A: $P(X=0) = e^{-1} \approx 0.3679$ is indeed correct
$P(X=1) = e^{-1} \approx 0.3679$ is also true, so $P(X\ge 2) = 1-2e^{-1} \approx 0.2642$
The probability the inspector will find a perfect beam before one with at least two defects is then $\dfrac{P(X=0)}{P(X=0)+P(X\ge 2)} = \dfrac{ e^{-1}}{ e^{-1}+ 1-2 e^{-1}} = \dfrac{1}{e-1} \approx 0.5820$, since either one of those cases is found or the inspector looks at the next beam


Q: Include files in sdist but not wheel I have a Python C extension that contains header files in the include folder.
I am currently trying to build wheels and a source distribution.
Because wheels are pre-compiled, they don't need to contain header files but the sdist does.
According to the Python docs, the following files are included in a sdist:

*

*all Python source files implied by the py_modules and packages options

*all C source files mentioned in the ext_modules or libraries options

*scripts identified by the scripts option See Installing Scripts.

*anything that looks like a test script: test/test*.py (currently, the Distutils don’t do anything with test scripts except include them in source distributions, but in the future there will be a standard for testing Python module distributions)

*Any of the standard README files (README, README.txt, or README.rst), setup.py (or whatever you called your setup script), and setup.cfg.

*all files that matches the package_data metadata. See Installing Package Data.

*all files that matches the data_files metadata. See Installing Additional Files.

These files are also included in the wheels as well.
How can I add the header files to a sdist but not a wheel?


Q: Which class provides implementation for RequestDispatcher forward() and include() method Does  RequestDispatcher object exits as it is an interface and as for i know we cant create an object to interface.
So what is happening in following code
RequestDispatcher requestDispatcher = request.getRequestDispatcher('somePage');

Are we creating object to RequestDispatcher or to subclass that implements RequestDispatcher.
Thanks in advance.

A: RequestDispatcher is an interface and we can't create an object obviously with that. So, it is an object of the class that implements RequestDispatcher that you get when the calling getRequestDispatcher().
You need to have the source code of the Servlet implementation(this depends on the container that you are using) to see the class that is providing the implementation.

A: You are right, RequestDispatcher is an interface you we can not create an object of this.
Now see:
request.getRequestDispatcher('somePage');  This method returns a class which implements RequestDispatcher and that class is totally depends upon the server which you are using.
For Ex. In case of Glass Fish server, it returns org.apache.catalina.core.ApplicationDispatcher object and it has already told by @Pshemo.


Q: Arrange tikzpicture horizontally I want to arrange three pictures drawn with tikzpicture horizontally.  Unfortunately I can't make it work using any of the threads on a similar topic.
Thank you a lot for your help,
best regards
Code:
\begin{figure}[!h]
 \centering
 \begin{subfigure}[b]{0.3\textwidth}

    \resizebox{\linewidth}{!}{
    \begin{tikzpicture}
    \draw plot[domain=-1.3:1.3]  ({\x,{(\x)^(2)+0.1*(\x)^(4)}});

    % Optional: Add axes
    \draw[-stealth] (-1.7,0) -- (1.7,0) node[right] {$M$};
    \draw[-stealth] (0,-1.7) -- (0,1.7) node[above] {${\cal L}$};

    \end{tikzpicture}
}
\caption{$T>T_c$}
\end{subfigure}

\begin{subfigure}[b]{0.3\textwidth}

    \resizebox{\linewidth}{!}{
    \begin{tikzpicture}
    \draw plot[domain=-1.4:1.4]  ({\x,{0.5*(\x)^(4)}});

    %Optional: Add axes
    \draw[-stealth] (-1.7,0) -- (1.7,0) node[right] {$M$};
    \draw[-stealth] (0,-1.7) -- (0,1.7) node[above] {${\cal L}$};

    \end{tikzpicture}
}
\caption{$T=T_c$}
\end{subfigure}

\begin{subfigure}[b]{0.3\textwidth}

    \resizebox{\linewidth}{!}{
    \begin{tikzpicture}
    \draw plot[domain=-1.6:1.6]  ({\x,{-2*(\x)^(2)+(\x)^(4)}});

    % Optional: Add axes
    \draw[-stealth] (-1.7,0) -- (1.7,0) node[right] {$M$};
    \draw[-stealth] (0,-1.7) -- (0,1.7) node[above] {${\cal L}$};

    \end{tikzpicture}
}
\caption{$T<T_c$}
\end{subfigure}

\caption{Plot of the Landau free energy for different values $M$ and $t=\frac{T-T_c}{T_c}$ around criticality.\label{fig:phasetrans}}
\end{figure}


Q: c# ValueInjecter : Mapping the whole object Graph I just started using ValueInjecter for my Entity Mappings(DTO <-> Entity).
Heres my DTO :
public class IncidentDTO
{
    int ID { get; set; }
    string Name { get; set; }
    AgencyDTO agencyDTO { get; set; }
}

public class AgencyDTO
{
    int ID { get; set; }
    string Name { get; set; }
    List<IncidentTypeDTO> incidentTypeDTOList { get; set; }
}

public class IncidentTypeDTO
{
    int ID { get; set; }
    string TypeName { get; set; }
}

Heres my NHibernate Proxy classes :
 public class Incident
{
    int ID { get; set; }
    string Name { get; set; }
    Agency agency { get; set; }
}

public class Agency
{
    int ID { get; set; }
    string Name { get; set; }
}

public class IncidentType
{
    int ID { get; set; }
    string TypeName { get; set; }
}

public class AgencyIncidentType
{
    int ID { get; set; }
    Agency agency { get; set; }
    IncidentType incidentType { get; set; }
}

Now, I need to query IncidentDTO from Repository.
Repository query Incident & AgencyIncidentType tables from database and map Incident -> IncidentDTO using ValueInjecter and return IncidentDTO.
What is the best possible way to do the above mapping using ValueInjecter??
Thanks,
Prateek

A: If you want to map Incident to IncidentDTO while retaining and mapping the Agency object in the agency property (to an AgencyDTO) of an Incident instance I'd suggest renaming the agencyDTO property to agency in your IncidentDTO and then use a tweak to the CloneInjection sample from the Value Injector documentation as described here: omu.valueinjecter deep clone unlike types


Q: /bin/bash - Alfred 3 workflow does not detect php So I downloaded this plugin https://github.com/vmitchell85/alfred-vuejs-docs and I got the Powerpack. Here is me trying to execute the workflow but pressing enter at this point does nothing:

After I press space and enter "vue events", I get in the debug:
[2018-09-02 16:56:33][ERROR: input.scriptfilter] Code 127: /bin/bash: php: command not found
Which is strange because I fire up my Terminal.app (Which uses bash) and I do php -v which gives me: PHP 7.2.8 (cli) (built: Jul 19 2018 12:15:24) ( NTS ). Same thing on my zsh profile.
What do I do?

A: Look at the image you posted. There's a Script Filter object on the Alfred Editor. You just have to double-click on it and replace php vuejs.php "{query}" with /usr/local/bin/php vuejs.php "{query}".


Q: How to focus to a block when cursor at start of line with Slate JS? I am using Slate JS.
I have some code, which should focus a given block (move the cursor there).
The use case here is: press / to open a modal, then when the modal closes, we want to refocus to the block we were at before.
To do this, we use Transforms.select().
Something like this:
getCurrentBlock(editor: Editor) {
  const { selection } = editor;

  if (!selection) {
    return { block: null, anchor: null, focus: null };
  }

  const { anchor, focus } = selection;
  const { path } = anchor
  const block = editor.children[path[0]] as Block;
  return { block, anchor, focus };
}

const focusBlock = (editor, path) => {
  ReactEditor.focus(editor);

  Transforms.select(editor, {
    anchor: { path: [path[0], 0], offset: 0 },
    focus: { path: [path[0], 0], offset: 0 },
  });
}

It generally works in all cases like this:
const { block, anchor, focus} = getCurrentBlock(editor)
const { path } = anchor
focusBlock(editor, path)

However, it does not work when the position of the cursor is at the start of a line.
i.e. when offset = 0.
In this case, the focus moves the cursor to the very top of the page.
Why might this be happening, and how can I make it focus the block in question, even when the cursor is at the start of the line?

A: Solved this by doing:
refocusEditor({ editor }: { editor: Editor }) {
   const block = Editor.above(editor, {
    match: (n) => Editor.isBlock(editor, n),
  });

  const path = block ? block[1] : [];
  ReactEditor.focus(editor);
  // @ts-ignore
  Transforms.setSelection(editor, path);
}


Q: QObject::connect: no such signal. Also, Qtimer not calling I have a class, myClass:
class myClass : public QObject
{
    Q_OBJECT
public:
    QQuickWidget* widget;
    QString mystring;
    myClass (QQuickWidget* quickWidget, QString string);
    void myfunction();

public slots:
    void slot();
signals:
    void clicked();
};

myClass::myClass(QQuickWidget* quickWidget, QString string) :
    widget(quickWidget), mystring(string)
{
    QTimer::singleShot(60000, this, SLOT(slot()));
    myfunction();
}

void myClass::slot()
{

}

void myClass::myfunction()
{
    widget->setVisible(true);
    widget->setSource(QUrl("qrc:/qmlsource.qml"));
    connect(widget, SIGNAL(clicked()), this, SLOT(slot()));
}

What I want to do is to call the slot() function 60 seconds after I create a myClass object. That doesn't happen. Also, at the connect line I get
QObject::connect: No such signal QQuickWidget::clicked()

message.
I would appreciate if someone could help me.

A: So, I think you have a few issues here.
1. QWidget
The big one is that QWidget (which QQUickWidget inherits from) does not have a signal called "clicked", so the message QObject::connect: No such signal QQuickWidget::clicked() is quite right ;)
What you need to do is create your own object that inherits from QQuickWidget and then re-implement/overload the function void QWidget::mousePressEvent(QMouseEvent * event) and/or void QWidget::mouseReleaseEvent(QMouseEvent * event)
These are the functions that are called in the widget that you can then emit your signal. Which means you also need to add a new signal into you your widget. So your new class header may look a bit like (just including the main elements):
class MyQQuickWidget: public QQuickWidget
{
    Q_OBJECT

public:
    MyQQuickWidget(QWidget *parent = 0);

signals:
    void clicked();

protected:
    void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
    void mouseReleaseEvent(QMouseEvent *event) Q_DECL_OVERRIDE;

};

And then in your implementation:
void MyQQuickWidget::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        emit clicked();
    }
}

Then when you connect your MyQQuickWidget signal clicked() to MyClass slot slot() it will connect ok.
2. QTimer
It looks like your timer should fire... but there appears to be no debug in the slot slot() so how would you know if this is working or not?


Q: How to properly get the int for totalEntries in MySQL database using PHP? I'm using PHP and a MySQL database to build a website.
However, I find PHP quite horrible compared to other languages I have learnt previously. Largely because I seem to find a lot of instructions online which are over 5 years old and they just don't work.
For example the accepted answer here: select count(*) from table of mysql in php
I have this code so far, but it gives me error (undefined index $recordCount = $row['totalEntries'];).
// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// check connection
if ($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM games ORDER BY id DESC LIMIT $startRow, $rowsPerPage";
$result = $conn->query($sql);

$sql = "SELECT COUNT(*) as totalEntries FROM games";
$results = $conn->query($sql);
$row = $result->fetch_assoc();
$recordCount = $row['totalEntries'];
echo "
 record count = " . $recordCount;

$totalPages = ceil($recordCount / $rowsPerPage);
$pagination = "
";

for ($i = 0; $i <= $totalPages; $i++) {
 $pagination .= "" . $i . "";
echo 'wtf!';
}

$pagination .= "
";
echo '
 pagination = ' . $pagination;

I also tried:
  $recordCount = Count($row);

and
   $recordCount = Count($result->num_rows);

and many other parameters passed into Count but they always return either 1 or 7(which is the number of COLUMNS)
I guess I find PHP so hard to learn because I don't have  a good IDE for it and am using Notepad++. Can anyone tell me how we get the Count of all entries in the table after I have done the SELECT statement as in the above code?

A:     $conn = new \mysqli('127.0.0.1', 'dev', 'SoMuchDev', 'test', '3306');
    $result = $conn->query('select * from test');
    while ($row = $result->fetch_assoc()) {
        $res[] = $row;
    }
    $res['total'] = $result->num_rows;
    echo "
";
    var_export($res);die();

http://php.net/manual/en/class.mysqli-result.php
As for editors, PhpStorm is widely used but afaik there's only a 30 day trial use. You could also give notepad ++ a try, I think it has some php plugins for autocomplete and what not.


Q: What does the path in an action of the following action-mapping mean What does the path in an action of the following action-mapping mean .Does it specify the jsp page from which a request is coming (search.jsp)?
<action-mappings>
<action path="/search"
        type="SearchAction"
        name="searchForm"
        scope="request"
        validate="true"
        input="/search.jsp">
</action>
</action-mappings>

A: The path refers to the name of the action you call from your HTML or jsp file.
For eg -
<html:form action="Name" name="nameForm" type="example.NameForm">

The corresponding action mapping will be something like  -
<action path="/Name" type="example.NameAction" name="nameForm" input="/index.jsp">
<forward name="success" path="/displayname.jsp"/>

Check out this link for a complete example.


Q: ReactJS: What's the real world use of Immutability Helpers in React? React's official document provide Immutability Helpers.
What would be some real world usage of such helpers? I think I am missing something really basic here.

A: React assumes that objects set in state are immutable, which means that if you want to add or remove some element inside your array you should create new one with added element keeping previous array untouched:
var a = [1, 2, 3];
var b = React.addons.update(a, {'$push': [4] });
console.log(a); // [1, 2, 3];
console.log(b); // [1, 2, 3, 4];

By using immutable objects you can easily check if content of object has changed:
React.createClass({
    getInitialState: function () {
        return { elements: [1, 2, 3] };
    },
    handleClick: function() {
        var newVal = this.state.elements.length + 1;
        this.setState({
            elements: React.addons.update(this.state.elements, { '$push': [ newVal ] })
        })
    },
    shouldComponentUpdate: function (nextProps, nextState) {
        return this.state.elements !== nextState.elements;
    },
    render: function () {
        return (

{ this.state.elements.join(', ') }

        );
    }
});

A: ReactJS state should preferably be immutable. Meaning that, everytime render() is called, this.state should be a different object. That is: oldState == newState is false and oldState.someProp == newState.someProp is also false.
So, for simple state objects, there's no doubt they should be cloned. However, if your state object is very complex and deep, cloning the entire state might impact performance. Because of that, React's immutability helpers is smart and it only clones the objects that it thinks it should clone.
This is how you do it when you clone the state by yourself:
onTextChange: function(event) {
    let updatedState = _.extend({}, this.state); // this will CLONE the state. I'm using underscore just for simplicity.
    updatedState.text = event.text;
    this.setState(updatedState);
}

This is how you do it when you let React's immutability helpers determine which objects it should actually clone:
onTextChange: function(event) {
    let updatedState = React.addons.update(this.state, { text: {$set: event.text} });
    this.setState(updatedState);
}

The above example will perform better then the first one when the state is too complex and deep.

A: React application prefer immutability, there are two ways (from Facebook) to support immutability,  one is to use immutable.js that is a complete immutability library, another one is the immutable helper that is a lightweight helper. You only need to choose one to use in one project.
The only disadvantege of immutable.js is that it leak itself throughout your entire application including the Stores and View Components, e.g.,
// Stores
props = props.updateIn(['value', 'count'], count => count + 1);

// View Components
render: function() {
    return
{this.props.getIn("value", "count")}
;
}

If you use immutable helper, you can encapsulate the immutability operations at the place where updates happen (such as Stores and Redux Reducers). Therefore, your View Components can be more reusable.
// Stores or Reducers
props = update(props, {
    value: {count: {$set: 7}}
};

// View Components can continue to use Plain Old JavaSript Object
render: function() {
    return
{this.props.value.count}
;
}


Q: Compatibility of textbox AutoCompleteMode and keyPress event, C# I have a textbox tbx. For it I had an event handler:
public void tbxPress(object sender, KeyPressEventArgs e)
    {
        MessageBox.Show("message 1");
        if (e.KeyChar == 13) // i.e. on Enter
        {
            MessageBox.Show("message 2");
        }
    }

and it worked perfect until I set AutoCompleteMode parameter of tbx.
After that auto-complete works fine, but on Enter i don't get "message 2". ... the hell?!
VC#2008EE

A: You can use the KeyDown event and check e.KeyCode == Keys.Enter.


Q: RTC value in stm32 Nucleo I'm trying to print RTC date and time on Tera Term. But I'm getting errors mentioned in code. Also nothing is being printed on Tera term. I have used pointer as the declaration for Setdate and Getdate have mentioned.
Also there are few warning such as
1)format '%d' expects a matching 'int' argument [-Wformat=]
2)passing argument 2 of 'HAL_RTC_GetDate' from incompatible pointer type [-Wincompatible-pointer-types]
3)passing argument 2 of 'HAL_RTC_SetDate' from incompatible pointer type [-Wincompatible-pointer-types]
#include "main.h"
#include "stdio.h"

//uint8_t Time[6]="HH:MM:SS";
//uint8_t Date[6]="DD/MM/YY";
int main(void)
{
  /* USER CODE BEGIN 1 */
    typedef struct
    {
      uint8_t Month = 0x03;
      uint8_t Date = 0x24;
      uint8_t Year = 0x21;
    }Date_struct;
  uint8_t *Date;
  Date = &Date_struct;  Error: Expected expression before Date_struct

HAL_RTC_SetDate(&hrtc, &Date, RTC_FORMAT_BCD);
  while (1)
  {
      HAL_RTC_GetDate(&hrtc,&Date, RTC_FORMAT_BCD);
      HAL_Delay(1000);
  }
}

A: I frankly don't have experience with Tera Term in particular, but I've programmed Atmel MCUs before and there seem to be issues with your general C code, rather than the MCU functions. The C compiler errors can be often hard to read, but I can see you're mixing up the structure definition, declaration and initialization, as well as struggle with pointers.

Consider the following plain C code and let's go over the differences with yours.
#include <stdio.h>
#include <stdint.h>

int main(void)
{
    struct date_struct
    {
        uint8_t month;
        uint8_t date;
        uint8_t year;
    }; // Define a structure named date_struct

    typedef struct date_struct date_struct_type; // make 'struct date_struct' into a new type

    date_struct_type date; // Declare a variable of the new type

    date.month = 0x03; // Initialize the fields of the variable
    date.date = 0x24;
    date.year = 0x21;

    date_struct_type * date_ptr; // Create a new pointer to the struct

    date_ptr = &date; // Assign the address of the variable to the pointer

    // Use the pointer to adress the structure's values
    printf("Month: %d\nDate: %d\nYear: %d\n", date_ptr->month, date_ptr->date, date_ptr->year);

    // ... or pass the pointer into any hypothetical function
    // func(date_ptr);

    // ... or pass a reference to the structure, but never a reference to the pointer
    // unless you know that you need it!
    // func(&date);

    return 0;
}

In your code, you first define an anonymous local structure and immediately typedef it to create a new type. That means, from that point on, you work with the structure as if it was just a variable type.
In my code, I split up the structure definition and the typedef into two individual statements. That code is identical to writing
typedef struct date_struct
{
    uint8_t Month;
    uint8_t Date;
    uint8_t Year;
} date_struct_type; // Define and typedef a structure at the same time

... or we can even leave the structure's name out and leave it anonymous - like you did in your code - we don't need it named at all since we already have a new type made out of it that we can use.
typedef struct // <-- leave out the name
{
    uint8_t Month;
    uint8_t Date;
    uint8_t Year;
} date_struct_type; // Define and typedef a structure at the same time

However, a structure definition is a "template" that tells the compiler how to allocate and access the structure in memory. The definition itself doesn't store any values and as such, we can't assign to it. We first need to declare a variable of that type*.
date_struct_type date;

* C is a very wild language, and you can do and use all sorts of shorthands, such as this. However, I strongly recommend against doing this when you're just starting out (and also in the future), as it's really not needed and is harder to read, maintain and debug.
With the variable in place, we can finally assign our values to the individual elements of the structure. When accessing members of a structure we use the member reference operator - ..
date.month = 0x03;
date.date = 0x24;
date.year = 0x21;

Now we're moving to pointers and the two magical operators - * and & in C, that often cause a lot of headaches.
In your code, you've successfully declared a pointer with this: uint8_t *Date;. Here, the * is not an operator, it signifies the variable holds a pointer - in other words, the uint8_t *Date; says "There is a variable named Date and it will hold an address of a uint8_t variable somewhere in the memory".
However, that is not what we intend - we want to point to our new structure, not the uint8_t. Pointers all have the same size (in your case 32 bits on the smt32 platform), so it works, but that's what's setting off the "incompatible pointer type" warnings of your compiler.
Instead, we should declare a pointer of the same type as the variable we intend to "point at" using this pointer. We'll once again split up the declaration and assignment statements for clarity - we're doing two things, writing them as one statement is just a shorthand.
date_struct_type * date_ptr;

The assignment is where the & operator comes into play. The & operator takes any variable and returns an address to it - which is exactly the thing we want to store inside our pointer.
date_ptr = &date;

Now whenever we want to pass a pointer to our new structure, either we use the one we just created - date_ptr, or directly pass a reference to the structure - &date. Both are viable, but be sure to not mistakenly write this: &date_prt. This gives you a pointer to a pointer, which is not something you usually want.
A few more things. When accessing member of a structure through a pointer to that structure, we have to use a structure dereference operator - ->. That's why the printf statement contains -> operators instead of just ..
I'm sure with this you can tweak your code to have it work. There shouldn't be any more issues in your function calls and the infinite while loop, just pay attention which pointers are you passing into the HAL_RTC_SetDate and HAL_RTC_GetDate functions. Do ask in the comments if there's still anything unclear or not working!