Using once method on event listener

Question: In the series of problems I have with the usage of once method, I wonder how I can refactor simply that code with the once method and be able to toggle local storage on a set of clickable elts:
(function ($, Drupal) {
  'use strict';
  /**
   *
   * @type {Drupal~behavior}
   */
  Drupal.behaviors.recherche = {
    attach: function (context) {

 const els = document.querySelectorAll(".block-facet-blocktype h2, .block-facet-blockaxe h2, .block-expertisescientifique h2, .block-domainedapplication h2");
    for (const el of els) {
      el.addEventListener("click", handler);
    }

    function handler(event) {
      event.preventDefault();
      var selector = $(this);
      toggleLocalStorage(selector, 'expanded');
    }
}}
})
(jQuery, Drupal);

What happens at the moment is one click call the toggle function 6times and have then no effect.
Comment: Is this a Drupal Q? I've noticed, more so with D9 and the core `once` library, that I have some unknowns. `once('myBehavior', 'html', context).forEach( function (element)` has the potential to run before the full DOM is loaded, and placing the global context inside an `if ()` check doesn't run. This is also a bit trickier when getting an element by ID to which you may not have any `.forEach()` functions in your scripts. I have the same Q as above, when adding an event listener, how do you go about running `once()`? Must you use the global context and set `once()` against `html` or `body`?
Answer: once is a jQuery plugin; it doesn't really make sense to mix it with vanilla JS event handlers, as you're already using jQuery by that point, and it's easier to attach events with jQuery.
After you've refactored your code to use jQuery, its usage is well explained, with examples, in the Drupal javascript docs. There are many permutations, here is one example for attaching an event handler:
$('a.foo', context).once('bar').each(function () {
    // You could also use this.addEventListener here, but as you're already in a jQuery context it doesn't really make sense to.
    $(this).click(function() {
      // ...
    });
});

Comment: Using that assumes your code is wrapped in a Drupal behavior (which is recommended). The same docs linked above explain that too
Comment: thanks it works only if i remove the ",context"
Comment: it was wrapped, as edited

Using once method on event listener


Remove drupal parameters from form submitted via POST

Question: When I submit form created with Form API, the POST variable contains values like form_token, form_build and form_id.
The problem is, I need to send submitted form values to external website. Is it possible to remove such values from POST request?
In particular, I am implementing redirection callback to commerce payment method
This callback is defined within Drupal Commerce. The callback works OK, but how can I remove the mentioned form parameters? (The third party payment service does not accept them in received POST variable).
I am not sure whether I can just unset them in hook_form_alter. This callback is just part of the order process and I am not sure if I  can just unset it.
Answer: You can make a call to external website using drupal_http_request in form submit handler.. Define extra submit handler using hook_form_alter and
<code>$form['#submit'][] = 'YOUR_FORM_SUBMIT_HANDLER';
</code>
For Example
<code>// Adds a submit handler/function for your form

function YOUR_FORM_SUBMIT_HANDLER($form, &$form_state) {

    $options = array();
    // Array keys are matching the key that the remote site accepts. URL encoding will be taken care later.
    $options['data'] = array(
        'firstName' => $form_state['values']['firstName'],
        'lastName' => $form_state['values']['lastName'],
        'email' => $form_state['values']['email'],
        'name' => $form_state['values']['name'],
        'phone' => $form_state['values']['phone'],
    );
    $options['data'] = http_build_query($options['data']);
    $options['method'] => 'POST';
    $url = 'https://[url path to external site]';

    // Put your additional headers here. Cookie can be set as well.
    $headers = array('Content-Type' => 'application/x-www-form-urlencoded');

    $options['headers'] => $headers;

    // Submits data to the remote server from the drupal server. User will remain in the Drupal form submission chain.
    $response = drupal_http_request($url, $options);

}
</code>


Update de dados com IONIC e Firebase

Question: Boa noite, estou estudando Firebase com IONIC e Angular(não estou usando o AngularFire) e surgiu uma dúvida.
Como faço para atualizar os dados salvos no  Firebase?
Para pegar os dados faço da seguinte forma:
const config = {
    apiKey: "x",
    authDomain: "x",
    databaseURL: "x",
    projectId: "x",
    storageBucket: "x",
    messagingSenderId: "x"
  };
  firebase.initializeApp(config);

  let ref = firebase.database().ref('statuspedido');//statuspedido

  this.pedidos = new Array();

  ref.on('value', (dataSnapshot) =>{
     let items = dataSnapshot.val();
     for(let dados in items){
        this.pedidos.push(
            new PedidoModel(
                items[dados].dataEmissao,
                items[dados].dataAtualizacao,
                items[dados].vendedor, items[dados].frete,
                items[dados].transportadora, items[dados].status)
        )
     }
  })

Minha estrutura no firebase está assim:

E quero por exemplo fazer o update do "idPedido = 1" sem alterar os demais.
Answer: Basta usar o método update, que você encontra na documentação:

var objeto = {
      a : 'a',
      b : 'b'
    };

    firebase.database().ref('caminho/para/o/meu/objeto').update(objeto)
    .then(function (retorno){
            //se cair aqui, os dados foram atualizados com sucesso
         })
    .catch(function (error){
            //se cair aqui, deu erro
     });

Você também pode atualizar dois lugares ao mesmo tempo:

var objeto = { a : 'teste' };
var atualizacoes = {};
atualizacoes['usuario/'] = objeto;
atualizacoes['todos/']=objeto;

firebase.database().ref('caminho/para/o/meu/objeto').update(atualizacoes)
   .then(function (retorno){
          //se cair aqui, os dados foram atualizados com sucesso
       })
   .catch(function (error){
          //se cair aqui, deu erro
   });
Comment: Bom dia, fiz como me passou porém ao invés de atualizar ele cria novos objeto. Preciso atualizar um objeto específico.
Comment: ```.update``` vai atualizar o objeto se ele já existir, senão, ele cria um novo

Update de dados com IONIC e Firebase


Errado de requisição da rota ao colocar ionic-slide-box na home

Question: Tenho o serviço neste arquivo www/app/home/home.service.js:
 angular.module('app.home')
        .service('services', ['$http',services]);

    function services($http) {
        var service = {};
        var self = this;

        service.listImages = function ($scope) {
            try {
                $http({
                    url: 'http://projeto.local/index/json-banner/status/2/campo/url_file',
                    method: 'POST'
                }).success(function(response, status, headers, config) {
                if (response.length && status == 200) {
                        var dImg = [];
                        for(var i in response) {
                            dImg[i] = 'http://projeto.com.br/imagens/banner/json/' + response[i];
                        }
                        $scope.images = dImg;
                    } else {
                        $scope.images = []
                    }

                });
            } catch (e) {
               console.log(e);
            }
        }

        return service;
    }

Cujo, a saída do json de services.listImages($scope) é exatamente assim:
[
"imagen1.png",
"imagen2.png",
"imagen3.png"
]

E o controller, www/app/home/Home.js, contem o seguinte código:
angular.module('app.home')
    .controller('Home', Home);

function Home($scope, services, $ionicSlideBoxDelegate, $ionicModal, $timeout, $http, $filter) {

    $scope.images = services.listImages($scope);

    // Called each time the slide changes
    $scope.slideChanged = function(index) {
        $scope.slideIndex = index;
    };

}

A view, www/app/home.html, contem a seguinte estrutura:
<ion-view view-title="Projeto">
    <ion-header-bar class="bar-stable">

Projeto

    </ion-header-bar>
    <ion-content>
        <ion-slide-box on-slide-changed="slideChanged(index)" show-pager="true" auto-play="true" does-continue="true" slide-interval="3500" ng-if="images.length">
            <ion-slide ng-repeat="slide in images">

            </ion-slide>
        </ion-slide-box>
    </ion-content>
</ion-view>

