Como humanizar uma data em PHP

Question: Como humanizar uma data em PHP? Por exemplo, a partir dessa data 2015-08-20, quero que a função me retorne Há uma semana, pois é estranho ler algo como foi publicado há 754 dias ou publicado há 38 semanas.
Comment: Relacionada: http://pt.stackoverflow.com/q/82278/101
Comment: @bigown, valeu essa ai eu não conhecia
Answer: Conheço duas bibliotecas para fazer essa conversão, uma é a carbon que é uma especialização da DateTime padrão do php e a PHP Humanizer que humaniza datas
e outras informações a limitação dela hoje é que possui localização apenas para inglês e polonês.
Carbon
Faça a instalação do nfs carbon pelo composer na linha de comando.
composer require nesbot/carbon

O criação do objeto pede uma data e o timezone ambos são opcionais, setLocale() é reponsavel pelas traduções sua chamada pode ser feita via
método estatico e diffForHumans() retorna a string formatada de quanto tempo passou desde a data inicial.
<?php
require 'vendor/autoload.php';
use Carbon\Carbon;
$data = new Carbon('2015-08-20', 'America/Sao_Paulo');
$data->setLocale('pt_BR');
echo $data->diffForHumans() .PHP_EOL;

$data->addDays(3);
echo $data->diffForHumans() .PHP_EOL;

Saída:
há 1 semana
há 6 dias

PHP Humanizer
Instalação
composer require coduo/php-humanizer

difference() faz o mesmo que diffForHumans() retorna uma string formatada aproximada, como 1 week ago, preciseDifference() exibe a diferença completa algo como:
20 days, 16 minutes, 52 seconds from now
<?php
require 'vendor/autoload.php';
use Coduo\PHPHumanizer\DateTime;

$data = new \DateTime('2015-08-10');
echo DateTime::difference($data, new \DateTime()) .PHP_EOL;
echo DateTime::preciseDifference($data, new \DateTime()) .PHP_EOL;

Saída:
3 weeks from now
20 days, 18 minutes, 7 seconds from now

Answer: Seguindo o mesmo princípio desta postagem, pode partir deste código:
function RelativeTimeString($timestamp) {
    $minute = 60;
    $hour = $minute * 60;
    $day = $hour * 24;
    $month = 30 * $day;
    $year = 12 * $month;

    $delta = floor(time() - $timestamp);
    if ($delta < 2 )           return 'Agorinha';
    if ($delta < 1 * $minute)  return "Há $delta segundos";
    if ($delta < 2 * $minute)  return 'Há um minuto';
    if ($delta < 45 * $minute) return 'Há '.round($delta / $minute).' minutos';
    if ($delta < 90 * $minute) return 'Há uma hora';
    if ($delta < 23 * $hour)   return 'Há '.round($delta / $hour).' horas';
    if ($delta < 48 * $hour)   return 'Ontem';
    if ($delta < 30 * $day)    return 'Há '.round($delta / $day).' dias';
    if ($delta < 45 * $day)    return 'Há um mês';
    if ($delta < 11 * $month)  return 'Há '.round($delta / $month).' meses';
    if ($delta < 18 * $month)  return 'Há um ano';
    return 'Há '.round($delta / $year).' anos';
}

Veja funcionando no IDEONE
Notas:

Por uma questão de conveniência, mantive o parâmetro como timestamp (em segundos, mais fácil de adaptar pra qualquer linguagem ou implementação). Para entrar com a data em string, basta usar
strtotime( $DateString )

em vez de
$timestamp

lembrando que datas com / são consideradas MM/DD/AAAA e com - são consideradas DD-MM-AAAA. Datas em AAAA-MM-DD são entendidas corretamente com qualquer separador.
O time() é baseado em UTC, se seus dados estiverem salvos em hora local (o que pode não ser interessante para este tipo de aplicação), precisa acrescentar a diferença:
$tzseconds = date('Z');
$delta = floor(time() - $timestamp - $tzseconds);

Considere que se tiver intervalos maiores que a capacidade de inteiros do PHP, precisa revisar a aplicação, pois inteiros de 32 bits só cobrem um span de 68 anos. Esta não é uma limitação da função em si, mas sim do modo com que inteiros são armazenados no PHP.

Como humanizar uma data em PHP


How to add label to sphere in three.js

Question: I am new to three.js but here is what I am trying to do.
I have a sphere.. and I want to add an id label at a distance (say) 2 units to its surface.
So
var geometry = new THREE.SphereGeometry( 50, 25, 25 );
 var draw_object = new THREE.Mesh( geometry, [ new THREE.MeshBasicMaterial( {  color: Math.random() * 0xffffff, opacity: 0.5 } ) ] );

now I want to give it a name "sphere 1"
and then at a distance "x" units from surface of sphere.. assign a label to it.
The catch is this sphere moves in space..so the label has to stay with it.
I have been trying since past two days without any luck.
Help
Any s
Comment: Have you checked out this previous question?

http://stackoverflow.com/questions/11447821/how-to-add-label-to-a-three-mesh
Answer: You will probably want to use a Sprite as in the example referenced above (how to add Label to a THREE.Mesh?) However, instead of setting the position to be the mouse coordinates, calculate the offset from the sphere -- say it was, for example, (3,4,5) -- and do something like
label.position.set( sphere.position.add( new THREE.Vector3(3,4,5) ) );

This way, the label's position stores a reference to the sphere's position, and as the sphere moves the label will move with it.

How to add label to sphere in three.js


What is correct selector for radios to determine if ANY radio is selected?

Question: Using #states to change form element visibility, I would like a 2nd element to be visible only if the 1st element is filled in. The first element is a pair of radio buttons, so I tried:
  '#states' => array('visible' => array(
  ':input[name="radio-id"]' => array('value' => '0', 'value' => '1'),
    ),),

However that doesn't work, the 2nd value condition clobbers the first, so the other element only appears if the 2nd radio ('1') is checked. So then I tried:
    :input[name="radio-id"]' => array('checked' => TRUE),

Nope, that doesn't work either.
What is the correct syntax to use for this, and which documentation page is it on? (drupal.org or other site?) I've looked and looked but can't find it.
Answer: Had same problem today. A slight modification of the negated value expression proposed on this comment: "Empty Radio Selection" on drupal_process_states() API page, did the trick for me!
'#states' => array(
   'visible' => array(
     ':input[name="radios-name"]' => array('!value' => false),
   ),
 ),

I just wanted the select list with the above #states entry to be invisible while no selection has still been made on my list of five radios (sharing name "radios-name").
Radios were also '#required' => true, in my case and all 5 individual radio-buttons have non-numeric string values. No #default_value is specified in my case either.
Disclaimer: I have only tested this on Chrome!
Comment: Excellent, thanks. Works on Firefox too, by the way.
Comment: Thanks - works well. Note in the example you link to they are using the _invisible_ state as opposed to _visible_ that you are using. I also have to use _invisible_ to get it to work.
Answer: You should take a look at the States example in the Form Example in the Examples project. This exact situation is demonstrated several different ways.
Comment: Please try to post code snippet here. We want our users here as long as possible.
Answer: The documentation for the #states property is in the documentation for drupal_process_states(), which contains the following sentence and example code.

When referencing select lists and radio buttons in remote conditions, a 'value' condition must be used:
  '#states' => array(
    // Show the settings if 'bar' has been selected for 'foo'.
    'visible' => array(
      ':input[name="foo"]' => array('value' => 'bar'),
    ),
  ),

The code you are using in your second snippet works for checkboxes, such as in the following example.
$form['toggle_me'] = array(
  '#type' => 'checkbox',
  '#title' => t('Tick this box to type'),
);

$form['settings'] = array(
  '#type' => 'textfield',
  '#states' => array(
    // Only show this field when the 'toggle_me' checkbox is enabled.
    'visible' => array(
      ':input[name="toggle_me"]' => array('checked' => TRUE),
    ),
  ),
);


XSLT: Exclude an element but keep it's sub elements

Question: Hi I want to exclude a specific element, in this case <ph> and keep it's sub elements.
xml file:
<?xml version="1.0" encoding="UTF-8"?>

   <s>
      <ph>
         <w>this</w>
         <w>is</w>
         <w>my</w>
         <w>first</w>
         <w>sentence</w>
         <pc>.</pc>
      </ph>
   </s>
   <s>
      <ph>
         <w>this</w>
         <w>is</w>
         <w>my</w>
         <w>second</w>
         <w>sentence</w>
         <pc>.</pc>
      </ph>
   </s>

desired output:
<?xml version="1.0" encoding="UTF-8"?>

   <s>
      <w>this</w>
      <w>is</w>
      <w>my</w>
      <w>first</w>
      <w>sentence</w>
      <pc>.</pc>
   </s>
   <s>
      <w>this</w>
      <w>is</w>
      <w>my</w>
      <w>second</w>
      <w>sentence</w>
      <pc>.</pc>
   </s>

xsl code:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">
<xsl:template match="p|s|w|pc">
        <xsl:copy>
            <xsl:copy-of select="@*"/>
            <xsl:copy-of select="p|s|w|pc"/>
            <xsl:apply-templates select="*/*[not(self::phr)]"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

The problem is that sometimes when <ph> is not there I lose sub elements, or have the same xml file with the <ph> element.
Comment: What's the purpose of the `[not(self::phr)]` predicate in your XSLT?
Comment: I saw that while googling to exclude an element on some forums but didn't work
Answer: How about:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="ph">
    <xsl:apply-templates/>
</xsl:template>

</xsl:stylesheet>

Comment: Without any more context, this is the standard answer.
Comment: Yes thank you, but can you explain your code how it's excluding the `ph` element, you are applying a template to the element but it's empty, is this how it works when the `apply-templates` is empty (nothing to do) we get rid of the marched element ?
Comment: The template is NOT empty. It contains the `xsl:apply-templates` instruction - and ONLY the `xsl:apply-templates` instruction. This means that when the processor gets to `ph`, it will NOT copy it, but WILL continue to process its children.


Area calculation of ellipse $x^2/2+y^2=1$

Question: Calculate the area of the ellipse that you get when you rotate the ellipse $$\frac{x^2}{2}+y^2= 1$$ around the x-axis.
My approach has been to use the formula for rotation area from $-2$ to $2$. But this gives a complicated integral and I'm unsure about the limits $-2$ to $2$.
I would really appriciate a detailed solution to this
Comment: Wait, doesn't rotating an ellipse around an axis give you an [ellipsoid](https://en.wikipedia.org/wiki/Ellipsoid) in three dimensions such that this question should be asking you to compute the area of a surface? Rotating a curve around an axis doesn't seem to make much sense in two dimensions.
Comment: http://math.stackexchange.com/questions/247332/area-of-an-ellipse
Answer: Draw a diagram.
Note that the maximum value of $x$ occurs when $y=0$, that is, when $x=\sqrt{2}$, and the minimum value of $x$ is $x=-\sqrt{2}$.  The volume is
 $$\int_{-\sqrt{2}}^{\sqrt{2}} \pi y^2\,dx.$$
