Prove or disprove: $S_{20}$ has an element of order 80.

Question: To be frank I don't even have a clue where to start.
I know $80$ divides $20!$, so assuming with contradiction that exists such a $g \in S_{20}$ wouldn't derive a contradiction looking at $\langle g\rangle$.
I know Cauchy's theorem states its true if 80 was prime, but since it isn't I'm not sure how to continue.
Comment: Do you understand/know of any relationship between cycle structure and element order? For example, what is the order of $(12)(345)$ and why?
Comment: OK great - what you need to do here is reverse-engineer the calculation to determine the order of an element of $S_n$. That is, if the order of an element is $80$ what must its cycle structure look like?
Comment: thanks you helped me a lot!
Comment: yes, i know two cycles are conjugated if they have the same cycle structures. I know how to calculate the order of an element in $S_n$ and determine if it's even or odd using the sign function. The order of your example would be the lcm(2,3) = 6.
Comment: Well, it could either be a single 80 length cycle, which is not possible because we only have 20 elements. So I must check if exists a combination of numbers between 1 to 20 and check if their lcm might be 80?
Comment: Basically, yeah!
Comment: (p.s. by "I know $80 / 20!$..." , I guess you mean "I know $80$ divides $20!$..."?)
Comment: yes this is what i meant
Answer: Sketchy answer: Find the prime decomposition of $80$, so $80=5\times 2^4$. As $5+16=21>20$, we see that $S_{20}$ contains no elements of order $80$ (but $S_{21}$ does).
Comment: Can you elaborate why this "smells" correctly? like why would this give you intuition if it's true or false?
Comment: I'm not sure I understand you question. Above you said you need to find "a combination of numbers between 1 to 20 and check if their lcm might be 80" - well, the optimal way of doing this is to take coprime numbers (as $\operatorname{lcm}(ax, ay)=\operatorname{lcm}(x, y)$), and $80$ has only 2 coprime factors.
Comment: I think i might be misunderstanding because based on what you wrote it means for all elements in $S_{20}$ we can find max lcm = 10. Is this the contradiction?
Comment: @MathStudent101 No; the numbers $2$ and $5$ come from the $80$ (claimed element order) rather than the $20$ in $S_{20}$. For example, $(1 \:2 \:3 \:4 \:5 \:6 \:7)$ has order $7$ and $(1\:2\:3\:4\:5\:6\:7)(8\:9\:10)$ has order $21$ (and lcm here is $21$).


Meu package.json está dando erro!

Question: Estou tento problemas com meu package.json. Está dando erro direto, e quando abro o node para fazer o arquivo, também dá erro como mostra as fotos anexadas.
Answer: Se voce deseja criar um arquivo package.json, voce deve executar o comando:
npm init -yes

Isso vai criar um package.json padrão.
Se quiser é possível utilizar o modo iterativo, para gerar de acordo com algumas perguntas que são feitas via linha de comando.
Para isso basta usar o comando:
npm init

Se deseja saber mais sobre o como criar um arquivo package.json e outras opções de uso, pode acessar a documentação.

Meu package.json está dando erro!


Unresolved project references only on first load of a solution

Question: Short description: First load of a solution will mark external project references as invalid, reloading the solution fix the problem.
Detailed description:
We have a large amount of C# projects in our system, with several different solutions containing only a small number of projects. The projects are referencing each other via project references instead of direct reference to the dll. The referenced projects are not part of the solution.
I experience a strange behavior when using these solutions: every time I open a solution for the first time, these external project references are marked as invalid under the References tree, and some features are not working properly (for example Code analysis, ReSharper references, etc.) Building the solution is possible without errors. However, when I reload the solution, all references will be valid again.
Additional infos:

If I change something in one of the project file, which triggers a reload of the project in the solution, the references are broken again, and I have to reload the solution twice to fix them.
If I add the external projects to the solution, than the problem does not appear.
If I close Visual Studio and load the last solution on next start, the references will be valid. Only loading another solution triggers the problem.

Although the problem is not crucial, it is very inconvenient and time consuming.
We are using Visual Studio 2010 and .NET 4.0 (Visual Studio 2012 is also installed).
Comment: What do you mean by _external project_? Is that a **solution project** or a **reference** to a component like an assembly? By external you mean that your external _thing_ is not under your solution.. where is it? (GAC?)
Comment: Simply it is a *project reference* to a project, which is not in the solution. It is included in other solutions.
Answer: Try installing this package in all your projects.
It happened to me something similar. I added to a solution project which already have another solution, and the references were wrong.
This package solve this issue, at least for me.
https://www.nuget.org/packages/NuGetReferenceHintPathRewrite


How to exclude a field when a search is done?

Question: I just enable the Search Form (provide by the search module) block to allow the visitor to make searches.
When a search is done the entered word is searched in all field of the nodes.
Can I exclude a field?
Let's say the content type has the fields: title, body and provider.
Then when a search is done I need to exclude the field provider from the search.
I have the custom_search module enabled but I see no way to exclude fields.
Answer: Default Search is not customizable. Consider using one of more advanced solutions:

Search API with client module that will suit your needs.
Finder with proper views configuration.
Comment: I was sure last line of question wasn't there when I answered. Strange.
Comment: but OP not made any edit, not possible
Comment: Of all the people here, you should know that [edits are not always visible](http://meta.drupal.stackexchange.com/questions/2492/look-like-bug-in-suggested-edit)
Comment: i know because i posted the question, may be this one different, please don't mistake me
Comment: thanks Molot. As far as I see the Search Api is the right way to do this


Convex hull of unions

Question: I would like to find a representation for convex hulls co$(\cdot)$ (see wikipedia for the definition of the convex hull) in normed spaces. Let $A,B\subset X$ be bounded and convex subsets of a normed space $X$, then $$co(A\cup B)=\bigcup_{t\in[0,1]}tA+(1-t)B$$
where $tA=\{ta: a\in A\}$ for $t\in[0,1]$ and where $co(A)=\{\sum_{i=1}^nt_ix_i:t_i\ge0, \sum_{i=1}^nt_i=1\text{ and }x_i\in X\}$. I have convinced myself (intuitively) that this equality holds, but I do not know how to write it formally down.
Comment: @Norbert : aren't they all equivalent? I mean, isn't the intersection of all convex sets containing some subset $S$ the same as the set of all convex combinations of elements of $S$?
Comment: What is your definition of $co(S)$
Comment: @Norbert : You should know from the question that it is the convex hull of $S$.
Comment: Pick an $x$ in the rhs, show it is in the lhs, then repeat the other way around. Alternatively, pick a point in the rhs and show that it must be in any convex set containing $A \cup B$ (hence it would be the convex hull, by definition).
Comment: @PatrickDaSilva You should know that there are different definitions of convex hull
Comment: Generally it is the smallest convex set containing the set in question (certainly the easiest to state :-)).
Comment: @copper.hat Under that definition, you have to show that the convex hall always exists by showing that the intersection of a collection of convex sets is convex.
Comment: @AlexBecker: That would be true of any definition (the need to show that the resultant object is indeed convex)? Existence of the object is not an issue from a set theoretic standpoint.
Comment: @copper.hat True. I just personally prefer definitions where it's immediately clear that the defined object exists.
Answer: Let $C_1$ be the left hand side above, and let $C_2$ be the right hand side.
It should be clear that $C_2 = \{ t a+(1-t)b | a \in A, b \in B, t \in [0,1]\}$.
First choose $x \in C_2$. Since $x = t a+(1-t)b$, by definition of $co$, $x \in C_1$.
Now choose $x \in C_1$. If $x \in A \cup B$, then $x \in C_2$ trivially, so suppose $x \notin A \cup B. $ By definition, $x= \sum_{i=0}^n t_i x_i$, where $x_i \in A \cup B$,
$t_i \in [0,1]$, and $\sum_{i=0}^n t_i = 1$. Let $I_A = \{i | x_i \in A\}$, and similarly for $I_B$. Let $t =\sum_{i \in I_A} t_i$, then it should be clear that $1-t = \sum_{i \in I_B} t_i$. Both $t$ and $1-t$ are non-zero since $x \notin A \cup B.$
Since $A$ is convex, then it contains the point $a = \frac{1}{t}\sum_{i \in I_A} t_i x_i$, and similarly, B contains the point $b = \frac{1}{1-t}\sum_{i \in I_B} t_i x_i$. Finally, since $x=t a +(1-t)b$, it is clear that $x \in C_2$.
Comment: No issue, this is how it works. Proofs are social processes :-).
Comment: How can one delete one's own comments?
Comment: I didn't read the part of the question which said that $A$ and $B$ were convex sets. I am sorry for my comment. Good answer. +1
Comment: just after the "n mins ago" there's supposed to be an $\times$ that you can click on.

Convex hull of unions


Sum a series of series where each value increments by one

Question: Can anyone suggest an elegant way to sum a series of numbers like this:
<code>    (1, 2, 3, 4)
    (2, 3, 4, 5)
    (3, 4, 5, 6)
    (4, 5, 6, 7)
