How to get height and width of image style?

Question: We have a custom module mymodule where we call mymodule_tokens so that we can assign custom token values from the current node. These custom tokens are used to insert values in the Article's MetaTag fields.
Problem
When fetching the default value based on an Image Style (e.g. medium), I cannot get the Height and Width based on the Configuration for the Image Style. How can I get the height and width from the Image Style?
What I have tried, but cannot get the height and width:
function mymodule_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];
  $node = $data['node'];
  $node_image = $node->field_image;
  $field_image_style = 'medium';

  if($node_image->isEmpty()) {
    $field_info = FieldConfig::loadByName('node', 'article, 'field_image');
    $image_uuid = $field_info->getSetting('default_image')['uuid'];
    $image = Drupal::service('entity.repository')->loadEntityByUuid('file', $image_uuid);
    $field_image_url = ImageStyle::load($field_image_style)->buildUrl($image->getFileUri());
    $image_style = ImageStyle::load($field_image_style)->getEffects()->getConfiguration();

    // Both give me error messages.
    $image_style_height = $image_style->get('height');
    $image_style_width = $image_style->get('width');
  }
  else {
    $field_image_url = $node_field_image->entity->getFileUri();
    $image_style = ImageStyle::load($field_image_style)->getEffects()->getConfiguration();

    // Both give me error messages.
    $image_style_height = $image_style->get('height');
    $image_style_width = $image_style->get('width');
  }

  foreach($tokens as $name => $original) {
    switch ($name) {
      case 'custom_image_url':
        $replacements[$original] = $field_image_url;
        break;
      case 'custom_image_height':
        $replacements[$original] = $image_style_height;
        break;
      case 'custom_image_width':
        $replacements[$original] = $image_style_width;
       break;
    }
  }

  return $replacements;
}

Error Message

Error: Call to a member function get() on array in mymodule_tokens()

When printing ImageStyle::load($field_image_style) using Kint this is what we get.

When printing $image_style, I get the following.

Using core or contrib tokens rather than custom tokens
Using the following tokens only work when there is a value added to the field_image field, but when the field_image is not populated, the token is not able to return the default image that is populated on the field's settings page.
[node:field_image:medium:height]
[node:field_image:medium:url]
[node:field_image:medium:width]

Comment: Everything under "image_scale_and_crop" is protected, so you won't be able to read those values. What are you trying to do, exactly?
Comment: Have you installed the Devel sub-module Kint and then did `ksm($image_style)` to show you the available methods? I doubt that the `$image_style` object holds the finalized image properties.
Comment: @leymannx i have updated the question with screenshots using `kint()` (same output when using `ksm()`). I can see that in the `'data'` array the width and height are there. I wonder if it has to do with being protected.
Comment: @Kevin The Image Style `medium` performs a scale and crop where `width => 400` and `height => 260`. I wanted to query that setting and use it to assign values to the custom tokens (see updated code) rather than hard coding the `400` and `260` in case those values are changed. Tokens such as `[node:field_image:medium:height]` does not return a value when the `field_image` is empty, hence the custom tokens.
Answer: If you wonder how to get the height/width of a rendered image style (not Image style configuration, but the result itself), here's how it's done :
<?php
use Drupal\image\Entity\ImageStyle;

$img_uri = $entity->field_picture->entity->getFileUri();
$image_style = ImageStyle::load('your_image_style');
// $build_url = $image_style->buildUrl($img_uri);
$build_uri = $image_style->buildUri($img_uri);
$image_factory = \Drupal::service('image.factory')->get($build_uri);

$height = $image_factory->getToolkit()->getHeight();
$width = $image_factory->getToolkit()->getWidth();

Comment: This is great. But .. If the image has not been generated beforehand, the $height and $width are 0 / 0 (because the styled image does not actually exist). This does create the correct URL, but the image is not generated until the path is visited.
Comment: You can check if the image has been generated with `file_exists($build_uri)`. `$image_style->createDerivative($img_uri, $build_uri)` will create the derivative file.
Answer: No Sssweat's answer inspired this.
I added this before if statement (if($node_image->isEmpty())) to get the height and width.
$image_style_config = (ImageStyle::load('medium')->getEffects()->getConfiguration());

foreach($image_style_config as $config) {
  if(isset($config['data'])) {
    if(isset($config['data']['height'])) {
      $image_style_height = $config['data']['height'];
    }
    if(isset($config['data']['width'])) {
      $image_style_width = $config['data']['width'];
    }
  }
}

Answer: You'll need to click on the Available Methods tab and see if there is an method for width and height.

When you click on it, searching for width or height should come up empty. I can tell this by looking at the ImageStyle Class.
But there will be a getEffects() method that you can use, which should contain the width and height.
$style = ImageStyle::load($field_image_style);

So do kint($style->getEffects());
I'll let you take it from here.

If you want to go the $image_style route then you can get the value with
$image_style[0]['1aa.......']['data']['width'];
$image_style[0]['1aa.......']['data']['height'];

PS:
I suggest you read my answer to What is easiest way to debug variables in nodes, views, blocks and page twig templates? to learn how to use kint properly.
Comment: If you see my answer below, i was able to iterate through it in a loop using the answer you provided.


Qual o nome do recurso/termo que expande um trecho de código entre chaves?

Question: Qual o nome do recurso que expande um trecho de código entre chaves?
Estou programando um arquivo .jsp mas a IDE não identifica as chaves, assim não consigo contrair o código.
Comment: Não sei se o nome tem alguma relevância, mas ele costuma se chamar *expand code* :)
Comment: porque não consigo minimizar o código entende? talvez o recurso não esteja instalado para a linguagem
Comment: Para contrair é *fold*.
Comment: @durtto Qual a ide que você está usando?
Comment: Alternativamente, faz parte do "code folding"
Comment: Como que chama a IDE ?
Comment: @MarlonTiedt, independente de IDE, quero saber o nome do termo entende?
Comment: https://en.wikipedia.org/wiki/Code_folding
Answer: O nome deriva do nome da funcionalidade que fecha o código, só que o nome dessa funcionalidade varia de IDE para IDE. Alguns nomes que eu já vi são:

Code Unfold, quando deriva de Code Folding.
Code Expand, quando deriva de Code-Collapsing.


Handling WebException with Queue

Question: I have a little C# project it send unique data with WebRequest on an internet site and get back a HttpWebResponse. Now I want to handle the situation with no internet connection or other thinks the data could not send or receive.
In my opinion its the best way to handle that with the Webexception in try/catch.
But its important on a Webexception, the program remember the action and try it again if the internet or the service is reachable again.
What is the best way in your opinion to realize that?
I read about Queue...
Maybe to put the action in the Queue if Webexception will throw and try it again if Service is reachable again?
Answer: Timer should work. When an exception is being thrown, reset the timer. When the interval occurs you can try to connect again
Answer: I think that a simple way is create a loop to call a boolean method, if inside this of this occurs an exception returns false and the loop continues
Answer: @Denis I found this question interesting and I had a go at it.
https://dotnetfiddle.net/2lx8FI

Push-based queue by converting a List<string> to an IObservable
sequence. Thread.Sleep controls how often an item is read from the
queue.
In case of WebException, we wait for "a while" and add the URL back to List<string>
Reading URLs from user input is just for testing purposes.

I hope it helps

Handling WebException with Queue


How do I find the location of the second largest number in a list? (Python)

Question: My first ever question on here!
The following line of codes asks if the largest number in the list seat_votes is located in position 0.
if seat_votes.index(max(seat_votes)) == 0:

Is there an easy way to ask this but for the second largest number in a list?
I'm thinking something similar to the large funtion on excel. So at a guess the code would look like the following.
if seat_votes.index(large,2,(seat_votes)) == 0:

Comment: Does this answer your question? [how to find position of the second maximum of a list in python?](https://stackoverflow.com/questions/23473723/how-to-find-position-of-the-second-maximum-of-a-list-in-python)
Comment: `max(enumerate(seat_votes), key=itemgetter(1))` will return tuple of index and value of max element in list. Imports: [`itemgetter()`](https://docs.python.org/3/library/operator.html#operator.itemgetter).
Comment: Python has a `sort` function, or just use `max` again on the remaining seats after eliminating the largest value from the list.
Comment: @OlvinRoght - That's a good technique for max and index, but it's not really addressing the question.
Answer: I will make the assumption that the list has at least two elements.
You can use the sorted function as suggested by others :
if sorted(seat_votes)[-2] == seat_votes[0]:

But if the maximum value is present multiple times in the input, it still considers the maximum value.
If you want to the second biggest unique, you can use sets :
if sorted(set(seat_votes))[-2] == seat_votes[0]:


Explanation regarding Gibbs Sampling

Question: I am new to MCMC and reading a intro paper regarding Gibbs sampling. However, there are two parts in the paper I cannot understand and get stuck. The first part is equation 2.3 in page 168. It says that if $X^{'}_{j}$ is drawn from the process of Gibbs sampling, $X^{'}_{j}\sim f(x|Y^{'}_{j}=y^{'}_{j})$. It further claims under "general conditions," the distribution of $X^{'}_{j}$ converges to $f(x)$ as $n\rightarrow\infty$. Can anyone help explain what these general conditions are and why/how this statement is true.
The second part is at the beginning of page 169, expression 2.9 says $\hat{f(x)}=\frac{1}{m}\sum^{m}_{i=1}f(x|y_{i})$, and the theory behind this equation is $E[f(x|Y)]=\int f(x|y)f(y)dy$. This confuses me because my understanding about monte carlo integration is that for example, $E[X]=\frac{1}{m}\sum^{m}_{i=1}X_{i}$ is true due to the law of large number that $\frac{X_{i}}{m}$ converges to $X_{i}\times p(X_{i})$ when $m\rightarrow\infty$. However, I don't see how equation 2.9 can be explained by the concept of monote carlo integration. Can anyone explain the intuition or math behind this equation? Thanks!
EDIT 1 (My Answer/Thought for Part 2)
I have thought about this question, and since no one responds yet, I will try my answer first and see whether someone has a better explanation. For the second part, instead of using $f(x|y_{i})$, let's focus on the density of a specific value $x^{a}$, which is $f(x^{a}|y_i)$. For simplicity, now assume $y_i$ is randomly drawn from a density $f(y)$ instead of $f(y|x_i)$ but the result could be generalized to $f(y|x_i)$. Both $f(x|y_i)$ and $f(y)$ are know distribution.
Now we first randomly draw a $y_i$ from $f(y)$ and once we have $y_i$, we further randomly draw a $x_i$ from $f(x|y_i)$. Suppose we do this process $n$ time, and $n\rightarrow\infty$. Given a specific $y^{a}$ and $x^{a}$, we do know the value of $f(x^{a}|y^{a})$, which is just the density of $x^{a}$ cnditional on $y^{a}$. In other words, by Monte Carlo integration, for a given set of $y_i$'s and $x^{a}$, we can dervive that $\frac{1}{n}\sum^{n}_{i=1}f(x^{a}|y_i)\approx\int f(x^{a}|y_i)f(y_i)dy_i=\int f(x^{a}|y)f(y)dy=\int \dfrac{f(x^{a},y)}{f(y)}f(y)dy=\int f(x^{a},y)dy=f(x^{a})$
We can do the same process to dervie $f(x^{b})$, $f(x^{c})$, and etc. In the end, we will have $f(x^{a})$, $f(x^{b})$, $f(x^{c})$, ..., which all together constrcut $f(x)$. Therefore, $\hat{f(x)}=\frac{1}{m}\sum^{m}_{i=1}f(x|y_{i})$.
Answer: For the convergence of the Gibbs sampler, the central condition is irreducibility: that is, the possibility to reach any part of the support of the target distribution (with density $g$) starting from any part of this support. If the chain is not irreducible, it will remain stuck in a subset of the support. If the chain is irreducible, then it is recurrent (and the Gibbs sampler convergent) since the stationary distribution is the joint target distribution.
Here are two results from our book (written with one of the authors of this "Gibbs for Kids" paper):

Theorem 10.8 For the Gibbs sampler, if the density $g$ satisfies the positivity condition, it is irreducible.

The "positivity condition" was introduced by Hammersley and Clifford (1970), imposing to the support of $g$ to be equal to the product of the conditional distributions used in the Gibbs sampler (for arbitrary conditioning elements). When it holds the joint density $g$ can be expressed in terms of the conditional densities as
$$
g(y_1,\ldots,y_p) \propto \prod_{j=1}^p \; {g_{\ell_j}(y_{\ell_j}|y_{\ell_1},
\ldots,y_{\ell_{j-1}},y_{\ell_{j+1}}^\prime,\ldots,y_{\ell_p}^\prime) \over
g_{\ell_j}(y_{\ell_j}^\prime|y_{\ell_1},\ldots,y_{\ell_{j-1}},
y_{\ell_{j+1}}^\prime,\ldots,y_{\ell_p}^\prime)}
$$
for every permutation $\ell$ on $\{1,2,\ldots,p\}$ and
every $y' \in \mathcal{Y}$.
Here is a counter-example where the support is made of two convex sets, for which the Gibbs sampler does not explore the entire support:

A second result due to Tierney (1994) is

Lemma 10.9 If the transition kernel associated with the Gibbs sampler is absolutely continuous with respect to the dominating
  measure, the resulting chain is Harris recurrent.

For the second part of the question, this is a special case of Rao-Blackwellisation. If the $y_i$'s are distributed from the stationary distribution, $f_Y$, then $$\mathbb{E}^Y[f(x|y_i)] =\int_\mathcal{Y} f(x|y_i)f_Y(y_i)\,\text{d}y_i = f_X(x)$$ This is also true when the $Y_i$'s are converging to this stationary distribution by virtue of the ergodic theorem (on averages).

Explanation regarding Gibbs Sampling


How to extract label text at button click

Question: So what I want to do is to extract the text from a label when a button is clicked. What I've got so far is the following:
    <asp:Label ID="lbl_carID" runat="server" Text="Label"></asp:Label>
    <asp:Label ID="lbl_ownerID" runat="server" Text="Label"></asp:Label>

    <asp:Button ID="btn_wishList" runat="server" Text="Add to wish list"  CssClass="btn" CommandArgument='<%= lbl_carID.Text.ToString() %>' OnCommand="btn_wishList_Command" />
    <asp:Button ID="btn_offer" runat="server" Text="Make Offer" CssClass="btn" CommandArgument='<%= lbl_ownerID.Text.ToString() %>' OnCommand="btn_offer_Command" />

I have also tried without the ToString() method, but it is not working. Also tried without the = after %. I am new to code insertion, so I guess it is something really small, but I cannot make it work. Any suggestions ?
EDIT: This is the code behind btn_offer_command. Both commands are identical at start, so I am posting the shorter code.
protected void btn_offer_Command(object sender, CommandEventArgs e)
    {
        string id = (string)e.CommandArgument;
        Session["ownerToBeOffered"] = id;
        Response.Redirect("LoggedInFeatures/MakeOffer.aspx");
    }

Comment: post the code for `btn_wishList_Command`
Comment: just posted the code, but for `btn_offer_Command` instead, as it is shorter.
Answer: I believe you cannot use <%= %> inside properties with a runat="server".
Try to pass the CommandName and check it in your handler.
Example
<asp:Label ID="lbl_carID" runat="server" Text="Labeddl1"></asp:Label>
<asp:Label ID="lbl_ownerID" runat="server" Text="Label1"></asp:Label>

<asp:Button CommandName="carID" CssClass="btn" ID="btn_wishList" OnCommand="btn_wishList_Command" runat="server" Text="Add to wish list" />
<asp:Button  CommandName="ownerID" CssClass="btn" ID="btn_offer" runat="server" Text="Make Offer" OnCommand="btn_offer_Command" />

And in your Code try something like the following...
    protected void btn_wishList_Command(object sender, CommandEventArgs e)
{
    if (e.CommandName == "carID")
    {
        //Do Something here
    }
}

protected void btn_offer_Command(object sender, CommandEventArgs e)
{
    if (e.CommandName == "ownerID")
    {
        //Do Something here
    }
}

Answer: place it somewhere in your code
[ExpressionPrefix("Code")]
public class CodeExpressionBuilder : ExpressionBuilder
{
    public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
       object parsedData, ExpressionBuilderContext context)
    {
        return new CodeSnippetExpression(entry.Expression);
    }
}

register in web.config under compilation section
<compilation debug="true" targetFramework="4.5.1" >
  <expressionBuilders>
    <add expressionPrefix="Code" type="WebApplication2.CodeExpressionBuilder"/>
  </expressionBuilders>
</compilation>

now you will be able to evaluate any code at that point as would expected by following construction
 <asp:Button ID="btn_offer" runat="server" Text="Make Offer" CssClass="btn" CommandArgument='<%$ Code: lbl_ownerID.Text %>' OnCommand="btn_offer_Command" />

Comment: Any other ideas that I may try ?
Comment: this property is Bindable so you can bind commandName in some iteration like structures by item name, if you are not using e.g. Repeater to print them dynamicaly, you just can set commandName at code behind in Page_Load event
Comment: also you can do something interesting with codeExpressionBuilders http://weblogs.asp.net/infinitiesloop/The-CodeExpressionBuilder
Comment: @Phantomazi check the updated answer, that might be exactly what you want


Classifying Surface Given a Triangulation.

Question: So I have a compact surface $M$ without boundary with a triangulation such that $q$ edges meet at each vertex.  I want to give possibilities for classifying $M$ for $3 \leq q \leq 6,$ and specify the number of vertices if possible.
My first attempt is to look at the Euler characteristic, $\chi(M) = V - E + F$.  Because each vertex is part of $q$ edges and each edge has two vertices in it, we have $E = \frac{q}{2}V$.  Similarly, because each face has three edges and each edge is part of two faces, we have $F = \frac{3}{2}E = \frac{3q}{4}V$.  Therefore, the Euler characteristic is $\chi(M) = \frac{4 + q}{4} V.$  Because $\chi(M) \leq 2$, this only makes sense for $q = 4$ and $V = 1$. Have I made some very silly mistake somewhere?  I have done the computation multiple times to check my work but can't seem to find anything.
Answer: The simplest triangulation to check for these is the tetrahedron, which has $q=3$, and $V=4$, $E=6$, $F=4$. It's then clear that while $ qV=2E $, the other relationship you posit cannot be correct: if there are $3$ edges for every face, and this has counted each edge twice, we should have $ 2E = 3F $, rather than vice versa as you have. We then have
$$ \chi(M) = V - \frac{q}{2}V + \frac{2}{3} \frac{q}{2}V = \left( 1-\frac{q}{6} \right) V. $$
Checking with the tetrahedron gives $(1-3/6)4 = 2$, so it's believable, at least!


How to prevent strange edits and why users approve it?

Question: Today I found some edits which is looking very strange made by the user https://magento.stackexchange.com/users/83709/deadly :
https://magento.stackexchange.com/review/suggested-edits/170024
https://magento.stackexchange.com/review/suggested-edits/170025
How to deal with that "improvements" and why some users approved it? Could someone stop them?
Comment: He is still doing same edits https://magento.stackexchange.com/review/suggested-edits/170312
Answer: @Siarhey Uchukhlebau
thanks for your information, we will look into it.
Deadly's edits does not improvement content. We will contact him.
Comment: Could you please contact Munesh one more time? :)


Searching in code of GitHub repositories

Question: How can I search in code of few GitHub repositories within a particular organisation?
Answer: IIUC, you could do this to search for code in all repositories of a given organization:
https://github.com/search?q=org%3A<ORG_NAME>+<STRING_TO_SEARCH>&type=Code
for example:
https://github.com/search?q=org%3Abroadcom+main&type=Code
https://github.com/search?q=org%3Aopenwrt+main&type=Code
To limit your search to specific repositories press Advanced Search
after opening above links and fill in In these repositories field.


$x^y y^x$ in more than one way

Question: I've submitted to OEIS the sequence consisting of numbers that can be written in more than one way as
$x^y y^x$ for integers $x,y$ with $1 < x \le y$.  The first $6$ examples are
$$ \eqalign{ 4^{16} \cdot 16^4 &= 8^8 \cdot 8^8 = 281474976710656 \cr
    3^{27} \cdot 27^3 &= 9^9 \cdot 9^9 = 150094635296999121\cr
 10^{80} \cdot 80^{10} &= 20^{50} \cdot 50^{20} \cr
 2^{324} \cdot 324^2 &= 8^{96} \cdot 96^8 \cr
 8^{144} \cdot 144^8  &= 16^{96} \cdot 96^{16} \cr
 16^{144} \cdot 144^{16} &= 32^{96} \cdot 96^{32} \cr}$$
I managed to find an infinite parametric family of solutions, generalizing the first example:
$$(2^{x+1})^{2^{x-k-1}} \cdot (2^{x-k-1})^{2^{x+1}} = (2^x)^{2^x} \cdot (2^x)^{2^x}\ \text{with}\ x = (k+1)  2^{k+2} - 1$$
Questions:

Can you find other infinite parametric families of solutions?
Is there any example that can be written in three or more ways?

[EDIT] This is now sequence A367001
Comment: In the first $2$ examples, one of the representations has $x=y$. In general, it may help to consider solving $(z^a)^{z^b} (z^b)^{z^a}=(z^c)^{z^c} (z^c)^{z^c}$, which is equivalent to solving $az^b+bz^a=2cz^c$. The first $2$ examples have $(z,a,b,c)$ equal to $(2,2,4,3)$ and $(3,1,3,2)$ respectively.
Comment: I was trying to find solution to the equation $(z^a)^{z^b}(z^b)^{z^a} = (z^c)^{z^c}(z^c)^{z^c}$ using the fact that is equivalent to solving $az^b+bz^a = 2cz^c$ as @GeoffreyTrang pointed out. Unfortunately I have brute forced for every possible value of $(a,b,c)$ in the range $a,b,c \in\{1,2,\dots,5000\}$ (where $a,b,c$ are not all the same number) using $z = 3$ and the only solution I found is exactly (1,3,2).. For $z > 3$ I didn't find any solutions of this form :(
Comment: I'm wondering if we can make use of the fact that $x^y y^x$ is the number of pairs of maps $[x] \to [y] \to [x]$. The question then becomes which finite sets can be expressed like this in more than one way (where we exclude singleton sets or course and disregard symmetric solutions). The comment by Geoffrey suggests that $[x]$ and $[y]$ itself will be sets of maps.
Comment: $nk^m+mk^n=p$ with $n,m,k,p\in \mathbb{N}$
Answer: Not a full answer, but some observations regarding the examples you have found and 2 new examples:
Consider the following examples:
$$
4^{16}\cdot 16^4 = 8^8\cdot 8^8
$$
$$
8^{144}\cdot 144^8 = 16^{96}\cdot 96^{16}
$$
$$
16^{144}\cdot 144^{16} = 32^{96}\cdot 96^{32}
$$
There is a clear recurrency here, in particular they are of the form:
$$
(2^{k})^{a}\cdot a^{2^k} = (2^{k+1})^b\cdot b^{2^{k+1}}
$$
and I have found two more! Namely:
$$
32^{1600}\cdot 1600^{32}=64^{1280}\cdot 1280^{64}
$$
$$
64^{1600}\cdot 1600^{64} = 128^{1280}\cdot 1280^{128}
$$
The pattern is now clear, and we can study it in order to generalize a possible new family of solutions. In particular I note that:

If $k$ is odd then $a$ and $b$ satistifes both the "consecutive"
equations $$ (2^{k})^{a}\cdot a^{2^k} = (2^{k+1})^b\cdot b^{2^{k+1}}
$$ $$ (2^{k+1})^{a}\cdot a^{2^{k+1}} = (2^{k+2})^b\cdot b^{2^{k+2}}
$$
Furthermore $\frac{a}{b} = 2$ in the first equation , $\frac{a}{b} =
\frac{3}{2}$ in the second and third, $\frac{a}{b} = \frac{5}{4}$ in
the fourth and fifth..
And if $(a,b)$ is a solution to the "$k$-th and $k+1$-th equations,
then they also satisfy: $$ b^2 = a\cdot
(2^{k})^{(\frac{a-b}{2^{k}})}\cdot 2^{-(\frac{b}{2^{k}})} $$ $$ b^2
= a\cdot (2^{k+1})^{(\frac{a-b}{2^{k+1}})}\cdot 2^{-(\frac{b}{2^{k+1}})} $$

For example, in the last two $(a,b) = (1600,1280)$ and:
$$
1280^2 = 1600\cdot (2^{5})^{(\frac{1600-1280}{2^{5}})}\cdot 2^{-(\frac{1280}{2^{5}})} = 1638400
$$
$$
1280^2 = 1600\cdot (2^{6})^{(\frac{1600-1280}{2^{6}})}\cdot 2^{-(\frac{1280}{2^{6}})} = 1638400
$$
Now, of course it seems that for $k = 7$ and $k = 8$, $\frac{a}{b}$ should be $\frac{9}{8}$, but zero positive integer solutions to
$$
b^2 = a\cdot(2^{7})^{(\frac{a-b}{2^{7}})}\cdot 2^{-(\frac{b}{2^{7}})}
$$
using $\frac{a}{b} = \frac{9}{8}$. I have also tried other fractions but I just can not found other solutions. I have also brute forced the $k=7$-th equation and didn't found any solution for $a,b < 25000$.
EDIT 1:
Dividing the consecutive equations ($b^2 = \dots$) we obtain that for odd $k$:
$$
(1-k)a+kb = 0
$$
where $(a,b)$ is the solution to the $k$-th equation.
For example $(1-5)\cdot 1600 + 5\cdot 1280 = 0$.
EDIT 2
Using EDIT1 we know that the solution $(a,b)$ of the $7$-th equation has to satisfy:
$$
(1-7)a+7b = 0 \implies 7b-6a = 0
$$
and on the other hand:
$$
b^2 = a\cdot(2^{7})^{(\frac{a-b}{2^{7}})}\cdot 2^{-(\frac{b}{2^{7}})} = a\cdot 2^{\frac{7}{128}a-\frac{8}{128}b}
$$
which implies that $\frac{7}{128}a-\frac{8}{128}b = n\in\mathbb{N}$. The system of equations:
$$
\begin{cases}
7b-6a = 0 \\
7a-8b = 128n
\end{cases}
$$
has solutions given by $a = 896n$, $b = 768n$. Substituing back we obtain:
$$
(768n)^2 = 896n \cdot 2^{n}
$$
which has.. no integer solutions. Very disappointing, but maybe there are no more solution of this form :(
The following code in Mathematica
f[k_] := Reduce[{-(k - 1)* x + k* y == 0, k* x - 1 (k + 1)*y == 2^k *n}, {x, y, n}, Integers]

finds for odd values of $k$ the possible value of $a$ and $b$ as a function of $n$. Substituing back we can check with the script below if there exists $n\in\mathbb{N}$ that satisfy the equation.
NSolve[(b)^2 == a*2^n, {n}, PositiveInteger]

where instead of $(a,b)$ one should substitute the values obtained before.
EDIT 3
The solutions of the previous system are of the form:
$$
(a,b) = (nk 2^k, n(k-1) 2^k)
$$
for every odd $k$. Using the following code we can see that it seems that there are no integer solution to the equation $b^2 = a2^n$ for $k \geq 7$:
g[k_] := NSolve[((k - 1)*2^k*n)^2 == k*2^k*n*2^n, {n}];
Table[g[2*k + 1][[3]], {k, 1, 100}]

Comment: Oops, sorry, yes.  OK, so if $n \ge k$, $k$ must divide $n$; if $n = k j$, we have $j (k-1)^2 = 2^{(j-1)k}$.  $j$ and $k-1$ are powers of $2$.  If $j = 2^p$ and $k = 2^q+1$ we get $(2^q+1)(2^p-1) = p + 2 q$.  But $2^q + 1 > 2 q$ for all real $q$, while $2^p - 1 > p$ for $p > 1$; it's easy to show the only solutions here are $(p,q) = (0,0), (1,1), (1,2)$, corresponding to $(n,k) = (2,2), (5, 3), (10, 5)$,   On the other hand, if $n < k$, $(k-1)^2$ must be $1$, and then $k=2$ and $n = 1$.
Comment: In EDIT 3 you want $b^2 = a 2^n$ with $a = n k 2^k$ and $b = n (k-1) 2^k$?  But that simplifies to $n (k-1)^2 = k$, and since $(k-1)^2$ and $k$ are coprime the only solutions are $n=k=0$ and $n=k=2$.
Comment: @RobertIsrael no, it simplifies to $n(k-1)^2 = k 2^{n-k}$ which has solutions for $k = 3,5$ but no more for $k\geq 7$. In your calculations I think you were simplifying $2^k$ with $2^n$, but $n\not = k$.
Comment: Exactly as you said Robert. Thank you for your reply! So unfortunately there are no more solutions of that form. We have to find some others!
Answer: The question essentially asks for solution to the following equation:
$$ a^b b^a = x^y y^x $$, with conditions $a\neq x \cap b\neq y$ or $ a\neq y \cap x\neq b $.
This can be solved as a pullback $\{(a,b,x,y)\in N^4|a^b b^a=x^y y^x,(a\neq x \cap b\neq y) \cup  (a\neq y \cap x\neq b)\}$.
This is essentially infinite filtering operation on $N^4$.
Given non-constructive nature of the problem, solving this requires tools that work with non-constructive problems, i.e. axiom of choice is your best bet. Thus we'll construct epimorphism and it's inverse to find infinite number of buckets and make a choice in each of the buckets to solve this problem. Choice function is obviously:
$$ch()=(\exists (a,b,x,y): a^b b^a = x^y y^x \cap ((a\neq x \cap b \neq y) \cup (a\neq y \cap x\neq b))) \cup \bot$$.
Applying and evaluating the choice function against infinite number of buckets in $N^4$ takes infinite amount of time, so it's not good approach, so the normal substitution approach for (a,b,x,y) does not work in this problem. (substitution is the inverse of $\exists$ and $\forall$ in adjoint functors.) It's worth mentioning though, since we can verify found solutions with it.
I have to think this further to figure out how to extract the (a,b,x,y) numeric values from the filter...
EDIT: I figured out that instead of mapping where the equation's sides are equal, we need to map the area where they're not equal. So we need to create distance metric for the $\bot$ in the choice function. Basically distance function $$d(a,b,x,y) = a^b b^a - x^y y^x$$ and then we can jump larger distances in the huge space while trying to move between different values of a,b,x,y.

$x^y y^x$ in more than one way


How to show a menu link that is hidden because the role has no permission to see the linked page?

Question: I need show a menu link that links to /node/add/article for anonymous users but they don't have access to that page.
I have seen solutions like:

Using an absolute URL (that way Drupal does not check user access).
Alter the menu access callback but I do not really want to give them access just to print the link.

Are there any other solutions?
Comment: What happens when an anonymous user follows the link? They see a forbidden page? User login?
Comment: Anonymous user will be redirected to user login.
Answer: In your case you can use two menu entries in the same menu:

One pointing to /node/add/article.
Another one pointing to /user/login.

First link is only visible to registered users, because anonymous users don't have permissions to add articles.
Second link is only visible to anonymous users because registered users don't have permissions to see the user login page (because they are already logged in).
The result is a menu with only one menu entry. Registered users see first link, anonymous see only second one.


Overloading subscription operator() or [] with no code repetition

Question: I have two versions of operator():
const A& operator(int x ,int y) const;
A& operator(int x ,int y);

But I don't know what would be the best way to avoid code repetition (because they essentially have the same logic).
I did read the awesome FAQ regarding operator overloading (and some other questions) but did not find answer.
EDIT_1: I've tried the suggestion that Skizz proposed but something like that does not quite work for me but maybe I've missed something:
Because this works while this does not compile giving the following error:
error: invalid initialization of reference of type 'int&' from expression of type 'const value_type {aka const int}'
Comment: If the logic is the same, making one of them call the other should do the trick, no?
Comment: How do you do that without `const_cast`?
Comment: What are the implementations of these functions?  If they are identical (as can be implied by your statement), then you could simply write 1 of them and ignore the other.
Comment: @ZacHowland I need the ability to both edit information and access it in other const methods.
Answer: If both methods 'essentially have the same logic' then surely they should both be marked const. If they do behave differently, should they be called the same thing?
What you need is a third, hidden method that does the common thing, like this:-
const A& operator(int x ,int y) const
{
  return Common (x,y);
}
A& operator(int x ,int y)
{
  return Common (x,y);
}
A& Common (int x, int y) const
{
   // common code
}

This takes advantage of the implicit non-const to const conversion. In the first method, the this object remains const in the call to Common but the non-const return value is converted to const. In the second, the non-const this object is converted to a const this object and the return object is unchanged.
Comment: They are the same in the sense that they both go and find an item at x,y coordinates but sometimes I'd like it to be a constant ref and sometimes not...
Comment: const matters here because the operators return references. One should be able to modify a(x,y)=5 if and only if a is non-const; one should be able to access z=a(x,y) regardless of whether a is const or not.
Comment: @Michael: In the original question, it's not clear if the operators are members of A or if A is a separate class. In the latter case, the constness of the operator function does not affect the constness or the return value. In the former case, yes, you'd need const and non-const operators.
Comment: @Skizz I've tried doing what you proposed but it doesn't work, maybe I've missed something ? (I've edited the question with more info)
Comment: @SadStudent: You're returning a reference to a member so it has the same constness as the constness of the this pointer (the first of the two alternatives I mention in my previous comment).
Answer: If you have the data in question as shared/unique pointer, you are able to forward it to a common function:
class X {
    public:
    const A& operator () (int x ,int y) const {
        common(data, x, y);
        return *data;
    }

    A& operator () (int x ,int y) {
        common(data, x, y);
        return *data;
    }

    private:
    void common(std::shared_ptr<T>, int x ,int y) const;
    std::shared_ptr data;
};

Now you are able to access the T* via data.get() which is 'T* get() const'.
(Note: I consider the common function a bad design)
You might do, also:
class X {
    public:
    const A& operator () (int x ,int y) const {
        common(x, y);
        return data;
    }

    A& operator () (int x ,int y) {
       // ... make mutations
       common(x, y);
       // ... make mutations
       return data;
    }

    void common(std::shared_ptr<T>, int x ,int y) const;
    T data;
};

Or actually, making the data mutable, if it is not breaking logical const:
class X {
    const A& operator () (int x ,int y) const {
        // ... make mutations on the mutable data, only
        return *lazy_evaluated_data;
    }

    A& operator () (int x ,int y) {
        const X& self = *this;
        self(x, y);
        return *lazy_evaluated_data;;
    }

    private:
    mutable T lazy_evaluated_data; // or a cache
};

Comment: Doesn't the second operator make a `const A&` i.e a const reference into a non const reference ?
Comment: @SadStudent No, but the shared poinnter has the function 'T* get() const'
Comment: OK but it's a plain vector anyway so I guess it's not relevant :\ And what would you consider a good solution for this problem? I can think of some bad ones too :)
Comment: Don't make data mutable for coding convenience. This may cause unintended data modifications from other seemingly const functions.
Comment: @Michael I know - it may be a cache
Answer: Write a helper function and call it from both operators. You'll need to do some const_cast<...>(this) which can be ugly, but it's a common pattern.
Comment: Doing `const_cast<...>(this)` is more than ugly - [it could lead to undefined behavior](http://stackoverflow.com/q/7349559/335858).
Comment: @SadStudent that's generally good advice, but nothing is so bad that it should be avoided without good reason. See duplicate answer at http://stackoverflow.com/questions/123758/how-do-i-remove-code-duplication-between-similar-const-and-non-const-member-func which references Scott Meyers' solution using `const_cast` AND `static_cast` together ;)
Comment: @cdmh as the previous commenter said I tend to avoid const_cast in a similar way I avoid fire :) so if there's some work around that would not use const_cast it'd be nice


