All unique combinations of n numbers

Question: How is the algorithm or process called which calculates all unique combinations of n numbers? By unique I mean that this 1234 is the same as this 1243.
Example:
Take this 4 numbers and list all unique combinations:
1
2
3
4

Output:
1
2
3
4
12
13
14
23
24
34
123
124
134
234
1234

Comment: Why did you not take 134?
Comment: These are the non-empty subsets, and you can generate them all by running $k$ from $1$ to $2^{n}-1$, write $k$ as a binary $n$-digit number, and then generate the set for $k$ by adding $i$ if the $i$th binary digit of $k$ is $1$.
Comment: *Higher-Order Perl* discusses this problem and provides code to solve it, I think in Chapter 5. [It is available online for free](http://hop.perl.plover.com/book/).
Comment: What if there are repetitions in the number? How would you find all unique combinations for 1134?
Answer: There are $2^n-1$ non-empty subsets of the set $\{1,...,n\}$. Given a number $k=1,...,2^n-1$, we can write the $k$ as an $n$-digit binary number, and then put $i$ in the set $A_k$ if the $i$th binary digit of $k$ is $1$.
For example, $n=3$ yields:
$$\begin{array}{cc}\text k & \text {binary} & \text{set}\\
1 & 001 & \{3\}\\
2 & 010 & \{2\}\\
3 & 011 & \{2,3\}\\
4 & 100 & \{1\}\\
5 & 101 & \{1,3\}\\
6 & 110 & \{1,2\}\\
7 & 111 & \{1,2,3\}
\end{array}$$
Comment: Thanks! It's so simple why haven't I thought about to consider it as binary counting where each element represents a bit :-)
Answer: If you want to list them, the easiest way is to count from $0$(if you allow the empty set) or $1$ (if not) to $2^n-1$ in binary.  At each value, use the bits that are turned on to represent the elements.  So when you get to $11_{10}=1011_2$ you output $134$
Answer: For $n$ numbers, the output consists of $2^n-1$ entries, which is the number of nonempty subsets of $\{1,\ldots,n\}$.
Comment: Yeah, he wants to generate the list of them, it seems.
Comment: Thank you but that wasn't my question. I'd like to know the name of the process which calculates all uniqe combinations of n numbers. If there is a name :-)

All unique combinations of n numbers


How to detect the country code and change flag in FPNTextField

Question: I am using FlagPhoneno Pod to search or select country codes with flags, by using below codes. But when comes to edit part I get full phone no to the FPNtextFeild ex- +971568573570 and by default i set country code as .AE
I want to detect and automatically change the country flag when any other country phone no fetch from json let recivedPhoneNo = self.json["phone_number"].string ?? ""
For the moment the flag is changing when select only. please show me an example method with code from same pod "FlagPhoneno" module.
I am using following code.
    func setupPhoneTF(){
        self.phoneTFView.layer.borderColor = UIColor.appColor.customGray.cgColor
        self.phoneTFView.layer.cornerRadius = 5
        self.phoneTFView.layer.borderWidth = 1

                phoneTF.displayMode = .list // .picker by default
                listController.setup(repository: phoneTF.countryRepository)

                listController.didSelect = { [weak self] country in
                    self?.phoneTF.setFlag(countryCode: country.code)
                }

                phoneTF.delegate = self
                phoneTF.font = UIFont.systemFont(ofSize: 14)

                // Custom the size/edgeInsets of the flag button
                phoneTF.flagButtonSize = CGSize(width: 35, height: 35)
                phoneTF.flagButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
                 let items = [
                UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.save, target: self, action: nil),
                UIBarButtonItem(title: "Item 1", style: .plain, target: self, action: nil),
                UIBarButtonItem(title: "Item 2", style: .plain, target: self, action: nil)
            ]
                phoneTF.textFieldInputAccessoryView = getCustomTextFieldInputAccessoryView(with: items)
                phoneTF.hasPhoneNumberExample = true
                phoneTF.placeholder = "Phone Number"
                phoneTF.setFlag(countryCode: .AE)
    }

extension AddNewAddressVC: FPNTextFieldDelegate {

    func fpnDidValidatePhoneNumber(textField: FPNTextField, isValid: Bool) {
        textField.rightViewMode = .whileEditing
        textField.rightView = UIImageView(image: isValid ?  imageLiteral(resourceName: "success") :  imageLiteral(resourceName: "error"))
        print(
            isValid,
            textField.getFormattedPhoneNumber(format: .E164) ?? "E164: nil",
            textField.getFormattedPhoneNumber(format: .International) ?? "International: nil",
            textField.getFormattedPhoneNumber(format: .National) ?? "National: nil",
            textField.getFormattedPhoneNumber(format: .RFC3966) ?? "RFC3966: nil",
            textField.getRawPhoneNumber() ?? "Raw: nil"
        )
    }

    func fpnDidSelectCountry(name: String, dialCode: String, code: String) {
        print(name, dialCode, code)
        self.selectedDialCod = dialCode
    }

    func fpnDisplayCountryList() {
        let navigationViewController = UINavigationController(rootViewController: listController)
        listController.title = "Countries"
        listController.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(dismissCountries))
        self.present(navigationViewController, animated: true, completion: nil)
    }
}

Answer: // You can change the chosen flag then set the phone number
phoneNumberTextField.setFlag(for: .FR)
phoneNumberTextField.set(phoneNumber: "0600000001")

// Or directly set the phone number with country code, which will update automatically the flag image
phoneNumberTextField.set(phoneNumber: "+33600000001")

Answer: FlagPhoneNumber pod have an issue by which flag get disappear after upload and if you reinstall the ipa from testflight the flag will be gone.


Name/notation for group of permutation matrices

Question: $S_n$ is the group of permutations, and there is a bijection between each permutation and its permutation matrix. Is there a name/notation for the group of permutation matrices?
Comment: The name is still $S_n$, since we usually consider groups only up to isomorphisms.
Comment: @DietrichBurde then how are the two groups distinguished? Though they are isomorphic they do not have the same elements.
Comment: @qwr The element of the group of permutation matrices are not denoted the same way. See my answer.
Answer: It's simply called : the group of permutation matrices.
A permutation matrix associated with the bijection $\tau$ is often denoted : $P_\tau$.
Comment: Do you know of a notation then?
Comment: We use the same notation as the symmetric group. But we use a notation to denote the element of this group differently (see above).
Answer: I cannot say that I have ever heard the group of permutation matrices called anything other than $S_{n}$ but most define $S_{n}$ as the set of bijections on an $n$-element set and there is obviously quite a few $n$-element sets out there. The common choice is thinking of bijections on the set $\{ 1 ,\dots, n\}$. I think this is probably best for any type of calculation to be carried out by hand especially considering you can write elements rather compactly using cycle notation, but you could of course use a different $n$-element set.
We could use other symbols as well obviously, such as the elements of the canonical basis for $F^n$ for some field $F$ but it obviously depends on context. Thinking about $S_{n}$ as the set of bijections on the canonical basis for $F^n$ obviously has broader implications because there is additional structure there. However, could you imagine working out orbits, stabilizers, cosets, etc. by hand if you were working exclusively with matrices? That would get really cumbersome for $n > 2$. If you are using a computer algebra system though, then this is of course turns out to be a great way to do things.


invalid on specified as date, must be a column (if DataFrame) or None

Question: The following line gives me error:
 invalid on specified as date, must be a column (if DataFrame) or None
How to resolve it?
test_data=pd.DataFrame({'date':['20190606','20190610','20190708','20190805','20190909','20190930'],'number':[3,5,4,1,0,0],\
                       'avg_last_2m':[None,3,4,4,1,0.5]})
test_data['date']=pd.to_datetime(test_data['date'])
print(test_data.rolling('90d', on='date')['number'].agg({'sum','count'}))

Answer: I think the issue is in your agg. Try this:
test_data.rolling('90d', on='date')['number'].agg({'sum':sum,'count':'count'})

Output:
    sum     count
0   3.0     1.0
1   8.0     2.0
2   12.0    3.0
3   13.0    4.0
4   5.0     3.0
5   5.0     4.0

Answer: Surprisingly, @Andy's answer was correct, it's likely a bug. Although passing a dictionary to agg is deprecated.
You can also fix it by:
test_data.set_index('date').rolling('90d')['number'].agg({'sum','count'})

output:
            count   sum
date
2019-06-06    1.0   3.0
2019-06-10    2.0   8.0
2019-07-08    3.0  12.0
2019-08-05    4.0  13.0
2019-09-09    3.0   5.0
2019-09-30    4.0   5.0


Serving pages and HTTP STATUS codes

Question: As all we know, when server gives HTTP 404 STATUS code, it can deliver some custom page. Which else status codes can serve some custom pages except 200-206 codes?
Answer: You may take a look at RFC 2616. The HTTP status codes and their definitions are listed beginning on page 56.
Comment: This RFC 2616 document covers only purpose of HTTP STATUS code. For me it is important to understand what can I expect from webserver looking from security perspective.

Serving pages and HTTP STATUS codes


Can't pass through second table data to foreach in laravel

Question: I am building a college project and i cannot pass through data from a second table with primary table / class.
When i try to pass it and access it in the view i get a try to access non object error.
this is my code below.
Gym class
class Gym extends Eloquent implements UserInterface, RemindableInterface {

use UserTrait, RemindableTrait;
 */
protected $table = 'gyms';

public $gym;

public function reviews()
{
return $this->hasMany('Review', 'unique_gym_id'); // represents the Review class
}

pages controller relevant section, i pass through data from this loop to the view.
foreach($gymsearchs as $gymsearch)
{

    Gym::save($gymsearch);
    $gyms[] = DB::table('gyms')->where('unique_gym_id', '=', $gymsearch->unique_gym_id)->get();
    Review::review($gymsearch);
    $reviews[] = DB::table('reviews')->where('unique_gym_id', '=', $gymsearch->unique_gym_id)->get();

}

//dd($reviews); this shows the full review object contents fine
    $data = array_add($data, 'gyms', $gyms, 'reviews', $reviews);

view
@foreach(array_slice($gyms, 0, 5) as $gym)
    {{$gym->name}} // works fine and with other objects from the $gym
@endforeach

@foreach(array_slice($gyms, 0, 5) as $gym)
     {{$gym->review}} // this gives me a trying to access non object error.
@endforeach

both the gym model and review model have unique_gym_id as a column
i thought this review class in the gym model should have brough the review table data with the $gym?
public function reviews()
{
return $this->hasMany('Review', 'place_id');
}

any ideas what i am missing? thanks i am a novice to laravel and php
Comment: $data = array_add($data, 'gyms', $gyms, 'reviews', $reviews); - better use
$data = $data + ['gyms'=> $gyms, 'reviews'=>$reviews];
Comment: cool thanks, as im a novice could you tell me why :)
Comment: clearer code works better. about your question - maybe you can add a little bit more details?..
Comment: Sure thanks, btw the line you changed let me access the $reviews in the view where as the other line did not. so thank you,

I am trying to loop through the $gyms but then bring the relevant data from the reviews table with it.

i thought having this  public function reviews()
{
return $this->hasMany('Review', 'place_id');
}