</code>
That is for $n$ sets of $d$ numbers, what is the total of all numbers?
For example in the series above, the total should be 64
Comment: You want a closed formula?
Comment: Does your first set always start by 1?
Comment: People are answering the generalization suggested by your example. Is this what you want or is your question exactly as you put it: `"That is for n sets of d numbers, what is the total of all numbers?"`?
Comment: I think we need more clarification on what you mean by "like this". Are you only interested in sets of numbers in which the rows start at 1, increment within each row by 1, and increment between rows by 1?  Or are you also interested in more general cases?
Comment: It happens to be the set always starts at $1$ but the general responses have been interesting too (i.e. @mweiss)
Answer: For n sets of d numbers, there must be an average number. If all of the rows increment by 1 then you could just take the average of the two corners, top left and bottom right to get the average for all spots.
Example:
Average of $1$ and $7$ (rows+columns-1) is $4$ (which is always $(n+d-1+1)/2$)
$4$ (average) times $4$ (rows) times $4$(columns) is $64$
So the total is $\frac{n+d}{2}*n*d$ if it always increments by one for ever row and column and it starts at one at the top left corner.
Comment: @AJStas Why? The formula is "symmetric" in that columns and rows are arbitrary and could be switched without change. Your formula makes it different when you do. Can you explain why you think that to be correct?
Comment: You're right, I didn't realize you forced it to start at $1$.
Comment: THanks this is a really handy answer
Answer: If you pair the $n$th number in the array, counting from the top left, with the corresponding number in the array counting from the bottom right, the total is always constant (in this example, we have $1+7=2+6=3+5=4+4=2+6= \cdots = 8$).  In an array with $n$ rows of $d$ numbers the number of such pairs will be $nd/2$.
Comment: Well, I'm not sure if we're supposed to assume that in every case the first row starts with $1$, that each row increments by $1$, or that each column increments by $1$.  (IOW I don't know whether those are *accidental* features of the example or *essential* ones.)  But as long as the rows increment by a constant and the columns increment by a constant (not necessarily the same one as for the rows) the approach I described will work.
Comment: and the value of each pair is $n+d$, so you get $(n+d) * n * d /2$.
Comment: So an $n \times n$ arrangement sums to $n^3$. That's interesting actually.
Comment: @mweiss Thats a good point to consider. The good thing is that even  with just the explanation for the 1-step case, it is relatively to derive the n-step versions
Comment: @mweiss You're forgetting about the identical diagonal numbers down the middle
Comment: @Imray Not sure what you mean by saying I'm "forgetting" about them.  Because in your example the rows and columns both increment by 1, you always have $a_{n,m+1}=a_{n+1,m}=a_{n,m}+1$. I don't see why that's relevant.  In general if the increment were $k$ within a row and $j$ between rows you'd have $a_{n,m+1}=a_{n,m}+k$ and $a_{n+1,m}=a_{n,m}+j$.
Comment: @mweiss , you said that for the rows it isnt necessary that the increment is constant, so I've tried one example, but I can get the answer right.. Can you help me out for a set of series like this one? {(13, 19, 36), (18, 25, 33), (24, 32, 41)} Both the columns and lines have a different increment, that is equal to the previous column/line + 1
Comment: @BrunoCasteleiro I didn't say that "it isn't necessary that the increment is constant".  On the contrary, I said that "as long as the rows increment by a constant and the columns increment by a constant (not necessarily the same one as for the rows) the approach... will work."  In your example neither the rows *nor* the columns increment by constants, so you will need some other method.
Comment: Sorry, misunderstanding.. But, as long as I find a constant relation between the numbers, I can work on an approach like the one you did right? I know its possible for the series I showed, I just can't get there..
Comment: My approach *explicitly* relies on the fact that the increments with each row, and between each row, are both constants.
Comment: Allright, tell me then.. if I make the difference of the next number in the line or column, I get a set of differences with constant increment.. For example, for the series {(1,3,6), (2,5,9)}, 3-1=2 and 6-3=2.. and 5-2=3 and 9-5=4 for the second serie. And if I difference this results, I will have constant increment for columns.. Can I reach now an answer for the sum with your method?
Comment: @BrunoCasteleiro I would post that as a new question. It is sufficiently different from this one that it deserves its own answers.
Comment: Thanks, I just did it.
Here you have the [link](http://math.stackexchange.com/questions/1817648/summation-of-numbers-without-constant-increment) in the case you have some thoughts you want to share.


Can likelihood be changed when the prior changes?

Question: I have a data which follows gamma distribution and want to know the uncertainty of the parameters of this data.

$\text{Data} \sim \text{Gamma} (\alpha, \beta)$
Parameters
$\alpha \sim \text{Gamma} (k_\alpha, \theta_\alpha)$
$\beta \sim \text{Gamma}(k_\beta, \theta_\beta)$

I used Winbugs (code below).
<code>model{
  for (i in 1:N){
     Y[i] ~ dgamma(k, theta)
  }

  k ~ dgamma(0.1, 0.1)
  theta ~ dgamma(0.1, 0.1)
}
</code>

To plot the likelihood I used a uniform prior then divided the posterior by the prior which makes the posterior same as the likelihood. (Figure1)

Next I changed the prior several times and looked what happens, but the problem is when I plotted the likelihood by dividing the posterior by the prior, likelihood changes which shouldn't, whenever I change the prior. (Figure 2, 3)

Question
Is it possible that the likelihood changes when the prior changes?
Can somebody help me what the problem is?
If the prior is too narrow, is there a possibility that the posterior might be wrong?
Comment: Likelihood is only a function of the model and the data. If those don't change, the likelihood is the same.
Comment: The posterior is given by $P(\theta|D) = \frac{P(D|\theta)P(\theta)}{\int_{\theta}P(D|\theta)P(\theta)}$. So if you change the prior, the denominator (model evidence) will also change. So, it will not be sufficient to divide the posterior by just $P(\theta)$ to get the likelihood back, you also need to keep track of the evidence term.
Comment: Yes, that's why I am confused about the results. The likelihood shouldn't be changed but it moves when the prior changes.
Comment: Is the posterior a proper distribution? I am wondering if the model evidence is playing a part in this? If the posterior is a proper distribution than for different priors, you have different marginal likelihoods and that should be taken into account to recover the likelihood, perhaps?
Comment: Would you please explain about it in detail? I'm not sure about your explanation since I just started to study bayesian.
Comment: Yes I understood. Then how can I plot the likelihood? Another question is in Figure3 when the prior is narrow the posterior is quite different to Figure1 and Figure2. Why is it that?
Comment: The prior has no effect on the likelihood so I suspect you have a bug somewhere. It's likely just due to the randomness of monte carlo but might indicate that your monte carlo chains have not converged. You probably need to run it much longer.
Comment: I just ran 100000 but unfortunately the result is same. Can there be some other reasons?
Comment: To Luca: I understood what you've mentioned about the denominator(model evidence) which changes when the prior changes, but isn't it a constant? I think the denominator can be changed but it affects to the scale of the likelihood not the location of the likelihood. Am I right?
Comment: You should provide your entire code for us. It would help to figure out what's happening. Your current code doesn't have a uniform as a prior. Also, aren't you mixing up joint and marginal priors (posteriors)?
Comment: Thanks for your comment. For uniform prior I just used duni() rather than dgamma(). k~duni(), theta~duni(). All the other things are same. Can you give me some more explanation about what mixing up joint and marginal priors means? The figures are only for shape parameter. I have the results of scale parameter as well but uploaded only shape parameter.
Comment: I understand that dividing the joint posterior by the joint prior should give the same likelihood (up to a constant). But I'm not sure this is true if you're dividing a marginal posterior over a marginal prior. That was my point.
Comment: Also, I'm not sure how you're actually dividing the posterior by the prior. I mean, how do you (your code) exactly do that? It may be a problem with your code that implement this part of your reasoning. That's why I asked for your complete code.
Answer: The likelihood expressed in terms of the prior, the posterior and the evidence is:
$$p(D|\alpha,\beta)=\frac{p(\alpha,\beta|D)p(D)}{p(\alpha,\beta)}$$
I assume that what you are looking at is:
$$
p(D) \int p(D|\alpha,\beta) \,\mathrm{d}\beta
= p(D) \int \frac{p(\alpha,\beta|D)p(D)}{p(\alpha,\beta)} \,\mathrm{d}\beta
$$
What you actually should look at is:
$$
\frac{\int p(\alpha,\beta|D)p(D) \,\mathrm{d}\beta}{\int p(\alpha,\beta) \,\mathrm{d}\beta}
=\frac{ p(\alpha|D) p(D)}{p(\alpha)}
= p(D|\alpha)
$$
However, without seeing your complete code, we do not know what you are looking at. What we know for sure is that the Likelihood does not depend on the choice of the prior distribution.


Draw shaded region within great circle distance from specified point with Matplotlib Basemap

Question: I want to use Python/Matplotlib/Basemap to draw a map and shade a circle that lies within a given distance of a specified point, similar to this (Map generated by the Great Circle Mapper - copyright © Karl L. Swartz.):

I can get the map to generate as follows:
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt

# create new figure, axes instances.
fig,ax = plt.subplots()

# setup Mercator map projection.
m = Basemap(
            llcrnrlat=47.0,
            llcrnrlon=-126.62,
            urcrnrlat=50.60,
            urcrnrlon=-119.78,
            rsphere=(6378137.00,6356752.3142),
            resolution='i',
            projection='merc',
            lat_0=49.290,
            lon_0=-123.117,
            )

# Latitudes and longitudes of locations of interest
coords = dict()
coords['SEA'] = [47.450, -122.309]

# Plot markers and labels on map
for key in coords:
    lon, lat = coords[key]
    x,y = m(lat, lon)
    m.plot(x, y, 'bo', markersize=5)
    plt.text(x+10000, y+5000, key, color='k')

# Draw in coastlines
m.drawcoastlines()
m.fillcontinents()

m.fillcontinents(color='grey',lake_color='aqua')
m.drawmapboundary(fill_color='aqua')

plt.show()

which generates the map:

Now I would like to create a great circle around a specified point, such as the top map.
My attempt is a function that takes the map object, a center coordinate pair and a distance, and creates two curves and then shade between them, something like:
def shaded_great_circle(map_, lat_0, lon_0, dist=100, alpha=0.2):  # dist specified in nautical miles
    dist = dist * 1852  # Convert distance to nautical miles
    lat = np.linspace(lat_0-dist/2, lat_0+dist/2,50)
    lon = # Somehow find these points
    # Create curve for longitudes above lon_0
    # Create curve for longitudes below lon_0
    # Shade region between above two curves

where I have commented what I want to do, but am not sure how to do it.
I have tried a few ways to do this, but what has me confused is that all inputs to the map are coordinates measured in degrees, whereas I want to specify points in length, and have that converted to latitude/longitude points to plot. I think this is related to data as lat/lon in degrees versus map projection coordinates.
Any nudges in the right direction would be appreciated
Thanks
Answer: In the end I had to implement this manually.
In short, I used an equation given here to calculate the coordinates given an
initial starting point and a radial to calculate points around 360 degrees, and then plot a line through these points. I don't really need the shading part, so I haven't implemented that yet.
I thought this is a useful feature so here is how I implemented it:
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt

def calc_new_coord(lat1, lon1, rad, dist):
    """
    Calculate coordinate pair given starting point, radial and distance
    Method from: http://www.geomidpoint.com/destination/calculation.html
    """

    flat = 298.257223563
    a = 2 * 6378137.00
    b = 2 * 6356752.3142

    # Calculate the destination point using Vincenty's formula
    f = 1 / flat
    sb = np.sin(rad)
    cb = np.cos(rad)
    tu1 = (1 - f) * np.tan(lat1)
    cu1 = 1 / np.sqrt((1 + tu1*tu1))
    su1 = tu1 * cu1
    s2 = np.arctan2(tu1, cb)
    sa = cu1 * sb
    csa = 1 - sa * sa
    us = csa * (a * a - b * b) / (b * b)
    A = 1 + us / 16384 * (4096 + us * (-768 + us * (320 - 175 * us)))
    B = us / 1024 * (256 + us * (-128 + us * (74 - 47 * us)))
    s1 = dist / (b * A)
    s1p = 2 * np.pi

    while (abs(s1 - s1p) > 1e-12):
        cs1m = np.cos(2 * s2 + s1)
        ss1 = np.sin(s1)
        cs1 = np.cos(s1)
        ds1 = B * ss1 * (cs1m + B / 4 * (cs1 * (- 1 + 2 * cs1m * cs1m) - B / 6 * \
            cs1m * (- 3 + 4 * ss1 * ss1) * (-3 + 4 * cs1m * cs1m)))
        s1p = s1
        s1 = dist / (b * A) + ds1

    t = su1 * ss1 - cu1 * cs1 * cb
    lat2 = np.arctan2(su1 * cs1 + cu1 * ss1 * cb, (1 - f) * np.sqrt(sa * sa + t * t))
    l2 = np.arctan2(ss1 * sb, cu1 * cs1 - su1 * ss1 * cb)
    c = f / 16 * csa * (4 + f * (4 - 3 * csa))
    l = l2 - (1 - c) * f * sa * (s1 + c * ss1 * (cs1m + c * cs1 * (-1 + 2 * cs1m * cs1m)))
    d = np.arctan2(sa, -t)
    finaltc = d + 2 * np.pi
    backtc = d + np.pi
    lon2 = lon1 + l

    return (np.rad2deg(lat2), np.rad2deg(lon2))

def shaded_great_circle(m, lat_0, lon_0, dist=100, alpha=0.2, col='k'):  # dist specified in nautical miles
    dist = dist * 1852  # Convert distance to nautical miles
    theta_arr = np.linspace(0, np.deg2rad(360), 100)
    lat_0 = np.deg2rad(lat_0)
    lon_0 = np.deg2rad(lon_0)

    coords_new = []

    for theta in theta_arr:
        coords_new.append(calc_new_coord(lat_0, lon_0, theta, dist))

    lat = [item[0] for item in coords_new]
    lon = [item[1] for item in coords_new]

    x, y = m(lon, lat)
    m.plot(x, y, col)

# setup Mercator map projection.
m = Basemap(
            llcrnrlat=45.0,
            llcrnrlon=-126.62,
            urcrnrlat=50.60,
            urcrnrlon=-119.78,
            rsphere=(6378137.00,6356752.3142),
            resolution='i',
            projection='merc',
            lat_0=49.290,
            lon_0=-123.117,
            )

# Latitudes and longitudes of locations of interest
coords = dict()
coords['SEA'] = [47.450, -122.309]

# Plot markers and labels on map
for key in coords:
    lon, lat = coords[key]
    x,y = m(lat, lon)
    m.plot(x, y, 'bo', markersize=5)
    plt.text(x+10000, y+5000, key, color='k')

# Draw in coastlines
m.drawcoastlines()
m.fillcontinents()

m.fillcontinents(color='grey',lake_color='aqua')
m.drawmapboundary(fill_color='aqua')

# Draw great circle
shaded_great_circle(m, 47.450, -122.309, 100, col='k')  # Distance specified in nautical miles, i.e. 100 nmi in this case

plt.show()

Running this should give you (with 100 nautical mile circle around Seattle):


Add an event listener to select list

Question: I've attached the following js to an exposed views form field and it works on first page load but when the form is changed (by ajax) it doesn't fire.
I can't quite work out where to add an event listener for onchange of the select list.
The following doesn't use jQuery but uses the core once library so I would like to avoid jQuery.
/**
 * @file
 * Landing page adjustments.
 */

 (function (Drupal, once) {
    'use strict';

    /**
     * Attached behavior for Custom DataLayer.
     *
     * @type {{attach: Drupal.behaviors.CurrentSelectOption.attach}}
     */
    Drupal.behaviors.CurrentSelectOption = {
      attach: function attach(context) {
        // First page load
        let elements = once('CurrentSelectOption', 'select#edit-field-event-country.form-select', context);
        elements.forEach(processingCallback);
      }
    };

    function processingCallback(value, index) {
      let option = value.options[value.selectedIndex]
      value.remove (option);
      value.add (option, 0);
    }

})(Drupal, once);

Comment: Why are you avoiding jQuery? It comes bundled with core. It's been almost 2 decades since I wrote raw JS without jQuery, so it's hard for me to provide the solution, though I'd have one without that requirement.
Comment: I didn't want to add another dependency to the script if I didn't have to and it was working apart from not being triggered when the form was changed. I've got nothing against jQuery :-)
Answer: When an AJAX call is made through the Drupal API, behaviours are re-attached. So if the API is in use, the answer is simply to put the code inside the attach method in your behavior, where you already have it.
The twist is: don't use IDs to target elements. This is a general best practice rule for CSS/JS DOM selection, but especially important here, as Drupal will generate a new ID for the form element it replaces. If you inspect the select and its wrapper after the AJAX call, you'll see -2 appended to the original ID.
Other than that (without a test) your code looks fine.
Comment: I had forgotten that :-) using a class solved the issue.

Add an event listener to select list


Rolar o conteúdo da DIV sem que o conteúdo saia da DIV

Question: Olá, estou com um problema, gostaria que minha DIV do canto direito acompanhasse o conteúdo da esquerda até acabar o conteúdo da esquerda, só que se eu colocar position fixed na DIV da direita ela fica fixa até o final da página. imagens do problema.Alguém pode me ajudar? :(

/* DIV COM AS DUAS COLUNA */
#paginas {
   max-width: 1024px;
   display:block;
   float:left;
}

/* DIV DA ESQUERDA COM CONTEÚDO DE ROLAGEM */
#paginas-coluna1 {
  display:block;
  float:left;
  max-width:520px;
}