mpm_winnt:notice and core:notice in Apache log. Is it ok?

Question: Well, my problem is that I have 500 Internal Server Error, but I'm unable to figure out what it is. I switched to php.ini-development as php.ini, I turned on all error reporting I could, I created and set error_log file in php folder. But nothing is reported. My simplest in the world php file looks like this:
<?php
  ini_set('display_startup_errors',1);
  ini_set('display_errors',1);
  error_reporting(-1);
  echo "Hello";
?>

However, no errors are displayed. What really drives me nuts, is that the page itself is executed, so that I see Hello in my browser, but still in the console I see this notorious 500 Internal Server Error.
PS. Apache error log contains nothing more than this:
[mpm_winnt:notice] [pid 2400:tid 340] AH00455: Apache/2.4.10 (Win64) PHP/5.6.3 configured -- resuming normal operations
[Thu Nov 13 23:55:40.461430 2014] [mpm_winnt:notice] [pid 2400:tid 340] AH00456: Apache Lounge VC11 Server built: Jul 17 2014 12:58:29
[Thu Nov 13 23:55:40.461430 2014] [core:notice] [pid 2400:tid 340] AH00094: Command line: 'C:\\Apache24\\bin\\httpd.exe -d C:/Apache24'
[Thu Nov 13 23:55:40.462430 2014] [mpm_winnt:notice] [pid 2400:tid 340] AH00418: Parent: Created child process 4552
[Thu Nov 13 23:55:40.812450 2014] [mpm_winnt:notice] [pid 4552:tid 228] AH00354: Child: Starting 64 worker threads.