this in my model allowed the $gyms var to pull in data from the reviews table, as i want to loop through both were they share a common unique_gym_id, your edit i can use them both or can i use them in the loop together even if the reviews function doesn't seem to work?
Answer: You told it to be a hasMany-relationship, so shouldn't it be "{{$gym->reviews}}" instead? Haven't tried it, but seems pretty odd. Also this should return an array rather then a single object, so you would have to iterate over it.
EDIT:
This whole section:
foreach($gymsearchs as $gymsearch)
{
   Gym::save($gymsearch);
   $gyms[] = DB::table('gyms')->where('unique_gym_id', '=', $gymsearch->unique_gym_id)->get();
   Review::review($gymsearch);
   $reviews[] = DB::table('reviews')->where('unique_gym_id', '=', $gymsearch->unique_gym_id)->get();
}

//dd($reviews); this shows the full review object contents fine
$data = array_add($data, 'gyms', $gyms, 'reviews', $reviews);

could probably be
Gym::save($gymsearchs);
$gyms = Gym::where('unique_gym_id', 'in', array_map(create_function('$o', 'return $o->unique_gym_id;'), $gymsearchs))->get();
$data['gyms'] = $gyms;

, as you don't seem to use the $reviews. But I don't quite grasp the intend of gymsearchs and what you are trying to do with the Review::review($gymsearch) approach. Also you should look into eager loading for this case. There is a ->with($relation) function, that can eager load all your reviews. This way you can optimise the number of queries send to the database.
Comment: Thanks for this, just to be clear as i can't get it to work, i get this
Trying to get property of non-object, so its in an array, the relationship sepecfied in the model should allow this object to be accesed via below?

 @foreach(array_slice($gyms, 0, 5) as $gym)

{{$gym->reviews}}
@endforeach