/* DIV DA DIREITA QUE DEVERIA FICAR FIXA AO LADO DO CONTEÚDO DA ESQUERDA ATÉ ACABAR O CONTEÚDO DA DIV PAGINAS-COLUNA1*/
#paginas-coluna2 {
  display:block;
  float: right;
  max-width: 504px;
  height: 730px;
}

/*CONTEUDOS INTERNO DA DIV DA DIREITA */

#campo-video2 {
  display:block;
  float:right;
  height: 270px;
  width: 466px;
}
#carga-horaria {
  width:273px;
  height:106px;
  display:block;
  background-color:#2BABE1;
  float: right;
  color: #fff;
  margin-top: 20px;
  text-align: center;
  font-family: arial;
  font-weight: bold;
  padding: 18px;
}
#botao-matriculapagina {
  width:194px;
  height:106px;
  display:block;
  float:right;
  background-color: #008DD1;
  margin-top: 20px;
  color: #fff;
  font-weight: bold;
  padding: 20px;
  text-align: center;
  font-size: 17px;
}
#botao-matriculapagina2 {
  width:91px;
  height:32px;
  line-height:32px;
  font-weight:normal;
  margin: 0 auto;
  background-color:#2BABE1;
  font-size:14px;
  cursor:pointer;
}
Comment: Gostei da imagem, é bem explicativa, porém não teria como você fazer um exemplo com uma pequena parte disto no code snippet(é um botão que adiciona código executável quando você está criando a pergunta bem parecido com o jsfiddle) ou entao no próprio http://jsfiddle.net :D
Comment: Paulo, obrigado pelo apoio, estou providenciando o código como solicitado :)
Comment: Pesquise no Google sobre Sticky Footer. Acho que isso resolve seu problema.
Answer: Use os valores table+table-cell para a propriedade display do CSS:
.div-pai {
    display: table;
    width: 100%;
}
.div-filha-esquerda, .div-filha-direita {
    display: table-cell;
    width: 50%;
}

Isso fará os conjuntos de divs se comportarem como tabela, alinhando suas alturas.
Obviamente, não funciona em IE < 8.
Se tiver que dar suporte para IE<8, use um comentário condicional para incluir o alinhamento por CSS (aqui e aqui), ou, em última tentativa, por JavaScript.

Se você quiser que somente parte do conteúdo seja esticado até o final, use position:absolute com bottom: 0 e o top: [xx]px. Onde [xx] é o deslocamento fixo do topo. Se quiser algo mais dinâmico, terá que ser por JavaScript, acredito.
.conteudo-esticado {
  position: absolute;
    top: 85px;
    right: 0;
    bottom: 0;
    left: 0;
}
.div-esticado-esq, .div-esticado-dir {
  float: left;
  height: 100%;
  width: 50%;
}