Comment: Have you set a different error log for your vhost?
Comment: don't do the debug options in your script. set them at the php.ini level. It's entirely possible that PHP is getting killed BEFORE your code ever executes. setting the options in php.ini ensures they're always active. Since you see hello, php's obviously working, but may be getting killed in a shutdown sequence somewhere.
Comment: @Stony I set just one error log
Comment: I got this message too, but my PHP script works. But the performance is very very very bad.
https://www.apachelounge.com/viewtopic.php?p=26936
Answer: In my case, this error occurs when one of my class has lot of constants CONST defined. After I reduce CONST quantity in this class file, error disappear (perhaps reduceing them to less than 64 when apache thred limit is set so, but this is guess only). Strange but maybe helpful.


SQL JOIN cant get it working

Question: I know the forum is full of this questions but i cant find the solution.
I want to join the table users from user_to_designment they both have a column with user_id the error that i get is:
select user_id, designment_id FROM user_to_designment
FULL JOIN users
ON  user_to_designment.user_id = users.user_id

 LIMIT 0, 25
MySQL meldt: Documentatie

#1052 - Column 'user_id' in field list is ambiguous

I use this query:
select user_id, designment_id FROM user_to_designment
FULL JOIN users
ON  user_to_designment.user_id = users.user_id

Please some advice
Comment: What do you think the words in "Column 'user_id' in field list is ambiguous " mean?
Comment: Tip of today: table aliases!
Comment: Possible duplicate of [1052: Column 'id' in field list is ambiguous](http://stackoverflow.com/questions/6638520/1052-column-id-in-field-list-is-ambiguous)
Answer: In your select list prefix the user_id with the table name:
select users.user_id, designment_id FROM user_to_designment
FULL JOIN users
ON  user_to_designment.user_id = users.user_id

Both columns have user_id, SQL cannot choose between them, you must specify explicitly.
Answer: You need to specify which user_id to return in your select, eg select users.user_id or Select user_to_designment.user_id
Answer: You must clarify which user_id table column you are selecting.
select a.user_id,b.designment_id from user_to_designment b
full join users a
on b.user_id=a.user_id

Answer: This is because "user_id" field exists on both tables.
you must put table name before field name.
    select user_to_designment.user_id, designment_id FROM user_to_designment
FULL JOIN users
ON  user_to_designment.user_id = users.user_id

Answer: It seems user_id exist in both the tables. so it gives the ambiguous error. We should say from which table we have to pick the column.
SELECT users.user_id
    ,user_to_designment.designment_id
FROM user_to_designment
FULL JOIN users ON user_to_designment.user_id = users.user_id

You may use either users.user_id or user_to_designment.user_id in your select statement. Always use tablename.columnname format. It avoids confusion.

SQL JOIN cant get it working


Post two field values with axios using a bootstrap vue b-form-select component

Question: I'm trying to post two fields to my backend but when I try I get null in the backend for both values.
Not sure what I'm doing wrong here.
<template>

        :Selected
        {{sport_id_form}}

      <button type="button" class="btn btn-dark" v-on:click="get_sports">Get Sports</button>

</template>

If I create a form this way everything works fine.

When I use the form the data goes to the backend and triggers events based on the values.
How can I post the data in the same format as the form but using a dropdown select?
Answer: Change the form
data() {
    return {
      sport_id_form: {
        sport_id: "",
        sport_name: ""
      },
      sport_id_form_options: [
        { item: null, name: "Please select an option" },
        { item: { "9": "Tennis" }, name: "Tennis" },
        { item: { "10": "Basketball" }, name: "Basketball" }
      ]
    };
  },

and select to

Comment: I don't get you. The form data example works but my example with the dropdown doesn't can you show me? I can't see in the axios examples
Comment: can you check the form data with the request in network tab
Comment: I'm still getting a null value with your answer. Not sure why. Looks like the content is empty.
Comment: install vue devtools and check if the value gets updated when changing form,
Comment: yes I can see the value updating in dev tools. problem is the post request. My selected array's value is  {"9" : "Tennis") I can see this but I cannot split the key and value to go in the url for posting. Do you know how?
Comment: there is no need to split into key-value pairs.  are you still passing form data like this
 this.$axios.post("/api/sportsid/add_sports/", this.sport_id_form);
Comment: i'm still getting null for both values posted to backend.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/220579/discussion-between-rahul-reghunath-and-tomoc4).


average timespan conversion error

Question: I have some data in a .csv file that looks like this:
1, task1, 00:00:02.0000000
1, task2, 00:00:00.3529381
1, task3, 00:00:01.1604731
1, task4, 00:00:00.1413738

The third column are TimeSpans.  I need to calculate the average, min, max, etc on them.  The problem I am having in trying the online methods is that its coming back as 0.  I've tried:
public Log(string a_action, string a_time, string a_executionTime, string a_studentLogin)
{
    Action = a_action;
    Time = a_time;
    ExecutionTime_s = a_executionTime;
    ExecutionTime_ts = TimeSpan.ParseExact("0:0", @"h\:m",
                       CultureInfo.InvariantCulture);

    ExecutionTime_l = Convert.ToInt64(ExecutionTime_ts.TotalMilliseconds);

    ExecutionTime_d = (double)ExecutionTime_ts.TotalMilliseconds;
}

public void Calc()
{
    List<Log> logList = CSVToList.GetList();

    double doubleAverageTicks = logList.Average(timeSpan => timeSpan.ExecutionTime_d);
    long longAverageTicks = Convert.ToInt64(doubleAverageTicks);

    TimeSpan sp = new TimeSpan(longAverageTicks);
}

Suggestions appreciated..also my linq sux
Answer: TimeSpan sp = TimeSpan.FromMilliseconds(doubleAverageTicks);

average timespan conversion error


Remove graft mark in git when history becomes available

Question: I'm experimenting with git shallow clones and wonder if there is any possibility
to "ungraft" a commit if I happen to fetch the parent of an already existing
commit.
Let's say I have a full repo with three commits looking like this (letters
indicating their checksums):
A--B--C

I then want a shallow clone of only commit C, and perform the following actions:
git init
git remote add origin url_to_my_repo
git fetch --depth=1 C
git checkout FETCH_HEAD

This leaves me with a shallow clone of the origin repo, where only commit C is
available. The commit is marked as grafted, indicating the broken history.
Let's say I now also fetch commit B in the same way:
git fetch --depth=1 B
git checkout FETCH_HEAD

Now it is getting interesting. I have two commits that are both marked
grafted. Recalling that each commit records its parent checksum, which can be
successfully verified using e.g. git cat-file -p C, Git actually has all
necessary information to replace the grafted mark of commit C with the
real history which in fact is available.
In essence, I want the same outcome as if I would checkout commit C with a depth
of 2 in the first place.
I've read this excellent explanation regarding grafted commits, however it
requires me to do a manual intervention. I'm sure there must be a command to
tell git to check all grafted commits if the grafted mark can be removed, e.g.
with git fsck.
Any ideas?
Comment: Other than `git fetch --unshallow`, there isn't any way to do this today. Probably Git should *automatically* do it on its own (e.g., during `git gc` work), but it doesn't.
Answer: After reading up a bit on the documentation of shallow concept, I started to play around with the shallow-file located in the .git-folder. Essentially it is a list of all commits that are grafted. Removing a commit hash in the file successfully "ungrafts" that very commit (i.e. the graft marker is removed, and history viewed correctly in git log).
One should be somewhat careful when directly editing anything within the .git-folder, but this at least points in the right direction on how to ungraft commits without perform git fetch --unshallow.
Edit:
I created a python script for this very purpose and recently published it on GitHub, should anyone be interested: https://github.com/chrillof/git-ungraft


absolute value global/local Minima and Maxima (piecewise function)

Question:
given the function $
f(x)=
\begin{cases}
 |x-2|&\text {} \, 0<x<3\\
 |x-5|&\text{}\, 3≤x≤7\\
     \end{cases}$
which of the following statements is true?(there can be more than one true or all false)

In the open interval $(0,7)$ there isn't a global maxima
In the open interval $(4,5)$ there is a global minima
The point $x=3$ is a local maxima or minima point in the interval $(0,7)$

What I tried:
First thing was to write it in a more comfortable way without the absolute value
$
f(x)=
\begin{cases}
 -x+2&\text {} \, 0<x<2\\
 x-2 &\text{}\, 2<x<3\\
-x+5 &\text{}\, 3<x<5\\
x-5 &\text{}\, 5<x<7\\
 \end{cases}$
then I checked if there is continuity at these points $(x=2,x=3,x=5)$ $\lim \limits_{x \to 2^+}=0$ $\lim \limits_{x \to 2^-}=0$ ,  $\lim \limits_{x \to 3^+}=2$ $\lim \limits_{x \to 3^-}=1$ (not continuous at x=3) and $\lim \limits_{x \to 5^+}=0$ $\lim \limits_{x \to 5^-}=0$.
then I calculated the derivative $
f'(x)=
\begin{cases}
 -1&\text {} \, 0<x<2\\
 1 &\text{}\, 2<x<3\\
-1 &\text{}\, 3<x<5\\
1 &\text{}\, 5<x<7\\
 \end{cases}$