if i cant get that to work right the way above with
$data = $data + ['gyms'=> $gyms, 'reviews'=>$reviews];
lets me access the $reviews where i could not before, but if i do a foreach and then a foreach inside to loop through the $reviews i get all 5 $reviews contents for each of the outside looop?
Comment: It should be something along the lines of: \@foreach(array_slice($gyms, 0, 5) as $gym) \@foreach($gym->reviews as $review) {{$review->reviewText}} \@endforeach \@endforeach. Where reviewText is an attribute of your Review entity. As I do not have much knowledge of the laravel templating engine, I can not say for sure how to nest \@foreach statements in it but this seems to be an appropriate way. (I had to escape the [at]-sign, as SO wouldn't allow me to comment otherwise)
Comment: Cheers Rick, ill try that now
Comment: Cheers rick i was orignally doing it wrong and calling the tabled data from the controller. hence the $reviews[]
i.e calling both tables as variables and passing it to the view, not actually utilising the model except to save, i have changed that, now what i am trying to do is your approach and just call $gyms, then in the model have the relationship bring the reviews data with it etc.
Comment: is this marked as answered now? thanks rick your explanation got it to work  exactly how you said.
Comment: Hey, glad I could be of any help. Just click the tick, next to the post you want to mark as the accepted answer. Have a great weekend.


Does the average increase of a "re-roll" increase with the size of the dice?

Question: I'm having trouble modeling the following scenario:

Roll two dice and take the best
  result.

What is the proper way to model the average result from this? I understand intuitively that the average should go up, but I'm having trouble understanding exactly what plays into this increase.
Furthermore, is the increase greater or simply proportional in dice of larger size  (more sides)? For comparison's sake, consider a normal 6-sided die, and a 12-sided die.
Answer: You have $n^2$ possible outcomes for two dice, where $n$ is the number of sides. The next step is to calculate the probability for each maximum pip ($k$).
For $k=1$ there is one possible outcome (1, 1).
For $k=2$ there are three possible outcomes {(1,2), (2,1), (2,2)}
For $k=j$ there are $2j-1$ possible outcomes. Here's a small graphic to illustrate this relation.

Finally calculate the expected value: $\sum_{i=1}^{n} p(i)i = \sum_{i=1}^{n} \frac{2i-1}{n^2}i = \frac{(n+1)(4n-1)}{6n}$.
Comment: which you could write  as $\frac{2}{3}n + \frac{1}{2} -\frac{1}{6n}$ to make it more obvious what happens when $n$ increases.
Comment: @Henry Given the question was about the increase over the average, I'd have written it as $\frac{2}{3}(n+1)-\frac{1}{6n}$, for easier comparison with the average of $\frac{1}{2}(n+1)$
Answer: Alternatively, in the limit of large number of sides you can think of rolling a die as picking a uniformly distributed random number on $[0,1]$, and then multiplying by the number of sides. So you're trying to find $E(max(X,Y))$ where $X, Y$ are independent uniform[0, 1] random variables. This is
$$ \int_0^1 \int_0^1 \max(x,y) \: dx \: dy $$
which you can split according to whether $x$ or $y$ is larger, giving
$$ \int_0^1 \int_y^1 x \: dx \: dy + \int_0^1 \int_0^y y \: dx \: dy. $$
Both of these integrals are $1/3$ and so $E(\max(X,Y)) = 2/3$; this tells you that the larger of the two dice will be, on average, $2n/3$. Of course this agrees with Tim's answer. (It turns out that if you have $k$ dice each with $n$ sides, the expectation of the largest die would be about $kn/(k+1)$.)
If you don't know calculus, don't worry about this. If you do know calculus, I hope this helped.
Comment: Could someone elaborate about why the second formula works? `K*N/(K+1)`
Answer: A quick simulation in R indicates the increase is proportional to the number of sides of the dice
<code>means = NULL
for(i in seq(6,72,by=6)) {
  dice1 = sample(1:i, 10000, replace=T)
  dice2 = sample(1:i, 10000, replace=T)
  m = mean(pmax(dice1, dice2))
  means = c(means, m)
}

plot(means)
</code>


Dimension of an object

Question: I know the dimension of a straight line, a circle is 1. But how can we prove it by using vector space? The dimension a vector space is the number of elements in the basis.
Comment: How ? Can you explain this ?
Comment: Actually a curve which is not a stright can be thought like a stright line, but later is the topological equivalence.... I just wanted to knew that, is there any basis of such non-stright curves like stright line has a basis consisting on a singel non zero element.
Comment: How can I explain the concept of dimension to a students of software engeenring?
Comment: To more fully answer that, you're gonna need a concept of "dimension" that's different from the one you know in linear algebra.
Comment: In linear algebra, we talk about vector spaces, and the dimension of a vector space. A vector space is defined by the ability to add things, and a scalar field (typically the real numbers $\mathbb{R}$ or complex numbers $\mathbb{C}$) by which we can multiply. Now think about a circle in the plane. Your conception of a circle is not "vector spacey", in that you aren't thinking about adding things. If anything, we'd think a circle two-dimensional, because we wouldn't even think of circles in $1$-space (the line). (cont.)
Comment: So we instead want a different way to talk about the dimension of objects other than vector spaces (e.g. a circle) that still conform with our intuition of what the dimension should be. One way to do this is hinted at in MattG88's answer, where we think of the circle as a very nice function from $1$-space into $2$-space (this involves what are called *manifolds*). Another is called Hausdorff dimension, which is how we talk about the dimension of "weird" sets, like fractals, or assign to dimension to the set of all rational numbers, or of all irrational numbers.
Comment: Two responses: (i) topology is not a vector space concept (there are "standard" ways to topologize certain vector spaces, but I can topologize $\mathbb{R}^2$ where the circle and line look nothing alike, or where almost anything looks the same as almost anything else), while the dimension under discussion here is; and (ii) not really because circles aren't additive structures, i.e. we don't define circles linear-algebraically, so there's not really a way to connect a linear-algebraic dimension with the intuitive dimension of a circle.
Comment: I think any connection you wanna make between linear algebra dimension and more proper geometric dimension will have to involve a linear-algebraic concept of a line, and then a geometric connection between circles and lines.
Comment: @PrinceKhan Maybe you can think like this: if you have a vector space described by $(x,0,0)$ you can say that is one dimensional (a base is (1,0,0)), it depends by a parameter ($x$) so if you have a geometric object that is described by a parameter it is one dimensional...it is a sort of analogy
Comment: @PrinceKhan However I agree with AJY so pay attention to the concept of dimension
Answer: The line is 1 dimensional because you can take an element (a number $n\ne 0$) as base and you can obtain all the others number by multiplication; in this case the base is made by only one element.
You can describe a circle with radius $r$ by $re^{i\theta}$, so it depends by only a parameter ($\theta$; r is fixed), that it is just a number so the circle is like the line, it is one-dimensional.
Comment: thats fine... Now we know that a curve in the plane (any curve of a continuos function in one variable) is also one dimensional... what will be the basis in this case ?
Comment: Yes that was my confusion.... Actually a curve whichis not a stright can be thought like a stright line,  butlater is the topological concept.... I just wanted to knew that, is there any basis of such non-stright curves like stright line has a basis consisting on a singel non zero element...
Comment: As the circle the curve can be described by a parameter so it is one dimensional...we can say that the curve is like the real line
Comment: Oh yes we need topology...with topology we can build bridges between objects that they seem different at the first sight

Dimension of an object


Como calcular PI com "n" casas decimais em JavaScript?

Question: Usando o objeto Math do JavaScript, eu consigo retornar um valor PI com casas decimais fixas, exemplo:
Math.PI //3.141592653589793

Mas e no caso de eu precisar (sim, bem incomum) calcular o mesmo com mais casas decimais, existe alguma outra forma de definir um número de casas decimais? Exemplo:
Math.pi(300) //retornaria com precisão de 300 casas decimais, etc.

Answer: A primeira coisa que você precisa é de uma biblioteca de manipulação de números decimais de precisão arbitrária. Um double (formato numérico usado por JavaScript para o tipo Number) tem precisão de no máximo umas 15 casas decimais (floor(log10(2^53))), de modo que se você precisa fazer qualquer conta envolvendo mais casas que isso, é necessário representar esses números de alguma outra forma.
(e você quer fazer contas com π, certo? Pois se fosse só questão de exibi-lo, uma string pré-populada com seu valor bastaria...)
Uma vez escolhida uma biblioteca, você tem duas opções:

Para se usar na prática, é preferível obter o valor de π de algum lugar em vez de calculá-lo. Uma string de 300 bytes não traz um overhead tão grande pro seu sistema... (em especial pelo código a mais que você teria que colocar para fazer seu cálculo)
Se for mesmo necessário (ou desejável, por exemplo para fins de estudo) calcular você mesmo, há diversas fórmulas que convergem para π. Uma delas (a primeira sugestão da resposta do Maniero) é π = 48*arctan(1/18) + 32*arctan(1/57) − 20*arctan(1/239), onde o arco tangente pode ser calculado por meio de uma série infinita. Outras séries e/ou expressões infinitas também convergem para π.

Não sei dizer qual é a melhor (nem qual o melhor critério para definir "a melhor"), então vou dar um exemplo usando o arco seno, pois me parece bem fácil de calcular:
                1 * x^3   1 * 3 * x^5   1 * 3 * 5 * x^7
arcsin(x) = x + ------- + ----------- + --------------- + ...
                2 * 3     2 * 4 * 5     2 * 4 * 6 * 7

arcsin(1/2) = π/6

Usando a biblioteca javascript-bignum:
var pi = new BigNumber("3", precisao + 5); // Começa com 3 (6*x, x == 1/2)
var antigo = new BigNumber("0", precisao + 5);

var numerador = new BigNumber("6", precisao + 5); // O numerador da próxima parcela
var denominador = new BigNumber("1", precisao + 5); // Parte do denominador (comum)
var potencia2 = new BigNumber("2", precisao + 5); // Outra parte (variável)

var indice = 1; // Qual parcela está sendo acrescentada

function passo() {
  if ( pi.compare(antigo) == 0 ) // Se o valor não mudou, já convergiu
    return;

  antigo = pi; // Salva o valor antigo

  numerador = numerador.multiply(indice);
  denominador = denominador.multiply(indice+1);
  potencia2 = potencia2.multiply(4);

  // Acrescenta a próxima parcela na série
  var parcela = numerador.divide(denominador).divide(indice+2).divide(potencia2);
  pi = pi.add(parcela);

  indice += 2
  setTimeout(passo, 0); // Executa o próximo passo (assíncrono)
}
passo(); // Começa

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/bignumber [rev. #4]

BigNumber = function(n, p, r){
    var o = this, i;
    if(n instanceof BigNumber){
        for(i in {precision: 0, roundType: 0, _s: 0, _f: 0}) o[i] = n[i];
        o._d = n._d.slice();
        return;
    }
    o.precision = isNaN(p = Math.abs(p)) ? BigNumber.defaultPrecision : p;
    o.roundType = isNaN(r = Math.abs(r)) ? BigNumber.defaultRoundType : r;
    o._s = (n += "").charAt(0) == "-";
    o._f = ((n = n.replace(/[^\d.]/g, "").split(".", 2))[0] = n[0].replace(/^0+/, "") || "0").length;
    for(i = (n = o._d = (n.join("") || "0").split("")).length; i; n[--i] = +n[i]);
    o.round();
};
with({$: BigNumber, o: BigNumber.prototype}){
    $.ROUND_HALF_EVEN = ($.ROUND_HALF_DOWN = ($.ROUND_HALF_UP = ($.ROUND_FLOOR = ($.ROUND_CEIL = ($.ROUND_DOWN = ($.ROUND_UP = 0) + 1) + 1) + 1) + 1) + 1) + 1;
    $.defaultPrecision = 40;
    $.defaultRoundType = $.ROUND_HALF_UP;
    o.add = function(n){
        if(this._s != (n = new BigNumber(n))._s)
            return n._s ^= 1, this.subtract(n);
        var o = new BigNumber(this), a = o._d, b = n._d, la = o._f,
        lb = n._f, n = Math.max(la, lb), i, r;
        la != lb && ((lb = la - lb) > 0 ? o._zeroes(b, lb, 1) : o._zeroes(a, -lb, 1));
        i = (la = a.length) == (lb = b.length) ? a.length : ((lb = la - lb) > 0 ? o._zeroes(b, lb) : o._zeroes(a, -lb)).length;
        for(r = 0; i; r = (a[--i] = a[i] + b[i] + r) / 10 >>> 0, a[i] %= 10);
        return r && ++n && a.unshift(r), o._f = n, o.round();
    };
    o.subtract = function(n){
        if(this._s != (n = new BigNumber(n))._s)
            return n._s ^= 1, this.add(n);
        var o = new BigNumber(this), c = o.abs().compare(n.abs()) + 1, a = c ? o : n, b = c ? n : o, la = a._f, lb = b._f, d = la, i, j;
        a = a._d, b = b._d, la != lb && ((lb = la - lb) > 0 ? o._zeroes(b, lb, 1) : o._zeroes(a, -lb, 1));
        for(i = (la = a.length) == (lb = b.length) ? a.length : ((lb = la - lb) > 0 ? o._zeroes(b, lb) : o._zeroes(a, -lb)).length; i;){
            if(a[--i] = (n = new BigNumber(n))._d.length, a = (r ? o : n)._d,
        b = (r ? n : o)._d, la = a.length, lb = b.length, x = new BigNumber, i, j, s;
        for(i = lb; i; r && s.unshift(r), x.set(x.add(new BigNumber(s.join("")))))
            for(s = (new Array(lb - --i)).join("0").split(""), r = 0, j = la; j; r += a[--j] * b[i], s.unshift(r % 10), r = (r / 10) >>> 0);
        return o._s = o._s != n._s, o._f = ((r = la + lb - o._f - n._f) >= (j = (o._d = x._d).length) ? this._zeroes(o._d, r - j + 1, 1).length : j) - r, o.round();
    };
    o.divide = function(n){
        if((n = new BigNumber(n)) == "0")
            throw new Error("Division by 0");
        else if(this == "0")
            return new BigNumber;
        var o = new BigNumber(this), a = o._d, b = n._d, la = a.length - o._f,
        lb = b.length - n._f, r = new BigNumber, i = 0, j, s, l, f = 1, c = 0, e = 0;
        r._s = o._s != n._s, r.precision = Math.max(o.precision, n.precision),
        r._f = +r._d.pop(), la != lb && o._zeroes(la > lb ? b : a, Math.abs(la - lb));
        n._f = b.length, b = n, b._s = false, b = b.round();
        for(n = new BigNumber; a[0] == "0"; a.shift());
        out:
        do{
            for(l = c = 0, n == "0" && (n._d = [], n._f = 0); i  1 || (e = l && n == "0" && a[i] == "0")))
                && (r._f == r._d.length && ++r._f, r._d.push(0));
                (a[i] == "0" && n == "0") || (n._d.push(a[i]), ++n._f);
                if(e)
                    break out;
                if((l && n.compare(b) == -1 && (r._f == r._d.length && ++r._f, 1)) || (l = 0))
                    while(r._d.push(0), n._d.push(0), ++n._f, n.compare(b) == -1);
            }
            if(f = 0, n.compare(b) == -1 && !(l = 0))
                while(l ? r._d.push(0) : l = 1, n._d.push(0), ++n._f, n.compare(b) == -1);
            for(s = new BigNumber, j = 0; n.compare(y = s.add(b)) + 1 && ++j; s.set(y));
            n.set(n.subtract(s)), !l && r._f == r._d.length && ++r._f, r._d.push(j);
        }
        while((i < a.length || n != "0") && (r._d.length - r._f) <= r.precision);
        return r.round();
    };
    o.mod = function(n){
        return this.subtract(this.divide(n).intPart().multiply(n));
    };
    o.pow = function(n){
        var o = new BigNumber(this), i;
        if((n = (new BigNumber(n)).intPart()) == 0) return o.set(1);
        for(i = Math.abs(n); --i; o.set(o.multiply(this)));
        return n < 0 ? o.set((new BigNumber(1)).divide(o)) : o;
    };
    o.set = function(n){
        return this.constructor(n), this;
    };
    o.compare = function(n){
        var a = this, la = this._f, b = new BigNumber(n), lb = b._f, r = [-1, 1], i, l;
        if(a._s != b._s)
            return a._s ? -1 : 1;
        if(la != lb)
            return r[(la > lb) ^ a._s];
        for(la = (a = a._d).length, lb = (b = b._d).length, i = -1, l = Math.min(la, lb); ++i < l;)
            if(a[i] != b[i])
                return r[(a[i] > b[i]) ^ a._s];
        return la != lb ? r[(la > lb) ^ a._s] : 0;
    };
    o.negate = function(){
        var n = new BigNumber(this); return n._s ^= 1, n;
    };
    o.abs = function(){
        var n = new BigNumber(this); return n._s = 0, n;
    };
    o.intPart = function(){
        return new BigNumber((this._s ? "-" : "") + (this._d.slice(0, this._f).join("") || "0"));
    };
    o.valueOf = o.toString = function(){
        var o = this;
        return (o._s ? "-" : "") + (o._d.slice(0, o._f).join("") || "0") + (o._f != o._d.length ? "." + o._d.slice(o._f).join("") : "");
    };
    o._zeroes = function(n, l, t){
        var s = ["push", "unshift"][t || 0];
        for(++l; --l;  n[s](0));
        return n;
    };
    o.round = function(){
        if("_rounding" in this) return this;
        var $ = BigNumber, r = this.roundType, b = this._d, d, p, n, x;
        for(this._rounding = true; this._f > 1 && !b[0]; --this._f, b.shift());
        for(d = this._f, p = this.precision + d, n = b[p]; b.length > d && !b[b.length -1]; b.pop());
        x = (this._s ? "-" : "") + (p - d ? "0." + this._zeroes([], p - d - 1).join("") : "") + 1;
        if(b.length > p){
            n && (r == $.DOWN ? false : r == $.UP ? true : r == $.CEIL ? !this._s
            : r == $.FLOOR ? this._s : r == $.HALF_UP ? n >= 5 : r == $.HALF_DOWN ? n > 5
            : r == $.HALF_EVEN ? n >= 5 && b[p - 1] & 1 : false) && this.add(x);
            b.splice(p, b.length - p);
        }
        return delete this._rounding, this;
    };
}

var continuar = true;
document.getElementById("calcular").onclick = function() {
    var precisao = parseInt(document.getElementById("precisao").value, 10);

    var pi = new BigNumber("3", precisao + 5);
    var antigo = new BigNumber("0", precisao + 5);

    var numerador = new BigNumber("6", precisao + 5);
    var denominador = new BigNumber("1", precisao + 5);
    var potencia2 = new BigNumber("2", precisao + 5);

    var indice = 1;
    function passo() {
      if ( pi.compare(antigo) == 0 || !continuar )
        return;

      antigo = pi;

      numerador = numerador.multiply(indice);
      denominador = denominador.multiply(indice+1);
      potencia2 = potencia2.multiply(4);

      var parcela = numerador.divide(denominador).divide(indice+2).divide(potencia2);
      pi = pi.add(parcela);

      indice += 2
      atualizar();

      setTimeout(passo, 0);
    }

    continuar = true;
    passo();

  function atualizar() {
    var str1 = "" + pi;
    var str2 = "" + antigo;
    var saida = "";
    var igual = true;
    for ( var i = 0 ; i < precisao ; i++ ) {
      if ( igual && str1[i] != str2[i] ) {
        igual = false;
        saida += ""
      }
      saida += str1[i];
    }
    document.getElementById("saida").innerHTML = saida;
  }
};

document.getElementById("parar").onclick = function() {
    continuar = false;
};
Precisão: <input id="precisao" type="number" value="70"/>
<button id="calcular">Calcular</button>
<button id="parar">Parar</button>

No exemplo de código acima, o precisao + 5 é para dar uma margem razoável para que a convergência aconteça (do contrário, as parcelas menores serão arredondadas pra zero e não entrarão na série). Coloquei 70 casas decimais, pois demora muito pra convergir no caso de 300 (se você tiver paciência de esperar, deve funcionar, entretanto).
Comment: Ótima resposta! Não tinha conhecimento dessa possibilidade, e o trecho de código calculando é perfeitamente auto-explicativo, incrível.
Answer: Certamente teria que criar um algoritmo próprio e não é algo tão simples.
Achei esse código. Como não há licença explícita não sei se posso trazer para cá.
Outro código que talvez possa ser usado como referência.
Se eu achar mais alguma coisa que possa melhorar a resposta eu postarei aqui.
Coloquei no GitHub para referência futura.
Answer: Pi One-liner
Abaixo alguns one-liner usando diversas linguagens... (quase todos roubados! de várias fontes)
bash+bc (bc=calculadora unix)(tang(π/4)=1 portanto 4 x arcotang(1)= 4 x π/4= π)
bc -l <<< "scale=1000; 4*a(1)"

internet-based...
curl --silent http://www.angio.net/pi/digits/pi1000000.txt | cut -c1-3000

perl
perl -Mbignum=bpi -le 'print bpi(100)'

python
python -c "from mpmath import mp;mp.dps=500;print mp.pi"

de certeza que algum include terá o PI com algumas casas...
grep -ohP '3.14\d{30,}' /usr/include/*.h

ou mesmo escolher o PI dos includes mais completo
grep -rohP '3\.14\d*' /usr/include | awk 'length > length(pi){pi=$0}  END{print pi}'
3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651

Se tiverem o LaTeX instalado... (convém ser a versão mais recente :)
tex --version | head -1 | cut -f2 -d' '

Comment: Já que foram "*quase todos roubados! de várias fontes*", por que não cita essas fontes?
Comment: @renan, agora é que tu me tramaste! Não sei... http://www.catonmat.net/blog/perl-one-liners-explained-part-three/; isto nasceu de uma discussão de café entre amigos -- É mais fácil a minha "não roubada" foi a dos includes (mas mesmo essa de certeza que já alguem se lembrou antes). Os monossílabos entre o código são meus...


Client side API google.script.run not working

Question: I am trying to get the div elements to be dynamically created and their values updated every second using the code:
setInterval(function() {
        google.script.run.withSuccesshandler(function(data) {
            var out = '';
            $(data).each(function() {
                out += "
" + $(this).val() + "
";
            });

            $('#item1').html(out);
        }).getReadyLine();
        }, 1000);

Ready Line, <?= getCountReadyLine() ?> items

Code.gs code:
 function getReadyLine() {
  var rawData = sheetMAT.getRange(3, 2, sheetMAT.getLastRow() - 2, 5).getValues();
  for (var i=0; i<rawData.length; i++) {
    if (rawData[i][3] === "A Ready Line" && rawData[i][4] === "ATY") {
      temp1 = ' ' + data[i][0];
      temp2.push(data[i][1], temp1);
      dataReadyLine.push(temp2);
      temp1 = '';
      temp2 = [];
    }
  }
  return dataReadyLine;
}

But it is giving the following error in the Console:
VM4084 userCodeAppPanel:67 Uncaught TypeError: google.script.run.withSuccesshandler is not a function
    at VM4084 userCodeAppPanel:67
(anonymous) @ VM4084 userCodeAppPanel:67
Why is it not recognized as a function? Is there any mistake in the code i am missing?
Comment: now I changed code only to run (but it's still not working): google.script.run.withSuccesshandler(function(data) {
            document.getElementById("#item1").innerHTML = data;
            }).getReadyLine();
Answer: The correct syntax is
google.script.run.withSuccessHandler()

Please note 'H' in Handler is capital
Comment: Thank you Jack. Indeed correct, i noticed it later on :-).


Reduzir tamanho de um Bitmap

Question: Como faço para reduzir o tamanho de um Bitmap.Por exemplo, pegar uma foto de 600kB e reduzir para 50KB.
obs:No java.
Comment: Favor poste o informações sobre a imagem, o tamanha máximo que você precisa, a resolução, ou seja seu post precisa de mais detalhes.
Answer: Para resolver problema de OutOfMemory, você deve fazer o seguinte:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap preview_bitmap = BitmapFactory.decodeStream(is, null, options);

Este inSampleSize reduz a utilização de memória.
Aqui vai o método completo. Primeiro ele lê o tamanho da imagem sem decodificar o conteúdo. Então ele acha o melhor valor para o inSampleSize, e finalmente a imagem é decodificada.
// Decodifica a imagem e escala para a redução do consumo de memória
private Bitmap decodeFile(File f) {
    try {
        // Decodifica o tamanho da imagem
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f), null, o);

        // O novo tamanho que queremos
        final int REQUIRED_SIZE=70;

        // Achar o valor correto para a escala
        int scale = 1;
        while(o.outWidth / scale / 2 >= REQUIRED_SIZE &&
              o.outHeight / scale / 2 >= REQUIRED_SIZE) {
            scale *= 2;
        }

        // Decodifica com o inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {}
    return null;
}

Reduzir tamanho de um Bitmap


Understanding kafka streams partition assignor

Question: I have two topics, one with 3 partitions and one with 48.
Initially i used the default assignor but i got some problems when a consumer(pod in kubernetes) crashed.
What happened was that when the pod came up again it reassigned the partition from the topic with 3 partitions and 0 from the topic with 48.
The two pods that did not crash got assigned 16 and 32 partitions from the topic with 48 partitions.
I've fixed this by using a round robin partition assignor but now i don't feel confident in how the partitions is distributed since i'm using kstream-kstream joins and for that we need to guarantee that the consumers are assigned to the same partition for all the consumer e.g. C1:(t1:p0, t2:p0) C2(t1:p1, t2:p1) etc..
One thing i thought of was that i could rekey the events coming in so they will repartition and then i might be able to guarantee this?
Or maybe i don't understand how the default partitioning work.. im confused
Comment: Actually, Kafka Streams does not allow to use a custom partition assignor. Probably your custom partition assignor is ignored. Additionally, according to the Kafka Streams [docs](https://kafka.apache.org/22/documentation/streams/developer-guide/dsl-api.html#join-co-partitioning-requirements),

**The input topics of the join (left side and right side) must have the same number of partitions.**
Comment: @kambo, Similar question https://stackoverflow.com/questions/55611088/partition-strategy-in-kafka-stream
Comment: It seems you can find an answer here:
https://stackoverflow.com/questions/18202986/kafka-partitioner-class-assign-message-to-partition-within-topic-using-key
Comment: Ok, so i thought of merging the streams instead and then do a stream.through(newTopic) Just to merge the streams of data to one topic with 3 partitions, then ill filter them to two streams and do the joins?

What do you think about this idea?

The other solution i was thinking of was to create a microservice that just forwards the messages to one topic and then filter them to two new kstreams and do the joins..

any better ideas?

And also the partition assignor, there is no way to change that when it comes to kstreams?
Comment: @dmvkl: The thread you linked to covers how to customize the partitioner on producer side and how the default partition assignor on consumer side works. However, here the question is about customizing the partition assignor.
Comment: @kambo: I answered to your original question. For help with your Kafka Streams application post to the Kafka user mailing list (https://kafka.apache.org/contact) or ask a new question here.
Answer: Kafka Streams does not allow to use a custom partition assignor. If you set one yourself, it will be overwritten with the StreamsPartitionAssignor [1]. This is needed to ensure that -- if possible -- partitions are re-assigned to the same consumers (a.k.a. stickiness) during rebalancing. Stickiness is important for Kafka Streams to be able to reuse states stores at consumer side as much as possible. If a partition is not reassigned to the same consumer, state stores used within this consumer need to be recreated from scratch after rebalancing.
[1] https://github.com/apache/kafka/blob/9bd0d6aa93b901be97adb53f290b262c7cf1f175/streams/src/main/java/org/apache/kafka/streams/StreamsConfig.java#L989
Comment: Thanks again. How will the application and kafka behave when changing keys inside the application. What i've seen so far is that there is some repartitioning going on. And it logs it heavily under load which i dont want. But does this mean bad news?
Comment: Records are repartitioned between a key changing operation and a key-based operation. For example, a `map` that outputs a new key followed by a `groupByKey`. See `groupByKey`  [javadocs](https://kafka.apache.org/22/javadoc/org/apache/kafka/streams/kstream/KStream.html#groupByKey--)


Proper ways to perform time series and ARIMA

Question: Note that I do most of my analysis using R and Excel.
Let's take this data set for example. I modified it as the data itself is proprietary: the years are also different:
1967    2,033,407
1968    2,162,275
1969    2,159,640
1970    2,312,352
1971    2,554,449
1972    2,548,425
1973    2,101,225
1974    1,951,944
1975    2,106,250
1976    1,687,625
1977    1,636,496
1978    1,494,525
1979    1,606,825
1980    1,460,937
1981    1,310,494
1982    1,319,750
1983    1,263,643
1984    1,171,656
1985    1,194,950

What I usually do:

A linear regression
Some form of polynomial trending
Moving average and double moving average
Basic ARIMA using p = 1, q = 0.
I calculate the errors for all these as well
I average all the forecasts out and the error to have my final result.

Note that I'm an engineer that wants to get into statistics and the ability to properly validate and calibrate my models.
Question
What is the correct way to forecast this to 5, 10, or even 15 future years?
In a way I'm looking to move beyond the plugging data into a model and believe the data. Yes, I'm aware I can look at the errors. I mainly use RMSE or MAE. But I still am not confident when it comes to just predicting data the right way.
Note
this is also related to this question I posted here before.
Answer: The answer here is the same as the previous one: cross-validate!  Don't forget exponential smoothing models as well.
In general, the ets and auto.arima functions in the forecast package are pretty good across a wide range of data.  The theta method did well in the M3 competition.
It might be a good idea to read some of the papers associated with the M3 competition, which will help you conceptualize how good forecasting models are evaluated.
Comment: @dassouki: No problem!
Answer: Your data suggests a model of the form
[(1-B**1)]Y(T) = + [X1(T)][(1-B**1)][(-  .17233E+06)]   :PULSE               7
                 + [X2(T)][(1-B**1)][(+  .32470E+06)]   :PULSE               9
                 + [(1-  .488B** 1)]**-1  [A(T)]

ARIMA (1,1,0) with 2 anomalous data points at 7 and 9
yielding an rsq of
R Square  =  .916201


What's the difference between "questionable" vs "doubtful" injury designations in the NFL?

Question: In the NFL, what is the difference between each of the designations for questionable vs doubtful? Which one is more severe?
Answer: In the NFL, there are injury designations. The injury designations indicate what percentage or chance that they'll play for that given day.
The NFL specifically has one that outlines them based on percentages:

Inactive (IA) - Players are officially inactive for the current game and will not play
  Out (O) – Not scheduled to play
  Doubtful (D) – Players have approximately a 25% chance of playing
  Questionable (Q) – Players have approximately a 50% chance of playing
  Probable (P) – Players are very likely to start in the upcoming week

The injury designations are exactly that; based on percentages. Additionally, from  my experience they can change as the NFL week progresses: for better and worse.
Moreover, the Wall Street Journal has provided some insight regarding these injury designations as well:

"Probable" means definite. "Questionable" is closer to probable. And
  "doubtful?" If a player is listed as doubtful, like the Colts' Peyton
  Manning is this week, then there's virtually no doubt whatsoever that
  he's going to sit out.

In the NFL, teams are required to report injury statuses on a daily basis. Apparently, they shouldn't be taken literally:

It's long been known that injury reports aren't to be taken totally
  literally. The official NFL definitions are that "out" means a player
  definitely won't play that week; doubtful means at least 75% chance
  the player sits; questionable means 50-50 and probable means it's a
  virtual certainty he'll play. Indeed, the Patriots famously have
  listed quarterback Tom Brady as "probable" for years, even though he
  made 111 straight starts at one point.


Best Practice for view data population?

Question: I've been working on a .NET application and experiencing a memory error (I'm a java developer that can do other things), I've been thinking about performance. What I'm posting about was not the memory problem. The memory problem just started me thinking.
I've repeated a trend in my ASP.NET application that I've used on countless J2EE applications: using Business Entities to populate drop down lists. The more I think about it, the more I don't like it. For example, on the app I'm working we have a drop down list of current projects. A project is a graph of objects. However, to create the list we pull back all of the projects, create the graph and only use the id and display name. This seems to be a terrible waste. To be fair, the dal layer is entirely hand written. The lead architect would not allow an ORM like NHibernate.
I realize that all of these objects are in GEN0 and quickly garbage collected. What worries me is that I'm taxing the GC. Ever 5% of the CPU needed to process the GC is 5% of CPU I can't use else where. This site is one of the few that I really respect. What do you all think? Is it bad to use the entity model for this? Should I create a set of IdValue objects that only house the display value and id? Would creating such a view object tier (I don't suppose this will go in the business layer) just create redundant code?
Thanks,
JPD
Answer: Don't worry about taxing the GC, it will tune itself to your application to give you optimal performance.  Yes it is best to reduce your memory footprint but I don't think it is quite as serious a problem as you imagine.
A good DAL that allows you to return only the data that you need will increase the performance of your application and will also decrease the amount of memory required by your application.  But whether you use "too much" memory or not, I imagine that in most cases the GC will be able to handle it just fine.
Answer: I've been working on line of business .NET apps for the last few years and have yet to run into a performance problem that was resolved by trying to help the garbage collector work more efficiently.
Gathering metrics on the otherhand has been incredibly helpful for to improve performance, memory usage, etc.
Answer: An alternative approach is to create light-weight objects for your purposes.  In this instance you would have a lighweight project object with only the id and display name.  The decision then needs to be made over re-using the existing DAL or creating a lightweight version of the DAL.

Best Practice for view data population?


Anko doAsync Call Not Executing

Question: I'm creating a project in Android Studio and at am using the Anko library to run an API request on a seperate thread. Said thread is simply making an HTTP GET call and parsing the data while the UI thread passes said data and starts the next activity.
The problem is, my program never seems to enter the doAsync block. I've posted my code below for the function I wrote for the call, it's called on a button click and when said button is clicked nothing happens. It doesn't stall, doesn't crash, nothing. Other parts of the activity will even respond.
Solutions I've tried:

Debugging to step into the block, simply skipped over it
Removing the try/catch
Doing the call and parsing on the main thread (throws an exception)
Putting the call in a separate function as it is now (originally was in the button listener)

I can't find anything really about this online so any help is welcome, thanks in advance.
MainActivity.kt
    private
    fun asyncCall(n : Int) {
        doAsync {
            try {
                // Call API, store Place objects in placesList
                toast("streamJSON call")
                placesList = streamJSON()
            } catch (e: java.lang.RuntimeException) {
                // Error parsing JSON
                toast("Invalid Request")
            }

            uiThread {
                if(n == 1) { // Submit button
                    goToResults()
                }
                else if (n == 2) { // Feeling lucky button
                    feelingLuckyAlert()
                }
            }
        }
    }

Comment: Have you tried `CountDownLatch` with `await` and also where are you calling `asyncCall` function ?
Comment: I haven't, I didn't think I needed to as I felt this was fairly simple. And I'm calling it from the on click listeners for two buttons which are in the onCreate() method. I thought this might be the issue but I don't think I can take said listeners out of onCreate().
Comment: Oh I guess the problem is with your `toast` that needs to be inside the `uiThread` have you tried debugging it inside the `doAsync`?
Comment: I added those to debug it so it should work without them, wouldn't that throw some kind of exception or something? I have tried debugging it, simply skips over the block.
Answer: The code is jumping into the catch block because you can't toast on a thread that has not called Looper.prepare(). The solution would be call the toast in the uiThread
private fun asyncCall(n : Int) {
    doAsync {
        try {
            uiThread {
                toast("streamJSON call")
            }

            // Call API, store Place objects in placesList
            placesList = streamJSON()
        } catch (e: java.lang.RuntimeException) {
            uiThread {
                toast("Invalid Request")
            }
        }

        uiThread {
            if(n == 1) { // Submit button
                goToResults()
            } else if (n == 2) { // Feeling lucky button
                feelingLuckyAlert()
            }
        }
    }
}

Comment: Tried that and it worked, is there a way I can make it so if it throws an error it just breaks out of the doAsync block and displays the error?
Comment: I think you can do `return@doAsync` to return from the doAsync block on error
Comment: Or you could also `throw` the exception from inside and put the `doAsync` block inside a try catch block to catch the exception

Anko doAsync Call Not Executing


How to authenticate with express-oauth-server?

Question: I want to implement an oAuth2 Server using nodejs for my app, and I'm using tutorial found on https://niceprogrammer.com/express-js-oauth-2-server-using-oauth2-server-package/
However, when I go to https://localhost:3000/oauth/authenticate (login route) and try to login, i get a json response: {"error":"invalid_request","error_description":"Missing parameter: `client_id`"}
The function responsible for authenticating is as follows:
router.post('/oauth/authenticate', async (req, res, next) => {

    let UserModel = mongoose.model('User');
    req.body.user = await UserModel.findOne({ username: req.body.username });

    return next();
}, oauth.authorize({
    authenticateHandler: {
        handle: req => {
            return req.body.user;
        }
    }
}));

Is there an issue with the tutorial or am I doing something wrong?
Answer: I have solved it, I was missing the ?client_id=xxx in the url.


Formulário não submete por causa de comando $("#div").attr("disabled",true); do jquery. O que fazer para resolver?

Question: $("#button").click(function(){
    $("#button").attr("disabled",true);
    $("#button").animate({opacity:0.2});

    var nome    = $("#nome").val();
    var telefone    = $("#tel").val();
    var email   = $("#email").val();
    var onde    = $("#onde").val();
    ......
)};

No IE e Firefox funciona de boa, quando clico no botão ele envia os dados via jquery para uma página e tem que desabilitar o botão, mas não envia os dados quando é pelo google chrome.
Answer: Coloque um setTimeout de 1 milissegundo na ação de bloquear o botão:
$('button').on('click',function(){
    var btn = $(this);
    setTimeout(function(){
        btn.attr('disabled',true);
    },1);
   //...
});

Desta forma ele não interrompe o envio do form mas ainda assim se bloqueia rapido o bastante para evitar mais cliques do usuário.
Exemplo
Answer: Porque não usa o evento de onsubmit do form para realizar o bloqueio?
$("#form").submit(...);
// Ou
$("#form").on('submit', (function(){
    $("#button").attr("disabled",true);
    $("#button").animate({opacity:0.2});

    var nome    = $("#nome").val();
    var telefone    = $("#tel").val();
    var email   = $("#email").val();
    var onde    = $("#onde").val();
    ......
)};

Acredito que esse comportamento esteja correto, mas não é coerente para todos os browsers...
É certo que se desabilitar o button que submete o form ele não irá submeter.
Acredito que usar o evento de onsubmit é mais certo porque ocorre durante o submit e não corre o risco de bloquear o submit.
De uma olhada na documentação jQuery para o evento de submit.


Counting the number of elements in vector x which equal any vector element in vector y

Question: I need to count the number of elements in vector x which equal any vector element in vector y.
From here I can count the number of elements in vector x which equal to value in scalar `y with code:
x <- c(4,23,4,23,5,43,54,56,657,67,67,435,
             453,435,324,34,456,56,567,65,34,435, 675)

sum(x == 67)

Question:  How to count the number of elements in vector x which equal any vector element in vector y?
Comment: @Rushabh Patel why you deleted updated answer? It was working correctly.
Answer: Try length-which-in:
length(which(x %in% y))

Answer: You can use:
For All matches use this:
length(na.omit(match(x,y)))

For unique Matches use this:
length(intersect(x,y))

Comment: This code gives the sum of "if element from `y` was matched at least one time in x" and here "several occurrences of `y` in `x` is counted as `1`".
Comment: @SmokeyShakers I changed my answer.


Group isomorphism applied to sum of characters

Question: Let $G$ be a finite abelian group and let $\widehat{G}$ be the group of group homomorphisms $\chi:G\to\mathbb{C}^*$ (i.e. the dual group of $G$, or the group of characters on $G$). Then there is an isomorphism $\varphi:G\to \widehat{G}$.
We have the following proposition:
Given a fixed $\chi\in\widehat{G}$, we have
$$\sum_{g\in G} \chi(g) = \begin{cases}|G| & \chi = 1_{\widehat{G}},\\0 & \text{otherwise.}\end{cases}$$
and given a fixed $g\in G$, we have
$$\sum_{\chi\in \widehat{G}} \chi(g) = \begin{cases}|\widehat{G}| & g = 1_G,\\0 & \text{otherwise.}\end{cases}$$

I can prove both statements separately but all texts I have found about it state that due to the fact that $G$ and $\widehat{G}$ are isomorphic, then it is enough to prove just one of them and the other one is a consequence of the first. My question is: how is the isomorphism applied here?
Comment: I think you need to understand the natural isomorphism between $\widehat{\widehat{G}}$ and $G$ to see the equivalence of these two statements.
Comment: The isomorphism is defined by $g \leftrightarrow \hat{\hat{g}}$, where $\hat{\hat{g}}(\chi) = \chi(g)$.
Comment: @DerekHolt care to elaborate? Isn't that isomorphism implied by that of $G$ and $\widehat{G}$ or is the fact that it's natural (not sure what that means) significant here?
Answer: To make your second set of equations look the first set, each $g \in G$ defines a character ${\rm ev}_g \colon \widehat{G} \to \mathbf C^\times$ as "evaluate at $g$":
$$
{\rm ev}_g(\chi) = \chi(g)
$$
for all $\chi$ in $\widehat{G}$.
That each ${\rm ev}_g$ is a group homomorphism is due to the definition of multiplication in $\widehat{G}$ as pointwise products:
$$
{\rm ev}_g(\chi\psi) = (\chi\psi)(g) = \chi(g)\psi(g) = {\rm ev}_g(\chi){\rm ev}_g(\psi).
$$
Thus ${\rm ev}_g$ is a character on $\widehat{G}$.
If $g = 1$, then ${\rm ev}_1$ is the trivial character on $\widehat{G}$.
Using the cyclic decomposition for finite abelian groups (or other methods), one can show for $g \not= 1$ in $G$ that there is $\chi \in \widehat{G}$ such that $\chi(g) \not= 1$. Writing that as ${\rm ev}_g(\chi) \not= 1$, we see that if $g \not= 1$ in $G$, then ${\rm ev}_g$ is a nontrivial character on $\widehat{G}$.
For each $g \in G$, let's evaluate
$$
\sum_{\chi \in \widehat{G}} \chi(g).
$$
If $g = 1$ then each term in the sum is $1$, so the sum is $|\widehat{G}|$.  We want to show if $g \not= 1$ that the sum is $0$.  Rewrite the above sum as
$$
\sum_{\chi \in \widehat{G}} {\rm ev}_g(\chi),
$$
which is the sum of a character ${\rm ev}_g$ over the elements of a finite abelian group $\widehat{G}$. If $g \not= 1$ then ${\rm ev}_g$ is a nontrivial character on $\widehat{G}$, so the above sum is $0$ by the general result that the sum of a nontrivial character over the elements of a finite abelian group is $0$.  That is, in the equation
$$
\sum_{x \in A} \chi(x) = 0 \ {\rm if } \ \chi \not= {\mathbf 1}_A,
$$
let $A = \widehat{G}$ and let the character on $A$ be ${\rm ev}_g$ for $g \in G$ with $g \not= 1$.
In this way, your second character sum formula can be regarded as a special case of your first character sum formula by using $\widehat{G}$ in place of $G$.
Here I am not explicitly relying on an isomorphism between $G$ and $\widehat{G}$, but there is a natural isomorphism $G \to \widehat{\widehat{G}}$ given by the mapping $g \mapsto {\rm ev}_g$, and this isomorphism is related to the argument above.


How to rigourously show the following function is onto ???

Question: The  Problem  is : Let  $C^{\infty}(0,1)$ denote the vector space of all smooth functions on $(0,1)$,  and let $\phi : C^{\infty}(0,1) \to C^{\infty}(0,1)$ be a linear map such that,
$\phi(f)= (f + f')$,  then verify ontoness of $\phi$ .
Obviously, here $\phi$ is not one-one as for any $f$, $f$ and $(f+ \exp^{-x})$ maps into same thing . But, I am not sure how to use linearity of the map $\phi$ for verifying ontoness, as the vector space is infinite dimensional.
For the functions $f$ in the vector space which are integrable on $(0,1)$, if $F(x)=\int_0^1 f$, then $(F+f)'$= $\phi(f)$, but $g(x)=1/x$ is not integrable on $(0,1)$ , then what's the pre-image of $g$ under $\phi$ ???
Answer: Let $g$ be any smooth function. Let $c \in (0,1)$. Consider the equation $f'+f=g$. We can write this as $e^{x}f'(x)+f(x)e^{x}=g(x)e^{x}$ or $(e^{x}f(x))'=g(x)e^{x}$. This gives $e^{x}f(x)=e^{c}f(c)+\int_c^{x} e^{t}g(t)dt + C$. Hence $f(x)=e^{-x}(e^{c}f(c)+\int_c^{x} e^{t}g(t)dt+C) $. We can take $C=0$
 and verify that this $f$ indeed satisfies the equation $f'+f=g$. Also this function is smooth and its image under the given map is $g$.


post complex viewmodels using ajax.beginForm MVC4 only getting null

Question: im very new to mvc, lest say i have a viewmodel that cotains objects like
public class vm_set_rol
{
    public IEnumerable<SelectListItem> roles { get; set; }
    public Rol_User rol { get; set; }

}

rol is an object like:
public class Rol_User
{
    public int idUser { get; set; }
    public int Role { get; set; }
    public int GrantedBy { get; set; }
    public bool canGrant { get; set; }
    public DateTime ExpirationDate { get; set; }
}

so i have a form on a view to let the user select 1 role from a roles dropdown and select a date and a checkbox somthing like:

        @using (Ajax.BeginForm(new AjaxOptions
                                        {
                                            UpdateTargetId = "gestionRolContainer",
                                            Url = "Permiso/Test",
                                            InsertionMode = InsertionMode.Replace,
                                            HttpMethod = "POST",

                                        }
                                )
                )
        {
            <fieldset>
                    <legend>@Res_String.RolLabel</legend>

                    ROL:
@Html.DropDownListFor(m => m.rol, Model.roles, new {@id="AdmPermUserRolesDropDown" })

                    @Html.CheckBoxFor(m => m.rol.conceder ,Model.rol.conceder) Delegate?

                    <input type="submit" class="buttonClass" value="OK" />
            </fieldset>

        }

the problem is that i only get null values, if i create some other property on the model like a string or int, those are posted back ok,
i kind of understad why objects are not posted back, bust is there any workaround??? or put a object on the modes is just wrong and i shuld declare the propertis on the viewmodel instead of an object???
Answer: Your dropdown is incorrectly bound. It should be bound to a scalar property to hold the selected value:
@Html.DropDownListFor(
    m => m.rol.Role,
    Model.roles,
    new { id = "AdmPermUserRolesDropDown" }
)

As far as the Roles collection property is concerned, it will always be null in your controller action because this list is never sent to the server when you submit a form. Only the selected value is sent. So if you need to redisplay this view once again you will have to populate the Roles collection property in your HttpPost action the same way you did in your GET action.
Also your checkbox is bound to some m => m.rol.conceder property which doesn't exist in the view model you have shown. I guess you meant using the canGrant boolean property. Also you don't need to provide as second parameter to the CheckBoxFor helper the value. It will be inferred from the lambda expression:
@Html.CheckBoxFor(m => m.rol.canGrant) Delegate?

Last but not least, since you are using an Ajax.BeginForm make sure that you have referenced the jquery.unobtrusive-ajax.js script in your view.
Comment: tks 4 the answer, all the code above is a translated example, canGrant is conceder on my aplication, just mis to translate it, but u are ok on the dropDown, tks


Counting the amount of times a number appears in a 2D array C

Question: I am trying to count the amount of times a number appears in a 2D array, but when I try and print values it starts giving me wrong numbers after the first element. I am trying to figure this out for a sudoku project I have, but I am posting different source code so I can figure out why this is happening.
#include <stdio.h>

int main() {
    int i, j, k;
    char check[10];
    char puzzle[6][10] = {
        { 1, 1, 3, 4, 4, 4, 5, 9, 2, 7 },
        { 9, 9, 8, 8, 8, 8, 8, 6, 9, 5 },
        { 1, 1, 3, 4, 4, 4, 5, 9, 2, 7 },
        { 9, 9, 8, 8, 8, 8, 8, 6, 9, 5 },
        { 1, 1, 3, 4, 4, 4, 5, 9, 2, 7 },
        { 9, 9, 8, 8, 8, 8, 8, 6, 9, 5 }
    };

    for (i = 0; i < 6; i++) {
        for (j = 0; j < 10; j++) {
            check[puzzle[i][j]]++;
        }
    }
    for (k = 1; k < 10; k++) {
        printf("check[%d] = %d\n", k, check[k]);
    }
    return 0;
}

OUTPUT:
check[1] = 6
check[2] = -101
check[3] = -6
check[4] = -56
check[5] = 101
check[6] = 2
check[7] = -126
check[8] = 15
check[9] = 12
Program ended with exit code: 0

Comment: properly initialize your array: `char check[10] = {0};`
Comment: `char check[10];` lacks zero initialization.  Perhaps other issues too.
Answer:
I am trying to count the amount of times a number appears in a 2D
  array, but when I try and print values it starts giving me wrong
  numbers after the first element.

The values in the array check that you are incrementing are non-zero because the array is never initialized.
This line:
char check[10];

Needs to be this:
char check[10] = {0};


Upon submitting a webform, set a date field on the article node equals to "current time" + "X minutes"

Question: I am using the Field Timer module to display countdown timer on my article node.
This module will take the value of the date/time field (my case: field_article_datetime) and convert it into a countdown timer in the display of the article.
I have a webform (machine name: ABC) attached as a field to the article content type so I can use [webform_submission:node:nid] to retrieve the article nid of the article to be updated.
The webform (machine name: ABC) has below element:
1) Select element (machine name: increase_time_in_minutes):

Text: Increase by 15 minutes (Value: 15)
Text: Increase by 30 minutes (Value: 30)
Text: Increase by 45 minutes (Value: 45)

And the article content type has below field:

date/time field (machine name: field_article_datetime) (the Field Timer module is applied to this field)

When the webform "ABC" is submitted, I want to:

Fetch the article nid ([webform_submission:node:nid])
Set the value of the date/time field (field_article_datetime) equal to current time + increase_time_in_minutes

EXAMPLE:
Say at 14/03/2019 08:30:15 PM, a user has submitted the webform "ABC" and selected Increase by 15 minutes option from the select list... So I need the related article to be fetched and update the (field_article_datetime) to have the value of 14/03/2019 08:45:15 PM
This way, the user will see a countdown timer for 15 minutes on the article node display page.

I am not a programmer, but I think the best Idea is to use a customwebformhandler.php file which will be enabled for the webform settings page.
I have created the file but I need help to finish it:
<?php

namespace Drupal\my_module_extras\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;

use Drupal\node\Entity\Node;

use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;

/**
 * Update a node entity from a webform submission.
 *
 * @WebformHandler(
 *   id = "Update a node",
 *   label = @Translation("Update a node"),
 *   category = @Translation("Entity Update"),
 *   description = @Translation("Updates a node from Webform Submissions."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class SetTimerOnNodeWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */

  // Function to be fired while submitting the Webform.
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    // Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // Fetch & Update node object from webform-submission.
    //get current node or use any other way to get the current node
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
    $current_time = \Drupal::time()->getCurrentTime();
    date_default_timezone_set('GMT');

    //get value from webform
    $increase = $values["increase_time_in_minutes"];

    //calculate new time
    $timer = date('Y-m-d\TH:i:s', $current_time + $increase * 60);

    //add it to article field and save
    $node->field_article_datetime->value = $timer;
    $node->save();
  }
}

}
Update #2:
The below error is generated because of one missing } at the end of the file. (Stupid mistake)
Update #1:
Error logged in in the dblog after trying to add the webformhandler.php file to the webform:
ParseError: syntax error, unexpected end of file, expecting function (T_FUNCTION) or const (T_CONST) in Composer\Autoload\includeFile() (line 59 of S:\######\dev.####\web\modules\custom\my_module_extras\src\Plugin\WebformHandler\SetTimerOnNodeWebformHandler.php) #0 S:\######\dev.#####\vendor\composer\ClassLoader.php(322): Composer\Autoload\includeFile('S:\\###### ...') #1 [internal function]: Composer\Autoload\ClassLoader->loadClass('Drupal\\my_module...') #2 [internal function]: spl_autoload_call('Drupal\\my_module...') #3 S:\#######\dev.#####\web\core\lib\Drupal\Component\Plugin\Factory\DefaultFactory.php(96): class_exists('Drupal\\my_module...') #4 S:\#######\dev.#####\web\core\lib\Drupal\Core\Plugin\Factory\ContainerFactory.php(17): Drupal\Component\Plugin\Factory\DefaultFactory::getPluginClass('Update a node', Array, 'Drupal\\webform\\...')

Comment: Please elaborate on `attached as a field to the article content type`.  How is this done ?  Do you mean include as a block under article content type ?
Comment: I have added a new field of type webform and select the webform ABC from the select droodown list list of all available webforms.
Comment: you are right, I had never noticed that you could include webform as a field.  The solution I posted should work for this case as well.
Answer: Use this as your submitForm
$values = $webform_submission->getData();

//get current node or use any other way to get the current node
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
  $current_time = \Drupal::time()->getCurrentTime();
  date_default_timezone_set('GMT');

  //get value from webform
  $increase = $values["increase_time_in_minutes"];

  //calculate new time
  $timer = date('Y-m-d\TH:i:s', $current_time + $increase * 60);

  //add it to article field and save
  $node->field_article_datetime->value = $timer;
  $node->save();
}

