Binary Search with strings in C

Question: I have implemented this binary search algorithm with the goal of finding a desired char contained in an array. I've tried doing the 'if' 'else' comparisons the standard way, considering the ASCII table: [ if ( searchElement > arrayChar[mid] ... etc ]. That didn't seem to work, so I realized that maybe it had something to do with string comparisons. I'm now using the function strcmp and using its returned value to compare:
(If string1 < string2 -> negative value. If string1 > string2 -> positive value. If string1 == string2 -> 0. )
which it doesn't seem to be working as well.
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <string.h>

int binarySearch(int arraySize, char arrayChar[]) {

    // Variable declaration;
    char searchElement[2];
    int startingPoint = 0, endingPoint = arraySize - 1;

    // Input for desired search element;
    printf("\nSearch for: ");
    scanf(" %c", &searchElement);

    while (startingPoint <= endingPoint) {
        int mid = (startingPoint + endingPoint) / 2;
        if (strcmp(searchElement, arrayChar[mid]) == 0) {
            return mid;
        }
        else if (strcmp(searchElement, arrayChar[mid]) < 0)
            endingPoint = mid - 1;
        else {
            if (strcmp(searchElement, arrayChar[mid]) > 0)
                startingPoint = mid + 1;
        }
    }
    return -1;
}

int main() {

    // Array declaration;
    char randomCharArray[7] = {'a', 'c', 'e', 'f', 'f', 'g', 'h'};

    // Calling  binarySearch() ;
    if (binarySearch(6, randomCharArray) == -1) printf("Element not found!");
    else printf("Element found in [%d] .", binarySearch(6, randomCharArray));

    return 1;

}

Comment: Reading with `%c` does not ensure that `searchElement[1] == '\0'`.  And string comparisons depend on null-terminated strings.  But since you're pass `arrayChar[mid]` to `strcmp()`, you're passing a character, not a string.  In fact, you should replace the calls to `strcmp()` with `if (searchElement == arrayChar[mid])`, etc because you are comparing single characters, not strings.
Answer: You seem to be having trouble with the distinction between individual char values and strings, which are contiguous sequences of char values ending with one having value 0.  Pairs of individual char values can be compared with the standard relational and equality-test operators (<, >, ==, etc.).  Pairs of strings can be compared via the strcmp() function.  Individual chars cannot be directly compared with strings, and you don't have strings anyway because neither the contents of binarySearch()'s searchElement nor the contents of main()'s randomCharArray are null-terminated.
That leads me to suggestion 1: make searchElement a char, not an array, since you know you need it to represent a single char only:
char searchElement;

Having done that, you can now (suggestion 2) compare the value of searchElement to elements of arrayChar via the standard operators, as you say originally tried to do.  For example,
    // with 'searchElement' as a char, not a char[]:
    if (searchElement == arrayChar[mid]) {

Alternatively, if you kept searchElement as an array then you could use searchElement[0] to access its first char for comparison.

Binary Search with strings in C


Neural network unable to predict

Question: Data (CSV): https://easyupload.io/firqeg
I'm trying to predict the last column of this data (binary) from the remaining columns. For this, I'm using neural networks (more to experiment with them at this point).
Some code follows, just to be transparent with what I'm doing but I also explain it to make it clear that this is not a coding question as the code works just fine. I'm using python.
I've scaled the cells using sklearn preprocessing:
min_max_scaler = preprocessing.MinMaxScaler()
X_scale = min_max_scaler.fit_transform(X)

I've split the data into a training set, validation set and testing set:
from sklearn.model_selection import train_test_split
X_train, X_val_and_test, Y_train, Y_val_and_test = train_test_split(X_scale, Y, test_size=0.3)
X_val, X_test, Y_val, Y_test = train_test_split(X_val_and_test, Y_val_and_test, test_size=0.5)

I'm using a model of 2 hidden layers and 32 neurons in each:
model = Sequential([
    Dense(20, activation='relu', input_shape=(22,)),
    Dense(20, activation='relu'),
    Dense(1, activation='sigmoid'),])

model.compile(optimizer='sgd',
              loss='binary_crossentropy',
              metrics=['accuracy'])

hist = model.fit(X_train, Y_train,
                 batch_size=32, epochs=100,
                 validation_data=(X_val, Y_val))

However the model never reaches any accuracy nor loss: https://prnt.sc/qzxmfe
Is the problem that there is missing data? Too many variables per observations? All insight appreciated!
EDIT: It's not too many variables as I reduced it to 3 variables that explain it well in a regression and get the same results.
Comment: What does it mean that it never reaches "any accuracy nor loss"? Do you mean that the accuracy/loss is very low, or that it is `NaN` or something else?
Comment: Explanatory picture: https://prnt.sc/qzxmfe
Comment: I should add I attempted with only 3 variables that do predict the dependent variable in a regression and get the same results so I'm wondering what's wrong with running a neural network on it.
Answer: This happens because your data contains missing values. For example, minimum of np.array([np.nan, 10, -4.5]) is nan, and likewise the maximum. Any sum or difference of nan is also nan.
Dividing by nan yields nan, so all of  your data values are nan where the feature contains at least 1 nan value.
You need to somehow fix your missing values. The preferred method is imputation. A bad option is deleting any values that are nan, or filling with some constant (like zero, the mean,  or the median).
Comment: Thank you, quick and concise with options on how to remedy.

Neural network unable to predict


Padronização de tabela

Question: Nessa tabela existem a descrição de 5 rodadas, gostaria de saber como definir uma rodada especifica pra colocar no site, por exemplo toda vez que abro a página sempre vai estar na rodada 1, para ir para as demais eu clico com a seta pra frente, porém gostaria que eu escolhesse a rodada a começar, colocaria tipo a 3 e depois poderia ir pra frente ou voltar com as setas.
Outro item seria o css, pois em cada rodada as células ficam de tamanhos diferentes, queria que todas tivessem o tamanho padrão para todas as rodadas.
Comment: Dei upvote porque você tinha 2 downvotes e nenhuma justificativa pra tal, o que é ridículo.
Answer: Para estabelecer rodada ativa bastaria utilizar o seguinte código:
// Estabelece que que a rodada atual é a décima rodada
var inRodada = 10;
var $rodadas = $('.rodadas .rodada').removeClass('active');
// O -1 é necessário porque o vetor de rodadas começa em 0
$rodadas.eq(inRodadav - 1).addClass('active');

e para fazer com que todas as rodadas tenham a mesma largura basta especificar o atributo width nas TD e TH.

Update: Segue abaixo um exemplo de como as tabelas ficariam com os tamanhos fixados.

$(document).ready(function() {

  // Estabelece que que a rodada atual é a décima rodada
  var inRodada = 2;
  var $rodadas = $('.rodadas .rodada').removeClass('active');
  // O -1 é necessário porque o vetor de rodadas começa em 0
  $rodadas.eq(inRodada - 1).addClass('active');

  $('.go').on('click', function(event) {
    event.preventDefault();

    var dir = parseInt($(this).data('go'));
    var $active = $('.rodadas .rodada.active');

    $('.wrapper .go').prop('disabled', false);

    if (dir == 1) {
      var $f = $active.next();
      $(this).prop('disabled', ($f.next().length == 0));
    } else {
      var $f = $active.prev();
      $(this).prop('disabled', ($f.prev().length == 0));
    }

    $active.removeClass('active');

    $f.addClass('active');

  });

});
<link href="http://files.saichorao.com.br/200000756-1d8ae1f3a7/rodadacss.css" rel="stylesheet" />

    <button class="prev random-button animate go" data-go="-1">Anterior</button>
    TABELA
    <button class="next random-button animate go" data-go="1">Próxima</button>

            1º RODADA

            CASA
            PONTOS
            X
            PONTOS
            FORA

            Teste 1
            65,93
            X
            61,39
            Teste 2

            Teste 3
            60,13
            X
            74,70
            Teste 4

            Teste 5
            79,98
            X
            46,15
            Teste 6

            Teste 7
            66,48
            X
            75,13
            Teste 8

            Teste 9
            81,02
            X
            52,94
            Teste 10

            Teste 11
            68,84
            X
            64,34
            Teste 12

            Teste 13
            52,84
            X
            65,12
            Teste 14

            Teste 19
            48,44
            X
            92,45
            Teste 20

            Teste 15
            57,04
            X
            100,94
            Teste 16

            Teste 17
            73,54
            X
            29,54
            Teste 18

            2º RODADA

            CASA
            PONTOS
            X
            PONTOS
            FORA

            Teste 16
            63,69
            X
            29,32
            Teste 18

            Teste 2
            57,24
            X
            42,02
            Teste 4

            Teste 11
            57,89
            X
            65,26
            Teste 5

            Teste 12
            56,39
            X
            32,29
            Teste 15

            Teste 17
            83,39
            X
            44,19
            Teste 13

            Teste 10
            47,34
            X
            79,52
            Teste 19

            Teste 14
            84,79
            X
            55,86
            Teste 1s

            Teste 6
            40,86
            X
            60,36
            Teste 7

            Teste 20
            54,46
            X
            59,96
            Teste 3

            Teste 8
            51,36
            X
            76,34
            Teste 9

            3º RODADA

            CASA
            PONTOS
            X
            PONTOS
            FORA

            Teste 19
            93,33
            X
            90,23
            Teste 12

            Teste 15
            67,43
            X
            88,83
            Teste 2

            Teste 1
            76,63
            X
            23,26
            Teste 6

            Teste 13
            52,13
            X
            55,83
            Teste 16

            Teste 5
            79,83
            X
            86,03
            Teste 20

            Teste 8
            70,25
            X
            58,30
            Teste 17

            Teste 3
            88,33
            X
            71,23
            Teste 10

            Teste 9
            75,65
            X
            75,33
            Teste 14

            Teste 4
            77,63
            X
            93,33
            Teste 7

            Teste 18
            91,75
            X
            60,33
            Teste 11

            4º RODADA

            CASA
            PONTOS
            X
            PONTOS
            FORA

            Teste 12
            19,31
            X
            26,22
            Teste 10

            Teste 20
            14,09
            X
            17,27
            Teste 15

            Teste 6
            41,44
            X
            24,29
            Teste 18

            Teste 11
            25,01
            X
            24,50
            Teste 17

            Teste 16
            30,51
            X
            11,92
            Teste 19

            Teste 4
            31,21
            X
            63,08
            Teste 8

            Teste 7
            43,97
            X
            34,38
            Teste 9

            Teste 2
            20,31
            X
            38,00
            Teste 13

            Teste 1s
            42,29
            X
            14,59
            Teste 5

            Teste 14
            25,09
            X
            30,29
            Teste 3

            5º RODADA

            CASA
            PONTOS
            X
            PONTOS
            FORA

            Teste 17
            84,86
            X
            54,24
            Teste 1

            Teste 19
            43,36
            X
            64,46
            Teste 11

            Teste 5
            67,36
            X
            72,06
            Teste 13

            Teste 3
            46,10
            X
            39,37
            Teste 6

            Teste 7
            49,44
            X
            84,46
            Teste 12

            Teste 16
            60,46
            X
            45,47
            Teste 20

            Teste 18
            51,80
            X
            48,20
            Teste 15

            Teste 10
            45,85
            X
            36,70
            Teste 8

            Teste 2
            68,56
            X
            60,15
            Teste 14

            Teste 9
            57,94
            X
            54,84
            Teste 4

Comment: @LeandroSantosOliveira Seu exemplo ficou offline coloca online denovo por gentileza
Comment: Exemplo atualizado
Comment: Felipe, teria como fazer e postar? Sou bastante iniciante e tudo faço "chutando", ás vezes da certo ou não e essas explicações suas não sei aonde ao certo colocar.
Comment: Mais alguém poderia ajudar?
Comment: Feito... Online novamente!
Comment: Obrigado pelo seu tempo dispensando em nos ajudar... Agora perfeito! Imagine a felicidade em ver que tudo deu certo.

Padronização de tabela


Prenex normal form of $\neg \big(\forall x \ P(x) \vee \forall x \ Q(x) \big)$

Question: I have the statement $\neg \big(\forall x \ P(x) \vee \forall x \ Q(x) \big)$ and I have to write it in prenex normal form.
First I use the second De Morgan law
$\neg \big(\forall x \ P(x) \vee \forall x \ Q(x) \big) \equiv \neg \forall x \ P(x) \wedge \neg \forall x \ Q(x)$
Then I use the second De Morgan law for quantifiers
$\neg \forall x \ P(x) \wedge \neg \forall x \ Q(x) \equiv \exists x \ \neg P(x) \wedge \exists x \ \neg Q(x)$
Now I can write it in prenex normal form but I made it in two different ways
$\exists x \ \neg P(x) \wedge \exists x \ \neg Q(x) \equiv \exists x \exists y \big( \neg P(x) \wedge \neg Q(y) \big)$
and
$\exists x \ \neg P(x) \wedge \exists x \ \neg Q(x) \equiv \exists x \big( \neg P(x) \wedge \neg Q(x) \big)$
Which one is correct/wrong and why?
Comment: The last one is false because you can find interpretations for $P$ and $Q$ such that the statements aren't equivalent. Think of real life examples of this, if necessary. To prove the first one, people need to know what rules you have available or if an informal argument is enough.
Comment: See [this](http://math.stackexchange.com/questions/1053318/pre-nex-normal-form-correct-way-to-distribute-negations-among-quantifiers) and [this](http://math.stackexchange.com/questions/1051988/is-the-order-of-four-quantifiers-in-a-predicate-formula-relevant) for similar problems.
Comment: I see but I can't really figure it out which relation there are to this?
Answer: The former formula is the correct statement.
$\exists X \,(\lnot P(X)) \land \exists X \, (\lnot Q(X))$
$\lnot P(x) \land \exists X \, (\lnot Q(X))$ by existential instantation
$\exists X \, \left[\lnot P(X)  \land \exists X \, (\lnot Q(X))\right]$ by existential generalization
note that we cannot apply existential generalization to the wff $\lnot P(X)  \land \exists X \, (\lnot Q(X))$ because $X$ appears free.
However if we rename:
$\exists X \, \left[\lnot P(X)  \land \exists Y \, (\lnot Q(Y))\right]$
we no longer have the above mentioned problem. So from here it is not hard to show that we have
$\exists X \, \exists Y\,(\lnot P(X)  \land \lnot Q(Y))$


Sum of cosines using imaginary exponentials

Question: Using trigonometry, one can easily establish that
$$\cos (\omega_1 t) + \cos (\omega_2 t) = 2 \cos \left[(\omega_1 - \omega_2) t/2\right] \cos \left[(\omega_1 + \omega_2) t/2\right]$$
But can we exploit $$\exp(i \theta) = \cos \theta + i \sin \theta$$
to arrive at the same answer using complex exponential form, i.e. starting from:
$$ \exp(i\omega_1 t) + \exp(i\omega_2 t) $$
and WITHOUT USING ANY TRIGONOMETRIC FORMULA?
Comment: You need to edit the first statement which is incorrect. There should be a factor of $\frac 12$ in the arguments
Comment: http://mathworld.wolfram.com/ProsthaphaeresisFormulas.html
Comment: @DavidQuinn - Thanks for pointing out the mistake. Just made the edit.
Answer: HINT:
$$e^{2iA}+e^{2iB}=e^{i(A+B))}\left(e^{i(A-B))}+e^{-i(A-B))}\right)$$
Now use Euler identity $e^{ix}=\cos x+i\sin x$  and subsequently, $$e^{i(A-B))}+e^{-i(A-B))}=2\cos(A-B)$$
Comment: Thanks a lot. One of those things that just don't occur to you at times!
Answer: Of course you can:
$$ \cos (\omega_i t ) = \frac{e^{ i \omega_i t} + e^{-i \omega_i t}}{2} $$
Therefore:
$$ \begin{aligned} \cos (\omega_1 t ) + \cos (\omega_2 t) &= \frac{e^{ i \omega_1 t} + e^{-i \omega_1 t}}{2} + \frac{e^{ i \omega_2 t} + e^{-i \omega_2 t}}{2} \\ &= \frac{1}{2} \left [ e^{ i\frac{\omega_1 + \omega_2}{2} t} \left ( e^{ i\frac{\omega_1 - \omega_2}{2} t} + e^{ -i\frac{ \omega_1 - \omega_2 }{2} t } \right ) + e^{-i \frac{\omega_1 + \omega_2}{2} t} \left ( e^{ i\frac{\omega_1 - \omega_2}{2} t} + e^{ -i\frac{ \omega_1 - \omega_2 }{2} t } \right )  \right ] \\ &= \frac{1}{2} \left [ \left ( e^{ i\frac{\omega_1 + \omega_2}{2} t} + e^{ -i\frac{ \omega_1 + \omega_2 }{2} t } \right ) \cdot  \left ( e^{ i\frac{\omega_1 - \omega_2}{2} t} + e^{ -i\frac{ \omega_1 - \omega_2 }{2} t } \right ) \right ] \\ &= 2 \cos \left ( \frac{\omega_1 + \omega_2}{2} t \right ) \cos \left ( \frac{\omega_1 - \omega_2}{2} t \right )\end{aligned} $$


