unable to install the python library "requests" on windows 7

Question: Encountering error while running the command
pip install requests

or
pip3 install requests

same error while installing any other python package on this system. Do I need to get any port opened on this system?
Collecting requests
  WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  Could not fetch URL https://pypi.org/simple/requests/: There was a problem con
firming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max
 retries exceeded with url: /simple/requests/ (Caused by SSLError(SSLCertVerific
ationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self
signed certificate in certificate chain (_ssl.c:1108)'))) - skipping
  ERROR: Could not find a version that satisfies the requirement requests (from
versions: none)
ERROR: No matching distribution found for requests
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming
 the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retrie
s exceeded with url: /simple/pip/ (Caused by SSLError(SSLCertVerificationError(1
, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certi
ficate in certificate chain (_ssl.c:1108)'))) - skipping

Comment: Do you have any kind of firewalls installed on your network?
Comment: palo alto firewall (this is a office system)
Comment: Maybe this is the problem. Try installing anything using `pip` and see if the same error persists.
Comment: PIP didnt work either
Comment: Then try different network.. or contact the IT department with this issue.
Answer: as suspected the issue was with the firewall. But the way i had to resolve is by finding the authorized process though which I can install libraries in my organization.
Regards
KK
Comment: Please accept your own answer, so other people can know that the question is solved.
Answer: i think your problem is related with a proxy, not a firewall.
anyway maybe you can ask pip to ignore the certificate issue, take a read at this post


Programmatically attach image to a content type from local system folder

Question: I am in middle of coding creating nodes programatically. Here i have one problem. I need to programmatically attach image to the content type from local system folder. I mean my image path example 'c://xxxxx/xxxx/images/img.jpg'.
Thanks in advance for your advice.
Hi i used this code and work fine in the localhost. But it's failed when i work on the server.
<code>$filepath = drupal_realpath('misc/druplicon.png');
// Create managed File object and associate with Image field.
$file = (object) array(
 'uid' => 1,
 'uri' => $filepath,
 'filemime' => file_get_mimetype($filepath),
 'status' => 1,
);

// We save the file to the root of the files directory.
$file = file_copy($file, 'public://');

$node->field_image[LANGUAGE_NONE][0] = (array)$file;
</code>
Reference link : attaching-files-to-nodes-programmatically-in-drupal-7

I didn't get the solution yet. Can any one have the experience?
Comment: Also check your logs to see if there is any error messages in there.  admin/reports/dblog
Comment: Did you check your file permissions to make sure you can copy into the folder?  admin/config/media/file-system
Answer: You can just use file_copy or file_move.
Here is an example: https://stackoverflow.com/questions/5129559/attaching-files-to-nodes-programmatically-in-drupal-7
Answer: I usually use a code like this:
<code>$filepath = 'TheFilePath';
$file = new stdClass();
$file->filename = basename($filepath);
$file->filepath = $filepath;
$file->filemime = file_get_mimetype($filepath);
$file->filesize = filesize($filepath);
$file->uid = 1;
$file->status = FILE_STATUS_PERMANENT;
$file->uri = $filepath;
$file->display = 1;
$file->description = '';
$file = file_copy($file, 'public://news-images', FILE_EXISTS_REPLACE);

$node->field_article_picture[LANGUAGE_NONE][] = (array)$file;
</code>
And it works...so I hope it helps for you too!


SelectNodes return null

Question: I am using SelectNodes to read xml nodes but i am getting null when i try GetElementsByTagName i get the values.
XmlDocument xml = new XmlDocument();
xml.Load(DownloadFile);
XmlNodeList xmlnode;
xmlnode = xml.GetElementsByTagName("CruisePriceSummaryResponse");

for (int i = 0; i < xmlnode.Count; i++)
{
    XmlNodeList rooms = xml .SelectNodes("RoomSize/CruisePriceSummaryRoomSize");
    for(int j = 0; j < rooms.Count; j++)
    {
        string bestFare = rooms[j].SelectSingleNode("BestFare/TotalPrice").InnerText;
        string fullFare = rooms[j].SelectSingleNode("FullFare/TotalPrice").InnerText;

        // do whatever you need
    }
}

I want to read TotalPrice from BestFare and FullFare Each child has two innerchilds BestFare and FullFareand I need to read each TotalPrice.
This is my XML
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfCruisePriceSummaryResponse
    xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://schemas.datacontract.org/2004/07/OpenseasAPI.ServiceModel">

        <CruisePriceSummaryResponse>
            <AvailablePromos
                xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
                <d3p1:string>FLA</d3p1:string>
                <d3p1:string>FLB</d3p1:string>
            </AvailablePromos>
            <Brand>PA</Brand>
            <CruiseCategory i:nil="true"/>
            <RoomSize>
                <CruisePriceSummaryRoomSize>
                    <BestFare>
                        <TotalPrice>2798.0000000</TotalPrice>
                    </BestFare>
                    <FullFare>
                        <TotalPrice>3198.000000</TotalPrice>
                    </FullFare>
                    <PaxCount>2</PaxCount>
                </CruisePriceSummaryRoomSize>
                <CruisePriceSummaryRoomSize>
                    <BestFare>
                        <TotalPrice>2796.000000</TotalPrice>
                    </BestFare>
                    <FullFare>
                        <TotalPrice>4196.000000</TotalPrice>
                    </FullFare>
                    <PaxCount>4</PaxCount>
                </CruisePriceSummaryRoomSize>
            </RoomSize>
            <ShipCode>PD</ShipCode>
        </CruisePriceSummaryResponse>
        <CruisePriceSummaryResponse>
            <AvailablePromos
                xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
                <d3p1:string>FLA</d3p1:string>
                <d3p1:string>LF1</d3p1:string>
            </AvailablePromos>
            <Brand>PA</Brand>
            <RoomSize>
                <CruisePriceSummaryRoomSize>
                    <BestFare>
                        <TotalPrice>1298.000000</TotalPrice>
                    </BestFare>
                    <FullFare>
                        <TotalPrice>3498.000000</TotalPrice>
                    </FullFare>
                    <PaxCount>2</PaxCount>
                </CruisePriceSummaryRoomSize>
                <CruisePriceSummaryRoomSize>
                    <BestFare>
                        <TotalPrice>1796.000000</TotalPrice>
                    </BestFare>
                    <FullFare>
                        <TotalPrice>5396.000000</TotalPrice>
                    </FullFare>
                    <PaxCount>4</PaxCount>
                </CruisePriceSummaryRoomSize>
            </RoomSize>
            <ShipCode>PJ</ShipCode>
        </CruisePriceSummaryResponse>
    </ArrayOfCruisePriceSummaryResponse>

Help would be appreciated. I do not want to use linq as this is a SSIS project using VS2008 and it doesnot support linq.
Thanks in advance
Answer: You never load or read the source XML. Your code
XmlDocument xml = new XmlDocument();
XmlNodeList xmlnode;
xmlnode = xml.GetElementsByTagName("CruisePriceSummaryResponse");

creates an empty XML document, and then tries to get elements from the empty xml.
You need to call XmlDocument.Load or XmlDocument.LoadXML to read the xml from a file or a string.
XmlDocument xml = new XmlDocument();
xml.Load("pathtosomefile.xml");
XmlNodeList xmlnode = xml.GetElementsByTagName("CruisePriceSummaryResponse");

Comment: Thanks i forget to add this line in the question posted and i am able to see the values in xmlnode but selectnodes is the problem here which is retuning null. P.S i have updated my question and added the missing xml.load line.

SelectNodes return null


List all revison users on a node

Question: I want to list all the users who have ever contributed to the revisions of a node.
Comment: you could see them on `http://your-site-url/node/%nid/revisions` just replace `%nid` by the node-id of the node.
Answer: Use The Views Module To Create A Custom Block
If you're using the Views module you can create a view that will show you what you need.
Create a new view (admin/structure/views/add) and choose 'Content Revisions' as the view type.

Add the 'Node Revision: User' relationship so that you can access the username of the user that made each edit.

Add a 'Node ID' contextual filter to your new view.

When the filter value is not available you should provide a default value.  Choose the Content ID from URL.

Add the field 'User: Name' but be sure to select the relationship you created earlier as in the graphic.  You may also want to add a link to view the revision or see when the revision was created.

You can optionally sort by "Content revision: Updated date" desc to ensure the block is easy to follow.
The last step is to go to 'admin/build/block' and enable the new block for the appropriate content types.
Lastly, one of my favorite resources for views comes from NodeOne's insanely talented Johan Flak. If you're new to views check out http://nodeone.se/sv/node/20
Also, as @indrock said in his comment, you can also see the history of a node's revisions at http://your-site-url/node/%nid/revisions  This is a much simpler solution and I wish I would have seen it before I went views crazy.
Comment: Just an addition: you can add user name twice and add aggregation to remove duplicate entries.
Comment: Nice use of screenshots to show some of the less obvious Views features.
Answer: Try to use Content revision: Nid as a contextual filter instead.

List all revison users on a node


T test when there are different raters? I am not sure if my procedure is correct

Question: I have two sets of translated text. The first set contains poor translations, and the second set includes perfect translations. I asked three evaluators to rate each of the translations. My objective here is twofold. First, I aim to demonstrate agreement among the evaluators using an Intraclass Correlation Coefficient (ICC) measurement. Second, I intend to use a T-test to highlight significant differences between the two sets of translations.
I am familiar with how to perform ICC and T-tests. However, I'm uncertain about conducting a T-test when multiple raters are involved. My current thought process is to take the average rating from the three evaluators for each translation, and then use these average ratings to perform the T-test.  The exampple below is my throught process.
Group A - poor translations
Translation 1: Rater 1 : 2, Rater 2 : 3, Rater 3 : 2
Translation 2: Rater 1 : 3, Rater 2 : 4, Rater 3 : 3
Translation 3: Rater 1 : 2, Rater 2 : 2, Rater 3 :  3
Group B - perfect translations
Translation 1: Rater 1 : 8, Rater 2 : 7, Rater 3 : 9
Translation 2: Rater 1 : 9, Rater 2 : 8, Rater 3 : 8
Translation 3: Rater 1 : 7, Rater 2 : 8, Rater 3 : 8
First, we compute the average rating for each Translation in both groups:
Group A
Translation 1: Average = (2+3+2)/3 = 2.33
Translation 2: Average = (3+4+3)/3 = 3.33
Translation 3: Average = (2+2+3)/3 = 2.33
Group B
Translation 1: Average = (8+7+9)/3 = 8
Translation 2: Average = (9+8+8)/3 = 8.33
Translation 3: Average = (7+8+8)/3 = 7.67
Now, I use the t-test to compare the means of the two groups.
from scipy import stats
<code># These are your means for each Translation
groupA_means = [2.33, 3.33, 2.33]
groupB_means = [8, 8.33, 7.67]

t_stat, p_val = stats.ttest_ind(groupA_means, groupB_means)

print('t-statistic:', t_stat)
print('p-value:', p_val)
```
</code>
Comment: Welcome to CV, Chen.  Might I suggest that instead of asking why some proposed procedure might be "correct," you ask what a good procedure would be?  In that fashion you are more likely to receive constructive answers that address your statistical problem rather than criticism of what or might not be a good procedure.  Regardless, you do need to format your post to help us understand what the lines beneath "Group A" represent: they are very ambiguous.
Comment: @whuberThanks for the comment. i have revised my question so it is more clear.
Answer: The use of the t-test here is not unreasonable, but it is not the most powerful way to analyze this data.
In this context, what you really have is a repeated measures ANOVA with both a within and between group factor.  As this may be sufficient to direct you to the correct analysis, I will stop here.  If you would like more information on running such an RM-ANOVA, I will be happy to update.
Comment: so in my case, it would be two way repeated ANOVA ? The between subject would be group A and B , within subject would be the different raters
Comment: By my reading of this context, the between subject effects are the treatment and the raters (where the raters could be viewed as a fixed or random factor), and the within subject effects would be the translation and the interaction of translation and treatment.


Site com animação

Question: comecei a estudar web agora e gostaria de saber quais linguagens são usadas para fazer um site com animações como estes:
http://helpsanta.panic.lv/
http://www.mallonitrace.com/
Grato!
Answer: Pelo visto os sites utilizam Javascript, HTML e css e o PHP, que são as bases para a web. Alem disso há um cms wordpress no ultimo site, que tem todas essas tecnologias já embutidas nele, mas recomendo que se quer aprender web, que começe a estudar o wordpress apenas quando tiver um certo conhecimento sobre as outras tecnologias.
Neste sentido voce pode estudar essas tres primeiras tecnologias que são voltadas mais ao front-end, ou seja a parte visual do site, e depois o PHP caso queira se aprimorar no back-end.
O wordpress irá te auxiliar a criar sites, ecommerces e até alguns sistemas de forma mais rapida, mas sem um conhecimento profundo, ficará um pouco engessado com este cms
Um bom site para pesquisar as tecnologias utilizadas na construção dos sites é o builtwith
Comment: Obrigado pela resposta e pelas dicas!

Site com animação


Prove that${n \choose k} \frac{1}{n^k} \le 2^{1-k}$, concluding that: $2 \le e \le 3$

Question: $${n \choose k} \frac{1}{n^k} \le 2^{1-k}$$ for all $1 \le k \le n$
by using $$e := lim_{n \rightarrow \infty} \Big(1+\frac{1}{1+n}\Big)^n$$
Show concluding that: $2 \le e \le 3$
My idea is the following:
${n\choose k}=\frac{n!}{k!(n-k)!}$ by using it :$${n \choose k} \frac{1}{n^k} \le 2^{1-k}=\frac{n!}{k!(n-k)!}\cdot\frac{1}{n^k} \le 2^{1-k}$$ I'm not sure that this step makes any sence since the exercise seems to be much more difficult now.
My second idea is that:
$${n\choose k}= {n\choose n-k}=\frac{n!}{{(n-k)}!(n-{(n-k)})!} = n!(n−k)!−k!$$ using the substitution:
$$n!(n−k)!-k!\frac{1}{n^k} \le  2^{1-k}$$ which doesn't makes the problem again more complicated.
I would appreciate your help a lot.
Comment: Did you try induction ?
Comment: I haven't and I'm actually a little bit confused how does it work in this exercise
Answer: The problem is equivalent to the following
$$\binom{n}{k}\frac{1}{n^k}\leq 2^{1-k}$$
$$\Rightarrow \binom{n}{k}\left( \frac{2}{n} \right)^k\leq 2$$
Now the term on the LHS are just the terms of the expansion of $(1+\frac{2}{n})^n$.Let $T_k$ denote the maximum term in the expansion.Our aim is to prove that $T_k\leq 2$
$$\frac{T_k}{T_{k-1}}\geq 1$$
$$\Rightarrow \frac{\frac{n!}{(n-k)!k!}\frac{2^k}{n^k}}{\frac{n!}{(k-1)!(n-k+1)!}\frac{2^{k-1}}{n^{k-1}}}\geq 1$$
This on simplification gives $k\leq 2\frac{(n+1)}{(n+2)}<2$.So k must be 0 or 1 .But we have $T_0=1$ and $T_1=n\times \frac{2}{n}=2$
Hence each term is less than 2 and our first part ,i.e, the inequality is proved.
Now for the second part consider
$$\binom{n}{k}\left( \frac{2}{n} \right)^k\leq 2$$
$$\Rightarrow \lim_{n\to \infty}\binom{n}{k}\left( \frac{2}{n} \right)^k\leq 2$$
$$\Rightarrow \frac{2^k}{k!}\leq 2$$
$$\Rightarrow \frac{1}{k!}\leq \frac{1}{2^{k-1}}$$
$$\Rightarrow 2\leq 1+\sum_{k=1}^{\infty}\frac{1}{k!}\leq 1+\sum_{k=1}^{\infty}\frac{1}{2^{k-1}}$$
$$\Rightarrow 2\leq e\leq 3$$


Logged in user name disappeares when navigating to another page

Question: In my first asp.net application, there are a master page & few WebForm pages. In the master page, there is a asp.net label control to show current user name. After login from Default.aspx , a user lands on Dashboard.aspx page. Master page label shows current user name correctly. But when i navigate to other page, current user name is disappearing. I am setting current user name in Dashboard.aspx page as the following -
<code> protected void Page_Load(object sender, EventArgs e)
{
    if (Session["CurrentUser"] ==null)
    {
        Response.Redirect("Default.aspx");
    }
    else
    {
         UserLogin user=(UserLogin) Session["CurrentUser"];

         Label userName = (Label)Master.FindControl("lblLoginName");
         if (userName != null)
         {
             userName.Text ="Welcome, " + user.EmployeeName;
         }

     }
}
</code>
How to overcome this issue?
Thank you.
Comment: Not very sure if this will solve the issue but did you try enabling view state for label? EnableViewState = "true" for the label?
Comment: Then did you tried disabling it?
Answer: if the label is in Master page you do not have to set it in page, simply set it on page load of Master page and effects will take place on every page.


Why do we choose exponential function as the nonlinearity in Possion GLM

Question: In Poisson GLM, the response variable $Y$ follows the Poisson distribution
$$P(Y=y)=\lambda^y\exp(-\lambda)/y!$$
and:
$$\lambda=\exp(\bf \theta^Tx)$$
My question is why do we use exponential as the nonlinearity function here (or why choose $\log()$ as the link function)? Why not use any other positive, monotonically increasing function?
Comment: It **is** possible to use other link functions,  for a discussion see https://stats.stackexchange.com/questions/203355/pros-and-cons-of-log-link-versus-identity-link-for-poisson-regression. But the log link function is most often used, one reason is that counts is an **extensive variable**, see https://stats.stackexchange.com/questions/142338/goodness-of-fit-and-which-model-to-choose-linear-regression-or-poisson/142353#142353  for an explication.
Answer: As mentioned in a comment, you don't need to use a log link: (R functions)
<code>glm(dat ~ x, family = poisson(link = "log")

glm(dat ~ x, family = poisson(link = "sqrt")

glm(dat ~ x, family = poisson(link = "identity"))
</code>
The log (or exponential) link is what is called the canonical link function for the Poisson glm.  It has nice properties and is derived as a side effect of writing the Poisson distribution as an exponential family.  But if you prefer a different link, you can use a different one.
Answer:
My question is why do we use exponential as the nonlinearity function here (or why choose $\log()$ as the link function)?

As AlaskaRon states, it is because it is the canonical form. This has many desirable properties. In general, we can write the density, $f$, of the exponential family as
$$\log f(y;\theta,\tau) = \log h(y, \tau) + b(\theta)T(y) - A(\theta) - d(\tau)$$
using the same notation as wiki where $\tau$ is the dispersion parameter and $\theta$ is related to the mean. We are working with a canonical form when $b$ is the identity function
$$\log f(y;\theta,\tau) = \log h(y, \tau) + \theta T(y) - A(\theta) - d(\tau).$$
This is the case with the Poisson model with the log link. You can see this by setting $\eta = \log \theta = \log \lambda$ and $\tau = 1$ with $d(\tau) = 1$ as
$$\begin{align*}
\log P(Y = y) &= y\log \lambda - \lambda -\log y! \\
  &= \underbrace{-\log y!}_{\log h(y,\tau)} + y\eta-\underbrace{\exp\eta}_{A(\eta)}
\end{align*}$$
One advantage with the canonical form is that the mean is
$$\text{E}(y; \theta,\tau) = A'(\theta)$$
and the variance is
$$\text{Var}(y; \theta,\tau) = A''(\theta)d(\tau)\geq0$$
Given that $d(\tau) > 0$ this implies that $\partial^2/\partial\theta^2\, \log f(y;\theta,\tau) \leq 0$ so the density is concave in $\theta$ which is nice for maximum likelihood estimation. There are further nice properties in terms of the moment generating function, that $T(y)$ is also the identity for many distributions, and more properties which are useful in a variety of applications.
See also this question, this question, and this answer.

Why not use any other positive, monotonically increasing function?

You can use another link function. You will not have all the nice properties which you get with the canonical form but the link function you choose may be a better approximation of the data generating process.


String vs Hash for string type? Hash will have only one key instead of many

Question: For example, I see many people are doing something like the following:
> set data:1000 "some string 1"
> set data:1001 "some string 2"

But what about using a hash to minimize the number of keys?
> hset data 1000 "some string 1"
> hset data 1001 "some string 2"

In the second way, it will only create one data key instead of creating many keys in the first way.
Which way is recommended?
I just see some people and tutorial are doing hset data:10 01 xxx. This is actually not related to my question. My question is simply asking what it's recommended between set data:1001 xxx and hset data 1001 xxx.
And I don't plan to modify hash-max-zipmap-entries and hash-max-zipmap-value. That means the hash will exceed the two values eventually. In such a config, are the two ways the same? or Which way is recommended?
Comment: This question is too broad, but [this memory optimization document](https://redis.io/topics/memory-optimization) should help.
Comment: @KevinChristopherHenry Thanks for your comment. I don't understand why you said the question was too broad. Just storing a simple string, is that broad? Everyone will need to store some strings with unique ids in the key. I am just wondering if I should use a hash or a string type. That's all. Because from my point of view, hash is much better. Only one key is required. But instead of hash, I see many people using string, which I don't understand why and wondering if this matters or just user's preference. Cheers.
Answer: Reasons to use strings:

you need per value timeouts
the values are semantically isolated
you're on cluster and want the values to be sharded over different nodes to spread load (sharding is based on the key)

Reasons to use hashes:

you want to be able to purge all of them at once (del/unlink), or have a timeout that impacts all of those values at once
you want to be able to enumerate them (prefer hscan/hgetall over scan/keys)
slightly better memory usage on the keys themselves
the values are semantically related
it is OK for all the values to be on the same node (whether single-server or cluster)
Comment: Thank you very much for the answer. I am more clear now. I don't use cluster for now, but I will definitely need to configure it in the future when the db gets bigger and bigger. That means I should choose strings instead of hashes then. *(unless I want to do pre-sharding like this `HSET object:12 34 somevalue`, which I really don't bother to do it)* Thank you very much!
Answer: This all depends on the tradeoffs you want to support. In general, using hashes will have a smaller memory footprint than using simple keys. In fact, it is about an order of magnitude less memory. And access to hash values is constant time. So, if you are using redis simply as a key-value store, then hashes are way more efficient than simple keys.
However, you will want to use simple keys if you need to support expiration, keyspace notifications, etc, then you will need to use simple keys.
Just be careful to tweak the values for hash-max-zipmap-entries and hash-max-zipmap-value in your redis.conf in order to ensure that hashes are treated correctly for your environment.
You can read all about the details in the memory optimization section of the documentation.
Comment: Thanks for the answer. But what if I don't need expiration, keyspace notification, and don't modify `hash-max-zipmap-entries` and `hash-max-zipmap-value` (that means the hash will exceed these two values), which way is recommended? OR are the two ways the same? Thanks a lot.
Comment: I'm not sure what you mean by "which way is recommended". If you don't need any of the special things that simple values give you (expiration, etc) then you should use hashes. You should also tweak your `hash-max-*` values so they are appropriate for your system. It's best to do some experementation and benchmarking to find out.
Comment: Thanks a lot for the reply. Regarding Marc's answer, I have to use strings instead of hashes if I use cluster and want to shard over different nodes. Due to this limitation, I think I will choose strings instead.


Date formator In django

Question: i working on a registration form in django
I taking  input from date field from front end is "12/15/2016"
but i want to save it like 12 dec 2016 in my django database.
I am using this calender
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">

my model.py for date is
posting_date = models.DateField(blank=True)

Views.py
post_date = str(request.POST['date'])

date = post_date.split('/')

formatted_date= date[1]+"-"+date[0]+"-"+date[2]

I want to save Dec instead of 12 for month
Comment: Possible duplicate of [Save date in django in desired format](http://stackoverflow.com/questions/41140317/save-date-in-django-in-desired-format)
Answer: Do it like this:
from dateutil import parser
formatted_date = parser.parse("12/15/2016")
yourobject.posting_data = formatted_date

Answer: Try formatting it using strptime and strftime instead:
formatted_datetime = datetime.strptime(post_date, strftime('%m/%d/%Y')) #formatted_datetime is now a datetime object
print( formatted_datetime.strftime('%d-%b-%Y') )

Documentation:
https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
Comment: global name 'strftime' is not defined
Comment: from datetime import datetime
Comment: i alreday import this
Comment: It needs to be, in the file:
from datetime import datetime

formatted_datetime = datetime.strptime(post_date, strftime('%m/%d/%Y'))
Answer: You can use DATE_FORMAT. See also: date

Date formator In django


Is the unitary group connected in infinite dimensions?

Question: Let $H$ be an infinite dimensional Hilbertspace and $U(H)$ the group of unitaries endowed with the norm topology.

Is $U(H)$ connected?

The following is a generalisation of the proof in the finite-dimensional case but will not work for an arbitrary unitary:

If we consider a unitary $u$, then $\Bbb1, u, u^*$ generate an abelian $C^*$-algebra isomorphic to $C(\sigma(u))$, here $\sigma(u)\subset S^1$ and $u$ corresponds to the function $\sigma(u)\to\Bbb C$, $z\mapsto z$. In the event that $\sigma(u)\neq S^1$ one can define a homotopy on $S^1$ that deforms $\sigma(u)$ to a point. This homotopy will correspond to a path that brings $u$ to $\Bbb1$ via unitaries in $C(\sigma(u))$ and thus in $U(H)$.

For $\sigma(u)=S^1$ such a homotopy is impossible, and $u$ is not connected to $\Bbb1$ in $C(\sigma(u))$. However if there exists a path in $U(H)$ connecting $u$ to a unitary with spectrum smaller than $S^1$, the above will give the result.
Another approach I had thought about was looking at the Cayley transform, however this does not have image all of $U(H)$. Finding a logarithm (ie a self-adjoint $A$ with $\exp(A)=u$) would give a path from $u$ to $\Bbb 1$ via $\exp(tA)$, but this path is only strongly continuous and not norm continuous.
Comment: Just as a side remark, the space $U(H)$ is even contractible by Kuiper's theorem.
Answer: $B(H)$ is a von Neumann algebra and you are allowed to use Borel functional calculus, so every unitary is connected to the identity.
Comment: I see, we may extend the algebra in my post to $L^\infty(\sigma(u))$ and remain a subalgebra of $B(H)$. Here any $S^1$ valued function may deformed continuously to the identity.
Comment: Maybe not any but the function $e^{it} \mapsto t$ is now Borel and hence applied to your unitary $u$ defines a logarithm, say $h$, of it. Then $t \mapsto e^{ith}$ deforms $u$ into $1$.
Comment: Let $A_1, A_2$ and be a decomposition of $S^1$ into an open and a closed "interval". Then any function $f= f_1+f_2$ where $f_1$ is zero on $A_i$. Now you can homotopy $A_i$ to points and then $f_i\circ h_{i,t}$ is a homotopy to a constant map that remains $S^1$-valued and in $L^\infty$. $f_1\circ h_{1,t} + f_2\circ h_{2,t}$ then deforms $f$ within $L^\infty$ to a function taking on at most two values, which can then be further deformed to the constant map.
Comment: Note also that the map $t\mapsto e^{ith}$ is not necessarily _norm continuous_. In general it is only strongly continuous.
Comment: The function $t \mapsto e^{ith}$ is surely norm continuous.
Comment: The generator $h$ of a semi-group can be unbounded, then you don't have norm-continuity. I was thinking about https://en.wikipedia.org/wiki/Stone%27s_theorem_on_one-parameter_unitary_groups . Although I see that you could define a bounded generator since you are only interested in hitting a specific unitary.
Comment: Okay, I already assumed that $h \in B(H)$, which is possible.


how to use "koa-favicon", getting "Not Found"

Question: const Koa = require('koa');
const app = new Koa();
const favicon = require('koa-favicon');
app.use(favicon());
app.listen(3008);

"favicon.ico" exist in root directory (__dirname). In Chrome I opening http://localhost:3008/ and see "network/favicon.ico" query with status 404:
Request URL: http://localhost:3008/favicon.ico
Request Method: GET
Status Code: 404 Not Found
[enter image description here][2]
Why ? favicon.ico exist there
Comment: I have a similar problem with `koa-sendfile` (Windows). It seems that `"C:\A1\B2\C3"` is treated as `".\A1\B2\C3"`, so the file is not found (you can check it by adding an error handler at the beginning of the middleware chain). A workaround is to use a relative path instead.
Answer: You need to specify path to icon.
const path = require('path');

app.use(favicon(path.join(__dirname, 'favicon.ico')));

Check this code. Middleware returns pass through function if you haven't specified icon path.

module.exports = function (path, options){
  if (!path) {
    return (ctx, next) => {
      if ('/favicon.ico' != ctx.path) {
        return next();
      }
    };
  } ...

Comment: app.use(favicon(path.join(__dirname, 'favicon.ico')));
the same result...Request URL: http://localhost:3008/favicon.ico Request Method: GET Status Code: 404 Not Found
Comment: but path.join(__dirname, 'favicon.ico') exist
Comment: @Алекс Make sure you have restarted the server and cleaned up browser cache just in case. If it doesn't  help you could set a breakpoint inside middleware function to check if it actually running and why it is not working as expected.
Comment: After load in chrome browser http://localhost:xxxx/, then "network/favicon.ico" auto-query to root directory г localhost:xxxx/favicon.ico. This file .ico exist there. What can I do in order to server give this existing "favicon.ico" instead of error "Not Found" ?
Comment: @Алекс It doesn't "query to root directory". It sends request to you server. This request will be processed by the middleware which reads icon file you have specified from anywhere in the file system. There are like 50 lines of code. Just drop debugger statement inside the function and launch your app in debug mode.
Comment: @Алекс Short article describing how to debug node app https://blog.risingstack.com/how-to-debug-nodej-js-with-the-best-tools-available/


Can we convert option[string] to caseclass in scala?

Question: When I tried to convert Some(string) into a case class I am getting an exception.
Ex:
val a:option[string]= Some("abc")
case class hello(a:string)
a.get.convertto[hello] => it is showing error

Answer: You need to allow for the Option being empty so avoid get and use getOrElse. Then just use the String to make the case class, like this:
val a: Option[String] = Some("abc")
case class hello(a: String)

val cc: hello = hello(a.getOrElse("default"))

Answer: The convertto you're looking for is map().
case class Hello(a: String)

val a: Option[String] = ??? //might be Some(s), might be None
val result: Option[Hello] = a.map(Hello)


How do I get this Highlighted feature through webpage code? And what is it called?

Question: Below is image, and i'm looking for the feature of if i select the icon, it becomes highlighted from BLUE to White.
I'm not sure what this feature is called I tried looking through boostrap and CSS HTML but can't seem to find what I'm looking for.
 Thank you !
Comment: That "feature" is called setting `active` class to vertical tabs!
Answer: You can use Stacked Tabs for that:

/* custom inclusion of right, left and below tabs */

.tabs-below > .nav-tabs,
.tabs-right > .nav-tabs,
.tabs-left > .nav-tabs {
  border-bottom: 0;
}

.tab-content > .tab-pane,
.pill-content > .pill-pane {
  display: none;
}

.tab-content > .active,
.pill-content > .active {
  display: block;
}

.tabs-below > .nav-tabs {
  border-top: 1px solid #ddd;
}

.tabs-below > .nav-tabs > li {
  margin-top: -1px;
  margin-bottom: 0;
}

.tabs-below > .nav-tabs > li > a {
  -webkit-border-radius: 0 0 4px 4px;
  -moz-border-radius: 0 0 4px 4px;
  border-radius: 0 0 4px 4px;
}

.tabs-below > .nav-tabs > li > a:hover,
.tabs-below > .nav-tabs > li > a:focus {
  border-top-color: #ddd;
  border-bottom-color: transparent;
}

.tabs-below > .nav-tabs > .active > a,
.tabs-below > .nav-tabs > .active > a:hover,
.tabs-below > .nav-tabs > .active > a:focus {
  border-color: transparent #ddd #ddd #ddd;
}

.tabs-left > .nav-tabs > li,
.tabs-right > .nav-tabs > li {
  float: none;
}

.tabs-left > .nav-tabs > li > a,
.tabs-right > .nav-tabs > li > a {
  min-width: 74px;
  margin-right: 0;
  margin-bottom: 3px;
}

.tabs-left > .nav-tabs {
  float: left;
  margin-right: 19px;
  border-right: 1px solid #ddd;
}

.tabs-left > .nav-tabs > li > a {
  margin-right: -1px;
  -webkit-border-radius: 4px 0 0 4px;
  -moz-border-radius: 4px 0 0 4px;
  border-radius: 4px 0 0 4px;
}

.tabs-left > .nav-tabs > li > a:hover,
.tabs-left > .nav-tabs > li > a:focus {
  border-color: #eeeeee #dddddd #eeeeee #eeeeee;
}

.tabs-left > .nav-tabs .active > a,
.tabs-left > .nav-tabs .active > a:hover,
.tabs-left > .nav-tabs .active > a:focus {
  border-color: #ddd transparent #ddd #ddd;
  *border-right-color: #ffffff;
}

.tabs-right > .nav-tabs {
  float: right;
  margin-left: 19px;
  border-left: 1px solid #ddd;
}

.tabs-right > .nav-tabs > li > a {
  margin-left: -1px;
  -webkit-border-radius: 0 4px 4px 0;
  -moz-border-radius: 0 4px 4px 0;
  border-radius: 0 4px 4px 0;
}

.tabs-right > .nav-tabs > li > a:hover,
.tabs-right > .nav-tabs > li > a:focus {
  border-color: #eeeeee #eeeeee #eeeeee #dddddd;
}

.tabs-right > .nav-tabs .active > a,
.tabs-right > .nav-tabs .active > a:hover,
.tabs-right > .nav-tabs .active > a:focus {
  border-color: #ddd #ddd #ddd transparent;
  *border-left-color: #ffffff;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />

Tabs -left

One

Two

Twee

Lorem ipsum dolor sit amet, charetra varius quam sit amet vulputate.
      Quisque mauris augue, molestie tincidunt condimentum vitae, gravida a libero.

Secondo sed ac orci quis tortor imperdiet venenatis. Duis elementum auctor accumsan.
      Aliquam in felis sit amet augue.

Thirdamuno, ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra varius quam sit amet vulputate.
      Quisque mauris augue, molestie tincidunt condimentum vitae.

Comment: Ahh lovely ! Thanks so much


Swift property wrappers initilaization error

Question: I am trying to use PropertWrapper for email validation. But when i try to initialize the eamilId varaible with empty string i am getting error : Incorrect argument label in call (have 'wrappedValue:', expected 'emailId:')
Here is the code of My view controller
class ViewController: UIViewController {
    var name: String = ""
    @EmailWrapper var emailId: String = ""

  override func viewDidLoad() {
    super.viewDidLoad()
    name = "User Name"
    emailId = "firstname.lastname@example.com"
    updateUserDetails()
  }

  func updateUserDetails() {
    if name.isEmpty || emailId.isEmpty {
        print("Please enter valid Name and emailId")
    }
    else {
        print("User data updated successfully")
    }
  }
}

And the code for my property wrapper is
@propertyWrapper
struct EmailWrapper {
    private var value = ""
    var wrappedValue: String {
        set {
            value = newValue
        }
        get {
            return isValidEmail(value) ? value : ""
        }
    }

    init(emailId: String) {
        self.value = emailId
    }
    private func isValidEmail(_ email: String) -> Bool {
        let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
        let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
        return emailPred.evaluate(with: email)
    }
}

How can I initialize the emailId with default value (String()) in ViewController while using the EmailWrapper
Answer: When you apply a property wrapper:
@EmailWrapper var emailId: String = ""

the Swift compiler actually generates a call to the initialiser to the initialiser of the property wrapper like this:
EmailWrapper(wrappedValue: "")

However, EmailWrapper doesn't have such an initialiser. Its only initialiser has the argument label emailId: instead.
To fix this, you just need to change the argument label of the initialiser:
init(wrappedValue: String) {
    self.value = wrappedValue
}


cakephp TinyMCE JS path not working after url change

Question: I suspect this is something to do with URL rewriting but I'm a little stuck.
I'm using the cakeDC tinyMCE plugin which works fine on my local web server but when I upload the whole cakeapp onto a testing url (I'm going from localhost/knowledgebase to intranet/knowledgebase) everything works apart from the TinyMCE JS include.
Heres the problem line -

When I click this in dev tools it can't load the file. Other script src's work fine such as:

The difference is I'm using the CakeDC TinyMCE helper to produce the link from the view, the other links all point to files in the webroot/js folder.
Can anyone point me in the right direction?
Thanks in advance.
Answer: What I always do is making sure the $this->webroot available in views is accessible in my JavaScript like so:
$this->Html->scriptBlock('var webroot = "' . $this->webroot . '"');

So now I can use the webroot as a path reference for path declarations in my JS. Since working with dots and double dots isn't that readable or usable.
It might be possible I am overlooking some features of Cake, but this has been my approach for every project in Cake since the beginning.
Comment: Thanks for the reply, the JS file in question isnt actually in webroot its in the TinyMCE plugin directory (Plugin/TinyMCE/View/Helper/TinyMCEHelper.php). The TinyMCE helper injects the script tag into the head of the view.
Comment: Can you clearify your question? I am not entirely sure what the problem is then :)


How to choose a special modulus to show that $6n^3 +3 = m^6$ has no solutions in the integers

Question: I was stuck on a problem from Mathematical Circles: Russian Experience, which reads as follows:

Prove that the number $6n^3 + 3$ cannot be a perfect sixth power of an integer for any natural number n.

The problems previous to this dealt with proving that numbers cannot be a cube and cannot be a square. The hints offered to these problem said that a square leaves a remainder of 0 or 1 when divided by 3 or 4, and that a cube leaves a remainder of 0, 1 or 8 when divided by 9. However, for this problem, the hint states that the reader should "experiment by dividing the number by 7 and comparing it remainders of sixth powers divided by 7".
Where did that come from? How would the solver figure out that $6n^3 + 3$ should be divided by 7? Moreover, why are 3 and 4 used in proving facts about squares, and why is 9 used when proving facts about cubes? Was this mainly through trial and error over the years, or is there some obvious fact that I'm blanking out on?
Thanks!
Comment: [Fermat's little theorem](https://en.wikipedia.org/wiki/Fermat%27s_little_theorem) states that If $a$ is not divisible by $p$ then $a^{p-1}\equiv 1\pmod p$. Like we have to find or find not a $6$th power, it's logically based to check $\pmod7$ too.
Comment: $n^6 \equiv 1 \pmod 7$ given that $n \neq 7k$.
Answer: Here is some motivation for the choice of $7$ as the modulus, as you asked. The equation that you want to show that has no solutions in the integers is $$6n^3 +3 -m^6=0.$$ When it comes to polynomial Diophantine equations, especially of the olympiad variety, a common trick is to take everything to one side, look at the equation in a certain modulus $q,$ substitute in all possible combinations of the residues and show that the expression never equals the zero residue. Both because you want to be efficient in your computations and because you want to reduce the chances of everything cancelling out to zero (this heuristic is not rigorous), the idea is to pick a modulus where the various terms in the expression will take on very few distinct values.
As far as I know, there is no general known method of finding the ideal modulus, but there are two general techniques of which I am aware: take advantage of Sophie Germain primes and Fermat's little theorem. Sophie Germain primes $p$ satisfy the fact that $2p+1$ is also a prime, and $3$ is a such a prime. By Fermat's little theorem, if $p$ is a Sophie Germain prime, then $$x^{2p}\equiv 1 \pmod{2p+1}$$ or $x\equiv 0\pmod{2p+1}.$ So $$x^p\equiv \pm 1 \pmod{2p+1}$$ or $x\equiv 0\pmod{2p+1}.$ This means $7$ is a really nice modulus because you have a cube whose resides can only be $0,1,-1,$ and a sixth power whose residues can only be $0,1.$ Then just compute the $2\cdot 3=6$ cases and none will work out.
By the way, years ago I asked the general question on MathOverflow in this thread. (Sadly, I deleted the email address associated with that account and so can no longer access the account, sigh.)
Comment: Like I said, there is no known method of finding the "optimal" modulus. It's just a matter of what happens to work, which is not always obvious (see the top-voted response in the thread that I linked). What you can do is remember some common tricks. Yes, $9$ is a good modulus to use when you have cubes because there are only three cubic residues $\pm 1,0.$ And $7$ is good for this problem because it has very few cubic and sixth power residues, and you can discover it by using the heuristics that I mentioned about Fermat's little theorem and Sophie Germain primes.
Comment: Yes, that's right.
Comment: Hey thanks for answering. Unfortunately, I have no background in number theory (since it's not taught at my high school) and usually think these problems out to get the right answer. While I could generally follow your solution, can you elaborate on how I would be able to "discover" that 7 is an optimal modulus to use for this problem? Is the general reason that 7 is used in this problem because of the fact that it only has 3 residues (0,1 and 6)? Is that also why 3 and 4 are used in proving facts about squares, and why is 9 used when proving facts about cubes? Thanks!
Comment: Okay, so to summarize and make sure I completely understand what you are saying: much of this intuition has been developed over the years and so it's not usually an expectation to know the perfect modulus right off the bat. However, ideas such as FLT and SGP help quantify the abstraction and point the problem solver in the correct direction. Are these accurate statements? Thanks once again.
Answer: I guess that the power is chosen because when working with modular arithmetic, one would directly consider euler's theorem (which is a generalization of fermat's little theorem) and see if it helps:
$$a^{\phi(n)} \equiv 1 \pmod{n}$$
If $a$ and $n$ are relatively prime, and $\phi(n)$ is euler's totient function. Now seeing that the problem required $m^6$, one would see which $n$ in euler's theorem would give him $\phi(n)=6$. The well known property of the totient function is that for any prime $p$, $\phi(p)=p-1$ and this works with us so we have to check modulo $7$. As far as I know, there isn't a secret formula to see which modulo would be the most useful. However, there are some useful things to consider, check the brilliant wiki "Diophantine equations: modular arithmetic considerations".
Now, back to the problem!
Hint: try the case $7|6n^3+3$ and prove there's a contradiction to get $7 \nmid6n^3+3$ so you can use fermat's little theorem/euler's theorem and modular arithmetic to prove that it can't be.
Solution:
$$6n^3+3=m^6$$
If $7| 6n^3+3$, we have
$$6n^3 \equiv-3 \pmod{7} \implies 2n^3 \equiv-1 \equiv6 \pmod{7}$$
$$\implies n^3 \equiv3 \pmod{7}$$
which is impossible. So $7 \nmid 6n^3+3 \implies 7 \nmid m^6$
$$\implies m^6 \equiv1 \pmod{7} \tag{FLT}$$
$$\implies 6n^3 \equiv2 \pmod{7} \implies 3n^3 \equiv1\equiv8\equiv15 \pmod{7}$$
$$\implies n^3 \equiv5 \pmod{7}$$
which is also impossible.
Comment: @Favst Oh, it's just a hint. Normally when checking modular arithmetic with such powers, one considers euler's theorem directly.
Comment: The student did not ask for a proof that shows why the modulus of $7$ works. The student asked how one might come up with the modulus in the first place.
Answer: $6n^3+3=m^6\tag{1}$
$n^3\equiv {0,1,6} \pmod{7}$ then $6n^3+3\equiv {2,3,4} \pmod{7}$.
On the other hand, $m^6\equiv {0,1} \pmod{7}$
Hence $LHS$ is not equal to $RHS$ $\pmod{7}.$
Therefore equation $(1)$ has no intger solution.


Using $2\pi\sqrt{\frac{a^2+b^2}{2}}$ to approximate the circumference of an ellipse

Question: I'm a 37 year old who hasn't had to think about the geometry of circles in 20 years, so I'm a bit stuck on my problem at hand. I am working on the design of a high tunnel greenhouse and trying to determine approximately (I don't need exact numbers as I can trim off extra) how much plastic I'll need to cover.
The width of my greenhouse is 8.5 ft and a height of 6 ft. Now, from what I've gathered online, the approx circumference of an ellipse can be determined with this formula: $2\pi\sqrt{\frac{a^2+b^2}{2}}$. If I plug in my number where a=12 (height x 2 since my greenhouse is only half of an ellipse) and b=8.5, I get a circumference of 65.33. Divide that by two (again, my greenhouse is only half of the ellipse) and I get 32.67 ft.
That looks right. But, just to check, I took a more simplistic look at a circle. The circumference of a circle is $\pi d$. If I used the width of my greenhouse, 8.5', which then means the height is also 8.5', which is higher than the actual 6' of my ellipse. $\pi 8.5 = 26.7$. Again, if I half that to get half the circumference, I get 13.35 ft.
Now, with the circle formula, I am assuming my height is greater than it actually is, yet the resulting number is significantly less than my result for the ellipse. So, I'm stumped here.
Answer:
The $a, b$ for the ellipse are "half" of what you put in (see screenshot below), which works out to 32.44. Half of that is ~16.2
A width of 8.5 and a height of 8.5 for a "half arc" doesn't yield a semi circle. You need width = 8.5 and height = 4.25, which yield ~13.3.
Hence, your greenhouse is $~40\% = \frac{ 6-4.25}{4.25}$ higher than a semicircle, so the material used is more. $~22\% = \frac{ 16.2-13.3}{13.3}$ more materials doesn't seem that off.
Answer: Semi circumference of greenhouse arch =$\pi\sqrt{\dfrac{a^2+b^2}{2}}$
$ (a,b)$ are semi-major and minor axes. So plug in
$$ a=\dfrac{8.5}{2} = 4.35,\, b=6 \,$$
calculates to $\approx 16.3336\,;$


How to add cache contexts to a region

Question: How can I add cache contexts to a region. I have been able to do this to my blocks but have noticed that parts of the region remain cached.
Answer: You can add a cache context to a region the same way as to any other page element:
<code>function mytheme_preprocess_region(&$variables) {
  if ($variables['region'] == 'myregion') {
    $variables['#cache']['contexts'][] = 'user';
  }
}
</code>
But this is probably not what you want, because regions are not cached. Usually the blocks inside a region are cached and the complete page which contains the regions. The cache context of the region will only have an effect on higher level elements, not downwards.

How to add cache contexts to a region


haproxy httpchk with authentication

Question: Is it possible to do health check httpchk and pass credentials?
I supposed to try to pass user name and password and if that fails to change server state to down.
Thanks
Answer: I will answer to myself it might be helpful to someone else. This is what I've done.
$ echo -n "my_username:my_password" | base64
I got this string: TkxCX0hCOkhCREhCX0NoZWNr
After that I put the following int my conf:
option httpchk GET /CSHRIS/WS/Service.asmx HTTP/1.0\r\nAuthorization:\ Basic\ TkxCX0hCOkhCREhCX0NoZWNr
Comment: Where did you put it in the configuration? Which section?
Answer: Had the same concern when I was trying to load balance between my Elastic search nodes,

Use curl and grab the Authentication header,
curl -v http://username:password@ip_or_domain_name:9200/path_to_the_heath_check

...
GET /path_to_the_heath_check HTTP/1.1
Host: ip_or_domain_name:9200
Authorization: Basic someBas64encoDedUsernameAndPassword==
User-Agent: curl/7.61.1
...
2. Derive the Healthcheck config

<code>option httpchk GET /path_to_heath_check HTTP/1.1\r\nAuthorization:\ Basic\ someBas64encoDedUsernameAndPassword==
</code>

haproxy httpchk with authentication


Composer.json deletes dir even with preserve path

Question: I am running composer on Drupal 7 and I am just trying to update my site; however when I run composer update, the composer deletes all the preserve paths I had specified.
My structure is as follows:
composer.json

composer.lock

web/

    -sites/default

in my composer.json I have as follow:
{
...
"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/7"
    }
],
"require": {
   ...
},
"conflict": {
    "drupal/core": "8.*"
},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
      "sort-packages": true
},
"autoload": {
    "classmap": [
        "scripts/composer/ScriptHandler.php"
    ]
},
"scripts": {
    "pre-install-cmd": [
        "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
    ],
    "pre-update-cmd": [
        "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
    ],
    "post-install-cmd": [
        "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
    ],
    "post-update-cmd": [
        "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
    ],
    "post-create-project-cmd": [
        "DrupalProject\\composer\\ScriptHandler::removeInternalFiles"
    ]
},
"extra": {
    "installer-paths": {
        "web/": ["type:drupal-core"],
        "web/profiles/{$name}/": ["type:drupal-profile"],
        "web/sites/all/drush/{$name}/": ["type:drupal-drush"],
        "web/sites/all/libraries/{$name}/": ["type:drupal-library"],
        "web/sites/all/modules/contrib/{$name}/": ["type:drupal-module"],
        "web/sites/all/themes/contrib/{$name}/": ["type:drupal-theme"]
    },
    "patches": {
        "cweagans/composer-patches": {
            "Call the preserve paths hooks" : "https://github.com/SebCorbin/composer-patches/commit/1cb9bacba51f8bba0c5f3f322c3bb61e4ceae974.patch"
        }
    },
    "preserve-paths": [
        "web/sites/all/drush",
        "web/sites/all/libraries",
        "web/sites/all/modules/contrib",
        "web/sites/all/modules/custom",
        "web/sites/all/modules/features",
        "web/sites/all/themes/contrib",
        "web/sites/all/themes/custom",
        "web/sites/all/translations",
        "web/sites/default"
    ]
}

}
What ends up happening is it install the core and modules correctly in web/ folder, but deletes all the preserve paths as well. Any suggestions as to why i am having this problem? Thank you.
I have tried to put composer.json in the web/ folder as well, that just imports all the require modules and core in a subfolder (web/web/).
I am now getting:
Files of installed package were overwritten with preserved path x/web/sites/default!
Files of installed package were overwritten with preserved path x/web/sites/all/libraries!
and the preserve paths didn't do anything.
Answer: It looks like you haven't installed the plugin. Just run:
composer require drupal-composer/preserve-paths

And try again.
If it still doesn't work, you'll probably need to report it as a bug to the plugin's issue queue.


What does :: do?

Question: I have some inherited code that I am modifying. However, I am seeing something strange(to me).
I see some code like this:
::User.find_by_email(params[:user][:email]).update_attributes(:mag => 1)

I have never seen something like this(I am new to Ruby on Rails). What does this do and why doesn't my User.find_by_email(params[:user][:email]).update_attributes(:mag => 1) work? The error says something about the User constant.
I am using Rails 2.3.5 if that helps.
Answer: :: is a scope resolution operator, it effectively means "in the namespace", so ActiveRecord::Base means "Base, in the namespace of ActiveRecord"
A constant being resolved outside of any namespace means exactly what it sounds like - a constant not in any namespace at all.
It's used in places where code may be ambiguous without it:
module Document
  class Table # Represents a data table

    def setup
      Table # Refers to the Document::Table class
      ::Table # Refers to the furniture class
    end

  end
end

class Table # Represents furniture
end

Answer: It makes sure to load the User model in the global namespace.
Imagine you have a global User model and another User model in your current module (Foo::User). By Calling ::User you make sure to get the global one.
Answer: Ruby uses (among other things) lexical scoping to find constant names. For example, if you have this code:
module Foo
  class Bar
  end

  def self.get_bar
    Bar.new
  end
end

class Bar
end

The Foo.get_bar returns an instance of Foo::Bar. But if we put :: in front of a constant name, it forces Ruby to only look in the top level for the constant. So ::Bar always refers the top-level Bar class.
You will run into situations in Ruby where the way your code is being run will force you to use these 'absolute' constant references to get to the class you want.
Answer: You might find a lead here: What is Ruby's double-colon `::`?
Comment: That explains what the :: does, but not what a :: with no identifier in front does. :)
Comment: True enough.  I don't use Ruby, but the '::' operator looks to be a scope resolution operator.  My guess is that '::User' simpy means the global User identifier in the current module.  Can someone confirm?
Comment: @Lennart: Thanks. I awarded you a +1 for getting your answer in before my clarification. Also, +1 to Gareth for a slightly clearer answer than ours.
Answer: The "::" operator is used to access Classes inside modules. That way you can also indirectly access methods. Example:
module Mathematics
    class Adder
       def Adder.add(operand_one, operand_two)
           return operand_one + operand_two
       end
    end
end

You access this way:
puts "2 + 3 = " + Mathematics::Adder.add(2, 3).to_s

What does :: do?


Modification of a reduced homology

Question: Background:
In Hatcher's Algebraic Topology Chapter 2, reduced homology with coefficient $R$ of a space $X$ is defined as the homology groups of a chain complex
$$
...\to C_{2}(X)
\overset{\partial_{2}}\to C_{1}(X)
\overset{\partial_{1}}\to C_{0}(X)
\overset{\epsilon}\to R
\to 0
$$
where $\epsilon(\Sigma_{i}n_{i}\sigma_{i}:=\Sigma_i n_{i})$.
If my understanding is correct, reduced homology is a better-behaved alternative for usual simplicial/singular homology.
Detail
I came up with a further modification of a singular homology for some $n$-dimensional orientable, compact, manifold $X$ defined as the homology of the chain complex
$$
R
\overset{\eta}\to C_{n}(X)
\to ...\to C_{2}(X)
\overset{\partial_{2}}\to C_{1}(X)
\overset{\partial_{1}}\to C_{0}(X)
\overset{\epsilon}\to R
\to 0\\
\text{where }\eta(r) := r\cdot [X]
$$
which I refer to as reduced-reduced homology $H_{\bullet}'(X)$ of $X$.
Dually, one can also define the reduced-reduced cohomology ${H^{\bullet}}'(X)$ of $X$ by modifying the de Rham complex of $X$;
$$
R
\overset{\Delta}\to\Omega^{0}(X)
\to ...\overset{d_{n-1}}\to \Omega_{n-1}(X)
\overset{d_{n}}\to \Omega_{n}(X)
\overset{\int}\to R
\to 0
$$
where $\Delta(r)$ is a constant scalar field on $X$ and $\int$ is an usual integration of a valume form on $X$.
It is easily checked that the above defined (co)chains are indeed (co)chain complexes.
Questoin:
My question is:

Do the reduced (co)homologies well-behave? In particular, does Poincare duality $H_{n-p}'(X)\cong {H^{p}}'(X)$ holds?
Are there any reference/article about this concept?

Thank you in advance.
Comment: Reduced homology isn't 'more' well behaved in general. It might be more useful for certain classes of spaces (such as wedge sums and quotients). In other cases you'd probably want to stick to regular homology (such as when dealing with products). Also I'm assuming question 1 is about whether Poincaré duality holds for $H'(X)$ that you define right?
Comment: Also, do you mean $\eta(r) = r[X]$? $X$ by itself is not a chain.
Comment: Osama, thank you. I edited my post.
Answer: I think you lose functoriality altogether, but I'm not entirely sure (feel free to correct me if I'm wrong). Suppose you have a map $X \to Y$. Then you have chain maps and in particular a homomorphism $C_i(X) \to C_i(Y)$ and this also works for the augmented $\mathbb{Z}$ (the square with $C_0(X), C_0(Y)$ and the two $\mathbb{Z}$'s commute). However it isn't apparent to me what happens with the square on the left. In the case where the dimensions of $X$ and $Y$ are the same, then we are trying to show commutativity of a square with two $R$'s, and $C_n(X)$ and $C_n(Y)$. For this to commute you might need some really strong conditions, such as that $f$ maps the fundamental class of $X$ to the fundamental class of $Y$. Now when $X$ and $Y$ are of different dimensions, the left square doesn't even make sense because you have mismatched groups.
Comment: Thanks, and I realized that the square induced by $\int$ also does not commute.

Modification of a reduced homology


Product of connected sets, proper subsets

Question: Let $X,Y$ be connected sets and $A,B$ proper subsets of $X$ and $Y$ respectively. Then it can be shown that the space $ (X \times Y) \setminus (A \times B)$ is connected. This is an problem from Munkres book. My question is:
Is the above result still true when we replace connectedness by path-connectedness instead?
Answer: Yes, and the proof is even easier than the connectedness proof. You just need to construct a path between any two points, which you can do piecewise, staying in subsets of the form $X\times\{y\}$ and $\{x\}\times Y$, which are path connected.
Alternatively you can copy the connectedness proof, which consists of covering $X\times Y\setminus A\times B$ in stages by connected sets which have a point in common. This still works for path connectivity.


How do I get an internal SVG element's position relative to the viewport of an outer SVG element?

Question: Say I have an SVG element containing some stuff:

  <svg>
    <g transform="translate(34.34,47.5) scale(0.345)" height="100%" width="100%">
      <svg x="20" y ="50" style="overflow: visible">
        <circle cx="0" cy="0" r="35" stroke="red" fill="blue">
        <text>a bunch of text</text>
      </svg>
      <line />
    </g>
  <svg>

I'm trying to find the center position of the <g> relative to the viewport of the outer <svg> element, so that I can translate the <g> to be centered within the outer <svg>, and scale it to fit.
I was able to get it working using getBoundingClientRect() and adjusting for the transform scale, but this does not work in Firefox because the <svg> elements inside the <g> container are not constrained to the bounding box of the displayed section of their contents (rather it's the same size as the outer <svg>, with some scaling).
There is probably a solution using createSVGPoint() and getScreenCTM() or getCTM() but frankly I'm not sure what I should be using.
Comment: Remove the inner  element and adjust the  transform to compensate.
Comment: in your example you have a circle inside an inner svg. the circle is drawn in part outside the inner svg due to it's center in the origin of the inner SVG. I can center the inner svg but then the circle won't be centered, or I can center the circle, but then the inner svg won't be centered.
Comment: The contents of the `` are arbitrary; in this case i have some components that render a circle with some text and arbitrary siblings wrapped inside its own `` so i don't have to recalculate coordinates relative to the outer ``. the `` is another example of what could be inside the ``. There can be multiple instances of the inner `` with different positions and text etc
Comment: @enxaneta yes that is why i have the overflow set to visible.
Answer: An SVG without a viewBox attribute has a width of 300px and a height of 150px. I've added a viewBox="0 0 300 150". You can remove it.
Also I've added a rectangle to be able to see the position and the size of the <g> element. You can remove it as well.
How I would center the <g> element: Since the <g> element is transformed the easiest way to get it's size and position would be wrapping the <g> element in another one, in this case <g id="wrap"> Next I can get the bounding box of the wrap: wrap.getBBox()
In order to center the wrap I need to know the center of the main svg canvas: x = 300/2; y=150/2. Now I can translate the wrap into the center

let c = {x:150,y:75}//the center of the main svg element
let bb = wrap.getBBox()//the bounding box of the wrap

let transformation = `translate(${c.x - bb.x - bb.width/2},
                                ${c.y - bb.y - bb.height/2})`

wrap.setAttributeNS(null,"transform",transformation)
svg{border:1px solid;width:100vh;}
text{fill:black;}
path{fill:none;stroke:black}

  <svg id="main" viewBox="0 0 300 150" >
    <g id="wrap">
      <rect x="29.165" y="47.5" width="45.03" height="29.325" fill="gold" fill-opacity=".5" />
      <g transform="translate(34.34,47.5) scale(0.345)" height="100%" width="100%">
      <svg x="20" y ="50" style="overflow: visible">
        <circle cx="0" cy="0" r="35" stroke="red" fill="blue"/>
        <text>a bunch of text</text>
      </svg>
      <line />
    </g>
    </g>

    <path d="M0,0L300,150M0,150L300,0" />
  <svg>

I hope this is what you were asking.
Comment: the transform on the `` is arbitrary based on the user's zoom/pan interaction (using `d3` to deal with this, it generates the translate and scale values). the functionality i'm writing is meant to snap the contents of the `` group to the center of the viewport and scale it so it fits
Answer: I managed to figure out a solution using one of the d3.zoom transform methods (we're using d3.zoom to manage the translate/scale transform), and  SVGElement.getBBox(). I originally was using this method but had messed up the calculation; this way it works though.

const selection = d3.select(group);
const zoomBehavior = d3.zoom().on('zoom', () => {
  selectionTransform = d3.event.transform;
});
selection.call(zoomBehavior);

const scaleAndTransformTo = () => {
  selection.call(zoomBehavior.translateBy, Math.random() * 100, Math.random() * 150);

  group.setAttribute("transform", selectionTransform.toString());
}
scaleAndTransformTo();

reset.addEventListener('click', scaleAndTransformTo);
run.addEventListener('click', () => {
  const { width: containerWidth, height: containerHeight } = container.getBoundingClientRect();
  const containerCenter = [containerWidth / 2, containerHeight / 2];

  const { height, width, x, y } = group.getBBox();
  const nodeBBoxCenter = [x + (width / 2), y + (height / 2)];

  // Apply the current interpolated translate/scale to the BBox center to get the actual position
  const groupCenterCoords = selectionTransform.apply(nodeBBoxCenter);

  const translationOffset = [
    (containerCenter[0] - groupCenterCoords[0]) / selectionTransform.k,
    (containerCenter[1] - groupCenterCoords[1]) / selectionTransform.k,
  ];

  selection.call(zoomBehavior.translateBy, ...translationOffset);

  group.setAttribute("transform", selectionTransform.toString());
});
#page {
  display: flex;
  flex-direction: column;
  position: relative;
  align-items: stretch;
  margin-left: 100px;
}

#container {
  background-color: grey;
  flex-grow: 1;
  flex-shrink: 0;
  min-height: 500px;
  border: 1px solid red;
}

#group > svg {
  overflow: visible;
}

#group > svg > circle {
  overflow: visible;
}

text {
  fill: black;
}

    <button id="run">Run</button>
    <button id="reset">Reset</button>

  <svg id="container">
    <g x="0" y="0" id="group" width="100%" height="100%">
      <line x1="20" y1="50" x2="150" y2="150" stroke="brown" />
      <svg x="20" y ="50">
        <circle cx="0" cy="0" r="35" stroke="red" fill="blue">
        <text x="35" y="0" height="100%" width="100%">a bunch of text</text>
      </svg>
      <line x1="100" y1="350" x2="160" y2="340" stroke="brown" />
      <svg x="100" y ="350">
        <circle cx="0" cy="0" r="35" stroke="red" fill="blue">
        <text x="35" y="0" height="100%" width="100%">a bunch of text 3</text>
      </svg>
    </g>
  <svg>


What to choose Content Type or Drupal Commerce or Ubercart

Question: I'm working on a project where we've people managing product in site (including product creation, editing, viewing, reviewing, etc.). These are not going to be techie people so the product management should be easy to use with quick loading. The site as of now doesn't allow users to sell and buy product online (It might allow in future, but not confirmed - very less chances). Its just viewing, reviewing, rating products. Also there will be variety of product. We're also planning on creating Mobile App for this so user can manage products from App.
As I've already worked with all of these 3 earlier, my personal thought is that Drupal Commerce and Ubercart may add an extra overhead of e-commerce functionality on our site. I need suggestion on how should we proceed here, what things should we consider while selecting any one of these 3. What should be best choice to go ahead in such scenario i.e. Plain content type or Drupal Commerce or Ubercart.
Comment: If you are not going to sell products then just use content types and adding ratings. Easy to use for end user and you don't need to configure Drupal Commerce or Ubercart stuff if you don't need it.
Comment: Thanks @pgrujic, for quick reply. Yes, but how best we can manage variety of product types using content type considering easy to use ui and performance?
Comment: There are too many possible answers to that question @Yogesh. You need to put a proof of concept together and see which scenario supports your specific needs
Answer: Just go (start with) what you call "Plain content types".
For the "rating" requirements, have a look at my answer to "What are recommended modules or processes which support rating based comments or reviews?".
Should you ever want to expand that to a (rather basic) e-shop and/or add a shopping cart, you can always use the modules as I suggested in my answer to "How to create a simple shopping cart without Drupal Commerce or Ubercart?".
Next question?
Answer:
We're also planning on creating Mobile App for this so user can manage
  products from App.

I highly suggest you go with Drupal 8 as it's mobile ready and friendly.
If you are not selling anything, content types is the way to go.
For displaying various products you can use the Views module, which comes with Drupal 8.
For performance Drupal 8 automatically caches your pages and clears the cache when you make changes.
Comment: Thanks for suggestion, but we've reviewed that already and there are many other modules which are not available for D8, few of them are Location, FiveStar, Voting API, etc. so D8 won't be good option in our case.


How to solve below question on Probability?

Question: You have a bag with 347 black balls and 278 white balls. Without looking, you pick up two balls from the bag and apply the following rule.
If both balls are of the same colour, you throw them both away.
Otherwise, you throw away the black ball and return the white ball to the bag.
You keep repeating this process. If at some stage there is exactly one ball left in the bag, which of the following is true?
A) The ball in the bag is definitely white.
B) The ball in the bag is definitely black.
C)Both colours are possible, but the probability of it being white is greater.
D) Both colours are possible, but the probability of it being black is greater.
the sample space is

Picking both black balls .
Picking both white balls .
Picking a black and a white ball

So probablity that a black ball will be thrown is 2/3 becoz in two scenarios it will be thrown , while a white ball will be thrown in only one case so accordingly option C goes , please rectify my approach .
Answer: Hint: the parity of white balls can never change.

EDIT: Further explanation:
The reason for this is this: The only case in which you throw out white balls is when you pick two of the same kind. And then you throw out two of them, so the parity stays the same.
How this can be used to solve the problem: The problem is about an event when there is just one ball left. You start with even number of white balls. So can the last (one) ball left be white?
Comment: @RadhaGogia This answer is a tremendous hint. You start with $278$ white balls. Can there ever be $277$ whilte balls? $276$? $275$? Investigate what the first few steps of the procedure possibly can be (don't worry about the exact likelihood yet) and what the number of white balls is after each step. Look for a pattern. If you don't see it right away, maybe you will see it after trying more examples. But if you don't see it yet and you don't try you will not see it. When you see the pattern, think about how your observations would extend to smaller numbers of white balls.
Comment: @RadhaGogia Are you puzzled about why this holds, or how it solves the problem? David's comment already should pretty much clarify them but I edited some further explanations also to the answer.
Comment: Sorry , couldn't get it .
Comment: @RadhaGogia, There is 100% probability that one ball remained in the bag will be a black ball.For clarification, read out my answer.
Answer: Let us simulate your question where the total number of balls in a bag are 9 in which 5 are black and 4 are white. The probability of picking white or black ball out of the nine balls will remain the same as in the original problem.The probability of picking black ball in the original question is $\frac{347}{625}=0.5552$, whereas in this simulation it is $\frac59=0.5555$
Now the probability of picking randomly 2 balls out of 9 balls in which both have the same colour is $(0.5555)^2+ (0.4444)^2=0.506072.$...(1)
And the probability of picking randomly 2 balls out of 9 balls in which both balls are of different colours is $2*(0.5555)(0.4444)=0.493817$...(2)
So the probability of (1)is more than (2).So let us assume you pick 2 balls of same colour i-e black and you remove these 2 balls from 9 balls. So now you have total 7 balls in which 4 are white and 3 are black.
Lastly in any scenario, when there are 3 balls left,1 of them will be Black and other 2s are white.if you pick any 2 balls of white colour,ball remained in the bag is black. And if you pick any 2 balls of different colours,one black ball will be thrown out and another white ball will be put inside the bag. So there are 2 white balls in the bag,when you pick them,both balls will be thrown out.So there will be nothing in the bag.So the probability of black ball is 100% when there is only 1 ball remained in the bag.


Explicit instantiation declaration with extern

Question: I am reading 14.7.2 in C++ Standard draft n3485 and it says:

2 The syntax for explicit instantiation is:
  explicit-instantiation:
  externopt template declaration
There are two forms of explicit instantiation: an explicit instantiation definition and an explicit instantiation declaration. An explicit instantiation declaration begins with the extern keyword.

Seeing that a template declaration and definition is always put in a header, I have never seen a declaration with extern on a template.  What exactly does that bolded sentence mean?
Also why would an instantiation care about extern?
Comment: "_Also why would an instantiation care about extern?_" Because that's the syntax used for an explicit instantiation declaration. Why would the compiler ignore valid syntax that changes the meaning of a decaration? Like `extern int i;` it says "this is a declaration, not a definition, there will be a definition somewhere in the program"
Answer: It tells the compiler not to instantiate that template in this TU.
Note that it should be instantiated in one TU (without the extern bit), if you want your code to actually link.


Adding Pallets to Substrate

Question: This is a very basic question, but I am following the "nicks" tutorial from the Substrate network, and it's not very clear how - after I have added the pallet - I install or "pull in" these dependencies so I can inspect the code. I was expecting something like node_modules folder where everything is put once you run npm i, but that is a different environment. I have run cargo build but to no avail. Please advise.
Comment: The cargo stuff goes into `~/.cargo`, not the current directory.
Comment: @forgetso The tutorial shows that crates appear under the pallets/ directory of the project.
Comment: I can't find that part of the tutorial but you can view the source of all the pallets [on github](https://github.com/paritytech/substrate/tree/master/frame).
Comment: @forgetso Thank you, but that is replying in a different question altogether. I am saying that when I add a crate as a dependency I don't see the code being downloaded and added to the project.
Answer: When you add dependency in Cargo.toml, by default, the actual dependency will download and store on global Cargo registry $HOME/.cargo/ and specify the version in Cargo.lock inside project directory, not the actual dependency.
For a tutorial on Substrate, after adding Nick's pallet and running cargo build, you can check the code of downloaded pallet_nick in $HOME/.cargo/. The easiest way is to download rust_analyzer plugin to your VSCode and CRTL + Click to the dependency name inside Cargo.toml, it will take you to the library.
Comment: And what is in the "pallets" folder then?

Adding Pallets to Substrate


Random Range orders

Question: I want to make a special random.
private Randomizer getNumberRnd;
getNumberRnd = new Randomizer(1, 10, true);
    firstNumber = getNumberRnd.getRandom();

I want to get 6 random numbers to be close.
For example: 7,6,5,8,9,5
As I see from 1 to 10, so how do I get these numbers random and close?
Comment: No, it wasn't clear. If the goal is that, pick a single number from this interval, let this be "a"; then, pick 5 other numbers from a-2 to a+2, or whatever will be the offset, using a new rand.
Comment: You want the numbers to be close, but from a "large" interval. I don't get your question, exactly.
Comment: Yes, I think it's quite clearly explained. I want 6 numbers from this interval but close
Answer: Let's say you want your number to not diverge from more than +- 2 and be close to 12. You could simply do
int randomOffset = Random.Range(-2, 3); // For ints, the upper value is exclusive
int value = 12 + randomOffset;

This will give you a value in the range

10, 11, 12, 13, 14

Now if you don't want it to be around twelve, but around a random value and keep them between 1 and 10
int randomPivot = Random.Range(3, 9);
int randomOffset = Random.Range(-2, 3); // For ints, the upper value is exclusive
int value = randomPivot + randomOffset;

And now, you want 6 values around the pivot, so we do
int[] randomValues = new int[6];
int randomPivot = Random.Range(3, 9);
for(int i = 0; i<6; ++i)
{
    int randomOffset = Random.Range(-2, 3);
    randomValues[i] = randomPivot + randomOffset;
}

Now random values contains 6 values that are random, but close to each other and are all between 1 and 10
Comment: Woops, I edited the answer. it was a type in the for loop.
Comment: randomValues[i] = randomPivot + randomOffset;
here's a mistake

Random Range orders


Which of the following sets are dense in $C[0,1]$

Question: Which of the following sets are dense in $C[0,1]$ with respect to sup-norm topology?
$1$. {$f$$\in$ $C[0,1]$ : $f$ is a polynomial }
$2$. {$f$$\in$ $C[0,1]$ :$f(0)$=$0$}
$3$. {$f$$\in$ $C[0,1]$ :$f(0)$$\neq$$0$}
$4$. {$f$$\in$$C[0,1]$ :$\int_{0}^{1}f(x)dx$$=$5}
I am thinking to apply Stone-weierstrass theorem but I don't know how to use it properly. Please help!
Comment: Stone-Weierstraß is a good idea for the first one. What does it exactly state? Any thoughts on 2.-4.?
Comment: @mathmax: From Stone weierstass says polynomials are dense in $C[0,1]$. I get the 1st one as my correct answer, as you said. But I'm having no hints for the rest. cann't it be done using Stone Weierstrass?
Answer: Answer: $1,\, 3$
Proof:

Stone-Weierstrass theorem states explicitly  the dense property of the polynomials in $(C[0,1],\parallel\cdot\parallel_\infty)$
It is not dense. Because it is a proper closed subset of  $(C[0,1],\parallel\cdot\parallel_\infty)$ as it is the inverse image of $\{0\}$ under the continuous map $f\mapsto f(0)$.
It is dense. It is obvious that every element of that set is a limit point of that set. So now, let $f(0)=0$. Then the sequence of functions $f_n(x)=f(x)+\frac{1}{n}$ converges to $f$ with respect to supnorm and $f_n(0)=\frac{1}{n}\neq 0$.
It is not dense. Because it is   the inverse of the set $\{5\}$ under the continuous map $f\mapsto \int_0^1 f(x)dx$. And hence it is a proper closed set.
Comment: For #2 one can also observe that any sufficiently small neighborhood of the constant function $f(x) = 42$ has empty intersection with the set under consideration. In fact, the 2nd example not only fails to be dense, but there are balls having arbitrarily large diameter that have empty intersection with the set.
Comment: @chellapillai; Can you please elaborate how the maps defined by you in options 2 and 4 are continuous?furthermore are these map open?
Comment: @Ibs Just notice that they are all linear maps. And continuity can be checked in the standard way.
Comment: @chellapilai If I am not wrong then showing boundedness is an easy task and you want me to prove the same,right?
Answer: (1) follows directly from the stone-weirstrass theorem, since $[0,1]$ is a closed interval.
(2) is not dense, show that $f(x)=1$ is not a limit point
(3) Here, the closure of this set is $C[0,1]$, try showing that any $g\in C[0,1]$ with $g(0)=0$ is a limit point.
(4) Not dense, again show that $f(x)=1$ is not a limit point.
Answer: Hint for 2 :
Let, $S=\{f\in C[0,1]:f(0)\not =0\}$.
Then $S=\{f\in C[0,1]:f(0)<0\}\cup \{f\in C[0,1]:f(0)>0\}$.
So, $\overline S=\{f\in C[0,1]:f(0)\le0\}\cup \{f\in C[0,1]:f(0)\ge0\}=C[0,1]$.
So, $S$ is dense in $C[0,1]$.
Again as $S$ is the union of two open sets so it is open subset of $C[0,1]$.
Hence its complement is nowhere dense.
That is, the set $\{f\in C[0,1]:f(0)=0\}$ is nowhere dense.
Similarly option 4 is nowhere dense.
Answer: Hint :

Stone-weierstrass theorem
Think about $\{x,x^2,x^3\cdots\}$
Think about $\{a+x^i : a\in \mathbb{R}\backslash \{0\}; i\in \mathbb{N}\}$
I have no hint for this as of now but i believe this is too small to generate $C[0,1]$
Comment: How to use your 2nd and 3rd hint? what do I need to show? @Praphulla Koushik
Comment: You need to spend some more time... what polynomials do you think are not in $2$??
Comment: The constant polynomials, right?
Comment: Yes... can you get constant function as limit function of elements in $2$??
Comment: and for the (3) rd? This is dense, right?
Comment: If you have accepted the other question you should know what does my hint for third condition says... those are not different...


HttpURLConnection .getInputStream() Crashes on Marshmallow not Oreo

Question: The following code works flawlessly on Android 8. On a tablet running 6 it crashes when getting the getinputstream with a file io error. I've tried for HOURS and HOURS without any luck. PLEASE help. Nothing works. Even trying a volley doesn't help. My Web API works great on a computer and a phone.
@Override
protected String doInBackground(String... args) {
    StringBuilder result = new StringBuilder();

    try {
        URL url = new URL("https://api.github.com/users/dmnugent80/repos");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;

        while ((line = reader.readLine()) != null) {
            result.append(line);
        }
    }
    catch(Exception e) {
        e.printStackTrace();
    }

    return result.toString();
}

LOG CAT HERE

06-24 02:01:21.813 22840-22890/com.marcusengineering.recipedatabase
  I/System.out: [CDS][DNS] getAllByNameImpl netId = 0 06-24 02:01:21.813
  22840-22890/com.marcusengineering.recipedatabase D/libc-netbsd:
  [getaddrinfo]: hostname=recipedatabase.gear.host; servname=(null);
  netid=0; mark=0
      [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0 06-24 02:01:21.817
  22840-22890/com.marcusengineering.recipedatabase D/libc-netbsd:
  [getaddrinfo]: hostname=recipedatabase.gear.host; servname=(null);
  netid=0; mark=0 06-24 02:01:21.818
  22840-22890/com.marcusengineering.recipedatabase D/libc-netbsd:
  [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=1024;
  ai_family=0 06-24 02:01:21.824
  22840-22890/com.marcusengineering.recipedatabase D/libc-netbsd:
  getaddrinfo: recipedatabase.gear.host get result from proxy gai_error
  = 0 06-24 02:01:21.824 22840-22890/com.marcusengineering.recipedatabase I/System.out: [CDS]rx
  timeout:0 06-24 02:01:21.826
  22840-22890/com.marcusengineering.recipedatabase I/System.out:
  [socket][0] connection
  recipedatabase.gear.host/126.96.36.199:80;LocalPort=43028(0)
      [CDS]connect[recipedatabase.gear.host/18.104.22.168:80] 06-24 02:01:21.826 22840-22890/com.marcusengineering.recipedatabase D/Posix:
  [Posix_connect Debug]Process com.marcusengineering.recipedatabase :80
  06-24 02:01:21.919 22840-22890/com.marcusengineering.recipedatabase
  I/System.out: [CDS]port[43028]
      [socket][/192.168.1.163:43028] connected 06-24 02:01:21.920 22840-22890/com.marcusengineering.recipedatabase I/System.out: [CDS]rx
  timeout:0
      [CDS]SO_SND_TIMEOUT:0 06-24 02:01:21.921 22840-22890/com.marcusengineering.recipedatabase I/System.out:
  [OkHttp] sendRequest>>
      [OkHttp] sendRequest<< 06-24 02:01:21.982 22840-22890/com.marcusengineering.recipedatabase W/System.err:
  java.io.FileNotFoundException:
  http://recipedatabase.gear.host/RestServiceImpl.svc/jsonfindtable/SELECT
  UnitID, UnitName, HiddenFlag FROM TblUnits ORDER BY UnitName FOR JSON
  PATH
          at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
          at com.marcusengineering.recipedatabase.MainActivity.getRestFromWebAsString(MainActivity.java:334)
          at com.marcusengineering.recipedatabase.MainActivity$MyAsyncInitialLoad.doInBackground(MainActivity.java:252)
          at com.marcusengineering.recipedatabase.MainActivity$MyAsyncInitialLoad.doInBackground(MainActivity.java:232)
          at android.os.AsyncTask$2.call(AsyncTask.java:295) 06-24 02:01:21.983 22840-22890/com.marcusengineering.recipedatabase
  W/System.err:     at
  java.util.concurrent.FutureTask.run(FutureTask.java:237)
          at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
          at java.lang.Thread.run(Thread.java:818)
Comment: Can you update your question with error log from logcat?
Comment: See updated question. Thanks.
Answer: FINNNNNNNALY FIGURED IT OUT!.
Not sure which ones were 100% needed but here's what I did to help any other poor souls.

Ensure that your web api is fomratted without the extra wrapping added from WCF, i.e. is plain text. (not critical)
Get rid of spaces in your URL. It appears OREO does this for you. Earlier versions must not. The code to do this is: URL url = new URL(query.replace(" ","%20"));
Happy dance

In totality the call should be as follows:
            URL url = new URL(query.replace(" ","%20"));
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        int i = urlConnection.getResponseCode();
        InputStream inputs;
        if (i < HttpURLConnection.HTTP_BAD_REQUEST) {
            inputs = urlConnection.getInputStream();
        } else {
            // Error
            inputs = urlConnection.getErrorStream();
            return "-1";
        }

        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = "";

        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

To set the formatting to raw string in the WCF see the following.
In the *****.cs
[OperationContract]
    [WebGet( UriTemplate = "jsonFindTableBare/{id}")]
    Stream DoWork(string id);

In the svc.cs
public Stream DoWork(String id)
    {

        WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
        String str = "YOUR RESPONSE HERE";
        WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
        return new MemoryStream(Encoding.UTF8.GetBytes(str));
    }

Thanks for all the help, Mangal. Appreciate it.
Answer: You should first check response code to also handle the error input stream.
InputStream inputs;
if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
            inputs = urlConnection.getInputStream();
        } else {
            // Error
            inputs = urlConnection.getErrorStream();
        }

then call
   InputStream in = new BufferedInputStream(urlConnection);

I had also faced some app crashing experience because of handling error stream direclty.
Please do check always, It's a good practice.
Comment: Appreciate the response. I had this. However every call just throws an error and no data is read.
Comment: urlConnection.getErrorStream() returns a null :(
Comment: same code worked for me on both versions here? What marshmellow device you are testing on??Is it virtual or regular device??
Comment: Tab 2. Also fails on an older htc version 5 android. The code works on all devices from a generic site such as: http://resttesttest.com/

However, for my web api which is formatted the exact same it fails ...
Comment: What response code you are getting for your web api.?check about that response code also..
Comment: There is no method like getResponseCode() in URLConnection class.


computing $\mathrm{d}V(\zeta)$

Question: So I'm trying to prove that $
f(z)=\frac{1}{\pi} \int_{\mathbb{D}} \frac{f(\zeta)}{(1-z \bar{\zeta})^2} \mathrm{d} V(\zeta)
$ for $z, \zeta \in \mathbb{D}$ and I have an idea of the proof, but I am stuck in something more basic.
The reference I am looking at says for $\zeta=re^{i\theta}$, we have $\mathrm{d}V(\zeta)=\mathrm{d}x\mathrm{d}y=r\mathrm{d}r\mathrm{d}\theta$. However, when I do the computations, this is what I get:
$$
\begin{align*}
\mathrm{d}V(\zeta)&= \mathrm{d}\zeta \wedge \mathrm{d}\bar{\zeta} \\
&= \mathrm{d} re^{i\theta} \wedge \mathrm{d}re^{-i\theta} \\
&= \mathrm{d} r (e^{i\theta})+(ir e^{i\theta}) \mathrm{d} \theta\wedge \mathrm{d} r (e^{-i\theta})+(-ir e^{-i\theta}) \mathrm{d} \theta \\
&= -2ir \mathrm{d}r\wedge \mathrm{d}\theta
\end{align*}
$$
and in somehow the same way,
$$
\begin{align*}
\mathrm{d}V(\zeta) &= \mathrm{d}\zeta \wedge \mathrm{d}\bar{\zeta} \\
&= (\mathrm{d} x+ i\mathrm{d} y) \wedge (\mathrm{d}x -i \mathrm{d} y) \\
&= (\mathrm{d} x \wedge \mathrm{d} x)-i(\mathrm{d} x \wedge \mathrm{d} y)+i (\mathrm{d} y \wedge \mathrm{d} x) + (\mathrm{d} y \wedge \mathrm{d}y) \\
&= -2i \mathrm{d}x \wedge \mathrm{d}y
\end{align*}
$$
I'd appreciate it if someone can let me know where am I wrong. Thanks.
Answer: The definition of $\textrm{d}V$ is $\textrm{d}x \wedge \textrm{d}y$ as the book says.  Writing $\textrm{d}V(\zeta)$ is just to indicate that you are integrating in the $\zeta$ plane instead of the $z$ plane.
Your mistake is thinking that $\textrm{d}V(\zeta) = \textrm{d}\zeta \wedge \textrm{d} \bar{\zeta}$.
Your  computation of $\textrm{d}\zeta \wedge \textrm{d} \bar{\zeta} = -2i \textrm{d}V(\zeta)$ is accurate.

computing $\mathrm{d}V(\zeta)$


What aspects of a GPO is stored in AD

Question: I'd like to know what components of a GPO are stored in Active Directory.  Is it all on the file system?
Answer: Nothing in the GPO is stored in the AD database, really. It's all in the SYSVOL (IIRC) on the domain controllers. AD has a GUID pointer to the location on the filesystem, and of course who it applies to, any permissions on it, etc.
Comment: The GPC is stored in AD and the GPT is stored in SYSVOL, which I think is what you're saying, but one without the other would be of no use.
Comment: Yup, you got the terminology correct.
Comment: You got what I was looking for... where is the GUID pointer within AD?
Comment: CN=Policies,CN=System,DC=something,DC=something,DC=something
Comment: @Maker - you can find that sort of thing by doing a little bit of google-searching, a little bit of studying/certification for AD, or by just playing around with tools like AD Explorer from SysInternals. I'm not telling you not to ask questions here, and your main question was a good one - but once you got the details on the GPC and GPT from @joeqwerty, you definitely should have had enough info to go find the easy things on your own.

What aspects of a GPO is stored in AD


Convert Base64 string to a pdf in Angular 2

Question: I have a webapi that returns a string in base64 and in angular 2 I should turn it into a pdf (and download it from the browser).
How can I do?
Answer: I suppose you get the blob from the back end:
const headers = new HttpHeaders()
  .set('Accept', 'application/pdf');

this.http.get(`${BASE_URL}/pdf`, {observe: 'response', headers, responseType: 'arraybuffer'});

You can do the following :
const blob = new Blob([base64String], {type: 'application/pdf'});

And then download the pdf file :
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob); //For IE browser
    }
    const linkElement = document.createElement('a');
    const url = window.URL.createObjectURL(blob);
    linkElement.setAttribute('href', url);
    linkElement.setAttribute('download', 'file.pdf');
    const clickEvent = new MouseEvent('click', {
      'view': window,
      'bubbles': true,
      'cancelable': false
    });
    linkElement.dispatchEvent(clickEvent);

Comment: He downloads the file, but tells me it's impossible to open because it's damaged...
Comment: Is your base64 content valid ?
Comment: Yes, i have tried in c# application with this code

            var resFin = Convert.FromBase64String(base64);
            File.WriteAllBytes(@"C:\Temp\Stampona.pdf", resFin);
And work...
Comment: I've updated my response, be sure when you retrieve the blob from the back to force the responseType to 'arraybuffer' in Angular