The answer asumes that you have included the webform as a block for article content types.  Another possibility is to include the webform as field and it should work exactly the same.
NOTE: before the webform handler works you have to enable your custom module and than go to your webform settings > email/handlers and include your handler
Comment: You are missing a closing brace `}` of the class and also make sure that your file is placed in `MODULENAME/src/Plugin/WebformHandler/SetTimerOnNodeWebformHandler.php`
Comment: The drupal community is the best because of people just like you who are willing to help at any time. Thank you @GiorgosK you rock!
Comment: I have updated the webformhandler.php file with the code in your answer and successfully enabled the module... However, I cannot add the handler to the webform with an error logged in dblog... See the **Update #1** of my question please
Comment: For other users who need a complete solution for similar issue, just copy the entire code available in my question above and paste it in your webformhandler.php file


MySQL package upgrades (Debian apt-get) always break master-master replication due to changes in mysql schema

Question: I have master-master replication set up on 2 Debian servers, and they replicate everything, including the mysql database itself (so that new users and such also replicate).  This generally works very well, except that most, if not all, apt upgrades to mysql involve some changes to the mysql database schema, which cause replication errors that halt replication.  Ultimately, I always need to manually fix by skipping the errant statements on each side.  This is always time-consuming, and I worry I could make mistakes doing it manually (skipping too many statements, mistyping CHANGE MASTER details, etc.).
Is there something I can do to make sure that apt-get updates to MySQL in the future will get processed smoothly without causing replication problems?  Surely there's a well-established best practice for this?
Comment: You might want to try using `replicate_ignore_table` to not replicate all tables in the `mysql` database. I personally don't replicate that database, and apply user etc. updates on each node separately.
Comment: Does this help ? https://dev.mysql.com/doc/refman/5.6/en/replication-upgrade.html
Comment: On an ongoing operating basis I wouldn't want to turn it off, as it's very helpful to be syncing users, permissions, etc. without having to apply to each node.  But if there was a script I could run before and after updating to toggle this on/off, I suppose that would be fine.  My understanding is that newer versions of mysql allow you to toggle replication filters dynamically using sql statements, but my version (5.5) apparently doesn't (?), so such a script would need to restart mysql with varying parameters... if the downtime is quick, it would be acceptable.  Suggestions for how to do it?
Answer: it would be nice to know what commands broke your replication, but I suppose, the mysql_upgrade script would be that rogue.
If yes, you can rebuild the mysql package, adding to the post install script a --skip-write-binlog (this is not needed after 5.6.7)
But normally I never would just apt-get upgrade a server which is in production, stop the slave, upgrade it and reconnect them.
This is the zen way.
Comment: Reasonable advice, but do you have a tested, step-by step method or script? (whether it uses apt-get or not)  One thing I was thinking was have a temporary file I could put in conf.d that had skip-write-binlog along with other settings that would stop my applications from connecting to mysql but allow upgrades to happen (is this possible using cnf settings?).  That way I could restart knowing that no apps could change data, perform my upgrade (apt-get or otherwise), then remove the temp cnf file and restart clean.
Comment: I looked at the source for the mysql-server deb package, and the postinst/fix_privs routine has a number of `ALTER TABLE user` commands... that's probably what's broken replication in the past.  So maybe the easiest path is temporarily `binlog-ignore-db=mysql`, upgrade as usual, and then remove the ignore-db?  Requires one additional restart, but seems simple enough.
Answer: I don't know if it will work for every possible upgrade scenario, but I just tested this, and the upgrade worked without any replication problems:
# /etc/mysql/conf.d/binlog_ignoredb_mysql.cnf.disabled
# Rename this to end in .cnf prior to performing `apt-get upgrade`.
# Otherwise, its attempts to `ALTER TABLE users` will cause replication errors.
# After upgrade is complete, rename back to .disabled and then /etc/init.d/mysql restart