.paginas {
  display: table;
  max-width: 1024px;
  width: 100%;
}
.paginas-coluna1,
.paginas-coluna2 {
  display: table-cell;
  position: relative;
  width: 50%;
}
.paginas-coluna1 { background: #ff9999; }
.paginas-coluna2 { background: #9999ff; }

.conteudo-espichado {
  border: 1px solid #000;
  position: absolute;
    top: 85px;
    right: 0;
    bottom: 0;
    left: 0;
  width: 100%;
}
.div-espichada-esq, .div-espichada-dir {
  float: left;
  height: 100%;
  width: 50%;
}
.div-espichada-esq { background: #dd4444; }
.div-espichada-dir { background: #4444dd; }

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla molestie turpis quis urna dapibus gravida. Maecenas ac mi id nibh volutpat ultrices. Duis vehicula nec urna ac volutpat. Nulla nec tortor sit amet diam iaculis euismod. In hac habitasse platea
    dictumst. Nulla facilisi. Quisque consequat quam id leo efficitur hendrerit. Pellentesque luctus mattis massa, quis dapibus erat ullamcorper ut. Nunc neque justo, consequat ac nunc nec, molestie dictum nisi. Pellentesque suscipit ac nunc id bibendum.
    Ut nec pharetra odio. Maecenas gravida erat vel condimentum tempus. Duis sit amet massa lobortis, pellentesque sapien et, feugiat mauris. Curabitur ac urna nec magna bibendum dapibus id sit amet ex. Sed et leo posuere, aliquam mi vel, auctor lorem.
    Cras blandit orci vel diam ullamcorper commodo.

imagem aqui por exemplo, ou uma div com altura fixa

conteudo

conteudo

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla molestie turpis quis urna dapibus gravida. Maecenas ac mi id nibh volutpat ultrices. Duis vehicula nec urna ac volutpat. Nulla nec tortor sit amet diam iaculis euismod. In hac habitasse platea
    dictumst. Nulla facilisi. Quisque consequat quam id leo efficitur hendrerit. Pellentesque luctus mattis massa, quis dapibus erat ullamcorper ut. Nunc neque justo, consequat ac nunc nec, molestie dictum nisi. Pellentesque suscipit ac nunc id bibendum.
    Ut nec pharetra odio. Maecenas gravida erat vel condimentum tempus. Duis sit amet massa lobortis, pellentesque sapien et, feugiat mauris. Curabitur ac urna nec magna bibendum dapibus id sit amet ex. Sed et leo posuere, aliquam mi vel, auctor lorem.
    Cras blandit orci vel diam ullamcorper commodo.

Comment: Obrigado pela ajuda Andre, só que ainda não foi solucionado o principal problema que seria a coluna da direita descer até o fim do conteúdo da coluna da esquerda, exemplo nas imagens, tem como fazer algo com position fixed ? algo assim?
Comment: @LeonardoMax o que não funciona? vc não quer que a altura div da direita acompanhe a altura da div da esquerda?
Comment: Atualizei a resposta.. dê uma olhada


python pandas: list of integers as individual values of DataFrame

Question: Question:
How to 'pd.read_csv' so that the values in a given column are of type list (a list in each row of a column)?
When creating a DataFrame (from a dict, see below), individual values are of type list. The problem: After writing the DataFrame to a file and reading from the file back to a DataFrame, I get a string instead of a list.

creating the DataFrame

import pandas as pd
dict2df = {"euNOG": ["ENOG410IF52", "KOG2956", "KOG1997"],
           "neg": [[58], [1332, 753, 716, 782], [187]],
           "pos": [[96], [659, 661, 705, 1228], [1414]]}
df = pd.DataFrame(dict2df)

value is a list
type(df.loc[0, 'neg']) == list # --> True
type(df.loc[0, 'neg']) == str # --> False
df.loc[1, 'neg'][-1] == 782 # --> True

write to file

df.to_csv('DataFrame.txt', sep='\t', header=True, index=False)

read from file

df = pd.read_csv('DataFrame.txt', sep='\t')

value is a string not a list
type(df.loc[0, 'neg']) == list # --> False
type(df.loc[0, 'neg']) == str # --> True
df.loc[1, 'neg'][-1] == 782 # --> False

Of course, it's possible to convert between the two data types, but it's computationally expensive and needs extra work (see below)
def convert_StringList2ListOfInt(string2convert):
    return [int(ele) for ele in string2convert[1:-1].split(',')]

def DataFrame_StringOfInts2ListOfInts(df, cols2convert_list):
    for column in cols2convert_list:
        column_temp = column + "_temp"
        df[column_temp] = df[column].apply(convert_StringList2ListOfInt, 1)
        df[column] = df[column_temp]
        df = df.drop(column_temp, axis=1)
    return df
df = DataFrame_StringOfInts2ListOfInts(df, ['neg', 'pos'])

What would be a better (more pythonic) solution? It would be very convenient to iterate over the Integers in the list without having to convert them back and forth.
Thank you for your support!!
Answer: You can use ast.literal_eval() to convert the strings to lists.
A simple example of ast.literal_eval() -
>>> import ast
>>> l = ast.literal_eval('[10,20,30]')
>>> type(l)
<class 'list'>

For your case, you can pass it to Series.apply , so that each element in the series is evaluated (safely). Example -
df = pd.read_csv('DataFrame.txt', sep='\t')
import ast
df['neg_list'] = df['neg'].apply(ast.literal_eval)
df = df.drop('neg',axis=1)
df['pos_list'] = df['pos'].apply(ast.literal_eval)
df = df.drop('pos',axis=1)

Demo -
In [15]: import pandas as pd

In [16]: dict2df = {"euNOG": ["ENOG410IF52", "KOG2956", "KOG1997"],
   ....:            "neg": [[58], [1332, 753, 716, 782], [187]],
   ....:            "pos": [[96], [659, 661, 705, 1228], [1414]]}

In [17]: df = pd.DataFrame(dict2df)

In [18]: df.to_csv('DataFrame.txt', sep='\t', header=True, index=False)

In [19]: newdf = pd.read_csv('DataFrame.txt', sep='\t')

In [20]: newdf['neg']
Out[20]:
0                     [58]
1    [1332, 753, 716, 782]
2                    [187]
Name: neg, dtype: object

In [21]: newdf['neg'][0]
Out[21]: '[58]'

In [22]: import ast

In [23]: newdf['neg_list'] = newdf['neg'].apply(ast.literal_eval)

In [24]: newdf = newdf.drop('neg',axis=1)

In [25]: newdf['pos_list'] = newdf['pos'].apply(ast.literal_eval)

In [26]: newdf = newdf.drop('pos',axis=1)

In [27]: newdf
Out[27]:
         euNOG               neg_list               pos_list
0  ENOG410IF52                   [58]                   [96]
1      KOG2956  [1332, 753, 716, 782]  [659, 661, 705, 1228]
2      KOG1997                  [187]                 [1414]

In [28]: newdf['neg_list'][0]
Out[28]: [58]

Comment: thank you! this is more pythonic in the sense that it uses a library instead of my own code. I was hoping to find a solution that would include this conversion when reading the data frame.


Prove this sequence is decreasing

Question:
Prove this sequence is decreasing for all $0<x<1$ and $ x>1$:
  $$n(x^{1/n} -1)$$

I've tried showing $(n+1)(x^{\frac{1}{n+1}} -1)<n(x^{1/n} -1)$ by separating into the cases $x>1$ and $x<1$ but end up with the inequality $nx^{\frac{1}{n+1}} + x^{\frac{1}{n+1}} < nx^{1/n} + 1$ and can only prove that $ x^{1/n} <  x^{\frac{1}{n+1}}< 1$ or vice versa depending on the case, which does not definitively prove the first inequality.
Answer: The AM-GM inequality yields:
$$\frac{nx^{1/n} + 1}{n+1} \ge \left( (x^{1/n})^n \times 1 \right)^{1/{n+1}} = x^{1/(n+1)}$$
with equality only when $x = 1$. This proves your result.
Comment: It's a calculus class, yes? AM-GM is strictly pre-calculus and is generally assumed. It's an easy proof by induction you should give it a go.
Comment: Unfortunately, the course hasn't covered the AM-GM inequality.

Prove this sequence is decreasing


extract two types of text from a string

Question: I have a string that contains two (N in the general case) types of data, delimited by open and close marks:
type1a <: type2a :> type1b <: type2b :> type1-c

There are numerous real-life examples of such intermixed data, e.g. code and comments (and probably javadoc comments), plain html and the scripting part, etc.
I want to split the string into strings that contain different types of data; just an array/list of ("type1a", "type2a", "type1b", "type2b", "type1-c") is not enough because I need the types of data.
Coding this would (and probably will) be a funny exercise, but there must be an existing library that already offers this functionality.
Is there a Java library offering such functionality, namely, splitting a string into multiple fragments of different nature, preserving information on each fragment's type?
Comment: With 11k rep, you should probably know that asking for library recommendations is off-topic on StackOverflow. It's also quite unclear what you are looking for if you were asking this as a coding question - what sort of output *do* you expect (your example of what's not good enough doesn't tell what *is* good enough)
Comment: Hello, if I understand your question correctly, you could consider this as a custom grammar. If so you could use language processsing libraries such as ANTLR or design patter Interpreter to solve this.
Answer: public static List<String> read(String str) {
    List<String> res = new ArrayList<>();

    try (Scanner scan = new Scanner(str)) {
        scan.useDelimiter("\\s*<:\\s*|\\s*:>\\s*");

        while (scan.hasNext())
            res.add(scan.next());
    }

    return res;
}

Comment: is it any different from `Arrays.asList(myString.split("<:|:>"))` ? Well, the problem is that I am not sure if each `<:` is followed by `:>`
Answer: Seems to me that you want to extract a list of pairs:
public static void main(String[] args) {
    String opening = "<:";
    String closing = ":>";
    String str = " type1a  <:  type2a :> type1b <:  type2b :> type1c   <: type2c :>  ";

    String[] splitted = str.split(closing);
    List<Pair<String, String>> list = new ArrayList<>();

    for (String item : splitted) {
        if (item.trim().isEmpty())
            break;

        int index = item.indexOf(opening);
        String first = item.substring(0, index).trim();
        String second = item.substring(index + opening.length()).trim();
        Pair<String, String> p = new Pair<>(first, second);
        list.add(p);
    }

    for (Pair<String, String> p : list) {
        System.out.println(p.getKey() + " " + p.getValue());
    }
}

will print
type1a type2a
type1b type2b
type1c type2c

extract two types of text from a string


prevent zfs storage driver in docker rootless mode

Question: I'm trying to use rootless docker, but when pulling and image, docker is trying to use zfs as the storage driver. I can confirm that docker info shows the zfs driver. I didn't intend or configure that anywhere. My OS isn't defaulted to zfs (btrfs the the root, boot etc). My home directory is in a mounted zfs.
The instructions for zfs in docker explains how to use the daemon.json to set the storage driver. However, it doesn't exist for me, which is expected, but I see no equivalent config in my system that does so. The ~/.docker/config.json has nothing about storage drivers.
Is the fact that my home directory (and the rootless docker directories) are in a mounted zfs location enough to force that as the storage driver? Is there any way to have rootless docker use a different storage driver, maybe by pointing my rootless install to another location that isn't a zfs backed directory?
Comment: for others to find this easier, this is the docker / zfs error:
`docker: failed to register layer: exit status 1: "/sbin/zfs fs create -o mountpoint`

(People see similar errors for docker for other permission issues as well.
Answer: I confirmed that moving the location of ~/.local/share/docker was enough to stop using the zfs storage driver. I made that directly into a soft link to /var/docker_rootless, and all worked. Even docker info reports using the overlay2 storage driver now.
notes on exact steps to resolve:

stopped docker service first.

systemctl --user stop docker.service

also made /var/docker_rootless owned by my user that is running rootless docker.

sudo mkdir /var/mynewdir; sudo chown $(whoami):$(whoami) /var/mynewdir

moved the original docker folder

mv ~/.local/share/docker ~/.local/share/docker.bak

created the link

ln -s /var/mynewdir ~/.local/share/docker

Coppied the old folder contents to the new directory.

rsync -A ~/.local/share/docker.bak/ ~/.local/share/docker


How do I get pre-rendered html pages from .net core back-end for angular 7?

Question: Can you use pre-rendered razor html pages by an angular app?
Setup: Angular 7, .net Core 2.1
Technically should be possible using templateUrl in angular and point that to the back-end endpoint.
I just don't know how to parse the html page into angular.
Also when the angular project is compiled it adds a prefix, './', to whatever it says in templateUrl which makes it impossible to write an address.
Answer: Yes, You can use prerendering with .Net Core & Angular 7.
Mark Pizszak has Asp.Net Core Angular Universal Starter Template which implements pre-rendering feature.
It's implementation contains many details. Look for BuildPrerenderer extension method and HomeController for .Net Core Side
public async Task<IActionResult> Index () {
    var prerenderResult = await this.Request.BuildPrerender ();

    this.ViewData["SpaHtml"] = prerenderResult.Html; // our <app-root /> from Angular
    this.ViewData["Title"] = prerenderResult.Globals["title"]; // set our <title> from Angular
        this.ViewData["Styles"] = prerenderResult.Globals["styles"]; // put styles in the correct place
        this.ViewData["Scripts"] = prerenderResult.Globals["scripts"]; // scripts (that were in our header)
        this.ViewData["Meta"] = prerenderResult.Globals["meta"]; // set our <meta> SEO tags
        this.ViewData["Links"] = prerenderResult.Globals["links"]; // set our <link rel="canonical"> etc SEO tags
        this.ViewData["TransferData"] = prerenderResult.Globals["transferData"]; // our transfer data set to window.TRANSFER_CACHE = {}
    ...

    return View();
}

BuildPrerender
 public static async Task<RenderToStringResult> BuildPrerender(this HttpRequest request) =>
        // Prerender / Serialize application (with Universal)
        await Prerenderer.RenderToString(
            "/",
            request.HttpContext.RequestServices.GetRequiredService<INodeServices>(),
            new System.Threading.CancellationTokenSource().Token,
            new JavaScriptModuleExport(request.HttpContext.RequestServices.GetRequiredService<IHostingEnvironment>().ContentRootPath + "/ClientApp/dist/main-server"),
            $"{request.Scheme}://{request.Host}{request.HttpContext.Features.Get<IHttpRequestFeature>().RawTarget}",
            request.HttpContext.Features.Get<IHttpRequestFeature>().RawTarget,
            // ** TransferData concept **
            // Here we can pass any Custom Data we want !
            // By default we're passing down Cookies, Headers, Host from the Request object here
            new TransferData
            {
                request = request.AbstractRequestInfo(),
                thisCameFromDotNET = "Hi Angular it's asp.net :)"
            }, // Our simplified Request object & any other CustommData you want to send!
            30000,
            request.PathBase.ToString()
        );

In your Index View.cs you need
@Html.Raw(ViewData["SpaHtml"])

In Angular Side (boot.server.ts)
import { createServerRenderer } from 'aspnet-prerendering';
export default createServerRenderer((params) => {

// Platform-server provider configuration
const setupOptions: IEngineOptions = {
  appSelector: '<app-root></app-root>',
  ngModule: AppModule,
  request: params,
  providers: [
   // Optional - Any other Server providers you want to pass
   // (remember you'll have to provide them for the Browser as well)
  ]
};

return ngAspnetCoreEngine(setupOptions).then(response => {

    // Apply your transferData to response.globals
    response.globals.transferData = createTransferScript({
      someData: 'Transfer this to the client on the window.TRANSFER_CACHE {} object',
      fromDotnet: params.data.thisCameFromDotNET // example of data coming from dotnet, in HomeController
    });

    return ({
      html: response.html, // our <app-root> serialized
      globals: response.globals // all of our styles/scripts/meta-tags/link-tags for aspnet to serve up
    });
  });
});


Why is suggested not to use symlink for sites/all and sites/default?

Question: The status report for Pantheon (Drupal 7) says that sites/all sites/default and sites/default/settings.php is not a symbolic link, and it is considered as best practice. Why?
Answer: You'd have to ask Pantheon to be 100% sure (they even did the initial development of the module). However, the warning message in response to a situation where sites/all is a symbolic link, is:

Avoid changing Drupal's site structure; remove the symbolic link and recreate sites/default.

So I think it's safe to assume this is just warning you not to mess with the structure of a Drupal site, which would probably cause problems or unexpected results when updated in future.
Comment: Yes, given the warning message, it seems the suggestion is not deleting the directories created when installing Drupal.


Resposta de ajax repete a de outra requisição e a página nem é a mesma

Question: O cenário é o seguinte: tenho um ajax que fica esperando resposta do servidor em Java na porta 2336 igual ao Hotmail, e, assim que tem atualização, o Java retorna resposta e fecha a requisição HTTP aberta. Depois o javascript pega a resposta e executa o que quer que seja e abre novamente outra requisição para esperar novamente por novas atualizações. Quando eu tenho que mandar alguma coisa para o servidor eu mando para o PHP pra porta 80, normalmente em outra requisição, e o PHP retorna a resposta se foi bem sucedido ou não. Até ai tudo OK, o problema é que se a requisição de sincronia com o Java na porta 2336 está aberta e eu mando alguma coisa para a porta 80 quando chega algum aviso de autalização do Java a resposta é a mesma da do PHP. Em seguida, se eu não tiver enviado nada para o PHP novamente, mostra a resposta do Java normalmente.
Alguém tem ideia do que pode estar acontecendo?
As funções são as seguintes:
function sincronizar() {
    ajax("http://" + window.location.hostname + ":2336", "POST", "Id=Anderson", executaResposta, "");
}

function controle() {
    ajax("php/controle.php", "POST", "Comando=ID", "containerFiltragemEntregas", "");
}

function ajax(endereco, metodo, dados, alvo, distracao) {
    xmlhttp = new XMLHttpRequest();
    if (distracao != "") {
        centralizaElemento(distracao);
        mostraElemento(distracao);
    }
    if (typeof(alvo) == "string") {
        elemento(alvo).innerHTML = "";
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var retorno = xmlhttp.responseText.trim();
            mostraAlerta(retorno + "\r\n\r\n" + metodo);
            if (typeof(alvo) == "function") {
                alvo(retorno);
                } else {
                    elemento(alvo).innerHTML = retorno;
            }
            if (distracao != "") {
                centralizaElemento(distracao);
                escondeElemento(distracao, 2000);
            }
        }
    }

    if (metodo == "GET") {
        xmlhttp.open("GET", endereco + "?" + dados, true);
        xmlhttp.send();
    } else if (metodo == "POST") {
        xmlhttp.open("POST", endereco, true);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.send(dados);
    }
}

function executaResposta(resposta) {
    var respostaSeparada = resposta.split("|");
    var comandoSeparado;
    if (respostaSeparada[0] == "01") {
        if (respostaSeparada[1] == "01") {
            comandoSeparado = respostaSeparada[3].split("&");
            if (respostaSeparada[2] == "05") {
                alertaEntrega("containerEntrega" + comandoSeparado[0]);
            } else if (respostaSeparada[2] == "04") {
                escondeElemento("containerEntrega" + comandoSeparado[0]);
            } else {
                normalizaEntrega("containerEntrega" + comandoSeparado[0]);
            }
            elemento("entregaSituacao" + comandoSeparado[0]).innerHTML = comandoSeparado[1];
        }
     }
    sincronizar();
}

Answer: O problema é que você usa um único objeto XMLHttpRequest. Eu posso estar errado, mas acho que para corrigir bastar tornar a sua variável xmlhttp local (pois ela é uma global implícita):
function ajax(endereco, metodo, dados, alvo, distracao) {
    var xmlhttp = new XMLHttpRequest();
    // ... O resto fica igual
}

Assim, cada chamada de ajax vai criar uma variável xmlhttp independente, e as requisições não vão interferir umas nas outras.
Comment: Era isto mesmo, sei que não é pra agradecer aqui mas resolveu o problema!
Comment: Fico feliz em ajudar :)


Why do all auto created urls in my multilingual site cause a Page not found?

Question: I have a multilingual site, using Drupal core 7.43 and the Redirect module, and the Pathauto module (and aliases are auto created without any problems).
Creating content translation I've got such problem: all auto created url aliases don't work.
When I change site language (as visitor) all seems Ok, I see all content has been translated. But if I (as a logged in user which is also an        administrator) try to open an article (for example), or any other translated content, I am always getting "Page Not Found". Auto created url leads nowhere.
What is wrong?
Note: When I am manually adding redirect (eg. from mysite/content/myarticle_1 to node/122), I am getting error "You are attempting to redirect the page to itself. This will result in an infinite loop." When I change article language from native to "All languages" then redirect could be saved and works as it should be.
Comment: How are you creating those urls for "auto created url aliases"? About your " if I try to open": is that as a logged in user, or a visiotor, which I assume mean "anonymous"?
Comment: I am just creating a translation for content as usual and aliases are auto creating from node:title,Yes, I am talking about logged in user,moreover,user with administrative rights(administrator).
Comment: well, If you mean auto creation pattern - it's   "content/[node:title]". That's all. This is configuration by default. By default there wasn't Redirect module installed in my site installation. I've added Redirect by myself. Then recreated few content translations and problem leaves the same.
Comment: Do you have the [Pathauto](https://www.drupal.org/project/pathauto) module enabled or not?
Comment: What I'm figured out. When I am manually adding redirect(eg. from:mysite/content/myarticle_1 to: node/122) I am getting error "You are attempting to redirect the page to itself. This will result in an infinite loop." When I change article language from native  to "All languages"  then redirect could be saved and works as it should be.
Comment: Yes, Pathauto module is enabled from the box. Aliases are auto created without any problems but then they don't work. That is the problem.
Answer: Check your configuration at Configuration -> Languages -> detection and selection: the order specified there could be what explains the current behaviour in your site.
You'd have to experiment a bit with what the exact order in your case should be. In my experience, I often get these kind of issues to work by using an order like 'URL, Default, User', and not something like 'Default, URL, User'. It could well be that that is all that's needed here ... So try to experiment a bit with the various combinations in this order to see if it helps.
Note: Debugging is the art of taking away all possible causes of a problem. So sorry upfront if this answer turns out to not be the solution.


Why child process only keeps the old version of variable after I re-clarify it?

Question: Why child process only keeps the old version of variable after I re-clarify it(with the same name) ?
Hi, I just tried to run the following code
#include <iostream>
#include <unistd.h>
using namespace std;
int main() {
    int a = 3;
    for (int i = 0; i < 3; ++i) {
        cout << getpid() << " " << a << endl;
        int a = 0;
        if (fork() == 0) {
            continue;
        }
        break;
    }
    wait(0);
    exit(0);
}

The output is
11470 3
11471 3
11472 3

Does anybody know why the output is not 0?
Comment: Do not tag C for C++ questions.
Answer: The scope of the 2nd instance of a, which is initialized to 0, starts with its initialization and extends to the end of its block.
Your cout statement appears before the 2nd instance of a is declared, and the referenced a is the first one, the one that gets initialized to 3.
int a=0; declares a different variable named a, it has no effect on the first variable named a.
This has nothing to do, whatsoever, with fork or child processes. If you get rid of the fork, execute a simple loop three times, declare int a=0; the same way, as in the shown code, and with cout appearing beforehand, this will produce the same output.
Answer: Your code declares a new variable a. To assign a new value to existing variable, do this instead:
  // int a = 0;  << don't do that
  a = 0;

Answer: In the for loop you use int a = 0; , which will create a new variable in the for loop's block, rather than modify the variable a declared outside.


How to add an EventListener to a moiveClips/Sprites's scaleX change event?

Question: How can i trigger an event for the scaleX property change of the movieClip or Sprite in Flash AS 3.
Answer: For Example: CustomSprite.as
package view {
import flash.display.Sprite;
import flash.events.Event;
import events.ScaleChangeEvent;

public class CustomSprite extends Sprite {

    override public function set scaleX(value:Number):void {
        super.scaleX = value;
        dispatchEvent(new ScaleChangeEvent(ScaleChangeEvent.SCALE_CHANGED));
    }

    public function CustomSprite() {
        super();
    }

    override public function dispatchEvent(event:Event):Boolean {
        if (willTrigger(event.type)) {
            return super.dispatchEvent(event);
        }
        return true;
    }
}}

ScaleChangeEvent.as
package events {
import flash.events.Event;

public class ScaleChangeEvent extends Event {

    public static const SCALE_CHANGED:String = "scaleChanged";

    public function ScaleChangeEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false) {
        super(type, bubbles, cancelable);
    }

    override public function clone():Event {
        return new ScaleChangeEvent(type, bubbles, cancelable);
    }

    override public function toString():String {
        return formatToString("ScaleChangeEvent", type, bubbles, cancelable, eventPhase);
    }
}}

Test.as
package {
import flash.display.Sprite;
import flash.events.Event;
import view.CustomSprite;
import events.ScaleChangeEvent;

public class Test extends Sprite {

    public function Test() {
        addEventListener(Event.ADDED_TO_STAGE, addedToStageListener, false, 0, true);
    }

    private function addedToStageListener(event:Event):void {
        removeEventListener(Event.ADDED_TO_STAGE, addedToStageListener);

        var customSprite:CustomSprite = new CustomSprite();
        customSprite.addEventListener(ScaleChangeEvent.SCALE_CHANGED, scaleChangedListener, false, 0, true);
        customSprite.scaleX = 0.2;
    }

    private function scaleChangedListener(event:ScaleChangeEvent):void {
        trace(event.target.scaleX);
    }
}}


Evaluate $\sum\limits_{k=1}^{255}\sqrt[4]{k+1}-\sqrt[4]{k}$

Question: Evaluate $\sum\limits_{k=1}^{255}\sqrt[4]{k+1}-\sqrt[4]{k}$
Answer 3
I tried writing it in the formula but I always have a $\sqrt[4]{255}$ that I can't do anything with
Answer: The author of the problem meant for the "+" in the middle to be a "-". Otherwise it's not true. How do I know?
The 4th root of 16 is 2; so the 16th term contains both that and the 4th root fo 17, which is larger, so the sum is at least 4.
Oh...I see. You've changed the sign now. Well, that's easy;
The sum looks like this
$(B-A) + (C-B) + ... + (Q - P)$
All the terms cancel except the first and last, $A - P$. The first is
the $A =$ 4th root of 1, which is 1. The last is the fourth root of 256, which is 4. And $4 - 1 = 3$.
Comment: Sorry that was a mistyping
Answer: Hint:
A more general concept is called telescoping sum.
With that, you would also be able to give an answer to the following exercise:
$$
\sum\limits_{k=1}^{2016}\sqrt[5]{k+1}-\sqrt[5]{k}=?
$$


Deriving the city and state from the location Facebook permission in Laravel 4

Question: I am trying to separate out the city and state from the location array object from Facebook in Laravel.  Before when I did this, I simply tried something similar to what I am trying in my Oauth2 Controller:
$citystate = $user['location'];
$citystate2 = $citystate['name'];
$split = explode(", ", $citystate2);
$city = $split[0];
$state = $split[1];

In the provider file, Facebook.php, I have this:
'location' => $user->location

However, when I run this, I get the error:
Use of undefined constant name - assumed 'name'

So, my question is, how do I access the "name" portion of the location array object.  Thank you for your help!
Answer: At first, you should json_decode (if it's a json string) like
$userArray  = json_decode($user, true);

So, you can use it like an array
$citystate = $userArray['location'];

Also you can check if the $user is already an array or not using
if(is_array($user) && array_key_exists('location', $user)) {
    // ...
    $citystate = $user['location'];
    // ...
}

Then you'll get an array like this
array (size=2)
 'id' => string 'xxx' (length=15) // xxx = digits
 'name' => string 'Sylhet' (length=6)

Update : $user['location'] is an object :
object(stdClass)#180 (2) { ["id"]=> string(15) "114952118516947" ["name"]=> string(25) "San Francisco, California" }

So, it should be :
$citystate = $user['location'];
$citystate->name;

Comment: I get this error when I do this:

json_decode() expects parameter 1 to be string, array given
Comment: Then it's already an array, no need to `json_decode`, try `var_dump($user)` and see what you get ?
Comment: This is the output for the location object ($user['location']):

object(stdClass)#180 (2) {
  ["id"]=>
  string(15) "114952118516947"
  ["name"]=>
  string(25) "San Francisco, California"
}
Comment: Ok, I figured it out.  I just had to use the location->name arrow attribute.


Normalization of data

Question: Generally the data is normalized with 0 mean and unit variance. Is it mandatory to use this method? Can I normalize data by simply dividing it with the mean of data (which is another normalization technique in data mining)?
Thanks in advance,
Comment: Welcome to CV. You will need to describe your question in more detail if you hope to get an answer. What is the objective of your project? What is your data? Etc..
Comment: What purpose does the normalization have? It will depend on that what is "required" (if anything is required, at all).
Comment: the data is about some catchment descriptors (Area, Mean elevation, NDVI etc)
Answer: What normalizing does is usually eliminating the effect of units. For example if you have a measurement in cm for example 1cm then it is .01m and .001km. Now assume you have another measurement for example weight, simple 1km, then it is .001ton and so on. Now the goal of analysing is comparing these two measurements. Obviously you cannot compare weight and height directly, then we have to find a way to normalize data in order to remove the measurements and make them comparable. On the other hand if you use very small units then it is difficult to cope with computations. Moreover, normalizing needs to provides you with some simplicities, for example saying $\frac{x-\mu}{\sigma}$ is preferable in statistics because in many cases the target distribution tends to Gaussian that this king of normalizations helps a lot. Another example is linear regression, if you normalize data to have a mean zero, then you basically removed the intercept and simplified the computation process a lot.
To sum up, you can use any kind of normalization you like but need to keep in mind that normalizing must give you something more than what you have already.
PS: there is not a consensus among statistician about normalizing. Some of them recommend that and some of them are against that.
Comment: @MUQ if this answer completely answers your question then click on the green tick to close the topic.

Normalization of data


OpenAPI generator: wrong format for the example value of date datatype. Is it possible to customize?

Question: I am using openapi-generator of the latest version (4.2.2) for generation of Java Spring API. Configuration looks like this:
openApiGenerate {
    generatorName = "spring"
    inputSpec = "${projectDir}/src/main/resources/api/users-spec.yaml"
    outputDir = "${buildDir}/generated/open-api"
    apiPackage = "com.example.accounts.api"
    invokerPackage = "com.example.accounts.handler"
    modelPackage = "com.example.accounts.model"
    modelNameSuffix = "Json"
    configOptions = [
            delegatePattern: "true"
    ]
}

I found out that definitions containing datatypes of date with example values produce differently formatted values in the output Java models.
definitions:
  User:
    properties:
      birthday:
        description: Date of birth
        type: string
        format: date
        example: "2020-01-01"

The generated model is:
  @ApiModelProperty(example = "Wed Jan 01 03:00:00 MSK 2020", value = "Date of birth")
  @Valid
  public LocalDate getBirthday() {
    return birthday;
  }

After the creation of swagger ui with springfox (2.9.2) I am having an example request as {"birthday": "Wed Jan 01 03:00:00 MSK 2020"}. It is confusing because a standard Jackson date deserializer cannot deserialize such value. Can I have an example value in yyyy-mm-dd format?
Comment: I have the same problem...
Comment: Same problem....
Answer: i found a solution here
birthday:
    description: Date of birth
    type: date
    format: yyyy-mm-dd
    example: "2020-01-01"

Comment: If your solution is not yours, you should share the link in a comment section.


Prove that $f$ is closed if and only if: exist $V \subset Y$ open set such that $y \in V$ and $f^{-1}(y)\in V$.

Question: Let $f: X \longrightarrow Y$ be a continuous function between two topological spaces. Prove that $f$ is closed if and only if: for every $U\subset X$ and for every $y\in Y$ such that $f^{-1}(y)\in U$, there exists an open set $V \subset Y$  such that $y \in V$ and $f^{-1}(y)\in V$.
Comment: $f^{-1}(y)$ is a subset of $X$, so I guess you mean $f^{-1}(y)\subset U$. Now $V$ is a subset of $Y$, so how is $f^{-1}(y)\subset V$?
Comment: $f^{-1}(y) \in V$ makes no sense, $f^{-1}(y)$, more properly denoted as $f^{-1}[\{y\}]$, is a subset of $X$, not a member of some subset of $Y$. I gave a correct formulation in my answer.
Answer: The correct formulation should be:

$f$ is closed iff for all $y \in Y$ and for every open set $U \subseteq X$ such that $f^{-1}[\{y\}] \subseteq U$, there exists some open set $V \subseteq Y$ such that $y \in V$ and $f^{-1}[V] \subseteq U$.

This is true regardless of continuity of $f$ (a map can be closed without being continuous).
Note that this is a sort of dual to continuity, using fibres (inverse images of singletons).
For normal continuity we have that for every $x \in X$ and every open neighbourhood $V$ of the forward image $f(x)$ we have some open $U$ that contains $x$ and such that $f[U] \subseteq V$.
In this criterion for closedness we take an open neighbourhood of the fibre of $y$ (so going back instead of forward) and ask for a neighbourhood of that point whose inverse image stays inside the given neighbourhood, instead of the forward image.
It's a useful criterion to think about closed maps in this way, especially if you're working with so-called perfect maps (closed, continuous, surjective and fibres are compact) and preservation of properties under those maps.
That's where I first learnt about it.

If $f$ is closed, then given any open set $U$ in $X$ with $f^{-1}\big[ \{ y \} \big] \subseteq U$, we see that $X \setminus U$ is closed in $X$, and so $f \big[X\setminus U \big]$ is closed in $Y$, and we can define
  $V \colon= Y \setminus f \big[ X \setminus U \big]$, which is then open.
Then $y \in V$, because if $y \not\in V$, this would mean $y \in f \big[X\setminus U \big]$, and  so $y=f(p)$ for some $p \in X \setminus U$, but this $p$ cannot be in $f^{-1}\big[ \{y\} \big]$ since  $p \notin U$.
Also $f^{-1}[V] \subseteq U$: if $p \in f^{-1}[V]$, then $f(p) \in V$, so $f(p) \notin f \big[X \setminus U \big]$, so $p$ cannot be in $X \setminus U$, so must be in $U$, as required.
If $f$ obeys the condition as stated, $f$ is closed:
Suppose $C$ is closed in $X$ and let $y \notin f[C]$. The latter means that $f^{-1} \big[ \{ y \}\big] \subseteq U$, where $U \colon= X\setminus C$, and so we have an open set $V$ of $Y$ such that $y \in V$ and
  $$ f^{-1}[V] \subseteq U = X \setminus C,$$
  which says that $V$ misses $f[C]$ entirely. So $y$ is an interior point of $Y \setminus f[C]$, making the latter set open and thus $f[C]$ closed.
Comment: does our map $f \colon X \rightarrow Y$ necessarily have to be surjective for this iff condition to hold? If so, can you please modify your post so as to state (and prove) the result in its full generality?
Comment: @SaaqibMahmood No, surjectivity is never used. It also was not part of the OP's question.


Handlebars doesn't seem to call my controller function

Question: I have a property on my controller, isLogin, bound to a handlebars conditional, {{#unless isLogin}}. But it doesn't seem to activate the function when the template is rendered. I inserted a console.log statement and that doesn't show up in the console either.
I have an application template like this:

      {{#unless isLogin}}

{{link-to "Classrooms" "classrooms" class="menu-item pure-menu-link"}}

      {{/unless}}

      {{outlet}}

And a controller like this:
import Ember from 'ember';

export default Ember.Controller.extend({
  isLogin : function(){
    console.log("isLogin called");
    return true;
  }

});

Can you see what is wrong? Thanks
Answer: Maybe you should make isLogin into a property, like the following:
// controllers/application.js

import Ember from 'ember';

export default Ember.Controller.extend({

  isLogin: function(){
    console.log("isLogin called");
    return true;
  }.property()

});

(see jsbin)
Answer: I think your way of implementation is wrong.
You should do it in below way - isLogin should be a variable in your controller and you can change the value of this variable in any controller functions like init(). As below -
export default Ember.Controller.extend({
isLogin: false,
init:function()
    {
        this._super();
        this.set('isLogin',true);

    }
});

then you can use this variable in your Unless inside your template.
[Just a Note- I am calling this.super() in init method only because i don't want to override any of the original functionality of controller's init.]


How can I get processor/RAM/disk specs from the Linux command Line?

Question:
Possible Duplicate:
How to find out details about hardware on the Linux machine?

How can I get processor/RAM/disk specs from the Linux command Line?
Comment: Similar questions: http://serverfault.com/questions/48642/how-to-find-out-details-about-hardware-on-the-linux-machine http://serverfault.com/questions/3552/is-there-a-linux-equivalent-of-cpu-z http://serverfault.com/questions/107234/command-line-what-is-this-machine http://serverfault.com/questions/55834/determining-type-of-linux-machine http://serverfault.com/questions/77920/how-can-i-find-out-the-server-specs-in-unix http://serverfault.com/questions/5031/how-can-i-find-out-what-hard-disks-are-attached-to-a-linux-box and more
Answer: CPU

$ cat /proc/cpuinfo

Memory :

$ free
$ cat /proc/meminfo

HDD:

$ df -h
$ sudo fdisk -l
$ hdparm -i /dev/device (for example sda1, hda3...)
Comment: cat /proc/cpuinfo is brilliant, never knew about this. Thanks
Answer: lshw command is also really useful to get a lot of information about all the hardware !
Comment: `sudo lshw | less`
Answer: sudo dmidecode command will also give you more hardware info than you ever wanted.
Answer: hwinfo would be one way to do it.


D7 Form Builder and Comment Forms

Question: I need to create a post/comment structure almost exactly like what you're looking at right now: original post with comments, subsequent 'answer' posts with their own comments. In response, I'm displaying a views page with a custom path displaying the original post (content type) and the subsequent answers (also content types). The issue lies with printing comment forms for each of the following nodes.
So far, I'm attempting to use the Views PHP field to print the comment form and failing pretty hard. There is D7 comment form doesn't submit relating to this, and Nikit's solution did produce a comment form on demand. However, this form does not submit or preview, submission just redirects the user to the node's comment reply page. Even now I do not understand how this method of calling drupal_get_form() works with two arguments.
So I turned to the trusty Drupal API to reference the drupal_get_form() function and saw that it doesn't take two arguments and returns drupal_build_form() instead. I thought that calling drupal_build_form() straight up might be more appropriate, since from what I could gleam off of the scarce user feedback said I needed to use a form_state['redirect'] of some sort to get users back to the original node page they posted their comments from. As expected however, everything I try returns a pile of errors and gets me nowhere.
The one spot of success was with the Commentsblock module that allowed me to place a real live comment form on a page and actually have the stupid thing submit a comment. While this works for the main content, I'm still at a loss for the subsequent 'answer' comments/forms. In ripping through the source code for the module I discovered comment_node_page_additions($node);, but this does not turn out any valid results either.
There are so many questions here:

How does one actually USE the Forms API (and to print comments)?
Should I be doing this in a .tpl file instead of Views?
Where does the second argument of drupal_get_form() go?
What exactly is the difference between drupal_get_form and drupal_build_form and how are they used?
Is $form_state['redirect'] called before either of these API calls or after?

This might seem like 'too much' of a question for a single thread, but I'm tired of posting partial questions and getting partial answers. In the interest of education, I would like to build some sort of tutorial either on Drupal.org or elsewhere so that this information can be made available to others in the same situation. Obviously I am not the best person to undertake this due to my massive lack of understanding, but maybe, just maybe with your help this can become a reality.
Answer:
If you select the 'forms' tag and select its mini menu option 'info', you will see a link to the Drupal pages for the form API and a great basic explanation on how it is used.
You should not use PHP in the view. PHP in content of any sort presents a security risk. The best place to do this is in a custom module.
The form API provides documentation on both.
$form_state is used as central storage for all information about the form. Any part of the $form_state array can be read and written to by any function at any time.

D7 Form Builder and Comment Forms


SQL Server Transpose / Unpivot All columns of the Table

Question: I'm trying to perform a Transpose for all the column table using UNPIVOT in SQL Server but with no results
Here is my table

ManufacturerID
1
2
3
4

Manufacturer
ABC
KW
MC
TZ

Logo
URL1
URL2
URL3
URL4

The output desired

ManufacturerID
Manufacturer
Logo

1
ABC
URL1

2
kw
URL2

3
MC
URL3

4
TZ
URL4

How could I achieve this result using UNPIVOT?
My attempt:
SELECT [ManufacturerID], [Manufacturer], [Logo] FROM ( SELECT [Column1] , [Column2],[Column3],[Column4],[Column5] FROM [TestFormation].[dbo].[IN_Manufacturer] ) unpivot ([ManufacturerID] FOR Name_ToDrop1 IN ([Column2],[Column3],[Column4],[Column5] )) AS p1 unpivot ([Manufacturer] FOR Name_ToDrop2 IN ([Column2],[Column3],[Column4],[Column5] )) AS p2 unpivot (Logo] FOR Name_ToDrop3 IN ([Column2],[Column3],[Column4],[Column5] )) AS p

Comment: FYI, rather than [deleting](https://stackoverflow.com/questions/73106646/how-to-transpose-all-the-table-using-the-first-column-as-the-column-names-in-s) your question, there is an [edit](https://stackoverflow.com/posts/73106646/edit) feature
Comment: If you're in PowerBI (I assume that's what you mean by "BI"), then I would likely suggest that you should be (un)pivoting in PowerBI, not the SQL layer. Though if you normalise your design, that would be an even better solution; then you don't need to unpivot.
Comment: What have you tried so far?
Comment: You say you've attempted using `UNPIVOT` too; what was that attempt? Why didn't it work? If you got no results (no rows?) then that likely isn't the `UNPIVOT` but your `WHERE` or `JOIN`s filtering out the data.
Comment: Sounds like you need both a pivot and an unpivot
Comment: It would be helpful if one of you guys could show a specific code to manage to do that,
Comment: I think i have to make a mix between Pivot and Unpivot using also some self join if i'm not wrong, but i don't know where to start to make it
Comment: Again, there is an [edit] feature, @Rahim ...
Answer: As mentioned in the comments, you need to both unpivot and pivot your data here. Hopefully the reason you want to do this is to fix your design; if it isn't make it so that it is. You design is poor, and denormalised (what happens when you need a 5th or 6th column for example?).
I don't use the PIVOT and UNPIVOT operators here, however, but use a VALUES table construct and conditional aggregation; both are far more versatile than the restrictive operators.
This gives the following solution:
SELECT UP.Col AS ManufacturerID,
       MAX(CASE V.ManufacturerID WHEN 'Manufacturer' THEN UP.VaL END) AS Manufacturer,
       MAX(CASE V.ManufacturerID WHEN 'Logo' THEN UP.VaL END) AS Logo
FROM (VALUES('Manufacturer','ABC','KW','MC','TZ'),
            ('Logo','URL1','URL2','URL3','URL4'))V(ManufacturerID,[1],[2],[3],[4])
     CROSS APPLY (VALUES(1,[1]),(2,[2]),(3,[3]),(4,[4]))UP(Col,Val)
GROUP BY UP.Col;

Based on the comments it seems you "have" to use UNPIVOT and PIVOT; I'm not sure why and I suggest against it, but if you "must" then it would look like this:
SELECT P.Col AS ManufacturerID,
       P.Manufacturer,
       P.Logo
FROM (SELECT ManufacturerID,
             [1],
             [2],
             [3],
             [4]
      FROM (VALUES('Manufacturer','ABC','KW','MC','TZ'),
                  ('Logo','URL1','URL2','URL3','URL4'))V(ManufacturerID,[1],[2],[3],[4]))YT
UNPIVOT (
    Val FOR Col IN ([1],[2],[3],[4])) UP
PIVOT (MAX(Val)
       FOR ManufacturerID IN (Manufacturer,Logo)) P;

Personally, I think this is pretty confusing to look at.
Obviously the sample data in both solutions would be replaced by your table, the above just use a VALUES table construct in the absence of DDL and DML in the question.
db<>fiddle


Existe alguma forma de bloquear a renderização de um determinado componente no React?

Question: Preciso bloquear a renderização de um certo tipo de componente, por exemplo:
{props.children}

Preciso capturar o componente que pode ser passado no children e bloquear sua renderização. Se eu quiser bloquear a tag p, como seria a forma de fazer isso? Existe alguma forma melhor de fazer isso?
Comment: Você deseja bloquear assumindo que uma certa condição seja satisfeita? Poderia, por favor, detalhar um pouco mais a sua pergunta? :)
Comment: apenas não renderizar essa componente. Independente de condição.
Comment: Então só não o coloque na renderização.
Comment: então, a principio não tenho como controlar qu seja passado esse componente. Por isso a questão...
Answer: Se você desejar filtrar algum elemento da prop children do React, você precisará usar a API React.Children:

https://reactjs.org/docs/react-api.html#reactchildren

Você pode, então, usar o método React.Children.toArray() para criar um array com base na propriedade children e filtrar somente os elementos que você desejar renderizar.
Para isso, já que estamos lidando com array, é conveniente usarmos o método filter.
Abaixo deixo um exemplo:

function Container(props) {
  return (

Componentes renderizados:

      {React.Children.toArray(props.children).filter(
        (child) => child.type !== 'h2'
      )}

  )
}

function App() {
  return (
    <Container>

[h1] Este componente será renderizado.

[h2] Este componente NÃO será renderizado.

[h3] Este componente tanbém será renderizado.

    </Container>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))

Referência:

React.Children;
Array.prototype.filter.
Comment: Valeu, Luiz. Resolvi de outra forma, mas fica a dica. Obg :D
Comment: Legal! Posso saber como você fez? :)


htaccess -> site is not working work anymore

Question: With the htaccess below the site is working fine, but when i rewrite all extensions .php to no .php the site is not working anymore. So now i want to rewrite a few urls to no .php
How do i do that? i can only find parts wich rewrite all scripts
This is what i have
<code>RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

# remove trailing slash if not directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# remove index.php
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\ /(.*)index\.php/?([^\?\ ]*)
RewriteRule ^ /%1%2 [L,R=301]

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^\.]*)(\.php)?(\?*)$ index.php/$1$3 [L,QSA]
</code>
Answer: Solved :)
rewriterule ^untitled.php http://www.bijschipholparkeren.nl/untitled [R=301,L]


Next.js 13, Context API, conditional layouts and SEO optimization

Question: This question is related to my two previous questions on the subject :

NextJS 13 Context API and SEO optimisation
Conditional layout in Next 13

So, my objective is to have a Context API and different layouts based on auth state in a SEO friendly manner.
Now I have the following code :
My folder structure
/app
--Layouts
  --Auth.jsx
  --Main.jsx
--layout.jsx
--Context.jsx
--page.jsx

./layout.jsx
import AppWrapper from './Context.jsx';

export default function RootLayout({ children }) {
    return (

            <AppWrapper>
                {children}
            </AppWrapper>

    )
}

./Context.jsx
"use client";
import { createContext, useContext, useState} from 'react';
import Main from "./Layouts/Main.jsx";
import Auth from "./Layouts/Auth.jsx";

const Context = createContext();

export default function AppWrapper({children}) {
    const [isAuth, setAuth] = useState(false)
    return (
        <Context.Provider value={{
            isAuth: isAuth,
            setAuth: setAuth
        }}>
            {   !isAuth ?
                {children}
                :
                <Auth>{children}</Auth>
            }
        </Context.Provider>
    )
}

export function useAppContext() {
    return useContext(Context);
}

./Layouts/Main.jsx (Same for Layouts/Auth.jsx)
export default function Main({ children }) {
    console.log('children of main');
    return (
        <>

Im main

        {children}
        </>
    )
}

./page.jsx
'use client'
import { useAppContext } from './Context';
import Context from "./Context";

export default function Home() {
    const context = useAppContext(Context);
    return (
        <>

Im self

        <button onClick={() => context.setAuth(current => !current)}>Toggle</button>
        </>
    )
}

As you can see :

root layout is a server component
./Context.jsx is a client component
./Layouts are server components
./page.jsx is a client component

But the console.log in ./Layouts/Main.jsx is displayed on the browser console.
So :

Is it a client component ?
Does this makes the whole app client side rendered ?
How to optimize all of that ?
What am I missing ?
Comment: You have rendred `Main` directly inside `AppWrapper` which is a client component, so yeah, it's a client component. Only a component passed as part of `props` to a client component can be a server component. See https://nextjs.org/docs/getting-started/react-essentials#nesting-server-components-inside-client-components.
Comment: @YoussoufOumar So what i'm trying to do is basically impossible ? And i'm not speaking about using native nextjs layouts... I'll have to create separate urls for auth and not authed...
Comment: I would say you are worrying too much. When using Next.js, even client components are rendered on the server and hydrated on the client, whereas server components won't be hydrated. The difference between the two here resides in the amount of JavaScript sent to the browser for the hydration. See https://nextjs.org/docs/app/building-your-application/rendering for more.
Comment: @YoussoufOumar I'm not sure. If i go for what i showed here, all the app is going to be client side rendered, making it whole not SEO friendly. I can simply not accept that
Answer:
Is it a client component ?

Yes

Does this makes the whole app client side rendered ?

Yes

How to optimize all of that ?

Keep the auth state on server using cookies, display and revalidate layouts on server for each user.

What am I missing ?

Need to forget SPA architecture, Context API is nice but outdated when it comes to conditionally render meta-components/layouts. Its place is at root only passing children and used only on leaf components.


Align ProgressBar horizontal to top (remove gap)

Question: I'm trying to put a horizontal progress bar at the top of my frame. But there seems to be padding that I simply have been unable to remove. Any help?

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent">
<ProgressBar android:id="@+id/flv_progress_bar"
             android:layout_width="fill_parent"
             style="@android:style/Widget.Holo.ProgressBar.Horizontal"
             android:indeterminateOnly="true"
             android:layout_height="wrap_content"
             android:layout_gravity="top"/>
</FrameLayout>

Answer: Pork'n'Bunny's answer worked API level 16 and up devices. This solution worked in all devices.
Just push it by 6dp up in XML.
 <ProgressBar
        android:id="@+id/progressbar_Horizontal"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:layout_alignParentTop="true"
        android:layout_marginTop="-6dp" />

Comment: How robust would this be against changes in the default styles? Are they guaranteed to look and work the same for all eternity or could they theoretically replace them at any time with something where pushing it up 6 pixels would create problems (e.g. an invisible progress bar)?
Comment: This does not work on every device. On Galaxy S6, even with a `-6dp` top margin, white space above the progress bar is still visible.
Comment: a better solution is
Answer: from the looks of it, I think its caused by the image used in the default styling
style="@android:style/Widget.Holo.ProgressBar.Horizontal"

(the image I'm referring to is this one: @android:drawable/progress_indeterminate_horizontal_holo and @android:drawable/progress_horizontal_holo_dark )
These images have a lot of canvas background; therefore its showing this gap.
My recommendation:
use a custom image to style you PregressBar. One which doesn't have much canvas spacing.
Comment: This is ultimately the right answer. I'll have to edit a version of all of the holo drawable (9 patches) to get rid of the padding.
Answer: A complete solution to this problem would be as follows. Just in case if someone needs code fragments, this is what I did.

Copied all the 8 indeterminate horizontal progressbar drawables
Edited the drawables using some image manipulator and remove unnecessary paddings
Copied the drawable XML named progress_indeterminate_horizontal_holo.xml from android platform
Copied the style Widget.ProgressBar.Horizontal and its parents
Set the style and min_height manually in the layout

Here is the progress_indeterminate_horizontal_holo.xml
<animation-list
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">
<item android:drawable="@drawable/progressbar_indeterminate_holo1" android:duration="50" />
<item android:drawable="@drawable/progressbar_indeterminate_holo2" android:duration="50" />
<item android:drawable="@drawable/progressbar_indeterminate_holo3" android:duration="50" />
<item android:drawable="@drawable/progressbar_indeterminate_holo4" android:duration="50" />
<item android:drawable="@drawable/progressbar_indeterminate_holo5" android:duration="50" />
<item android:drawable="@drawable/progressbar_indeterminate_holo6" android:duration="50" />
<item android:drawable="@drawable/progressbar_indeterminate_holo7" android:duration="50" />
<item android:drawable="@drawable/progressbar_indeterminate_holo8" android:duration="50" />

Style resources copied to my local styles file.

And finally, set min height to 4dp in my local layout file.
<ProgressBar
    android:id="@+id/pb_loading"
    style="@style/Widget.ProgressBar.Horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:indeterminate="true"
    android:minHeight="4dp"
    android:minWidth="48dp"
    android:progressDrawable="@drawable/progress_indeterminate_horizontal_holo" />

Comment: Thanks Subin! I hasn't actually set about doing this yet because I wasn't sure how much beyond editing the one drawable would it take to do, now we all know. Thanks for sharing.
Comment: The question is about `?android:attr/progressBarStyleHorizontal` and not `@style/Widget.ProgressBar.Horizontal`
Answer: Came up with another solution since the drawable is working as intended in the screenshot. Just push it by 6dp up.
    mProgress = (ProgressBar) view.findViewById(R.id.fwv_progress);
    mProgress.animate().withLayer().yBy(-6.0f*getResources().getDisplayMetrics().density).setDuration(0).start();

Comment: It works only API level 16 and up.. Is there any way to fix for API 8 and above ?
Answer: I think the problem is with height attribute. try setting the layout height to some value
<ProgressBar
            android:id="@+id/progressBar"
            android:max="100"
            android:layout_width="match_parent"
            android:layout_height="2dp"
            style="@android:style/Widget.ProgressBar.Horizontal"
            />

Comment: If that is the case then you should change the drawables to customised ones in your styles file


If $f$ is entire and does not take values in $|w|\leq 1$, then $f$ is constant

Question:
Possible Duplicate:
Magnitude of differentiable complex function $f(z)$

I have the question

Let $f(z)$ be an entire function and assuming $f(z)$ does not take values in $|w|\leq 1$, show that $f(z)$ is identically constant.

I tried to prove with Liouville's theorem, but I couldn't find the correct implementation., because I did not understand the meaning of "$f(z)$ does not take values in $|w|\leq1$".  Could you help me please? If you can, could you give the proof?
Thanks.
Comment: If $f(z)$ does not take values in the unit disc, then it does not come arbitrarily close to $0$. What does that mean for $g(z)=\frac{1}{f(z)}$?
Comment: yes your right . ı got solution from there. thanks
Comment: **Picards theorem :** If $f$ is a non-constant entire function on $\mathbb{C}$ then then $f$ assumes all the values in $\mathbb{C}$ except possibly one value. Since your function misses out on all values inside the unit disc. It is automatically a constant function.
Answer: If $|f(z)|\not\leq 1$, then $|f(z)|>1$ for all $z\in \mathbb{C}$.  Take reciprocals of the inequality.  Then you should see how to apply Liouville to $\frac{1}{f(z)}$.


Separate A Static NSString For Loading Into An Array

Question: So following Apple's DocInteraction Sample here I put a static NSString to define some preloaded documents.  Now I need to load them into an NSArray in the viewDidLoad method.  If I put it into a for() statement, it says "expression result unused", and I know I could solve it by using documents[indexPath.row], but it's the viewDidLoad method.  So how do I forEach a static NSString for loading into the NSArray?
CODE (EDIT):
//Before @implementation

static NSString* documents[] =
{   @"Musette.pdf",
    @"Minore.pdf",
    @"Cantata.pdf",
    @"Finalé.pdf"
};
//In viewDidLoad

    if ( _icons == nil )
{

    _icons = [[NSMutableArray alloc] init];
    UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(0, 0, 200.0, 324.0)
                                                     cornerRadius: 18.0];
    for (NSUInteger i = 1; i <= 4; i++){

        UIGraphicsBeginImageContext( CGSizeMake(200.0, 324.0) );

        // clear background
        [[UIColor clearColor] set];
        UIRectFill( CGRectMake(0.0, 0.0, 200.0, 324.0) );

        // fill the rounded rectangle
        [path fill];

        UIImage *image = [UIImage imageNamed:@"ClearImage.png"];

        UIGraphicsEndImageContext();

        // put the image into our list
        [_icons addObject: image];
    }
}

[_gridView reloadData];

Comment: Odd that the code nowhere references your `documents` array.
Comment: EDIT: Code now works perfectly thanks to Denis' suggestion.  Thanks to all who answered.
Comment: I think it has something to do with apple's special documentWatcher class from the example.
Answer: I'm not sure I understand what you're asking completely:
for(NSString * myStr in _icons) {

This won't work because _icons == nil.  Why can't you create the strings before this line?
You also need to make this an NSArray.
Comment: Denis' answer was what I was looking for, thanks for the critique though!
Answer: C-arrays are not supported by the for-each modification of the for statement in Objective-C. So you have 2 choices here:

use ordinary for-statement cycle
for(int idx = 0; idx < KNOWN_DOCUMENTS_COUNT; ++idx) {
    ...
}
Create a custom subclass of the NSEnumerator and use it... however, I believe, this will be a big overhead for this case
Comment: Beautiful.  Thank you.  I will checkmark as soon as that dastardly time limit is through.
Answer: This makes no sense whatsoever:
if ( _icons == nil )
    {
        for(NSString * myStr in _icons) {

        _icons = [[NSMutableArray alloc] init];

You need to step back a bit and understand what you're doing.
Added
Still doesn't work.  What's wrong with this picture??
    _icons = [[NSMutableArray alloc] init];
    UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(0, 0, 200.0, 324.0)
                                                     cornerRadius: 18.0];
                for(NSString * myStr in _icons) {
        UIGraphicsBeginImageContext( CGSizeMake(200.0, 324.0) );

Comment: Check the code now, totally a typo, as that would have initialized an array 4 times!
Comment: Would never have initialized the array at all.
Comment: OK, check the most recent edit... it has been solved... and what's with the down vote?


Difference between gaussian and log-normal distribution

Question: I have a random variable say X that is a Gaussian distributed with mean equal to zero dB. When I convert it into linear domain, i.e from dB to linear, does it imply that the resulting variable is log-normally distributed?And if yes, would the mean of resulting log-normally distributed variable also be zero? I would be thankful if anyone clears my doubt.
Answer: Yes, the resulting distribution has a log-normal distribution. If $X$ is normally distributed, then $e^X$ has a log-normal distribution. Be careful however, your transformation is not just $\exp$, it must be $10^X$ or something like that, according to the definition of dB.
No, the mean of the resulting variable is not zero. It can't be zero as a log-normally distributed random variable is almost surely positive. However it's possible to determine its mean as a function of the parameters of the original gaussian distribution.
See https://en.wikipedia.org/wiki/Log-normal_distribution
Comment: I see. Since the mean in my case is defined in dB (0dB), do I need to convert it first into linear domain and then calculate the new mean of the log normally distributed variable based on the formula in the link that you provided?
Comment: Yes, but you'll also need the variance of the original variable.


parent page title on sub menu

Question: I am building a website where i generate a submenu based on my main navigation.
The structure looks like this:

Home
About
Work at

vacancies

contact

when you land on one of the level 1 pages, a submenu will appear in the sidebar with the children links of this page.
i want the title of the parent page to show above this menu.
also, on the vacancies page there's a overview of vacancies, and when you go to one of the detailed vacancies i want it to show
"Work at" and not "vacancies" in the submenu title.
i've tried alot of things but can't find the right solution for it.
Answer: The menu_block module with the patch in https://www.drupal.org/node/2809699 should work.
Note: you'll have to select the "Use the following as title" field to "Active trail's parent title" when configuring your block.

parent page title on sub menu


How to find & remove duplicates in data frames?

Question: I have the follwing data frame which happens to be NBA draft data:
<code> draft_year draft_round teamid playerid draft_from
 1961           1         Bos    Pol1      Nan
 2001           1         LA     Ben2      Cal
 1967           2         Min    Mac2      Nan
 2001           1         LA     Ben2      Cal
 2000           1         C      Sio1      Bud
 2000           1         C      Gio1      Bud
</code>
I would like to find & remove only those rows with duplicates in playerid. For obvious reasons, the remaining duplicates have a meaningful purpose and must be kept.
Answer: Try this
<code>## assuming df holds your data
df.unique <- df[!duplicated(df$playerid), ]
</code>