Porém o meu problema não está em relacionado ao funcionamento disso, pois as imagens estão sendo carregadas na tela, o problema é que estou recebendo uma outra requisição que eu não faço ideia do que seja, aparentemente parece que ele está forçando um "state" (http://localhost:8100/#/slide/) :
http://localhost:8100/%7B%7Bslide%7D%7D

Veja na imagem:

Este é método da navegação:
function configRouter($stateProvider, $urlRouterProvider) {
    $stateProvider

        .state('app', {
            url: '/app',
            abstract: true,
            templateUrl: 'app/layout/layout.html',
            controller: 'Layout'
        })

        .state('app.home', {
            url: '/home',
            views: {
                'menuContent': {
                    templateUrl: 'app/home/home.html',
                    controller: 'Home'
                }
            }
        })

        .state('app.busca-proximo', {
            url: '/busca-proximo',
            views: {
                'menuContent': {
                    templateUrl: 'app/busca-proximo/busca-proximo.html',
                    controller: 'BuscaProximo'
                }
            }
        });

    $urlRouterProvider.otherwise('/app/home');

}

Comment: Tente substituir a propriedade src  da tag img por ng-src, recentemente tive um problema parecido e isso resolveu.
Comment: Parece que no  border="0"> ele está procurando o caminho errado da imagem. Tente imprimir o {{slide}} para ver se printa o caminho e nome correto da imagem. O também trocaria {{slide}} por algum outro nome tipo {{img_slide}} pode estar dando conflito
Comment: @1fabiopereira, eu acabei chegando na solução sozinho, mas é isso mesmo. Obrigado.
Answer: Descobri o problema, tive que trocar src:

Por ng-src:


If conditions in twig to check if field has a value

Question: I have used this below code to check if the field has a value
{% if content.field_title is not empty %}

{{ content.field_title }}

{% endif %}

But p tag is rendering even though the field doesn't have a value. Same happening for {% if content.field_title is not null %} as well and {{ dump(content.field_title) }} is not an empty array if the field has no value. So how to check empty condition in twig for a field.
Edited: Trying to use the content object instead node/paragraph/term object. Here Verify a field is not empty used node object.
Thanks in advance!
Answer: Quite a few ways to check. For content fields in Twig I generally prefer:
{% if content.field_title['#items'].getValue() %}


Yii2 'Your system does not support any of these drivers: gmagick,imagick,gd2'

Question: The problem is like this : i am following a yii tutorial in order to learn more about the framework, the tutorial is https://www.youtube.com/watch?v=whuIf33v2Ug&t=11365s and i found myself strugalling at 2:55:31 ( thumbnail resize ) , i installed the necesary dependencie using composer require yiisoft/yii2-imagine and i wrote the code.
 Image::getImagine()
                ->open($thumbnailPath)
                ->thumbnail(new Box(1280, 1280))
                ->save();

but for some reason i encountered this error and i can't figure out how to resolve it :
"Your system does not support any of these drivers: gmagick,imagick,gd2"
image of the error in question
Comment: Install the driver with php.
Answer: that one is not a yii2 error. you will need to enable one of that extension in you php.ini
if you are a windows user:
i would suggest to start with gd2 that one does not need any extra installation, only you will need to uncomment following line in your php.ini
extension=gd2
if you are linux user:
sudo apt-get install php-gd

will solve your problem. (you will need root permissions to the system)


Weird Logic Pro quirk with scoring

Question: I have an issue with the score display in Logic Pro X (10.3.2).
Consider the following chords (F#m and E6) that last a full bar each:

When switching to the score representation, I see the following:

and if I add a new bar, I get this:

While it's accurate, it doesn't make sense to display it that way.
Is there any reason for this?
Comment: Logic pro isn't really for engraving sheet music so quirks like this are somewhat understandable. It's more normal  than the "chord detector" they have.
Comment: There is so many bug in all that software that this is just a little issue.
Answer: What I can gather visually, your new bar contains a simplified rest notation rhythm as the second bar of your chords, specifically, there you have an E6 chord rhythmicised as dotted quaver + two 16ths + a half note, which is more accurately represented as in the second bar, namely, quaver + dotted 8th + 16th + half note.
It seems like the chord notation got messed up somehow, but you can try to repair it with view parameters.
Comment: How can the view parameters fix it? I've toggled some of the settings back and forth, but to no avail
Comment: @Thomas have you tried using separate duplicate that's quantized? It helps with scoring view
Comment: that issue ended up being random; some changes in the project would trigger a different representation.

Weird Logic Pro quirk with scoring


performance of symbolicc++

Question: Anyone has experience with the SymbolicC++ ? I'm trying to solve some linear problem with this library, but the performance seems not acceptable, here's my test
<code>#pragma warning(disable: 4800 4801 4101 4390)
#include<iostream>
using namespace std;
#include "Symbolic/symbolicc++.h"

int main() {
    // x==10  y==9  z==7
    Symbolic x("x"), y("y"), z("z");
    Equations rules = (
        x + y + z == 26,
        x - y == 1,
        2*x - y + z == 18
    );

    list<Symbolic> s = (x, y, z);

    list<Equations> result = solve(rules, s); // slow here

    for(auto& x : result) {
        cout << x << endl;
    }
}
</code>
The solve function takes 402ms(debug)/67ms(release) on an i7 cpu, is that too slow for a simple problem like this?
Anyone knows why?
Thanks
Answer: Symbolic computations are slow, they need if you want to handle formulaes.
If you just want to solve system of linear equations, consider using tool, specially created for that, like Eigen(http://eigen.tuxfamily.org/index.php?title=Main_Page), BLAS(http://www.netlib.org/blas/).
Also read http://en.wikipedia.org/wiki/Symbolic_computation
Answer: Thanks kassak, just got this done with Eigen.
<code>#include <iostream>
#include "Eigen/Dense"
using namespace std;
using namespace Eigen;
int main()
{
    Matrix3f A;
    Vector3f b;
    A <<    1, 1, 1,
            1,-1, 0,
            2,-1, 1;
    b <<    26, 1,18;
    cout << "Here is the matrix A:\n" << A << endl;
    cout << "Here is the vector b:\n" << b << endl;
    Vector3f x = A.colPivHouseholderQr().solve(b);
    cout << "The solution is:\n" << x << endl;
}
</code>
Comment: more info on this method. https://www.mathsisfun.com/algebra/systems-linear-equations-matrices.html

performance of symbolicc++


mysql help: Joining Two Tables With a Where Clause and Displaying Rows From the Other

Question: Write SELECT statement to list products with vendor data for products purchased after 2010-1-15.
I have tried multiple different commands with the best results being from:
 select * from product where p_indate > '2010-1-15';

Lists information from the product table instead of vendor
and
 select p_indate from product right join vendor on p_indate > '2010-1-15';

Just lists the p_indate with 11 duplicate values for each date that meets the conditions
I have tried searching for awhile now and nothing seems to fit exactly my question, thanks for the help!
Here are the tables:
Vendor:
v_code(primary)|v_name|v_contact|v_areacode|v_phone|v_state|v_order

product
p_code(primary)|p_descript|p_indate(foreign)|p_qoh|p_min|p_price|p_discount|v_code(foreign)

Answer: Use the on clause to pick out the columns that the tables have in common:
select  p_indate.*, vendor.*
from product
right join vendor on p_indate.v_code=vendor.v_code
where p_indate > '2010-1-15';

Comment: `SELECT p_indate.*, vendor.*
FROM product
RIGHT JOIN vendor ON p_indate.v_code=vendor.v_code
WHERE p_indate > '2010-1-15';`  will return every column from both tables.  This is not efficient.  Best to specify only those columns you are actually using.  Don't forget to `htmlspecialchars` to prevent XSS.
Comment: This worked to get a column that shows all the p_indates they have in common that are > 2010-1-15, but it displays no further information, is there a way I can get this column with the corresponding information from the vendor table?
Answer: You can specify p.* and v.* in the select to get all the product and vendor data
SELECT p.*, v.*
FROM product p
JOIN vendor v ON p.v_code = v.v_code
WHERE p.p_indate > '2010-01-15' ;

You can also pick and choose your fields to return by prefixing them with p.field name or v.field_name
Comment: Thanks a bunch!! ultimately in ended up using
`SELECT p.p_indate,
 v.*

FROM product p

JOIN vendor v ON
p.v_code = v.v_code

WHERE
p.p_indate > '2010-01-15' ;`


Prove that the result depends on the variable

Question: I have a formula:
$\dfrac{a_1\cdot\sin(-k\cdot x + \phi_1)+a_2\cdot\sin(k\cdot x + \phi_2)}{\ a_1\cdot\cos(-k\cdot x + \phi_1)+a_2\cdot\cos(k\cdot x + \phi_2)} $
I have to prove that, when $ a_1 \neq a_2 $ , the formula depends on x.
If $ a_1 = a_2 $ , it is clear that the result is $ \tan\left(\dfrac{\phi_1+\phi_2}{2}\right) $, the result does not contains $x$.
Any suggestion?
Answer: Hint
Give two different values to $x$ and notice how the result is different. For example take $x = \phi_1 / k$, $x = \phi_2 / k$
Comment: Thanks, but $ x = -\dfrac{\phi_2}{k} $ is better for me, but anyway, the hint was helpful :)


How many different ways to select a subset

Question:
We want to select three subsets A, B, and C of {1, 2, . . . , n} so that A ⊆ C,
B ⊆ C, and A ∩ B $\ne$ ∅. In how many different ways can you do this?
This is my attempt:
Let A= $A_1$, B= $A_2$ and C = $A_1 \cup  A_2$. The set = $A_1 \cup  A_2 \cup A_3$. Then $3^n$ ways?
Comment: I assume that either means $A\cap B=\varnothing$ or $A\cap B\ne\varnothing$.  It probably is important to know which one :)
Comment: I meant does not equal
Comment: Er, I don't think you can assume that $C = A\cup B$... just because $A$ and $B$ are subsets of $C$ that are not disjoint does not necessarily mean that $C=A\cup B$. For example, if $A=B\neq C$.
Answer: We want to ensure that $A \subset C$ and $B \subset C$ such that $A \cap B \neq \emptyset$.
We'll suppose that $A \cap B = \emptyset$, which are the cases that we don't want to account... Having in hands that formula, we can just subtract from all possible cases of sets $A$ and $B$ without restriction.
So suppose that the condition is: $A \subset C$ and $B \subset C$ such that $A \cap B = \emptyset$.
First suppose that $|A| = 0 \implies A = \emptyset$. Therefore $B$ can be any subset of $C$. It'll follow that for $A = \emptyset$ you can choose $B$ in $2^n$ different ways.
Now suppose that $|A| = 1$. The way how you pick $B$ defines $A$, so you only need to think about defining $B$. For that, $B$ can have any element different than the element that you picked for $A$. It can be of cardinality $0,1,\cdots,n-1$. If it's of cardinality $0$ than $B = \emptyset$. If it's of cardinality $1$ then you have $n-1 \choose 1$ ways to define it. If it's of cardinality $2$ then you have $n-1 \choose 2$ ways to define it... Continuing it in the same manner it'll follow that for $|A| = 1$ you could pick $B$ in:
$$
{n-1 \choose 0} + {n-1 \choose 1} + {n-1 \choose 2} + \cdots + {n-1 \choose n-1}
$$ways.
But you can pick $A$ for $|A| = 1$ in $n \choose 1$ different ways, so it'll follow that if $|A| = 1$ you would have:
$$
{n \choose 1} \cdot \bigg( {n-1 \choose 0} + {n-1 \choose 1} + {n-1 \choose 2} + \cdots + {n-1 \choose n-1} \bigg)
$$
ways to pick $A$ and $B$ such that the condition holds.
Using the same argument for the cardinality of $A$ over $\{0,1,2,3,\cdots,n\}$, it follows that the final answer is:
$$
\sum_{0 \leq j \leq n}{n \choose j} \cdot \bigg(\sum_{0 \leq i \leq j} {n-j \choose i}\bigg)
$$
If you use the following identity:
$$
\sum_{0 \leq i \leq n} {n \choose i} = 2^n
$$
then you can simplify the result as:
$$
\sum_{0 \leq j \leq n}{n \choose j} \cdot 2^{n-j}
$$
And that is the number for the cases where $A \cap B = \emptyset$. All cases are given by $R = \{(a,b) \mid a \subset C \text{ and } b \subset C\}$. It's clear to see that $|R| = 2^n \cdot 2^n = 2^{2n}$. So our final answer is going to be:
$$
2^{2n} - \sum_{0 \leq j \leq n}{n \choose j} \cdot 2^{n-j}
$$

Quick sanity check.
Suppose that $n = 3$, therefore $C = \{1,2,3\}$. Let's list all the possible combinations of the sets $A$ and $B$ such that $A \cap B = \emptyset$ and see if the first formula gives us the same result. A solution is going to be written as $(A,B)$.
\begin{align*}
S_1 &= \{(\emptyset,\emptyset),(\emptyset,\{1\}),(\emptyset,\{2\}),(\emptyset,\{3\}),(\emptyset,\{1,2\}),(\emptyset,\{1,3\}),(\emptyset,\{2,3\}),(\emptyset,\{1,2,3\})\}\\
S_2 &= \{(\{1\},\emptyset),(\{1\},\{2\}),(\{1\},\{3\}),(\{1\},\{2,3\})\}\\
S_3 &= \{(\{2\},\emptyset),(\{2\},\{1\}),(\{2\},\{3\}),(\{2\},\{1,3\})\}\\
S_3 &= \{(\{3\},\emptyset),(\{3\},\{1\}),(\{3\},\{2\}),(\{3\},\{1,2\})\}\\
S_5 &= \{(\{1,2\},\emptyset),(\{1,2\},\{3\})\}\\
S_6 &= \{(\{1,3\},\emptyset),(\{1,3\},\{2\})\}\\
S_7 &= \{(\{2,3\},\emptyset),(\{2,3\},\{1\})\}\\
S_8 &= \{(\{1,2,3\},\emptyset)\}\\
\end{align*}
The number of solutions is the sum of the cardinalities of all the sets above. So it'll follow that it is:
$$
8 + (4 + 4 + 4) + (2 + 2 + 2) + 1 = 27
$$
which is indeed every term in the sum of our first formula:
\begin{align*}
{3 \choose 0} 2^3 + {3 \choose 1} 2^2 + {3 \choose 2} 2^1 + {3 \choose 3} 2^0 &= 1\cdot 8 + 3 \cdot 4 + 3 \cdot 2 + 1 \cdot 1\\
&= 8 + (4 + 4 + 4) + (2 + 2 + 2) + 1\\
&= 27
\end{align*}
So, using our last formula, it follows that $2^{6} - 27 = 37$ is the required number for $A \subset C$, $B \subset C$ and $A \cap B \neq \emptyset$.
Hope it helped :)

Doyun Nam's answer
It's a combinatorial identity that
$$
{n \choose 0} + 2{n \choose 1} + \cdots + 2^n{n \choose n} = 3^n
$$
So simplyfing even more my answer (last formula), we'll get:
$$
2^{2n} - \sum_{0 \leq j \leq n}{n \choose j} \cdot 2^{n-j} = 4^n - 3^n
$$
which is Doyun Nam corrected answer as pointed out by Ross Millikan in the comments.
Answer: Let $U = \{1, \ldots, n\}$.
Then every elements should belong to one and only one of
$A \cap B$, $A - B$, $B-A$, $C - (A\cup B)$, and $U-C$.
And we should subtract the cases when $A \cap B = 0$ from the whole cases.
Hence, there are $5^n - 4^n$ ways.
Comment: But $C$ is the universe, so there are no sets in $U-C$.  Your answer becomes $4^n-3^n$ which agrees with Bruno Reis' hand count for $n=3$


Find the values of p for which there is no turning points in the curve

Question: The question:

So, I have done almost everything. I am in the last part of the question. This is how I did it:
I differentiated the curve $y = x^3 + px^2 + px$ and got:
$dy/dx = 3x^2 + 2px + p$
I am not sure how to proceed from here. I would like to know how I would solve from here. Any help would be very highly appreciated. Final answer:
$0 < p < 3$
Comment: I dont know why but the image is not appearing.
Comment: Click on the link for questuon
Comment: Nevermind works now.
Answer: Basic approach. You now have for the derivative a quadratic expression of the form $ax^2+bx+c$.  The original curve has no stationary points if and only if the derivative has no zeros; that is, when $ax^2+bx+c = 0$ has no solutions.  Using the quadratic formula
$$
x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}
$$
as a guide, identify the values of $p$ for which that derivative has no zeros.  (Hint: When is the quadratic formula undefined in the reals?)
Answer: No stationary points means $$3x^2+2px+p\neq 0$$
Use the discriminant of this quadratic equation $D=(2p)^2-4\cdot 3\cdot p$. In order for a quadratic equation to have no real roots the discriminant has to be negative. Hence, $4p^2-12p<0$ or $4p(p-3)<0$.
Can you complete it from here?
EDIT:
A product of two real numbers can only be negative if only one of them is negative. As $p>0$ from the beginning you can conclude $p-3<0$ or $p<3$. Combined with $p>0$ we get the result $0<p<3$.
Comment: Oh I did that and thought it was wrong. How do I show it as a range?
Comment: I know the answer is 0 < p < 3 but how do you get that from $4p(p - 3) < 0$
Comment: @HassanAlthaf: I added the explanation.
Comment: How did you get p > 0?
Comment: @HassanAlthaf The exercise states p is positive. Hence, p>0.