[mysqld]
binlog-ignore-db=mysql

Note that my test was on a minor upgrade (5.5.41 to 5.5.43).
Answer: While investigating whether mysql_upgrade causing issues in replicated setups was still a thing (because it has bitten me and my team before, but at the same time binlog-ignore-db=mysql also has issues) I ran into this page and I was excited to read the answer by banyek which states that this is a solved problem!
However I wanted a more explicit reference to confirm that the problem is solved (and also I was curious how it was solved) so I looked through the MySQL 5.6.7 change logs and here it is:

Replication: mysql_upgrade failed when the server was running with gtid_mode=ON and --disable-gtid-unsafe-statements because the MySQL system tables are stored using MyISAM. This problem is fixed by changing the default logging behavior for mysql_upgrade; logging is now disabled by default. (Actions taken by mysql_upgrade depend on the server version, and thus should not be replicated to slaves.) To enable logging, you can execute mysql_upgrade using the --write-binlog option.

Update:
In response to the comment by @dlo, the help text of the mysql_upgrade command can be inspected to confirm whether a given server has received the update mentioned above:
$ mysql_upgrade --help | grep -A2 write-binlog
  --write-binlog      All commands including mysqlcheck are binlogged. Disabled
                      by default; use when commands should be sent to
                      replication slaves.