checked the limits to see if it is differentiable at the points mentioned above and found that they are all critical points (sorry if it is not the right word but what I mean is "suspicious" points).
Did a small table to check if the points are minima or maxima. found out that $x=2$ is a minima , $x=3$ is a maxima and $x=5$ is also a minima but I cannot tell if local or global so I cannot tell if statements 1 or 2 are right since I cannot calculate $f(2)$ or $f(5)$ $f(3)$
Can anyone give me hints on how to continue from here? and if my way was correct?
Thank you!
Edit: I just checked the limits of the interval but what can I learn from that?
$\lim \limits_{x \to 0^+}=2$ $\lim \limits_{x \to 7^-}=2$
from what I personally know I can conclude from that if the limits are infinite
Comment: You need also consider the end points $x=0, x=7$ and not the question focuses on *open *intervals
Answer: Actually, you can calculate $f(2)$ and $f(5)$. To check which of the two minima is the global one (both of them are local minima), you can see a bit more carefully the domains on which $f$ is defined. By doing this you should also discover that the function has an additional maximum, other than the one you found.
Comment: $f(2)$ and $f(5)$ are local minima, while $f(3)$ and $f(7)$ are local maxima.  The first question restricts you to the open interval $(0,7)$, where the only local maximum is $f(3)$. Thus, it is a global maximum and the first statement is false. In the open interval $(4,5)$ there is no local maximum or minimum, thus the second statement is false. Finally, as you said $f(3)$ is a local maximum in $(0,7)$ and the third statement is true.
Comment: Thank you for the help , I got that $f(7)=2$, $f(4)=1$ , $f(5)=0$ , $f(2)=0$ and $f(3)=2$  Does that mean $f(2)$ and $f(5)$ are local minimum and $f(7)$ and $f(3)$ are global maximum? if that is the case then statement 1 is false , statement 3 is false and the second statement is also false? or the second statement is true ?


Is there an API for this?

Question: I know about user_access API. I've written a module that should display some information only if the user has specific rights on the taxonomy.
To be more precise:

we've created a vocabulary, say books.
in this vocabulary books we have a lot of terms, say for example children and cooking
we've created roles according to the terms, i.e. roles like role for children and role for cooking => one role = one term.
now I've written a module that should diplay a link to 'edit' or 'create' only if the user is logged, and if he has the rights based on the role (which heavily relies on the taxonomy access rights).

In short: in my node_view hook:

I have to check if it's a node with books vocabulary.
if so, I have to read the associated term (there can be only one), let's take an example: children
if the user is logged in and has the permissions of editing nodes with the specific term (children here), the I display a text with a link like edit this book and another like like create a children's book.

