Loading image from remote server in different LAN

Question: My stack is ASP.NET (Nancy) with Razor view engine. But this may concern all technologies I suppose.
I have two LAN networks (let's call them Large network and Small network) and two servers (a.k.a Main server and Image server). Main server can be reached by computers from both networks but Image server is visible only for machines in Small network. I have website served by Main server which shows images from remote (Image) server:

All is fine when computer from Small network is loading the webpage from Main server as it has access to Image server too (the same network). Problem occurs when the computer from Large network loads the webpage. The image is not loading because Image server is in Small network which is not accessible for machines from Large LAN.
Is there any way to force Main server to serve the image directly?
Answer: I don't know why I couldn't find this before posting my question. The simplest approach seems to be proper router configuration. But... changing router configuration is not possible in my situation. Knowing all that I started up my own brain finally ;).
My solution is converting the image to base64 string first with the following C# snippet:
    private string convertToBase64(string imageURL)
    {
        var request = WebRequest.Create(imageURL);

        using (var response = request.GetResponse())
        {
            using (var stream = response.GetResponseStream())
            {
                using (Image image = Image.FromStream(stream))
                {
                    using (MemoryStream m = new MemoryStream())
                    {
                        image.Save(m, image.RawFormat);
                        byte[] imageBytes = m.ToArray();
                        string base64String = Convert.ToBase64String(imageBytes);
                        return string.Format("data:image/png;base64,{0}", base64String);
                    }
                }
            }
        }
    }

It's all happening at the server side so no issues with access to image.
Then I'm passing the string to the View via Model property and displaying the image as follows:

Probably this solution has it's flaws, but it works for me, and I couldn't find anything else that I could use in this case.


Regular expression to extract a group of words

Question: I want to extract the string in Description column for each line in the following table. Since the search sting contains spaces and the columns are delimited by spaces , I am not sure how I can parse the right field in each line.
    Name     PCI Device    Driver  Admin Status  Link Status  Speed  Duplex  MAC Address         MTU  Description
-------  ------------  ------  ------------  -----------  -----  ------  -----------------  ----  ----------------------------------------------------------------
vmnic0   0000:3d:00.0  i40en   Up            Down             0  Half    00:00:00:00:03:14  1500  Intel(R) Ethernet Connection X722 for 10GbE SFP+
vmnic1   0000:3d:00.1  i40en   Up            Down             0  Half    00:00:00:00:03:15  1500  Intel(R) Ethernet Connection X722 for 10GbE SFP+
vmnic10  0000:d9:00.1  ixgben  Up            Down             0  Half    a0:36:9f:d9:b9:11  1500  Intel(R) Ethernet Controller 10G X550
vmnic11  0000:01:00.0  i40en   Up            Down             0  Half    3c:fd:fe:a9:4e:b8  1500  Intel(R) Ethernet Controller XXV710 for 25GbE SFP28
vmnic12  0000:01:00.1  i40en   Up            Up           10000  Full    3c:fd:fe:a9:4e:b9  1500  Intel(R) Ethernet Controller XXV710 for 25GbE SFP28
vmnic2   0000:00:1f.6  ne1000  Up            Down             0  Half    88:88:88:88:87:88  1500  Intel Corporation Ethernet Connection (3) I219-LM
vmnic3   0000:3d:00.2  i40en   Up            Down             0  Half    00:00:00:00:03:16  1500  Intel(R) Ethernet Connection X722 for 10GbE SFP+
vmnic4   0000:3d:00.3  i40en   Up            Down             0  Half    00:00:00:00:03:17  1500  Intel(R) Ethernet Connection X722 for 10GbE SFP+
vmnic5   0000:18:00.0  ixgben  Up            Down             0  Half    90:e2:ba:37:50:a8  1500  Intel Corporation 82599EB 10-Gigabit SFI/SFP+ Network Connection
vmnic6   0000:18:00.1  ixgben  Up            Down             0  Half    90:e2:ba:37:50:a9  1500  Intel Corporation 82599EB 10-Gigabit SFI/SFP+ Network Connection
vmnic7   0000:81:00.0  ixgben  Up            Up           10000  Full    90:e2:ba:1e:b6:24  1500  Intel Corporation 82599EB 10-Gigabit SFI/SFP+ Network Connection
vmnic8   0000:81:00.1  ixgben  Up            Down             0  Half    90:e2:ba:1e:b6:25  1500  Intel Corporation 82599EB 10-Gigabit SFI/SFP+ Network Connection
vmnic9   0000:d9:00.0  ixgben  Up            Up            1000  Full    a0:36:9f:d9:b9:10  1500  Intel(R) Ethernet Controller 10G X550

Answer: It seems your delimiter is "more than one space". The regular expression for that would be \s{2,}.
So for each line here, description  = re.split('\s{2,}', line)[-1]
Answer: Using pandas:
from io import StringIO
import pandas as pd

TESTDATA = StringIO("""
        Name     PCI Device    Driver  Admin Status  Link Status  Speed  Duplex  MAC Address         MTU  Description
-------  ------------  ------  ------------  -----------  -----  ------  -----------------  ----  ----------------------------------------------------------------
vmnic0   0000:3d:00.0  i40en   Up            Down             0  Half    00:00:00:00:03:14  1500  Intel(R) Ethernet Connection X722 for 10GbE SFP+
vmnic1   0000:3d:00.1  i40en   Up            Down             0  Half    00:00:00:00:03:15  1500  Intel(R) Ethernet Connection X722 for 10GbE SFP+
vmnic10  0000:d9:00.1  ixgben  Up            Down             0  Half    a0:36:9f:d9:b9:11  1500  Intel(R) Ethernet Controller 10G X550
vmnic11  0000:01:00.0  i40en   Up            Down             0  Half    3c:fd:fe:a9:4e:b8  1500  Intel(R) Ethernet Controller XXV710 for 25GbE SFP28
vmnic12  0000:01:00.1  i40en   Up            Up           10000  Full    3c:fd:fe:a9:4e:b9  1500  Intel(R) Ethernet Controller XXV710 for 25GbE SFP28
vmnic2   0000:00:1f.6  ne1000  Up            Down             0  Half    88:88:88:88:87:88  1500  Intel Corporation Ethernet Connection (3) I219-LM
vmnic3   0000:3d:00.2  i40en   Up            Down             0  Half    00:00:00:00:03:16  1500  Intel(R) Ethernet Connection X722 for 10GbE SFP+
vmnic4   0000:3d:00.3  i40en   Up            Down             0  Half    00:00:00:00:03:17  1500  Intel(R) Ethernet Connection X722 for 10GbE SFP+
vmnic5   0000:18:00.0  ixgben  Up            Down             0  Half    90:e2:ba:37:50:a8  1500  Intel Corporation 82599EB 10-Gigabit SFI/SFP+ Network Connection
vmnic6   0000:18:00.1  ixgben  Up            Down             0  Half    90:e2:ba:37:50:a9  1500  Intel Corporation 82599EB 10-Gigabit SFI/SFP+ Network Connection
vmnic7   0000:81:00.0  ixgben  Up            Up           10000  Full    90:e2:ba:1e:b6:24  1500  Intel Corporation 82599EB 10-Gigabit SFI/SFP+ Network Connection
vmnic8   0000:81:00.1  ixgben  Up            Down             0  Half    90:e2:ba:1e:b6:25  1500  Intel Corporation 82599EB 10-Gigabit SFI/SFP+ Network Connection
vmnic9   0000:d9:00.0  ixgben  Up            Up            1000  Full    a0:36:9f:d9:b9:10  1500  Intel(R) Ethernet Controller 10G X550
    """)

df = pd.read_csv(TESTDATA, sep="\s{2,}").iloc[1:]
descriptions = [x for x in df['Description']]

And the output:
['Intel(R) Ethernet Connection X722 for 10GbE SFP+',
 'Intel(R) Ethernet Connection X722 for 10GbE SFP+',
 'Intel(R) Ethernet Controller 10G X550',
 'Intel(R) Ethernet Controller XXV710 for 25GbE SFP28',
 'Intel(R) Ethernet Controller XXV710 for 25GbE SFP28',
 'Intel Corporation Ethernet Connection (3) I219-LM',
 'Intel(R) Ethernet Connection X722 for 10GbE SFP+',
 'Intel(R) Ethernet Connection X722 for 10GbE SFP+',
 'Intel Corporation 82599EB 10-Gigabit SFI/SFP+ Network Connection',
 'Intel Corporation 82599EB 10-Gigabit SFI/SFP+ Network Connection',
 'Intel Corporation 82599EB 10-Gigabit SFI/SFP+ Network Connection',
 'Intel Corporation 82599EB 10-Gigabit SFI/SFP+ Network Connection',
 'Intel(R) Ethernet Controller 10G X550']

Answer: I suppose you can get each line in a string.
>>> s = "vmnic0   0000:3d:00.0  i40en   Up            Down             0  Half    00:00:00:00:03:14  1500  Intel(R) Ethernet Connection X722 for 10GbE SFP+"
>>> row = re.split(r"\s{2,}", s)
>>> description = row[-1]

Comment: Could you please explain the pattern that you used in split
Comment: It's catching 2 spaces or more.


Get a value in a numpy array from a index in a variable

Question: I am trying to access a value in a multi dimensional numpy array.
This can be easily done when you know everything, for exemple :
T = numpy.arrange(9).reshape(3, 3)
T[2, 2]
And it returns 8, which is what I want.
Now, Let's assume [2, 2] is stored in index variable.
How can I do to take the value in T with the index stored in index ?
I would like to do
T[index] but it returns the last row twice (pretty logical but not what I want).
Thank you !
Comment: Try `ind=tuple(2,2); x[ind]`
Comment: Thanks, works perfectly !
Answer: Try
ind=tuple(2,2)
x[ind]

x[2,2] is the same as x[(2,2)] which is translated into a method call: x.__getitem__((2,2)).
Some numpy functions build an index as a list or array, then convert it to a tuple for use in the index.
Comment: If you want to access multiple values at once, make sure to use a 2-tuple which consists of two arrays: first for x-values, second for y-values respectively. If you have a list of indices in format `p=[[x0,y0],[x1,y1], ... ]` for the 2d array `D`, just use `indx=tuple(np.transpose(p))` which is `([x0,x1,..],[y0,y1,...])` and access via `D[indx]`.


Multiple reference in single MongoDB schema

Question: I am new in MongoDB. I have the following schema with two references(event and regdetail) to two other tables.
var MessageSchema = new Schema({
    event: { type:Schema.ObjectId, ref:"Event", index: true },
    regdetail:{ type:Schema.ObjectId, ref:"Registrant", index: true },
    status: {type:String, require:true},
    content: { type: String, require: true },
    createTime:{type:Date,require:false,default:Date.now},

},{
    //no auto indexing at the beginning
    autoIndex:false,

    strict:false}
);

I want to know if this is the best way to declare multiple references in mongoose or is there any shorter way?
Any hint is highly appreciated.
Comment: There is something called virtual populate in Mongoose check that out. Thanks
Answer: Yes, You can.
As per your requirements, your message is highly dependent upon event and regdetail. So, you can easily fetch message data along with event and regdetail.
Check below one
var SurveySchema = new Schema({
  title: {
    type: String,
    required: true
  },
  ct: {
    type: Number,
    require: true,
    default: new Date().getTime()
  },
  ut: {
    type: Number,
    require: true,
    default: new Date().getTime()
  },
  claimsList : [{
    type: Schema.Types.ObjectId,
    ref: 'claims'
  }],
  surveyAnalysisType : {
    type: Schema.Types.ObjectId,
    ref: 'surveyAnalysisType',
    required: true
  },
  assignedUserList : [{
    type: Schema.Types.ObjectId,
    ref: 'User'
  }],
  language: {
    type: Schema.Types.ObjectId,
    ref: 'language',
    required: true
  }
});


For a ring $R$, if $ab=ca$ implies $b=c$, show $R$ is commutative

Question: If R be a ring and assume that for all a,b,c belongs to R ab=ca implies b=c, then prove that R is a commutative ring
Comment: Next time, put the tags in the tags section and not in the title, and use a title that is *actually useful.*
Answer: For any $a,b$ in the ring, $aba=a \times ba = ab \times a$ so by the defining property $ab=ba$.


time() function php