If the Disabled by default text is there you should be good .
Comment: I'm not able to confirm this right away in a working setup, but it's a very logical behavior change, so I hope it's true.


Verify that the given sequence is uniformly convergent

Question: Problem
Verify that the sequence {$f_n$} , where $f_n= n \sin( 4 \pi^2 n^2+x^2)^ {0.5}$ , converges uniformly on$ [0,a] , a \geq 0 $. Does {$f_n$} converge uniformly on  $\mathbb{R} $?
Attempt
I have figured out that the the given function converges pointwise to $f(x) = x^2/4\pi$. After that i don't know how to proceed. My approach is to find $d_n$=sup {$ f_n(x) - f(x)| x \in [0,a] $}. Then show that $d_n$ approaches zero as n tends to infinity. But i am not able to find $d_n$
Edit:  $\sin( 4 \pi^2 n^2 +x^2)^ {0.5} $= $\sin ( 2n\pi( 1+ \frac{x^2}{4 \pi^2 n^2})^{0.5} + 2n\pi- 2n \pi)$=
$ \sin ( 2n\pi( 1+ \frac{x^2}{4 \pi^2 n^2})^{0.5} -1)$=
$ \sin (\frac{ x^2} { (4n^2 \pi^2+x^2 )^{0.5}+ 2n\pi})$
Now it is easy to see how pointwise limit should be $\frac{x^2}{4\pi}$
Comment: While I agree with your assessment of the potential approach, it's hard to know how to describe that approach without seeing how you proved that the pointwise limit is $x^2/4\pi$. It's likely that a slightly more careful version of that proof will succeed in establishing the uniform convergence on $[0,a]$.
Comment: Edited to question  . Thanks .
Comment: Your edit seems wrong, where did that $ -1$ come from?
Answer: As you realized, the term $(4\pi^2n^2+x^2)^{0.5}$ will, for fixed $x$ and increasing $n$, get very near to $2\pi n$, so the sin function will apply to a small value $(4\pi^2n^2+x^2)^{0.5}-2\pi n$ that can be easily approximated by the Taylor series for the sin-function.
The problem is therefore to put this into quantifiable inequalites that can finally be used to prove the uniform convergence.
First for small $\epsilon > 0$ (say $\epsilon < 1$) we have
$$1+\frac{\epsilon}2-\epsilon^2 < \sqrt{1+\epsilon} < 1+\frac{\epsilon}2,$$
which can proved by squaring both sides of each inequality. The right inequality is always true, the left side, when squared is $1+\epsilon$ + terms of $\epsilon$ of order $2$ or greater and the coefficient of $\epsilon^2$ is negative.
That means, because
$$(4\pi^2n^2+x^2)^{0.5}=2\pi n\sqrt{1+\frac{x^2}{4\pi^2 n^2}},$$
and if we set $x_n:=\frac{x^2}{4\pi^2 n^2}$, we get for $x_n < 1$
$$2\pi n(1+\frac{x_n}2-{x_n}^2) < (4\pi^2n^2+x^2)^{0.5} < 2\pi n(1+\frac{x_n}2).$$
If we assume the even stricter inequality $2nx_n < 1$, we get
$$2\pi n < 2\pi n(1+\frac{x_n}2-{x_n}^2) < (4\pi^2n^2+x^2)^{0.5} < 2\pi n(1+\frac{x_n}2) < 2\pi n +\pi\frac12.$$
Since the sin-function is increasing in the interval $[2\pi n,2\pi n+\frac12\pi]$, and $2\pi$-periodic, we get
$$\sin (2\pi n(\frac{x_n}2-{x_n}^2)) < \sin ((4\pi^2n^2+x^2)^{0.5}) < \sin (2\pi n\frac{x_n}2),$$
under the assumption $2nx_n < 1$, which is equivalent to $x^2 < 2\pi^2 n$.
Putting in the definition of $x_n$, we get
$$\sin (\frac{x^2}{4\pi n}-2\pi n{x_n}^2) < \sin ((4\pi^2n^2+x^2)^{0.5}) < \sin (\frac{x^2}{4\pi n}).$$