svn check out using C# program

Question: I am writing a small utility to execute svn commands using c# program
Here is the key line in my program
System.Diagnostics.Process.Start("CMD.exe", @"svn checkout C:\TestBuildDevelopment\Code");
As I assume, the above code should be able to do svn check out and download all the code to the local path mentioned above. But what's happening is that, the command prompt opens up with the default path of the c# project and does nothing.
If I run this svn command in command line it works fine. But when I run using C# it just pops up the command prompt without executing the svn checkout operation. Any idea on what is going wrong?
Comment: Have you considered using [`svnsharp`](http://code.google.com/p/svnsharp/) instead?
Comment: @JonSkeet svnsharp is great!!! I downloaded the dll and good to go now. Thanks a lot. I should mark this as the best answer. Eventhough there are some acceptable answers below, this is the best answer. But how can I mark this as accepted.
Comment: This is very old... nowadays, there is also SharpSVN:
 https://sharpsvn.open.collab.net
Answer: You don t have to run CMD.exe. CMD.exe ist just a program that calls other assemblies.
You can call svn.exe directly with your argument checkout ... (but isnt there a url missing?)
Process.Start("svn.exe", @"checkout C:\TestBuildDevelopment\Code");

you may also try this:
Process proc = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.RedirectStandardOutput = true;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "svn.exe";
startInfo.CreateNoWindow = true;
startInfo.Arguments = "checkout ...";

proc.StartInfo = startInfo;
if(proc.Start()) {
    proc.WaitForExit();
}

Answer: You need to add the parameter /c. Try:
Process.Start("CMD.exe", @"/c svn checkout C:\TestBuildDevelopment\Code");

The parameter /c means that the cmd should execute the command and exit.
Answer: As Jon notes, svnsharp would be a good choice here; but IMO the problem is shelling cmd.exe, rather than the exe you actually want to run:
Process.Start(@"path\to\svn.exe", @"checkout ""C:\TestBuildDevelopment\Code""");

although a ProcessStartInfo would make it easier to set the working path etc.

svn check out using C# program


Devise broke by itself? /users/edit goes to 404

Question: When clicking on the User Profile link edit_user_registration_path (http://localhost:3000/users/edit) which used to work yesterday. Today goes to a 404 error that looks like this.
    Routing Error

    No route matches {:controller=>"devise/ideas"}
    Try running rake routes for more information on available routes.

I checked rake routes and I get
           like_idea GET    /ideas/:id/like(.:format)      ideas#like
        comment_idea POST   /ideas/:id/comment(.:format)   ideas#comment
               ideas GET    /ideas(.:format)               ideas#index
                     POST   /ideas(.:format)               ideas#create
            new_idea GET    /ideas/new(.:format)           ideas#new
           edit_idea GET    /ideas/:id/edit(.:format)      ideas#edit
                idea GET    /ideas/:id(.:format)           ideas#show
                     PUT    /ideas/:id(.:format)           ideas#update
                     DELETE /ideas/:id(.:format)           ideas#destroy
    new_user_session GET    /users/sign_in(.:format)       devise/sessions#new
        user_session POST   /users/sign_in(.:format)       devise/sessions#create
destroy_user_session GET    /users/sign_out(.:format)      devise/sessions#destroy
       user_password POST   /users/password(.:format)      devise/passwords#create
   new_user_password GET    /users/password/new(.:format)  devise/passwords#new
  edit_user_password GET    /users/password/edit(.:format) devise/passwords#edit
                     PUT    /users/password(.:format)      devise/passwords#update
cancel_user_registration GET    /users/cancel(.:format)        devise/registrations#cancel
   user_registration POST   /users(.:format)               devise/registrations#create
new_user_registration GET    /users/sign_up(.:format)       devise/registrations#new
edit_user_registration GET    /users/edit(.:format)          devise/registrations#edit
                     PUT    /users(.:format)               devise/registrations#update
                     DELETE /users(.:format)               devise/registrations#destroy
                root        /                              home#index

Which looks about right one can see the correct route for edit_user_registration_path
I'm new to Ruby so any help will be greatly appreciated.
Answer: It's not your edit_user_registration_path that is the problem.
If you look at the error message, Rails is looking for an ideas_controller in the devise folder (ie "devise/ideas"). If you don't have a controller there, it means that somewhere you are calling an incorrect path.
Answer: edit_user_registration_path require user id.
So you need something like edit_user_registration_path(@user)
Comment: I had tried that from another answer I found here. Makes no difference. :(
Comment: Interesting, if I do `<%= debug @user %>` I get

    ---
    ...

Which could explain why it's not working, I wonder why though.
Comment: I disagree. if you run `bin/rake routes | grep edit_user_registration` you see that this route does not require an `:id` param (As of devise 3.2 .. 4.2).


retornar dados de um select no modal

Question: Faço insert, update e select com o modal. Quando faço editar carrega os dados retornados nos inputs, na checkbox, nos textarea, mas nos select não carrega a informação.
Código onde consulto os dados e crio o botão editar:
$result = mysqli_query($conn, $query);
$output;
while($row = mysqli_fetch_array($result))
 {
   $output .= '

         <form id="insert_form">

                     Código Utente

                        <input type="text" id="codigo1" name="codigo" value="'.$row["codigo"].'" class="form-control" readonly="true"/>

                     Dependência

                        <input type="text" id="dependencia2" name="dependencia" value="'.$row["Dependencia"].'" class="form-control" readonly="true"/>

                 <button type="button" class="btn btn-danger" data-dismiss="modal">Cancelar</button>
                 Editar

             </form>
             ';
         }

      $output;
     echo $output;
    }

Para enviar os dados para o form do modal para editar faço-o desta forma:
$(document).on('click', '.edit_data', function(){
 var employee_id = $(this).attr("Id");
   $.ajax({
        url:"./fetchutente",
        method:"POST",
        data:{employee_id:employee_id},
        dataType:"json",
        success:function(data){
          $('#codigo').val(data.codigo);
          $('#dependencia1').val(data.Dependencia);
          $('#employee_id').val(data.Id);
          $('#insert').val("Gravar");
          $('#add_data_Modal').modal('show');
          }
      });
    });

O form do modal que abre para editar:
<form id="formulario">

          Código Utente

            <input type="text" class="form-control" id="codigo" name="codigo" placeholder="Código Utente" required="">

          Dependência

            <select class="form-control" name="dependencia" id="dependencia1" placeholder="Dependência" required="">
               <option></option>
               <?php
               $sql = "SELECT * FROM raddb.Dependencia ORDER BY Discricao ASC";
               $qr = mysqli_query($conn, $sql);
               while($ln = mysqli_fetch_assoc($qr)){
               echo '<option value="'.$ln['Id'].'">'.$ln['Discricao'].'</option>';
               }
               ?>
            </select>

</form>

Mas como mostro na imagem, carrega a informação do input com o código, mas o select com name=dependencia, fica em branco:

Também tentei assim, mas também não carrega a informação vinda do json:
$('select[name="dependencia"]').val(data.Dependencia);

Comment: então ai que está o problema, você tem que setar esse `select` através do `val=""` dos `options` e não pela descrição.
Comment: você já deu um `console.log` nesse `data.Dependencia` para ver se está retornando alguma coisa?
Comment: esse `$('select[name="dependencia"]').val();` seta pelo valor do `option` e não pelo conteúdo  texto dentro do `option` html
Comment: @William na consola retorna o valor correto, só não carrega o valor no select
Comment: esse `data.Dependecia` retonar um número ou um texto?
Comment: @William retorna texto
Answer: Ao invés de fazer isso:
$('select[name="dependencia"]').val(data.Dependencia);

Você teria que fazer isso
$('select[name="dependencia"]').val(data.DependenciaId);

para que ele possa achar o um option dentro do seu select com o mesmo valor que você quer setar
Comment: já resolvi o problema, o problema estava na query que está no `/fetchutente` que retornava no json
Comment: quando faço `insert` no `Id é número e quando carrego o form para fazer o `update` retorna texto. Será por causa disso que continua sem carregar a informação?
Comment: @Bruno na verdade o correto seria depois que você fizesse esse `insert` e retornasse esse `id`, você fizesse um `select` para pegar os dados já atualizado, mas poste o seu código que está no `/fetchutente.`  para podermos ver melhor o que você está tentando fazer.

retornar dados de um select no modal


Pass multiple ids as Views Arguments in the Rule action Save PDF as file on server

Question: I'm using views PDF to print out a list of nodes on a single PDF, one per page.
Now I have more than 1000 nodes/pages on a single generated pdf, so I'm trying to use VBO and Rules to create a view where I can filter/select the nodes I need and execute a Rule component that saves the resulting pdf on the server and sets a field "printed" to "yes" on those nodes.
The problem is that every time I fire my Rule the saved PDF has just the last selected node via VBO.
On the "Views Arguments" of the "Save PDF as file on server" action, instead of [node:nid] I've tried writing manually some node ids (eg. 1,2,3...)  and it works fine: the saved PDF has all the written nodes printed out.
Probably I have to write some PHP code to print the VBO-passed ids as a single csv argument.
I've tried something like this and doesn't work, blank pdf page. How to debug?
<?
$vboNids=arg(1);
echo implode(",",$vboNids);
?>

Thanx in advance.
Comment: In your contextual filters did you check box the argument for allowing multiple arguments in the URL?
Comment: Yes, sure.
If I test the VBO view with "pass ids as arguments to a page" with my PDF page display as destination, it opens the pdf correctly with just the nodes selected printed out.
It works, but my users need to save the file manually, while I need it to be saved on the server and change
If I test my own rule by passing integers  writing them in the arguments of "Save PDF as file on server", the resulting pdf is correct, but I need it to take the vbo ids.
Answer: If I would like to save those files using vbo then I would try to create drupal action in your own module. And in this case you wouldn't need rules. Or you could revoke rules event if you would want to with rules_invoke_event function;
function mymodule_action_info() {
  return array(
    'dosomethinggoodfunction' => array(
      'type' => 'node',
      'label' => t('Do something'),
      'configurable' => FALSE,
      'triggers' => array('node_save'),
    ),
  );
}
function dosomethinggoodfunction($node) {
  // function to do some good stuff.
}

Comment: Thanx, I can try this. I'm a noob and I think it will take me almost one week to learn how to code actions.
It could be great if it can be done through the UI instead, just because I've already done the most part -or I think so.
I'm still trying to create a loop in the rule where concatenate nids incrementally in a string, then, outside the loop, pass it to my arguments...
But surely there's an easier way... An already done variable...


why am i getting this error in compiling programme?

Question: i am trying to compile c file in linux OS but i'm getting so many errors.
I searched it on internet and found solution that is to install mingw-w64. I installed but getting the same error.
here is my first.c file :
#include<stdio.h>

int main()
{
 printf("Hello world");
 return 0;
}

here what i got after compiling :
┌──(rootkali)-[/home/dj/Desktop/c/graphics]
└─# gcc first.c -o output                                                                                1 ⚙
In file included from /usr/local/include/corecrt.h:10,
                 from /usr/local/include/corecrt_stdio_config.h:10,
                 from /usr/local/include/stdio.h:9,
                 from first.c:1:
/usr/local/include/_mingw.h:272:2: error: #error Only Win32 target is supported!
  272 | #error Only Win32 target is supported!
      |  ^~~~~
In file included from /usr/local/include/corecrt.h:10,
                 from /usr/local/include/corecrt_stdio_config.h:10,
                 from /usr/local/include/stdio.h:9,
                 from first.c:1:
/usr/local/include/_mingw.h:580:14: error: expected '=', ',', ';', 'asm' or '__attribute__' before '__debugbreak'
  580 | void __cdecl __debugbreak(void);
      |              ^~~~~~~~~~~~
/usr/local/include/_mingw.h:581:36: error: expected '=', ',', ';', 'asm' or '__attribute__' before '__debugbreak'
  581 | __MINGW_INTRIN_INLINE void __cdecl __debugbreak(void)
      |                                    ^~~~~~~~~~~~
In file included from first.c:1:
/usr/local/include/stdio.h:93:23: error: expected '=', ',', ';', 'asm' or '__attribute__' before '__acrt_iob_func'
   93 | _CRTIMP FILE *__cdecl __acrt_iob_func(unsigned index);
      |                       ^~~~~~~~~~~~~~~
/usr/local/include/stdio.h:158:15: error: expected '=', ',', ';', 'asm' or '__attribute__' before '__mingw_sscanf'
  158 |   int __cdecl __mingw_sscanf(const char * __restrict__ _Src,const char * __restrict__ _Format,...);
      |               ^~~~~~~~~~~~~~
/usr/local/include/stdio.h:161:15: error: expected '=', ',', ';', 'asm' or '__attribute__' before '__mingw_vsscanf'
  161 |   int __cdecl __mingw_vsscanf (const char * __restrict__ _Str,const char * __restrict__ Format,va_list argp);

...
/usr/local/include/sec_api/stdio_s.h:857:23: error: expected '=', ',', ';', 'asm' or '__attribute__' before '_vscwprintf_l'
  857 |   _CRTIMP int __cdecl _vscwprintf_l(const wchar_t *_Format,_locale_t _Locale,va_list _ArgList);
      |                       ^~~~~~~~~~~~~
/usr/local/include/sec_api/stdio_s.h:858:23: error: expected '=', ',', ';', 'asm' or '__attribute__' before '_fwscanf_l'
  858 |   _CRTIMP int __cdecl _fwscanf_l(FILE *_File,const wchar_t *_Format,_locale_t _Locale,...);
      |                       ^~~~~~~~~~
/usr/local/include/sec_api/stdio_s.h:859:23: error: expected '=', ',', ';', 'asm' or '__attribute__' before '_swscanf_l'
  859 |   _CRTIMP int __cdecl _swscanf_l(const wchar_t *_Src,const wchar_t *_Format,_locale_t _Locale,...);
      |                       ^~~~~~~~~~
/usr/local/include/sec_api/stdio_s.h:860:23: error: expected '=', ',', ';', 'asm' or '__attribute__' before '_snwscanf_l'
  860 |   _CRTIMP int __cdecl _snwscanf_l(const wchar_t *_Src,size_t _MaxCount,const wchar_t *_Format,_locale_t _Locale,...);
      |                       ^~~~~~~~~~~
/usr/local/include/sec_api/stdio_s.h:861:23: error: expected '=', ',', ';', 'asm' or '__attribute__' before '_wscanf_l'
  861 |   _CRTIMP int __cdecl _wscanf_l(const wchar_t *_Format,_locale_t _Locale,...);
      |                       ^~~~~~~~~
first.c:4:1: error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
    4 | {
      | ^
first.c:7: error: expected '{' at end of input
    7 | }
      |

please help me to solve this.
Thanks in advance
Comment: You definitely do not need Mingw on Linux. Get rid of it
Comment: try `gcc -o output first.c` then run it with `./output`. Notice the `#error` right at the top of your output.
Comment: again i got the same error                                                                                `In file included from /usr/local/include/corecrt.h:10,
                 from /usr/local/include/crtdefs.h:10,
                 from /usr/local/include/conio.h:9,
                 from first.c:1:
/usr/local/include/_mingw.h:272:2: error: #error Only Win32 target is supported!
  272 | #error Only Win32 target is supported!`
Answer: The Mingw-w64 compiler is for windows. If you're using linux, then you just need to install gcc which should be already preinstalled on your system. Just remove the mingw package and it should work then.


How to split a string without spaces into an array of words?

Question: So I'm practicing javascript at freecodecamp.org by making an algorithm of a telephone checker. I succeeded in checking it when only the provided phone number is a string of numbers. Now I'm stuck and don't know how to check it if the provided phone number contain words such as 'sixnineone'. So I want to split it into "six nine one" or convert them into "691" with an array of number objects.
Here's the problem:
(https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/telephone-number-validator)
I tried to get some hints via the website, but they only solve the problem with regular expressions which i don't understand well.
here is what I've done:
    function telephoneCheck(str) {
    let phoneNum = str.toLowerCase().replace(/[^1-9a-z]/g, "");
    let numbers = [
        {0: "o"},
        {1: "one"},
        {2: "two"},
        {3: "tree"},
        {4: "four"},
        {5: "five"},
        {6: "six"},
        {7: "seven"},
        {8: "eight"},
        {9: "nine"}
    ];

    if (phoneNum.match(/[1-9]/)) {
        phoneNum = phoneNum.split('')

        if (phoneNum.length === 10) {
            phoneNum.unshift(1);
        }

        for (let i = 0; i < phoneNum.length; i++) {
            phoneNum[i] = Number(phoneNum[i]);
        }

        if (phoneNum.length === 11 && phoneNum[0] === 1) {
            return true;
        } else {
            return false;
        }

    }

    if (phoneNum.match(/[a-z]/)) {
        console.log(phoneNum);
    }
}

console.log(telephoneCheck("sixone"));

In the solution of the problem, it is said that the only solution is their's, but if what I think is right then there might be another one.
Comment: Of course there are usually multiple ways to go about a problem like this. Is there an actual question here, or …?
Comment: My problem is that i don't know how to split an array if it contains numbers in words and digits like: "one7eightsix9tree". I want to split it in order to convert the "one", "eight","six", "tree" thanks to an object the numbers array.
Answer: One way might be to use a Map and use the names as a key and the value as the number.
Then extract the keys from the map, order them so that the longest string comes first and create a regex with a capturing group and an alternation
The regex would eventually look like:
(three|seven|eight|four|five|nine|one|two|six|o)

Then split the string using this regex. Map over the items removing all non digits when the map does not contain the key and remove all empty values from the array.
Finally get the value from the map by using the key.

let map = new Map([
  ["o", 0],
  ["one", 1],
  ["two", 2],
  ["three", 3],
  ["four", 4],
  ["five", 5],
  ["six", 6],
  ["seven", 7],
  ["eight", 8],
  ["nine", 9]
]);
let regex = new RegExp("(" + [...map.keys()]
  .sort((a, b) => b.length - a.length)
  .join('|') + ")");

let strings = [
  "69ooooneotwonine",
  "o",
  "testninetest",
  "10001",
  "7xxxxxxx6fivetimesfifefofourt",
  "test"

].map(s =>
  s.split(regex)
  .map(x => !map.has(x) ? x.replace(/\D+/, '') : x)
  .filter(Boolean)
  .map(x => map.has(x) ? map.get(x) : x)
  .join(''));

console.log(strings);


Ntp causing problems

Question: I have a FreeIPA server running on Centos 6 and one of its functions is to provide time sync to client hosts. NTP is version 4.2.6
The problem is that its own NTP synchronisation is nor working properly & I can't see why. This is then affecting the Kerberos/authentication functions.
The FreeIPA server cannot directly get to the internet so it needs to use another server that can see the internet.
Here is an nptq listing from the "master" time server whose IP address is 10.20.1.23.

# ntpq -p
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
*126.96.36.199   184.108.40.206    2 u  111  128  377   10.234    0.865   3.491
+126.96.36.199      188.8.131.52   2 u  121  128  377   14.806   -0.365   2.858
+22.214.171.124   220.127.116.11     2 u  117  128  377   10.677    0.816   1.931
+126.96.36.199  249.224.99.213   2 u  100  128  377   14.064   -1.678   1.525

All pretty standard stuff. 188.8.131.52 is being used as reference
Here is the output from another client using that server for time sync

# ntpq -pn
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
*10.20.1.23       188.8.131.52    3 u  230  256  377    0.439  1095.65  34.637
 127.127.1.0     .LOCL.           5 l  49m   64    0    0.000    0.000   0.000

This is fine telling me 10.20.1.23 is using 188.8.131.52 as its ref
But when I go to me FreeIPA server I get

# ntpq -pn
    remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
*10.20.1.23       LOCAL(0)         6 u   97  128  377   32.193  92334.0  17.646

The refid is different and it tells me we have about a minute & a half offset. In fact I set the clocks within a second by hand but now it's being pulled off by ntpd.
Comment: Can you post the output of `ntpq -c associations` ?
Comment: Things have changed and the sys_peer is now correct. The problem is that it fails back and the problem returns. When it does that the peer gets marked as falsetick and I have to restart ntpd to clear it.

 ntpq -c associations
ind assid status  conf reach auth condition  last_event cnt
===========================================================
  1 64586  963a   yes   yes  none  sys.peer    sys_peer  3
Comment: Can you check the output of `ntpq -c rv 963a` ? This is the assID (no, really, I can't make this stuff up...) of your peer associate and should give you a better idea of why you're seeing so much time source jitter in respect to your  local clock.
Comment: I'm pretty sure the jitter is caused when the refid changes from what it should be, a pool NTP server, and  refid=LOCAL(0). The the offset changes by about 125291ms, at the moment. If I can convince that the refid is the correct one it all falls into place
Comment: Curently I have

srcadr=10.20.1.23, srcport=123, dstadr=10.0.4.121

10.0.4.121 is the address of my freeipa server which is supposed to be the client

On all other clients it is correct.
It's just my freeipa server has got it into its head that the time server is refering back to the freeipa server
Comment: Is it possible that you have a configuration management service that is changing the ntp.conf on the FreeIPA server?
Comment: I'm pretty sure that is not the case. The ntp.conf file looks fairly standard
Answer: Also see: Why is NTP syncing to LOCAL rather than remote server?
What seems to be going on is that your local clock is running way too fast in relation to the time source that it's trying to sync against. As a result it trashes the synchronization source and goes with what it thinks is the best answer, which is it's own local kernel timesource. There are a couple of things you can do to help alleviate this condition and try getting your local clock into better shape.
First, to alleviate the issue, you can set the local clock to a higher stratum than your synchronization sources. An example in your ntp.conf file would be:
server 127.0.0.1
fudge 127.0.0.1 stratum 16   ## or some value greater than it's synchronization peer

This will make it a less-desirable source when NTP starts selection of peers for synchronization.
Next, if your local clock is really out of whack, you can adjust it using adjtimex. BE CAREFUL, you are playing with the hardware clock at this point. An example would look something like:
# adjtimex -p         ## List out how the clock is currently running...
     mode: 0
   offset: 0
frequency: 0
 maxerror: 0
 esterror: 0
   status: 64
time_constant: 4
precision: 1
tolerance: 32768000
     tick: 9900
 raw time:  1272299204s 17444us = 1272299204.017444
return value = 5

And adjust the value of the 'tick' field:
adjtimex -t 9800

Restart ntpd and see how it behaves. If it makes the jitter more acceptable, then leave it at that, or adjust it again, if necessary. NTP can be somewhat obscure and I hope I've helped things, but if you need more information, I'd trust the source at http://support.ntp.org
References
http://support.ntp.org/bin/view/Support/TroubleshootingNTP
http://log.or.cz/?p=80
Comment: I have eased the problem by adding a local clock.

I played with the kernel tick and it was very inconclusive.
What is nuts is that using ntpq -pn the freeipa server thinks that its time source is locked to the freeipa server. There used to be a circular reference but I took that out. Something seems to be remembering it despite restarting ntpd on both servers. No other ntp client shows the same problem

On the freeipa server ntpq -pn gives me

  remote           refid        offset
 10.20.1.23       10.20.4.179     84321.6

10.20.4.179 is the address of the freeipa server
Comment: Probably the best thing to do would be to get more peers defined for the FreeIPA server to select from. Are there any other systems in the network that can fill this role? Preferably ones with an internet connection to a higher stratum peer?
Comment: Unfortunately that is not an option. I have given it a local clock as an option and now it runs more stably. When the peer appears to jump to the wrong time this server uses its own clock until the proper peer seems ok. During this time the peer is working properly, it's just that this server sees it as wrong..

Ntp causing problems


How to repeat a plot in different subplots in matplotlib?

Question: I have
fig, (((ax1, ax2), (ax3, ax4))) = plt.subplots(ncols=2, nrows=2,
                                               sharex='col',
                                               sharey='row',
                                               figsize=(12, 12))

and I want to repeat one plot, say P in all axes, something like:
P.plot(ax = [ax1, ax2, ax3, ax4], facecolor = "none",
       edgecolor = "black")

without having to repeat the line for each plot. Is there a way to do that?
Comment: what is `P`? Are you looking for an object `P` that would allow for the given command?
Comment: any reason you cannot use a for-loop? `for ax in [ax1, ax2, ax3, ax4]: ax.plot(...)`
Comment: @ImportanceOfBeingErnest: it's a `geopandas` `GeoDataFrame` with a `plot()` method.
Comment: @DizietAsahi: no reason. I wanted to learn whether there was a "pythonic" way to pass all axes without iterating over the axis. Thanks!
Answer: Some people prefer to use map instead of for in python. So I suppose if the aim is to replace some canonical loop like
for ax in [ax1, ax2, ax3, ax4]:
    geodf.plot(ax=ax)

you could do
list(map(lambda ax: geodf.plot(ax=ax), [ax1, ax2, ax3, ax4]))

Answer: This is one way to do this using list comprehension method without having to write four separate plot commands explicitly. I am using a DataFrame as p to be consistent with your problem. You can try replacing df with your p variable.
import pandas as pd
import matplotlib.pyplot as plt

fig, (((ax1, ax2), (ax3, ax4))) = plt.subplots(ncols=2, nrows=2,
                                               sharex='col',
                                               sharey='row',
                                               figsize=(8, 8))

df = pd.DataFrame({"x": [1, 2, 3, 4],
                   "y" : [1, 4, 9, 16]})

_ = [df.plot(x="x", y="y", ax=ax) for ax in [ax1, ax2, ax3, ax4]]
plt.show()


ng-repeat - filter by function in datastructure

Question: I have an array with json objects which contains a function
items = [...{
   id:1,
   isActive: function(){
     this.id < activeId;
   }
}...];

In a directive elsewhere I use this json array in an ng-repeat. I want to filter with regards to the function.

However, this doesn't work. I can do it with properties, but not with function calls. How can I achieve this?
Answer: You will have to use custom filter function (make sure to return from isActive object methods btw):
$scope.isActive = function(el) {
    return el.isActive();
};

and use it like this

{{i.id}}

Demo: http://plnkr.co/edit/Ib8LINdHNBPDfXOBusez?p=preview
Comment: Allright, is there no way to do it inline? What if I only want to iterate trough inactive elements? I can't do `filter:!isActive`... Do I have to write two custom filter functions?
Comment: Yes, using this approach, you would have to write an additional function. That is why I recommended writing a custom AngularJS filter below, so that the same functionality could be reused whenever and however you need it. If you get to another page in your app where the same functionality is needed, you will be repeating yourself, it's better to keep code [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself).
Answer: First, you need to return the result of your function:
$scope.items = [
  {
      id: 1,
      isActive: function() {
          return this.id < activeId;
      }
  },
  {/* ... */}
];

Then, in your HTML, simply use the orderBy filter.

{{item.id}} - {{item.isActive()}}

That should work.
EDIT
Sorry, misunderstood the question. I don't believe the 'filter' $filter will take a method as the expression. You are probably better off writing your own filter. I took a quick stab at it, but have only tested it lightly, more thorough testing would be required before using it.
/**
 * Defines a filter on the $filter provider that will call a method
 * to filter objects inside of ngRepeat.
 *
 * @return {Function}
 *    @param {Array} - the array to loop through
 *    @param {String} - the Object method name
 *    @param {Any} - the value to match against
 *    @return {Array} - the resultant array
 */
.filter('evalMethod', [function() {
    return function(array, method, expected) {
        var results = [];
        /**
          * loop through all items in the array
          * and bind the results to the results object
          */
        angular.forEach(array, function(item, key) {
            /**
             * call the method against the item context,
             * if it returns as expected, push it into the results array
             */
            if (item[method].call(item) == expected) {
                this.push(item);
            }
        }, results);
        return results;
    };
}]);

And then using markup like:

{{item.id}} - {{item.isActive()}}

Then, if you want to use this inside the controller (or anywhere else), just include $filter as a dependency and call.
$filter('evalMethod')($scope.items, 'isActive', true);

Comment: Sorry, I misunderstood the question. I've updated my answer.
Comment: Thank you for your answer, but this looks very complicated, in such case it's perhaps better to do custom filter function and put it on the scope..
Comment: All this is is defining a custom filter to be reused anywhere on the app ([see this tutorial](https://docs.angularjs.org/tutorial/step_09)). Putting a function on the $scope like that would generally be advised against as you don't want to pollute your $scope with unnecessary functions. If it makes you feel better, I will comment the filter to let you know what's happening.


Getting error from TFS 2015 trying to restore packages from a private feed

Question: We have an on-premise TFS 2015 build. We've recently added a reference to a 3rd party package. I have added a nuget restore build step to our build pipeline before the MSBUILD step to restore the package.

Here's the nuget restore build task

Here's the MSBUILD step

The error message I'm getting is this.
Failed to retrieve information about 'myPrivatePackage' from remote source 'https://nuget.myPrivatePackage.com/nuget/FindPackagesById()?id='myPrivatePackage'&semVerLevel=2.0.0'.
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

Here's the build output log.

UPDATE
Here's the detailed TFS build log output from the nuget restore step.
Task "RestoreTask"
         (in) RestoreGraphItems Count '19'
         (in) RestoreDisableParallel 'False'
         (in) RestoreNoCache 'True'
         (in) RestoreIgnoreFailedSources 'False'
         (in) RestoreRecursive 'True'
         (in) RestoreForce 'False'
         (in) HideWarningsAndErrors 'False'
         (in) RestoreForceEvaluate 'False'
         Running restore with 4 concurrent jobs.
         Reading project file E:\TfsData\Build\_work\4\s\OscarWeb\OscarWeb.csproj.
         Reading project file E:\TfsData\Build\_work\4\s\OscarWeb\OscarWeb.csproj.
         Persisting no-op dg to E:\TfsData\Build\_work\4\s\OscarWeb\obj\OscarWeb.csproj.nuget.dgspec.json
         Restoring packages for E:\TfsData\Build\_work\4\s\OscarWeb\OscarWeb.csproj...
         Restoring packages for E:\TfsData\Build\_work\4\s\OscarWeb\OscarWeb.csproj...
         Restoring packages for .NETCoreApp,Version=v2.2...
         Restoring packages for .NETCoreApp,Version=v3.1...
           GET https://www.nuget.org/api/v2/FindPackagesById()?id='BuildBundlerMinifier'&semVerLevel=2.0.0
           GET https://www.nuget.org/api/v2/FindPackagesById()?id='Microsoft.VisualStudio.Web.CodeGeneration.Tools'&semVerLevel=2.0.0
         Retrying 'FindPackagesByIdAsyncCore' for source 'https://nuget.telerik.com/nuget/FindPackagesById()?id='BuildBundlerMinifier'&semVerLevel=2.0.0'.
         The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

Any ideas what is causing the error and how to fix it?
Answer: According to your screenshot. One issue I notice is that the MSBuild task is doing a restore at all. It shouldn't. Let the Nuget task do the NuGet restore.
Suggest go to Advanced options for the build task and uncheck "Restore NuGet Packages" or if there is some other way you are invoking NuGet restore during the build turn that off.
If this is not do the trick, also set variable system.debug=true to Enable Verbose Debug Mode for TFS Build vNext. Which may provide more detail info for troubleshooting.
Comment: I'ver got it working by using "dotnet restore" instead of "nuget restore"
Comment: @DomBurf Glad to hear this, you could share your solution here as an answer, then mark your reply, which will also helps others in the community.
Comment: When I try that I get the following error message:

"Assets file 'MyProject\obj\project.assets.json' not found. Run a NuGet package restore to generate this file."
Comment: Hi  DomBurf, according to your error message, seems your Nuget Install task didn't restore the package at all. You could check the logs of Nuget Install task if your build service account access that private feed and download files. If not, this maybe the root cause. Then you could try to narrow down , if your build service account have enough permission/access to the private feed. Also check if network block your build agent to private feed url to download packages.
Comment: I have disabled the "restore" on the build step but still getting exactly the same error message.
Comment: Hi @DomBurf According to your updated logs  `Retrying 'FindPackagesByIdAsyncCore' for source 'https://nuget.telerik.com/nuget/FindPackagesById()?id='BuildBundlerMinifier'&semVerLevel=2.0.0'.`  Since you are trying to get source from a 3rd-party site `https://nuget.telerik.com`. Not sure what's your nuget.config looks like. But I guess  `..telerik.com` should need some extra authentication. This may cause some issue. Suggest you could  use Remote Desktop to connect to the build server and open the project in Visual Studio there, check if it restores the packages and builds fine.
Answer: I have managed to get this working by using the dotnet restore command instead of nuget restore.
dotnet restore "MyProject.csproj"  --configfile "nuget.config" --verbosity detailed --packages "rootfolder\packages" --no-cache

My 3rd party packages are now being restored as part of the build pipeline correctly.


Does Drupal 8 entities have any events I can listen to?

Question: I know we can use hook_entity_update() hook to do something when an entity is updated. But is there an event to listen for node updates/deletes, or other entities such for that matter?
Answer: You can't listen to an event. You can either use a hook or implement a method like postSave() in your custom entity.
Here is the order of hooks and other events that happen during an entity save:

Entity::preSave() is called on entity objects, and FieldItemListInterface::preSave() on field objects.
hook_ENTITY_TYPE_presave()
hook_entity_presave()
Entity is saved to storage.
Entity::postSave() is called on the entity object.
hook_ENTITY_TYPE_insert() (new) or hook_ENTITY_TYPE_update() (update)
hook_entity_insert() (new) or hook_entity_update() (update)
Comment: Yes, many Drupal specific events are still in hooks. Eventually all hooks will be replaced, see http://drupal.org/node/1509164 and http://drupal.org/node/1972304.
Comment: So entities won't dispatch any events that I can subscribe to? I would have to use a hook?
Answer: Ideally you would listen for entity related events but these aren't ready yet. See "Add events for matching entity hooks".
For now, if you're wanting to stay away from hooks, you can use a contrib module: Hook Event Dispatcher
Answer: A node is an entity type, so hook_ENTITY_TYPE_update(.. is the same as hook_node_update(..,
function hook_node_update(Drupal\Core\Entity\EntityInterface $entity) {
    //$entity->bundle()  - 'article' 'page'
}

or
function hook_customentity_update(Drupal\Core\Entity\EntityInterface $entity{
    //$entity->bundle()  - 'awesome_entity_bundle'
}

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Entity!entity.api.php/function/hook_ENTITY_TYPE_update/8.2.x


Serving CSS, images and JavaScript in Drupal

Question: Does the whole Drupal stack get fired up (bootstrapped) each time one of these static content types gets requested?
Answer: Nope, it does not.
But if you have let's say in one of your stylesheet files a reference to a missing image, or your code is trying to load a missing js file then because of the Rewrite Rules in .htaccess this requests are redirected to index.php and that causes the bootstrapping of the whole system to render the 404 page.
Comment: Apache is the one who knows the difference via rules in the [.htaccess](http://httpd.apache.org/docs/trunk/howto/htaccess.html) file. If you are getting a lot of 404s for CSS/JS files might I recommend the [advagg](http://drupal.org/project/advagg) module.
Comment: How does Drupal knows the difference between a dynamic page request and a static resource request?


SQL Server - contar registros por combinação

Question: Pessoal estou precisando fazer uma consulta no sql server de forma que ela identifique pra mim quando as combinações 1,2 e 3 ou 2 e 3 da coluna "desc" estejam presentes para valores repetidos da coluna "cod" o resultado deve ser retornado como 1 para encontrado e 0 não encontrado. Alguem sabe como é possivel fazer esta consulta? Obrigado.
Comment: Não ficou muito claro, vc quer retornar uma pesquisa onde o desc for igual ao id?
Comment: Não, o "id" é a resposta olhe apenas para as colunas "cod" e "desc" quando as letras forem repetidas em "cod" quero verificar se dentro das repetições existem as combinações mencionadas. No exemplo B repete e tem a combinação 1,2 e 3 na coluna "desc", C possui a combinação 2 e 3 e por fim H possui a combinação 1,2 e 3. Obrigado
Comment: Tentando explicar de uma forma mais clara, quero que toda vez que tiver uma repetição das letras na coluna "cod" seja verificado na coluna "desc" as se os números 1 e 2 e 3 não importando a ordem esteja contido dentro das repetições isso vale também para a combinação 2 e 3 não importando a ordem. Obrigado.
Answer: Você pode usar uma query para analisar as combinações usando STUFF, veja esse link: https://sqlperformance.com/2014/08/t-sql-queries/sql-server-grouped-concatenation
E a partir dessa query, analisar os valores combinados para retonar o ID com CASE.
A query ficará assim:
WITH combinado (cod, descr)
     AS (SELECT cod,
                -- combina os valores 1,2 e 3, agrupado por cod
                Stuff((SELECT ', ' + Cast(descr AS CHAR(1))
                       FROM   teste AS t2
                       WHERE  t2.cod = t.cod
                       ORDER  BY descr
                       FOR xml path(N'')), 1, 2, N'') AS descr
         FROM   teste t)
SELECT cod,
       descr,
       CASE descr
         WHEN '1, 2, 3' THEN 1
         WHEN '2, 3' THEN 1
         ELSE 0
       END AS ID
FROM   combinado

Veja um exemplo funcionando aqui nesse fiddle: http://sqlfiddle.com/#!18/da106/15
Comment: Muito obrigado colega ajudou muito. abs


Several pages with the same structure in Angular

Question: I'm relatively new to Angular and I'm struggling to create the same behavior for several pages using a common module.
Here is the situation: I'm creating a CRUD SPA with several "pages" (using routing). Turns out that several of those pages shares the same structure and behaviors, and only differs (visually) from the way the items are rendered in a list and its details when selected. Think like several pages of Asana, where the only difference between the pages are the way the list and the details are renderer.
I was thinking to create a Module for each of these pages, but it seemed lame to copy and paste all the code just to change a small portion of the files (updating would be a nightmare too).
The solution I'm trying to achieve is to create a master CRUD Module, with one Component/html/css where I can in some way parameterize which renderer to use for each page. Or any other solution that has as minimum copy-paste as possible.
Thanks for the help.
Answer: I read about the tool and some other things like dynamically created components, but none was exactly what I wanted (specially considering the learning curves). So, it took me some time, but I found a (pretty crazy) solution on my own.
First, I created a Base Module. Within it, I created a PageComponent that calls the two parts of the pages that I needed: one for the list and other for the details (like Asana). The page.component.html template looks like this:

        <app-list></app-list>

        <app-details></app-details>

`

In this base module, I created an abstract base class for each of the components that I needed (an AbstractListComponent and AbstractDetailsComponent). I had some issues with dependency injection and automatic variable creation using the access word in the constructor, so my solution was the following:
export abstract class AbstractDetailsComponent {
    protected service: BaseService;

    protected constructor(service: BaseService) {
        this.service = service;
    }
}

Note that I didn't use the @Component decorator since it will be ignored (in PageComponent too). Another thing was that some Base* classes and interfaces were created to ensure the consistency (like BaseService).
As you can see, nobody will answer when the PageComponent requests for <app-list> and <app-details>. Here starts the crazy part.
For each page I created a module and within it, components that filled the gaps. Also, the main component for the page extends PageComponent. For example, in my app, I have a Skills page, which leads to the following SkillsComponent:
@Component({
    selector: 'skills-page', // doesn't really matter, this will be called by the router
    templateUrl: '../base-module/page.component.html',
    styleUrls: [ '../base-module/page.component.css', './skills.component.css' ]
})
export class SkillsComponent extends PageComponent { }

Note that the templateUrl and one of the styles points to files inside the base module. This was the way I found to share the same page structure between all pages.
Now, the gaps. Both components that I needed are similar. Basically, I extend the base class for each one and inject the right service. Here is the SkillDetailsComponent:
@Component({
    selector: 'app-details', // <-- the name required by the PageComponent template
    templateUrl: './skill-details.component.html',
    styleUrls: [ '../base-module/details.component.css', './skills-details.component.css' ]
})
export class SkillsDetailsComponent extends DetailsComponent {
    public constructor(service: SkillsService) {
        super(service);
    }
}

The selector is exactly the one required by page.component.html. All list and details components for all pages share the same approach. This makes the same template useful in all pages, since the selector is the same.
Another thing is the constructor. I had to make it like this to inject the right service.
The final file structure looks like this:
app/
    ├ base-module/
    │    ├ base.component.css
    │    ├ base.component.html
    │    ├ base.component.ts
    │    ├ base.module.ts
    │    ├ details.component.css
    │    ├ details.component.ts
    │    ├ list.component.css
    │    ├ list.component.html
    │    └ list.component.ts
    └ skills-module/
        ├ skills-details.component.css
        ├ skills-details.component.ts
        ├ skills-list.component.css
        ├ skills-list.component.ts
        ├ skills.component.css
        ├ skills.component.html
        ├ skills.component.ts
        └ skills.module.ts

I don't know if it's the best solution, but it's woking like I needed. It was kinda hard to explain all the steps I've made (usually this is a sign of a too-much-complicated solution) but I hope it's understandable.
Answer: My guess is that you are using ng-route. Try checking out ui-router https://github.com/angular-ui/ui-router
UI-Router is the de facto standard AngularJS client-side routing framework that supports nested views. The concept behind UI-Router is to model views as a hierarchical tree of states.
Comment: Wow, this seems to be the solution I wanted! I'm reading about it right now. For the record, I'm using Angular 4, not AngularJS.


Guess the value of the limit

Question: Simplify and guess the value of $\lim_{x\to 2}\frac {x^3-8}{x-2}$.
I'm very confused on how to do this.  Please help!
Comment: hint $$x^3-2^3=(x-2)(x^2+2x+2^2)$$
Answer: Quick way: We know that $x^3 - 8 = x^3 - 2^3$, so this is a difference of cubes, which factors into $(x - 2)(x^2 + 2x + 2^2)$. So your expression is the same as $\frac{(x-2)(x^2 + 2x + 4)}{x - 2}$. Cancel the $x - 2$s. We get $x^2 + 2x + 4$. At $x = 2$, this is $12$, which is our answer.
But why does that work? Why are we allowed to cancel?
The trick is: we can cancel whenever $x - 2 \ne 0$. So we can cancel, with a restriction: $\frac{(x-2)(x^2 + 2x + 4)}{x - 2} = x^2 + 2x + 4$, for all $x \ne 2$. Conveniently, when we look at the limit of our function, we look at values of $x$ that are close to, but not equal to $2$. So we can conclude:
$$\lim_{x \to 2} \frac{(x-2)(x^2 + 2x + 4)}{x - 2} = \lim_{x \to 2} x^2 + 2x + 4$$
We know that polynomials are continuous, so the limit at any $c$ is the same as the value at $c$, so we just plug in $2$ and get $12$ as our answer. We don't have to go through this process every time, normally we just "cancel", but it is good to know that there's no trickery going on.
(Also, for math notation on SE, see here.)
Answer: Provided you know some basic differential calculus, which may not be the case as you are asking a question about limits which is necessarily an earlier topic, here is an alternative method.
Letting $f(x) = x^3$, we have
$$\lim_{x \to 2}\frac{x^3 - 8}{x - 2} = \lim_{x \to 2}\frac{f(x) - f(2)}{x -2} = f'(2).$$
As $f'(x) = 3x^2$, the limit is $f'(2) = 12$.
Answer: One way to do this is to approach this like the velocity question from before.  You want to see what happens as $x$ gets closer and closer to $2$, so just check some nearby values. We say
$$f(x)=\frac{x^3-8}{x-2}$$
And when $x$ gets closer to $2$, $f(x)$ gets closer to some limit.  Plugging in a few values, we have:
$$
f(3) = \frac{3^3-8}{3-2}=19\\
f(2.1)= 12.61\\
f(2.01)=12.0601\\
f(2.001)=12.006
$$
What value is $f(x)$ getting closer to as $x\to2$?

Alternatively, you can notice that for any $x$ not equal to $2$, we have
$$
f(x)=\frac{x^3-8}{x-2}=\frac{(x-2)(x^2+2x+4)}{x-2}=x^2+2x+4
$$
Why does this help?
Comment: This helps a lot man, for some reason this stuff is not clicking at all. The only question I have is how did you get 3 for f(3)?  And how did you create the arrow.
Comment: It didn't have to plug in $3$, it was just the first obvious choice of something kind of close to $2$. If you want to see what I wrote, you could always click "edit" to see how I typed everything.  Quick tip: any time you want to do math-stuff, put it between dollar signs `$like this$`. For example, to get $x \to 2$, I typed `$x \to 2$` and could have also typed `$x\rightarrow 2$`.  I suggest you take a look at [this page](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) for future reference.
Comment: Also, if you want to see how to write any particular thing in MathJax, right-click it and select "Show Math As"$\to$"TeX Commands". Click that, and you'll get a little pop-up with the code written out.  For example: $\pmatrix{a^1_1&a^1_2\\a^2_1&a^2_2}$
Answer: For $\lim\limits_{x\to 2}\dfrac{x^3−8}{x−2}$, when $x \to 2$, the result tends to positive or negative infinity.
Apply L'Hôpital's rule, we differentiate both denominator and numerator separately, we will get $\dfrac{3x^2}{1} = 3x^2$.
Put $x=2$, $3 \times 2^2 = 3\times 4 = 12$.
Comment: Isn't L'Hospital's Rule only for 0/0 or $\infty / \infty$ forms?
Comment: @zerosofthezeta Yes, and this limit *is* in $0/0$ form.
Answer: The above answers are not the solution you are looking for.  When you are asked to "guess" a limit, you are to construct a table and test input values that approach 2.  To be complete you should consider both values greater than 2 and values less than 2.
x         1.8    1.9   1.95   1.99  Und.  2.01   2.05   2.10   2.20
f(x)     10.84  11.41 11.70  11.94  ?    12.06  12.30  12.61  13.24
Now look for the trend.  As x->2, f(x)-> 12.  Since the output values are approaching 12, we can reasonably "guess" that the limit is equal to 12.
(NOTE: in a later section of your course you will be asked to "evaluate" the limit.  That is what others were trying to explain, and unfortunately probably caused you even more confusion.)

Guess the value of the limit


Degree of $\mathbb{Q}(\sqrt{3 + 2 \sqrt{2}})$ over $\mathbb{Q}$

Question: In the text by Dummit and Foote, there is the following exercise in chapter 13:

Determine the degree of the extension $\mathbb{Q}\big(\sqrt{3 + 2 \sqrt{2}}\big)$ over $\mathbb{Q}$.

To solve this problem, I proceeded by letting $\alpha = \sqrt{3 + 2 \sqrt{2}}$ and then computing $\alpha^2$ and $\alpha^4$.  Assuming I did this correctly, one gets
\begin{equation*}
\alpha^2 = 3 + 2 \sqrt{2} \quad \text { and } \quad \alpha^4 = 17 + 12 \sqrt{2}
\end{equation*}
It follows from this that the polynomial $f(x) = x^4 - 6x^2 + 1$ has $\alpha$ as a root.  The only divisors of the constant term are $1$ and $-1$, and $f(\pm1) \neq 0$.  By the Rational Roots Test, we should have $f$ be irreducible over $\mathbb{Q}$, so that the answer to the question is $4$.
However, I was looking at this write up  of solutions, and here the answer is given as $2$.  So I am guessing there is some error in my "proof" that the degree is $4$, but can't seem to find what I did incorrectly...
Comment: Careful: lack of roots for quartic polynomials does not guarantee irreducibility.  That only holds with quadratics and cubics.
Answer: The trick is to note that
$$ (1+\sqrt{2})^2=1+2\sqrt{2}+2=3+2\sqrt{2}$$
so in fact $\mathbb{Q}(\sqrt{3+2\sqrt{2}})=\mathbb{Q}(\sqrt{2})$.
The problem with your argument is that even if a quartic polynomial has no rational roots, it can still be reducible over $\mathbb{Q}$ since it could be a product of two irreducible quadratic polynomials.
Comment: In fact, it is true for no degrees other than $2$ and $3$. What's going on is that every polynomial over $\mathbb{R}$ factors (uniquely!) into the product of irreducible polynomials of degree $\leq 3$. When the degree of your polynomial is $2$ or $3$ that means that every reducible polynomial has at least one linear factor, but not for degree $>3$. You likely have the tools at your disposal to prove this very interesting fact about polynomials.
Comment: @carmichael561  I see your point about the fallacy of the implication ($f$ has no rational roots) $\implies$ ($f$ is irreducible) when $f$ is of degree $4$.  Thanks for pointing that out.
Comment: @Sam Y.: The argument in the solution manual looks ok to me, it just uses a previous exercise which I was unaware of when I wrote my answer.
Comment: @carmichael561  Sorry, I got mixed up.  Just forget that previous comment.  Great answer.  Thanks.


Applications of infinity in real life

Question: I am writing a mathematical essay and would like to focus on the concept of infinity. I am not sure of any real life applications of infinity to write about or some way to narrow down the topics. Does anyone have any ideas on ways to focus the essay on a section of the topic infinity.
Comment: Limits to infinity gave us the big-O notation used in computer science, which allows us to compare algorithms runtime
Comment: Anytime calculus has ever been applied to real life problems. Can't have the nice properties of the real numbers without infinity.
Answer: As far as I'm aware of there has no infinite object been observed in real life , and according to many logical and philosophical discussion in the history of man it might even be impossible to observe it if it were existent.
Infinity is a construct of mind: it is the mental process to say: "I see this long street and if I do one step and do another step I mov forward but without reaching its end behind the horizon. And I can do this one time more... and, mama, if I do it forever ?" Or even simpler: meditating about a clock where the hands go in circles...
So, in the sense, how we extrapolate concrete experiences in our finite world, the first concept in our mind is: "and when I proceed infinitely many steps/infinitely long time"- so I think this is the way, how something "infinite" comes into the (mental) world. Always our natural idea of "infinite" comes from extrapolation - be it then also infinite height, length, temperature, area, volume,...
Our geometrical common-sense has the natural concept of the euclidean space - whose length, height, width is thought as "infinite".
So far, this is speaking of "infinite" as an adjective, as a property . It seems to me this is only a property, a "construction-feature" of our mental "machine of rational thinking" (I seem to remember some philosophical/religious discussion where it was even said: because there is such a feature "installed" it must also be existent in nature, and another one: this courious inherent feature of the rational machine is that what allows us the contact with the godly which would be impossible otherwise... but I don't know how far this arguments explain only themselves, are somehow circular...)
Even more abstraction and philosophical reasonning tend then to make some philosophical concept of the "infinity" as an own mental object - and after that, may proceed to postulate it even as real object.
In the ideal world of, say mathematics, this goes on much more straightforward - infinity is essentially involved in our idea of counting (we assume counting is infinitely possible in our mathematics). But then the student of mathematics cannot follow so fast and then he asks: "ok if I count to infinity, what comes after it?" or: "ok, 0.9999... has infinitely many digits, but if then comes one 8, what does it mean?" or "Ok, you might say there is no greatest number in $\mathbb N$ but what about "infinity" and what when I divide 1 by infinity?" etc.
So "infinity" is all around, but, say, 90% subcutane/subconscious and, say, 5 more percent, as a buzz-word because we have a time where attractive buzzwords are worth money when they can succesfully be transferred into the common discourses...  - and/but always only in our mental world.
But wait. Maybe we cannot observe infinite objects (in size), infinite processes (in time) - by some philosophically explained reason. But we observe in the modern physics (high energy I think) processes, which behave in a way such that we must describe them mathematically with the help of concepts of infinity - and which are native only in our mind/modeling! One example is the zeta-regularization of a divergent series: this deals with the problem of summing to, and over infinity and to arrive anyway at meaningful finite equivalents - as I said: initially only inside the bounds of our ideal world of mathematics. But if such specific concepts are needed for the mathematical explaining of nature as well, then it might be possible that we have some "real life" object/process at hand, which owns in some yet obscure and hidden way something similar as our mathematical "infinity" - and this would then be one hint/one vague shadow of "infinity in real life".

Applications of infinity in real life


Injecting try/catch block for serializable check in bytecode through ASM

Question: I am new to ASM and I want some help related to bytecode transformation.
I would like to add print function with try/catch block for every local variable in bytecode through ASM. I found that previous questions about adding try/catch block were about the entire method.
I know little about the stack map frame, so any pointers would be highly appreciated. Thanks in advance.
What I expected for every object, e.g. someObject: print the serialized representation for it if this object is serializable, if not, use toString() to print:
try {
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  ObjectOutputStream oos = new ObjectOutputStream(bos);
  oos.writeObject(someObject);
  String serializedObject = Base64.getEncoder().encodeToString(bos.toByteArray());
  oos.close();
  System.out.println(serializedObject);
} catch (IOException ex) {
  System.out.println(someObject.toString());
}

Since I'm trying to do this for every object, so I override visitVarInsn() in MethodVisitor, as following:
@Override
public void visitVarInsn(int opcode, int var) {
  super.visitVarInsn(opcode, var);
  switch (opcode) {
    case Opcodes.ASTORE:
      Label tryStart = new Label ();
      Label tryEnd = new Label ();
      Label catchStart = new Label ();
      Label catchEnd = new Label ();
      mv.visitTryCatchBlock(tryStart, tryEnd, catchStart, "java/io/IOException");

      mv.visitLabel(tryStart);
      // ==> ByteArrayOutputStream bos = new ByteArrayOutputStream();
      mv.visitTypeInsn(Opcodes.NEW, "java/io/ByteArrayOutputStream");
      mv.visitInsn(Opcodes.DUP);
      mv.visitMethodInsn(INVOKESPECIAL, "java/io/ByteArrayOutputStream", "<init>", "()V", false);
      mv.visitVarInsn(Opcodes.ASTORE, var + 1);
      // ==> ObjectOutputStream oos = new ObjectOutputStream(bos);
      mv.visitTypeInsn(Opcodes.NEW, "java/io/ObjectOutputStream");
      mv.visitInsn(Opcodes.DUP);
      mv.visitVarInsn(Opcodes.ALOAD, var + 1);
      mv.visitMethodInsn(INVOKESPECIAL, "java/io/ObjectOutputStream", "<init>", "(Ljava/io/OutputStream;)V", false);
      mv.visitVarInsn(Opcodes.ASTORE, var + 2);
      // ==> oos.writeObject(someObject);
      mv.visitVarInsn(Opcodes.ALOAD, var + 2);
      mv.visitVarInsn(Opcodes.ALOAD, var);
      mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/ObjectOutputStream", "writeObject", "(Ljava/lang/Object;)V", false);
      // ==> String serializedObject = Base64.getEncoder().encodeToString(bos.toByteArray());
      mv.visitMethodInsn(INVOKESTATIC, "java/util/Base64", "getEncoder", "()Ljava/util/Base64$Encoder;", false);
      mv.visitVarInsn(Opcodes.ALOAD, var + 1);
      mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/ByteArrayOutputStream", "toByteArray", "()[B", false);
      mv.visitMethodInsn(INVOKEVIRTUAL, "java/util/Base64$Encoder", "encodeToString", "([B)Ljava/lang/String;", false);
      mv.visitVarInsn(Opcodes.ASTORE, var + 3);
      // ==> oos.close();
      mv.visitVarInsn(Opcodes.ALOAD, var + 2);
      mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/ObjectOutputStream", "close", "()V", false);
      // ==> System.out.println
      mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
      mv.visitVarInsn(Opcodes.ALOAD, var + 3);
      mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);

      mv.visitLabel(tryEnd);
      mv.visitJumpInsn(Opcodes.GOTO, catchEnd);

      mv.visitLabel(catchStart);
      mv.visitVarInsn(ASTORE, var + 1); // store exception
      // ==> System.out.println
      mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
      mv.visitVarInsn(Opcodes.ALOAD, var);
      mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "toString", "()Ljava/lang/String;", false);
      mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);

      mv.visitLabel(catchEnd);

      // not sure whether I should add this.
      mv.visitLocalVariable("e", "Ljava/io/IOException;", null, catchStart, catchEnd, var + 1);
      break;
    default: // do nothing
  }
}

But when I tested, I keep getting NotSerializableException -- I thought I used try-catch to catch this exception.
I'm not sure whether I should add visitFrame for try-catch block (and I also don't know how to do it).
PS -- Any pointers about other better methods to do logging for every local variable would also be highly appreciated!
Comment: No, just create a method somewhere, say `public static void printSerializedWithToStringFallback(Object someObject)` in class `mypackage.MyUtil` containing all the code and then, instead of all the complicated code, you're just doing `super.visitVarInsn(opcode, var); if(opcode == Opcodes.ASTORE) {  super.visitVarInsn(Opcodes.ALOAD, var);  super.visitMethodInsn(Opcodes.INVOKESTATIC, "mypackage/MyUtil", "printSerializedWithToStringFallback", "(Ljava/lang/Object;)V", false); }` to inject a call to that method passing the object to print.
Comment: You are injecting too much. You are potentially overwriting variables used by the original code (unless you're using `LocalVariableSorter`) and injecting this code block for every store operation will make the code size explode. Create a dedicated method encapsulating the operation of your first code snippet, can be compiled ordinarily, and just inject an invocation of that helper method.
Comment: Further, note that to ensure that all serialized data has been flushed to the `ByteArrayOutputStream` you have to `close` the `ObjectOutputStream` *before* calling `toByteArray()`. But why do you think the base64 encoded serialized data is better than the `toString()` output?
Comment: @Holger The reason to generate the serialized data is that I would like to deserialize those data back to object and do comparison.
Comment: @Holger Inject an invocation -- do you mean doing it outside `MethodVisitor`?
Comment: Thanks so much! I made it work!
Answer: Your logic of building a try-catch block is correct, except that you are using variables var + 1 to var + 3 which may clash with uses by the original code. When I try your code to instrument an example specifically chosen such that it has no such variable clashes, it works.
You could work-around such issues using a LocalVariablesSorter but it requires calls to newLocal to declare a variable for your injected code and since there's no such call in your code, I assume, you're not using LocalVariablesSorter.
Generally, injecting code of such complexity, even potentially multiple times, not only is error prone, it might raise the code size significantly, up to the point that it exceeds the maximum code size of a method.
The preferable approach is to move the complex code in a method on its own, which might even be delivered in precompiled form, i.e. created using ordinary Java source code, and only inject an invocation of that method.
So, assuming a helper class like
package mypackage;

import java.io.*;
import java.util.Base64;

public class MyUtil {
    public static void printSerializedWithToStringFallback(Object someObject) {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(someObject);
            oos.close();
            System.out.println(Base64.getEncoder().encodeToString(bos.toByteArray()));
          } catch(IOException ex) {
            System.out.println(someObject.toString());
          }
    }
}

You can inject the invocation like
@Override
public void visitVarInsn(int opcode, int var) {
    super.visitVarInsn(opcode, var);
    if(opcode == Opcodes.ASTORE) {
        super.visitVarInsn(Opcodes.ALOAD, var);
        super.visitMethodInsn(Opcodes.INVOKESTATIC, "mypackage/MyUtil",
            "printSerializedWithToStringFallback", "(Ljava/lang/Object;)V", false);
    }
}

Injecting this invocation does not introduce any branches, so the stack map table does not need to be recalculated. Even the requirements for the stack do not change. The injected code does not introduce new local variables and its highest stack size, after the aload, is identical to the stack size before the astore. So this simple instrumentation does not need the COMPUTE_FRAMES option and not even COMPUTE_MAXS.
Comment: There is one corner case. When you have rather old bytecode (targeting Java 6 or older), you may encounter `jsr`/`ret` pairs which have a strange asymmetry. `jsr` will push a *returnaddress* to the stack, but `ret` expects the *returnaddress* in a local variable. To support this, `astore` can pop such a *returnaddress* and store it into a local variable. But `aload` can not read a *returnaddress*. Otherwise, I don't know a case where reading immediately after storing should fail. But seeing the complete `VerifyError` would be helpful. Usually, it includes the entire bytecode for analysis.
Comment: I tried your methods to log local variables. In most cases, it works fine, but in some cases, it got `VerifyError: Bad local variable type` with the reason `Type top (current frame, locals[14]) is not assignable to reference type` for `ALOAD`. I thought every `ASTORE` could have an `ALOAD`, but sometimes it failed with `not assignable`. Any idea about this?


Phantom template file?

Question: I've inherited a site running a custom Zen sub-theme.
It uses standard CCK content types with several "page-node-" and "node-" template files for layout control.
The original designer used the .tpl files to manually embed various views and blocks (with specific HTML structure for styling) into different pages throughout the site.  As you can imagine, these views and blocks can not be directly configured through the UI.
One page however has some block like sidebar image elements that cannot be manipulated through the UI and appear to be embedded via a template file, but I can't find a template file in either the sub-theme or base theme (zen) directory that would affect this page at the page level. There is a node level template, but it only affects the content area, not the right sidebar.
From the source, I can see that they are not actual blocks as they simply have "
" tags around them

 ...

The element between #sidebar-right-inner and #block-block-39 simply has a
 tag with no drupal classes or ids.  This is what needs to go.  Block-block-39 has been configured through the "blocks" administration page and is supposed to be there.
If it were indeed embedded via template file, I should have a file like sites/all/themes/mytheme/pages/page-node-15.tpl.php, but I don't.  I've checked Page.tpl.php in both sub-theme and base theme (and every other .tpl file) and cannot figure out how these elements are getting there!  Is there somewhere else that a block of HTML could be embedded?
I've tried disabling Javascript on my browser with no change.  And if it were created through the UI somehow, I'm thinking it would have additional divs wrapped around it or other classes / ids.
I think I have a pretty good handle on how templates work (hierarchically speaking), and I've spent days searching for an answer. I'm sure I'm missing something silly, but I'm pretty stumped at the moment.
I basically need to just get rid of them.
Comment: Disable javascript to see if they might be injecting the content that way.  You can also check if the context module is adding anything.  Another place you can look is template.php.
Comment: Given the `id="block-block-39"` tags, I'd look to see if they have been manually created through the block UI, eg `admin/build/block` and then thus stored in the DB...
Comment: @PatrickRyan Template.php doesn't show any signs of it,  Context Module isn't installed, Disabling JavaScript has no effect. :(  Thanks for the suggestions though.
Comment: @Jimajamma Thanks for the reply. The `id="block-block-39"` div is simply what follows the element that I need to remove.  I've updated the question for clarity.
Answer: Ok, these elements do not display an "edit block" option when I am logged in as an admin and mouse hover them, nor do they display any of the HTML class / id properties which are typically associated with a block.  So It had to be somehow injected or modified VIA a template file.
I did however, finally discover that they were in fact being added via a cryptically named block.
This meant that it was likely being acted upon by a "block-" template. Armed with the newly discovered block number, I found that the file "block-block-22.tpl.php" was stripping the edit link and other divs and formatting to prevent the block from having it's own background etc.
The standard "block.tpl.php" file writes all blocks in the sub-theme like:
<div id="block-<?php print $block->module . '-' . $block->delta; ?>" class="<?php print $classes; ?>">

  <?php if ($block->subject): ?>

<?php print $block->subject; ?>

  <?php endif; ?>

    <?php print $block->content; ?>

  <?php print $edit_links; ?>

Whereas "block-block-22.tpl.php" was overriding the default and writing it as such:
<?php print $block->content; ?>

effectively stripping all of the block's formatting so that only the images that it contained would show with no extra margin, padding, background etc.
I had a feeling I was missing something simple...
Furthermore, changing it to:
<?php print $edit_links; ?>
<?php print $block->content; ?>

Enabled the "edit block" link for administrators, so now it can be edited directly from the page.

Phantom template file?


How to create an ordered list starting by 01

Question: I am working on a rails app where I loop over tuto
    .container
      .row
        .col-xs-12.col-sm-12
          h1.text-gray Tutorials
          br
        .col-xs-10.col-sm-5.index-background
         - @tutos.each do |tuto|
            ol.h4.text-white
              li
                h4.text-white = link_to tuto.title, tuto_path(tuto)

I found out this solution, it starts from 01as expected...
ol {
list-style-type: decimal-leading-zero;
}

But it render all the lines with 01.
What did I miss?
Answer: Myolwas not at the right place , just moved it a little bit above :)
 .container
  .row
    .col-xs-12.col-sm-12
      h1.text-gray Tutorials
      br
    .col-xs-10.col-sm-5.index-background
      ol.h4.text-white
        - @tutos.each do |tuto|
         li
           h4.text-white = link_to tuto.title, tuto_path(tuto)


Finding the set of n-bit integers related to a given integer by single bit 'hopping'

Question: Given an n-bit integer, I want to find the set of n-bit integers which are related to my original integer by the interchange of a single 1 by a single 0 where the interchanged 1 and 0 must be adjacent
So what I want is to find some function such that for example, if I gave it the binary 1011 (11 in base 10) it returns 0111 and 1101 (7 and 13 in base 10)
ie. so this would look like:
>>> bit_hop(11, n=4)
[7, 13]

It's important that this function knows how many bits the number is because my other constraint is that I need this to have periodic boundary conditions such that for example 0111 would return not only 1011 but also 1110, ie. the edges of the binary number should be adjacent.
Also, as said, only one swapping should be allowed per hop. This means that bit_hop(1010) should return [1100, 0011, 1001, 0110]
Does anyone have any ideas on how one might go about doing this? I know that this should involve some clever usage of the >>, << and ^ operations but I'm having trouble seeing the synthesis.
Comment: You can locate adjacent 1s and 0s by XORing your number with a 1-bit bitwise rotation of your number, and swap an adjacent 1 and 0 by XORing those bits with 11 (appropriately aligned).
Comment: Why not `1110`? Do the 1 and 0 have to be adjacent?
Comment: Hm, this works when there are only two possible outputs ie. like with `1011` but it doesn't and can't work with `1010` which should give `[1100, 0011, 1001, 0110]`
Comment: Sounds like you're not going through all detections.
Comment: I'm not sure what you mean by detections. Perhaps I misunderstood your previous comment but the only two possible variations I see of your algorithm are `(n^rotate_right(n,4))^n` and `(n^rotate_left(n,4))^n`. Both of these for `n=1010` give `0101` which is not a valid output.
Comment: Yup, you misunderstood. The 1 bits of `n^rotate_right(n,4)` (or `n^rotate_left(n,4)`, either works) tell you where 1s and 0s were adjacent in the original number. XORing that with `n` doesn't make any sense.
Comment: Hm, I see. It was a coincidence that my nonsense worked `1011`.
Comment: Alright, it seems that I've figured it out. Thanks for the help!
Answer: To do this directly in binary, you have to notice a couple of things about the algorithm. First it always deals with adjacent bits, except for looping around from the first bit to the last. Second those bits must be different, if they're the same swapping them wouldn't do anything.
This code walks a 2-bit mask around the value and tests to see if the bits are different, then uses exclusive-or to swap them.
def bit_hop(x, n):
    for i in range(n-1):
        mask = 3 << i
        if x & mask != 0 and x & mask != mask:
            yield x ^ mask
    mask = (1 << (n-1)) | 1
    if x & mask != 0 and x & mask != mask:
        yield x ^ mask

Comment: Yep, this is a very nice, elegant solution!