This is equal to
$$\int_{-\sqrt{2}}^{\sqrt{2}} \pi \left(1-\frac{x^2}{2}\right)\,dx.$$
Remark: Because I like symmetry, and dislike negative numbers, I would actually integrate from $x=0$ to $x=\sqrt{2}$, and double the result.
Comment: But the question was about the area and your answer is calculating the volume?
Answer: Surface
$\frac{x^2}{2}+y^2=1$
$S=2\pi\int_{-a}^{a}yds=4\pi\int_{0}^{a}yds$
$y'= -\frac{x}{2y}$
$ds=\sqrt{1+y'^2}dx=\sqrt{1+\frac{x^2}{4y^2}}dx=\frac{\sqrt{4y^2+x^2}}{2y}dx$
$S=4\pi\int_{0}^{\sqrt{2}}y\frac{\sqrt{4y^2+x^2}}{2y}dx=2\pi\int_{0}^{\sqrt{2}}\sqrt{4y^2+x^2}dx=2\pi\int_{0}^{\sqrt{2}}\sqrt{4-x^2}dx$
Substitution: $x=2sint, dx=2cost\cdot dt$
$S=2\pi\int_{0}^{\pi/4}\sqrt{4-4sin^2t}\cdot 2costdt=8\pi\int_{0}^{\pi/4}cos^2tdt=$
$=4\pi\int_{0}^{\pi/4}(1+cos2t)dt=4\pi[t+\frac{sin2t}{2}]_{0}^{\pi/4}dt=\pi(\pi+2)$


Spring Batch CommandLineJobRunner hangs when run by enterprise scheduler

Question: Our organization uses the Skybot enterprise scheduler to run batch jobs. We recently deployed our first spring batch app, and scheduled our jobs to run using CommandLineJobRunner as the main class (Main-Class is defined in the manifest of our jar). The command looks like this:
java -Dspring.profiles.active=production -jar AppName.jar jobs/jobName.xml jobId

When executed on the command line manually, the jobs run perfectly. When the same command is executed by the scheduler, the job immediately hangs with no output in the skybot logs, and no work done by the job. We investigated possible permissions problems, but none exist. The spring batch documentation states that CommandLineJobRunner is available for the purpose of running scheduled jobs from the shell, but all our jobs are hanging immediately upon execution. How can we solve this?
Answer: This appears to be an incompatibility between the CommandLineJobRunner class and Skybot. After deciding to replace the spring batch class with my own (loading the application context, constructing a JobLauncher, etc), I looked at the source code for CommandLineJobRunner. The main method has an early call to System.in.available(); when we run the job by typing the command and hitting enter, the standard input can read the line feed from the keyboard. Skybot as stdin, on the other hand, does not immediately block, but no line feed follows, so the program waits interminably for input.
From the main method of org.springframework.batch.core.launch.support.CommandLineJobRunner:
if (System.in.available() > 0) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String line = " ";
    while (line != null) {
        if (!line.startsWith("#") && StringUtils.hasText(line)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Stdin arg: " + line);
            }
            newargs.add(line);
        }
        line = reader.readLine();
    }
}

Our job parameters are all arguments to the initial command, so this code was unnecessary and problematic. The solution was to roll our own - very similar to CommandLineJobRunner but without any interaction with the standard input.
Comment: @MichaelMinella, thank you - I will need to look into that.


Python basic math

Question: Now, just before you start downvoting this question let me explain something, I'm pretty young and trying to learn python. I don't have any resources at all in school to learn this kind of math.
I am doing an exercise which says this:

Write a function called myPi that will return an approximation of PI
  (3.14159...). Use the Leibniz approximation.
  Located here: http://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80

So, they show how to calculate it like this:
http://upload.wikimedia.org/math/9/e/8/9e804b8a1a11e442be93fed1d52205a9.png
I have no idea how to calculate this in python. I mean, I don't even know how to calculate it normally since how would I calculate something that goes on infinite?
Also, another question is. Do I really need such advanced math to write programs later? Many of my friends learned to program while they were 12/13 and they had no problems. So is advanced math that important? Since I doubt my friends even knew how to calculate the area of a circle when they were learning.
Comment: In any case maths any computer science are strongly related..if you are interested in programming you slould really have a good background in maths
Comment: The key to your 'goes to infinity problem' is the the use of the word 'approximation'. The exact solution is an infinite sum. Since you cannot calculate an infanite sum, you must settle for an approximation, which is a finite sum. In other words if you stop that some at an arbitrary point you will be left with an approximation of ``π/4``, which you then solve for ``π``
Comment: To answer your second question, while knowledge of mathematics is definitely useful for programming, there are many, many tasks that programmers do that don't require more than basic algibra (you'll at least need algibra, most programming language symantics borrow pretty heavily from algibraic notation). You just happened to pick a problem that had some math beyond your experience, but there are many many problems that require no real math at all.
Comment: @aruisdante Whats the logic behind that though? I mean, pi/4 would give me 1/4th of PI. Don't I want all of pi? Can you show me code that would do what it asks for? Seeing some code would probably make it easier for me to understand.
Comment: @aruisdante I do understand algebra, that isn't a problem so I guess I am good?
Comment: Where did you get that exercise from? How much python do you already know?
Comment: If ``x = π/4`` then ``4x = π`` ;). The reason it's expressed as being equal to ``π/4`` is because that's what the nicely formed infinite sum adds up to, and they assume anyone actually wanting to calculate π will simply do the last step. Especially since that multiplication will amplify the innacuracy of the approximation, so it's important.
Answer: To address your first question, "how do you calculate an infinite series", the answer is to approximate it, usually using either:

A defined number of steps ("I want it to take this long"); or
Until the change at each step falls below a specified tolerance ("I want it to be this accurate").

To illustrate these (there is some relatively advanced Python here - leibniz_series is a generator to remove some duplicated code between the two implementations, it just churns out the terms in the series as long as you keep asking for them):
def leibniz_series():
    """Generator producing the Leibniz series (1, -1/3, 1/5, -1/7, ...)."""
    numerator = denominator = 1.0
    while True:
        yield (numerator / denominator)
        numerator *= -1
        denominator += 2

def pi_steps(steps=100):
    """Calculates pi from the Leibniz series with a defined number of steps."""
    values = leibniz_series()
    output = 0
    for _ in range(steps):
        value = 4 * next(values)
        output += value
    return output

def pi_tolerance(tolerance=0.0001):
    """Calculates pi from the Leibniz series with a defined output tolerance."""
    values = leibniz_series()
    output = 0
    value = 4 * next(values)
    while abs(value) > tolerance:
        output += value
        value = 4 * next(values)
    return output

As to the second question, "do you need to know ('advanced') maths to program", the answer really is "it depends what you're doing". Do you want to write a game with a physics engine? That would be very difficult to do without the equations of motion! But there are other things you can do with little more than the addition and subtraction required to deal with indexing into lists etc.
This specific exercise is more about using the software to carry out a repetitive task than it is about actually calculating pi (which is available as math.pi anyway!) Don't worry if you don't fully understand that maths at this stage; what is important is being able to understand the task (sum over some of the Leibniz series, multiply the result by 4) and how to break that down to steps you can represent in code.
Comment: In my defence, I do say as much! I wanted to decouple the idea of general `steps` vs. `tolerance` implementations from the specific series being used.
Comment: Perhaps a generator is unneccessarily complicated for a beginner.
Comment: @jonrsharpe Thanks, I guess I will go back and reference this when I have learned more python. It seems strange that they would give me this exercise so early on though.
Comment: Why did you leave the `4 *` outside the generator? Since the point of that generator is reducing code duplication and separating the creation of the steps from the rest it ought to be inside it...
Comment: @Bakuriu because the Leibniz series is `1, -1/3, 1/5, -1/7, ...`. You could refactor to move the `4`, but I thought it was clearer to have the generator `yield` the original series and have the multiplier elsewhere.
Answer: Given that @jonrsharpe already provided a solid answer on the specific problem, I'd like to add some additional information on learning Python or any language in general, and how much math may be necessary.
Many tutorials teach programming by recreating problems with known solutions, a method often considered "reinventing the wheel" or "reimplementing the wheel". This strategy will teach you how to solve a given problem and how to approach problems with similar nature.
However in order to make for a productive learning process you should focus on problems that you can reason about or for which you can visualize a way towards a solution. Otherwise you will get lost between the two things that you will need to learn: the tool (programming language) and the strategy (in this case, using math).
My suggestion, think of something that you want to do. Start with simple tasks like reading text files, parsing and transforming text, or small games like tic-tac-toe, hangman, simon and other memory games. Then break the problem into smaller problems that you can solve. For instance, you may not know how to draw a tic-tac-toe board, so first you would learn how to draw a line and a circle. Then you may not know how to make the computer smart and have it play against you, so instead make the game so you play against another person, and so on.
If you are just starting with programming, have a look at the exercises from Code Club. They are somewhat basic but still challenging.
Once you feel comfortable with the Python language, start looking at code written by other people. Since Python modules are generally open-source, you can search for any topic you might find interesting at PyPi and study how other people solved the problem.
If at any point you feel lost, you can also join the #Python channel on the Freenode IRC network where, with some patience, you will find someone willing to help you and give you some guidance.
Comment: is Codeclub python 2 or 3?
Comment: And also, I don't really have any goals to be completely honest. I was first told that I should try making a website with python? But isn't it too early as I have only been learning python for about a week.
Comment: @czaarek99 Codeclub is python 3 but can easily be done in python 2. As for making a website, again, is that something you want to do? In order to do a website you will need to learn a lot more technologies: Basic HTTP, HTML, CSS, (maybe) JavaScript, Databases,... not just Python. I don't know who is giving you advices but they clearly have no idea how to guide someone through the process of learning about programming. If you dive in all that at the same time you'll just get lost. Maybe https://www.python.org/about/gettingstarted/ would also be a good start for you.
Comment: Learning all that too would be useless to be completely honest. So what do you recommend? I mean, what tasks can I achieve when I know  python? I don't want to learn it and then end up actually being unable to create anything of use or just making small console applications. BTW I am using this website to learn: http://interactivepython.org/runestone/static/thinkcspy/toc.html
Comment: Programming like many other things in life, is not something you learn once and that's it, it's a constant learning process. Whatever you pick will get you there, what may differ is how much effort and how long it will take. Regardless, just make sure you don't rush through it, and most of all "try and see". Simply reading a solution may seem like you get it, but only when you try it you will find difficulties. In my opinion, the best learning process is one where you are faced with problems that you can't solve and then you actually come up or learn (new) ways to solve them.
Comment: I have that in mind, so I try to program things I have a really hard time to. It usually ends up being a mess in code but then I google and get a better solution. My question remains though, is there any serious use in python as itself?
Comment: Many, Just pick one https://www.python.org/about/success/
Answer: To actually solve the problem, consider the following:
The fraction portion of the sum is:
-1/3+1/5-1/7+1/9 ...

What is the pattern here? Well, first the sign obviously alternates every number. Next, the denumerator starts at 3 and then adds 2 to it every iteration. This, when combined with the initial value of 1 leads us to the mathematical sum that is represented on the wiki page,
Sum(-1^n/(2n+1))

How to express this in code?
Well, in 99% of programming languages, if you are trying to express a sum, which is a formula that is based on some input number (n), and then added to itself with the value calculated at (n+1), you should think for loop . in python, we can express that sum as so:
def approximate_pi(iterations):
    sum = 0
    for n in range(iterations):
        sum += (-1)**n/(2*n+1)
    return sum*4