Let's for a moment stop here and wonder if the assumptions I made are reasonable.
The most strict assumption I made is $2nx_n < 1$, which is equivalent to $x^2 < 2\pi^2 n$. In case where we consider the interval $[0,a]$ for $x$, this is fullfilled if $n > \frac{a^2}{2\pi^2}$. Since uniform convergence requires bounds for some $n>M$, increasing $n$ is not a problem. That means that we can make the term $x_n$ as small as later required, and this is uniformly over the interval [0,a].

Going back to the inequality above, we use  $\sin(x) < x$ on the right side and $x-\frac{x^3}6 < \sin(x)$ on the left hand side to get
$$(\frac{x^2}{4\pi n}-2\pi n{x_n}^2) - \frac{(\frac{x^2}{4\pi n}-2\pi n{x_n}^2)^3}6 < \sin ((4\pi^2n^2+x^2)^{0.5}) < \frac{x^2}{4\pi n}.$$
Multiplying that with $n$ leads to the final inequality:
$$(\frac{x^2}{4\pi}-2\pi n^2{x_n}^2) - \frac{n(\frac{x^2}{4\pi n}-2\pi n{x_n}^2)^3}6 < n\sin ((4\pi^2n^2+x^2)^{0.5}) < \frac{x^2}{4\pi}.$$
Notice term on both sides without $n$ is the $\frac{x^2}{4\pi}$. The remaining terms (on the left side) are of much smaller order. Recall that $x_n=\frac{x^2}{4\pi^2 n^2}$, that means
$$2\pi n^2{x_n}^2 = 2\pi n^2\frac{x^4}{16\pi^4 n^4}= \frac{x^4}{8\pi^3 n^2},$$
which means the term becomes uniformly small when $\frac{a^4}{8\pi^3 n^2}$ is made small by a big $n$. The remaining term has an even smaller order and become uniformely small when $n$ gets big.
This means that $f_n(x)$ on the interval $[0,a]$ is squeezed between $\frac{x^2}{4\pi}$ and a sligher smaller term whose difference to $\frac{x^2}{4\pi}$ can be made uniformely as small as required. That means $f_n(x)$ uniformely converges to $\frac{x^2}{4\pi}$ on any finite interval $[0,a]$.

If we consider the whole line $\mathbb R$ for convergence, the matter changes. No matter how big we choose $n$, there will always be big values of $x$ where $(4\pi^2n^2+x^2)^{0.5}$ is far from $2\pi n$ and thus all the previous discussion becomes useless.
For example, we can choose $x(n)=\sqrt{5}\pi n$, which means
$$(4\pi^2n^2+x(n)^2)^{0.5} = (4\pi^2n^2+5\pi^2n^2)^{0.5}= (9\pi^2n^2)^{0.5}=3\pi n$$
which implies
$$f_n(x(n))=n\sin((4\pi^2n^2+x(n)^2)^{0.5})=n\sin(3\pi n)=0$$
That means for any $n>0$ we can use that $x(n)$ to show that
$$|f_n(x(n)) - \frac{x(n)^2}{4\pi}|=\frac{x(n)^2}{4\pi} = \frac{5\pi^2n^2}{4\pi}=5\pi n^2$$
which is not something that goes to zero for $n \to \infty$. So the convergence of $f_n(x)$ is not uniform on $\mathbb R$.