How do you verify that the notification to the Silent Post URL is indeed from PayPal Payflow and not a hacker?

Question: Payflow supports a Silent Post URL, which is a page that will be notified upon completion of a successful transaction (payment, refund, etc...). The Silent Post URL can be configured via the PayPal manager.
Most similar payment systems implement the notion of a "post back" where the receiving software can post back the results to make sure that the transaction information is legitimate and not originating from a hacker. Payflow doesn't appear to support a post back and the Payflow Pro documentation doesn't mention any other way of verifying the transaction data received at the Silent Post URL.
Answer: All valid PayPal notifications originate from 18.104.22.168. Simply ignore any notifications that don't come from this IP.
The answer is hidden away in the depths of the PayPal knowledge base: https://ppmts.custhelp.com/app/answers/detail/a_id/445. More information can also be found at https://ppmts.custhelp.com/app/answers/detail/a_id/883/kw/payflow%20ip%20address
Answer: I have choosed different approach, by passing authentication token within my request to PayPal, which I validate after receiving POST request


É possível fazer com que uma linha do repeater não repita ? c#

Question: É possível fazer com que uma linha do repeater não repita ? Ou dar um bind em umas linhas do FooterTemplate do Repeater ?
Preciso que a ultima linha que eu tentei colocar no FooterTemplate não repita, pois são os valores totais.
Quando eu deixo no ItemTemplate ele exibe 3 vezes de acordo com o numero de linhas que o datatable possui.
Era pra ficar assim:

Porém, quando eu coloco no FooterTemplate fica assim:

Meu código:
//ASPX
<FooterTemplate>

                <asp:Label ID="Label46" class="fontlbl" runat="server" Text="Totais"></asp:Label>

            <%# Eval("qtdTotalCompra") %>

            <%# string.Format("{0:C}", Eval("valorTotalCompra")).Replace("R$", "") %>

            <%# Eval("qtdTotalDevolucao") %>

            <%# string.Format("{0:C}", Eval("valorTotalDevolucao")).Replace("R$", "") %>

            <%# Eval("qtdTotalRetorno") %>

            <%# string.Format("{0:C}", Eval("valorTotalRetorno")).Replace("R$", "") %>

            <%# Eval("qtdTotalVenda") %>

            <%# string.Format("{0:C}", Eval("valorTotalVenda")).Replace("R$", "") %>

            <%# Eval("qtdTotalDoacao") %>

            <%# string.Format("{0:C}", Eval("valorTotalDoacao")).Replace("R$", "") %>

            <%# Eval("qtdTotalReenvio") %>

            <%# string.Format("{0:C}", Eval("valorTotalReenvio")).Replace("R$", "") %>

</FooterTemplate>

Comment: Você não pode deixar a ultima linha fora do loop?
Comment: @Willian Então, eu já deixei só que não preenche essa ultima linha de acordo com o que precisa com o que eu joguei pra dar o Bind
Comment: Tem como você mostrar como está aparecendo e como deveria aparecer? Tipo imagens, mesmo que sejam com dados fictícios?
Comment: Pronto @Willian, teria que ficar igual a primeira imagem.
Comment: Os valores totais são calculados em qual momento? Você chegou a verificar se as chamadas de "ValorTotalCompra" e etc está retornando os valores?
Comment: @Willian, sim, estão retornando valores, eles são carregados no momento em que eu chamo o método que retorna pro datasource do repeater.
Answer: Eu não sei e nunca utilizei Eval dentro do FooterTemplate. Você pode criar um  método no seu código para calcular a soma das colunas do DataTable e chamar no Repeater
  protected decimal Total(string campo)
  {
            return Convert.ToDecimal(dt.Compute($"Sum({campo})", string.Empty));
  }

Assim:
<FooterTemplate>

                        <%# Total("colCompraQtde") %>
                        <%# Total("colCompraValor") %>
                        <%# Total("colDevolucaoQtde") %>

</FooterTemplate>

Exemplo completo ASPX:
<asp:Repeater ID="rptVendas" runat="server">
            <HeaderTemplate>

            </HeaderTemplate>
            <ItemTemplate>

                  <%# Eval("colCompraQtde") %>
                  <%# Eval("colCompraValor") %>
                  <%# Eval("colDevolucaoQtde") %>

            </ItemTemplate>
            <AlternatingItemTemplate>

                    <%# Eval("colCompraQtde") %>
                    <%# Eval("colCompraValor") %>
                    <%# Eval("colDevolucaoQtde") %>

            </AlternatingItemTemplate>
            <FooterTemplate>

                        <%# Total("colCompraQtde") %>
                        <%# Total("colCompraValor") %>
                        <%# Total("colDevolucaoQtde") %>

            </FooterTemplate>
        </asp:Repeater>

C#
public partial class WebForm1 : System.Web.UI.Page
    {
        private DataTable dt;
        protected void Page_Load(object sender, EventArgs e)
        {
            dt = new DataTable();
            dt.Columns.Add("colCompraQtde", typeof(decimal));
            dt.Columns.Add("colCompraValor", typeof(decimal));
            dt.Columns.Add("colDevolucaoQtde", typeof(decimal));

            dt.Rows.Add(1, 5, 0);
            dt.Rows.Add(1, 2.5, 0);
            dt.Rows.Add(1, 3, 0);

            rptVendas.DataSource = dt;
            rptVendas.DataBind();
        }

        protected decimal Total(string campo)
        {
            return Convert.ToDecimal(dt.Compute($"Sum({campo})", string.Empty));
        }

    }


Php Parse text to array with contain duplicate key

Question: I want to parse text to array:
text delimited with =>
 First is the key and last is the value
 I will parse the text to an array. If a duplicate key is found, the value is an array with these keys. if not, the value is a string.
The expected result is exactly like this:
Array
(
    [phone] => phone1
    [email] => Array
        (
            [0] => email1
            [1] => email2
            [2] => email3
            [3] => email4
        )

    [fax] => fax1
    [other] => Array
        (
            [0] => other1
            [1] => other2
            [2] => other3
        )

)

My Script doesn't work

    <?php
    $txt = "
    phone=>phone1
    email=>email1
    email=>email2
    fax=>fax1
    email=>email3
    other=>other
    other=>other1
    email=>email4
    other=>other
    ";

    $lns = explode("\n", $txt);
    print_r($lns);
    $res = array();
    foreach($lns as $v) {
      $trim = trim($v);
      if($trim != '') {
        list($extName, $extVal) = explode("=>", $v);
        if(array_key_exists($extName, $res)) {
          //echo "eee=$extName, $extVal\n";
          $vv[] = $extVal;
          $value = $vv;
        } else {
          //echo "nnn=$extName, $extVal\n";
          $value = $extVal;
        }
        $res[$extName] = $value;

      }
    }
    print_r($res);

    ?>

I just get unexpected result :
Array
(
    [    phone] => phone1
    [    email] => Array
        (
            [0] => email2
            [1] => email3
            [2] => other1
            [3] => email4
        )

    [    fax] => fax1
    [    other] => Array
        (
            [0] => email2
            [1] => email3
            [2] => other1
            [3] => email4
            [4] => other
        )

)

Comment: "_My Script not works_" _What_ doesn't work? Blank page? Wrong results? Server crash?
Comment: its mean that doesnt work as expected.
Comment: `$vv` isn't defined.  Perhaps add `$vv = is_array($res[$extName]) ? $res[$extName] : [$res[$extName]];` just before your `$vv[] = $extVal;` line
Comment: @Rob Eyre. Thats no problem with php 8.2.4 we dont need to define with $vv= array()
Comment: You should also be using the trimmed value in your `explode` call - ie `explode("=>", $trim);`
Comment: @Hida `$vv[]` means 'append a value to the $vv array', but you're not defining what that is, or resetting it for each new call.  That's why you're getting values 'leaking' into the next key.
Comment: It's also why you're missing the value for `email1`.  Basically the value starts out as a simple value `email1`, but when it encounters another email, you need to turn the value into an array with the first element included, then append your new email value.  That's what the suggested line of code does.
Comment: @Rob Eyre. yes I should have to resetting $vv[] but dont know where to place it.
Comment: Just before your array append statement `$vv[]` as suggested above
Answer: So I have solve this by create array for key and value.
then use array_unique() and array_keys() function.
$txt = "
    phone=>phone1
    email=>email1
    email=>email2
    fax=>fax1
    email=>email3
    other=>other
    other=>other1
    email=>email4
    other=>other
    ";

$rowsArr = explode("\n", $txt);
foreach($rowsArr as $row) {
  $trim = trim($row);
  if($trim != '') {
    list($k, $v) = explode("=>", $row);
    $arr_keys[] = trim($k);
    $arr_vals[] = trim($v);
  }
}

$uniqueKeys = array_unique($arr_keys);
foreach($uniqueKeys as $uniqueKey) {
  $arr_keycheck = array_keys($arr_keys, $uniqueKey);
    if(count($arr_keycheck)>1) {
      $value = array();
      foreach($arr_keycheck as $keyval) {
        $value[] = $arr_vals[$keyval];
      }
    } else {
      $value = $arr_vals[$arr_keycheck[0]];
    }
$result[$uniqueKey] = $value;
}
print_r($result);

Which result:
Array
(
    [phone] => phone1
    [email] => Array
        (
            [0] => email1
            [1] => email2
            [2] => email3
            [3] => email4
        )

    [fax] => fax1
    [other] => Array
        (
            [0] => other
            [1] => other1
            [2] => other
        )

)


Can I validate client certificates signed with different root certificates in nginx?

Question: Preface: I'm new to certificate validation
I've configured an nginx website as a reverse proxy, which validates client certificates.
Without all the other specifics, this is the config that I used:
ssl_client_certificate /etc/ssl/ca/certs/si-trust-root.pem;
ssl_trusted_certificate /etc/ssl/ca/certs/si-trust-root.pem;
ssl_verify_client on;
ssl_verify_depth 3;

Inside si-trust-root.pem is an intermediate and the root certificate.
After successful validation and some additional backend magic, the user is logged into the website.
The "problem" is that I will have to validate client certificates signed with different root certificates. Is this possible in nginx, or in any other reverse proxy software (eg apache)?
From what I've gathered, it's only possible to do this in nginx with different server blocks. If nothing else works, this is what I'll probably do.
Answer: It should work by concatenating the CA certificates in a single file.
See these questions:

nginx, ssl_trusted_certificate and multiple certificates
How to specify multiple root certificates for nginx client certificate verification?


Code signing certificate not working when deployed by GPO

Question: Our codesigning certificat from Symantec has been converted to a password protected  pfx with complete certificate chain, public- and private-key
Signing with signtool (version 10.0.17763.0, x64) works when the certificate is manually imported to a build server (Windows Server 2012 R2) but not when it is pushed with a GPO from DC (Server 2012 R2)
In both scenarios:

The complete certificate chain is imported and all certificate
details on DC is identical to the certificate on the server
Certificate general tab on the server claims that 'You have a private
key that corresponds to this certificate'

My signing command is this:
C:\Users\myUser>"C:\Program Files (x86)\Windows Kits\10\bin\10.0.17763.0\x64\signtool.exe" sign /debug /v /a /sm /s Root /n "" /t http://timestamp.verisign.com/scripts/timstamp.dll MyApp.exe
Result when executed after manual import to server:
After EKU filter, 40 certs were left.
After expiry filter, 34 certs were left.
After Subject Name filter, 1 certs were left.
After Private Key filter, 1 certs were left.

Result when executed after GPO push to server:
After EKU filter, 40 certs were left.
After expiry filter, 34 certs were left.
After Subject Name filter, 1 certs were left.
After Private Key filter, 0 certs were left.
SignTool Error: No certificates were found that met all the given criteria.

What is the reason for After Private Key filter, 0 certs were left ?
Comment: You cannot use GPO to distribute certificates with private keys. Only public parts of the certificate can be deployed via GPO.
Answer: My gpo for publishing certificates was setup with the certificate in: Computer Configuration, Policies, Windows Settings, Security Settings, Public Key Policies, Trusted Root certificates
To get it to work I also had to setup the same certificate in: Computer Configuration, Policies, Windows Settings, Security Settings, Public Key Policies, Trusted Publishers
I also had to enable Computer Configuration, Policies, Administrative Templates, Windows Components, Windows Update, Allow signed updates from an intranet Microsoft update service location
Comment: Did you need to specify a different certificate store parameter to use Trusted Publishers? e.g. iirc the root authority store is "/sm /s My"
Comment: No we used the same parameters


Mock DataAccess methods that uses Enterprise Library to return IDataReader