This will, given a finite number of iterations, calculate an approximation of the value of π. The bigger iterarions, the more accurate the result will be, at the cost of increased run time.
Python, however, has some shortcuts that make this even easier. The first is the built in function sum, which returns the result of adding together the numbers in a list. The next is a list comprehension, which produces a list from some input arguments. This simplifies our original function to the following:
approximate_pi(iterations):
    return 4*sum([(-1)**n/(2*n+1) for n in range(iterations)])

This is doing basically the same series of operations, just in a way that's more efficient for python (for loops are expensive i n python) and that actually looks closer to the original pure mathematical notation.

Python basic math


Where are the RESTful module permissions other than `Administer REST resource configuration`?

Question: According to the tutorial An Introduction to RESTful Web Services in Drupal 8, the admin/people/permissions path should contain the following permissions:

But now that I installed the latest version of Drupal, the big surprise is on my website there are no other RESTful module permissions than Administer REST resource configuration, no permissions to grant DELETE, GET, PATCH or POST to each role.

I have Enabled all core web services modules (HAL, HTTP Basic Authentication, RESTful Web Services, Serialization) + REST UI module.
Are those permissions removed from Drupal 8.2.5?
Answer: This was introduced since 8.2.0
Accessing entities via REST no longer requires additional REST-specific permissions

This was actually only meant to be a temporary measure, because we
  already have an Entity Access API that governs access/operations to/on
  those entities. And in fact, Entity Access is respected when accessing
  entities via REST. So, there was no more reason for this to exist in
  Drupal 8.0.x and Drupal 8.1.x, but it was simply forgotten to be
  removed before Drupal 8.0.0's release. The fact that you needed to
  grant both those permissions as well as Entity Access needing to grant
  you access, was a source of confusion and frustration with Drupal 8's
  REST API, which has now been fixed.
So, as of Drupal 8.2.0, new installations no longer need those permissions to access entities via REST. Existing installations
  continue to have the old behavior. Existing sites can opt out of that
  behavior, and opt in to the new behavior, by modifying the
  rest.settings configuration from
bc_entity_resource_permissions: true
to
bc_entity_resource_permissions: false
(The latter is the default on new Drupal 8.2 installations.)
Comment: for my case that installed drupal 8.2, in order to get the REST module to work properly, should I left the bc_entity_resource_permissions: false or change it to true?
Comment: @Mde leave it false. The previous permissions it had was only temporary. Not having them is how D8 was/is meant to be.
Comment: thanks @No Sssweat, I thought the problem of my following question was this issue: http://drupal.stackexchange.com/questions/226130/getting-json-format-of-a-node-using-drupal , but it seems the problem is something else, could you help me solve it? thanks again.


How to let a user switch between blocks that need to be shown?

Question: I have pre-defined blocks A,B and C that are meant to be placed in the sidebar_first region. What I would like to achieve is: a visitor could select the block that needs to be displayed for the sidebar_first region when click on a dropdown button containing option A, B and C. This dropdown button should exist somewhere on the same page of these blocks (means the visitor will not do it in the admin pages).
For example, if Option A is selected by default, then only Block A should be shown. If the visitor clicks on Option B, then Block A will be hidden (or removed) and Block B will show up.
The way I could think of is to disable and enable blocks programmatically on clicking the dropdown button, and then refresh the region via ajax, but I have no clue how this can be acheived. I am also open to other approaches.
Answer: For Drupal 8, there is the Block Tabs module:

This module provides basic tabs function for Drupal. Deep integration with Drupal8's API, Plugin, Block, Entity and Config API. Provide simple tabs functions, you can control the CSS by your self. Based on jquery.ui.tabs...Tab type using Plugin system, it is very easy to extend.

For Drupal 7:
The Quicktabs module might work for you.

The Quicktabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes and other quicktabs. You can create a block on your site containing multiple tabs with corresponding content.

You would create a Quicktabs instance (Admin > Structure > Quicktabs) with the blocks you want to display. You can select a default block, and load the blocks with or without AJAX. With certain render options, you can choose to maintain a history of the user's selection.

The Quicktabs Styles sub-module provides various tab styles (enable the Quicktabs Styles module to use them and visit Admin > Structure > Quicktabs > Styles to preview them). Or you can style the tabs with your own CSS. Examples of some of the included styles:

Once your Quicktabs instance is created, you would add the block to the sidebar region (Admin > Structure > Blocks). Example:

If you need the selection element to be a dropdown menu instead of tabs, you might be able to use a custom renderer plugin. From the Quicktabs README.txt:

Another way to extend Quicktabs is to add a renderer plugin. Quicktabs comes with 3 renderer plugins: jQuery UI Tabs, jQuery UI Accordion, and classic Quicktabs. A renderer plugin is a class that extends the QuickRenderer class and implements the render() method, returning a render array that can be passed to renderer service (\Drupal::service('renderer')). See any of the existing renderer plugins for examples. Also see Quicktabs' implementation of hook_quicktabs_renderers().
Comment: Thank you for this detailed answer. My apologies that I didn't mention I'm on Drupal 8. Edited. But this is certainly a way to do it, and now I will check if there are similar modules available for D8.
Comment: No worries, I wasn't sure and should have clarified first. I edited my answer with a suggestion for D8 - the Block Tabs module. I haven't tested it myself but it might work for you.
Comment: Block Tabs didn't work out well for my need, but I found Accordion Blocks to be my solution.
Answer: I found Block Accordions to be my solution. It shows blocks at your choice in accordion style. With some simple modification to the JavaScript and CSS file (maybe the twig as well), you can also get blocks to show in tabs or dropdown menu.


How can i print multiple json object data using firebase snapshot - data pull succeded

Question: I got this working so far.
Data pulled to console from snapshot :
{34FrUM8777N6i0IWfqsatdMc29g1: {…}, 3DSOrtpBHlYENn14bE9UJKWly4G3: {…}}
3DSOrtpBHlYENn14bE9UJKWly4G3:
-MH8EpUbn1Eu3LdT0Tj0: {code: "https://www.apesyntax.com", content: "This is the tut content", date: "2020-09-13", email: "test", first: "tester guy", …}
-MH8TRc3NfinUtI-XORZ: {code: "https://www.codepen.io/apesyntax/pen/ExKNawv", content: "asdad asd asd a", date: "2020-09-13", email: "test@tester", first: "tester", …}
__proto__: Object
34FrUM8777N6i0IWfqsatdMc29g1:
-MH9rJPyKpgKm7HnulTZ: {code: "https://www.codepen.io", content: "Tutorial content from the second tutroial posted by this author. ", date: "2020-09-13", email: "firstname.lastname@example.com", first: "ape ", …}
-MH49Fad5NKD9awjQzVF: {code: "https://www.codepen.io/apesyntax/pen/ExKNawv", content: "new tutorial testing data fetching", date: "2020-09-12", email: "firstname.lastname@example.com", first: "apesyntax", …}
__proto__: Object

So far I managed to pull the data in the order I want to paste them but how can I paste this data to my view?
here is my complete code:
<template>
  <v-container id="my-tutorials">

All Tutorials

{{ user.uid.title }}

{{ tutorial.content }}

  </v-container>
</template>

here is my result:

But I can't get to print on my screen in all tutorials data yet:

Any hints?
Comment: What is `user` meant to be in your template? You have no `user` defined.
Comment: true, it's not defined, I  remove that " = user "  to save me that auth user is not defined error, tnx.
Answer: You've got a couple of syntax and logical errors in your value handler.
What you want to do (I think) is flat-map all the nested documents into one array or object.
I'd go for an array like this
data: () => ({
  authUser: null,
  allTutorials: [] // initialise an array
})

and in your value handler
tutRef.once('value', snapshot => {
  const val = snapshot.val()
  if (val) {
    this.allTutorials = Object.values(val).flatMap(tutes =>
      Object.entries(tutes).map(([ _key, tutorial ]) => ({ _key, ...tutorial })))
  }
})

Then in your template, you can use this

{{ tutorial.title }}

{{ tutorial.content }}

Comment: Holy smokes man, you got this one right again, I was about to post my dumb object printing for all records, but this solution takes me a step further in the iteration and cleaning the data, I will try to learn more on flatMap and the way you solved this problem thanks @phil


Estimating Maximum of Truncated Fourier Series

Question: Let $L$ be an integer. Is there any good way to estimate the $L^{\infty}$ norm of
$$f(x)=a_0+\sum_{n=1}^{2L}\Big(a_n\cos\Big(\frac{n\pi x}{L}\Big)+b_n\sin\Big(\frac{n\pi x}{L}\Big)\Big)?$$
The trivial way would be to use the triangle inequality and the fact that $|\cos(x)|, |\sin(x)|\le 1$ to get
$$\|f\|_{\infty}\le |a_0|+\sum_{n=1}^{2L}(|a_n|+|b_n|).$$
One can do slightly better with Holder to get
$$\begin{aligned}
\|f\|_{\infty} &\le |a_0|+\sup_{x\in\mathbb{R}}\left(\sum_{n=1}^{2L}a_n^2\sum_{n=1}^{2L}\cos^2\Big(\frac{n\pi x}{L}\Big)\right)^{1/2}+\sup_{x\in\mathbb{R}}\left(\sum_{n=1}^{2L}b_n^2\sum_{n=1}^{2L}\sin^2\Big(\frac{n\pi x}{L}\Big)\right)^{1/2} \\
&\le |a_0|+\sqrt{2L}\left(\sum_{n=1}^{2L}a_n^2\right)^{1/2}+\sqrt{2L}\left(\sum_{n=1}^{2L}b_n^2\right)^{1/2}.
\end{aligned}$$
Is there a way to do better?
By differentiating we also know that at whichever $x_0$ the maximum occurs, we'll have
$$\sum_{n=1}^{2L}a_n\sin\Big(\frac{n\pi x_0}{L}\Big)=\sum_{n=1}^{2L}b_n\cos\Big(\frac{n\pi x_0}{L}\Big).$$
Answer: No, in general there's no "reasonable" way to get a "good" estimate on $||f||_\infty$ from the Fourier coefficients. If there were a lot of things would be much simpler.
That trivial estimate is very simple, but it's typically a very bad estimate. You should note that your "better" estimate is actually never any better and is usually much worse, since $$\sum_{j=1}^{2L}|c_j|\le\sqrt{2L}\left(\sum_{j=1}^{2L}|c_j|^2\right)^{1/2}.$$


Will the collect operation of a Flow in Kotlin be launched again when the flow is changed?

Question: The following code comes from Android studio project with Room. I havn't tested it.
I don't know if listIncompleted().collect{..} will be launched again when the records in database info_table is changed, or listIncompleted().collect {...} is only launched once in the code below.
Could you tell me?
class MyService : Service() {
    private val serviceScope = CoroutineScope(Dispatchers.Main)
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
         serviceScope.launch {
              listIncompleted().collect { recordList ->
                  recordList.forEach { record ->
                      // handle each record individually
                  }
              }
         }
    }
    ...
}

@Dao
interface  RecordDao {
    @Query("SELECT * FROM info_table where translateState != :translateState ORDER BY createdDate desc")
    fun listIncompleted(translateState: ETranslateState = ETranslateState.COMPLETED): Flow<List<RecordEntity>>
}