Escape quotes within triple-quoted strings

Question: Where quotes withing JSON strings are not escaped but nested in triple-quotes e.g.
j0 = '[
  {
      "A" : "no quoted bits"
  },
  {
    "A" : """this contains: "quoted" bits""",
    "B" : "no quoted bits"
  },
  {
    "A" : "no quoted bits",
    "B" : """this contains: "quoted" and "more quoted" bits"""
  }
]'

reading into R will error e.g.
jsonlite::fromJSON(j0)
#> Error: parse error: after key and value, inside map, I expect ',' or '}'
#>            bits"   },   {     "A" : """this contains: "quoted" bits"""
#>                      (right here) ------^

I've cobbled together a hacky workaround
escape_triple_quoted = function(j){
  j_split = strsplit(j, '"{3}')[[1]]
  f = seq_along(j_split) %% 2 == 0  # filter
  j_split[f] = gsub('"', '\\\\"', j_split[f])
  paste(j_split, collapse = '"')
}

escape_triple_quoted(j0) |> jsonlite::fromJSON()
#>                              A                                              B
#> 1               no quoted bits                                           <NA>
#> 2 this contains: "quoted" bits                                 no quoted bits
#> 3               no quoted bits this contains: "quoted" and "more quoted" bits
# function for parsing strings where quotes are not escaped but nested inside triple-quotes

but it doesn't feel like best practice.  Is there a better approach?
Answer: Here is a one-liner for escape_triple_quotes using gsubfn. The  gsubfn function is like gsub except the second argument may be a function which inputs the capture groups of the match and outputs the replacement of the match.  It may be expressed in formula notation as we do here.
library(gsubfn)
library(jsonlite)

escape_triple_quoted2 <- function(s) {
  gsubfn('"""(.*?)"""', ~ sprintf('"%s"', gsub('"', '\\\\"', x)), s)
}

j0 |>
  escape_triple_quoted2() |>
  fromJSON()

giving
                            A                                              B
1               no quoted bits                                           <NA>
2 this contains: "quoted" bits                                 no quoted bits
3               no quoted bits this contains: "quoted" and "more quoted" bits

Comment: gsubfn runs on all platforms that R runs on if you use a standard build which includes tcltk and that has been the case for a decade.  gsubfn uses the regex engine in tcl by default (it can also use other engines). It does not use tk  or X. proto has no dependencies so it is not related to proto.  I don't have a Mac but things you can try are unsetting DISPLAY or using R directly if you are using a front end to R.
Comment: This looks pretty neat. Note the proto dependency opens up X11/XQuartz though - is this a portable workflow?
Comment: Feels like `gsubfn()` deserves to be a base R function..


What is the most sustainable way to obtain aggregate information on fields?

Question: EntityFieldQuery is not intended to be used to run aggregate functions (SUM, AVG, etc.) on field data because it is SQL-agnostic. That said, such operations legitimately need to be run from time to time. According to SQL function with EntityFieldQuery and especially EntityFieldQuery and how to use aggregate functions SUM, ARG and MAX, SQL queries need to be used, and that approach fits my use case the best. I was speaking with @chx yesterday and he recommended using a couple of internal functions to find the field name and column name. I'm just wondering if this is sustainable and if it's appropriate to do in a codebase that I might release to otehrs.
If it's the best way, then it's the best way. I just don't want to do it before I'm absolutely sure because it feels messy.
Comment: For now, I've just used the internal functions (`_field_sql_storage_tablename($field)` and `_field_sql_storage_columnname($field_name, $column`), which suits my current needs, but it isn't sustainable, so still interested in an answer to this question should one come.
Answer: The View field module allows you to expose field tables as base tables to views. This differs from Views default behavior in that the base table is the field table and not an entity to which the field data is then loaded from. For example when selecting node as a base table you can then add fields, but the primary (base table) in the query is still node which depending on your data can screw up the aggregate functions (aka a many-to-one relationship of some fields to the node).
Views field allows you direct access to the field tables which means aggregate functions work properly. Additionally if you need to do "interesting" joins to other field tables you can control them completely using the following.
<code>/**
 * Implements hook_views_data_alter().
 */
function mymodule_views_data_alter(&$data) {
  views_field_add_multi_join($data, /* see docs */);
}
</code>
Which is fairly simple to use and allows you to then perform aggregate functions across multiple field tables at once. You can then manually invoke a view <code>$view->execute()</code> and pull the results off the view. There are examples of this in the views documentation.
The benefits of this approach over EntityFieldQuery is that you can manage the process in Views (which almost everyone will already be using) and allow it to perform the physical query building in less direct way which helps elevate possible breakage down the road. In addition many times you will want to display such aggregate data on an admin screen which you can then use the view to provide both a display and access the results in code for additional purposes.
Comment: I'll have to check this out. I could swap that code into my computed fields instead of doing the query manually. I'll probably be working on the site where I need this soon and will report back at some point. If it works, I'll accept.
Answer: Could this be done in an add-on module to views?  It handles queries very well and some results are published with aggregate functions such as in actions when contextual filters fail where it can default to all values and give counts on the available results in each.  The functions for the queries should be there but a UI form would be needed for it.  Let me know if this makes sense.  I am just beginning to dissect views and am speculating.
Comment: COUNT queries can be run on entities, so that's solved. I'm more interested in SUM myself. views_calc may provide insight, but I want to use the value in a Computed Field...which I could well do with views_get_view_result (or similar). However, getting Views to generate that query in the first place is the trick. It seems like the hackish way might be the best. I guess I will start with that because if I don't release it, I'll be golden. If I do, someone will hopefully submit a patch.


View path variable

Question: How can I programmatically fetch the view path field value?

I am able to fetch title and body, but but I cannot get the path.
function view_path_views_pre_render(\Drupal\views\ViewExecutable $view) {
  kint($view->result);
  if ($view->id() == 'view_idea_shots_for_home_page' && $view->current_display == 'block_3') {
    foreach ($view->result as $value) {
      kint($value->_entity->get('title')->value);
      kint($value->_entity->get('body')->value);
    }
  }
}

Comment: Did you try `$value->_entity->get('path')->value` ?
Comment: Yes iam getting null
Answer: path is not a field stored in the entity. It is a computed views field plugin, which can only be outputted by applying Path::render():
$path = $view->field['path']->render($value);

View path variable


Is there a way to "cut" and "paste" parts of a string in PHP

Question: I want to remove the first character of a string like so,
$a1 = "A10";
$a2 = substr($a1,1,strlen($startsem1)-1);

but I want to retrieve that removed "A" later on. Is there a way I can "cut" or "copy" that removed "A" to some variable?
Comment: why aren't you just splitting the string?
Comment: DarkXphenomenon, please specify "splitting the string" in PHP. There are numerous functions to "split" a string and I find none suitable for this problem.
Comment: I'm going to be choosing from a pull down list of several different strings such as "A07", "A08", "A09", "A10", which are pulled from a database. I will need just the number at one point, but I will need the "A" later.
Answer: Use substr again.
$a3 = substr($a1, 0, 1);

or as others commented, just split the string on whatever delimiter you're interested in using.
Comment: I can't do it this way, because I'm going to be cutting A's, B's, and C's. And I need the A10 later on.
Answer: You can do directly this way:-
<?php
$result1 = "A10";
$result2 = $result1{0};
echo "$result1{0} : " . $result1{0} . "\n";
echo "$result2 : " . $result2 . "\n";
?>

Result:
A10{0} : A
A : A

Refer LIVE DEMO
Answer: Did you mean:
$a1 = "A10";
$a2 = substr($a1,1,strlen($a1)-1);
echo $a1[0]; // output "A" eg old value for you
echo $a2; // output "10"

PHP supports array like syntax for strings too so $a1[0] (zero based index as in array) extracts first letter from string.
Answer: For fun, you could do this:
$a1 = "A10";
$split = str_split( $a1); // Split the string into an array
$first_char = array_shift( $split);
$everything_else = implode( '', $split);

Answer: You can save it in its own variable (here I use string indexing to get the first character, but you may just as well use substr):
$saved_a = $a1[0];

Also note that you may skip the third parameter to substr if you want to get the rest of the string:
$a2 = substr($a1, 1);


Expressing the likelihood function using conditional density and Radon-Nikodym

Question: Let $X \sim P$ for some distribution $P$ and $Y \sim Q(\cdot | X)$ for some distribution $Q$. Assume that $P$ has a density $p$, with respect to some ground measure $\mu$ and $Q(\cdot|X)$ has a density $q(\cdot | X)$ with respect to the same $\mu$ for every $X$. How do I express the likelihood function for a point $y$ in terms of the densities $q(\cdot | X)$ and $p$?
What I've tried
Let $G$ be the marginal distribution of $Y$. Assume $G$ has density $g$. I want to express $g(y)$ in terms of $q(y | X)$ and $p(y)$. My understanding is that this reduces to:
$$\frac{d\mathbb E [ Q(\cdot | X)]}{d\mu}=\frac{d\mathbb E [ Q(\cdot | X)]}{dP}\frac{dP}{d\mu}$$
But I don't know how to proceed from here. It does not make sense to me to exchange the order of the expectation and the Radon-Nikodym derivative (without justification). Any help would be appreciated.
Answer: Suppose that $P$ and $Q$ are both measures on $S$, where $S$ is some measurable space. Then
\begin{align*}
G(A)&= \mathbb{E}[Q(A \: | \: X)] \\
                   &= \int_S Q(A \: | \: x) \: P(dx) \\
                   &= \int_S \int_A Q(dy \: | \: x) P(dx) \\
                   &= \int_S \int_A q(y \: | \: x)p(x) \mu(dy)\mu(dx) \\
                   &= \int_A \int_S q(y \: | \: x)p(x) \mu(dx) \mu(dy) \quad \quad\text{(using Tonellis theorem.)}
\end{align*}
It immediately follows that $G$ is absolutely continuous with respect to $\mu$ with density
$$\frac{dG}{d\mu}(y) = \int_S q(y \: | \: x)p(x) \mu(dx).$$


Creating an Availability Dataframe

Question: I have a pandas dataFrame that contains the values of several parameters against timestamps that are 15 minutes apart. The parameters may contain NaN values(np.nan). My aim is to find the total number of available values per month for each parameter, i.e total number of values in that month that are not 0 or np.nan.
I tried turning all the valid values (values that are not zero or np.nan) into 1; and all the invalid values into 0. That way I can just sum all the values of a parameter in a month and I'd get the total number of available values for that month.
df.fillna(0)

for col in selected_parameters:
    df.loc[df[col] > 0, col] = 1

This generates the df having 1 for valid and 0 for invalid values.
What I can't do is create a new dataFrame that'll have the timestamps a month apart (instead of 15 min apart) and against each month, I can have the total number of available values for that month.
Answer: Use a groupby with sum as your aggregator function
df.groupby([df.index.dt.year, df.index.dt.month]).agg('sum')

This assumes that your timestamps are at the index.
Comment: Thanks a ton! Btw I was using timestamps so didn't have to do a index.dt.  "df.groupby([df.index.year, df.index.month]).agg('sum') " worked for me.
Comment: something like this? df[selected_parameters].groupby([df.index.year, df.index.month]).agg('sum')
Comment: Could I do this in a way that only calculates the sum for only the "selected_parameters" instead of all the non-index parameters ?

Creating an Availability Dataframe