This is only the last part that is a problem to me.
Does the user access API call works flawlessly, and takes in account those rights, or do I have some specific calls to do? No API seems available for the taxonomy access control (TAC).
Maybe you have an example somewhere (didn't find one actually)?
Answer: Are you actually having a problem with user_access or just asking before you're trying it? I'm not really following what exactly is your problem.
Taxonomy Access Control should influence what user_access returns. Or you could just set permissions for "Use contextual links" and let Drupal take care of it with contextual links instead of writing a custom module.
Comment: I'm having a problem with `user_access` because it doesn't go "deep" enough for permissions, and I need to know whether user has rights to edit/create **plus** the rights to edit create the specific node regarding its terms *and* the rights given to the user through the api taxonomy access rights
Comment: Sorry I didn't read carefully the notes at the bottom of the TAC module. Now it works. I write your answer as  the good one. Thank you.
Comment: Glad you solved it.

Is there an API for this?


Moodle PayPal Enrolment on Payment tosses up a superfluous code string that scares users

Question: I have Enrollment on Payment (through PayPal) working flawlessly, except for one things: when users click the "Select Payment Type" button and the enrol.html popup opens, it has the following string under the PayPal payment button:
{$a->label}: {$a->value}
screenshot showing oddball code
I have searched high and low for any information and have only been able to verify that my integration follows all the instructions. The payments are processed; users receive no error. But that line of code is worrying everyone. I appreciate any and all help.
Answer: OK. It turns out this is a known bug and they're working on it now: https://tracker.moodle.org/browse/MDL-77003
Thank you again, Russell.
Comment: Ah, I usually check there too, nice one!
Answer: Looks like its a core Moodle string labelvalue in /lang/en/moodle.php
$string['labelvalue'] = '{$a->label}: {$a->value}';

Which is being displayed in the fee breakdown via a mustache template in /payment/templates/fee_breakdown.mustache

    {{#surcharge}}
        {{# str }} labelvalue, core, {
            "label": {{# quote }}{{# str }} cost {{/ str }}{{/ quote }},
            "value": {{# quote }}{{# str }} feeincludesurcharge, core_payment, {
                "fee": "{{fee}}",
                "surcharge": {{surcharge}}
                } {{/ str }}{{/ quote }}
            } {{/ str }}
    {{/surcharge}}
    {{^surcharge}}
        {{# str }} labelvalue, core, {
            "label": {{# quote }}{{# str }} cost {{/ str }}{{/ quote }},
            "value": "{{fee}}"
            } {{/ str }}
    {{/surcharge}}

Which I think is being called by updateCostRegion in /payment/amd/src/gateways_modal.js
Maybe one of the PayPal settings in Moodle has a null value somewhere, so its not being displayed correctly
Check the value for the PayPal surcharge - if its already 0 then click save to make sure the database has been updated with 0 rather than a null
Site admin > Plugins > Payment gateways > Paypal
Or direct to /admin/settings.php?section=paymentgatewaypaypal
If that doesn't fix it, then check the enrol cost for the paypal enrolment plugin
Site admin > Plugins > Enrolments > Paypal
Or direct to /admin/settings.php?section=enrolsettingspaypal
Again, if Enrol cost is already 0 then save changes to make sure
And check the enrol cost for the course
Course menu > Participants > Enrolment methods > Paypal
Comment: Thanks, Russell. I carried out each of those checks and nothing has changed. I also tried creating a new payment method (replacing the previous one but with all the same information pulled direct from PayPal) as well as changing the theme. No dice; the problem remains the same.


Preserve Nulls in Pandas dataframe

Question: I have a df
a=pd.DataFrame({'A':[1,2,3,4], 'B':[1.0,NaN,3.0,NaN]})

I want to convert column B to string preserving the nulls. Please suggest a method on how to achieve it.
Answer: You can mask:
a['B'].astype(str).where(a['B'].notna(), None)

Output:
0     1.0
1    None
2     3.0
3    None
Name: B, dtype: object

Comment: Thank you for suggestion. I am getting a combination of string and float values. I want the entire column to be string values and the float NaN to be None
Comment: @Arcanesaw see updated answer. Just curios, are you trying to pass this to JSON?
Comment: No, I am not. .
Answer: There are several ways you can do this:
np.where method:
df['B'] = np.where(df['B'].isna(), np.nan, df['B'].astype(str))

mask method:
df['B'] = df['B'].mask(df['B'].notnull(), df['B'].astype(str))

Preserve Nulls in Pandas dataframe


Is "You shouldn't play all 6 strings together on an electric guitar" good teaching?

Question: Someone I know who has been playing electric guitar for many years says this quite often, as a key difference between playing acoustic and electric guitar. He claims that even playing rhythm, you shouldn't be strumming all 6 strings but only two or three (typically by playing power chords).
I can see this having a point with certain amp/effect setups - it gets awfully muddy - but I'm not convinced it should be considered a rule. Isn't there a place for playing an electric with standard open acoustic guitar chords?
I'm very new to electric guitar so I'm trying hard to determine which things I'm told should be considered rules, and which is just that person's style of play.
Comment: If someone ever tells you there's a rule in music, they are wrong.
Comment: You are correct, this does not apply as a general rule.
Comment: Just re the word "rules" .. Them's just guidelines .. there aren't really any rules in music, just advice for what normally sounds ok :-)
Comment: "Would you buy a book called 'Suggestions of Acquisition'?" -- the first Grand Nagus.
Comment: Whoa. Definitely not a rule. It depends on what/how you're playing.....and what you're playing it through.
Comment: Many answers focus on the role of distortion in this question.  However the (generally) higher _sustain_ of electric guitars (even w/o distortion) is an import factor -- a big open acoustic guitar chord fades relatively quickly, and is less likely to be overwhelming than the same chord on a (clean) electric guitar.
Comment: I'd say that the point of it is that you should always control which strings you're playing, think about it and make it an intentional choice - you should play all 6 strings together if and only if you've decided that's best for this part, and not as a default option.
Comment: Clearly the person who came up with this rule doesn't listen to a lot of Led Zeppelin. Page plays all **twelve** strings on an electric 12-string in the end section of *Stairway to Heaven*. Also, the intro riff for *Say it Ain't So* by Weezer has all six strings played on electric. There are many examples of all six strings being played on electric by famous bands.
Answer: The direct answer: No, this is not good teaching
There is very little difference between electric and acoustic guitar. Playing all 6 strings can be absolutely fine on either. Many barre chords are 6 string.
The question should really be "...shouldn't play all 6 strings together when using distortion"
When you use distortion you add in harmonics which generally act to muddy the sound, and if you choose the wrong notes you can end up with horrible discordant sounds.
That said, many bands use distortion perfectly well with barre chords, and even open chords, using the distortion to add acoustic textures.
Comment: Distortion has no regard for equal temperament so it usually requires special tuning to pull off - either a guitar tuned for a specific song, or layered guitars in the studio where each part is played only on 3-4 strings that are carefully tuned by ear for the desired harmonics. Just mashing a full barre chord is pushing the limits of good taste with even a hint of distortion (some might argue even without).
Comment: @DarrenRinger: "Rock and Roll, pushing the limits of good taste since 1950". I wonder how many rules of good-taste guitar playing Dave Davies and Link Wray rewrote just between the two of them ;-) Which of course is not to say that when a student does it they'll necessarily get anything other than an awful mess.
Comment: Some chords are particularly bad, but to be honest, some are beautiful with distortion - you just need to know what harmonics will be introduced by your distortion, and where they fit.
Comment: I find `add9` barre chords in 2nd inversion to be particularly bada** with heavy distortion.  Double that `9` on the `G` string too if you want.
Comment: What you say is correct, but your answer is off-key. Distortion is irrelevant to the question. It's about learning to play guitar, not how to blow people's minds with a glorious power-ballade. Knowing when and how to use each string is something you develop over time, just as it is to know the same when dealing with effects or sharing the soundscape with other musicians. Honestly, there is no one way to go about it, but one typically learns to crawl before they learn to walk or run.
Comment: Quick - that's exactly my point.
Comment: @quickthyme: Everything depends upon the style of music.  There are some styles where strumming 5-6 notes is entirely the right thing to do, and others where it's the wrong thing to do.  If the styles one wants to play are those where 5-6 chords are appropriate, and one is capable of playing such the chords cleanly, the fact that they would be inappropriate for other styles shouldn't be an issue.
Comment: Yes, I agree with all that, and you speak true. However, what I disagree on, is on the point of whether or not this is "good teaching". I am of the opinion that it is in fact good teaching to discipline one's self to learn how to NOT play all the strings first and focus on making each individual note intentional. This should hold true no matter what style of music you intend to play. To be utterly pedantic about it all, I view learning to strum a guitar and learning to play a guitar as being two completely different pursuits.
Comment: So yes, playing every possible string on your instrument at the same time is certainly acceptable, as long as it's on purpose. "The dentist could remove all the teeth, or he could pull just the one that has the infection. Unfortunately, he skipped that part in Med School, and so he goes with what he knows."
Comment: So i think that's a separate question altogether.
Answer: The only rule is, "If it sounds good, it is good."
Comment: Even if it sounds bad, that can be good too.
Comment: If it sounds, it is.
Comment: - Duke Ellington
Answer: The very first thing to know, is to Never assume there is a certain rule you should or should not apply, of course some ways are better than others, but you can do and experiment everything you want, in music only comes to the ear is what matters.
In case you have heard AC/DC songs before, "Highway To Hell" for example, open chords are played, they thing here is what kind of distortion and what chords are you playing, some chords just sound awful distorted to some point.
Another thing is barred chords, where you do play all 6 strings but not in open positions, these are more common when playing a chord with distorted sound.
After all the key is how much the distortion is, try to roll back on the distortion and you can get some nice results... get a more "metal" distortion and good luck making the worst noise ever on open chords.
Answer: Well, I don't see it as a key difference between electric and acoustic since I am not overly fond of just hitting all six on the acoustic either.  And when playing the acoustic, I don't even have to share sound texture between lead and rhythm guitar.
On the other hand: how are you going to start off "A Hard Day's Night" without playing all six?
It's right that using distortion makes full-bodied chords an even worse idea (mostly because of cross-harmonic distortion, but also because of hogging all the frequency spectrum).  But stuff gets more interesting for more separable notes and chord voicings, and an electric guitar does not need to revert to full chords in order to get heard.
Comment: @leftaroundabout: If one tunes the G string on a guitar about a seventh of a semitone flat, flat, an open E chord can sound very nice with distortion (frequency ratios 2:3:4:5:6:8), vs. 2:3:4:5.04:6:8 with equal note spacing).  Unfortunately, tuning the G string flat will cause almost every *other* chord to sound horrible.
Comment: As always when "cross-harmonic distortion" is mentioned as a problem, I'd like to remark that this is not in principle a problem of full-bodied chords – only, distortion makes the deficiencies of 12-edo tuning (in particular, its really not so good approximation of thirds) painfully obvious, that's why all full chords get so muddy on a distorted standard guitar.
Comment: I once saw a video that dissects the intro to A Hard Day's Night - each instrument is actually playing a very simple chord, but they are all different chords and only one instrument has the fundamental.  So, that's how you do it without playing all six strings ;p
Answer: 6-string chords can work on an electric guitar. Increasing distortion greatly increases the chance that it won't sound good, but there are still situations where it can provide flavor. And that's not even considering alternate tunings.
But I think your friend may have been trying to point out something important that took me a while to learn. Playing any instrument is about balance, restraint, and nuance. No matter how heavy the tone, you should still be using controlled, precise movements and every note should have a purpose.
In other words, don't just play the strings because you can shape the chord. Play them because it gives you the result you want to achieve. You can play many songs with 5-6 note barre chords (and that's fine when starting out), but it's likely that you'll be missing out on a lot of detail which can only be achieved with smaller chords and individual notes.
Comment: While I like your answer, and have upvoted, I think the entire grunge movement, and punk, and others would disagree with "you should still be using precise controlled movements and every note should have a purpose" :-)
Answer: I often find myself playing all six strings on electric. More than I should, even.
I was listening to a Nile Rodgers tutorial the other day, and he talked about hearing cover bands play good times, hitting a lot of strings, and he says "No! I didn't play it like that! I played it like this!". It's hard to tell the difference, because he's talking and you can hear the pick noise in the microphone, but the message is clear.
Which is, in some styles, where you might be playing clean and wanting to hit all the strings, but you really shouldn't. Even when you have a relaxed hand, you want to have a disciplined stroke.
Should this be NEVER? Perhaps not. Should you give students awareness early on that backing off, controlling the number of strings you play and your place in the whole? Certainly.
Answer: That principle stems from the fact that electric guitars, in a band setting, share frequencies (specifically mids) with a lot of other instruments. It's right up there with the piano, keys, vocals, even some horns and of course, with other guitars.
So it is encouraged that as electric guitar, you should play differently i.e, find variations when playing chords. That way, you add to the sound of the band. If you play barre chords or open chords (again, in a band setting), you'll get lost in the mix; your sound would 'match' with other instruments and thus, not be heard.
But then again, music isn't something that has one definition. For example in some form of blues, the guitar is the main driving force. You can basically play a lot of things, and not worry of being lost in the mix. "Isn't there a place for playing an electric with standard open acoustic guitar chords?" kind of applies in blues/ blues-rock.
So to answer your question, yes, generally speaking it is good teaching. Because it opens you up to being creative with your playing. But it shouldn't be a rule for every other music setting in existence.
Answer: If you are playing with other musicians, playing all six strings at once will tend to create a muddy mix where it becomes difficult to distinguish who is doing what. Depending on the style of music, that may or may not be a desirable outcome.
Answer: An electric guitar can be used to play in many styles that would sound silly on an acoustic, or produce effects that an acoustic guitar simply can't match. Some styles and effects are apt to work much better when playing fewer notes than when playing more. As others have mentioned, distortion only works well when playing certain combinations of frequencies; major triads are apt to sound bad unless one can lower the third relative to the other notes in the chord (something which is apt to be difficult). Whammy-bar effects are unlikely to effect all notes evenly; that unevenness can add interest when there are two or three notes, but will simply yield a muddle if there are five or six.
On the other hand, electric guitars can also be used for many styles which would be equally at home on an acoustic; if an acoustic guitar would play a chord with five or six notes, there's no reason an electric guitar shouldn't do so as well. Most guitars have a pickup selector which can switch between a "clearer" sound (neck pickup) and a "fatter" sound (bridge pickup). While the fatter sound of the bridge pickup may become muddled when strumming larger chords (I like the sound of plucking notes individually while letting earlier notes ring), the clearer sound of the neck pickup when passed through a clean amp, should sound much fuller with 5-6 string chords than with 3-4 string ones.
Comment: are bridge and neck pick ups juxtaposed?
Comment: @Tim: I don't think so.  On my guitars, the clearer sound is on the neck pickup.  When I want to emphasize the bass strings, I use little metal bars to bridge the top four pairs of magnets on the humbucker pickups (softening the treble strings).  The effect of adding the bars to the neck pickup is noticeable when the switch is set for the position I would describe as giving the "clearer sound".  Maybe we differ in how we interpret "clearer" and "fatter"?
Answer: Like any good wine taster can tell you, the palate is in the mind, not the taste buds. One needs to train their inner ear so that sonic finesse and accuracy can be achieved.
The question is not asking whether or not this is a rule one must always follow, but rather if this is "good teaching".
From a teaching perspective, YES, this is a good practice to enforce. When students are first learning to play an instrument, they are still learning good form and proper technique and are not ready to start thinking "out-of-the-box" quite yet. (Generally speaking; this assumes that the student is at a beginning level in music.) Typically, it's much more effective for the sake of learning to start out working with less and then gradually build from there. Learn to identify the notes you hear, and develop a good habit of only playing the notes you truly intend.
If later, once you actually know what you're doing, you decide to use all 6 strings to unleash an emotional wail upon the listener, then it will be on purpose, and you will have created true artistic expression.
Answer: As a "Rule of thumb" (I.E Do this unless doing the opposite works better. But starting out here will save you time.) YES!
Answer: I agree with Dr. Mayhem, you shouldn't strum all 6 strings with distortion. When you play clean, it sounds great. But, with distortion, you lose some of the frequencies, and a lot of the notes get muddied. Its better to play power-chords or 3 note chords with an electric guitar. They just add more to the overall mix of the music.
Comment: I have to disagree. One of my favorite sounds (which I'm always trying to work into a song) is an inverted sus2 chord using all six strings and a medium-high level of distortion. An example on D of this would be 5 5 7 7 5 5 (barre on 5, ring and pinky on 7). It just sounds pretty awesome. There's also an open E5 made by 0 7 9 9 0 0 (lowest to highest) and inverted open A5 of 0 0 7 9 10 0. You just have to play the **right** six string chords.
Answer: Raphael's answer is patently false.  This stems from using distortion and/or overdrive on an amplified instrument.  Power chords (or specifically the interval of a fifth) create a strong implied "almost major" overtone when distorted (asymmetric distortion; symmetric distortion creates additional harsh overtones which is why most people prefer the former).  That implied major tone isn't in temper with the instrument itself and so sounds bad played against other intervals.
Players that play clean, jazz players for instance, and some very lightly distorted rock bands (the stones come to mind here, the who, zepplin) or guitarists that are playing effects other than distortion (Fripp, Satch, Vai, etc) often play much more complex rhythm sections than three string chords or power chords.
Tonal reinforcement is common in pretty much every type of music ever written, from punk rock to jazz to orchestral music.  Multiple instruments often play the same exact notes in the same tonal range to reinforce that part of the texture.  Standing out from the group has very little to do with it.  This is even common in early piano and harpsichord music (Mozart K471) where the fundamental is repeated over three octaves to reinforce it (you hear the octave overtone anyway, so those notes aren't "distinct").
Comment: Saying "patently false" is a bit harsh, but I think it is fair to say that distortion generally requires using fewer strings, while cleaner sounds work better with more.  I use chords of 5-6 strings almost exclusively (sometimes strummed as a group, or 1+4, or five individual notes, or three individual notes followed by the last two together, etc.)  My reason for using an electric rather than an acoustic isn't that I want the "electric guitar sound", so much as that cheap electrics have better actions than cheap acoustics.


RGB to HSL conversion

Question: I'm creating a Color Picker tool and for the HSL slider, I need to be able to convert RGB to HSL. When I searched SO for a way to do the conversion, I found this question HSL to RGB color conversion.
While it provides a function to do conversion from RGB to HSL, I see no explanation to what's really going on in the calculation. To understand it better, I've read the HSL and HSV on Wikipedia.
Later, I've rewritten the function from the "HSL to RGB color conversion" using the calculations from the "HSL and HSV" page.
I'm stuck at the calculation of hue if the R is the max value. See the calculation from the "HSL and HSV" page:

This is from another wiki page that's in Dutch:

and this is from the answers to "HSL to RGB color conversion":
case r: h = (g - b) / d + (g < b ? 6 : 0); break; // d = max-min = c

I've tested all three with a few RGB values and they seem to produce similar (if not exact) results. What I'm wondering is are they performing the same thing? Will get I different results for some specific RGB values? Which one should I be using?
hue = (g - b) / c;                   // dutch wiki
hue = ((g - b) / c) % 6;             // eng wiki
hue = (g - b) / c + (g < b ? 6 : 0); // SO answer

function rgb2hsl(r, g, b) {
    // see https://en.wikipedia.org/wiki/HSL_and_HSV#Formal_derivation
    // convert r,g,b [0,255] range to [0,1]
    r = r / 255,
    g = g / 255,
    b = b / 255;
    // get the min and max of r,g,b
    var max = Math.max(r, g, b);
    var min = Math.min(r, g, b);
    // lightness is the average of the largest and smallest color components
    var lum = (max + min) / 2;
    var hue;
    var sat;
    if (max == min) { // no saturation
        hue = 0;
        sat = 0;
    } else {
        var c = max - min; // chroma
        // saturation is simply the chroma scaled to fill
        // the interval [0, 1] for every combination of hue and lightness
        sat = c / (1 - Math.abs(2 * lum - 1));
        switch(max) {
            case r:
                // hue = (g - b) / c;
                // hue = ((g - b) / c) % 6;
                // hue = (g - b) / c + (g < b ? 6 : 0);
                break;
            case g:
                hue = (b - r) / c + 2;
                break;
            case b:
                hue = (r - g) / c + 4;
                break;
        }
    }
    hue = Math.round(hue * 60); // °
    sat = Math.round(sat * 100); // %
    lum = Math.round(lum * 100); // %
    return [hue, sat, lum];
}

Comment: The English one looks correct to me, the Dutch one I don't recognise and I don't understand what it says on the wiki page. :)
Comment: Here's the octave implementation of hsv2rgb: http://hg.savannah.gnu.org/hgweb/octave/file/549f8625a61b/scripts/image/hsv2rgb.m
Answer: I've been reading several wiki pages and checking different calculations, and creating visualizations of RGB cube projection onto a hexagon. And I'd like to post my understanding of this conversion. Since I find this conversion (representations of color models using geometric shapes) interesting, I'll try to be as thorough as I can be. First, let's start with RGB.
RGB
Well, this doesn't really need much explanation. In its simplest form, you have 3 values, R, G, and B in the range of [0,255]. For example, 51,153,204. We can represent it using a bar graph:

RGB Cube
We can also represent a color in a 3D space. We have three values R, G, B that corresponds to X, Y, and Z. All three values are in the [0,255] range, which results in a cube. But before creating the RGB cube, let's work on 2D space first. Two combinations of R,G,B gives us: RG, RB, GB. If we were to graph these on a plane, we'd get the following:

These are the first three sides of the RGB cube. If we place them on a 3D space, it results in a half cube:

If you check the above graph, by mixing two colors, we get a new color at (255,255), and these are Yellow, Magenta, and Cyan. Again, two combinations of these gives us: YM, YC, and MC. These are the missing sides of the cube. Once we add them, we get a complete cube:

And the position of 51,153,204 in this cube:

Projection of RGB Cube onto a hexagon
Now that we have the RGB Cube, let's project it onto a hexagon. First, we tilt the cube by 45° on the x, and then 35.264° on the y. After the second tilt, black corner is at the bottom and the white corner is at the top, and they both pass through the z axis.

As you can see, we get the hexagon look we want with the correct hue order when we look at the cube from the top. But we need to project this onto a real hexagon. What we do is draw a hexagon that is in the same size with the cube top view. All the corners of the hexagon corresponds to the corners of the cube and the colors, and the top corner of the cube that is white, is projected onto the center of the hexagon. Black is omitted. And if we map every color onto the hexagon, we get the look at right.

And the position of 51,153,204 on the hexagon would be:

Calculating the Hue
Before we make the calculation, let's define what hue is.

Hue is roughly the angle of the vector to a point in the projection, with red at 0°.

... hue is how far around that hexagon's edge the point lies.

This is the calculation from the HSL and HSV wiki page. We'll be using it in this explanation.

Examine the hexagon and the position of 51,153,204 on it.

First, we scale the R, G, B values to fill the [0,1] interval.
R = R / 255    R =  51 / 255 = 0.2
G = G / 255    G = 153 / 255 = 0.6
B = B / 255    B = 204 / 255 = 0.8

Next, find the max and min values of R, G, B
M = max(R, G, B)    M = max(0.2, 0.6, 0.8) = 0.8
m = min(R, G, B)    m = min(0.2, 0.6, 0.8) = 0.2

Then, calculate C (chroma). Chroma is defined as:

... chroma is roughly the distance of the point from the origin.

Chroma is the relative size of the hexagon passing through a point ...

C = OP / OP'
C = M - m
C = 0.8- 0.2 = 0.6

Now, we have the R, G, B, and C values. If we check the conditions, if M = B returns true for 51,153,204. So, we'll be using H'= (R - G) / C + 4.
Let's check the hexagon again. (R - G) / C gives us the length of BP segment.
segment = (R - G) / C = (0.2 - 0.6) / 0.6 = -0.6666666666666666

We'll place this segment on the inner hexagon. Starting point of the hexagon is R (red) at 0°. If the segment length is positive, it should be on RY, if negative, it should be on RM. In this case, it is negative -0.6666666666666666, and is on the RM edge.

Next, we need to shift the position of the segment, or rather P₁ towars the B (because M = B). Blue is at 240°. Hexagon has 6 sides. Each side corresponds to 60°. 240 / 60 = 4. We need to shift (increment) the P₁ by 4 (which is 240°). After the shift, P₁ will be at P and we'll get the length of RYGCP.
segment = (R - G) / C = (0.2 - 0.6) / 0.6 = -0.6666666666666666
RYGCP   = segment + 4 = 3.3333333333333335

Circumference of the hexagon is 6 which corresponds to 360°. 53,151,204's distance to 0° is 3.3333333333333335. If we multiply 3.3333333333333335 by 60, we'll get its position in degrees.
H' = 3.3333333333333335
H  = H' * 60 = 200°

In the case of if M = R, since we place one end of the segment at R (0°), we don't need to shift the segment to R if the segment length is positive. The position of P₁ will be positive. But if the segment length is negative, we need to shift it by 6, because negative value means that the angular position is greater than 180° and we need to do a full rotation.
So, neither the Dutch wiki solution hue = (g - b) / c; nor the Eng wiki solution hue = ((g - b) / c) % 6; will work for negative segment length. Only the SO answer hue = (g - b) / c + (g < b ? 6 : 0); works for both negative and positive values.
JSFiddle: Test all three methods for rgb(255,71,99)

JSFiddle: Find a color's position in RGB Cube and hue hexagon visually
Working hue calculation:

console.log(rgb2hue(51,153,204));
console.log(rgb2hue(255,71,99));
console.log(rgb2hue(255,0,0));
console.log(rgb2hue(255,128,0));
console.log(rgb2hue(124,252,0));

function rgb2hue(r, g, b) {
  r /= 255;
  g /= 255;
  b /= 255;
  var max = Math.max(r, g, b);
  var min = Math.min(r, g, b);
  var c   = max - min;
  var hue;
  if (c == 0) {
    hue = 0;
  } else {
    switch(max) {
      case r:
        var segment = (g - b) / c;
        var shift   = 0 / 60;       // R° / (360° / hex sides)
        if (segment < 0) {          // hue > 180, full rotation
          shift = 360 / 60;         // R° / (360° / hex sides)
        }
        hue = segment + shift;
        break;
      case g:
        var segment = (b - r) / c;
        var shift   = 120 / 60;     // G° / (360° / hex sides)
        hue = segment + shift;
        break;
      case b:
        var segment = (r - g) / c;
        var shift   = 240 / 60;     // B° / (360° / hex sides)
        hue = segment + shift;
        break;
    }
  }
  return hue * 60; // hue is in [0,6], scale it up
}
Comment: Hi, I am shocked that you answer is ignored or not seen by majority.
Thank you so much for explanation I have been researching it for a while and your answer is the best
Comment: @AlexanderGurevich I just love to get to the bottom of things, and this was a good study. I wanted to put it out in the open. I'm glad someone have found it useful :)
Comment: @Binajmen You can check the one `rgb2hsl` in the question. All three hue calculations (for M=R) are there. Just delete the first two.
Comment: Wow, amazing answer! I would upvote it more than once if that would be possible :D
Comment: Still in 2021, this is so wonderful. Thank you for your work.
Comment: Awesome auto-answering, thanks for the effort. For the sake of completeness, you could perhaps provide the final `rgb2hsl` :)
Comment: I do not follow the logic here.  You project the cube onto a hexagon, but that only gives you a certain amount of colors.  My idea was to transform the cube into a hexagonal grid and come up with a formula for that.  Not saying your wrong just not sure if all the colors are there.
Comment: @akinuri I think it depends on the programming language used, and its definition of the [modulo operator](https://en.wikipedia.org/wiki/Modulo#Variants_of_the_definition). In most programming languages, `% 6` will ensure a positive result, effectively adding 6 (as many times as needed) when `g - b` is negative. That is definitely the case in python for example, and the Eng wiki and SO codes are then strictly identical.
Comment: Are we working with RGB as-is? or do we need to linearize it first?
Comment: @akinuri Why wouldn't the Eng wiki solution (`hue = ((g - b) / c) % 6`) work for negative segment lengths? The `% 6` modulo operation would do exactly the same as `+ (g < b ? 6 : 0)`.
Comment: @LeadVaxeral I think you're mistaken about my question/answer. This is not really about 3D projection. It's about calculating the hue. This does not require 3D. If you want to create a 3D space that contains all colors, you simply use the cube or modify/reshape it. That is out of scope of this post.
Comment: @Xavier It simply doesn't. See the "test all three methods" link in my answer. Also check [Matey](https://stackoverflow.com/users/4437888/matey)'s [answer](https://stackoverflow.com/a/39124032/2202732) (and the comments).
Comment: I'd also like to mention that in places where `hue = ((g - b) / c) % 6` seem to work, the actual calculation is seperated into two. The hue is later corrected (for negative values) with `if (h < 0) h += 360;`. For example, examine [Crashalot](https://stackoverflow.com/users/144088/crashalot)'s [answer](https://stackoverflow.com/a/58426404/2202732). So saying `hue = ((g - b) / c) % 6` works is misleading. It's incomplete. That's what got me in the first place. Wiki pages do not seem to mention this.
Comment: @Xavier Oh, right. Indeed that seems to be the case with Python. In JavaScript, however, `%` doesn't handle negative values. So one needs to manually adjust the result. Thanks for point it out.
Answer: This page provides a function for conversion between color spaces, including RGB to HSL.
function RGBToHSL(r,g,b) {
  // Make r, g, and b fractions of 1
  r /= 255;
  g /= 255;
  b /= 255;

  // Find greatest and smallest channel values
  let cmin = Math.min(r,g,b),
      cmax = Math.max(r,g,b),
      delta = cmax - cmin,
      h = 0,
      s = 0,
      l = 0;

  // Calculate hue
  // No difference
  if (delta === 0)
    h = 0;
  // Red is max
  else if (cmax === r)
    h = ((g - b) / delta) % 6;
  // Green is max
  else if (cmax === g)
    h = (b - r) / delta + 2;
  // Blue is max
  else
    h = (r - g) / delta + 4;

  h = Math.round(h * 60);

  // Make negative hues positive behind 360°
  if (h < 0)
      h += 360;

  // Calculate lightness
  l = (cmax + cmin) / 2;

  // Calculate saturation
  s = delta === 0 ? 0 : delta / (1 - Math.abs(2 * l - 1));

  // Multiply l and s by 100
  s = +(s * 100).toFixed(1);
  l = +(l * 100).toFixed(1);

  return "hsl(" + h + "," + s + "%," + l + "%)";
}

Comment: The code on line 3, 4 and 5 is not making fractions of 1.
It's scaling the number into a ratio.
If anything, it would be calculating the fraction of 255.
Answer: Continuing from my comment, the English version looks correct, but I'm not sure what's happening in the Dutch version as I don't understand the WIKI page.
Here is an ES6 version that I made from the English WIKI page, along with some sample data that appear to match the WIKI examples (give or take Javascript's numeric accuracy). Hopefully it may be of use while creating your own function.

// see: https://en.wikipedia.org/wiki/RGB_color_model
// see: https://en.wikipedia.org/wiki/HSL_and_HSV

// expects R, G, B, Cmax and chroma to be in number interval [0, 1]
// returns undefined if chroma is 0, or a number interval [0, 360] degrees
function hue(R, G, B, Cmax, chroma) {
  let H;
  if (chroma === 0) {
    return H;
  }
  if (Cmax === R) {
    H = ((G - B) / chroma) % 6;
  } else if (Cmax === G) {
    H = ((B - R) / chroma) + 2;
  } else if (Cmax === B) {
    H = ((R - G) / chroma) + 4;
  }
  H *= 60;
  return H < 0 ? H + 360 : H;
}

// returns the average of the supplied number arguments
function average(...theArgs) {
  return theArgs.length ? theArgs.reduce((p, c) => p + c, 0) / theArgs.length : 0;
}

// expects R, G, B, Cmin, Cmax and chroma to be in number interval [0, 1]
// type is by default 'bi-hexcone' equation
// set 'luma601' or 'luma709' for alternatives
// see: https://en.wikipedia.org/wiki/Luma_(video)
// returns a number interval [0, 1]
function lightness(R, G, B, Cmin, Cmax, type = 'bi-hexcone') {
  if (type === 'luma601') {
    return (0.299 * R) + (0.587 * G) + (0.114 * B);
  }
  if (type === 'luma709') {
    return (0.2126 * R) + (0.7152 * G) + (0.0772 * B);
  }
  return average(Cmin, Cmax);
}

// expects L and chroma to be in number interval [0, 1]
// returns a number interval [0, 1]
function saturation(L, chroma) {
  return chroma === 0 ? 0 : chroma / (1 - Math.abs(2 * L - 1));
}

// returns the value to a fixed number of digits
function toFixed(value, digits) {
  return Number.isFinite(value) && Number.isFinite(digits) ? value.toFixed(digits) : value;
}

// expects R, G, and B to be in number interval [0, 1]
// returns a Map of H, S and L in the appropriate interval and digits
function RGB2HSL(R, G, B, fixed = true) {
  const Cmin = Math.min(R, G, B);
  const Cmax = Math.max(R, G, B);
  const chroma = Cmax - Cmin;
  // default 'bi-hexcone' equation
  const L = lightness(R, G, B, Cmin, Cmax);
  // H in degrees interval [0, 360]
  // L and S in interval [0, 1]
  return new Map([
    ['H', toFixed(hue(R, G, B, Cmax, chroma), fixed && 1)],
    ['S', toFixed(saturation(L, chroma), fixed && 3)],
    ['L', toFixed(L, fixed && 3)]
  ]);
}

// expects value to be number in interval [0, 255]
// returns normalised value as a number interval [0, 1]
function colourRange(value) {
  return value / 255;
};

// expects R, G, and B to be in number interval [0, 255]
function RGBdec2HSL(R, G, B) {
  return RGB2HSL(colourRange(R), colourRange(G), colourRange(B));
}

// converts a hexidecimal string into a decimal number
function hex2dec(value) {
  return parseInt(value, 16);
}

// slices a string into an array of paired characters
function pairSlicer(value) {
  return value.match(/../g);
}

// prepend '0's to the start of a string and make specific length
function prePad(value, count) {
  return ('0'.repeat(count) + value).slice(-count);
}

// format hex pair string from value
function hexPair(value) {
  return hex2dec(prePad(value, 2));
}

// expects R, G, and B to be hex string in interval ['00', 'FF']
// without a leading '#' character
function RGBhex2HSL(R, G, B) {
  return RGBdec2HSL(hexPair(R), hexPair(G), hexPair(B));
}

// expects RGB to be a hex string in interval ['000000', 'FFFFFF']
// with or without a leading '#' character
function RGBstr2HSL(RGB) {
  const hex = prePad(RGB.charAt(0) === '#' ? RGB.slice(1) : RGB, 6);
  return RGBhex2HSL(...pairSlicer(hex).slice(0, 3));
}

// expects value to be a Map object
function logIt(value) {
  console.log(value);
  document.getElementById('out').textContent += JSON.stringify([...value]) + '\n';
};

logIt(RGBstr2HSL('000000'));
logIt(RGBstr2HSL('#808080'));
logIt(RGB2HSL(0, 0, 0));
logIt(RGB2HSL(1, 1, 1));
logIt(RGBdec2HSL(0, 0, 0));
logIt(RGBdec2HSL(255, 255, 254));
logIt(RGBhex2HSL('BF', 'BF', '00'));
logIt(RGBstr2HSL('008000'));
logIt(RGBstr2HSL('80FFFF'));
logIt(RGBstr2HSL('8080FF'));
logIt(RGBstr2HSL('BF40BF'));
logIt(RGBstr2HSL('A0A424'));
logIt(RGBstr2HSL('411BEA'));
logIt(RGBstr2HSL('1EAC41'));
logIt(RGBstr2HSL('F0C80E'));
logIt(RGBstr2HSL('B430E5'));
logIt(RGBstr2HSL('ED7651'));
logIt(RGBstr2HSL('FEF888'));
logIt(RGBstr2HSL('19CB97'));
logIt(RGBstr2HSL('362698'));
logIt(RGBstr2HSL('7E7EB8'));

Comment: I don't know about much more complicated (sure, in all it can do a few more things than your example), but basically it's the same but broken down into smaller testable and reusable functions rather than a single function. I could probably do it in a single line of code, but that wouldn't be very readable, reusable or maintainable. Oh and I used ES6 rather than just ES3, I know you didn't ask for any code but I needed to dust off some rust and I thought that I may as well share my tinkering with you in an answer rather than just the comment. :)
Comment: I just finished updating my answer and noticed that `hue = ((g - b) / c) % 6;` results in incorrect values. It doesn't handle negative values. Also I don't see any scenario where `(g - b) / c)` is greater than 6. It should always be <= 1. So why do mod? See this [fiddle](https://jsfiddle.net/f15dbw06/) test.
Comment: In my answer you will see a check for the negative, and add 360. I haven't looked so close at the theory or the math, I have just assumed that it is correct as I have seen it in several sources and the numbers come out as expected.
Comment: I really appreciate the effort, but this seems much more complicated than the one I've already written :) I've been reading the wiki pages over and over again, and creating the rgb cube-to-hexagon projection in a 3d software. I'm really close to understanding *everything* in the calculation. I'll post my understanding sometime soon. (Sorry for the late reply :)
Comment: I've posted my answer (if you haven't seen it already). It's incomplete right now. Updated it once. Gonna update it again. I'd like your feedback (I might be doing it wrong, idk :)
Comment: It's a very pretty description of what needs to be calculated, but so far doesn't answer the actual question that you posted. I'm kind of thinking that perhaps your questions and answer were better suited to http://mathoverflow.net/ as it doesn't really seem to have much to do with the programming aspect, but a great deal to do with mathematics.
Comment: It's still not done yet. I'll add the last part where I'll talk about the calculation. I liked this conversion thing so much that I wanted to be thorough with it. I'm sure it'll be useful for future visitors.
Answer: Hue in HSL is like an angle in a circle. Relevant values for such angle reside in the 0..360 interval. However, negative values might come out of the calculation. And that's why those three formulas are different. They do the same in the end, they just handle differently the values outside the 0..360 interval. Or, to be precise, the 0..6 interval which is then eventually multiplied by 60 to 0..360
hue = (g - b) / c;  // dutch wiki
does nothing with negative values and presumes the subsequent code can handle negative H values.
hue = ((g - b) / c) % 6; // eng wiki uses the % operator to fit the values inside the 0..6 interval
hue = (g - b) / c + (g < b ? 6 : 0); // SO answer takes care of negative values by adding +6 to make them positive
You see that these are just cosmetic differences. Either the second or the third formula will work fine for you.
Comment: I don't think the second will work for both positive and negative values.  I don't see any scenario where `(g - b) / c)` is greater than 6. It should always be <= 1. So mod seems redundant. Only the third formula works as expected. See my updated answer.
Comment: @akinuri : `mod` for negative values of the dividend increases the dividend by the divisor until it's positive. Which is exactly the same as the third formula.
Comment: See this [jsfiddle](https://jsfiddle.net/f15dbw06/). `en_rgb2hue()` uses the mod calculation. It does not give the correct value.
Comment: My bad. There are obviously two worlds regarding how the negative values should be handled by `%`. Thanks for correcting me.

RGB to HSL conversion


Find the image of this Linear Transformation

Question: The Question:
Let $V$ be a finite-dimensional complex inner product space.
Let $W$ be a subspace of $V$ with basis $\{ e_1,\dots,e_k\}$.
Let $T:V \rightarrow W$ be a linear transformation defined by
$$T(v) = \langle v,e_1 \rangle e_1+\langle v,e_2 \rangle e_2+ \cdots + \langle v,e_k \rangle e_k$$
Show that the Image of $T$ is $W$, $\;$ i.e. $\text{Im}(T) = W$.

My Attempt:
Showing one direction of the inclusion is easy:
\begin{align}
w \in \text{Im}(T) & \implies \exists \; v \in V \,|\, T(v) = w \\
& \implies w = T(v) = \langle v,e_1 \rangle e_1+\langle v,e_2 \rangle e_2+ \cdots + \langle v,e_k \rangle e_k \\
& \implies w \in \text{span} \{e_1,\dots,e_k\} \\
& \implies w \in W
\end{align}
But I don't know how to show the converse.
I suppose that it suffices to show that $\exists \; v_i \in V \,|\, T(v_i)=e_i$ for each $i=1,\dots,n$, but when I tried to construct such $v_i$ it became really messy.
I have also considered Gram-Schimdt but it doesn't seem to help.
Any hints?
Comment: Maybe try and show that the restriction of $T$ to $W\subset V$, i.e. $T|_W:W \to W$ is an isomorphism.
Comment: Aren't you just restating what I have to prove...?
Comment: Well, I guess you can read my comment that way. My point is: Show that $T|_W$ is one-to-one, and then since $W$ is finite-dimensional, then $T|_W$ is automatically an isomorphism.
Answer: Hint: Because $V$ is finite dimensional, it suffices to show that $\ker T|_{W} = \{0\}$.
With that in mind: if $T(v) = 0$, then we can deduce that $\langle v,e_k \rangle = 0$ for $k = 1,\dots,n$.  Using the fact that $\{e_1,\dots,e_n\}$ is a basis and the linearity of our inner product, we can show that this implies that $\langle v,v \rangle = 0$, which is to say that $v = 0$.
Comment: I proceeded to reason that because $T|_W(v) = 0 \iff v=0$ and that $\text{Im}(T)\subset W$, it follows that $T|_W : W\rightarrow W$ is a bijection, and hence $\text{Im}(T) = W$.
Comment: Does that sound right?
Comment: @glowstonetrees that's right.


text-based viewer for profiling results

Question: Do you know of a text-based application for viewing results of application profiling? The profiling results basically contain a list of C++ function call backtraces and how often these backtraces were encountered; now I'm looking for a console tool to analyze the raw data (which backtrace occurred most often; which function was called most often, independent of call trace...).
So far I've created callgrind-compatible files from the raw data and then used the excellent KCachegrind tool for analysis; but now I'm also looking for a tool that works without on text-based terminal. Any ideas?
Answer: Take a look at callgrind_annotate.

This command reads in the profile data, and prints a sorted lists of functions, optionally with source annotation.
Answer: I wrote such a viewer once. It focussed on a line of code, showing the percent of samples running through that line, and a butterfly view allowing transitions to superior or subordinate lines of code.
It made a nice demo, but did I really use it? Not for long.
(I'm assuming the stack samples have been taken during the interval that you wish to speed up, i.e. not during user-wait.)
The thing is, the program is probably doing something wasteful in that time. (If it is not, you can't speed it up.)
Whatever that wasteful thing is, it consists of some percent of time being spent for poor reasons, like 10%, 50%, 90%, or whatever. During that time, it is on the stack, so an examination of the stack samples will show it.
And, you don't have to look at very many of them. If something is taking 50% of time, 1000 samples will show it on about 500, and 10 samples will show it on about 5. The larger number of samples will estimate the percentage with an extra digit of precision. If your goal is to isolate the problem so you can fix it, you don't need that extra digit.
So, a tool that shows you, by line, the percent of stack samples going through that line is a very nice thing to have, because the wasteful code will appear on it, showing the percentage.
What it does not show you is the reason why the statement is being executed, which is how you know if it's wasteful. Looking at the statement's context on the stack does tell you that.
So even though I had the viewer, I just ended up examining the samples themselves, and only about 10 or 20 of them. The bigger the percentage is, the smaller the number of samples I need to look at before I find it. Here's an example.

text-based viewer for profiling results