Comment: Yeah! It can be changed immediately.
https://developer.android.com/codelabs/basic-android-kotlin-training-intro-room-flow#8
Answer: collect { ... } just means "listen for items on this flow, and run this function with each of them". So as long as that Flow keeps producing items, the function passed to collect will keep running in response.
A Room query that returns a Flow is an observable query, i.e. it'll keep producing new values if the tables referenced in the query update. So when you call listIncompleted, you get back a Flow object that produces the result of the query when collected, and will continue to produce results when relevant updates happen.
You're only calling the function once to get a Flow, and only calling collect on it once, so you're only setting up one "source" and connecting one "pipe" to it - that pipe will just keep running as updates happen in the database. It's not being "relaunched", it's an open tap.
But you are running this in onStartCommand, which is invoked every time you call startService - so it's possible you could end up launching multiple coroutines that fetch their own Flow for the same query and start collecting it, each one getting a new value to process when a relevant update happens to that common query. So watch out for that!
Answer: Just want to point out that talking about whether collect { } is called again is a little ambiguous, because you might be talking about (1) the higher-order collect function being called repeatedly or (2) the FlowCollector SAM-converted lambda that you pass to it being called repeatedly.
In your code collect() is called a single time. But the lambda that you pass to it is called over and over on every change to the database that affects the table(s) you're querying.
It's just like how calling list.forEach { } is a single call to the higher-order function, but under the hood it calls your lambda over and over for each item in the iterable.


Created my own version of Binary Search, can't understand why it is faster than the regular approach?

Question: Hello to everyone who reads this post. I recently graduated and I'm basically going over every concept I ever learned to refresh my memory or sharpen my skills even better so that I may apply to companies and get hired. My first refresher is going over binary search and I decided to write my own version without looking over the regular approach. I happen to write the following code in which I compared the time complexity of the regular approach to my own version of binary search. Although, my binary search seems to integrate both linear search and binary search and yet it seems it is somehow faster than the regular approach and I just don't understand why. Linear search is utilized for when the key is greater than the middle element, which seems like it would actually increase the time complexity of the search. You can see this within my code of the last else if condition in "myBinarySearch" method. Yet, even after searching through 15,000 integers of an array, my version is still faster.
Can anyone please explain to me why my version is much faster? Below is the regular approach compared to my version of binary search. My version is only slower when searching for a key that does not exist and is over excessive, for example, searching for 16,000. It must be excessive, because searching for 15,001 does result in a faster time of returning -1.
I've concluded that it is because I only used one variable as oppose to using 3 variables in the regular approach which is checking and/or updating these variables when looping through the array. Although, the linear search in the last else if statement in my method throws me off and makes me wonder how this does not increase the time complexity.
<code>public static void main(String[] args) {
    int[] array = new int[15000];
    File file;
    BufferedReader br;
    try {
       file = new File("../Java/bin/IntroToJavaBook/largeArray.txt");
       br = new BufferedReader(new FileReader(file));
       String st;
       int i = 0;
       while((st = br.readLine()) != null)
       {
           array[i] = Integer.parseInt(st);
           i++;
       }
    } catch (FileNotFoundException e) {
       e.printStackTrace();
    } catch (IOException e) {
       e.printStackTrace();
    }

    int key = 4200;
    long startTime = System.nanoTime();
    System.out.println(binarySearch(array, key));
    long endTime = System.nanoTime();
    long duration = (endTime - startTime);
    System.out.println(duration);

    long startTime1 = System.nanoTime();
    System.out.println(myBinarySearch(array, key));
    long endTime1 = System.nanoTime();
    long duration1 = (endTime1 - startTime1);
    System.out.println(duration1);

}

static int binarySearch(int[] array, int key) {
    int low = 0;
    int high = array.length - 1;
    while (high >= low)
    {
        int mid = (low + high) / 2;
        if (key < array[mid])
        {
            high = mid - 1;
        }
        else if (key == array[mid])
        {
            return mid;
        }
        else
        {
            low = mid + 1;
        }
    }
    return -1;
}

static int myBinarySearch(int[] array, int key) {
    int half = array.length/2;
    while(true)
    {
        if(half == 0 || half == array.length)
        {
            return -1;
        }
        else if(key < array[half])
        {
            half /= 2;
        }
        else if(key == array[half])
        {
            return half;
        }
        else if(key > array[half])
        {
            half = half + 1;
        }
    }
}
</code>
Comment: Mirco benchmarks are hard to do right, especially with JVM. You said you compared the time complexity and then started talking about conditions where each one is faster. Go back and review the time complexity topic again, benchmarking has nothing to do with it. You should get a simple mathematical equations `O()` in terms on `n`. The traditional bin search is O(log2(n)) sounds like yours may be O(log2(n) + n/2) which you can see from easy algebra is slower. Benchmarks generally measure best/worst/small n cases and do not tell you much about the algorithm as a whole.
Comment: Can't tell much without seeing the code for binarySearch and myBinarySearch
Comment: It can't be faster, of course. The usual way of writing your code would be `half += half/2` and `half -= half/2` depending on the comparison.
Answer: You confuse complexity with speed.
In complexity, n>1000, even if you run a test with n=500.


Lighttpd won't start when fastcgi.debug directive is used

Question: I'm running lighttpd/1.4.28 (ssl) on Ubuntu 12.04 LTS.  Everything's working, and I'm trying to do some performance tuning.  I'd like to enable debug mode for the fastcgi module, however when I add the directive fastcgi.debug to my conf file, lighttpd chokes with a "parser failed" error:
2013-10-08 10:56:23: (configfile.c.912)
source: /etc/lighttpd/conf-enabled/15-fastcgi-php.conf
line: 1
pos: 15 parser failed somehow near here: (EOL)

The config file is: /etc/lighttpd/conf-enabled/15-fastcgi-php.conf
fastcgi.debug=1

fastcgi.server += ( ".php" =>
    ((
            "bin-path" => "/usr/bin/php-cgi",
            "socket" => "/tmp/php.socket",
            "max-procs" => 1,  # runs max-procs bin-path controllers plus (max-procs * PHP_FCGI_CHILDREN) workers
            "idle-timeout" => 20,
            "bin-environment" => (
                    "PHP_FCGI_CHILDREN" => "10",
                    # PHP_FCGI_MAX_REQUESTS: The number of requests that a single worker handles before it kills itself.
                    "PHP_FCGI_MAX_REQUESTS" => "10000"
            ),
            "bin-copy-environment" => (
                    "PATH", "SHELL", "USER"
            ),
            "broken-scriptfilename" => "enable",
            "check-local" => "disable"
    ))
)

Why isn't the directive recognized?  I get the error even if I set it to zero.
Comment: Try making it `fastcgi.debug = 1` and you didn't edit it on windows did you?
Comment: Thanks, I had tried that, also thinking it's a whitespace issue, and it gives the same error.  I only edited the file using vi on the server.
Answer: I've spent the last hour on this, and finally ran across this thread:  http://redmine.lighttpd.net/boards/2/topics/2265
At the very end of the thread, the OP mentions running lighttpd interactively from the console:
sudo lighttpd -Df /etc/lighttpd/lighttpd.conf

When I did that, it printed out the message:
Duplicate config variable in conditional 0 global: fastcgi.debug

So I grep'd all of my configs, and sure enough, there was another file with the fastcgi.debug directive.  When I removed the dup entry, lighttpd started.
lighttpd should write that message to the error log!


UnhandledPromiseRejectionWarning: TypeError: Cannot set property 'prefix' of null

Question: I make commands to change the prefix to the server, well, when I try to change, an error occurs, I looked in all the search engines, and I could not find the answer.
(node:4632) UnhandledPromiseRejectionWarning: TypeError: Cannot set property 'prefix' of null
module.exports = {
    name: 'prefix',
    args: true,
    usage: '<префикс>',
    aliases: ['set-prefix', 's-prefix'],
    async execute(message, args) {
        const data = await Guild.findOne({ guildID: message.guild.id });

        message.channel.send(`Новый префикс: \`${args[1]}\``);
        data.prefix = args[0];
        data.save;
    },
};

Answer: This is because there is no prefix in the database. You can use findOneAndUpdate method:
await Guild.findOneAndUpdate({
guildID: message.guild.id //find the needed guild
}, {
guildID: message.guild.id, //update prefix
prefix: args[0]
}, {
upsert: true
});

message.channel.send(Новый префикс: \${args[1]}``);


Simple limit of a sequence defined recursively