Question: I was given a task to rewrite an Api and corresponding unit tests. I am still quite new to unit testing and so I am struggling to write the test code for a data access class that uses Enterprise Library. Here is the code:
namespace TOS_Landside_BL.Classes {
  using System.Collections.Generic;
  using System.Data;
  using System.Data.Common;
  using Microsoft.Practices.EnterpriseLibrary.Data;
  using Interfaces;

  public class DataAccess : IDataAccess {
    private readonly Database yasDB;

    public DataAccess () {
      DatabaseProviderFactory factory = new DatabaseProviderFactory ();
      DatabaseFactory.SetDatabaseProviderFactory (factory, false);
      yasDB = factory.Create ("AutomationDB");
    }

    // caller is responsible for closing the reader.
    public IDataReader ExecuteReaderForStoredProcedure (string cmdName, List<DbParameter> parameters = null) {
      DbCommand cmd = yasDB.GetStoredProcCommand (cmdName);
      if (parameters != null)
        cmd.Parameters.AddRange (parameters.ToArray ());

      return yasDB.ExecuteReader (cmd);
    }

    public IDataReader ExecuteReaderForSqlStringCommand (string cmdScript, List <DbParameter> parameters = null) {
      DbCommand cmd = yasDB.GetSqlStringCommand (cmdScript);
      if (parameters != null) {
        cmd.Parameters.AddRange(parameters.ToArray());
      }

      return yasDB.ExecuteReader (cmd);
    }
  }
}

Here is the interface IDataAccess:
namespace TOS_Landside_BL.Interfaces {
  using System.Collections.Generic;
  using System.Data;
  using System.Data.Common;

  public interface IDataAccess {
    IDataReader ExecuteReaderForStoredProcedure (string cmdName, List<DbParameter> parameters = null);
    IDataReader ExecuteReaderForSqlStringCommand (string cmdScript, List <DbParameter> parameters = null);
  }
}

And here is a sample on how I would call it:
namespace TOS_Landside_BL.Data {
  using System;
  using System.Collections.Generic;
  using System.Data;
  using System.Data.Common;
  using System.Data.SqlClient;
  using System.Linq;
  using Classes;
  using Enums;
  using Factories;
  using Interfaces;

  public class LandsideTransactionDataProvider {
    private readonly IDataAccess _dataAccess;

    public LandsideTransactionDataProvider (IDataAccess dataAccess = null)
    {
      _dataAccess = dataAccess ?? new DataAccess ();
    }