Question: Estou paginando algumas compras que tem datas especificas, e quando passo como parametro que uma data deve ser < que date("Y-m-t", time() + 14*24*60*60), que no caso teria que ser 2 semanas, ele me pagina 1 mês. De acordo com o doc do php, 24*60*60 é 1 dia, logo date("Y-m-t", time() + 14*24*60*60) seria 14 dias/ 2 semanas. Alguém entender o porque disso?
Comment: Da data atual vc quer adicionar mais 14 dias?
Comment: isso, preciso pegar a data de hoje mais 14 dias, depois mais 1 mes, depois mais 2 meses..
Comment: As respostas resolvem isso? ou falta algo?
Comment: mais uma pergunta, no strtotime quando quero mais de uma semana, ou mes, eu tenho que colocar no plural? 2 weeks, 2 months ?
Comment: pode ser no singular, tanto faz.
Comment: então é isso. Todos minhas dúvidas foram sanadas. Obrigado à todos.
Comment: :D volte sempre!
Answer: Se quiser utilizar apenas funções, strftime() e strtotime() resolvem também.
echo strftime('%Y-%m-%d', strtotime('+2 weeks'));

Comment: Muito obrigado, funcionou perfeitamente.
Answer: Em vez de usar o date() você pode usar DateTime que possui vários métodos interessantes.
Doc PHP - DateTime
Usando o método add() - Doc DateTime - Add
Exemplo:
$now = new DateTime();

echo $now->format('d/m/Y H:i:s'); // exibe 18/09/2015 10:12:40

echo '
';

$now->add(new DateInterval('P2W'));

echo $now->format('d/m/Y H:i:s'); // exibe 02/10/2015 10:12:40

time() function php


Create an expiration date field that auto expires

Question: We are currently migrating a Drupal 6 site to Drupal 8. We have a view that shows a table of files uploaded through the file depot. One of the columns on the table was an Expiration Date. In Drupal 6 we had a module called Auto Expire to set a date for a node to expire which we used to create a field on the view showing the number of days until the link to the file expired.
We created a Node view with multiple fields as the column headings (Date Created, Expiration Date, Staff Member, File Name). For the expiration field, we used Auto Expire to create an Expiration Date field set to 7 days after the creation date. After the 7 days, the node (file depot page) and it's attachments would get deleted.
How do I recreate this functionality (whether programmatically or otherwise) in Drupal 8, since Auto Expire is not updated for Drupal 8?
I am currently looking into the Scheduler module as there is a version for Drupal 8.
Comment: You can use rules to do this . An track your custom field expiration date
Comment: Really? How????
Comment: "How do I recreate Auto Expire" unfortunately is a too-broad question for Drupal Answers. Please try to get something up-and-running yourself and then ask a specific and narrow question if something's not working as expected.
Answer: You can use Scheduler to unpublish the node (and then optionally use Scheduler's hooks/events to delete the node). However, to get the date set into the Scheduler unpublish_on field, you could use Rules (reacting on 'after creating' event) or use your own custom mymodule_hook_save() to set the date.
We are also in the process of migrating Scheduler's actions and events for Rules, (see https://www.drupal.org/node/2651348) and I think that Rules would then let you delete the node reacting to being unpublished by Scheduler.


Is it allowed to log a already (logged)transformed continuous variable for low skewness?

Question: I wonder if it is allowed to log a variable which is already logged (transformed). When I do this, the skewness of my model goes to 0.05 which is quite good. Let me know!
Thanks in advance :)
Comment: Sure. Everything is 'allowed' as long as you aren't breaking math.  But does it actually make sense in the context of your problem? That's not something we could answer with the info provided.
Comment: Can you edit your question to include the context you gave in a comment?
Comment: Is the already logged variable strictly positive? Why do you consider that a variable having small skewness is "good"?
Comment: Hi Dason, thank you for your reaction! The context is as following: Your client has commissioned you to conduct a survey study on the determinants of "consumer preferences" (Y-variable) for a new health service.
The client wants to know the (potential) indirect effect of consumer "values" (X-variable) on these preferences via the mediator "confidence" in one's own health (M-variable): a * b.
I have 2 continuous variables, V16 (age) and V17 (mood) and they are already transformed, says the assignment. However transforming them again leads to a perfect skewness...
Comment: @Dason, am I still allowed to log here? :)
Comment: You ask about when to take the log of a variable--it doesn't matter whether that variable originally is the log of something else (because *all* real numbers are logarithms of other numbers).  Thus, everything in the thread at https://stats.stackexchange.com/questions/298 applies here.
Answer: Transforming the predictor variables (independent variables) to achieve a particular distribution does not make sense. We don't need particular distributions of the predictors to do regression. When we make a normality assumption, it is about the error term, not the predictors.
There might be cases where theory says that a transformed predictor variable makes more sense. There might be cases where you determine that a transformed variable results in a model with stronger performance.
But transforming the variable just because you want something that isn't skewed? I'll pass.


Does this liminf characterization hold true?

Question: Let $f:\mathbb{R}\to\mathbb{R}$ be a continuous function such that
$$0<a:=\liminf_{|t|\to\infty} tf(t) <\infty.$$
I am interested in writing the above relation by using the definition. On by lecture notes, I have written that it corresponds to say that, fixed $\varepsilon>0$, it is
$$ tf(t)\geq(a-\varepsilon) - c_1 \quad\mbox{ for all } t, $$
where $c_1$ denotes a positive constant. Now, I would like to obtain a similar relation but using the "reverse" inequality, I mean, it is true that
$$ tf(t)\leq (a+\varepsilon) +c_2\quad\mbox{ for all } t $$
holds too?
Thank you in advance!
Comment: What is $\beta$?
Comment: Sorry, there were a mistake. I edited the question, thank you.
Answer: Let $g(t)=\inf \{x f(x): |x|\ge t\}$. This is an increasing function with value in ${\mathbb R}\cup \{-\infty\}$ and we have $\lim_{t\to\infty} g(t) = a$.
The condition that $0<a<+\infty$ is equivalent to the fact that $0<g(t_0)$ for some $t_0$ and $g$ is bounded from above by some constant $A$. This entails the two conditions which characterize the fact that $a \in (0, \infty)$

$\exists m > 0,\exists t_0 \in {\mathbb R}, \forall t, |t|\ge t_0 \Rightarrow t f(t)\ge m$
$\exists A\in{\mathbb R}, \exists t_n,  |t_n|\to \infty, t_n f(t_n)\le A$
Comment: Thank you for the  answer. So, my deduction was wrong? Cuold you write, if possible, the second condition using an epsilon-delta argumrnt?
Comment: The problem is that I don't understand the conditions that you have written above. Try to rewrite them using quantifiers $\exists$ and $\forall$ to see what they really mean.
Comment: I refer to this: https://en.wikipedia.org/wiki/Limit_superior_and_limit_inferior#Properties
Comment: The connection with your formulas is not obvious. You don't need $\epsilon$ s and $\delta$ s to characterize that $0<a<\infty$. You could use $\epsilon$s to say for example that there is a sequence $|t_n|\to\infty$ such that $t_n f(t_n)\to a$. Such things are written in the Wikipedia page, but you don't need them here. It is much more important to understand the argument with the function $g(t)$.
Comment: Fine, thank you again. But it is not possible to write your second relation in a "easier way", I mean not using the sequence $t_n$ but something like your first charsacterization?
Comment: In plain english the condition is that there exist arbitrarily large values of $|t|$ for which $t f(t)\le A$ (but this is not true for *all* large values of $t$). The "arbitrarily large" part is usually rendered by using a sequence which absolute value tends to infinity. You could say that the set $\{t: t f(t)\le A\}$ is not bounded, but I'm not sure it is clearer.


Random points in spherical shell

Question: I have a sphere of radius $R_1$, and a smaller, concentric sphere of radius $R_2$. Let them be centered at the origin $(0,0,0)$. I need to generate random points with uniform density in the volume between the two sphere surfaces.
Here I found a solution for picking random points in a sphere volume, using
$$\frac{R_s U^{1/3}}{\sqrt{X_1^2 + X_2^2 + X_3^2}} (X_1, X_2, X_3)$$
where $X_1,X_2,X_3$ are independent normal random variables with mean 0 and variance 1, and $U$ is uniformly distributed between 0 and 1.
That strategy could be used for my problem as well, combining it with a rejection method:

Generate a random point $(x,y,z)$ within $R_1$, using the abovementioned solution
If $x^2 + y^2 + z^2 \leq R_2^2$, go back to step 1