Question: For each $ \ N \in \mathbb{R} \ $ and each $ \ t \in \mathbb{R} \, $, let $ \ S(N,t) = (X_n)_{n \in \mathbb{N}^*} \in \mathbb{R}^{\mathbb{N}^*} \ $ be a sequence such that $ \ X_1 = t \ $ and, $\forall n \in \mathbb{N}^*$, $$X_{n+1} = X_n + \frac{N - X_n^2}{2 X_n} \ \ . $$ I want to know for which values of $N$ and $t$ the sequence converges and the value of the limits $$L(N,t) = \lim \, S(N,t) = \lim_{n \to \infty} X_n \ \ . $$
I have a feeling that, for $ \ 0<t<N< \infty \ $ the sequence converges to $ \sqrt{N}$, because I have an intuitive idea of some areas of a square I have drawn (picture below). The square has area $ \ N = (a+t)^2 \, $, with sides of lenght $ \ a+t = \sqrt{N}$, where $ \ 0<a<t \, $. So we have $ \ N = t^2 + 2at + a^2 \, $. In my first approximation I simply forget the small $ \, a^2 \, $ and get $ \ N = t^2 + 2at \ \Rightarrow \ a = \frac{N-t^2}{2t} \, $. Thus, my first approximation was a square of sides $ \ X_1 = t \ $ and my second approximation was a square of sides $ \ X_2 = X_1 + a \ $ and I proceed in this fashion to get the sequence above. But this is just a feeling and I want to know if this process converges and if I can generalize this to any $ \ N \in \mathbb{R} \ $ and any $ \ t \in \mathbb{R} \, $.
Thanks.
Comment: I forget to say that $ \ t \neq 0 \, $.
Comment: If $ \ N=0 \, $, then $ \ X_n = t/2^{n-1} \, $, $\forall n \in \mathbb{N}^*$.
If $ \ N  \neq 0 \ $ and $ \ t= \pm \sqrt{N} \, $, then $ \ X_n = t \, $, $\forall n \in \mathbb{N}^*$.
Answer: Indeed, the sequence converges to $\sqrt N$.
The sequence you're looking at is actually reasonably well-known: it is the sequence of Newton's method iterations for finding a root of the function $f(x) = x^2 - N$. Your recurrence can be rewritten as $X_{n+1} = X_n - \frac{f(X_n)}{f'(X_n)}$, which is just a single step of Newton's method.
If you don't recognize this sequence, then it's easy to see that if it converges to anything, it must converge to $\pm \sqrt N$. Write the recurrence as $X_{n+1} = g(X_n)$. Then if $X_n \to X$ as $n \to \infty$, we must have $g(X_n) \to g(X)$ as $n \to \infty$. But the sequence $g(X_n)$ is just $X_n$, one iteration ahead. So $X$ must satisfy $g(X) = X$. In this case, $$X = X - \frac{N - X^2}{2X} \quad\Rightarrow\quad \frac{N - X^2}{2X} = 0 \quad\Rightarrow\quad X^2 = N.$$
Actually showing convergence is tricky. One way is to observe that if $X_n > \sqrt N$, then $X_{n+1} > \sqrt N$ but $X_{n+1} < X_n$ (which just takes some more algebra to show), and if $0 < X_n < \sqrt N$, then $X_{n+1} > \sqrt N$. So the sequence $t = X_1, X_2, X_3 \dots$ will keep getting smaller and smaller while staying above $\sqrt N$. It must converge to something and that something can only be $\sqrt N$.
Comment: Great. So I can generalize this sequence to complex numbers as well and, by your answer, I can say that if the sequence converges for some $ \ N = |N| e^{i \theta} \in \mathbb{C} \ $ and some $ \ t \in \mathbb{C} \, $, it must converge to $ \ \pm \sqrt{|N|} \cdot e^{i \cdot \theta / 2} \, $, for all $ \ t \in \mathbb{C} \, $. I will work on showing convergence later. Thanks.
Comment: In fact, this is Newton's method applied to the function $ \ x \mapsto N-x^2$


How to best visualize one-sample test?

Question: We are currently writing a paper with several one-sample Wilcoxon tests. While visualizing two-sample tests is easy via boxplots, I was wondering whether there is any good way to visualize one-sample test results?
# Example data
pd <- c(0.80, 0.83, 1.89, 1.04, 1.45, 1.38, 1.91, 1.64,
        0.73, 1.46, 1.15, 0.88, 0.90, 0.74, 1.21)

wilcox.test(pd, mu = 1.1)

#   Wilcoxon signed rank test
#
# data:  pd
# V = 72, p-value = 0.5245
# alternative hypothesis: true location is not equal to 1.1

...and also:
I would like to get Z-value instead of V-value. I know that if I use coin package instead of basic stats I will have z-values, but coin package
seems not to be able perform one-sample Wilcoxon test.
Comment: When I calculate the test statistic "by hand" in R, I get the same value as R gives. $\quad\quad\quad\quad\quad\quad$ (`r=rank(abs(pd-1.1));` `s0=(pd>1.1);` `sum(r*s0)`)
Comment: Hmm... In SPSS, I got with your data V=72.5 (Z=.710) and p=.478. I wonder why `R` gives 72, not 72.5 value of the test statistic.
Comment: Hi @ttnphns, from you comment is to me evident that SPSS gives both V and Z vales. Or not? Or you make some conversion of V to Z value?
Comment: http://pic.dhe.ibm.com/infocenter/spssstat/v20r0m0/topic/com.ibm.spss.statistics.help/alg_npar_tests_wilcoxon.htm , also the same in sligthly different notation http://pic.dhe.ibm.com/infocenter/spssstat/v20r0m0/topic/com.ibm.spss.statistics.help/alg_nonparametric_onesample_wilcoxon.htm . But what I still don't understand is why SPSS and R give not identical results...
Answer: Something like this?

Or were you after some interval for the median, like you get with notched boxplots (but suited to a one sample comparison, naturally)?
Here's an example of that:

This uses the interval suggested in McGill et al (the one in the references of ?boxplot.stats). One could actually use notches, but that might increase the chance that it is interpreted instead as an ordinary notched boxplot.
Of course if you need something to more directly replicate the signed rank test, various things can be constructed that do that, which could even include the interval for the pseudo-median (i.e. the one-sample Hodges-Lehmann location estimate, the median of pairwise averages).
Indeed, wilcox.test can generate the necessary information for us, so this is straightforward:
> wilcox.test(pd,mu=1.1,conf.int=TRUE)

    Wilcoxon signed rank test

data:  pd
V = 72, p-value = 0.5245
alternative hypothesis: true location is not equal to 1.1
95 percent confidence interval:
 0.94 1.42
sample estimates:
(pseudo)median
        1.1775

and this can be plotted also:

[The reason the boxplot interval is wider is that the standard error of a median at the normal (which is the assumption underlying the calculation based off the IQR) tends to be larger than that for a pseudomedian when the data are reasonably normalish.]
And of course, one might want to add the actual data to the plot:

Z-value
R uses the sum of the positive ranks as its test statistic (this is not the same statistic as discussed on the Wikipedia page on the test).
Hollander and Wolfe give the mean of the statistic as $n(n+1)/4$ and the variance as $n(n+1)(2n+1)/24$.
So for your data, this is a mean of 60 and a standard deviation of 17.61 and a z-value of 0.682  (ignoring continuity correction)

The code I used to generate the fourth plot (from which the earlier ones can also be done by omitting unneeded parts) is a bit rough (it's mostly specific to the question, rather than being a general plotting function), but I figured someone might want it:
notch1len <- function(x) {
  stats <- stats::fivenum(x, na.rm = TRUE)
  iqr <- diff(stats[c(2, 4)])
  (1.96*1.253/1.35)*(iqr/sqrt(sum(!is.na(x))))
}

w <- notch1len(pd)
m <- median(pd)

boxplot(pd,horizontal=TRUE,boxwex=.4)

abline(v=1.1,col=8)
points(c(m-w,m+w),c(1,1),col=2,lwd=6,pch="|")

ci=wilcox.test(pd,mu=1.1,conf.int=TRUE)$conf.int                       #$
est=wilcox.test(pd,mu=1.1,conf.int=TRUE)$estimate

stripchart(pd,pch=16,add=TRUE,at=0.7,cex=.7,method="jitter",col=8)

points(c(ci,est),c(0.7,0.7,0.7),pch="|",col=4,cex=c(.9,.9,1.5))
lines(ci,c(0.7,0.7),col=4)

I may come back and post more functional code later.
Comment: I just did that Friday; that's how I know ;-).
Comment: Thank you @Glen_b, it draws away my uncertainty. I hope reviewers will not have any problem with it.
Comment: @Glen_b, the boxplot with median doesn't look to me right for presenting 1-sample **Wilcoxon** test. The test checks if the population distribution is _symmetric_ about a test value, not if that value is the _median_ (as would be with 1-sample **sign** test). Well, of course, is it is symmetric, then the value is automatically the median; but it contrary isn't true, it can be the median without symmetricity. Saying all that, I mean that _boxplot_ isn't right to depict Wilcoxon: you must show symmetricity, hence histogram, density, violin plots would be better.
Comment: @ttnphns (i) The OP explicitly regards ordinary boxplots as suitable for indicating a two sample comparison (presumably a rank sum test) even though that test is not actually a comparison of medians, and (ii) the signed rank test is a test of location that assumes symmetry. Ordinary notched boxplots have underlying normal assumptions(!). One can check the reasonableness of the symmetry assumption fairly easily, but I think the point of the suggested display was not to explicitly replicate the test but simply to indicate that the middle of the data is close to the hypothesized value.
Comment: What do you call pseudomedian here? one-sample Hodges-Lehmann location estimator?
Comment: @ttnphns Yes. This is (for example) the terminology in the R help on wilcox.test (and also in Hollander and Wolfe, among others).
Comment: @Glen_b, in your function, if you just want the interquartile range, you can get it directly via [?IQR](http://stat.ethz.ch/R-manual/R-patched/library/stats/html/IQR.html), instead of `diff(fivenum())`.
Comment: Thanks, @gung -- for some reason, I was trying `iqr` and going "oh, they don't have one".
Answer: If you like boxplots, you can as readily show a single boxplot with a line or other reference showing your hypothesised value. (@Glen_b posted an answer with an excellent simple example precisely as I was first writing this.)
It is arguable that boxplots, now very popular, are massively overused for one-sample and two-sample exploration. (Their real value, in my view, is when you are comparing many sets of values, with number of samples or groups or variables more like 10, 30 or 100, and there is a major need to see overall patterns amid a mass of possible detail.)
The key point is that with just one or two samples (groups, variables), you have space on a plot to show much more detail, detail that could be interesting or important for comparison. With a good design, such detail need not be distracting in visual comparison.
Evidently, in most usual versions the box plot suppresses all detail in its box, showing the middle half of the data, except in so far as the position of the median inside the box conveys some information. Depending on the exact rules used, such as the 1.5 IQR convention of showing data points individually if and only if they are 1.5 IQR or more from the nearer quartile, it is even possible that the box plot suppresses most of the detail about the other half of the data. Often, and perhaps even usually, such detail may be irrelevant to something like a Wilcoxon test, but being prepared to see something illuminating in the data display is always a good idea.
A display that remains drastically underused in many fields is the quantile plot, a display of the ordered values against an associated cumulative probability. (For other slightly technical reasons, this cumulative probability is typically not $1/n, \cdots, n/n$ for sample size $n$ but something like $(i - 0.5)/n$ for rank $i$, 1 being the rank of the smallest value.)
Here are your example data with a reference line added for 1.1.

In other examples, key points include

For two-sample comparisons, there are easy choices between superimposing traces, juxtaposing traces, or using related plots such as quantile-quantile plots.
The plot performs well over a range of sample sizes.
Outliers, granularity (lots of ties), gaps, bi- or multimodality will all be shown as or much more clearly than in box plots.
Quantile plots mesh well with monotonic transformations, which is not so true for box plots.

Some will want to point out that cumulative distribution plots or survival function plots show the same information, and that's fine by me.
See W.S. Cleveland's books (details at http://store.hobart.com/) for restrained but effective advocacy of quantile plots.
Another very useful plot is the dot or strip plot (which goes under many other names too), but I wanted to blow a small trumpet for quantile plots here.
R details I leave for others. I am focusing here on the more general statistical graphics question, which clearly cuts across statistical science and all software possibilities.
Incidentally, I don't know the background story but the name wilcox.test in R seems a poor choice to me. So, you save on typing two characters, but the name encourages confusion, not least because of past and present people in statistical fields called Wilcox. Lack of justice for Mann and Whitney is another detail. The person being honoured was Wilcoxon.
Comment: +1 - In addition to the many groups notes - with only 15 values box-plots (while still useful in general) can be misleading (e.g. bimodal data). Super-imposing the points on the box plot can show such discrepancies (examples [here](http://stats.stackexchange.com/a/22733/1036) and [here](http://stackoverflow.com/q/9232331)).
Comment: There's much to be said for such displays.
Answer:
I would like to get Z-value instead of V-value. I know that if I use
coin package instead of basic stats I will have z-values, but coin
package seems not to be able perform one-sample Wilcoxon test.

{coin} package works for one-sample tests, but they are identified as symmetrical problems and the reference vector must be supplied explicitly in a formula format. The function is wilcoxsign_test() for Wilcoxon-Pratt signed-rank test for symmetry in 1+ samples instead of wilcox_test() for location tests among 2+ samples.
wilcoxsign_test(
  c(0.80, 0.83, 1.89, 1.04, 1.45, 1.38, 1.91, 1.64,
    0.73, 1.46, 1.15, 0.88, 0.90, 0.74, 1.21) ~
    rep(1.1, 15),
  distribution = "exact")

    Exact Wilcoxon-Pratt Signed-Rank Test

data:  y by x (pos, neg)
     stratified by block
Z = 0.68155, p-value = 0.5245
alternative hypothesis: true mu is not equal to 0

The you can extract the z statistic through wilcoxsign_test(...)@statistic@standardizedlinearstatistic.
We can possibly derive the z statistic from wilcox.test() from the asymptotic p value without continuity correction.
wilcoxsign_test(
  c(0.80, 0.83, 1.89, 1.04, 1.45, 1.38, 1.91, 1.64,
    0.73, 1.46, 1.15, 0.88, 0.90, 0.74, 1.21) ~
    rep(1.1, 15))

    Asymptotic Wilcoxon-Pratt Signed-Rank Test

data:  y by x (pos, neg)
     stratified by block
Z = 0.68155, p-value = 0.4955
alternative hypothesis: true mu is not equal to 0

wilcox.test(
  c(0.80, 0.83, 1.89, 1.04, 1.45, 1.38, 1.91, 1.64,
    0.73, 1.46, 1.15, 0.88, 0.90, 0.74, 1.21),
  mu = 1.1, exact = F, correct = F)

    Wilcoxon signed rank test

data:  c(0.8, 0.83, 1.89, 1.04, 1.45, 1.38, 1.91, 1.64,
0.73, 1.46, 1.15, 0.88, 0.9, 0.74, 1.21)
V = 72, p-value = 0.4955
alternative hypothesis: true location is not equal to 1.1

Then z statistic is qnorm(1 - wilcox.test(...)$p.value/2).
Comment: As the sample size is small enough (n = 15), exact p values can be calculated. Otherwise, simulated p values can be used through permutation, distribution =  approximate(nresample = 20000L). The number of Monte Carlo replicates used for the computation of the approximative reference distribution is recommended to be over 15000L for better accuracy.

How to best visualize one-sample test?


Is the OLRE term meaningful in the negative binomial model? + Is overdispersion in the NB model an issue?

Question: I'd like to ask three questions regarding the negative binomial (NB) regression / distribution.

The NB model with NB2 parameterization ($var(Y_{NB2}) = \mu + \frac{\mu^2}{\theta}$) is sometimes referred to as the Poisson-gamma model. It should be because the count data come from a Poisson-gamma mixture distribution – a mixture where each count is from its own Poisson distribution with its own $\lambda$ parameter and these $\lambda$'s follow a gamma distribution (e.g. here). The negative binomial model is basically a generalization of Poisson regression which loosens the restrictive assumption that $var(Y) = E(Y)$.
Now let's shift to an overdispersion, so common to Poisson models. One way to handle overdispersion is to include an observation-level random effect (OLRE). I learned that these models can be called the Poisson-lognormal mixed models. It should be for a similar reason as in the previous case: the data $Y$ are Poisson distributed, but the mean $\mu$ comes from a lognormal distribution. That should be the difference between the NB2 (Poisson-gamma) model and the Poisson-lognormal model, as pointed out here on CV SE (see a comment from Bryan posted at 17:01). (I also registered Björn's comment at 16:52 about the NB2 model also being 'secretly' a mixed model, and I think I understand it.)
But now: What is the meaning of the OLRE term in negative binomial models? What I'm saying about the distribution – do I create a 'Poisson-gamma-lognormal mixture'? Harrison (2014) used OLRE to model overdispersion in count data. He ran three simulations, one of which was a negative binomial one. And he included the OLRE term.

The second question is related to the first. I thought the NB model is used when the equidispersion assumption of the Poisson model is not met. This suggests to me that overdispersion is no longer a problem with NB models. Also according to Ben Bolker's GLMM FAQ (bullet number 2), dispersion is a problem only for models with fixed variance like binomial or Poisson ones. So why would Harrison fit a NB model with an OLRE to model overdispersion? Or am I missing something? Is overdispersion in the NB model really an issue? I read this post here on CV SE but I'm still not sure about it.

My last question is about the difference in NB1 and NB2 parameterization. NB2 (described above) assumes a quadratic variance-to-mean relationship while NB1 assumes a linear relationship ($var(Y_{NB1}) = \mu + \mu\theta$). When I simulate data from the NB distribution, the classic NB2 parameterization is used. How could I simulate the data with the NB1 parameterization? I work in R (RStudio) and for NB simulations I used functions stats::rnbinom() and MASS::rnegbin(), both of which use the NB2 parameterization.

Thank you in advance. (Sorry if my last question is dumb.)
Answer: I see this question has been quiet for some time, so I'll chime in hopefully in a useful way, since I have similar questions to you. In my reading of the Harrison paper, I don't think he uses a negative binomial model with an OLRE term. He had the three simulations (extra Poisson noise, zero inflation, and negative binomial), and fit two models to each - one a naive Poisson model, and the other a Poisson with an OLRE term. He did verify that he could recover the parameter estimates from each simulation with a third model that matched the data generating process. Maybe that is where you are thinking he used a negative binomial with OLRE? I don't believe he did though. That was just a plain negative binomial model.
A negative binomial model with an OLRE term seems like a weird construction. As you correctly say, in a negative binomial each count comes from its own Poisson distribution, and those Poisson means are in turn gamma distributed. Adding an OLRE term would be then additionally stating that each count has its own Poisson mean, and those are normally distributed. It seems redundant. Hopefully someone with more knowledge can chime in. I'd also be curious if OLRE terms can be included in a zero-inflated context. In that case there doesn't seem to be the same redundancy in the Poisson means.
Comment: In thinking about this a bit more, there's an obvious potential practical benefit to including OLRE in a negative binomial model. Most R packages I'm aware of don't let you recover the observation level Poisson means with negative binomial, so if those are what you are interested in, then OLRE might be necessary.


Are there any nontrivial ways to factor n-cycles into a product of cycles?

Question: I was reading a proof here about the simplicity of $A_n (n \ge 5)$. It states (and proves) a lemma about 3-cycles:
A 3-cycle $(a, b, c)$ may be written as $(a, b, c) = (1, 2, a)^{-1}(1, 2, c)(1, 2, b)^{-1}(1,2, a)$ (here, multiplication is right to left).
Later on, the author shows that a 3-cycles $(1, 2, 3)^{-1}$ and $(1, 2, k)$ are conjugate in $A_n$, decomposing the former into a product of the latter and some transpositions: $$(1, 2, k) = ((1, 2)(3, k))(1, 2, 3)^{-1}((1, 2)(3, k))^{-1}.$$
This certainly makes sense now that I see it, but how is this arrived at a priori? Is there a way to "factorize" cycles into other cycles?
Thank you so much.
Comment: What is a (non) trivial factorization for you in $\;S_n\;$, @user ?
Comment: The author is exploting that $\sigma (k_1\cdots k_r)\sigma^{-1}=(\sigma(k_1)\cdots \sigma(k_r))$
Answer: If the permutation $x$ maps $i$ to $j$, then conjugation by $g$ (i.e. $gxg^{-1}$) maps $g(i)$ to $g(j)$ since $gxg^{-1}(g(i)) = gx(i) = g(j)$.  Thus, the permutation $gxg^{-1}$ has the same cycle structure as $x$, but with the points $i$ replaced by their image $g(i)$.
For example if the 3-cycle $x=(132)$ is already in the normal subgroup $H$ of $A_n$, and we want to obtain another 3-cycle, say $(2k1)$, then we look for a map $g$ that takes $1$ to $2$, $3$ to $k$ and $2$ to $1$; for example, consider $g=(12)(3k)$.  Observe then that $gxg^{-1}$ is the 3-cycle $(12k)$, and by normality $gxg^{-1}$ is required to be in the subgroup $H$.  Thus, if $H$ contains the 3-cycle $(123)$ then $H$ also contains the 3-cycle $(12k)$, and so on.  We try to get all the 3-cycles in this manner by considering action by conjugation, which expresses the new 3-cycles as a product of three factors that have the form $gxg^{-1}$.
Answer: I believe you need another way of looking on conjugation:
If the group $S_n$ is realized as acting on $n$ points, then conjugating by some permutation is just renumerating points. (i.e. if you have a cycle $\sigma=(123)$ and a renumeration $\tau=(12)$ then the new cycle will be $\sigma=(213)$ and that is exactly the conjugation by $\tau$). Now it is very easy to construct the element in $S_n$ that changes two $3$-cycles and all you need is to check, that this element is even. Well, you have a concrete formula for the element so that's easy.


Qual a diferença entre Math.random() e java.util.Random?

Question: Qual a diferença em utilizar o random sem o import, direto no método.
public class random {

    public static void main(String[] args) {

        int x = (int) (Math.random() * 10);
        System.out.println(x);

    }

}

Ou com o import na classe, qual é a diferença?
import java.util.Random;

public class random {

    public static void main(String[] args) {

        Random aleatorio = new Random();
        int numero = aleatorio.nextInt(10);
        System.out.println(numero);

    }

}

Answer: A primeira diferença é que Math.random() é um método estático da classe Math, enquanto java.util.Random é uma classe.
Neste aspecto a vantagem de Math.random sobre java.util.Random é que não é necessário criar um objecto.
Math.random() retorna um double de 0,0 até, mas não incluindo 1.0.  Para conseguir outra gama de valores é necessário recorrer a operações como a multiplicação.
É necessário recorrer ao cast para convertê-lo para um número inteiro.
Internamente usa java.util.Random como gerador dos números.
A classe java.util.Random fornece formas mais flexíveis para gerar números aleatórios distribuídos uniformemente, proporcionando fácil geração de outros tipos além do double.
Um aspecto que pode ser interessante(em caso de testes) é que se duas instâncias de java.util.Random forem criados com a mesma semente(seed), e a mesma sequência de chamadas de métodos for feita para cada uma, elas vão gerar e retornar sequências idênticas de números.
Answer: A classe é mais completa e flexível, permite determinar o tipo de dado que se deseja e é mais eficiente. Ela pode, por exemplo, repetir os mesmos números se usada com a mesma semente.
O método estático contido em Math é mais simples e resolve sem muitas preocupações, o método cuida de vários detalhes para você, consequentemente você não pode configurar como quer usar. Só trabalha com valores double. Ele é prático quando precisa do básico.
Coloquei no GitHub para referência futura.


Views List tag filtering, add a tag to a view for filtering purposes

Question: On the Views list admin/structure/views, I can filter my list of views by the tags on the View.

I can search for the tags, but how do I add my own tags to the views so that I can easily filter them?
Answer:
Open (edit) your view
Click on edit view name/description

Add to/change tags under View tag and click Apply


When cars start from the pit lane, what determines when they can start?

Question: When an F1 race start (or re-start) takes place, what determines when cars starting from the pit-lane allowed to start? Is it based on cars on-track or something else?
I was thinking of this particularly in regard to the very unusual race restart in the 2021 Hungarian GP where every car except one came in to change tyres, leaving Lewis Hamilton as the only car on the grid with all others starting from the pit lane. If Lewis suffered car failure at the start or simply decided to sit on the grid at lights-out would everyone else have been allowed to restart?
Answer: There's a separate light signal at the end of the pit lane, that shows green if cars allowed to leave the pit lane, and red if they're not. Cars that start the race from the pit lane have to wait for that light to change from red to green before they can set off. This is the same procedure that occurs at the start of practice and qualifying.
My understanding is that the light doesn't change automatically, and has to be manually triggered by the race director. This ensures that cars can only leave the pit lane once it's safe to do so (i.e. every other car has passed the pit exit, and there's no danger of crashing into someone while merging onto the track).
The scenario you describe would most likely lead to an aborted start as soon it becomes clear that Hamilton can't (or won't) move. You can't have cars stranded in the middle of a live race track.
Comment: I had been considering a crazy idea where he was first but on wrong tires and decided just to 'run the clock' :)


Counterexample, where every projective representation can be lifted to a linear representation, but $H^{2}(G,\mathbb{C}^{\times}) \neq \{e\}$.

Question: I am currently learning about projective representations and I have seen a proof that if $H^2(G,\mathbb{C}^{\times})=\{e\}$, then every projective representation can be lifted to a linear representation. However, I have not found anywhere that this statement would be an iff. I am trying to find a counterexample, for which it holds that every projective representation can be lifted to a linear representation, but $H^2(G,\mathbb{C}^{\times}) \neq \{e\}$. Does  anyone have a hint in mind, or a reference?
I know that projective reps. are in 1-1 correnspondence with linear reps of $\mathbb{C}^{\times}$ extensions, but I don't know how this helps in this particular case.
Answer: The group $H^2(G,{\mathbb C}^\times)$ is the Schur Multiplier $M(G)$ of $G$, and $G$ has a Schur Cover $H$ with a subgroup $M \le Z(H) \cap [H,H]$ of $H$ with $M \cong M(G)$ and $H/M \cong G$.
If $M(G)$ is nontirivial, then $H$ has an irreducible complex representation $\rho$ with $M \not\le \ker \rho$, and then the projective representation $\bar{\rho}$ of $G$ induced by $\rho$ does not lift to an ordinary representation of $G$.
Comment: Is it then true that $H^2(G,\mathbb{C}^{\times})$ is in bijective correspondence with $\text{ProjRep}$, where $\text{ProjRep}:=\{\theta:G \to \text{PGL}(V)| \theta \; \; \text{is a group homomorphism} \}?$ Given a projective representation $\theta \in \text{ProjRep}$, we can associate to it a cohomology class. But is it true that every cohomology class comes from a projective representation? How could one see this?
Comment: This looks wrong for a number of reasons. The set ProjRep that you have defined looks infinite. Even if you restrict to irreducible representations then (as I think you have already noted) the representations that are induced by ordinary representations of $G$ all correspond to the zero cohomology class.
Comment: This makes sense. Then how to formulate mathematically that "the second cohomology group classifies projective representations"? I certainly know that central $\mathbb{C}^{*}$ extensions are in one-to-one correspondence with $H^2(G,\mathbb{C}^{*})$. However, my main motivation for studying $H^2$ and central extensions is itself that I am interested in projective representations. How to relate **(possibly irreducible) projective representations** to **the second cohomology group** $H^2(G,\mathbb{C}^{*})$? I seem not to find an answer for this in the books/articles I am learning from.
Comment: https://math.stackexchange.com/questions/4677059/precise-relation-between-group-cohomology-and-projective-representations -  I created a concrete post about this question, not to prolong the comment section too much.
Comment: I believe the main theorem says that there is a one-one correspondence between the equivalence classes of irreducible projective representations of $G$ and the equivalence classes of irreducible ordinary representations of $H$. Here $H$ can be any Schur Cover of $G$ - it is not always uniquely determined by $G$. For example $D_8$ and $Q_8$ are both Schur Covers of the Klein 4-group.


Calculating on objects in recursive function

Question: I'm trying to make a function that calculates the percentage of "completed tasks" in a recursive manner.
Here's what I have now, but this only calculates the percentage on the parent, not grandparent etc:

const tasks = [
    { id: 1, task: 'Clean apartment', completed: null, parentId: null},
    { id: 2, task: 'Make app', completed: null, parentId: null},
    { id: 3, task: 'Clean bathroom', completed: null, parentId: 1},
    { id: 4, task: 'Clean kitchen', completed: null, parentId: 1},
    { id: 5, task: 'Wash sink', completed: true, parentId: 3},
    { id: 6, task: 'Wash shower', completed: null, parentId: 3},
    { id: 7, task: 'Wash glass panes', completed: null, parentId: 6},
    { id: 8, task: 'Wash floor', completed: null, parentId: 6},
]

function compileTask(tasks, taskId) {
    var task = (typeof taskId === 'number') ? tasks.find(task => task.id === taskId) : taskId;
    var children = tasks.filter(t => t.parentId === task.id);

    task.percent = children.filter(c => c.completed === true).length / children.length * 100

    task.children = children.map(child => compileTask(tasks, child));
    return task
}

console.log(compileTask(tasks, 1))

As you see, task id 3 is 50% completed because one of the two child tasks are marked completed, but task id 1 is 0% completed. If I'm calculating right in my head, task id 1 should return 25% completed.
Any tips?
Answer: You are mixing objects and integers.
var task = (typeof taskId === 'number') ? tasks.find(task => task.id === taskId) : taskId;

returns a task in one case and an id in another
then here
task.children = children.map(child => compileTask(tasks, child));

You are passing a child instead of the child.id. It should be
task.children = children.map(child => compileTask(tasks, child.id));

Comment: Thanks, fixed that! Seems to have been working either way, though?

Do you have any tips on calculating the percentage of completed grandchild tasks?
Answer: I'm not quite sure of the output format you want, so I'm going to generate something like the following.  We can probably alter it to fit your needs:
[
  {id: 1, task: 'Clean apartment', percent: 25, parentId: null}
  {id: 2, task: 'Make app', percent: 0, parentId: null}
  {id: 3, task: 'Clean bathroom', percent: 50, parentId: 1}
  {id: 4, task: 'Clean kitchen', percent: 0, parentId: 1}
  {id: 5, task: 'Wash sink', percent: 100, parentId: 3}
  {id: 6, task: 'Wash shower', percent: 0, parentId: 3}
  {id: 7, task: 'Wash glass panes', percent: 0, parentId: 6}
  {id: 8, task: 'Wash floor', percent: 0, parentId: 6}
]

Initial Approach
This is a fairly simple recursive technique:

const sum = (ns) => ns .reduce ((a, b) => a + b, 0)

const findPercent = (task, tasks, children = tasks .filter (({parentId}) => task .id == parentId)) =>
  children .length
    ? sum (children .map (c => findPercent(c, tasks))) / children .length
    : task .completed ? 100 : 0

const compileTasks = (tasks) => tasks .map (
  (task, _, __, {completed, parentId, ...rest} = task) => ({
    ...rest,
    percent: findPercent (task, tasks),
    parentId
  })
)

const tasks = [{id: 1, task: 'Clean apartment', completed: null, parentId: null}, {id: 2, task: 'Make app', completed: null, parentId: null}, {id: 3, task: 'Clean bathroom', completed: null, parentId: 1}, {id: 4, task: 'Clean kitchen', completed: null, parentId: 1}, {id: 5, task: 'Wash sink', completed: true, parentId: 3}, {id: 6, task: 'Wash shower', completed: null, parentId: 3}, {id: 7, task: 'Wash glass panes', completed: null, parentId: 6}, {id: 8, task: 'Wash floor', completed: null, parentId: 6}]

console .log (compileTasks (tasks))
.as-console-wrapper {max-height: 100% !important; top: 0}

findPercent is a helper function that recursively looks through the children, and averages their percentages.  It bottoms out when there are no children, and then chooses 0% or 100% depending upon whether the task is completed.  It uses a trivial sum helper, which adds up an array of numbers.
The main function is compileTasks.  It simply maps the list of tasks to slightly altered versions, removing completed and adding percent, which is found by calling findPercent.
There is a potential problem with this technique, though.  It doesn't matter at all for small tests, but there is a lot of work that is done multiple times.  We average the percentages of 7 and 8, when building 1, then do it again when building 3, and again when building 6.  This is problematic, and so I will suggest a:
More Performant Approach
The problem here is that our flat list is not the best way to track what is fundamentally a tree structure.  This would be much easier to work with:
[
    {id: 1, task: "Clean apartment", completed: null, children: [
        {id: 3, task: "Clean bathroom", completed: null, children: [
            {id: 5, task: "Wash sink", completed: true},
            {id: 6, task: "Wash shower", completed: null, children: [
                {id: 7, task: "Wash glass panes", completed: null},
                {id: 8, task: "Wash floor", completed: null}
            ]}
        ]},
        {id: 4, task: "Clean kitchen", completed: null}
    ]},
    {id: 2, task: "Make app", completed: null}
]

I would suggest that you consider using this more useful structure internally all the time, and only using the flat list for storage.   But if you can't, do this,  then we can convert back and forth between the two structure, and do your calculations on that nicer tree structure.  It might look like this:

const sum = (ns) => ns .reduce ((a, b) => a + b, 0)

const nest = (tasks, parent = null) =>
  tasks .filter (({parentId}) => parentId === parent) .map (
    ({id, parentId, ...rest}, _, __, children = nest (tasks, id)) => ({
      id, ...rest, ...(children.length ? {children} : {})
    }))

const unnest = (nodes, parentId = null) => [
  ...nodes .map (({children, ...rest}) => ({...rest, parentId})),
  ...nodes .flatMap (node => unnest (node .children || [], node.id))
]

const calcPcts = (tasks) =>
  tasks .map (({completed, children = [], ...rest}, _, __, kids = calcPcts (children)) => ({
    ... rest,
    ... (kids .length
          ? {percent: sum (kids .map (k => k.percent)) / kids .length, children: kids}
          : {percent: completed ? 100 : 0}
        )
  }))

const compileTasks = (tasks) =>
  unnest (calcPcts (nest (tasks)))

const tasks = [{id: 1, task: 'Clean apartment', completed: null, parentId: null}, {id: 2, task: 'Make app', completed: null, parentId: null}, {id: 3, task: 'Clean bathroom', completed: null, parentId: 1}, {id: 4, task: 'Clean kitchen', completed: null, parentId: 1}, {id: 5, task: 'Wash sink', completed: true, parentId: 3}, {id: 6, task: 'Wash shower', completed: null, parentId: 3}, {id: 7, task: 'Wash glass panes', completed: null, parentId: 6}, {id: 8, task: 'Wash floor', completed: null, parentId: 6}]

console .log (compileTasks (tasks))
.as-console-wrapper {max-height: 100% !important; top: 0}

Here, after the sum helper, we have a nest function that converts your flat list into that tree structure, and an unnest function that converts it such a tree back into the flat list.
Our main function is compileTasks, which simply composes these two functions and runs the core function calcPcts between them to generate this intermediate format:
[
    {id: 1, task: "Clean apartment", percent: 25, children: [
        {id: 3, task: "Clean bathroom", percent: 50, children: [
            {id: 5, task: "Wash sink", percent: 100},
            {id: 6, task: "Wash shower", percent: 0, children: [
                {id: 7, task: "Wash glass panes", percent: 0},
                {id: 8, task: "Wash floor", percent: 0}
            ]}
        ]},
        {id: 4, task: "Clean kitchen", percent: 0}
    ]},
    {id: 2, task: "Make app", percent: 0}
]

And now we need to discuss calcPcts.  This works much like above, except that because we're calling top-down, and rolling up the results from the bottom up, we don't have to  re-call it for nested nodes.
One interesting thing about this approach is that you can reuse nest and unnest around other recursive node conversion techniques.  The roll-up from completed to percent is isolated in that one place, but the overall mechanism is shared.
Comment: Wow, this is great! Sorry for my late respons, there was a lot to go through.

I've been thinking about performance for this project. First I tried making the "tasks" nested, but I had trouble adding tasks etc because my lack of experience in recursive thinking.

I ended up making this flat structure assuming I'm gonna use a mysql database. Do you think a nosql database would be better?

In the end I would like my webserver to return a nested structure of the tasks.
Comment: Not at all a slow response (and that should never be a worry on StackOverflow anyway.) How you choose to store your data is far too complex a topic to decide in a short chat. But these days you do have good choices for Object stores if you like. If you do store it flat, I would recommend that you use something like `nest` as soon as you retrieve it, use the tree format for your application code, and only use the `unnest` when you go to store it back. The tree is much easier to work with for all sorts of cases. And in those places where it's harder, it's only *slightly* harder. Best of luck!
Comment: Hello, again! I'm having trouble making the calcPcts function accept one task instead of all tasks. If I use the function I wrote (compileTask) as the nest function, I can't use calcPcts because it expects an array (I think). Do you mind making an edit?
Comment: I'm afraid you're missing the point.  `calcPcts` operates on the **tree** structure displayed above.  It transforms a *tree* of objects with `completed` properties into a *tree* with `percent` properties. The whole idea is that it is not individual nodes which capture the information you want but the entire tree structure. My initial approach works more like you seem to want. You can use it, but it will have performance problems as the data grows.  I don't know how bad or how soon, and it may never become an issue for you, but the second approach is not only more performant: it's also cleaner.


Difference between spanning set and a basis

Question: Can anybody please shed some light on the difference between a spanning set and a basis?
Comment: A spanning set does not need to be linearly independent.
Answer: A basis is a spanning set that is also linearly independent.
For example, consider the vector space $\mathbb{P}$ of all linear polynomials over $\mathbb{R}$, of the form
$$
\mathbb{P} = \{a+bx|a,b\in \mathbb{R}\}.
$$
Let $\vec{u} = 1, \vec{v} = x, \vec{w} = 1+x$ and let $S = \left\{\vec{u},\vec{v},\vec{w}\right\}$.
Note that $S$ spans $\mathbb{P}$, but it not linearly independent, hence $S$ is not a basis for $\mathbb{P}$. To get a basis, take any 2 elements of $S$.


How do I update customers cart prices and add discount and then let them checkout?

Question: I'm using Drupal 7 Commerce and Commerce discount, amongst many others.
So the use case is this. We often get enquiries for bulk orders containing many products. We want our customer to go to the website and add what they want into their cart. As admin I want to open that unpaid cart, edit product prices and apply a Fixed Price Discount. Then when the customer refreshes their cart they will see our amendments and continue with payment. Is this possible? Am I missing something obvious?
At present I can edit a order that is in the cart but when the customer refreshes their cart the order is reverted back to prior my changes. I can't edit product prices at all whilst the order isn't completed. Once in Completed status, I can tweak product prices and add the discount.
To get the Fixed price discount feature to work I had to switch from the Line Item Manager widget over to Multiple Inline Entity References. For the line items field on orders that is. Before that I couldn't use the Fixed price discount feature at all.
Any help would be greatly appreciated. I must be performing the wrong searches or something.
Answer: There aren't many good solutions here, because you're hitting up against the limitations of the pricing system. You have two basic options: custom line item fields that contain special pricing paired with a pricing rule that overrides the default product price or some combination of discounts that adjust product prices solely for that user. The former may be a challenge, because I can't remember if we ever fully got Inline Entity Form to manage line items, and the latter would be a pain for orders with a lot of different products.
The Commerce Price List module was ultimately developed to handle situations like this, where price lists can be assigned on a per user / quantity basis. It appears the same feature set works in D7 as in D8, but it would give the customer access to that pricing on any order while the price list was active, not just a single one. If that's no problem, then that's probably your solution.
Comment: The button only shows depending on the order status. Up until "Checkout: Payment" it is unavailable. That's why I couldn't find it. I was trying to add products and discounts, then let them check themselves out. That one snagged me for ages.
Comment: It's all good. I know the feeling of trying to remember part of a system you haven't touched for a while. I wouldn't have done it so quickly if it hadn't been for you pointing me in the right direction with the additional field. Really appreciated...
Comment: Thanks so much for your reply. I'm not too familiar with the pricing system side of commerce. I've only just got back to this task. I've chosen to go option 1 as things will vary per order. I've created the product line item field. Added a pricing rule however I can't get it to take effect. It's as follows:

Event: calculating sell price.
Condition: line item has the new discount price field & New field is not empty.
Tried these actions: Set the unit price to a specific amount & Set a data value.

No cigar though. Don't suppose you have any pointers?
Comment: Set the unit price to that specific value should've worked imo. May need to ensure it's not being undone by some other rule firing after it?
Comment: I thought it should have worked too. Sounds like a great idea and exactly the end result I needed. I'll check out the rules. I found this little module for sending a customer a link to complete checkout: https://github.com/sjsam/Drupal-MOPL. Just need to beat this into submission. We deal with customers via email and on Instagram. That's our motivation.
Comment: Also if I use line item manager I don't get my custom discount field to edit. So I've been using Entity Reference widget. Using it and updating the qty updates the line item fine. Is there a way to surface to field with line item manager? Perhaps there is a issue there.
Comment: I wondered if I was using the wrong token. So I removed the conditions and set the value to 150.00. However this isn't reflected in the order upon updating the line item.
Comment: It does change all the prices on the website. Just not in the admin create order screen.
Comment: So this is now half working. I changed the token from amount decimal to just amount in the rule. On the admin screen I set the discounted price on the line item. After updating the line item the price change isn't reflected. Save the order and it isn't reflected on the page of orders. If it was made via the cart, on refresh of the orders page the price is reflected. If the order is created via admin, the price isn't reflected anywhere in the admin section. However, using the small module above, the email gets sent and the prices are reflected for the buyer at checkout.
Comment: Ahh, yeah, that detail is important - pricing rules aren't automatically executed on the order edit form in the same way they are on the customer shopping cart. We do offer a local action link to apply pricing rules to an order, though - that would do the trick!
Comment: Where is that button/link? I expected to see it next to Simulate checkout completion on the order edit page. Can't see it anywhere
Comment: If it's not appearing, you're either on an older version of Commerce 1.x or upgraded from it without specifically toggling the option on. Go to your order settings page (Admin > Store > Configuration > Order settings) and ensure the checkbox labeled "Enable the local action link on order edit forms to apply pricing rules." is checked.
Comment: @gMaximus OH! Man, I must've forgotten - I guess I didn't want someone to apply pricing rules and then have the changes reverted in an ordinary cart refresh on the front end. Waiting until "Checkout: Payment" just means the order is no longer considered a cart for the purposes of cart refresh. It could be any status "after" that, basically. Feel free to open an issue for that to be more clear in the UI help text.
Answer: There was a few steps to this
1) Create a custom field on your product line items. Use a "price" field type. I called it "Discount unit price".
2) On your order entity line item field widget, you'll need the "Multiple Inline Entity References." This allows you to edit your custom field.
3) Create a pricing rule
   Event: Calculating the sell price of a product
   Conditions: 1) "Entity has field" and select our new field. 2) "Data value is empty" with the negate box checked. In other words we're interested if the field is not empty.
   Action: "Set the unit price to a specific amount". Enter the token for your new field. I used "amount" not "amount-decimal."