    public LandsideTransaction GetLandsideTransaction (string keyword, bool isKioskID = false)
    {
      var strCmd = isKioskID ? "proc_get_landside_transaction_by_kiosk_id" : "[LandSide].[GetLandsideTransactionDetail]";
      var parameters = new List <DbParameter> () {
        new SqlParameter ("@keyword", SqlDbType.NVarChar, 11) {Value = keyword}
      };

      using (var reader = _dataAccess.ExecuteReaderForStoredProcedure (strCmd, parameters)) {
        return reader.Read () ? reader.CreateLandSideTransaction () : null;
      }
    }
  }

In the SetUp method of my test class, I tried this:
var dataAccess = new Mock<IDataAccess>();
dataAccess.SetUp(d => d.ExecuteReaderFromStoredProcedure(null, null)).Returns(IDataReader);

but it won't accept IDataReader or any concrete data reader classes.
Please advise as to what I'm doing wrong, and any suggestion would really be appreciated.  Thank you.
Answer: You can create a mock for the IDataReader and set it up for the test as well.
var reader = new Mock<IDataReader>();
//..Setup the reader as expected for the test.
//Like reader.Read(), etc.

var dataAccess = new Mock<IDataAccess>();
dataAccess
    .Setup(_ => _.ExecuteReaderForStoredProcedure(It.IsAny<string>(), It.IsAny<List<DbParameter>>()))
    .Returns(reader.Object);//return mocked reader.

Comment: @RodericAgustin if this solution solved your issue you should mark it as the answer so that it can be considered resolved.
Comment: @RodericAgustin any feedback on the solution.
Comment: Hey, Nkosi! Sorry, I was busy with a project.  Yes, the solution actually worked but I had to do a lot of refactoring/decoupling in the old code.  Thanks again!


Algebraic dual space of $c_{00}$

Question: Let $c_{00}$ be the space of real sequences that has finite non-zero elements. I do not know what is the algebraic dual (space of all linear forms on $c_{00}$) of $c_{00}$.
Thank you for all construction.
Answer: For each $\varphi \in c_{00}'$, consider
$$
y_j := \varphi(e_j)
$$
where $e_j$ denotes the $j^{th}$ term in the standard basis of $c_{00}$. Then $y := (y_j)$ is merely a sequence of complex numbers with the property that
$$
\varphi((x_n)) = \sum x_ny_n \quad\forall (x_n) \in c_{00}
$$
Hence the algebraic dual would be the space of all sequences of complex numbers!

Algebraic dual space of $c_{00}$


Is the WebSocket constructor native Javascript?

Question: I'm wondering, is the WebSocket() constructor a part of native Javascript? Or is it a part of the "ws" module of node.js?
If it's a part of the "ws" module, I'm confused, because I'm in a lynda.com training course, and this is a client-side js file that me and my instructor set up:
<code>var ws = new WebSocket("ws://localhost:3000");
ws.onopen = function() {
setTitle("Connected to Cyber Chat");
};

ws.onclose = function() {
setTitle("DISCONNECTED");
};

ws.onmessage = function(payload) {
printMessage(payload.data);
};

document.forms[0].onsubmit = function () {
var input = document.getElementById('message')
ws.send(input.value);
input.value = '';
};

function setTitle(title) {
document.querySelector('h1').innerHTML = title;
}

function printMessage(message) {
var p = document.createElement('p');
p.innerText = message;
document.querySelector('div.messages').appendChild(p);
}
</code>
So in my mind, the WebSocket() constructor would have to be a native Javascript constructor that looks for a Websocket server in the url you provide it in the argument, because there is nothing referring this file to the "ws" node module that I have in this project folder.
Comment: Its not the same code base, but the API is the same, `rejectUnauthorized` wont work in the browser though, so if invalid/self-signed SSL certs wont work for wss, apart from that their pretty much identical.
Comment: NIT: WebSocket is *not* part of "native JavaScript" ([ECMAScript](https://www.ecma-international.org/publications/standards/Ecma-262.htm)). It is part of 'standard browser Web API' with some "ports" in/for node.js. A valid ECMAScript ("JavaScript") implementation does *not* need to provide this type.
Answer: webSocket is not part of the Javascript ECMA standard.  It's not a standard part of Javascript itself.  You will find no mention of it at all in the EMCAScript standard that defines the Javascript language.
It has its own standard for the webSocket protocol and then an implementation that meets that standard is supplied by browsers and by the ws library (and other libraries too).  The API used by the browsers is being worked on by the W3C in a standards process, but that is completely independent of Javascript itself.
But, if you were to grab a plain JS engine such as the V8 engine, it would not have a webSocket implementation in the V8 engine.  That's why, for example, node.js does not come with a webSocket implementation built-in.  It's not part of the V8 Javascript engine.


does a matrix commutes with its resolvet?

Question: Let $A$ be a non singular matrix, and $\omega$ a complex number such that
$$
\det(I\omega-A)\neq 0 \forall \omega
$$
where $I$ is the identity matrix.
Does the following equality holds?
$$
(I\omega-A)^{-1}A = A(I\omega-A)^{-1}
$$
How to prove it?
Comment: multiply both sides by $(I\omega-A)$
Comment: The answer is yes.
Answer: It should be clear that $(I\omega-A)^{-1}(I\omega-A )= (I\omega-A)(I\omega-A)^{-1}$.
Can you take it from here ?


Laravel json api to webapp

Question: I've build an api for 2 apps. Now I want to build a webapp but how should I parse the output to an object? json_decode is not working!?
In postman this is the response I receive:
    {
  "company": [
    [
      {
        "CompanyName": "Weimann-Watsica",
        "Logo": "/tmp/7a23ae584c52f3ab351e89bff25ce3eb.jpg",
        "Address": "108 Turcotte Lane Suite 292\nMyatown, VA 65405",
        "Zip": "98604-",
        "City": "Craigview",
        "KvkNumber": null,
        "EcaboNumber": "abc8db0e-847e-343c-9"
      },
      {
        "CompanyName": "Schuster-Harber",
        "Logo": "/tmp/11ab2217784143c2f8633ee36979bc2e.jpg",
        "Address": "98050 Green Circle Apt. 773\nKassulkefort, SC 17967",
        "Zip": "12712-",
        "City": "Granvilleborough",
        "KvkNumber": null,
        "EcaboNumber": "ad805e0a-fc5b-381e-9"
      },
      {
        "CompanyName": "Considine and Sons",
        "Logo": "/tmp/3ad1fd539790a26731efa58fc6aa60d3.jpg",
        "Address": "8456 Nick Road\nEast Kaseyborough, KY 51166",
        "Zip": "24489-",
        "City": "Langworthbury",
        "KvkNumber": null,
        "EcaboNumber": "c6676f89-b18b-3c29-9"
      },
      {
        "CompanyName": "Franecki Group",
        "Logo": "/tmp/22c955f9ffbfb7ff9c5815be4bdc285a.jpg",
        "Address": "5862 Lindsey Islands\nGusikowskistad, IL 93018",
        "Zip": "75074-",
        "City": "Denesikmouth",
        "KvkNumber": null,
        "EcaboNumber": "73003d6e-980e-3b5a-9"
      },
      {
        "CompanyName": "Haley, Funk and Prosacco",
        "Logo": "/tmp/673faaa8f27ebf429ad3fd2233433f66.jpg",
        "Address": "410 Watsica Place Apt. 189\nEast Draketon, WV 43417-8899",
        "Zip": "88619",
        "City": "Cassinville",
        "KvkNumber": null,
        "EcaboNumber": "bb13a773-13d1-3e45-9"
      },
      {
        "CompanyName": "Littel Ltd",
        "Logo": "/tmp/48af3b908f843b84aa16184c6c785ff4.jpg",
        "Address": "30658 Leopold Squares Suite 278\nLake Otiliafurt, AZ 63970",
        "Zip": "71925",
        "City": "Lake Lerahaven",
        "KvkNumber": null,
        "EcaboNumber": "ddc14688-8a61-3278-8"
      },
      {
        "CompanyName": "Padberg-Schinner",
        "Logo": "/tmp/f4c83766297f0a3644cbbbfc3c6abf07.jpg",
        "Address": "247 Amani Mountains\nLake Erwin, NJ 63657-4632",
        "Zip": "89299",
        "City": "West Merl",
        "KvkNumber": null,
        "EcaboNumber": "6ba1be4e-0faf-3faf-8"
      },
      {
        "CompanyName": "Gaylord PLC",
        "Logo": "/tmp/6ae6de23a4a0aa41aae8dea7c7e7910c.jpg",
        "Address": "479 Conrad Wells\nWest Earl, UT 70491-6540",
        "Zip": "83609-",
        "City": "Schusterfurt",
        "KvkNumber": null,
        "EcaboNumber": "7630d83a-b16d-3d2c-a"
      },
      {
        "CompanyName": "O'Hara-Witting",
        "Logo": "/tmp/3f250a95fe2939295b96900c49f0e24b.jpg",
        "Address": "001 Evert Well\nShyanneport, UT 69785-4429",
        "Zip": "49353",
        "City": "Port Aleenburgh",
        "KvkNumber": null,
        "EcaboNumber": "25ee832a-aca5-3c53-a"
      },
      {
        "CompanyName": "Cormier and Sons",
        "Logo": "/tmp/e67e1ae47e2659ee25bea28b6832a974.jpg",
        "Address": "5130 Spinka Vista Apt. 888\nWest Carissamouth, ID 48028-9281",
        "Zip": "50161",
        "City": "Lake Loyhaven",
        "KvkNumber": null,
        "EcaboNumber": "a2886d81-1bbd-34cf-8"
      },
      {
        "CompanyName": "Johnston, Stracke and Hyatt",
        "Logo": "/tmp/355efcb5fd1070d5ae12d50d07b92804.jpg",
        "Address": "74364 Cheyenne Mall\nWest Tysonfort, DE 19649",
        "Zip": "00872-",
        "City": "Schambergerview",
        "KvkNumber": null,
        "EcaboNumber": "0f90c863-2997-37a4-a"
      },
      {
        "CompanyName": "Mann-Little",
        "Logo": "/tmp/772c54749e18028a571a344d1ce8ecb0.jpg",
        "Address": "2816 Elisha Canyon\nNew Rhett, NJ 06711",
        "Zip": "02541",
        "City": "Kiehnberg",
        "KvkNumber": null,
        "EcaboNumber": "bc2eb9e9-764c-3427-9"
      },
      {
        "CompanyName": "Koelpin LLC",
        "Logo": "/tmp/d71bdd9f4180e3ef2ac78ca1d8f4c544.jpg",
        "Address": "83328 Robb Gardens\nNew Alannaburgh, OH 82265-4451",
        "Zip": "91119-",
        "City": "Terryside",
        "KvkNumber": null,
        "EcaboNumber": "94c2969e-1080-3e4b-a"
      },
      {
        "CompanyName": "Hettinger-Koepp",
        "Logo": "/tmp/ba956219f80d557ccce96e7904a8b98f.jpg",
        "Address": "368 Jacobs Road\nDylanside, CT 29936",
        "Zip": "84392",
        "City": "Kaylahtown",
        "KvkNumber": null,
        "EcaboNumber": "616dca15-8f8c-307d-b"
      },
      {
        "CompanyName": "Bartell-Heathcote",
        "Logo": "/tmp/23a34d152c7c9972f787c61829c7a348.jpg",
        "Address": "98939 Borer Loaf\nWest Augustine, WY 98256",
        "Zip": "16916-",
        "City": "Leuschketown",
        "KvkNumber": null,
        "EcaboNumber": "4e0b237b-9841-3052-8"
      },
      {
        "CompanyName": "Crist, Prohaska and Pacocha",
        "Logo": "/tmp/53d1c7eb7dd16b1d1a9ec0a7019b990f.jpg",
        "Address": "97779 Grant Stravenue Apt. 753\nLake Coty, AK 67959-9158",
        "Zip": "70297-",
        "City": "Port Lelia",
        "KvkNumber": null,
        "EcaboNumber": "d612fe06-a438-32c8-a"
      },
      {
        "CompanyName": "Leuschke, Rice and Quigley",
        "Logo": "/tmp/b2e5e7c7dedf630934de260ffacaeab5.jpg",
        "Address": "13475 Nitzsche Lodge\nAlysaside, MT 85057",
        "Zip": "24897",
        "City": "East Bernice",
        "KvkNumber": null,
        "EcaboNumber": "1d160d74-6d1d-3d0d-9"
      },
      {
        "CompanyName": "Champlin Ltd",
        "Logo": "/tmp/e08399803fbbc3b361ca09942af5fc30.jpg",
        "Address": "1864 Baumbach Dam\nPort Joeyborough, VT 04166-1913",
        "Zip": "83480-",
        "City": "New Alana",
        "KvkNumber": null,
        "EcaboNumber": "626f6b9c-2681-3ad9-8"
      },
      {
        "CompanyName": "Hilpert Group",
        "Logo": "/tmp/aa142bb879e8a03df8634e87cb2e5f5e.jpg",
        "Address": "9193 Funk Alley\nMcCluretown, MO 03610-2601",
        "Zip": "32091",
        "City": "New Karentown",
        "KvkNumber": null,
        "EcaboNumber": "ec29c579-f6de-3d58-8"
      },
      {
        "CompanyName": "Conroy-McKenzie",
        "Logo": "/tmp/275dac535cb9ce031faee19309363ad5.jpg",
        "Address": "906 Shirley Wall Suite 397\nO'Reillyfort, AL 85503-2410",
        "Zip": "49532-",
        "City": "Lake Oletaport",
        "KvkNumber": null,
        "EcaboNumber": "39dad66c-e399-319a-b"
      },
      {
        "CompanyName": "Kris, Schoen and Orn",
        "Logo": "/tmp/9ca37b175c49e2a786afc747659d91c9.jpg",
        "Address": "41106 Amelia Locks\nLavinaburgh, DC 59553",
        "Zip": "75767",
        "City": "South Melyssaside",
        "KvkNumber": null,
        "EcaboNumber": "115e3932-12b4-3fb4-b"
      },
      {
        "CompanyName": "Zemlak, Wuckert and Rosenbaum",
        "Logo": "/tmp/635c51a3cc0de11289c2997a8eba0347.jpg",
        "Address": "99847 Stiedemann Estates Suite 623\nWest Korymouth, HI 41991-1801",
        "Zip": "61771",
        "City": "Justicebury",
        "KvkNumber": null,
        "EcaboNumber": "9f2a79b9-b353-3c09-8"
      },
      {
        "CompanyName": "Bogisich, Stokes and O'Conner",
        "Logo": "/tmp/37f259657a82c06a96affba1ac8f7940.jpg",
        "Address": "240 Mariane Rapid\nWest Effie, WA 73757-8372",
        "Zip": "26105",
        "City": "Port Caden",
        "KvkNumber": null,
        "EcaboNumber": "f27b4b43-d964-3ef0-9"
      },
      {
        "CompanyName": "Swift and Sons",
        "Logo": "/tmp/28b2223c1bb990dfb0a072054f900a9d.jpg",
        "Address": "318 Maybelle Turnpike\nSchaefermouth, OK 59036",
        "Zip": "44838",
        "City": "Homenickmouth",
        "KvkNumber": null,
        "EcaboNumber": "3ce903d4-10b3-3c9d-9"
      },
      {
        "CompanyName": "Gleichner, Mosciski and Donnelly",
        "Logo": "/tmp/fd7e0af605193766fc1f1da598886f49.jpg",
        "Address": "922 Dariana Club Apt. 822\nEast Mireille, NY 88400-0249",
        "Zip": "89335-",
        "City": "Hortensefort",
        "KvkNumber": null,
        "EcaboNumber": "05b2ed89-3568-3478-a"
      },
      {
        "CompanyName": "Schiller-Conroy",
        "Logo": "/tmp/37ad9c0d3946b50668e916ed7e5192a0.jpg",
        "Address": "4251 Mariah Knoll\nPort Shanelburgh, MT 37153-6153",
        "Zip": "37923",
        "City": "Ronaldochester",
        "KvkNumber": null,
        "EcaboNumber": "058cd122-60e3-31fd-8"
      },
      {
        "CompanyName": "Cartwright, Sanford and Morar",
        "Logo": "/tmp/cb9804f1dd41bfe137255a3fefd0264d.jpg",
        "Address": "204 Grover Roads Suite 203\nLake Hailee, HI 24534-2955",
        "Zip": "85590-",
        "City": "Ronside",
        "KvkNumber": null,
        "EcaboNumber": "cdc49e99-fb43-31e0-9"
      }
    ]
  ]
}

When I try:
$companies = $this->company->showCompanies();
dd($companies);

Result is:
JsonResponse {#230 ▼
  #jsonOptions: 0
  #data: "{"company":[[{"CompanyName":"Weimann-Watsica","Logo":"\/tmp\/7a23ae584c52f3ab351e89bff25ce3eb.jpg","Address":"108 Turcotte Lane Suite 292\nMyatown, VA 65405","Zip":"98604-","City":"Craigview","KvkNumber":null,"EcaboNumber":"abc8db0e-847e-343c-9"},{"CompanyName":"Schuster-Harber","Logo":"\/tmp\/11ab2217784143c2f8633ee36979bc2e.jpg","Address":"98050 Green Circle Apt. 773\nKassulkefort, SC 17967","Zip":"12712-","City":"Granvilleborough","KvkNumber":null,"EcaboNumber":"ad805e0a-fc5b-381e-9"},{"CompanyName":"Considine and Sons","Logo":"\/tmp\/3ad1fd539790a26731efa58fc6aa60d3.jpg","Address":"8456 Nick Road\nEast Kaseyborough, KY 51166","Zip":"24489-","City":"Langworthbury","KvkNumber":null,"EcaboNumber":"c6676f89-b18b-3c29-9"},{"CompanyName":"Franecki Group","Logo":"\/tmp\/22c955f9ffbfb7ff9c5815be4bdc285a.jpg","Address":"5862 Lindsey Islands\nGusikowskistad, IL 93018","Zip":"75074-","City":"Denesikmouth","KvkNumber":null,"EcaboNumber":"73003d6e-980e-3b5a-9"},{"CompanyName":"Haley, Funk and Prosacco","Logo":"\/tmp\/673faaa8f27ebf429ad3fd2233433f66.jpg","Address":"410 Watsica Place Apt. 189\nEast Draketon, WV 43417-8899","Zip":"88619","City":"Cassinville","KvkNumber":null,"EcaboNumber":"bb13a773-13d1-3e45-9"},{"CompanyName":"Littel Ltd","Logo":"\/tmp\/48af3b908f843b84aa16184c6c785ff4.jpg","Address":"30658 Leopold Squares Suite 278\nLake Otiliafurt, AZ 63970","Zip":"71925","City":"Lake Lerahaven","KvkNumber":null,"EcaboNumber":"ddc14688-8a61-3278-8"},{"CompanyName":"Padberg-Schinner","Logo":"\/tmp\/f4c83766297f0a3644cbbbfc3c6abf07.jpg","Address":"247 Amani Mountains\nLake Erwin, NJ 63657-4632","Zip":"89299","City":"West Merl","KvkNumber":null,"EcaboNumber":"6ba1be4e-0faf-3faf-8"},{"CompanyName":"Gaylord PLC","Logo":"\/tmp\/6ae6de23a4a0aa41aae8dea7c7e7910c.jpg","Address":"479 Conrad Wells\nWest Earl, UT 70491-6540","Zip":"83609-","City":"Schusterfurt","KvkNumber":null,"EcaboNumber":"7630d83a-b16d-3d2c-a"},{"CompanyName":"O'Hara-Witting","Logo":"\/tmp\/3f250a95fe2939295b96900c49f0e24b.jpg","Address":"001 Evert Well\nShyanneport, UT 69785-4429","Zip":"49353","City":"Port Aleenburgh","KvkNumber":null,"EcaboNumber":"25ee832a-aca5-3c53-a"},{"CompanyName":"Cormier and Sons","Logo":"\/tmp\/e67e1ae47e2659ee25bea28b6832a974.jpg","Address":"5130 Spinka Vista Apt. 888\nWest Carissamouth, ID 48028-9281","Zip":"50161","City":"Lake Loyhaven","KvkNumber":null,"EcaboNumber":"a2886d81-1bbd-34cf-8"},{"CompanyName":"Johnston, Stracke and Hyatt","Logo":"\/tmp\/355efcb5fd1070d5ae12d50d07b92804.jpg"

When I try:
$companies = $this->company->showCompanies();
dd(json_decode($companies));

Result is null?
What should I do?
(it's dummy data)
Comment: Did you `dd` just the `$companies` variable? I bet the result is decoded already.
Comment: It's not decoded! Added the result to my question.
Comment: You're supposed to put a json-encoded string into `json_decode`. You're feeding it an object. Try `dd(json_decode($companies->data))`. Alternatively try dumping `get_class($companies)` to let us know the FQCN (looks like a Symfony JsonResponse)
Comment: @Denker the result of get_class($companies) is "Illuminate\Http\JsonResponse" when I do json_decode($companies->data) result is: Cannot access protected property Illuminate\Http\JsonResponse::$data
Comment: use `$companies->getData()` instead of `json_decode($companies)` :) You can always refer to the [Laravel API documentation](https://laravel.com/api/5.2/Illuminate/Http/JsonResponse.html) or just pop open the class and look inside it.
Answer: I see wrong json format:
$dummy = '{
"company": [
    [{
        "CompanyName": "Weimann-Watsica",
        "Logo": "/tmp/7a23ae584c52f3ab351e89bff25ce3eb.jpg",
        "Address": "108 Turcotte Lane Suite 292\nMyatown, VA 65405",
        "Zip": "98604-",
        "City": "Craigview",
        "KvkNumber": null,
        "EcaboNumber": "abc8db0e-847e-343c-9"
    }, {
        "CompanyName": "Schuster-Harber",
        "Logo": "/tmp/11ab2217784143c2f8633ee36979bc2e.jpg",
        "Address": "98050 Green Circle Apt. 773\nKassulkefort, SC 17967",
        "Zip": "12712-",
        "City": "Granvilleborough",
        "KvkNumber": null,
        "EcaboNumber": "ad805e0a-fc5b-381e-9"
    }, {
        "CompanyName": "Considine and Sons",
        "Logo": "/tmp/3ad1fd539790a26731efa58fc6aa60d3.jpg",
        "Address": "8456 Nick Road\nEast Kaseyborough, KY 51166",
        "Zip": "24489-",
        "City": "Langworthbury",
        "KvkNumber": null,
        "EcaboNumber": "c6676f89-b18b-3c29-9"
    }, {
        "CompanyName": "Franecki Group",
        "Logo": "/tmp/22c955f9ffbfb7ff9c5815be4bdc285a.jpg",
        "Address": "5862 Lindsey Islands\nGusikowskistad, IL 93018",
        "Zip": "75074-",
        "City": "Denesikmouth",
        "KvkNumber": null,
        "EcaboNumber": "73003d6e-980e-3b5a-9"
    }]
]
}';
          $companies = json_decode($dummy);
          dd($companies);

Edit: you edit your json and I'm getting -2, anyway, this code working:
$dummy = '{

 "company": [
    [
      {
        "CompanyName": "Weimann-Watsica",
        "Logo": "/tmp/7a23ae584c52f3ab351e89bff25ce3eb.jpg",
        "Address": "108 Turcotte Lane Suite 292\nMyatown, VA 65405",
        "Zip": "98604-",
        "City": "Craigview",
        "KvkNumber": null,
        "EcaboNumber": "abc8db0e-847e-343c-9"
      },
      {
        "CompanyName": "Schuster-Harber",
        "Logo": "/tmp/11ab2217784143c2f8633ee36979bc2e.jpg",
        "Address": "98050 Green Circle Apt. 773\nKassulkefort, SC 17967",
        "Zip": "12712-",
        "City": "Granvilleborough",
        "KvkNumber": null,
        "EcaboNumber": "ad805e0a-fc5b-381e-9"
      },
      {
        "CompanyName": "Considine and Sons",
        "Logo": "/tmp/3ad1fd539790a26731efa58fc6aa60d3.jpg",
        "Address": "8456 Nick Road\nEast Kaseyborough, KY 51166",
        "Zip": "24489-",
        "City": "Langworthbury",
        "KvkNumber": null,
        "EcaboNumber": "c6676f89-b18b-3c29-9"
      },
      {
        "CompanyName": "Franecki Group",
        "Logo": "/tmp/22c955f9ffbfb7ff9c5815be4bdc285a.jpg",
        "Address": "5862 Lindsey Islands\nGusikowskistad, IL 93018",
        "Zip": "75074-",
        "City": "Denesikmouth",
        "KvkNumber": null,
        "EcaboNumber": "73003d6e-980e-3b5a-9"
      },
      {
        "CompanyName": "Haley, Funk and Prosacco",
        "Logo": "/tmp/673faaa8f27ebf429ad3fd2233433f66.jpg",
        "Address": "410 Watsica Place Apt. 189\nEast Draketon, WV 43417-8899",
        "Zip": "88619",
        "City": "Cassinville",
        "KvkNumber": null,
        "EcaboNumber": "bb13a773-13d1-3e45-9"
      },
      {
        "CompanyName": "Littel Ltd",
        "Logo": "/tmp/48af3b908f843b84aa16184c6c785ff4.jpg",
        "Address": "30658 Leopold Squares Suite 278\nLake Otiliafurt, AZ 63970",
        "Zip": "71925",
        "City": "Lake Lerahaven",
        "KvkNumber": null,
        "EcaboNumber": "ddc14688-8a61-3278-8"
      },
      {
        "CompanyName": "Padberg-Schinner",
        "Logo": "/tmp/f4c83766297f0a3644cbbbfc3c6abf07.jpg",
        "Address": "247 Amani Mountains\nLake Erwin, NJ 63657-4632",
        "Zip": "89299",
        "City": "West Merl",
        "KvkNumber": null,
        "EcaboNumber": "6ba1be4e-0faf-3faf-8"
      },
      {
        "CompanyName": "Gaylord PLC",
        "Logo": "/tmp/6ae6de23a4a0aa41aae8dea7c7e7910c.jpg",
        "Address": "479 Conrad Wells\nWest Earl, UT 70491-6540",
        "Zip": "83609-",
        "City": "Schusterfurt",
        "KvkNumber": null,
        "EcaboNumber": "7630d83a-b16d-3d2c-a"
      },
      {
        "CompanyName": "O\'Hara-Witting",
        "Logo": "/tmp/3f250a95fe2939295b96900c49f0e24b.jpg",
        "Address": "001 Evert Well\nShyanneport, UT 69785-4429",
        "Zip": "49353",
        "City": "Port Aleenburgh",
        "KvkNumber": null,
        "EcaboNumber": "25ee832a-aca5-3c53-a"
      },
      {
        "CompanyName": "Cormier and Sons",
        "Logo": "/tmp/e67e1ae47e2659ee25bea28b6832a974.jpg",
        "Address": "5130 Spinka Vista Apt. 888\nWest Carissamouth, ID 48028-9281",
        "Zip": "50161",
        "City": "Lake Loyhaven",
        "KvkNumber": null,
        "EcaboNumber": "a2886d81-1bbd-34cf-8"
      },
      {
        "CompanyName": "Johnston, Stracke and Hyatt",
        "Logo": "/tmp/355efcb5fd1070d5ae12d50d07b92804.jpg",
        "Address": "74364 Cheyenne Mall\nWest Tysonfort, DE 19649",
        "Zip": "00872-",
        "City": "Schambergerview",
        "KvkNumber": null,
        "EcaboNumber": "0f90c863-2997-37a4-a"
      },
      {
        "CompanyName": "Mann-Little",
        "Logo": "/tmp/772c54749e18028a571a344d1ce8ecb0.jpg",
        "Address": "2816 Elisha Canyon\nNew Rhett, NJ 06711",
        "Zip": "02541",
        "City": "Kiehnberg",
        "KvkNumber": null,
        "EcaboNumber": "bc2eb9e9-764c-3427-9"
      },
      {
        "CompanyName": "Koelpin LLC",
        "Logo": "/tmp/d71bdd9f4180e3ef2ac78ca1d8f4c544.jpg",
        "Address": "83328 Robb Gardens\nNew Alannaburgh, OH 82265-4451",
        "Zip": "91119-",
        "City": "Terryside",
        "KvkNumber": null,
        "EcaboNumber": "94c2969e-1080-3e4b-a"
      },
      {
        "CompanyName": "Hettinger-Koepp",
        "Logo": "/tmp/ba956219f80d557ccce96e7904a8b98f.jpg",
        "Address": "368 Jacobs Road\nDylanside, CT 29936",
        "Zip": "84392",
        "City": "Kaylahtown",
        "KvkNumber": null,
        "EcaboNumber": "616dca15-8f8c-307d-b"
      },
      {
        "CompanyName": "Bartell-Heathcote",
        "Logo": "/tmp/23a34d152c7c9972f787c61829c7a348.jpg",
        "Address": "98939 Borer Loaf\nWest Augustine, WY 98256",
        "Zip": "16916-",
        "City": "Leuschketown",
        "KvkNumber": null,
        "EcaboNumber": "4e0b237b-9841-3052-8"
      },
      {
        "CompanyName": "Crist, Prohaska and Pacocha",
        "Logo": "/tmp/53d1c7eb7dd16b1d1a9ec0a7019b990f.jpg",
        "Address": "97779 Grant Stravenue Apt. 753\nLake Coty, AK 67959-9158",
        "Zip": "70297-",
        "City": "Port Lelia",
        "KvkNumber": null,
        "EcaboNumber": "d612fe06-a438-32c8-a"
      },
      {
        "CompanyName": "Leuschke, Rice and Quigley",
        "Logo": "/tmp/b2e5e7c7dedf630934de260ffacaeab5.jpg",
        "Address": "13475 Nitzsche Lodge\nAlysaside, MT 85057",
        "Zip": "24897",
        "City": "East Bernice",
        "KvkNumber": null,
        "EcaboNumber": "1d160d74-6d1d-3d0d-9"
      },
      {
        "CompanyName": "Champlin Ltd",
        "Logo": "/tmp/e08399803fbbc3b361ca09942af5fc30.jpg",
        "Address": "1864 Baumbach Dam\nPort Joeyborough, VT 04166-1913",
        "Zip": "83480-",
        "City": "New Alana",
        "KvkNumber": null,
        "EcaboNumber": "626f6b9c-2681-3ad9-8"
      },
      {
        "CompanyName": "Hilpert Group",
        "Logo": "/tmp/aa142bb879e8a03df8634e87cb2e5f5e.jpg",
        "Address": "9193 Funk Alley\nMcCluretown, MO 03610-2601",
        "Zip": "32091",
        "City": "New Karentown",
        "KvkNumber": null,
        "EcaboNumber": "ec29c579-f6de-3d58-8"
      },
      {
        "CompanyName": "Conroy-McKenzie",
        "Logo": "/tmp/275dac535cb9ce031faee19309363ad5.jpg",
        "Address": "906 Shirley Wall Suite 397\nO\'Reillyfort, AL 85503-2410",
        "Zip": "49532-",
        "City": "Lake Oletaport",
        "KvkNumber": null,
        "EcaboNumber": "39dad66c-e399-319a-b"
      },
      {
        "CompanyName": "Kris, Schoen and Orn",
        "Logo": "/tmp/9ca37b175c49e2a786afc747659d91c9.jpg",
        "Address": "41106 Amelia Locks\nLavinaburgh, DC 59553",
        "Zip": "75767",
        "City": "South Melyssaside",
        "KvkNumber": null,
        "EcaboNumber": "115e3932-12b4-3fb4-b"
      },
      {
        "CompanyName": "Zemlak, Wuckert and Rosenbaum",
        "Logo": "/tmp/635c51a3cc0de11289c2997a8eba0347.jpg",
        "Address": "99847 Stiedemann Estates Suite 623\nWest Korymouth, HI 41991-1801",
        "Zip": "61771",
        "City": "Justicebury",
        "KvkNumber": null,
        "EcaboNumber": "9f2a79b9-b353-3c09-8"
      },
      {
        "CompanyName": "Bogisich, Stokes and O\'Conner",
        "Logo": "/tmp/37f259657a82c06a96affba1ac8f7940.jpg",
        "Address": "240 Mariane Rapid\nWest Effie, WA 73757-8372",
        "Zip": "26105",
        "City": "Port Caden",
        "KvkNumber": null,
        "EcaboNumber": "f27b4b43-d964-3ef0-9"
      },
      {
        "CompanyName": "Swift and Sons",
        "Logo": "/tmp/28b2223c1bb990dfb0a072054f900a9d.jpg",
        "Address": "318 Maybelle Turnpike\nSchaefermouth, OK 59036",
        "Zip": "44838",
        "City": "Homenickmouth",
        "KvkNumber": null,
        "EcaboNumber": "3ce903d4-10b3-3c9d-9"
      },
      {
        "CompanyName": "Gleichner, Mosciski and Donnelly",
        "Logo": "/tmp/fd7e0af605193766fc1f1da598886f49.jpg",
        "Address": "922 Dariana Club Apt. 822\nEast Mireille, NY 88400-0249",
        "Zip": "89335-",
        "City": "Hortensefort",
        "KvkNumber": null,
        "EcaboNumber": "05b2ed89-3568-3478-a"
      },
      {
        "CompanyName": "Schiller-Conroy",
        "Logo": "/tmp/37ad9c0d3946b50668e916ed7e5192a0.jpg",
        "Address": "4251 Mariah Knoll\nPort Shanelburgh, MT 37153-6153",
        "Zip": "37923",
        "City": "Ronaldochester",
        "KvkNumber": null,
        "EcaboNumber": "058cd122-60e3-31fd-8"
      },
      {
        "CompanyName": "Cartwright, Sanford and Morar",
        "Logo": "/tmp/cb9804f1dd41bfe137255a3fefd0264d.jpg",
        "Address": "204 Grover Roads Suite 203\nLake Hailee, HI 24534-2955",
        "Zip": "85590-",
        "City": "Ronside",
        "KvkNumber": null,
        "EcaboNumber": "cdc49e99-fb43-31e0-9"
      }
    ]
  ]
}';
          $companies = json_decode($dummy);
          dd($companies);

Comment: I don't understand what you mean. The second block of code fails the json validator.
Comment: I see what you are saying. My mistake. Yes the JSON format is invalid in the whole block. The smaller test sample in your answer passes the JSON validator but the complete string doesn't. The second block of JSON you posted also fails the validator.
Comment: Had you tested it? I make `$dummy` as string to decode it, by replace `'` to `\'`, you can change  opposite if needed.
Comment: Oh, I know what happened! @jamie post wrong format and I fix it in block 1, then he edit it. So i write block 2
Comment: @rome sorry about that! +1 for you :)

Laravel json api to webapp


Is there any package in R that's commonly used for semi-supervised learning?

Question: Is there any package in R that's commonly used for semi-supervised learning ? I have a dataset where I manually labeled 100 data points so I'd like to use semi-supervise learning for the rest of the data sets.
Answer: You can try for example the upclass package
http://cran.r-project.org/web/packages/upclass/index.html
There you will find the standard pdf reference and a vignette explaining it all along with examples. I think the function upclassify() would match your requirements.
Answer: Probably irrelevant now, but it might make the answer more complete to also mention the spa package as well. It uses a graph-based technique to learn a model. Basically it uses information from both the data point features and how similar data points are to each other. If you have a distance matrix for the data points, it might work well. This article explains it with a bit more detail and some examples. You can find the package binary files here:
https://cran.r-project.org/web/packages/spa/index.html
edited to provide some additional info about package.
Comment: Can you say anything about these? Just listing a package &/or a link is considered inadequate here.
Comment: We are trying to build a permanent repository of high-quality statistical information in the form of questions & answers. We try to avoid [link-only answers](/stats.stackexchange.com/help/how-to-answer). If possible, could you expand it, perhaps by giving a brief discussion about what's in the spa package and perhaps a comparison with the other package mentioned before.
Comment: @gung @Glen_b, done. I don't understand how the initial answer was any different however. Also, `upclass` gathers a variety of different algorithms for data classification, so comparing that to this would be somewhat apples-and-orangesish. Also, with so little info about the inquirer's dataset, there is not much more to be said.
Comment: Your answer came up in the 'low quality' review queue. Most likely, an algorithm picked it for additional scrutiny because it was short and without upvotes. I didn't see the other answer because it wasn't displayed, but you're right about it.


Condition for linear minimal polynomials

Question: I'm just wondering that there is a necessary and sufficient condition for minimal polynomials for in which cases are them linear.
Let $A$ be a square matrix. I think that $A$ has a linear minimal polynomial if and only if $A=cI$ for some $c$ constant. Furthermore, the minimal polynomial is $x-c$.
Is that true?
In that special case, if $c=0$, then $A$ is zero matrix and the minimal polynomial of $A$ is $x$.
Answer: The minimal polynomial of a matrix $A$ is a polynomial $f \ne 0$ such that: $f(A) = 0$, $f$ is monic and $f$ has minimal degree with these conditions.
Now suppose $A$ has a linear minimal polynomial $f$. Then, since $f$ is monic (by definition), $f$ has the form $f(x) = x - c$ for some constant $c$. We also have $f(A) = 0$, that is, $A - cI = 0$, hence $A = cI$. Conversely, if $A = cI$ than it has a linear minimal polynomial (do the same reasoning backwards).
So yes, it is true.


Estrutura de tabelas para calculo de transações financeiras no MySQL?

Question: Estou desenvolvendo um sistema que terá transações financeiras. Nesse sistema o usuário poderá inserir ou retirar dinheiro, poderá comprar e vender produtos, enviar dinheiro para outros usuários, e etc.
Atualmente eu tenho uma tabela de usuários que além dos dados de cadastro, contém também o saldo total de dinheiro que o usuário tem em sua carteira (wallet).
E outra tabela de transações, onde indica todas transações que foram feitas, dinheiro que entrou ou saiu da conta (in_or_out), qual referência da transação (transaction_ref) e valor (value) que foi transferido.
Segue abaixo a estrutura atual:

Meu medo é que por algum erro na transação o valor não seja somado na tabela do usuário. Ou que o usuário efetue um pagamento e o valor não seja descontado da tabela. Porque estarei sempre levando em consideração o valor do wallet do usuário como o dinheiro que ele tem em conta.
Então se ele fizer uma compra, por exemplo de R$ 1.000,00, e esse valor não for descontado da conta dele, ele ainda terá o mesmo valor para gastar, o que pode dar um prejuízo depois para a empresa ter que pagar o prejuízo do valor adicional gasto, já que com 1 milhão de usuários, ficaria difícil saber de qual usuário que deu o problema.
Daí eu pensei: em vez de fazer um total da carteira na tabela do usuário, que eu fizesse sempre uma consulta somando as transações. Aí nesse caso fico pensando, se eu tiver 1 milhão de usuários, e 1 bilhão de transações, ficaria muito pesado pra se somar o tempo todo, podendo trazer muita lentidão nas consultas do sistema.
Alguém que tenha alguma experiência com cálculos, ou sistemas parecidos, poderia me orientar uma lógica melhor para estruturar essas tabelas?
Eu não preciso que me passem os códigos de consulta e soma etc. Só preciso entender uma forma melhor de estrutura de quem tem mais experiência no assunto.
Lembrando que a estrutura atual ainda pode ser modificada de qualquer forma necessária.
Comment: comece lendo https://dev.mysql.com/doc/refman/8.0/en/commit.html
Answer: Se for feito o código certo, com transação do SGDB ligada (em MyISAM não tem transação), não tem porque ter esse medo, o banco de dados está aí para dar garantia que todas tabelas serão atualizadas ou nenhuma será (atomicidade do ACID), mantendo a consistência. Você não está lidando com NoSQL que não dá essa garantia.
Confie no banco de dados, não confie no seu código.
Se ainda preferir manter o saldo pegando das transações financeiras, e tudo estiver configurado corretamente, com índices adequados, uma consulta que pega os valores das transações para encontrar o saldo certamente será mais lenta, mas pode não ser tanto quanto imagina e poderia ser uma solução. Eu acho que a chance de cometer algum erro fazendo assim é maior.
Não existem respostas únicas e definitivas que resolvam todos os problemas, cada caso tem uma forma de resolver que se adéqua mais.
Comment: É que esse sistema também será usado em aplicativos. Com muitos usuários simultâneos. Fico com receio de por exemplo o usuário fazer uma compra e essa compra for registrada na tabela de transações, mas se der uma pequena queda no sistema no momento e não der tempo de alterar o valor da carteira na tabela do usuário.

As vezes um erro de meio segundo no sistema de hospedagem pode causar um grande prejuízo. Talvez eu nunca tenha esse tipo de problema, mas como é a primeira vez que vou fazer algo financeiro, é sempre bom perguntar pros mais experientes no assunto kkk Obrigado por responder.


Unity WebApi DbContext disposed when using InjectionConstructor, but works fine without it

Question: Repositiory, OrderRequestRepository.cs
 public OrderRequestRepository(IntranetApplicationsContext context, ILogger logger)
    {
        _context = context;
        _logger = logger;
    }

...CRUD Methods

 public void Dispose()
    {
        Dispose(true);
    }

 protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
           _context.Dispose();
        }