But this is quite inefficient when the spherical shell is small. I guess it is possible to use a transformation method to generate points between $R_1$ and $R_2$. Can this be done?
Comment: You can use generate a random spherical coordinate $(\rho, \theta, \phi$, $R_2 \leq \rho \leq R_1$, where each of the variables is weighted according to their appearance in the volume form $\rho^2 \sin \phi \, d\rho \, d\theta \, d\phi$.
Comment: @Travis That is the correct idea.
Answer: No need to use accept-reject methods here.
First generate a point on the unit sphere ($r=1$). There are several ways, for example:
$$\theta \sim U[0,2\pi]$$
$$Z_0 \sim U[-1,1]$$
$$X_0=\sqrt{1-Z_0^2} \cos(\theta)$$
$$Y_0=\sqrt{1-Z_0^2} \sin(\theta)$$
Then generate a random radius $R$ in $[r_1,r_2]$ with density proportional to $r^2$ : first generate  $T \sim U[r_1^3,r_2^3]$ and then
$$R= T^{1/3}$$
(so that $f_R(r)=\frac{3}{r_2-r_1}{r^2}$ as desired)
Finally scale: $X=X_0 R$, $Y=Y_0 R$, $Z=Z_0  R$
It's also possible to generate the random point in the unit sphere volume, like in the question body, and then traslate+rescale radially.
Comment: In practice, using current technology, I think it's faster to compute an extra value or two via a Mersenne Twister (due to rejection) than to compute a sine, cosine, or square root. That's one reason to use rejection to generate a normal pseudorandom variable although a non-rejection method is available. Another reason is that on a computer, the alleged "real" uniform variable is really only a discrete variable with a large number of possible outcomes. In practice I would probably still use my answer to this question. Mathematically, however, I think I prefer this answer.
Comment: @Rahul Of course, fixed - thanks
Comment: @DavidK I would be somewhat surprised by that - the trig functions and square root have all been highly optimized too, and the compares and branching necessary to handle the rejection algorithm could easily swamp the trig computations.
Comment: @StevenStadnicki I periodically check the performance of functions in my code and find that trig functions and square root are suprisingly expensive; on the other hand, modern computer architectures do suprisingly well with branches. Looking at both algorithms again, I'm making somewhere between two and three expensive function calls per successful outcome, the solution above makes four; so it really comes down to how badly the "failed" branches affect processing.
Comment: @StevenStadnicki  FWIW, I _did_ vote for this answer, because I really do like it.
Answer: A very good way to generate normal variables is to start with pairs of uniform variables
and apply a rejection method.  If you're considering these normal variables as input
to a rejection method, then, why not start with uniform variables so you only have
to do one level of rejection?
You could generate a random point uniformly distributed within the volume of the
sphere of radius $R_1$ (using three uniform variables and a rejection method)
and then move that point further from the origin
by applying a transformation of the form $r' = f(r)$
($r$ the original distance from the origin, $r'$ the distance after moving the point)
so that the result is uniformly distributed in the spherical shell.
The transformation function $f$ should satisfy
$$\int_r^{R_1} t^2 dt = k \int_{f(r)}^{R_1} t^2 dt$$
where $k = \dfrac{R_1^3}{R_1^3-R_2^3}$
is the ratio of the volume of the entire sphere to the volume of the spherical shell.
I get the relationship
$$(f(r))^3 = \frac 1k r^3 + \frac{k-1}{k} R_1^3
= \frac{R_1^3-R_2^3}{R_1^3} r^3 +  R_2^3 $$
by computing both integrals and rearranging terms.
Note that $f(0) = R_2$ and $f(R_1) = R_1$, as desired.
Another way of writing this is
$$\frac{f(r)}{r} = \left(\frac{R_1^3-R_2^3}{R_1^3} + \frac{R_2^3}{r^3} \right)^{\frac13}.$$
So the procedure is to generate three uniform variables, $U_1$, $U_2$, and $U_3$ (between $-R_1$ and $R_1$),
and compute $r = \sqrt{U_1^2 + U_2^2 + U_3^2}.$
If $r \leq R_1$, the desired point within the spherical shell is
$$(x,y,z) =
 \left(\frac{R_1^3-R_2^3}{R_1^3} + \frac{R_2^3}{r^3} \right)^{\frac13} (U_1, U_2, U_3).$$
If $r > R_1$ you reject the three variables and try again.
You will be able to use $\frac\pi6$ of the triples you generate,
which is worse than the $\frac\pi4$ of pairs of uniform variables
that you would be able to use when generating pairs of normal variables
by the usual rejection method, but a lot better than rejecting everything inside
the shell if the shell is thin.

Random points in spherical shell


Notational confusion on derivative of multivaribale functions

Question: These problems are from the book "Calculus on Manifolds" by M. Spivak. I have some notational confusions on these problems.

$\textbf{Solutions:}$

$\textbf{Q1:}$  I know that, $Df(a)$ denots the derivative of $f$ at the point $a$. For a function $f:\Bbb R\to \Bbb R$, $Df(x)$ is is a function of $x$ and $Df(a)$ is a constant. For $f:\Bbb R^n\to \Bbb R^m$, $Df(x)$ is a matrix of order $m\times n$ with variable entries $x$ (that is $Df(x)$ is a linear transformation from $\Bbb R^n$ to $\Bbb R^m$.). So at a particular point $a$, $Df(a)$ should be a matrix with constant entries. Then what does it mean in Problem(2) that $Df(a)=f$ ?
$\textbf{Q2:}$ In Problem(4), $Ds(a,b)$ denotes the derivative of $s$ at the point $(a,b)$, that should be also a constant. Butwhat does it mean that $Ds(a,b)=s$ ?
$\textbf{Q3:}$ In Problem(5), what is the meaning of the notation $Dp(a,b)(x,y)$ ?
Comment: Given a function $f \colon \Bbb R^n \to \Bbb R^m$, and a point $a \in \Bbb R^n$, the derivative of $f$ at $a$ is a linear transformation $Df(a) \colon \Bbb R^n \to \Bbb R^m$. So, $Df(a)$ is itself a function; and for $x \in \Bbb R^n$, the value of $Df(a)$ at $x$ is written as $Df(a)(x)$, which is an element of $\Bbb R^m$.
Answer: For $F:V\to W$ where $V,W$ are powers of $\Bbb R$, and $p\in
V,$ $DF(p)$ is a linear map from $V$ to $W$ (which may be represented by a matrix, but it is useless here).
In the particular case $V=W=\Bbb R,$ such a linear map is of the form $t\mapsto kt$ and may then be identified to the constant $k.$
In the other particular case where $F:V\to W$ is linear, the linear map $DF(p):V\to W$ is $F$ itself, i.e.$$\forall h\in V\quad DF(p)(h)=F(h).$$
Comment: @Empty No, $Df(x,y)$ is a linear transformation, whereas $f(x,y)$ is an element of $\Bbb R^2$ (or whatever the codomain of $f$ is). The equality $Df(x,y) = f(x,y)$ doesn't make sense.
Comment: Got it. Thanks!
Comment: $DF(p)$ is derivative at the point $p$ ?
Comment: You are probably unable to understand my question! I know derivative is a linear transformation.
Comment: 1/2 Yes, like you wrote in your post after "$\textbf{Q1:}$ I know that". 2/2 I am used to your question. My students often had the same.
Comment: Suppose for a certain function $f:\Bbb R^2 \to \Bbb R^2$, derivative $Df(x,y)=(x+y,x-y)$. Then $Df(2,1)=(3,1)$. Right ?
Comment: Yes. $Df(x,y)=(x+y,x-y)$ is linear transformation.
Comment: Suppose $f$ is a linear map. Then, $Df(x,y)=f(x,y)$. So $Df(1,2)=f(1,2)$ ?
Comment: Empty you are confusing $DF(p)\in L(V,W)$ with $DF:V\to L(V,W).$ Look at the new version of my answer. Btw did *you* downvote it?
Comment: I am extremely sorry, if some of my comments goes rude. Still I am confused. $DF$ is a linear transformation from $V$ to $W$. That is $DF\in L(V,W)$. Then what about the point $p$ ?
Comment: No. I didn't downvote it.
Comment: Yes, at the last line in answer, $DF(p)\in L(V,W)$. How can we read $DF(p)$? Derivative of $F$ at $p\in V$ ? Then what is the meaning of $DF(p)(h)$ ? That was my Q3.
Comment: Yes $DF(p)$ is the derivative of $F$ at the point $p. $ It is a linear map from $V$ to $W$ hence for any vector $h\in V,DF(p)(h)$ is an element of $W.$ That was azif00's comment to your post, 40 min ago.
Comment: Ok. So, derivative of $F$ at a point $p$ is a linear transformation from $V$ to $W$. How can we relate this when $V=W=\Bbb R$ ? Suppose, $F:\Bbb R \to \Bbb R$ defined by $F(x)=x^2$. Then derivative of $F$ at a point $x=1 \in \Bbb R$ is $DF(1)=2$. So how can we say this is a linear transformation from $\Bbb R \to \Bbb R$ ?


Slide com imagem inicial ativa

Question: Olá, estou com um problema em meu slide, ele inicia com a janela do navegador em branco e após os 5 seg começa a aparecer as imagens, e quando ele chega na ultima imagem ele teria que retornar a primeira.
Pesquisei em vários lugares, mas sempre que arrumo uma coisa, estraga outra.
Sei que tenho que jogar uma classe de ativação na primeira imagem, mas como estou informando as imagens por Js, não estou conseguindo.
o HTML:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Slide Show</title>

        <link rel="stylesheet" href="css/slider.css">

                  ❮
                  ❯

o Js:
var i = -1;
var images =
          ['/img/home/banner/_perfiladeira_de_perfis_estruturais_esquadros.jpg',
          '/img/home/banner/_perfiladeira_de_telhas_metalicas_esquadros.jpg',
          '/img/home/banner/_maquina_de_corte_longitudinal_slitter_esquadros.jpg',
          '/img/home/banner/_maquina_de_corte_longitudinal_e_transversal_combinado_esquadros.jpg',
          '/img/home/banner/_linha_de_producao_esquadros.jpg',
          '/img/home/banner/_software_profil_esquadros.jpg'];

function nextImg(){
  document.slide.src = images[(++i)%3];
  if (i>=images.length) return true;
}

function prevImg(){
  document.slide.src = images[(i = i<=0 ? 0 : i-1)%3];
}

window.onload = () => {
  let time = 4000;
  let id_interval = setInterval(() => {
    if(nextImg()) {
      clearInterval(id_interval);
    }
  }, time);
}'

Comment: Porque vc não inicializa antes de entrar no setInterval, a imagem na posição 0: ; `... window.onload = () => {
  let time = 4000; document.slide.src = images[0] ...`
Comment: Deu certo, muito obrigado.
Answer: Além de iniciar a imagem com o caminho da primeira posição da array images, é preciso também aletrar o valor de i e em vez de usar o valor fixo 3 em images[(++i)%3], substituir o 3 pelo tamanho da array, senão só irá até a terceira imagem:
document.slide.src = images[(++i)%images.length];

O correto seria:
var i = -1;
var images =
          ['/img/home/banner/_perfiladeira_de_perfis_estruturais_esquadros.jpg',
          '/img/home/banner/_perfiladeira_de_telhas_metalicas_esquadros.jpg',
          '/img/home/banner/_maquina_de_corte_longitudinal_slitter_esquadros.jpg',
          '/img/home/banner/_maquina_de_corte_longitudinal_e_transversal_combinado_esquadros.jpg',
          '/img/home/banner/_linha_de_producao_esquadros.jpg',
          '/img/home/banner/_software_profil_esquadros.jpg'];

function nextImg(){
  document.slide.src = images[(++i)%images.length];
  if (i>=images.length) return true;
}

function prevImg(){
  document.slide.src = images[(i = i<=0 ? 0 : i-1)%3];
}

window.onload = () => {
   ++i;
   document.slide.src = images[0];
  let time = 4000;
  let id_interval = setInterval(() => {
    if(nextImg()) {
      clearInterval(id_interval);
    }
  }, time);
}

Comment: Obrigado por esse detalhe!

Slide com imagem inicial ativa


text element should not change parent element width

Question:

.root {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

p {
  text-overflow: ellipsis;
  text-wrap: none;
  white-space: nowrap;
}

.p1 {
  background-color: pink;
}

.p2 {
  background-color: yellow;
}

 Some very long text that changes parent element width random text

      <Dropdown/>

 short text

      <Dropdown/>

the problem here is for long text it increases the size of its parent div and the ratio of 1:1 changes , if i use overflow:hidden in the parent div then the dropdown doesnt work properly as this also gets hidden due to overflow:hidden property , how can i fix this so that the ratio is not distorted.
Comment: Not posting that as an answer since I don't have the knowledge to back it up, but as a workaround I've seen that using `grid-template-columns: 50% 50%;` [solves the issue](https://jsfiddle.net/k1n5r6ug/).
Comment: min-width: 0 to the parent element also fix this in addition to the duplicate solution
Answer: Change the columns to have a minimum with of 0

.root {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  width: 80vw;
}

p {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

.p1 {
  background: pink;
}

.p2 {
  background: yellow;
}

 Some very long text that changes parent element width random text

 short text

 short text

 Some very long text that changes parent element width random text


after_destroy callback error "cannot update on new record object"

Question: I have an after_destroy callback like so:
after_destroy :update_max_depth_on_entire_tree

The definition is:
  def update_max_depth_on_entire_tree
    root = self.root
    root.check_or_update_max_tree_depth
    root.descendants.each { |c|
      c.check_or_update_max_tree_depth
    }
  end

  def check_or_update_max_tree_depth
    update_columns(max_tree_depth: last_depth)
  end

  def last_depth
    if child_ids.empty?
      return depth
    else
      return children.map{|c| c.last_depth}.max
    end
  end

Whenever I try to delete an object, I get this error:
ActiveRecord::ActiveRecordError at /posts/detecting-ramsay-is-offered-ceo-job
cannot update on a new record object

This is what the Server log looks like:
Started DELETE "/posts/detecting-ramsay-is-offered-ceo-job" for 127.0.0.1 at 2015-01-05 09:56:24 -0500
Processing by PostsController#destroy as HTML
  Parameters: {"authenticity_token"=>"2xRY+A=", "id"=>"detecting-ramsay-is-offered-ceo-job"}
  User Load (0.5ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 3  ORDER BY "users"."id" ASC LIMIT 1
   (2.9ms)  SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 3]]
   (2.4ms)  SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'editor') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 3]]
  Post Load (0.9ms)  SELECT  "posts".* FROM "posts"  WHERE "posts"."slug" = 'detecting-ramsay-is-offered-ceo-job'  ORDER BY "posts"."id" ASC LIMIT 1
   (0.2ms)  BEGIN
  Post Load (5.2ms)  SELECT "posts".* FROM "posts"  WHERE (("posts"."ancestry" ILIKE '69/%' OR "posts"."ancestry" = '69'))
  Role Load (0.6ms)  SELECT "roles".* FROM "roles"  WHERE "roles"."resource_id" = $1 AND "roles"."resource_type" = $2  [["resource_id", 69], ["resource_type", "Post"]]
  FriendlyId::Slug Load (2.9ms)  SELECT "friendly_id_slugs".* FROM "friendly_id_slugs"  WHERE "friendly_id_slugs"."sluggable_id" = $1 AND "friendly_id_slugs"."sluggable_type" = $2  ORDER BY "friendly_id_slugs".id DESC  [["sluggable_id", 69], ["sluggable_type", "Post"]]
  SQL (1.5ms)  DELETE FROM "friendly_id_slugs" WHERE "friendly_id_slugs"."id" = $1  [["id", 47]]
  SQL (1.2ms)  DELETE FROM "posts" WHERE "posts"."id" = $1  [["id", 69]]
  Post Load (0.4ms)  SELECT "posts"."id" FROM "posts"  WHERE "posts"."ancestry" = '69'
   (0.2ms)  ROLLBACK
Completed 500 Internal Server Error in 281ms

ActiveRecord::ActiveRecordError - cannot update on a new record object:
  activerecord (4.1.6) lib/active_record/persistence.rb:272:in `update_columns'
   () /app/models/post.rb:122:in `check_or_update_max_tree_depth'
   () /app/models/post.rb:130:in `update_max_depth_on_entire_tree'

How do I call this method, or achieve what I want to achieve (i.e. update an attribute on all the nodes on the tree, when 1 node has been deleted) without getting this error?
Edit 1
This is what my routes look like:
mark_as_published_post_path PUT /posts/:id/mark_as_published(.:format)  posts#mark_as_published
mark_as_unpublished_post_path   PUT /posts/:id/mark_as_unpublished(.:format)    posts#mark_as_unpublished
posts_path  GET /posts(.:format)    posts#index
POST    /posts(.:format)    posts#create
new_post_path   GET /posts/new(.:format)    posts#new
edit_post_path  GET /posts/:id/edit(.:format)   posts#edit
post_path   GET /posts/:id(.:format)    posts#show
PATCH   /posts/:id(.:format)    posts#update
PUT /posts/:id(.:format)    posts#update
DELETE  /posts/:id(.:format)    posts#destroy
status_path GET /:status(.:format)  posts#status {:status=>/confirmed|unconfirmed|corroborated/}
GET /posts/:id(.:format)    redirect(301, /%{id})
GET /:friendly_id(.:format) posts#show
GET /posts/:friendly_id(.:format)   posts#show
GET /rbt/:name(.:format)    redirect(301)
GET /:name(.:format)    posts#show
root_path   GET /   posts#index

And this is what my PostController#Destroy looks like:
  def destroy
    @post = Post.find(params[:id])
    @post.destroy
    respond_to do |format|
      format.html { redirect_to posts_url, notice: 'Report was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

Edit 2
I believe the issue is with this portion of code:
  def check_or_update_max_tree_depth
    update_columns(max_tree_depth: last_depth)
  end

What the error seems to be saying is that somewhere along the chain it encounters a new record, and it can't execute update_columns(max_tree_depth: last_depth) on an object that is a new record.
How do I get around this?
Comment: Shouldn't you call `before destroy`? Since you still use the object
Comment: So what I am trying to do is, I have a tree and I want to store the maximum depth of the tree in every node. If a node from within the tree, representing 1 level of depth, gets deleted, then the entire tree needs to be updated. i.e. if there are 6 levels and 1 level gets deleted, all other nodes on the tree need to know that the `max_tree_depth` is now 5 and not 6. I couldn't achieve that with a `before_destroy` because the node (and level) still exists.
Comment: I assume the error is generated since the object is already gone. So my suggestion would be to use before destroy and count - 1, because the object will soon be deleted... Only as a comment as I'm sure there are better and cleaner solutions...
Comment: That's the thing, it isn't gone. The delete action doesn't complete - you can tell by the `(0.2ms)  ROLLBACK` in the logs.
Comment: Ah ok, then I misunderstood
Comment: could you post your routes? and also output the log of the `root` object
Comment: Think you can check if `root` is in database before call `root.check_or_update_max_tree_depth` like `Root.where(id: root.id).present?`
Comment: You know what is happening, `root.descendants` is returning a blank collection - I think that could be it.
Comment: Nope `root.descendants` being empty is not the issue. I updated the question with another edit that spells out my most recent analysis of what is causing the issue.
Answer: This question has become a bit large to grasp, but I'll give it a shot. . .
Your latest update suggests that your problem lies in the fact that update_columns doesn't work on new records.  Why not use update_attributes` instead?
Change:
def check_or_update_max_tree_depth
  update_columns(max_tree_depth: last_depth)
end

to:
def check_or_update_max_tree_depth
  update_attributes(max_tree_depth: last_depth)
end

I found a discussion related to the issue of update_columns not working on new records from back in 2012 that may contain some information that could help you restructure parts of your app that are giving you trouble: https://github.com/rails/rails/issues/7226
Update:
You already answered this, but just noting here for completionist's sake. . .
An alternative solution is to simply add a conditional to your update_columns method that checks if the object is a new_record? or not:
if new_record?
  return
else
  update_column(:max_tree_depth, last_depth)
end

Comment: This is so close, but the problem is that `update_attributes` executes the callback (particularly the `after_save`) which sends it into an infinite loop. That's why I have to use something that updates the attribute, but doesn't execute the callbacks associated with the model.
Comment: Hmm, as I thought I will need to try to get a better grasp of the largeish subject matter of the question.  I'll try to do so within the next day.  Hopefully someone beats me to it, but I'll try to get back here if I'm needed.
Comment: I think I got it. I am going to post my answer. Thanks for trying though.
Answer: I eventually figured it out by doing a few things. Wrapping my update_column(max_tree_depth: last_depth) inside a new_record? check like so:
  def check_or_update_max_tree_depth
    if new_record?
      return
    else
      update_column(:max_tree_depth, last_depth)
    end
  end

That got around that error.
And another error I was having was that whenever my callback encountered a record that was the root record, because of the fact that I am using the :adopt orphan strategy in ancestry to determine what to do with deleted posts, it was creating a new record from the post.children and assigning them root and throwing everything into wack.
So I just modified my code like so:
  def update_max_depth_on_entire_tree
    if max_tree_depth <= 0
      return
    else
      root = self.root
      root.check_or_update_max_tree_depth
      root.descendants.each { |c|
        c.check_or_update_max_tree_depth
      }
    end
  end

And that seems to have done it.


How to convert Bitmap to HBITMAP with alpha via Bitmap::GetHBITMAP?

Question: I need to draw PNG images with transparency. I use GDI, GDI+, and WinApi.
To load and draw images, I always used GDI+, but now I'm using more "native" GDI algorithms (StretchBlt, etc).
The problem is that GDI can't load PNG. I searched the internet and found 2 ways:

loading via GDI+
using WIC.

WIC seems to be too difficult (but what did I expect?), so I choose the first one.
It's easy to load a PNG image using GDI+, just create a Bitmap object passing the file path to the constructor, then call the  getHBITMAP() method to receive an HBITMAP handle, and that's all.
The problem is that the HBITMAP produced by Bitmap loses transparency.
I searched how to fix it. There are different ways - like passing Color::Black as first argument, etc. But it doesn't work.
So, how can I Ioad a PNG image and convert it to HBITMAP with transparency?
I don't use DrawImage method, because it's slow, GDI is faster
I pinned the code:
I understood my mistake: I have to blit hdc_mem to hdcc firstly, and then blit the image. I've did it, but i have a new problem¬_¬
I made a class to manage uploaded images, here the code:
class Imagee
{
HDC hdc; HBITMAP bm;
Imagee(HDC hdc, HBITMAP bm, another args)
{
this->hdc=CreateCompatibleDC(hdc);
this->bm=bm;
SelectObject(this->hdc,this->bm);
}
void draw(int hdcc, int x,int y, int cx, int cy)
{
**StretchBlt(this->hdc,0,0,cx,cy,hdcc,x,y,cx,cy,SRCCOPY); //I'VE ADDED THIS
SelectObject(this->hdc,this->bm); //AND THIS **

StretchBlt(this->hdcc,x,y,cx,cy,hdc,0,0,cx,cy,SRCCOPY);
};
};
Imagee *image;

void render()
{
for(;;)
{
//some draws

//Loading a bitmap via Gdi+, calling a GetHBITMAP function, HBITMAP variable named hbm

if(image==0)
image=new Imagee(hdc_mem, hbm, x, y etc..);

image->draw(hdc_mem, x, y etc..);

StretchBlt(hdc_main,0,0,1920,1080,hdc_mem,0,0,1920,1080,SRCCOPY);
}

I have a black screen. It seems I can't call     SelectObject again, yes?
Comment: Why do you need to resort to GDI for drawing? You can create a `Graphics` object for an `HDC` and then pass the `Bitmap` to `Graphics::DrawImage()`. See [Loading and Displaying Bitmaps](https://msdn.microsoft.com/en-us/library/ms533830.aspx) in the GDI+ documentation. If you have to resort to GDI, see [How would I load a PNG image using Win32/GDI (no GDI+ if possible)?](https://stackoverflow.com/questions/4567875/).
Comment: `SRCCOPY` doesn't perform alpha blending. A simple block transfer (which `SRCCOPY` does) is a *lot* faster than alpha blending. Given the code, it's unclear, what you really need. The code (like its formatting) is severely broken. Get a copy of Petzold's [Programming Windows®](https://www.amazon.com/dp/157231995X).
Comment: GDI+ will draw the png with transparency. You haven't shown what problems you are having. GDI functions don't understand alpha, but you can use `GetHBITMAP(Gdiplus::Color::Transparent, &hBitmap)` for some special cases.
Comment: @Remy Lebeau Gdi draws image faster than DrawImage method
Comment: @Barmak Shemirani I've tried Color::Transparent too, it didn't work(I mean there wasn't transparency)
Comment: Alpha transparency is inherently slow, irrespective of the rendering API used, because it has to read memory. Since we cannot see the code you used it stands to reason that you are comparing a simple block transfer operation to an alpha blending operation.
Comment: @IInspectable, I've pinned the code
Comment: I've used the `CImage` class for similar things. May be my post https://stackoverflow.com/a/43183800/383779 can give some guidance?
Comment: **The Solve_______________________________** https://ru.stackoverflow.com/questions/743530/%d0%9a%d0%b0%d0%ba-%d0%ba%d0%be%d0%bd%d0%b2%d0%b5%d1%80%d1%82%d0%b8%d1%80%d0%be%d0%b2%d0%b0%d1%82%d1%8c-bitmap-%d0%b2-hbitmap-%d0%b1%d0%b5%d0%b7-%d0%bf%d0%be%d1%82%d0%b5%d1%80%d0%b8-%d0%bf%d1%80%d0%be%d0%b7%d1%80%d0%b0%d1%87%d0%bd%d0%be%d1%81%d1%82%d0%b8?noredirect=1#comment1141028_743530
Comment: We don't put "solved" in the title.  If you have it solved, post the solution as an answer.
Answer: From: https://ru.stackoverflow.com/questions/743530
class Imagee
{
   HDC hdc; HBITMAP bm;

   Imagee(HDC hdc, HBITMAP bm, another args)
   {
      this->hdc=CreateCompatibleDC(hdc);
      this->bm=bm;
      SelectObject(this->hdc,this->bm);
   }

   void draw(int hdcc, int x,int y, int cx, int cy)
   {
      BITMAP btm;
      GetObject(bm,sizeof(BITMAP),&btm);

      BLENDFUNCTION bf;
      //initialize bf
      AlphaBlend(hdcc,x,y,cx,cy,his->hdcc,0,0,btm.bmWidth,btm.bmHeight,bf);
   };
};

Usage
Imagee *image;

void render()
{
   for(;;)
   {
      //here I am downloading via gdi+ bitmap, converting it to hbitmap, writing it to the variable HBITMAP hbm

      if(image==0)
         image = new Image(hdc_mem, hbm, x, y и т.д.);

      image->draw(hdc_mem, x, y и т.д.);

      StretchBlt(hdc_main,0,0,1920,1080,hdc_mem,0,0,1920,1080,SRCCOPY);
      //hdc_main главный дс, hdc_mem буфер
   }
}


Prove using mathematical induction pt 2

Question: Assumed that i asked a question like 30 min ago thinking i got the hang of this, seems not.
So $$1^2+4^2+7^2+\dots+(3n-2)^2=\frac12n(6n^2-3n-1) \text{ for all } n\in\mathbb N$$
This time it seems way harder with the squares.
so i did the steps and got stuck on the 3rd step(Again).
Step 1: prove LHS = RHS which it does for n=1
Step 2: Assume $n=k$ is true $$1^2+4^2+7^2+\dots+(3k-2)^2=\frac12k(6k^2-3k-1)$$
Step 3: would $n = k+1$? And would $n = k+1$ work for all equations?could someone help me with the last step, would be appreciated thanks
EDIT: Cheers for the help, i know where i went wrong!
Comment: What have you tried so far for step3? Also just so you know, you can get nicely formatted fractions using `\frac{}{}`.
Comment: The way you phrased step 3 makes me think your question might be a bit deeper than this. (For example, I'm not sure what "$n = k + 1$ work for all equations" means) You want to prove $P(n)$ is true for all $n$. In steps $2$ and $3$, what you want to do is show that, if $P(k)$ is true for _some_ $k$, then $P(k+1)$ is also true. So, the proof part goes like "assume that $P(k)$ is true. do some algebra to it that shows that $P(k+1)$ is true".
Answer: Well... $(3 - 2)^2 = 1 = \frac{6-3-1}{2}$ so it is true for $n=1$. Now, suppose it's true for $n=k$. Then, $1^2+4^2+\dots+(3k-2)^2+(3k+1)^2 = \frac{k\cdot(6k^2-3k-1)}{2} + (3k+1)^2 =\cdots$
Answer: Hypothesis:
$$
1^2+4^2+7^2+\dots+(3n-2)^2=\frac{1}{2}n(6n^2-3n-1)
$$
Thesis:
$$
1^2+4^2+7^2+\dots+(3n-2)^2+(3(n+1)-2)^2=\frac{1}{2}(n+1)(6(n+1)^2-3(n+1)-1)
$$
By the induction hypothesis
$$
1^2+4^2+7^2+\dots+(3n-2)^2+(3(n+1)-2)^2=
\frac{1}{2}n(6n^2-3n-1)+(3(n+1)-2)^2
$$
Write this as a polynomial in $n$; write
$$
\frac{1}{2}(n+1)(6(n+1)^2-3(n+1)-1)
$$
as a polynomial in $n$.
Verify that the expressions are the same. End.
Comment: What happens to the (3(n+1)−2)^2 cause i got the exact same answer but confused on that appearing
Comment: @Unknownstarz Are you able to write $(3(n+1)-2)^2=(3n+1)^2=9n^2+6n+1$? I believe so.
Answer: $$1^2+4^2+7^2+\dots+(3n-2)^2=\frac{1}{2}n(6n^2-3n-1), \forall n\in N$$
$$1^2+4^2+7^2+\dots+(3n-2)^2+(3n+1)^2=\frac{1}{2}n(6n^2-3n-1))+(3n+1)^2 $$
$$=\frac{1}{2}(6n^3-3n^2-n+2(3n+1)^2)=\frac{1}{2}(6n^3+15n^2+11n+2))= $$
$$\frac{1}{2}(6n^3+12n^2+6n+3n^2+5n+2)=$$
$$\frac{1}{2}(6n(n^2+2n+1)+3n^2+3n+2n+2)=$$
$$\frac{1}{2}(6n(n+1)^2+3n(n+1)+2(n+1))=$$
$$\frac{1}{2}(n+1)(6n(n+1)+3n+2)=\frac{1}{2}(n+1)(6n^2+9n+2)=$$
$$=\frac{1}{2}(n+1)(6n^2+12n+6-3n-3-1)=$$
$$=\frac{1}{2}(n+1)(6(n+1)^2-3(n+1)-1)$$

Prove using mathematical induction pt 2


Java Android Como montar um banco de dados randômico?

Question: Na aplicação para Android, usando Java, recebo uma string em Json parecida com essa:
String teste = "{\n" + "  \"nometabela\":{\n" + "    \"id\":\"f83d6101cc\",\n" + "    \"coluna1\":\"codigo\",\n" + "    \"coluna2\":\"descricao\",\"coluna3\":\"quantidade\"\n" + "  }
Com esses dados, preciso criar o banco usando SQLite. Por exemplo, o dado "nometabela"dentro da string Json vai ter que ser o nome da tabela, o "id" será "f83d6101cc", a o nome da primeiro coluna será "codigo", a segunda "descricao" e a terceira "quantidade".
Com os dados fixos, consegui criar o banco.
Porém, os dados não serão sempre assim. Eu nunca vou saber como será esse arquivo Json. O banco criado terá que ser baseado nele, então poderão haver mais colunas, ou menos colunas, etc.
Como faço pra ler essa String Json e criar um banco de acordo com os valores passados por ela? Obrigado.
Answer: Você pode fazer seu código reconhecer que cada " : " passado pelo Json significa uma nova coluna. E o que estiver a esquerda desses pontos significa o nome da tabela, e a direita seu conteudo.


Can you always bound the derivative of a Sobolev norm by a higher Sobolev norm in $\mathbb R$ and $\mathbb R^n$?

Question: Background: While reading a paper written by a mathematician, I noticed that they frequently "bounded the derivative of a function" by a Sobolev norm of one higher derivative. This was done when working against a subset of $\mathbb R$. Does this essentially fall out of the definition of the one-dimensional Sobolev norms? Does a similar result hold in $\mathbb R^n$?
Claim: Given any positive integer $s$ and $u\in H^s(\mathbb R)$, we have
$$
\|\partial_x u\|_{H^s(\mathbb R)} \le \|u\|_{H^{s+1}(\mathbb R)}.
$$
Proof: By the definition of the one-dimensional Sobolev norm,
$$
\|u\|_{H^s(\mathbb R)}^2 = \sum_{j=0}^s \|\partial_x^j u\|_{L^2(\mathbb R)}^2.
$$
Upon setting $\ell = j+1$, we discover
\begin{align*}
\|\partial_x u\|_{H^s(\mathbb R)}^2 &=
\sum_{j=0}^s \|\partial_x^{j+1} u\|_{L^2(\mathbb R)}^2 \\&=
\sum_{\ell=1}^{s+1}\|\partial_x^{\ell} u\|_{L^2(\mathbb R)}^2 \\&\le \sum_{j=0}^{s+1} \|\partial_x^{j} u\|_{L^2(\mathbb R)}^2 \\&=
\| u\|_{H^{s+1}(\mathbb R)}^2.
\end{align*}
I would "assume" that something like this would be true for subsets of $\mathbb R^n$.
Claim 2: Given any positive integer $s$, multi-index $\beta$ where $|\beta|\leq s$, and $u\in H^s(\mathbb R^n)$, we have
$$
\|D^{\beta} u\|_{H^s(\mathbb R^n)} \le \|u\|_{H^{s+?}(\mathbb R^n)}.
$$
Proof 2: For every multi-index $\alpha$ where $|\alpha|\leq s$, we have by the definition of the multi-dimensional Sobolev norms,
$$
\| u \|_{H^s(\mathbb R^n)}^2 = \sum_{|\alpha | \leq s} \left \| D^{\alpha}u \right \|_{L^2(\mathbb R^n)}^2
$$
Upon setting $\gamma = \alpha+\beta$, we discover
\begin{align*}
\|D^{\beta} u\|_{H^s(\mathbb R^n)}^2 &=
\sum_{|\alpha | \leq s} \left \| D^{\alpha}D^{\beta} u \right \|_{L^2(\mathbb R^n)}^2 \\&=
\sum_{|\gamma -\beta | \leq s} \left \| D^{\gamma} u \right \|_{L^2(\mathbb R^n)}^2 \\&\leq
\sum_{|\gamma| \leq s} \left \| D^{\gamma} u \right \|_{L^2(\mathbb R^n)}^2 \\&= \|u\|_{H^{s+\beta}(\mathbb R^n)}.
\end{align*}
I don't think what I wrote in claim 2 is correct. To me, both of these results look like variations of the Poincaré inequality. Is there a theorem from Sobolev space theory which gives these results?
Comment: I don't see a problem with what you wrote and poincare is the reverse inequality. I don't know if it is a named result, the proof is exactly as you wrote. Oh, I guess you should have $s+|\beta|$ for the exponent. And ok, you didn't work the indices quite right. But these are details that aren't so important
Comment: Yes, it should be $s+|\beta|$ in the final equality. I'm not sure what is wrong with the indices other than I should have been more careful with the way I wrote $\alpha$ and $\beta$ in relation to $s.$
Comment: Yes, that's precisely what I meant. Otherwise, why is it that you "don't think what [you] wrote in claim 2 is correct"? what are you unsure about?
Comment: I don't think anything else is wrong outside of that (at least, this is the standard technique I learned to handle multi-indices for PDEs). I wasn't initially confident in my analysis because I didn't know that the exponent should be $s+ |\beta|$. Other than that, I cannot see any other mistakes.
Comment: I'd like to point out that, if you're working with non-integer $s$ (I only bring this case up because it's very frequent in the literature nowadays, so maybe this is the case for the paper you're reading), it does need a proof and it depends on which definition of "fractional" Sobolev space is being used.
Answer: I copy what you wrote to number the lines- \begin{align*}
\|D^{\beta} u\|_{H^s(\mathbb R^n)}^2 &=
\sum_{|\alpha | \leq s} \left \| D^{\alpha}D^{\beta} u \right \|_{L^2(\mathbb R^n)}^2 \tag1\\&=
\sum_{|\gamma -\beta | \leq s} \left \| D^{\gamma} u \right \|_{L^2(\mathbb R^n)}^2\tag2 \\&\leq \tag3
\sum_{|\gamma| \leq s} \left \| D^{\gamma} u \right \|_{L^2(\mathbb R^n)}^2 \\&= \|u\|_{H^{s+\beta}(\mathbb R^n)}. \tag4
\end{align*}
I'm not a fan of how  (2) is written, because the fact that $\gamma-\beta\ge 0$ (by which I mean a component-wise inequality) is hidden in the definition of a multi-index. (2) to (3) is wrong, consider the 1D case with $\beta=100$ and $s=1$. Then $|\gamma-100|\le 1$ and $|\gamma|\le 1$ describe disjoint sets of indices $\gamma$. Furthermore, as there is no mention of $\beta$ in (3), there is no way you can get that (3) is equal to (4), which does involve $\beta$.
I would have not bothered to write a line (2), and simply claim
\begin{align*}
\|D^{\beta} u\|_{H^s(\mathbb R^n)}^2 &=
\sum_{|\alpha | \leq s} \left \| D^{\alpha}D^{\beta} u \right \|_{L^2(\mathbb R^n)}^2 \\&\leq
\sum_{|\gamma| \leq s+|\beta|} \left \| D^{\gamma} u \right \|_{L^2(\mathbb R^n)}^2 \\&= \|u\|^2_{H^{s+|\beta|}(\mathbb R^n)}.
\end{align*}
where the inequality is justified since a derivative of the form
$$ D^\alpha D^\beta, |\alpha|\le s$$
is in particular, a derivative of order at most $s+|\beta|$ (and there are no repeats).
PS as mentioned in the comments Poincaré is the reverse inequality, involving the control of many terms by a few high order terms and is wrong without extra conditions (e.g. mean zero, vanishing on the boundary, etc.)
PPS if a paper writes $H^s$, then there is a good chance they are talking about $s\in\mathbb R$, rather than merely $s\in\mathbb Z_{\ge0}$. Here the space is defined using the Fourier transform (and agrees with the integer case). The proof is similarly easy, this time coming from a polynomial inequality $|\xi^\beta|\le (1+|\xi|^2)^{|\beta|/2}
$.
Comment: Thanks for pointing out the mistakes in my indices in $(2) \to (3)\to (4)$. By letting $\gamma = \alpha+\beta$ in the multi-index, one can deduce

\begin{align*} |\gamma|=|\alpha+\beta|\leq |\alpha|+|\beta|\leq s + |\beta|
\end{align*}

Although, this is the same procedure as the claim. Another thing that could be improved is that both claims should be replaced by something similar to "Let $s \geq 0$ be an integer where $u\in H^s(\mathbb R)$, then $\ldots$" so that the reader knows that I am considering functions $u=u(x,z)$ in the space $H^s(\mathbb R)$. I agree with both of your remarks.


How to approximate $\text{li}(z)$ numerically?

Question: I'm trying to implement a function to calculate $\pi(x)$ via Riemann's formula:
$$
\pi(x) = \operatorname{R}(x^1) - \sum_{\rho}\operatorname{R}(x^{\rho}) - \frac1{\ln x} + \frac1\pi \arctan \frac\pi{\ln x} ,
$$
with $    \operatorname{R}(x) = \sum_{n=1}^{\infty} \frac{ \mu (n)}{n} \operatorname{li}(x^{1/n})$, the sum runs over the non-trivial roots of $\zeta$ and $\text{li}(z)$ being the logarithmic integral.
The problem is that I don't have function to calculate $\text{li}(z)$.
Since I'm not familiar with complex limits I'm not sure if I can write it as a simple sum.
Thanks for your help,
BTW, my result for $x=100,n_{max}=1$ and only one root of $\zeta$ is $30.2748$. Can anyone crosscheck that?
Comment: Can't you use the exponentially converging series by Ramanuajan mentioned in the article to approximate li$(x)$?
Comment: I guess, you only need it for real $x$?
Comment: @Marvis No $z=x^{1/2 + it_k}$...
Comment: Oh ok. I didn't see you wanted $R(x^{\rho})$.
Comment: I should have an idea about this from your stated purpose, but how accurately do you need to compute this?
Comment: @rlgordonma let's say the steps in the approximation should be visible. Is that enough?
Comment: Is [this](http://math.stackexchange.com/questions/8860/efficiently-calculating-the-logarithmic-integral-with-complex-argument) helpful?
Comment: @Argon not sure maybe I'll take this one: $\mathrm{E_1}(z)=\frac{\exp(-z)}{z}\sum_{n=0}^{N-1} \frac{n!}{(-z)^n} $ from [here](http://en.wikipedia.org/wiki/Exponential_integral#Asymptotic_.28divergent.29_series). And then $\text{li}(z)=E_1(\ln(z))$ What do you think?
Comment: @Marvis what would you think about using $
    \mathrm{E_1}(z)=\frac{\exp(-z)}{z}\sum_{n=0}^{N-1} \frac{n!}{(-z)^n} $? And then $\text{li}(z)=E_1(\ln(z))$
Comment: Doesn't $\textrm{li}(x^{1/n})$ diverge as $n\to\infty$?
Comment: @user7530 true: The function $1/\ln(t)$ has a singularity at t = 1...
Comment: See J.M.'s answer [here](http://math.stackexchange.com/questions/8860/efficiently-calculating-the-logarithmic-integral-with-complex-argument) : I too recommend using $\operatorname{Ei}$ (or $\operatorname{E1}$) as well as the continued fraction (rather than series that may require too much precision and time!). Remember too writing $\operatorname{Ei}(\rho\ln(x))$ and not $\operatorname{Ei}(\ln(x^{\rho}))$ (important for large imaginary part!).
Comment: @RaymondManzoni ok I'll give that a try.
Comment: @RaymondManzoni "Continued fractions" work perfectly. Thanks for the hint...
Answer: Ok I found this very nice paper:

$\phantom{somespace}$On the Evaluation of the Complex-ValuedExponential Integral
by Vincent Pegoraro and Philipp Slusallek
  Saarland University:
Abstract. Although its applications span a broad scope of scientific fields ranging
  from applied physics to computer graphics, the exponential integral is a nonelementary
  special function available in specialized software packages but not in standard
  libraries, consequently requiring custom implementations on most platforms. In
  this paper, we provide a concise and comprehensive description of how to evaluate
  the complex-valued exponential integral. We first introduce some theoretical background
  on the main characteristics of the function, and outline available third-party
  proprietary implementations. We then provide an analysis of the various known
  representations of the function and present an effective algorithm allowing the computation
  of results within a desired accuracy, together with the corresponding pseudocode
  in order to facilitate portability onto various systems. An application to
  the calculation of the closed-form solution to single light scattering in homogeneous
  participating media illustrates the practical benefits of the provided implementation
  with the hope that, in the long term, the latter will contribute to standardizing the
  availability of the complex-valued exponential integral on graphics platforms.
  CCS: G.1.2 [Numerical Analysis]: Approximation – Special function approximations

They put pseudocodes for all approximations there, which are really close to an implementation.


DATEADD in MariaDB

Question: I'm using DATEADD statement in SQL Server and I need migration to MariaDB
  SUM (
    CASE
    WHEN CONVERT(varchar, Production.MadeDate , 112) BETWEEN DATE_ADD(DAY, -2, '2018-06-05') AND DATE_ADD(DAY, -2, '2018-06-05') THEN
      Production.Qty
    ELSE
      0
    END
  ) AS 'N-2'

And i got error like this

[42000][1064] You have an error in your SQL syntax; check the manual
  that corresponds to your MariaDB server version for the right syntax
  to use near 'varchar, Production.MadeDate , 112) BETWEEN DATE_ADD(DAY,
  -2, '2018-06-05') AND ' at line 3

I'm got references from MariaDB DATE_ADD and MariaDB ADDDATE but it's still doesn't working
My Version MariaDB 10.1.32-MariaDB
EDIT :
[SOLVED]
Changing the SQL Statment from CONVERT to CAST
  SUM (
    CASE
    WHEN CONVERT(varchar, Production.MadeDate , 112) BETWEEN DATE_ADD(DAY, -2, '2018-06-05') AND DATE_ADD(DAY, -2, '2018-06-05') THEN
      Production.Qty
    ELSE
      0
    END
  ) AS 'N-2'

TO
SUM (
    CASE WHEN CAST(Production.MadeDate AS DATE) BETWEEN DATE_ADD('2018-06-05', INTERVAL -2 DAY) AND DATE_ADD('2018-06-05', INTERVAL -2 DAY) THEN
        Production.Qty
    ELSE
        0
    END
) AS 'N-2'

It's working for me on
10.1.32-MariaDB

Comment: And why do you convert the Date to a VarChar before comparing it to a Date?
Comment: I don't understand what your `WHERE` clause is supposed to be checking.  Logically speaking, the date range is the same date on both ends.  Can you add some sample data to your question?
Comment: @dnoeth - perhaps to get rid of the time portion?
Comment: @RickJames: Yep, probably a DateTime in SQL Server. But then  `CAST(timestampCol AS DATE)` is way simpler :-)
Answer: You can't use the CONVERT like this on MariaDB / MySQL:
CONVERT(varchar, Production.MadeDate, 112)

The order of the parameters isn't valid on MariaDB / MySQL. The order of the parameters looks like TSQL / SQL Server syntax.
So you can replace the current CONVERT with one of the following:
CONVERT(Production.MadeDate, DATE)  -- using CONVERT (ODBC syntax)
CAST(Production.MadeDate AS DATE)   -- using CAST (SQL92 syntax)

You can use the following SUM using CAST and DATE_ADD:
SUM (
    CASE WHEN CAST(Production.MadeDate AS DATE) BETWEEN DATE_ADD('2018-06-05', INTERVAL -2 DAY) AND DATE_ADD('2018-06-05', INTERVAL -2 DAY) THEN
        Production.Qty
    ELSE
        0
    END
) AS 'N-2'

Note: Check the condition on CASE WHEN also. You check between the same days.
Comment: So i can't use CONVERT? How about DATE_ADD?
Comment: @Aldan: Well, you found the entry in the MariaDB manual for `DATE_ADD`, I doubt they will add it without supporting it.
Comment: Sebastian Brosch and dnoeth thanks a lot, it's working for me.
Answer: In no database should you be converting date/time values to strings for comparison.  I also discourage the use of BETWEEN.  So, I would expect something like this in MariaDB:
 SUM(CASE WHEN Production.MadeDate >= '2018-06-05' - INTERVAL 2 DAY AND
               Production.MadeDate < '2018-06-05' - INTERVAL 1 DAY
          THEN Production.Qty
          ELSE 0
     END) AS N_2

In SQL Server, I would write this as:
SUM(CASE WHEN Production.MadeDate >= DATEADD(day, -2, '2018-06-05') AND
              Production.MadeDate < DATEADD(day, -1, '2018-06-05')
         THEN Production.Qty
         ELSE 0
    END) AS N_2

Note the changes:

All comparisons are done using native date/time types.
The N-2 is changed to N_2, so the column alias does not need to be escaped.
The date/time comparisons are made using direct comparisons, rather than BETWEEN.

DATEADD in MariaDB


Server and Application architecture for large outgoing email volume

Question: we need to develop an application to send large amount of emails (newsletters)
We estimate 15 millions of emails per month (6 - 10 emails per seconds).
Would you recommend me the proper architecture for this application?
should we have several MTA agents and use them in a round robin fashion?
What considerations should we take on account to not being treated as spammers
(its really not spam what we are going to send).
Thanks for your help.
Ezequiel
Comment: see this question http://serverfault.com/questions/41693/best-practices-for-preventing-you-from-looking-like-a-spammer
Comment: Ah - ok, so where is the large outgoing volume here? 6-10 emails per second was not impressive 10 years ago, it is definitely not impressive now. One server can handle that ;)
Comment: Agree with TomTom, if it was 6k-10k/sec it might need some thought, an iPhone could do 6-10/sec.
Comment: yes, you are right, the volume is not the major problem,
 but what about being considered spammer?
Answer:
Use a mailing list software like PHPList to

Not send emails to people who did not ask for it.
Include a Unsubscribe link in the Emails.
Stop sending emails to people who click on the link to unsubscribe.
If any emails bounce, remove that from the list.

To make sure your MTA is not considered a SPAMMer, take this Email Server Test from each of your MTA's and implement suggested fixes.
6-10 emails per second is not a big deal. You should be able to put a reasonably powerful server (4GB RAM, some HDD, etc.) with Postfix and a good Internet line and achieve the speeds.
Once you start sending emails, participate in the Feedback Loop program of major Email providers.


Array single cell to entire column in Google Sheets

Question: I've got something I think is really simple to achieve but I just can't figure out (total amateur here).
I have referenced a single cell from another sheet in the very top of my working sheet and would like for the entire column to populate with the same value. I've tried a few different formulas and can't seem to crack it. Would INDIRECT perhaps be a better route?
Attempt 1 =ArrayFormula(Copy!$D$5)
Attempt 2 =ArrayFormula({Copy!D5})
Answer: Try this:
=ArrayFormula(IF(ROW(A:A),Copy!D5))
This assumes that you want the results to start in Row 1 of your column and that the above formula is in the top cell of your result column. If you want the results to start in Row 2 (e.g.), then place the formula in Row 2 of your result column and use this:
=ArrayFormula(IF(ROW(A2:A),Copy!D5))
... etc.
Comment: Happy I could help.
Answer: Alternatively, put this in your cell J2:
={Copy!D5:D}
{} works as an array without the need to specify the ARRAYFORMULA function. It gets everything from cell D5 and below, from the 'Copy' sheet.


How do I Set custom error messages on Codeigniter

Question: I'm trying to set a custom error message for a particular field on some particular rule as per codeigniter's doc, and I'm running into issues. My code looks like the following

function start(){
$this->form_validation->set_message('rule1', 'Rule 1 Error Message');

$this->form_validation->set_rules('amount', lang('users amount'), 'required|trim|numeric|greater_than[0]', array('rule1' => 'Error Message on rule1 for this field_name'));

if ($this->form_validation->run() == FALSE)
{
  $this->index();
}
else{
$amount =$this->input->post("amount", TRUE);
}

I've tested the rules for each field and they work fine, the problem starts when I add a custom error message for each form field. Previously, if there was an error I'd redirect and display a generic message for the entire form.
$this->session->set_flashdata('error', "Please provide correct data about the transfer");
With the custom message it doesn't throw the custom message at all when I enter data that doesn't obey the rules, however it does throw an error for a pre-defined rules like min_length or max length.
I've followed the docs to a tee, and I don't seee why this issues is happening. I'm aware that there is a way to throw custom messages using callback functions, but preferably I'd like to use this method.
Answer: Please try the following steps:
$this->session->set_flashdata('field_name', "Any custom error message");
redirect('page_URL');//use url to be redirected upon.

OR
$this->form_validation->set_message('is_unique', 'The %s is already taken');

The form_validation changes %s with the label seted for the field.
I hope one of these will helps!


Exibir e ocultar campos conforme o checkbox for selecionado

Question: Preciso que para cada uma dessas opções do checkbox (se ela for selecionada) mostre o campo input relacionado a cada um deles. Mas quando seleciono o checkbox não mostra o campo texto relacionado a ele que deveria ser exibido.
Aqui o script que estou utilizando

        $('#quais_redes input[type="checkbox"]').change(function() {
    let name = this.value;
    $('[data-label=' + name + ']').css('display', this.checked ? '' : 'none');
    });

                        Possui redes sociais?

                                <input class="form-check-input" id="rede_facebook" type="checkbox" name="redes[]" value="1">
                                    Facebook

                                <input class="form-check-input" id="rede_instagram" type="checkbox" name="redes[]" value="2">
                                    Instagram

                                <input class="form-check-input" id="rede_twitter" type="checkbox" name="redes[]" value="3">
                                    Twitter

                                <input class="form-check-input" id="rede_telegram" type="checkbox" name="redes[]" value="4">
                                    Telegram

                                <input class="form-check-input" id="rede_whatsapp" type="checkbox" name="redes[]" value="5">
                                    Whatsapp

                            Qual o seu Facebook?
                            <input type="text" class="form-control" name="facebook" id="facebook" data-label="rede_facebook">

                            Qual o seu Instagram?
                            <input type="text" class="form-control" name="instagram" id="instagram" data-label="rede_instagram">

                            Qual o seu Twitter?
                            <input type="text" name="twitter" class="form-control" id="twitter" data-label="rede_twitter">

                            Qual o seu Telegram?
                            <input type="text" name="telegram" class="form-control" id="telegram" data-label="rede_telegram">

                            Qual o seu Whatsapp?
                            <input type="text" name="whatsapp" class="form-control" id="whatsapp" data-label="rede_whatsapp">

Comment: E como tentou fazer com JS? Poderia postar o código e descrever o resultado obtido?
Comment: Sim, claro! Então, eu acabei usando esse script, tentei fazer um teste só com um campo mesmo pra ver se funcionava mas não rolou.

$(document).ready(function(){
  $('#rede_facebook').on('input', function(){
    $('#facebook').prop('disabled', false);
  });
});

E coloquei o disable no campo do facebook.
Só que o campo só fica desabilitado e não habilita. Mas na realidade não era pra aparecer o campo antes deu selecionar o checkbox, e ele aparece mesmo sem clicar no checkbox e fica sempre desabilitado.
Comment: Seria importante vc tb incluir na sua pergunta o CSS e o JS que vc tentou, assim da para ver ando vc está errando
Comment: Sim, Hugo. Mas parando pra analisar, o código do Javascript que eu tinha colocado ele não estava servindo para ocultar e sim somente para desabilitar, sabe? Eu preciso que ele fique oculto, não desabilitado. Então de qualquer forma tava errada a forma que eu estava fazendo mas vou colocar aqui.
Comment: Galera, tentei resolver usando Ajax mas não funcionou também, vou editar a postagem colocando essa forma que eu fiz q ta mais completa que a anterior.
Answer: Olá, existem algumas incoerências no seu código, e coisas que não estão batendo. Arrumei aqui está funcionando perfeitamente, as etapas:
A tag label for="quais_redes" logo no começo, está sendo um label para a própria label, só está servindo como um texto apenas, e no caso do jQuery na $('#quais_redes input') não existe input no quais_redes como dito antes é um label que não está fazendo nada alí. E em vez de quais_redes pode-se notar que a div que engloba esses checkbox, é a div com a class="col-sm-10", e os inputs estão dentro dela, assim você poderia detectar mudanças dos checkbox com o change() através dela.
No próximo, let name = this.value ao qual ele irá trazer esse value para pegar outro elemento com o data-label = name, porém você pode observar que os values dos inputs checkbox são numeros 1,2,3,4 e 5 e o data-label dos elementos que contém o atributo data-label são rede_nomeDaRedeSocial e não números, logo o que realmente você está querendo pegar para pegar os inputs com o atributo data-label são os id dos input[type="checkbox"], observe o id dos checkbox são rede_nomeDaRedeSocial, ou seja em vez de let name = this.value seria let name = this.id
E por último no css() do jQuery, cada elemento com o [data-label="name"] está dentro do de uma div com a class="form-group" e pode notar que é essa div que tem o display='none' do css, ao qual vc quer alterar, e não o [data-label="name"] em si, até então é essa div pai que tem o atributo style. Assim você pode usar o parent() do jQuery que pega o elemento pai. Ou seja com o parent() ele vai pegar o elemento Pai do elemento com o data-label ao qual você está procurando, e em vai mudar o css dele, no caso o display.
Assim o jQuery ficaria:

$('.col-sm-10 input[type="checkbox"]').change(function(){
        let name = this.id
        $('[data-label="' + name + '"]').parent().css('display', this.checked ? '' : 'none' )
    })

Código Inteiro:

    $('.col-sm-10 input[type="checkbox"]').change(function(){
        let name = this.id
        $('[data-label="' + name + '"]').parent().css('display', this.checked ? '' : 'none' )
    })

        Possui redes sociais?

                <input class="form-check-input" id="rede_facebook" type="checkbox" name="redes[]" value="1">
                    Facebook

                <input class="form-check-input" id="rede_instagram" type="checkbox" name="redes[]" value="2">
                    Instagram

                <input class="form-check-input" id="rede_twitter" type="checkbox" name="redes[]" value="3">
                    Twitter

                <input class="form-check-input" id="rede_telegram" type="checkbox" name="redes[]" value="4">
                    Telegram

                <input class="form-check-input" id="rede_whatsapp" type="checkbox" name="redes[]" value="5">
                    Whatsapp

            Qual o seu Facebook?
            <input type="text" class="form-control" name="facebook" id="facebook" data-label="rede_facebook">

            Qual o seu Instagram?
            <input type="text" class="form-control" name="instagram" id="instagram" data-label="rede_instagram">

            Qual o seu Twitter?
            <input type="text" name="twitter" class="form-control" id="twitter" data-label="rede_twitter">

            Qual o seu Telegram?
            <input type="text" name="telegram" class="form-control" id="telegram" data-label="rede_telegram">

            Qual o seu Whatsapp?
            <input type="text" name="whatsapp" class="form-control" id="whatsapp" data-label="rede_whatsapp">

Espero ter ajudado
Comment: muito obrigada, NoFace! :)


json_encode and parsing information if there are no records returned

Question: I make some AJAX (PHP + JQuery), but I have one problem.
I have:
dataType:"json",
in Javascript
Everything works fine when json_encode returning some records from DB.
The problem is what to do, how to say server in case that there are not any records?
When I have an array which is encoded to JSON is ok.
WHen array is empty the json_enocde returning NULL.
But this is not in expected format so I can't catch this error.
Hope, question is clear :)
Comment: Why not just make a case that if a NULL value is returned, another action will take place? Meaning, why don't you just handle the case?
Comment: if(empty($response)) { echo json_encode(['error' => true']) }  ?
Answer: Here are two (of several) possibilities:
PHP Option:
Handle the NULL object to make it parseble ahead of time...
<code>if ($mydata==NULL) {
    $mydata = new stdClass();
}
echo json_decode($mydata);
</code>
JS Option:
Try catching the error when parsing it on the client side.
<code>// Catch the error
try {
    var data = JSON.parse(json);
} catch(error) {
    // Handle the error
}
</code>


Can you prove this three-way linear map composition?

Question: OK, this was an example that my prof gave when talking about surjective, injective and bijective functions. I also am curious if I am approaching this the right way. (Everyone here has been a really big help in pointing out to me where I am messing up).
It comes after one remark he made: the composition of two bijective (linear) maps are bijective.
So the statement: let $f$ be a function from $A \rightarrow \ B$ and $g$ be a function from $A \rightarrow\ C$.
Assume $f$ is surjective.
$\exists$ a function $h:B\rightarrow C$ such that $h\circ f = g \iff \forall x,y \in A, \ f(x) = f(y)$ implies $g(x) = g(y)$
OK. I approached this as follows: given that if $f$ and $g$ are both surjective, $g \circ f$ will be surjective also. It is also true that if $g \circ f$ is surjective, $g$ is surjective.
Now, the only way $f(x) = f(y)$ implies $g(x) = g(y)$ is if g is surjective as well. Is this the case? I am trying to be sure I understand this.
Meanwhile the statement says that there has to be a function h that when applied to f maps to g. But only if the surjectivity of f implies the surjectivity of g.
But that is about as far as I got. And I don't even know if I understood the premise correctly.
Answer: It's really quite simple.  If $f(x) = f(y)$, then $(h(f(x)) = (h(f(y))$, so $g(x) = g(y)$.
On the other hand, suppose $f(x) = f(y)$ implies $g(x) = g(y)$.  For any $x$,
you want $h(f(x)) = g(x)$.  So just define $h$ on the range of $f$
by $h(t) = g(x)$ where $t = f(x)$.  This is unambiguous because if $t = f(x) = f(y)$, $g(x) = g(y)$.  And on the complement of the range of $f$, define $h$ as you wish.
There is no need for any surjectivity here.  And $f(x) = f(y)$ implying $g(x) = g(y)$ has nothing to do with whether $f$ or $g$ is surjective.
Comment: Ah, my prof was midirecting! Clever! Thanks.

By the way, if I understand you right, the reason your proof works is because you're only trying to show that there is some h that works, right? Not that there is only one or whatever, just that someplace you can have such a function.
Comment: ALso, what if I change the initial statement so that g is a function $B\rightarrow C$? Does that alter things?
Comment: If $g: B \to C$, $g = h \circ f$ doesn't make sense, because $f$ is defined on $A$, not on $B$.


É possível modificar um valor de um vetor com assign() no R?

Question: Suponhamos que temos
x <- "teste"

Dá para atribuir uma outra string a teste, utilizando assign:
assign(x, 1:5)

Assim:

teste
[1] 1 2 3 4 5

Seria possível eu modificar algum dos valores do vetor usando assign?
Algo como:
assign("teste[1]", 2)

Answer: Não dá para fazer diretamente com o assign. Conforme consta na ajuda:

assign does not dispatch assignment methods, so it cannot be used to
  set elements of vectors, names, attributes, etc.

Se você quiser utilizar o assign, uma solução seria fazer uma cópia temporária antes:
temp <- get("teste")
temp[1] <- 2
assign("teste", temp)
teste
[1] 2 2 3 4 5

Você poderia criar uma função que faça isso:
assign2 <- function(x, i, value){
  temp <- get(x, envir = parent.frame())
  temp[i] <- value
  assign(x, temp, envir = parent.frame())
}

x <- "teste"

assign(x, 1:5)
teste
[1] 1 2 3 4 5

assign2(x, 1, 2)
teste
[1] 2 2 3 4 5

Uma outra forma não recomendada de fazer algo semelhante seria com eval e parse:
eval(parse(text = paste("teste[1]", "<-", 2)))

Em todos esses casos, é provável que tenha uma solução mais simples a depender do problema específico que você esteja lidando.
Comment: @GuilhermeDuarte dá uma olhada aqui http://stackoverflow.com/questions/13649979/what-specifically-are-the-dangers-of-evalparse
Comment: Carlos, por que essa forma não é recomendada?


how to get the immediate previous node and next node of the Current selected TreeNode in asp.net?

Question: I have created TreeView in asp.net page.When user select the any node then i want to get the immediate previous TreeNode and immediate next TreeNode of the current selected TreeNode.There is a method in C# windows form application.But it is not available in web controls TreeView.
for example :

Suppose,

user selecting "Sales Order Detail" then i want to get previous Node ->"Product Line   Sales" and next Node ->"Territory Sales Drilldown"
2.User selecting "SampleReports" then i want to get the Previous Node->"Employees" and next Node ->"Company Sales".
Answer: this shold get you the index of the selected node and then you can try to specify the neighbors nodes based on the index to be selected.  I hope it helps.
<code>  TreeNode obj = new TreeNode();
  obj = treeView1.SelectedNode;
  index = treeView1.Nodes.IndexOf(obj);
  TreeNode oTreeNode = treeView1.GetNodeFromIndex((index-1).ToString());
  oTreeNode.select();
  TreeNode oTreeNode2 = treeView1.GetNodeFromIndex((index+1).ToString());
  oTreeNode2.select();
</code>
Comment: There is no such method GetNodeFromIndex() in TreeView.How do i call it?
Comment: I am using VS-2010.It is not listed the method you specified above.
Comment: This only apply to Asp.Net we apps, not WinForm.


Change of state to make button enable from disabled postion in react js

Question: i have this finish button in my child class ...
im trying to change the state of the disabling button when the finish button is clicked
{currentQuest === Quizdata.length - 1 && (
    <Button
      onClick={() => {
        this.finishQuiz();
        this.pushtoDB2();
        //  this.disableCheckLevel();
        this.props.handleDisableValue(scores); // child to parent
      }}
    >
      Finish
    </Button>
)}

i have 4 buttons to change state to false onclick of finish button to enable clicking.
i have a rookie button,sutdent,intermediate,expert,master button.
but i want to change the state in that order.
say if I'm on rookie i can only enable student when rookie is enabled and the score >=5
then student is enabled. then intermediate is enabled if student is enabled and scores>=5 else stays in the same state. this goes until master button
Issue I'm having is that mine goes from rookie to student but doesn't move any further.
this is the  logic i used for disabling state
disabledRook: true,
disabledStudent: true,
disabledInterm: true,
disabledExpert: true,
disabledMaster: true,

//intiall state value
handleDisableValue = scores => {
    if (this.state.disabledRook && scores >= 5) {
      this.setState({
        disabledStudent: false
      });
    } else if (this.state.disabledStudent === false && scores >= 5) {
      this.setState({
        disabledInterm: false
      });
    } else if (this.state.disabledInterm === false && scores >= 5) {
      this.setState({
        disabledExpert: false
      });
    } else if (this.state.disabledExpert === false && scores >= 5) {
      this.setState({
        disabledMaster: false
      });
    } else if (this.state.disabledRook && scores < 5) {
      this.setState({
        disabledRook: true
      });
    } else if (this.state.disabledStudent && scores < 5) {
      this.setState({
        disabledStudent: true
      });
    } else if (this.state.disabledInterm && scores < 5) {
      this.setState({
        disabledInterm: true
      });
    } else if (this.state.disabledExpert && scores < 5) {
      this.setState({
        disabledExpert: true
      });
    } else if (this.state.disabledMaster && scores < 5) {
      this.setState({
        disabledMaster: true
      });
    }

This is where i call the states in the buttons i created
<Button
  onClick={() => {
    this.changeToquiz1();
    this.articelState();
  }}
>
  Rookie
</Button>
<Button
  disabled={this.state.disabledStudent}
  onClick={() => {
    this.articelState();
    this.changeToquiz2();
  }}
>
  Student
</Button>
<Button
  disabled={this.state.disabledInterm}
  onClick={() => {
    this.changeToquiz3();
    this.articelState();
  }}
>
  Intermediate
</Button>
<Button
  disabled={this.state.disabledExpert}
  onClick={() => {
    this.changeToquiz4();
    this.articelState();
  }}
>
  Expert
</Button>
<Button
  disabled={this.state.disabledMaster}
  onClick={() => {
    this.changeToquiz5();
    this.articelState();
  }}
>
  Master
</Button>

Any help thanks
Comment: Please clarify problem / help needed.
Comment: @realAlexBarge i have above..Issue I'm having is that mine goes from rookie to student(enabled state) but doesn't move any further. like intermidiate,expert etc stops on on student
Answer: There is a problem with too many if else after studnent level it will go in wrong condition. I have another solution for your problem instead of many boolean just keep one state like level and just increase level once player score more than 5 points.
const STUDENT = 1;
const INTERN = 2;
const EXPERT =3;
const MASTER =4;

state = {
  level: 0
}
handleDisableValue(score) {
  if(score > 5 && this.state.level < 4) {
    this.setState(prevState=> ({ level: prevState.level + 1 }));
  }
}

In your button:
<Button
 onClick={() => {
   this.changeToquiz1();
   this.articelState();
 }}
>
 Rookie
</Button>
<Button
 disabled={this.state.level < STUDENT}
 onClick={() => {
   this.articelState();
   this.changeToquiz2();
 }}
>
 Student
</Button>
<Button
 disabled={this.state.level < INTERN}
 onClick={() => {
   this.changeToquiz3();
   this.articelState();
 }}
>
 Intermediate
</Button>
<Button
 disabled={this.state.level < EXPERT}
 onClick={() => {
   this.changeToquiz4();
   this.articelState();
 }}
>
 Expert
</Button>
<Button
 disabled={this.state.level < MASTER}
 onClick={() => {
   this.changeToquiz5();
   this.articelState();
 }}
>
 Master
</Button>

I Have made working codesandbox with next level button this you should call once quiz is complete i used it just for demo purpose.
Comment: this.state.level < EXPERT returns a boolean @dave
Comment: @Donzen when i used this code it enabled all the buttons as it was false so something is wrong with this
Comment: @dave i have updated answer and added working codesandbox url.
Comment: Ok its working...also im trying to get the value sent to database for the level do that when user logs in he is already in the latest level rather than re doing all the levels again...would u know how should i assign the value from DB to the level:0?
Comment: you can map DB value to your javascript level values. for eg. if your DB has a level as "student" you can use state value to STUDENT constant which is 1. you can create a simple object like `{ "student": STUDENT, "master": MASTER, and other }` and get current level and assign that to your state.
Comment: @AmitChauhan can u do an example of what u said above if u dont mind because i have the level value in db and have it retrieved but dont know how to assign it
Comment: can tell me what are values in your database?
Comment: @dave what problem are you facing here? it should be fairly easy with react's lifecycle method to setState from your rank value. if you can show me code how are you getting api in codesandbox then i can help you there.
Comment: @dave that's so much of code and i am confused. basically you need to pass your rank value to your component and update that value in state, read about react's lifecycle methods.
Comment: @AmitChauhan i have a new issue the above one is fixed...see for the level say if we have passed all the way to expert level but u want to redo level student again and if the user scores >5 they pass but the levelling up doesnt move past expert level as they havent attended expert level quiz yet...how do i approach this part
Comment: you can pass quiz level to your function and check if quizLevel === this.sate.leave then only increase level otherwise don't increase level.


How can I make a faceted bar chart use stacked bars?

Question: I'm sure I'm missing something obvious here, but have tried a million different iterations and can't seem to find the right recipe. I'm working with survey data and faceting it in a facet_grid, which is now working nicely:
# ingest some data
df <- structure(list(Q52_bin = structure(c(3L, 2L, 2L, 2L, 2L, 2L), .Label = c("low",
"medium", "high"), class = "factor"), Q53_bin = structure(c(2L,
3L, 2L, 2L, 2L, 2L), .Label = c("low", "medium", "high"), class = "factor"),
    Q57_bin = structure(c(2L, 2L, 2L, 2L, 2L, 2L), .Label = c("low",
    "medium", "high"), class = "factor"), Q4 = c("A little",
    "Some", "Some", "A great deal", "A lot", "Some")), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))
# make column names coherent and simplified
names(df) <- c("Q52_bin", "Q53_bin", "Q57_bin", "response")

df %>%
  pivot_longer(!response, names_to = "bin_name", values_to = "b") %>%
  count(response, bin_name, b) %>%
  ggplot(aes(x=n,y=response)) +
  geom_col(position="stack", stat="identity") +
  scale_fill_discrete()+
  facet_grid(vars(b), vars(bin_name)) + labs(caption = "How much have you thought about climate change before today?", x = "", y = "")

However, what I'd really like is for these bars to be stacked horizontal bars with a single bar inside each facet using colours to indicate the different likert responses. I was thinking I could simply switch to:
  ggplot(aes(x=n,fill=response)) +
  geom_bar(position="fill") +

but the output is incoherent (zillions of narrow bars).  Any suggestions on how I can switch this as desired?
Comment: Does `ggplot(aes(x = n, y = "", fill = response)) + geom_col(position="stack")` do what you want?
Comment: Yep - that's the ticket. I also changed to position="fill" and that's me sorted. Just need to sort the colours now.
Answer: Not sure if I understand your question but I would assume this is what you are after.
Sample code:
 df %>%
      pivot_longer(!response, names_to = "bin_name", values_to = "b") %>%
      count(response, bin_name, b) %>%
      ggplot(aes(x=n,y=b, fill=response)) +
      geom_bar(position="stack", stat="identity") +
      scale_fill_discrete()+
      facet_grid(vars(b), vars(bin_name)) +
      labs(caption = "How much have you thought about climate change before today?", x = "", y = "")

Plot:

And if change
facet_grid(~b) # b takes values medium and high

  response     bin_name b          n
   <chr>        <chr>    <fct>  <int>
 1 A great deal Q52_bin  medium     1
 2 A great deal Q53_bin  medium     1
 3 A great deal Q57_bin  medium     1
 4 A little     Q52_bin  high       1
 5 A little     Q53_bin  medium     1
 6 A little     Q57_bin  medium     1
 7 A lot        Q52_bin  medium     1
 8 A lot        Q53_bin  medium     1
 9 A lot        Q57_bin  medium     1
10 Some         Q52_bin  medium     3
11 Some         Q53_bin  medium     2
12 Some         Q53_bin  high       1
13 Some         Q57_bin  medium     3

If you want to ignore the Q52_bin...-s

and to make more nicer use a different theme
library(ggtheme)

theme_gdocs()

Comment: Can you clarify what you mean about `facet_grid(~b)`? I can't seem to make that work in my code.


How to set a contextual filter based on an entity reference field

Question: I am currently working on a radio website.
Here is the basic information to keep it simple.
I have two content types: [emission] (programme) and [podcast].
The [emision] content is merely a general presentation with the broadcasting time. The [podcast] content has a field [field_emission] in which I can make a reference to the [program] you can hear (it works with entity reference).
I have a View displaying all podcasts.
I have another display of that View, a block, shown only on the [emission] pages.
I want to restrict to results of the view to all [podcast] concerned with the displayed [emission]. How should I set the contextual filters.
Here is how I tried so far. Up to now, nothing shows up.
Answer: On the View you started (Podcast Views) the Contextual filter you need to add is the Entity reference field, not the Nid.
Here are the settings for it:
When the filter value is NOT available:
Provide default value
Content Id from URL
When the filter value IS available or a default is provided (optional)
Specify validation criteria
Validator Content
Emission
Place the block on Emission nodes. The block will take the NID of the Emission node it's on, pass it to the Entity reference contextual filter to match Emission in question, and Views results will be limited to only Podcasts which reference that Emission through the field.
You don't need the Relationship unless you plan on displaying Emission information in this block, which you probably don't.

Another approach would be through the opposite side, through Emission Views, where you list Emission content type, but you don't have to display any Fields concerning Emission. Instead you'll display only the Title field of the Podcast that is referencing that Emission.
You do that by adding the Contextual filter ID (it's not the same field as above, but the settings are are the same).
And you have to add the Relationship for the Entity reference field, but the reverse one (Relate each Content with a field_emission set to the content.)!
Then you add the Title Field, but make it uses the above Relationship. This will make the Title Field show Podcast title, and not Emission title. Set its label to something like "Podcasts referencing this Emission".
Make sure to tick "Hide if empty" under "No results behavior" so nothing is output on Emission pages that have no Podcasts referencing them.
And in the end display that block on Emission pages.
Comment: Thank you, it works.
It didn't show because of some other setting I left, concerning the request parameters. I set it back to default and now everything is fine.
Comment: I'm glad it's working :)


How do I move a text character across the screen in c++

Question: I am trying to make a program where I can use the arrow keys or the WASD keys to move a character across the screen (rpg style). I dont have any clue how to redraw the board in an easy way since there would be so many possible positions. I was thinking about creating a 2d array which would hold the positions. I am not asking for you all to write the code, I am asking simply. Is it possible to make the text character move along positions across the array?
Comment: _'I am not asking for you all to write the code'_ But we're asking you to show some.
Comment: What O/S are you using?  This is highly O/S dependant
Comment: I am using microsoft visual c++ 2010 with windows 7. @bobobobo
Comment: So I'd use `SetConsoleCursorPosition` then. It's fairly easy to use. You can [change the colors too](http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047(v=vs.85).aspx). [see here](http://msdn.microsoft.com/en-us/library/windows/desktop/ms682088%28v=vs.85%29.aspx#_win32_character_attributes)
Answer: One way would be to clear the "screen" and redraw the "map" at every change. Another might be to only redraw the lines that have changed. Yet another might be to position the cursor after the character you want to "move", print a backspace followed by e.g. a space, then reposition the cursor to after where you want the new character to be, print another backspace and then the character.
Or simply use a library such as ncurses.
Comment: If the OS supports [ConsoleScreenBuffer](http://msdn.microsoft.com/en-us/library/windows/desktop/ms682088(v=vs.85).aspx) type functions, you're best off using them. `cls`/full reprint won't perform well on many systems.
Answer: On Windows, you can use the SetConsoleCursorPosition function to move the cursor to any arbitrary XY coordinates that you like.
TO do this, you need a HANDLE to the console, which is fairly easy to get
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

More Windows Console functions.
See here for an example
Comment: what library do i use to do that. I tried it and it didnt recognize the handle stuff. @bobobobo
Comment: You `#include `


Are there any acceptable uses for $_COOKIE['has_js'] outside of core?

Question: Drupal 7 has a cookie called has_js.  drupal.js sets this cookie, and it is used by the Batch API and the authorize.php script.
There is a rather old issue about this cookie, backport "$_COOKIE['has_js'] must die" patch to 7.x, but this cookie still remains in drupal-7.x.
Are there any acceptable uses for this cookie, outside these two cases in core?
Comment: I do not consider this a duplicate of http://drupal.stackexchange.com/questions/77967/what-is-the-use-of-has-js-cookie.  I encountered a module that uses this cookie, but in some instances its use causes bugs.  I am trying to determine the proper course of action for my patch.
Answer: I don't think so, for many separate reasons.

Given the comment made to 8.x change records Removed has_js cookie:

Only Batch API used it as a workaround. A clean solution has been reached avoiding the need for the cookie.

I would extrapolate that any solution that uses it should be considered unclean.
There is no page for it on api.drupal.org so it appears it wasn't designed to be used outside and it's not guaranteed to stay unchanged. It's a common in IT to assume one uses undocumented features at his own risk.
It can be unset if JavaScript is on, but Cookies are off, so it cannot have a clear meaning.
It can be unset if some module will successfully try to make site EU Cookie Law compliant (and user didn't agreed yet)
If you read it from PHP, it will be unset if your page is first one loaded after "open in private window" or "clear cookies" click, no matter what are client's JS and Cookie settings.

Reasons in no particular order.
Comment: #5 is the exact reason I am asking this.  I spent the better part of this afternoon boiling down my problem to the cookie in this situation.
Comment: @MPD I can't imagine how this could be avoided, when using cookies. I would try to go for a page with JavaScript redirect to JavaScript-enabled implementation, and link + http refresh (with longer delay) to trigger non-JS implementation. But it all depends on *what* you are trying to implement.