4) Create a 2nd rule to re-apply pricing rules when admins create or update a order
   Event: "After saving a new commerce order", "After updating an existing commerce order"
   Conditions: "User has roles". Select your admin roles.
   Action: "Execute custom PHP code" (you need "php filter" module enabled). Enter this "commerce_cart_order_refresh([commerce-order:order-id]);"
5) In order to send the customer a payment link with the discounted prices, install this small module: https://github.com/sjsam/Drupal-MOPL. When you download the zip folder, you'll want to change the folder name to "mopl".

In order to use this:
1) Create a new order or update a existing order.
2) Set your discounted prices in your new field.
3) Set the status to "Checkout: checkout".

The customer will now get a link to click in order to complete the checkout.

If they have populated their cart first. Edit it accordingly and save the order. When they refresh the page their cart prices will get updated.

In the question I also wanted to add a fixed price discount from the discount module. I couldn't work out how to have the "Fixed price discount" applied when the customer completes checkout. So I created a product called Discount and set the price to zero. I then add that product to the cart and set the discounted unit price to the discount I want ie -300.

At this point the customer could go back to the Shopping cart page and update the qty for the discount product. So I added a filter to exclude the "discount" product.

That's it!


What does a B on a note stem in guitar music mean?

Question: I found B's on note stems in sheet music of the 3rd movement of the Libra Sonatine, "Fuoco", by Roland Dyens, which is for guitar:

What does that B on a note stem mean in this guitar music? Those notes with B's are not played entirely cleanly, and part of me suspects that the B has to do with barre, but I still cannot figure out what the B is entirely for (unlike Z's on note stems earlier in the music, which are for mordents).
The sheet music scrolls by with the music in the following video, and notes with B's are played starting at 13:49 in

 (the video should start at 13:49).
Even after taking a good hard look at Roland Dyens playing "Fuoco" in

 (he starts playing notes with B's at 3:14, and the video should start there), I remain confused - he didn't even seem to play the notes with B's in a consistent fashion, especially not the ones in the last measure of the piece.
For what it's worth, my Google searches for what this symbol means have produced only irrelevant results, and I couldn't find any guide on what those B's mean earlier in the sheet music.
(When I made an Liszt's-Paganini-Etudes-style enhanced transcription of "Fuoco" for piano, I ended up treating the notes with B's as if the B's weren't there. To this day, I am not completely satisfied with how I treated those notes.)
Comment: "When I made an Liszt's-Paganini-Etudes-style enhanced transcription of "Fuoco" for piano, I ended up treating the notes with B's as if the B's weren't there. To this day, I am not completely satisfied with how I treated those notes." Add an unpitched percussion part which should play on all notes with B's.
Answer: Not sure what it is, but it sounds like a snap pizzicato, alternatively called Bartók pizzicato (that could be that B -- this technique was first used on violin by Bartók, so it's sometimes called by his name).
It is performed like this: instead of plucking normally, you put your finger (it's best done with thumb) under the string (between the string and the guitar body), pull the string upwards and release. The string gives a tone as usual, but there is an added "percussive" sound as the string hits the frets and rebounds.
(Alternatively, you can do it with two fingers like John Williams in this performance of the Usher Waltz. I think you will be able to hear the effect more clearly in this video, too.)
Comment: Definitely this! A well-known technique used by bassists (electric) called *popping*. I use it  on electric guitar too. Works absolutely fine using finger or thumb. Gives a sfortzando sounding note.
Comment: Now I'm wondering whether it's in fact meant to stand for "Bartok," or for some French verb...
Comment: @AndyBonner Wdym? The spelling of the name is correct. https://en.wikipedia.org/wiki/Béla_Bartók
Comment: @Divide1918 Oh, I was just idly wondering—yes, this technique is probably what's intended, and bowed-string players are used to calling it "Bartok pizz," but wondering whether the "B" here does in fact stand for Bartok, or for some other word (*battez*?).
Comment: On closer inspection, it actually does look like Roland Dyens is using this kind of pizzicato at the notes with B's on their stems (along with another performer of "Fuoco"). Thanks!