        GC.SuppressFinalize(this);
    }

Unity.WebApi UnityConfig.cs
 container.RegisterType<IOrderRequestRepository, OrderRequestRepository>(new InjectionConstructor(new IntranetApplicationsContext() , new ElmahLogger()));

With the above line in UnityConfig.cs the first call to the api works, the second call fails with the error :
The operation cannot be completed because the DbContext has been disposed.
If I comment out the _context.Dispose() line, then it works, which is fine as Garbage Collection will clean up for me, but ideally I'd like to manage it myself.
Alternatively, if I use the below lines instead - without the InjectionConstructor - in the UnityConfig.cs then it also works fine.
container.RegisterType<ILogger, ElmahLogger>();
container.RegisterType<IOrderRequestRepository, OrderRequestRepository>();

But I want use the InjectionConstructor as I want to add another parameter to the OrderRequestRepository Constructor and manage the disposal. Any suggestions as to why doing both causes the error?
Update
I removed the IDisposable code, as suggested by Steven, and because

The general rule is that the one who creates an object should destroy it,  so I'll leave my EF dbcontext (IntranetApplicationsContext) alone.
An IOC container (Unity.Webapi in my case) should handle disposal

So with  this line in UnityConfig
container.RegisterType<IOrderRequestRepository, OrderRequestRepository> (new InjectionConstructor(new IntranetApplicationsContext(), new ElmahLogger()));

Reads with EF are working, but interestingly when I try an edit I get the following error:

Attaching an entity of type
  'IntranetApplications.Infrastructure.Models.OrderRequest' failed
  because another entity of the same type already has the same primary
  key value. This can happen when using the 'Attach' method or setting
  the state of an entity to 'Unchanged' or 'Modified' if any entities in
  the graph have conflicting key values. This may be because some
  entities are new and have not yet received database-generated key
  values. In this case use the 'Add' method or the 'Added' entity state
  to track the graph and then set the state of non-new entities to
  'Unchanged' or 'Modified' as appropriate.

If I roll back and use the basic line in the UnityConfig
container.RegisterType<IOrderRequestRepository, OrderRequestRepository>();

...  everything works. I believe both lines are using the the same default lifetime manager, TransientLifetimeManager, so it's odd that using InjectionConstructor still seems to break things.
Answer: The problem here is that your OrderRequestRepository is disposing stuff it doesn't own. The IntranetApplicationsContext is injected into the repository and since the OrderRequestRepository has no idea what the lifestyle of that dependency is, it cannot dispose it.
You probably registered the IntranetApplicationsContext to have a per-request lifestylem while your repository is transient.
Solution: only implement IDisposable if you have anything to dispose itself. In your case that means that your repository doesn't need to IDisposable at all.
Answer: I've got around this, rather than fix the error:
I was using InjectionConstructor so I could pass multiple parameters, but as an alternative I have changed it so that I pass a single parameter, a Factory object to the repository instead.
public class OrderRequestRepository : IOrderRequestRepository
{
    private readonly IntranetApplicationsContext _context;
    private readonly ILogger _logger;

    public OrderRequestRepository(IOrderRequestRepositoryFactory respositoryFactory)
    {
        _context = respositoryFactory.CreateIntranetApplicationsContext();
        _logger = respositoryFactory.CreateLogger();
    }

    ...
}

Factory
public interface IOrderRequestRepositoryFactory
{
    ILogger CreateLogger();
    IntranetApplicationsContext CreateIntranetApplicationsContext();
}

public class OrderRequestRepositoryFactory : IOrderRequestRepositoryFactory
{
    public ILogger CreateLogger()
    {
        return new ElmahLogger();
    }

    public IntranetApplicationsContext CreateIntranetApplicationsContext()
    {
        return new IntranetApplicationsContext();
    }
}

UnityConfig
container.RegisterType<ILogger, ElmahLogger>();
container.RegisterType<IOrderRequestRepository, OrderRequestRepository>();
container.RegisterType<IOrderRequestRepositoryFactory, OrderRequestRepositoryFactory>();

This works in that, I am not using the InjectionConstructor, so don't get the associated errors and can still pass as many parameters as I want, by using my Factory.


When adding barlines in a music theory exam are all the bars supposed to be complete?

Question: Here are some samples I am working on. Either I have made a mistake or the final bar is incomplete. Is it normal in an exam to have incomplete bars at the end?
Comment: I hope the assignment makes extra clear that those are two separate examples. I can imagine plenty of students who would join the last beat of the top example and the first three beats of the second into a single measure, especially since doing so means ending with a full bar of the second excerpt.
Comment: yeah you have to just look at the letters on the left but it can be tricky
Comment: To stave off (heh) related questions about incomplete measures in "real" pieces: https://music.stackexchange.com/questions/95245/did-the-music-of-the-common-practice-period-always-end-with-a-full-measure, https://music.stackexchange.com/questions/49445/is-a-rest-required-at-the-end-of-the-final-measure-of-a-piece/49455#49455
Comment: If it were one piece I would want to know how both the key signature and time signature change inside a measure.
Comment: @Richard - it does say '*extracts*', and they're written in different keys, and there wouldn't be a new (different) time sig. for what some may consider a follow on from the first extract - which then couldn't be starting on the 1st beat - as also stated. I think we're safe!
Answer: Yes, they're literally open-ended. This means you can't necessarily work backwards, as sometimes that can help, so makes the question a touch more difficult.


randomForest::varImp VS conditional variable importance

Question: Data:

My training set consists of ~450k obs and 26 variables, out of which 1 is an ordinal factor (order_month, 12 levels) and the rest is numerical. Moreover, some of my predictors are highly correlated (Pearson's > 0.5), which is expected and sometimes intentional.
I trained a good RF model (ROC 0.96, ~90% specificity & ~90% sensitivity when tested on unseen data) and I derived Variable importance for it using varImp().

Problem:

Now, I know that having factorial and / or correlated predictors could result in biased variable selection in RF models, to which conditional inference trees (CIT) should be a remedy.
I tried to compare results of randomForest::varImp() with party::varimp(myforest, conditional=TRUE) however I get an error in the latter:

Error in model.matrix.default(as.formula(f), data = blocks) :
  term 1 would require 9e+12 columns,
suggesting that I have either too many variables or variables with too many levels.

On top of that it takes over 24hrs to run party::cforest() and running predict() on CIT model crashes my computer altogether. Given the above, I have a couple of

Questions:
1) how likely is it that I may completely misclassify the top VarImps in RF model. Is running CIT here absolutely necessary?
2) what are alternative ways of obtaining conditional variable importance if not through party::varimp()?
Big thanks for your suggestions!
Kasia
Answer: 1) how likely is it that I may completely misclassify the top VarImps in RF model. Is running CIT here absolutely necessary?
Unlikely, because you have good results from random forest, unless you biase the probabilities obtained in the predict function. Random forest is an independent model so I don't see any absolute reason to run CIT.
2) what are alternative ways of obtaining conditional variable importance if not through party::varimp()?
There are others like: extendedForest and also this set of slides should give you more information.
Note
Please note that correlated predictors could result in biased variable selection in RF is not entirely true.: Ref: Why is multicollinearity not checked in modern statistics/machine learning
Comment: thanks, @discipulus, that's reassuring. However, even though I obtained good results from RF model, I'm not sure if the Variable Importance that it throws is correct, due to the issues described in the post. I know this won't affect the predictions, but I need to present the results to lay audiences and want to make sure that I explain the predictive power of the variables correctly


Use htaccess to only allow download of files if user agent is a specific type

Question: I have a folder with some zip files in it. I want to reject all requests to download them directly unless the user agent is of the type I specify (eg. user-agent : myuseragent)
How is this possible with .htaccess file?
Rejected requests would redirect to the index file while accepted requests will download the file.
eg. if a user tried http://download.com/files/myfile.zip they would get rejected but if a script with a useragent of 'myuseragent' access the same url, it would download the file
I understand that useragents can be spoofed. It is only mild protection from having the files freely available
Comment: Please provide an example of such download URL.
Comment: Be aware that it is possible to fake `user-agent`. For example, `curl -A` and `wget -U` do that. In Safari, if you enable the Develop menu then you can select your own user agent. In Firefox, use `about:config`.
Answer: Here how you can do it using .htaccess and mod_rewrite:
Options +FollowSymLinks -MultiViews
RewriteEngine On

RewriteCond %{HTTP_USER_AGENT} !=myuseragent
RewriteRule ^files/.*$ - [F,L]

The above rule will instruct Apache to issue 403 Access Denied response for any file in /files/ folder if user agent is not equal to myuseragent.
If you want to issue 404 File Not Found response, replace [F,L] by [R=404,L].
If you want to redirect such failed requests to home page then use this rule (you can change redirect from 302 to whatever other redirect code you like):
RewriteCond %{HTTP_USER_AGENT} !=myuseragent
RewriteRule ^files/.*$ / [R=302,L]

Comment: I put this in a .htaccess file in the folder called /files/ and it allowed downloads of any file from any useragent
Comment: The rule was supposed to be placed in .htaccess in website root folder. If placed in `/files/.htaccess`, then you have to alter a rule a bit -- remove `files/` part and put full domain name instead of `/` . It is also depends how you wrote your user agent string -- does it contains spaces, case sensitive? Please provide what have you done exactly (in case if the above corrections will not work).


Why isn't my std::set sorted?

Question: I have a class to store data that looks like this:
class DataLine
{
public:
   std::string name;
   boost::posix_time::time_duration time;
   double x, y, z;

   DataLine(std::string _name, boost::posix_time::time_duration _time, double _x,
            double _y, double _z); //assign all these, not going to do it here

   bool operator < (DataLine* dataLine) { return time < dataLine->time; }
}

Then I read in a bunch of data and .insert it into a std::set of the objects:
std::set<DataLine*> data;
data.insert( new DataLine(newname, newtime, newx, newy, newz) );
//...insert all data - IS OUT OF ORDER HERE

Then I run through my data and do stuff with it while appending new elements to the set.
boost::posix_time::time_duration machineTime(0,0,0);

for(std::set<DataLine*>::reverse_iterator it = data.rbegin(); it != data.rend(); ++it)
{

    if(machineTime < (*it)->time)
    {
       machineTime = (*it)->time;
    }

    machineTime += processDataLine(*it); //do stuff with data, might add to append list below

    for(std::vector<AppendList*>::iterator iter = appendList.begin(); iter != appendList.end(); ++iter)
    {
        data.insert( new DataLine( (*iter)->name, machineTime,
                                  (*iter)->x, (*iter)->y, (*iter)->z); );

    }
}

When I try to loop through the set of data both before and after inserting the elements all my data is out of order! Here are some times outputted when looped using
for(std::set<DataLine*>::iterator it = data.begin(); it != data.end(); ++it)
{
   std::cout << std::endl << (*it)->time;
}

14:39:55.003001
14:39:55.003002
14:39:55.001000
14:39:59.122000
14:39:58.697000
14:39:57.576000
14:39:56.980000

Why aren't these times sorted in order?
Comment: A pointer is (!) object.
Answer: It is sorted. It's sorted based on the data type you're storing in the set, which is a pointer to a DataLine. In other words, it'll sort according to the location in memory of your objects which is probably creation order (but may not be, depending on how the memory allocation functions work in your implementation).
If you want to sort based on the DataLine type itself, don't use a pointer. Store the objects themselves.
You can see a similar effect from the following code which creates two sets. The first is a set of integer pointers, the second a set of actual integers:
#include <iostream>
#include <iomanip>
#include <set>
using namespace std;

int main (void) {
    set<int*> ipset;
    set<int> iset;

    cout << "inserting:          ";
    for (int i = 0; i < 10; i++) {
        int val = (i * 7) % 13;
        cout << ' ' << setw(2) << val;
        ipset.insert (new int (val));
        iset.insert (val);
    }
    cout << '\n';

    cout << "integer pointer set:";
    for (set<int*>::iterator it = ipset.begin(); it != ipset.end(); ++it)
        cout << ' ' << setw(2) << **it;
    cout << '\n';

    cout << "integer set:        ";
    for (set<int>::iterator it = iset.begin(); it != iset.end(); ++it)
        cout << ' ' << setw(2) << *it;
    cout << '\n';

    cout << "integer pointer set pointers:\n";
    for (set<int*>::iterator it = ipset.begin(); it != ipset.end(); ++it)
        cout << "   " << *it << '\n';
    cout << '\n';

    return 0;
}

When you run that code, you see something like:
inserting:            0  7  1  8  2  9  3 10  4 11
integer pointer set:  0  7  1  8  2  9  3 10  4 11
integer set:          0  1  2  3  4  7  8  9 10 11
integer pointer set pointers:
   0x907c020
   0x907c060
   0x907c0a0
   0x907c0e0
   0x907c120
   0x907c160
   0x907c1a0
   0x907c1e0
   0x907c220
   0x907c260

You can see the unordered way in which values are added to the two sets (first line) and the way the pointer set in this case matches the order of input (second line). That's because the addresses are what's being used for ordering as you can see by the fact that the final section shows the ordered addresses.
Although, as mentioned, it may not necessarily match the input order, since the memory arena may be somewhat fragmented (as one example).
The set containing the actual integers (as opposed to pointers to integers) is clearly sorted by the integer value itself (third line).
Answer: You need to define member operator < like below, and save objects in std::set instead of raw pointers. Because for raw pointers, the default comparision criteria is based on the pointer value itself.
bool operator < (const DataLine &dataLine) const
{
   return time < dataLine.time;
}

...
std::set<DataLine> data;

Comment: You are right; you cannot overload built-in operators for pointer types. So to use your own comparison for a set of pointers, you have to create a functor class and pass it as the second template argument to `std::set`.
Comment: And insert objects instead of pointers into the set... Or define a free function to compare the pointers.
Comment: @Nemo, Are you sure you can define a free global function to override the behavior of comparing two raw pointers? See here: http://msdn.microsoft.com/en-us/library/zy7kx46x.aspx

Why isn't my std::set sorted?


Python 3 change turtle pen brightness

Question: I am trying to generate random noise, and draw it on the screen, but I need the turtle's pen to be able to change the brightness
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: Your best bet is probably varying your color between white (or whatever background you are using) and the "brightest" you want to display. For example, if you want your bright color to be green, your RGB color code would be (0,255,0). The RGB color code for white is (255,255,255). So to vary "brightness", you would simultaneously change the red and blue channels between 0 for as bright as possible and 255 for as dim as possible.
If you want say 100 levels of brightness, you can use the linspace function from numpy (https://numpy.org/doc/stable/reference/generated/numpy.linspace.html) to get an array of values that are equally spaced out.
import numpy as np
color_range = np.linspace(255, 0, 100)
# color_range will be a np array of length 100 where color_range[0] = 255.0
# and color_range[99] = 0.0

# now we can create a list of colors from least bright to most bright
colors = [(int(i),255,int(i)) for i in color_range]
# colors[0] will be (255, 255, 255) which is white
# colors[99] will be (0, 255, 0) which is green

Answer: You could use the colorsys library to convert between a color model that supports brightness, we'll use HSV below, and the RGB colors that turtle uses.  Here's a gradient example:
from colorsys import hsv_to_rgb
from turtle import Screen, Turtle

WIDTH, HEIGHT = 100, 100
CURSOR_SIZE = 20

screen = Screen()
screen.setup(WIDTH, HEIGHT)
screen.setworldcoordinates(0, HEIGHT, WIDTH, 0)
screen.tracer(False)

turtle = Turtle()
turtle.hideturtle()
turtle.shape('square')
turtle.shapesize(1 / CURSOR_SIZE)
turtle.penup()

for y in range(HEIGHT):
    turtle.goto(0, y)

    for x in range(WIDTH):
        value = x * y / (WIDTH * HEIGHT)
        rgb = hsv_to_rgb(0.0, 1.0, value)
        turtle.color(rgb)
        turtle.stamp()
        turtle.forward(1)

screen.update()
screen.exitonclick()

OUTPUT

where all the colors are different brightnesses of red.  To generate noise, we can import the random() function from the random library, and change the value assignment to:
value = random()

(ENLARGED) OUTPUT
Comment: When I try to implement your code, it gives me this error:
NotImplementedError: colorsys is not yet implemented in Skulpt on line 1 in main.py
Comment: @JacobMorrison, since Skulpt doesn't include the library colorsys.py, you can go to  [its source code](https://github.com/python/cpython/blob/3.9/Lib/colorsys.py) and copy the definition of the `hsv_to_rgb()` function into your own code as it is completely self-contained.  And remove the `import`.

Python 3 change turtle pen brightness


Nema 5-20 Female to Nema 5-15 Male Power Adapter for UPS: safe?

Question: I bought a large UPS for my server and didn't realize it comes with a NEMA 5-20 plug. We're in a residential setting and don't have those outlets. I see Nema 5-15/20 Female to Nema 5-15 Male Power Adapters but it seems not safe to me, if the device is expecting a dedicated 20 amp circuit. This is the UPS:
https://www.cdw.com/product/cyberpower-smart-app-online-ups-series-ol2200rtxl2u-ups-1.8-kw-2200-v/3059881?pfm=srh
is it safe to use an adapter and plug it into a residential circuit?
Comment: You may get better quality responses over at https://diy.stackexchange.com/  A bunch of electrician-type people hang around and answer questions related to home wiring and safety (among other things diy/home improvement related)
Comment: Your circuit breaker needs to stay below what the cables and plugs can handle, as long as you don't load the UPS with more than what the breaker can handle you are still good. But be careful with dodgy outlets if you put high load on them.
Answer: I wouldn't do it - you can plug a standard 15A plug into a 20A socket, but going through an adapter to "downgrade" from 20A to 15A seems incredibly unwise, at the very least.
It's akin to using the grounding/non-grounding adapter to utilize a three-prong plug in an old-style two-prong outlet.
Either:

get a UPS with the proper plug for your outlet, or
get an electrician to rewire the outlet and associated circuit breaker to a 20A (presuming the wall wiring can handle it)

I'd lay heavy odds CyberPower will not honor their attached equipment guarantee if you've done something janky to get it connected to the wall :)
Comment: Using a 20A max rated device in a 15A rated outlet with a 15A fuse is safe, but might give issues if you try to pull more than the 15+A.
In the US a manufacturer can not void warranty based on what you do with the device, unless they can prove that what you did actually caused the issue.
Comment: @NiKiZe - I didn't say they'd void the warranty, I said they'd not honor the attached equipment guarantee if you've done something unsupported :)
Answer: There is no problem with safety, as long as the adapter is of good quality. The 5-15 outlet will be fused 15 A, which is about the same as the maximum current draw for this UPS. It depends on the characteristics of the UPS and the total power consumption of your servers, if the fuse will blow or not, so it's not the best solution. Doesn't cost much to try tho'.
It might be that the UPS a bit of an overkill for your server size, since it is designed for a higher current than what you have available.