Persisting a subset of Core Data objects

Question: This is a little strange, but I want to store an array of NSManagedObjects outside of Core Data.
Core Data is managing all of my model's properties and relationships. One such relationship is to all of an Author's Books. Sometimes it is useful to know that same list in a certain order, so I have added booksByDate (for example) to the NSManagedObject Author.
Because the sort descriptor proved expensive, I implemented a cache, using an iVar on Author. This helped a lot with some laggy UI issues I was experiencing. But the cache was only useful after it was first loaded, so when my application launches, I now go and tell each Author to cache its booksByDate. This adds a few seconds to my launch time, but drastically speeds up the performance once the app is running.
I would like to reduce that launch time. One area I am experimenting with is somehow storing each Author's cached booksByDate. At launch, instead of telling each Author to generate its cache using the expensive sort descriptor, I could just pass out each stored cache to it's correct Author.
How might I store these caches so they persist between executions?
Answer: I think the best option would be to have a index member for each book.
When you insert a new book , just loop through the book's author list of books and set the appropriate value for that book's index.
This way , every time you ask for the books , you can sort based on that index.
That will be much faster than comparing by date.
Comment: That's interesting - I hadn't considered that it was the Date part that was having the impact - I assumed it was any sort descriptor. I will give it a try. It would still be interesting to know if what I proposed in my question is possible, though.
Comment: I'm investigating the 'Indexed' option in XCode's Core Data editor - scouting for imformation at http://stackoverflow.com/questions/13022065/indexing-a-core-data-property-to-improve-nssortdescriptor-performance
Comment: Indexing would be an improvement but I guess you are not adding the books in a chronological order. So you still have to order them. Of course the Date comparison is far more expensive than a simple int comparison.
Comment: Even if I add them in chronological order, there's nothing to say I won't want them in a different order later, and experience the same issues. I am going to try managing the index myself as outlined in your answer.


BitBucket server Ctrl M character removal

Question: We observed Ctrl+M character after the BitBucket migration from Perforce almost of the files. Do you have BitBucket-server level options/settings to remove the Ctrl+M chars in all the repository or from each repo/branch?
or else
Let us know if any other method this can be handled
Answer: The canonical way to store text files in Git is with LF endings, even if your project uses other endings, and to convert the line endings on checkout as necessary.  It sounds like your repository has CRLF line endings, and a CR character is also Ctrl-M (byte 13).
Servers do not get to modify data on clone because the integrity of data is verified by the hash, and consequently servers cannot change the line endings used.
If you wish to change the line endings for your repo, the easiest way to do that is to create a file called .gitattributes in the root of your repository with the following content, and then run git add --renormalize ., and commit that together:
* text=auto

This will result in your files being checked in with LF endings and each user can control which line endings are used on their system.  By default, the platform's native line endings are used.
If you have patterns of files, such as shell scripts or PowerShell files, that must always use a given line ending, then you can add lines like this to .gitattributes:
*.sh eol=lf
*.ps1 eol=crlf

You can read more about these options in the gitattributes manual page.


Custom form validation is missing

Question: I have a registration form :

{{ form.status_messages_user_register_form }}

{{ form.field_first_name }}

{{ form.field_last_name }}

{{ form.account.mail }}
{{ form.account.name }}

{{ form.account.pass.pass1 }}

{{ form.account.pass.pass2 }}

{{ form.form_build_id }} {# required #}
{{ form.form_token }}{# required #}
{{ form.form_id }} {# required #}
{{ form.actions }}

Now i want to add custom validation for the registration.I have a custom ajax handler for registration using form alter:
$form['actions']['submit']['#ajax']  = [
         'callback'    => 'custom_register_form_ajax_validate',
         'event'       => 'click',
         '#attributes' => [
           'class' => [
             'use-ajax',
          ],
         ],
       ];
       $form['#attached']['library'][]      = 'core/drupal.dialog.ajax';
       $form['#attached']['library'][]      = 'core/drupal.ajax';

       $form['#prefix']                     = '

';

And this is my function :
function custom_register_form_ajax_validate(&$form, $form_state){

$response = new AjaxResponse();

  $form_state->setTemporaryValue('entity_validated', TRUE);

  $firstname = $form['field_first_name']['widget']['#default_value'];

  $email = $form_state->getValue('mail');

  $pass1 = $form_state->getValue('pass1');

  $pass2 = $form_state->getValue('pass2');

    if($firstname == ''){
         $text = '
Firstname is required.
';
          $response->addCommand(new InvokeCommand('.form-text', 'css', array('border-bottom', '2px solid red')));
      $response->addCommand(new HtmlCommand('#email-valid', $text));
    }
    if($lastname == ''){
         $text = '
Lastname is required.
';
          $response->addCommand(new InvokeCommand('.form-email', 'css', array('border-bottom', '2px solid red')));
      $response->addCommand(new HtmlCommand('#email-valid', $text));
    }
    if($email == ''){
         $text = '
Email field is required.
';
          $response->addCommand(new InvokeCommand('.form-email', 'css', array('border-bottom', '2px solid red')));
          $response->addCommand(new HtmlCommand('#email-valid', $text));
    }
}

I want to validate "Firstname is required" condition.But when i submit and  validate the form,always showing "Email field is required".
How can i solve this issue?
Comment: Would be a huge help you'd follow [Drupal Coding Standards](https://www.drupal.org/docs/develop/standards/coding-standards).
Answer: You're probably not printing something required by the form since you are printing items individually. To start debugging, you can comment your entire form twig out and just use {{ form }} and see if it triggers validation.
At the same time, you are copy pasting the wrong thing in each error case:
      $response->addCommand(new InvokeCommand('.form-email', 'css', array('border-bottom', '2px solid red')));
      $response->addCommand(new HtmlCommand('#email-valid', $text));

This will always apply to elements with .form-email class and #email-valid id.
You're trying to evaluate $lastname but that variable is never set. If the email validation error always shows, then validate that you are using the right key in $form_state->getValue().
Since you are applying it to the same id, you are going to overwrite your own message each time as well. Check the documentation on HtmlCommand. It implements jQuery's html(string):

When .html() is used to set an element's content, any content that was
  in that element is completely replaced by the new content.

You need to provide different divs to print these errors for the users sake, or rethink how you are doing this.
Comment: Thanks for your reply.Can you help me to find out how to get value using $form_state->getValue()?.I have tried with many options,but not working anything.
Comment: `$form_state->getValue('field_name');`... I can't really debug it for you. You'll have to do that and see what the variable/values are.
Answer: What exactly are you trying to do? It looks like you are trying to do custom validation without actually submitting the form?

Custom form validation is missing


jQuery - Show/Hide Conundrum

Question: So I am building a Glossary page, you know, you click A-Z and it shows the words assocated with that letter below.
The problem is, now that I have all the "word blocks" hiding from the get-go ($(".words").hide();) none of them are being shown when I click the letters.
Here is my HTML:

        A

        B

        C

   .... and so on to Z

And the HTML for the words to be shown below. (words removed, just for structure purposes.)

Here is my show/hide javascript code:
$(document).ready(function(){
    $(".words").hide();

    $(".letter").click(function(){
        var whichLetter = $(this).children("span").text();
        $(".words").fadeOut(200, function(){
            $(selectedGloss).fadeIn();
        });
        var selectedGloss = "#glossary-" + whichLetter;
        console.log(selectedGloss);

    });

});

Answer: $(document).ready(function(){
    $(".words").hide();

    $(".letter").on('click', function(){
        var sel = $('#glossary-' + this.id.replace('selector-','') );

        $(".words").fadeOut(200, function(){
            sel.delay(200).fadeIn(200);
        });
    });

});

FIDDLE
Answer: try declaring the selectedGloss to be the first line within the  ".letter" click function.
Comment: Also, try putting a breakpoint inside the .letter click. Then you should be able to observe if any of the selectors/variables are undefined. Go from there.

jQuery - Show/Hide Conundrum


Remove links from the menu tabs

Question: How can I remove the some links from the Tab, when we are login as a particular user. Please see the below picture. I want to remove the tab Items maked in red rectangle (deny access to this link).

I tried with hook_menu_alter, but it do not worked and also understood, hook_menu_alter only hide the item in the tab.  Please give me a solution. I am using drupal 7 version
Please note:
I am using node gallery module to this content type to attach gallery with a node. I have added roles & assigned role to a particular user. Also give permission form that this content type in permission tab. The problem is that, when we logged as user, only the edit link is disappearing, not the gallery attached  with it. I want to set this in page wise. The same user want to edit the gallery in some page & also want to edit the node. I used simple access module, but no use. it only remove the edit of that page, not the gallery attached with it. I also tried hook_node_access(). For that also the same result.  Please give any solution.
Please see: node gallery permission is separate, which is not connected with a content type. I need to deny below url based on the roles.
1) node/#/items,
2) node/#/upload
3) node/#/sort
Comment: Please add all the info you posted as comments under my answer directly to your question.  It would be a waste of time if someone answered in a way that does not satisfy you and only after discovered that his answer is not applicable due to requirements you knew, but omitted in question.
Comment: Looking at the permissions screenshot, it seems that you've configured all authenticated roles to be able to see the tabs except administrator (which seems a bit weird!). Which role _shouldn't_ be able to see the tabs? (Btw I've just looked at node gallery's `hook_menu()` and it seems this should all be possible via permissions unless I've missed something.)
Comment: Andy, I need to give permission to different nodes of same content type based on the role. So I need to check those.
Comment: I need to deny below url based on the roles. 1) node/*/items 2) node/*/upload 3) node/*/sort.
Comment: IIUC you want to remove the node gallery tabs _Sort Items_, _Manage Items_, and _Upload New Items_ for certain roles. These tabs should only be shown if the role has the appropriate permission. So if you can say which role shouldn't be able to see the tabs, I can help debugging based on the permissions screenshot.
Comment: Andy, Node gallery is connected to a content type. I created a content type 'Home' and node gallery is associated with it and created 3 content using "home" content type.I created three roles. Based on the role i need to give permission to three pages. So that I need to give permission for content type "Home" & "Node Gallery". I am working on the three page of same content type. I tried simple access module, but it only give access to edit of the content type, not with the gallery attached with it.
Comment: I'm afraid I don't understand that update. I'm not sure why you're not sharing which role shouldn't be able to access the tabs?
Comment: Role Flexi should not able to access the tabs
Comment: Thanks. Can members of _flexi_ create galleries themselves? If yes, should they be able to edit/manage/upload to their own galleries?
Comment: Andy, Node gallery is something, which is always attached with a content type. admin can connect gallery to a content type while a admin create a content. This is not an applicable solution
Comment: Shino I know what node gallery is. I'm looking directly at the code that decides whether those tabs should show up. It's based on permissions. Before I can give you a definite answer I need you to answer my previous comment (it makes a difference!).
Comment: yes. Flexi role should able to edit/manage/upload their own galleries
Answer: You can give permissions to menu links according to role.give permission to the above links then they will appear as per according to roles.
use the below given module for permissions as per role
Menu per Role
May this will help you.
Comment: Please note: this is not menu, this is a tab in a page. actually I printing tab (print render($tabs)) in the page.tpl.php
Comment: @Shino tabs are menu local tasks in Drupal (usually)
Comment: only drupal 6 version Menu per Role is available.
Comment: you can use dev version of it
Answer: As I understand it, you'd like the following behaviour:

if a user with the flexi role is looking at their own gallery, they see the three tabs;
when looking at someone else's gallery, the flexi user can't see the three tabs.

I believe you can do it with permissions. The flexi role:

needs: TYPE: Create new content, TYPE: Edit own content
mustn't have: Administer content, Administer Node Gallery Settings, Upload to All Galleries, TYPE: Edit any content

Replace TYPE with the node gallery content type(s) that flexi users can create.
Comment: Andy, It is a live project. Also already contents are created & need to give permission to the same content type, based on role
Comment: @Shino I'm sorry I don't really understand :/ If your site is live, I'd definitely suggest ensuring the permissions are appropriate (eg. from your screenshot _flexi_ users can administer node gallery settings, which from your comments you clearly don't want!).
Comment: Andy, I  am sorry. you didn't understand my requirement.
Comment: @Shino So the description of your requirement at the beginning of my answer is incorrect? Or maybe incomplete?
Comment: Yes. The problem is that I was not able to describe my requirement properly.

Remove links from the menu tabs


Abrir div ao passar mouse por cima do input text

Question: Eu tenho esta div, onde o input text está dentro:

                        <input type="text" asp-for="FornecedorID" onkeypress="return BuscaDados(event);" onblur="CarregaFornecedor(this.value);" class="form-control" name="FornecedorID" id="idfornecedor" />

E essa é a div que eu preciso que mostre, ao passar o mouse na div passarmouse,

Tentei por css porém não está dando certo:
    #mostrar {
    display: none;
}

#passarmouse:hover #mostrar {
    display: block;
}

Como posso resolver? Pensei em colocar tipo um modal então.
Comment: Se div #mostrar vem logo depois da div #passarmouse, isso deve funcionar `#passarmouse:hover + #mostrar {
    display: block;
}`
Comment: se `#mostrar` não é descendente de `#passarmouse` não funciona, pois o teu seletor CSS é de descendência, ou seja, *para qualquer elemento que tenha id 'mostrar' e que tenha um descendente com o id '#passarmouse' aplique as propriedades abaixo.*.
Comment: você não pode fazer um seletor (por exemplo #passarmose) selecionar outro elemento (#mostrar). você consegue agir no próprio elemento do seletor ou num dos filhos no máximo, o que você quer fazer vai precisar usar `javascript`
Comment: Cara já tento usar o evento onFocus do javascript para isso?
Comment: @Thayllervilelacintra não tentei.
Answer: Atere seu  css para

#mostrar {
    display: none;
}

#passarmouse:hover + #mostrar {
    display: block;
}

     <input type="text" asp-for="FornecedorID" onkeypress="return BuscaDados(event);" onblur="CarregaFornecedor(this.value);" class="form-control" name="FornecedorID" id="idfornecedor" />

    aaa

     bbb

     ccc
     ddd

      eee
      fff

Ao adicionar  o  sinal  de  mais você estará indicando que o evento deve ser adicionado a div mostrar
Comment: @fernandosavio na verdade até está funcionando, só que por algum motivo ele colocou o texto na cor branca, ai não parece quando faz o :hover pq o fundo tb é branco. O que ele podia fazer é dar uma explicação melhor mesmo, citar links de apoio etc, mas ele tb não é obrigado a isso, vai de cada um...
Comment: Só pra esclarecer que é para ser uma crítica construtiva para não confundir quem ler a resposta. Não é nenhum ataque pessoal. @hugocsl, explicar ou não explicar vai de cada um, porém não dá pra fazer uma afirmação que não é verdadeira, pode ser que alguém tome como verdade e aprenda errado. Mas enfim, os comentários estão aí pra isso. Bola pra frente
Comment: O `+` é o [seletor de elemento adjacente](https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors), não implica de maneira nenhuma que o evento deve ser adicionado à div `#mostrar`. As regras CSS sempre são aplicadas ao seletor mais a direita.
Comment: @fernandosavio >> http://jsfiddle.net/ego3cafh/ funcionando desta forma
Comment: Marcos, não estou dizendo que o código não funcionará (apesar do Fiddle não estar funcionanado). O que estou dizendo é que não adianta dar um código funcionando e explicar errado o porquê de estar funcionando. Não existem eventos sendo adicionados ao `#mostrar`. O `#mostrar` simplesmente satisfaz o seletor que é ser um elemento adjacente e posterior a um elemento `#passarmouse` que esteja no estado de `:hover`.
Comment: @MarcosBrinner não funcionou no meu exemplo, achei que era porque tinha uma outra div do lado, que estava atrapalhando ela de aparecer, porém mesmo sem ela, não funciona.
Comment: Após fechar a div `passarmouse` depois da div `mostrar` o meu código mesmo funcionou.
Comment: excelente, que bom  q  de uma forma ou  de  outra conseguiu  resolve-lo
Comment: E adicionei uma class pra que ele fique flutuante: `.div_teste {
        width: 350px;
        height: 120px;
        background: #ffffff;
        position: absolute;
        z-index: 100;
        top: 30%;
        left: 40%;
        border: 1px solid;
    }`


Displaying from Nodejs ExpressJS route to EJS view

Question: I render the calc.ejs from calc.js router like this:
// calc.js router
router.get('/calc', function(req, res, next) {
  res.render('calc', {page:'Calculator', menuId:'Calculator', result: ''});
});

My calc.ejs is :
// calc.ejs view
<form action="/user/calc" method="post">
    <input type="number" name="num1"/>

    <input type="number" name="num2"/>

    <input type="submit" value="Submit"/>

</form>

<% if( result ){ %>

 Display result here!!! :  < %= result %>

  <% } else{ %>

No Result

 <% } %>

And I have my calc.js controller which takes two numbers, calculates and returns them as json, but I want to display the result in the paragraph element in calc.ejs
// calc.js controller
exports.calc = (req, res, next) => {
    let rezz = Number(req.body.num1) + Number(req.body.num2)

    res.status(200).json({
      result: rezz
    });
 }

I get this json  :
{"result":46}

My question is why the result doesn't display in
 element but comes as json, and how to display it there..
Thanks in advance !
Answer: In ejs :
< %= result %>  // this is wrong
<%= result %>   // this is right

In your controller, you can direct render your view and it should be:
exports.calc = (req, res, next) => {
    let rezz = Number(req.body.num1) + Number(req.body.num2)
    res.render('calc',{
        page:'Calculator',
        menuId:'Calculator',
        result: rezz
    });
 }

Answer: you can again render view in calc function
exports.calc = (req, res, next) => {
    let rezz = Number(req.body.num1) + Number(req.body.num2)
     return res.render('calc', {page:'Calculator', menuId:'Calculator', result: rezz });
 }

if you want to use json then you have to call ajax function on form submit and send request and display returned response in view


How to set precision for double data type variables in C?

Question:
Possible Duplicate:
Most effective way for float and double comparison

In my program some double variables take values of the form 1.00000001. Equality check of these variables with 1 obviously fails.
I wanted to know how can I reduce the precision of double type variables in c, so that equality with integers works.
Comment: http://stackoverflow.com/questions/17333/most-effective-way-for-float-and-double-comparison
Comment: What would be the intended behavior if the value is `1.5` ?
Comment: @J.N. For `1.5` equality should return false. Let us say, anything after fifth decimal place should be ignored.
Comment: Why the fifth decimal place? There are two problems with that. First, a number very slightly below 1.00001 and a number very slightly above 1.00001 will be reported as not equivalent even though you might want otherwise (because they differ only because of rounding errors, not because of actual difference if computed with mathematical exactness). Second, you should have a basis for setting the threshold for considering numbers to be equivalent. You should know how much error can be produced in the values you are comparing and how much error your decision can tolerate.
Answer: You should almost never check floating point values for exact equality, expecially when they comes from comutation. You should check the absolute value of the difference from the compare value being less than a certain epsilon. The "precision" of the double is given by the internal number representation and you can't change it.
How to exactly choose epsilon can be difficult, there is some comment to that answer discussing that, read it, but you eventually come with the pratical epsilon based equality.
Comment: The double variables are returned by a linear program, therefore I can't do without the equality check.
Comment: The question linked by @Lucas suggest being extremely careful when doing so.
Comment: @stressed_geek you just have to change your if from == to abs(a-x) < epsilon ...
Comment: this suggestion is wrong in many ways, `abs(a-x) < epsilon` is a good idea only for numbers close to zero (both `a` and `x`) otherwise relative epsilon or ulps. And you sometimes have to compare doubles using `==`
Comment: @unkulunkulu I agree, but you'd better say why ;)
Comment: @unkulunkulu everybody would appreciate to know why.
Comment: @FelicePollano, complete answer is here http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
Comment: @unkulunkulu and J.N comparing doubles for exact equality is always wrong.
Comment: @FelicePollano, say I have an input from the user and I want to count the numbers that are non-zero, in this case comparing directly is the only way to go. Also, recently I had a queue simulation system at my hands and I had to estimate the waiting times distribution, sometimes the client gets served immediately after arriving , I used direct comparison and I was right.
Comment: @unkulunkulu I remove the never with "almost never"
Answer: There's no portable way, no.
With the GNU C library, you can use this API to change the rounding mode.
But in general, it's better to express it with code, so that your expectations become clear and portable:
#define EQUALITY_EPSILON 1e-3  /* Or whatever. */

if(fabs(x - y) <= EQUALITY_EPSILON)
{
}

Answer: You should avoid checking for equality in floating-point comparisons.  Instead, use a precision value epsilon like so:
if (fabs(a - b) < epsilon)
{
    // treat a and b as equal
}

The choice of epsilon is probably complicated, but my knowledge doesn't go that far.
Do a Google search for "What Every Programmer Should Know About Floating-Point Arithmetic".  It's a well-known article that covers all this stuff.
Comment: This is absolutely not correct code. abs is the integer absolute value function. The floating-point value a-b will be converted to integer (by truncation), and the absolute value of that will be compared to epsilon. Any value of a-b less than 1 will be reported as less than epsilon, regardless of how small epsilon is (as long as it is positive). The correct function to use is fabs.
Comment: Oops, I'm used to C++ where it's overloaded. Fixed in edit.
Answer: It doesn't make a lot of sense to 'reduce the precision of double type variables'.  You should probably think instead of using functions such as ceil, floor, and round to make an integer out of your double in a way that you have good control over and then use that integer in your comparisons.
Answer: in C99
#include <stdio.h>
#include <math.h>

int main(){
    double d = 1.00000001;
    int i = (int)round(d);

    printf("%d\n", i);

    return 0;
}


C# MVC RouteBase routing too many redirects

Question: Eu tenho um sistema de todas dinâmico aonde eu pego todos os meus paths, controllers, views e areas a partir do BD.
Meu problema agora é quando eu tento acessar uma página ele me retorna too many redirects response.
O que acontece nessa área é:

Usuário preenche um formulário;
O formulário é postado via AJAX e o usuário é redirecionado via Jquery;
O usuário então faz um agendamento ou visualiza o voucher;

Se o usuário tenta retornar a pagina inicial tanto usando o botão de voltar ou alterando a URl ele cai em um loop de redirect, isso ocorre porque nas páginas de agendamento e voucher eu tenho uma verificação de session, se ela for nula eu faço o redirecionamento de volta ao inicio(formulário), esta é a verificação de redirect:
if (TempData["LeadID"] == null || Session["UnidadeCE"] == null)
{
    Response.Redirect( HelperMethods.CreateLink( Request.RawUrl.TrimStart( '/' ).Split( '/' )[0] ) );
    Response.End();

    return null;
}

Agora, o que é estranho é que quando ele tenta mudar a página o RouteBase tenta recuperar as informações desta nova URL e neste momento por algum motivo ele acaba pegando a mesma página, de agendamento, ao invés da página de form e daí começa todo o looping.
O pior é que isto só acontece na primeira vez, por exemplo:
Preenchi o form, cai no agendamento e fui para o voucher, tentei retornar cai em loop, espero e dou um refresh, carrega a pagina normalmente.
Como o código é meio extenso eu coloquei ele em um bin: http://pastebin.com/yTdWKMp4
E tem também os headers dos requests:
HTTP/1.1 302 Found
Cache-Control: private, no-store, max-age=1
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Expires: Wed, 25 Nov 2015 19:01:23 GMT
Last-Modified: Wed, 25 Nov 2015 19:01:22 GMT
Etag: ""
Location: /teste-lp
Server: Microsoft-IIS/8.0
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-UA-Compatible: IE=Edge,chrome=1
Date: Wed, 25 Nov 2015 19:01:22 GMT
Content-Length: 115

HTTP/1.1 200 OK
Cache-Control: private, no-store, max-age=1
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Expires: Wed, 25 Nov 2015 19:02:10 GMT
Last-Modified: Wed, 25 Nov 2015 19:02:09 GMT
Etag: ""
Server: Microsoft-IIS/8.0
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-UA-Compatible: IE=Edge,chrome=1
Date: Wed, 25 Nov 2015 19:02:12 GMT
Content-Length: 6852

EDIT
Depois de muito debug e checagem de vars ( tenho cerca de 6k rotas dentro do pageList ) eu descobri que o problema está sendo na hora de verificar o valor e atualizar a variável.
Na linha 128 do arquivo do pastebin eu recebo uma lista de rotas e procuro dentro dela a rota que me interessa, na linha 167 é o caso do voucher, eu verifico se tem este nome na URL e procuro a rota correta, como esta é uma rota "genérica" para as três áreas ( form, agendamento e voucher ) eu preciso colocar o Controller e Action que eu quero. Neste momento eu estou atualizando uma variável local, mas acabo atualizando também o parâmetro pageList.
Eu também já tentei colocar uma outra variável pages dentro do método da linha 128, copiar o pageList para ela e depois realizar a busca dentro dela. o pageList também acaba sendo atualizado assim como o Cache, linha 202.
O que pode estar gerando isso ?
Answer: Depois de um pouco de pesquisa eu descobri que o meu problema estava na verdade relacionado ao cache do .NET, eu não havia utilizado o método clone.
Se o clone não for utilizado o valor copiado de um Cache manterá um "link de referência", e com isso quando eu estava editando algumas informações nas rotas ele estava aplicando esta alteração ao cache e com isso caindo em um loop de redirect.
No meu caso acontecia isso porque na para cair na página de agendamento eu preciso alterar o valor da Action pois a rota de cadastro é genérica ( mesma rota existente no BD server para o cadastro, agendamento e voucher ), quando eu alterava o valor a rota original ficava sempre apontando para a Action Agendamento ao invés da action Index e quando caia na verificação de uma Session ele fazia o redirect.
Como expliquei acima, consegui resolver o problema implementando o Clone para estes objetos, atualizei o meu doc no PasteBin ( http://pastebin.com/yTdWKMp4 ) caso alguém queira entender como funciona.


BEM approach for an element than can belong and look different depending on the Block?

Question: Let's say I have a styled checkbox (think material design, where there is a bit going on to achieve the desired checkbox style). Which block is responsible for modifying a parent-dependent child block?
Example Component - Checkbox
So I have the following:

        <input class="Checkbox__input" type="checkbox" checked=true />

        {label}

I style up each element within the block for the base checkbox. Within the context of the application, the checkbox block can live in many other blocks (with their own BEM structures).
Example of other blocks
The checkbox with have slightly difference appearance when say within the "Compact Panel":

Disclaimer.. [text]

    <Checkbox label="I Agree" />

Option One - Parent "knows" about child
So.. should the Compact Panel be "aware" of the various children blocks, and style them, so:
// Checkbox.scss
.Checkbox {
    margin: 15px;
    // .. other
}

// Panel.scss
.Panel {
    &.Panel--compact {
        margin: 0;
        padding: 2px;
    }
    &.Panel--compact .Checkbox {
        margin: 0;
        padding: 1px;
    }
}

Option Two - Child "knows" about parent
Or, the panel has zero awareness, and the checkbox checks for parent scope.
// Checkbox.scss
.Checkbox {
    margin: 15px;
    padding: 15px;
    // .. other
}
.Panel.Panel--compact .Checkbox {
    margin: 0;
    padding: 1px;
}

// Panel.scss
.Panel {
    &.Panel--compact {
        margin: 0;
        padding: 2px;
    }
}

Option Three - ?
Maybe there are other options.
Answer: Usually with BEM if they look different, they are different.
Usually.
There are a number of different choices for handling context and state with BEM. Each has different pros and cons, so which you use will depend heavily on your use case.
The first option I'll mention is to use descendant selectors. You've already identified this choice, and are running into the usual problem of "where does the code belong?"

For the following examples, I'm going to rely on LESS syntax, this is only to make it easier for me to demonstrate relationships in the code.

Descendant Selector
If you're going to use a descendant selector, I recommend that the code be grouped with the child block.
widget.less
.widget {
  &__container {
    ...
  }
  ...
}

checkbox.less
.checkbox {
  &__label {
    ...
  }
  ...

  // using inversion to override checkbox styles in a widget
  // this will render to `.widget .checkbox` instead of
  // `.checkbox .widget` due to the `&` placement
  .widget & {
  }
}

The reason I recommend associating the styles with the inner block is because the styles will affect the checkbox, and the cascade order will be important.
If the styles were associated with the parent, reordering the parent styles relative to the child styles could adversely affect how the styles render.
Consider this inclusion order:
site.less
@import 'widget';
@import 'checkbox';

If the styles were part of the widget, they could be overridden by a selector of equal specificity in checkbox.less.
Modifiers
I recommend using modifiers for state. I don't generally consider position or context to be "state", so modifiers may not be appropriate. Additionally, multiple modifiers on the same element can be difficult to reason about and therefor difficult to style.
Assuming you're not using a modifier on the checkbox block, then it may be simpler to add the modifier for the case where it's used in a panel.
.checkbox {
  &__label {
    ...defaults...
  }
  ...defaults...

  &--alt {
    &__label {
      ...overrides...
    }
    ...overrides...
  }
}

Of course, this requires that the markup be updated for the particular case where it's used in a panel, but then it also opens you up to using the checkbox with the same styles elsewhere.
Different Selector
I'm going to reiterate my first point: If they look different they are different.
This doesn't mean you have to start from scratch on the checkbox. BEM allows for object oriented styles. Come up with a new name, and extend* the checkbox:
checkbox.less
.checkbox {
  &__label {
    ...
  }
  ...
}

checkbox-2.less
@import (reference) 'checkbox';
.checkbox-2 {
  .checkbox;

  &__label {
    ...overrides...
  }
  ...overrides...
}

* in LESS I'm using a mixin for this as it's generally better suited toward extending and overriding styles than using the :extend feature of the language. Feel free to use the :extend feature, just be aware that selector order will matter.
Refactor the Need Away
Sometimes I run into cases where I want to use a descendant selector or modifier because I need to bump a block for positioning purposes in a container.
In these cases, I often find that the container itself is what should be changed. I can usually tell that it's the container when I need to update the child to have different:

margins
padding
position
top, right, bottom, left
width
height
flex

Refactoring comes with other challenges, however I often end up using container divs to normalize the insertion region for blocks that contain other blocks; YMMV.

tl;dr: Which Should I Pick?
Can you (reasonably) update the markup?
YES: If you can easily update the markup to use different classes, I'd recommend extending your checkbox block as a new block. Naming things is hard though, so be sure to document which one is which somewhere.
NO: If you can't easily update the classes, using modifiers wouldn't be a great choice either. I'd recommend skipping that one, and falling back to the good ol' descendant selector. In BEM you really want to avoid descendant selectors, but sometimes they're the right tool for the job.
Comment: @Chris, I'd have answered this days ago if I'd seen it. It's a good question, and it touches on some of the advanced parts of BEM that make it really powerful.
Comment: The timer makes it more dramatic. Thanks again, I will read over it a few times in the coming days to make sure it sinks in. I think powerful answers like these step through the thinking behind a decision as well as the decision itself
Comment: Dude - with 5 mins on the clock, you have nailed the answer. Esp. this line "The reason I recommend associating the styles with the inner block is because the styles will affect the checkbox, and the cascade order will be important." -- This is the sound logic I was after - Awesome
Answer: According to this documentation, the use of nested selectors should be avoided in BEM, but "is appropriate for changing elements depending on the state of a block or its assigned theme". This means that you can use a block's modifier to style its elements, but I couldn't find any mention of using a block's modifier to style its child blocks.
I think the best approach would be to add modifiers to both .Pannel and .Checkbox blocks, like: .Panel--compact and .Checkbox--context-compact. This way you won't create a dependency between them, which is a BEM principle.
If somehow you can't add a modifier to .Checkbox depending on it's context, I think the closest option would be the second one, where the child behaves differently depending on the state of its parent.
Answer: This is the "right" way:
I'm quite surprised why the accepted answer doesn't mention BEM "mixes".
In these scenarios, that is, when a block should change style when used within another block, the official BEM documentation recommends using a block AND an element class on the same DOM node.
So, in your case, this would be the markup:

Disclaimer.. [text]

And this would be the CSS/SCSS:
// Checkbox.scss
.Checkbox {
    margin: 15px;
    padding: 15px;
    // .. other
}

// Panel.scss
.Panel {
    &__checkbox {
        margin: 0;
        padding: 2px;
    }
}

It's really that easy and simple. The other answers are overcomplicating this unnecessarily, and I don't know why, the BEM documentation has a clear answer to this question. You can also find many articles online that explain the very same technique I just described.
Answer: I recently started a react project and I would like to share my experience on styling react components.
Cascading styles within react components are really confusing. So first thing is try to write class per element. If you want you can wrap using a main class which defines the component.
.panel {
  .checkbox {

  }
}

I use css-modules. This is super awesome. This tool can create unique classes so you don't need to worry about duplicating same name in other components. You can learn more from their git page and there are many articles online.
If you are using sass and need to use variables you can define a separate sass file in a different folder (let's say ../assets/variables.scss), in your component scss file you can import it and use all variables. Same goes to mixins and functions.
In your case don't worry about child and parent relationship, write single classes for all elements you need to style. Sometime you may need to target children using parent.
A good read
Comment: this is not BEM methodology. The OP requested for a BEM approach to this
Comment: Your very last sentence is what I am looking for more information on "sometimes you may need to target children using the parent" - a detailed answer outling the how and why around parent children relationships in BEM is basically what I am after


How capture an error like "Package Validation Error"

Question: I what to read some Excel files put by users into a share folder. The issue occurs when the user changes the sheetname or changes the location in some rows or columns used to share data.
In this situation, SSIS show a Package Validation Error.

Package Validation Error------------------------------Package Validation Error------------------------------ADDITIONAL
  INFORMATION_Error at PackageName [SSIS.Pipeline]_ Leer Staging Modelo
  LS2 failed validation and returned validation status
  _VS_NEEDSNEWMETADATA_.Error at PackageName [SSIS.Pipeline]_ One or more component failed validation.Error at PackageName_ There were
  errors during task validation.
  (Microsoft.DataTransformationServices.VsIntegration)------------------------------BUTTONS_OK------------------------------

Is possible to capture this kind of error using the event handler or other option to detect the errors?
Comment: One thing you could do is write something to validate the files BEFORE trying to import them.  Then handle the error that way and send email or something if the validation does not match what you expect.  You should be able to do this relatively easily (if you know c#) in an SSIS c# script task.
Answer: You can add an Event Handler for the OnError event of the Data Flow Task and read the error description from the System Variables @[System::ErrorCode] and @[System::ErrorDescription]:

System Variables for Event Handlers

If you want to learn more about Event Hanlders check the following article:

SSIS Event Handlers Basics

Update 1 - Workaround
You can use a Script Task to check if this excel file exists or no using the System.IO.File.Exists() method.
Then you can use Microsoft.Interop.Excel library or System.Data.Oledb to check if the worksheet exists within the Excel file:

Using Excel OleDb to get sheet names IN SHEET ORDER
C# - Retrieve Excel Workbook Sheet Names.
Comment: I tried with event Handler, put was not possible to catch the Package Valildation Error, another option??
Comment: @MarcosMorales please show what you tried. So i can help you
Comment: @MarcosMorales if you are looking for a workaround check my answer update


Sendmail slow to accept emails

Question: I have a PHP web app which is using SMTP to sendmail on localhost to send email.
I would like sendmail to accept the mail request immediately and queue it for later sending, as I don't want to have user-facing request threads blocked on emails.
Sendmail is installed with the default settings on RHEL web servers.
Sometimes sendmail is blocking for a long time after the MAIL command is sent -- sometimes taking 60 or 90 seconds to accept the mail. The time take is usually very close to 60 or 90 sec, which makes me think this is some kind of timeout.
I have looked in the sendmail logs, and there are plenty of "deferred" emails, but nothing which looks responsible for this delay.

How can I diagnose what is slowing down sendmail?
How can I configure sendmail to always accept the mail immediately and to queue the mail for later sending?

Update: I'm not sure, but it looks like this might be linked to aol.com addresses. I strongly suspect that sendmail is doing some kind of blocking receipient address verification at the accept-email-for-sending stage. How can I disable that, so that sendmail doesn't block my UI threads?
Update 2: This only seems to happen at busy times. Perhaps I am running out of sendmail threads or something? How can I check that?
Comment: I'd look at DNS settings - if sendmail is e.g. trying to check whether the HELO matches the hostname of the sending server, or whether the server has correct DNS records, a DNS timeout would match the times you're seeing.
Comment: 1) Have you considered using sendmail progmail directly (without SMTP)?  2) Check your sendmail.cf for 30s settings. I do not remember any default sendmail setting casin n*30s delays at "MAIL FROM:" (I remember something but at SMTP connection setup stage)
Comment: I looked in the sendmail config, and I couldn't see anything relevant. Please could you be more specific? What settings should I check?
Comment: @Rich Start by checking if DNS lookups function properly from that server, e.g. by using `dig` to lookup www.google.com
Comment: DNS works fine.
Answer: There are several sendmail tuning parameters that can affect the initial delivery attempt.  Have a look at Sendmail Tuning.
Comment: I don't have a reproducible test case, so I can't really sniff the traffic. I have given up on fixing sendmail, and I wrote an app-layer email queuing system that pipes emails into sendmail in a background thread, to isolate my app from these random delays.
Comment: Thanks, I've had a look in there and I can't see anything that affets me. The "`DeliveryMode`" is set to "b deliver in background (asynchronously)". I still can't explain why I'm seeing long delays at the accept email for delivery stage from `sendmail` during busy times. I strongly suspect `sendmail` is doing some kind of recipient verification. Any ideas?
Comment: Puzzling.  May be time to breakout [Wireshark](http://www.wireshark.org/) and find out exactly what network traffic you have at each "stage" of your mail delivery.  You could also monitor the mail queue to see when files "arrive".
Answer: I have been unable to fix sendmail, so I wrote an app-layer queue to hold emails before they go to sendmail, which negates this problem for me.
The emails are queued on disk by the web request threads, and then a single background thread (per web server) passes the emails to sendmail from that queue.
I have added extra logging, and sendmail is still occasionally blocking when receiving emails (now only for 5-15 seconds). I had thought sendmail was designed to accept all the emails immediately, without blocking, and then attempt to deliver them to their final recipient in the background on its own queue.
The frequency of slow emails is now much lower. I wonder if part of the problem is that sendmail was running out of "receive" threads.
In my original setup, all the PHP request handling threads would pass their emails into sendmail (via SMTP) as soon as a user action caused an email to be sent. At busy times, this must have meant that sendmail was receiving lots of emails in parallel. It was occasionally blocking for 60-90 seconds (which was disastrous for my app's performance).
Now that I have added this app-layer queue, which pipes emails to sendmail on at most 1 thread, sendmail appears to be able to cope fine (most of the time) with the same volume of emails without blocking at all. It does occasionally block though, which makes it unsuitable as an email queueing layer.

Sendmail slow to accept emails


Set page title from DataProvider value yii2

Question: I have a view event and it has a extra action button which redirects to checkin/index page
here is my gridview
<?= GridView::widget([
    'id'=>'event-table',
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        'title',
        'location',
        [
            'class' => 'yii\grid\ActionColumn',
            'template' => '{checkin/index} {view} {update} {delete} ',
            'contentOptions' => ['class'=>'action-td'],

            'buttons' => [
                'checkin/index' => function ($url,$model) {
                    return Html::a('
'.EventSearch::showCheckin($model->id) .'
', $url,['data-pjax' => true]);
                },
            ]
        ],
    ]
]);

When use clicks on that button it will open a checkin/index page
so i want to send the title of the row on which the button was clicked so that
on the checkin/index page i can use that title as $this->title
is there any way to pass data on action button click
here is my checkin/index code
public function actionIndex()
{

    $searchModel = new CheckinSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

I cannot use below code because my $model will only have value of event_id as related table and on checkin/index page i use gridview and relation to display title directly using event.title
$this->title = isset($dataProvider->models[0]->title) ? $dataProvider->models[0]->title : 'empty result';

Comment: You want to pass data with url?
Comment: @InsaneSkulll i just need to set the title of the page.. Anyhow i can... Flow is like this... in the row of `event/index` gridview user will click on the action column button and it will open `checkin/index` page for that particular record... so i want to get the title of the row where user clicked and pass it to next page to set the page title
Comment: you can simple pass the data with url and get them on desire page and pass it  to page title.
Comment: @InsaneSkulll yeah  but how.. i have given the code of `event/index` gridview in the question and the code of action column.. Can you tell me how to do that???
Comment: ok..i will post my answer very soon.
Comment: @InsaneSkulll hey mate.. still waiting for the answer
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/91160/discussion-between-insane-skulll-and-mike-ross).
Answer: For Example,
'buttons' => [
    'checkin/index' => function ($model) {
       return Html::a('
', Url::to(['checkin/index', 'title' => $model->title]), $options);
     }
],

In your checkin/index:
 $this->title => $_REQUSET['title'];

For more read a() and to().
Comment: thank you for your help once again... it helped.. Had to modify it a little bit but solved my problem


View Mode not showing up under Manage Display

Question: I created a view mode let's call as my_node_view for content type under display type settings, I was expecting it to show along with default and teaser tabs as default|teaser|my_node_view in manage display section, but it did not show up. I have ensured my_node_view is checked under custom display settings for Use custom display settings for the following modes. Am I missing anything?
Comment: Did you try a cache clear? I remember seeing an issue that a manual cache clear is necessary for this. @PHP Weblineindia: There is no code necessary for any of this in D8.
Comment: You need to provide the code here. That way only we can help.
Comment: @Berdir clear cache did the job, can you please add it as answer, I am adding it in drupal issue queue as configurations should not require a manual cache clear.
Comment: Added issue on D.O. https://www.drupal.org/node/2422293
Answer: Writing out my comment as an answer.
This apparently needs a manual cache clear right now to work.


hive queries with jdbc spark sql

Question: I have java application which runs multiple hive queries using jdbc connection.
Will i be able to run the same queries just on spark sql connected with jdbc without using/having hive.
The queries i have now are like creating tables, doing simple aggregations and joins no major transformations happening . I don't have any UDF's.
Answer: Yes, you can do this. Spark sql can be handle all the queires which you prepared in hive and there is no need to hive connection.

hive queries with jdbc spark sql


What 'special' properties do real quadratic fields have?

Question: Sorry for the vague title...  I've proved a number theoretical result for  the imaginary quadratic fields (it was already known for the rationals).  I think it would be much easier to sell if I could prove it for all quadratic fields.  I think to do it will require using some special properties of the field, as proving it for general number fields seems very difficult...
What special properties do the real quadratic fields have, that are not enjoyed by a general number field?
Any and all suggestions welcome.  Also, obviously ones which apply to all quadratic fields would also be useful.  My result for the imaginary quadratic fields relies on the fact that they have only finitely many units, which means that the norm is 'well behaved' in some sense, but this does not help me for real ones.
Comment: This is a ridiculously vague question.
Comment: @samian: It looks as follows to me: You have a result; you don't want to say what it is (perhaps for fear of being scooped; fair enough, perhaps); at the same time, you're not sure it is sufficiently important, so you want to extend it. So you are asking people to list say **everything they can think of** about the fields you want to extend it to, perhaps in the hope that you will see something that will either help you extend it, or that will show what you want is already known. And you want them to do it blidnly, without any idea where you want to go. It's not only vague, it's rather unfair.
Comment: @samian: If your vagueness is indeed because you don't want to disclose your problem, then my suggestion is: write it up, put it up in a preprint server (to establish your priority), submit it if you want, and then you'll be free to discuss it with your priority well-established. If you didn't discuss it because it would take too long, then perhaps this is simply not a suitable question to ask in a site like this, but something to discuss face-to-face during conferences. They still have those, I believe.
Comment: Hmmm I was afraid that might be the case.  I'm not really sure how to make it less vague without going into a lot of detail about my problem though.  Thought it was worth a shot.
Comment: well add detail about your problem if you want anyone to say anything...
Comment: Real quadratic fields are ordered?  Just saying...
Comment: I asked a almost duplicate question some weeks ago: http://math.stackexchange.com/questions/23012/what-is-so-special-about-negative-numbers-m-mathbbz-sqrtm
Comment: @Fredrik: You gave suitable background and context so that the answer wasn't an open ended "Tell me everything you can think of about real quadratic/imaginary quadratic number fields." In my mind, specifying exactly what led you to your question makes a big difference, because then the answers could be direct and relevant.
Answer:
The complex quadratic fields have finitely many units, but the real quadratic fields have infinitely many.
There are only a handful of complex quadratic UFDs but nobody knows yet how many real quadratic UFDs there are.


How to version control PowerApps project in DevOps repo

Question: Does anyone have any input or idea on how to add PowerApps projects into a DevOps repo.
I understand that PowerApps has it's own version control, but I was just wondering if there is a way to version control PowerApps codes into DevOps.
Comment: Hi Did you check out below steps, how did it go? Please let me if you have any question.
Comment: @LeviLu-MSFT Thanks for the touch base, I have not been able to explore this option yet. I will update this at the soonest. Thanks
Comment: Hi @the.herbert. Hope below answer works out for you. Look forward to your update.
Answer: You can use the SolutionPackager tool to extract solution components.
Step 1:
Export your solution using the Export-CrmSolution cmdlet
Export-CrmSolution -SolutionName "SolutionName" -Managed -SolutionZipFileName "SolutionName.zip"
Step 2:
Extract the solution
SolutionPackager.exe /action:extract /folder:.\package /zipfile:"SolutionName.zip" /packagetype:Both /allowDelete:Yes /c
You can add these steps in a powershell script that execute from a Post-Build event in Visual Studio, similar to this:
if $(ConfigurationName) == Debug (
powershell.exe -ExecutionPolicy Bypass -File .\SolutionExport.ps1)
Once this is done you can commit to your repo.
For more details:
https://learn.microsoft.com/en-us/dynamics365/customerengagement/on-premises/developer/compress-extract-solution-file-solutionpackager
Answer: I built a Power Automate Flow which will move your PowerApps Canvas apps to Github for version control. Its not perfect because the PowerApps "source code" has some strange features (such as a .jpg file with a dynamic name for every save!).

Flow
Instructions
Comment: Your repo is not online anymore
Answer: If you have the Powerapps codes, it is very easy to push it into a azure devops repo. You can follow below steps.
However, it would be hard for you to version control the PowerApp project, for its source code is complicated and not nice to read. Please check this thread for more information on Power Apps Community site.
1, create an empty repo from azure devops UI. Click Repos -> click the "+" beside the project name -> choose New repository. Check here for detailed steps.

Then uncheck Add a README

After you create your repo. You will get a guide to add the repo url to your local git repo

2, Then In the local directory for the PowerApps codes. Run below git commad to create a local repo for PowerApps codes. Check this thread for more information
<code>#Then In the local directory for the PowerApps codes

git init
git remote add origin <URL for Azure Git repo>
git add .
git commit -m 'initial commit'
git push -u origin master
</code>
Then the powerapp codes will be pushed to azure git repo.


Factors variables labels coded according number of levels

Question: I'd like to get a R script to count/identificates factors variables levels  and recode labels according this number of levels.
I have a dataframe whith several factor variable. They are coded from "A" to "E" , "A" to "H" or "A" to "D" etc, for example. I want recode to 1:5 , 1:8 , 1:4 etc labels automatically, with one command. I don't want recode label for each one manually.
I saw a way with this command:
nums_fct <- factor(nums, lebels = levels, ordered = T), but this would be for each variable, just what I don't want.
I'm a Stata user in learning R process.I appreciate the help.
Comment: Fyi. If you post a [MCVE] you are more likely to get tested code. My answer below is not tested. It's *your* responsibility.
Comment: IRTFM,
Great!
This code works.
Thanks so much!
Answer: This is the reverse of the usual request to convert character digits to type numeric.
<code>dfrm2  <- dfrm # make copy
dfrm2[ sapply(dfrm2, is.factor) ] <-  # only work on factors, preserve structure of dfrm2
        lapply( dfrm2[sapply(dfrm2, is.factor)],  #
            function(x) { as.character( as.numeric( x)) } )
</code>
Comment: @AnnaPaulaGonçalves : there is a `levels<-` function that will let you reassign the character values of levels. If you need a coded example you should use 'dput` to deliver an unambiguous data object. DO NOT DO THIS IN COMMENTS. Use [edit] facilities to add to you question body.


Cakephp 2.x Stuck with Auth component with different models

Question: I'm coding a app for car selling, i'm stucked with auth component.
I have 3 kind of access:
admin: app owner
dealers: the owners of car dealers
user: people who whach car offers and make questions etc

i'm not working with roles, ech one (admin, dealer and users) has an username and password from diferent models, so i'm very lost.
i'm not asking for codes, i just wanna a good explanation about how can i deal with auth assuming this scenario.
Comment: What are your ideas so far?  What have you found when searching for this? ...etc
Comment: i understand how auth works.. but i dont know what controller i have to call auth, i dont understant how tell to auth what Model i'm using (they always look for users table) etc...
Answer: Well it's just a matter of allowing/denying access for a certain user. If you can recognize the users model in controllers beforeFilter method, you can allow/deny access accordingly with $this->Auth->allow() or $this->Auth->deny() (in beforeFilter method). So maybe you can put some pseudo-role in the session after the login if you don't wish to have it in the db table. You can then put Auths allow/deny in conditions on the pseudo-role stored in Session.
Or have I misunderstood the question?
UPDATE
I just realized that you are probably refering to actual login. Changing the default Model is documented in CookBook. See userModel configuration key. Keep in mind that you are supposed to change this in beforeFilter method.
Comment: but like i said. i dont have a table called users and each user with one role. i have 3 tables for each type of user. like i said too auth component always point to User model..
Comment: See the answer update for the auth always pointing to User model.


Consul node will not be discoverable via DNS due to invalid characters

Question: We are primarily a VM based environment with a lot of microservices that need client discovery, configuration management etc. So decided to use Hashicorp Consul.
we are facing an issue: hostname with the dot(.)
<code>[WARN] agent: Node name "myorg.vsi.uat.xxx.com" will not be discoverable via DNS due to invalid characters. Valid characters include all alpha-numerics and dashes.
</code>
We are unable to change the hostname at the moment. Tried changing the node name using configuration but unable to find success.
is there anything we can do to overcome the issue?
Comment: Were you able to find any solution for the same ? Because I am getting the exact same issue.
Answer: You can write small bash script and use it to startup agent with random uuid as name by providing config file name override upon first run:
<code>    FILE=/etc/consul.d/host_id.hcl
    if [ ! -f "$FILE" ]; then
        echo "node_name=$(uuidgen)" > "$FILE"
    fi
    consul agent -config-file=$FILE #... use your your agent run command with loading file config override
</code>


Dados não aparecem no DataGridView C#

Question: Tenho DataGridView em dois Forms do meu projeto, porém só aparecem os dados em um, e no outro não está aparecendo, já revisei tudo mas parece tudo certo pra mim.
Código do Load do Form
<code>    private void CriarOrc_Load(object sender, EventArgs e)
    {

        dgv_produtos1.DataSource = Banco.ObterProdutosGrid();

        dgv_produtos1.Columns[0].Width = 70;
        dgv_produtos1.Columns[1].Width = 250;
        dgv_produtos1.Columns[2].Width = 70;
        dgv_produtos1.Columns[3].Width = 80;
        dgv_produtos1.Columns[4].Width = 70;

    }
</code>
Código da classe Banco
<code>   public static DataTable ObterProdutosGrid()
        {
            SQLiteDataAdapter da = null;
            DataTable dt = new DataTable();
            try
            {
                var vcon = ConexaoBanco();
                var cmd = vcon.CreateCommand();
                cmd.CommandText = "SELECT idprod as 'ID Produto', nome as 'Nome', medida as 'Medida', qtd as 'Quantidade', valor as 'Valor' FROM tb_produto";
                da = new SQLiteDataAdapter(cmd.CommandText, vcon);
                da.Fill(dt);
                vcon.Close();
                return dt;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
</code>
Answer: CONSEGUI POR MEIO DE UM BOTÃO. COLOQUEI O BOTÃO VISUALIZAR E CODIFIQUEI O BOTÃO NORMALMENTE E DEU CERTO.
AINDA NÃO SEI PORQUE NAO APARECEU NO LOAD, MAS ESSA FOI A SOLUÇÃO QUE ENCONTREI.
<code> private void btn_visualizar_Click(object sender, EventArgs e)
    {

        dgv_produtos1.DataSource = Banco.ObterProdutosGrid();

        dgv_produtos1.Columns[0].Width = 70;
        dgv_produtos1.Columns[1].Width = 250;
        dgv_produtos1.Columns[2].Width = 70;
        dgv_produtos1.Columns[3].Width = 80;
        dgv_produtos1.Columns[4].Width = 70;

    }
</code>

Dados não aparecem no DataGridView C#


How to select a column in pandas based on a name?

Question: I'm trying to select a column.
So I work with the iris dataset. I want to only have the setosa flower for now so I stored it in a variable called Setosa.
Setosa = iris_df[iris_df['Name'] == 'Iris-setosa']
Then I used the df function because I wanted a specific column.
Setosa = df['SepalLength']
Now I made a trace, I want to create a scatterplot. X-axis for sepallength and Y-axis for sepalwidth. But I don't know how to specify that I want it to be on the Setosa flower only?
trace1 = {
    "x": `df['SepalLength']`,
    "y": `df['SepalWidth']`,

I first tried "x": Setosa = df['SepalLength'] and "y": Setosa = df['SepalWidth'] but that doesn't work.
Comment: Could you add a sample of the data are you using? Without it, is difficult to understand what you are trying to do.
Comment: `df` is not a function. It is though the most commonly used variable name for a DataFrame. You can as well use `DonaldTrump` instead of `df`. I think you need `iris_df` here instead of `df`
Comment: mmm, I remember working with this dataset on datacamp (=, try `iris_df.loc[iris_df['Name'] == 'Iris-setosa']`
Comment: @Sheldore Thanks for pointing that out, it still doesn't work even though I changed it to iris_df
Comment: @Datanovice Yeah I already have it sorted now by the iris-setosa but I want to select the SepalWidth column
Comment: `iris_df['SepalWidth'].loc[iris_df['Name'] == 'Iris-setosa']` ?
Answer: Just adding this as an answer since it worked
iris_df['SepalWidth'].loc[iris_df['Name'] == 'Iris-setosa']

Short explanation,
you wanted to return a series where it matched a certain condition, to do this you need to first select the column with either bracket or dot notation and use a .loc or another filter to match your condition.
best of luck


What is the explanation for higher harmonics not being integral multiples of the fundamental?

Question: Looking at this file of a A4 note from a piano, I get this spectrogram (simply using Python code performing a FFT):

Piano A4 spectrum with harmonics values assuming a 440 Hz tuning
I'm trying to understand it (I'm not an expert in harmony). The vertical lines are the locations expected for the harmonics. We see the A4 fundamental at 440 Hz, then the first 4 harmonics of this A4 in decreasing amplitude at the correct locations, so far, so good.
After this, the peaks are continuously sliding from their expected locations, so it rather seems there is a new note at about 2670 Hz, closest are A4 6th harmonics (2640) and E7 tuning (2637), followed by what looks like its two shifted harmonics, the process repeats at about 4000 Hz. I think it's a new note rather than an harmonics because its amplitude exceeds the neighboring harmonics (not sure I'm right).
I can't get the sense of that.
Another attempt with A4 tuned at 458 Hz to have the 11th harmonics matching, this time other peaks don't align with their expected frequencies:

Piano A4 spectrum with harmonics values assuming a 458 Hz tuning
Update: I did this analysis to compare timbres from a tuning fork and from different instruments and detect possible procedural errors. In addition of the previous piano (which maybe a digital one), I got a Steinway sample, and also a sax to verify @ttw 's explanation (verified):

Comparing different instruments using the same tool-chain (tuning fork, piano, piano, sax)
Another explanation could be the E7 string starts resonating with the A4, can someone shed some light on this? Is this usual?
Comment: That could depend on various aspects, including some resonance of the room, but it's likely that your assumption about the E7 string is correct: remember that the higher notes of a piano don't have any dampers (usually they are the last 18-20 notes).
Comment: That depends. Piano tuners generally "stretch" octaves, with higher notes a bit higher than lower ones (see [stretched tuning](https://en.wikipedia.org/wiki/Stretched_tuning)).
Comment: It would be interesting to see a second graph made after covering the undamped strings with something to damp them. That would clarify whether or not they are influencing the initial graph.
Comment: @musicamante: Thanks, that's interesting. Are the notes of the last octaves (of a piano) tuned as exact multiples of the, say, 3rd octave (I mean are the comma issue or the temperament playing a role)
Comment: Seems also to me that the shift gradually increases. If the fundamental is not at 440Hz sharp, but at 441Hz, the 10th harm will be at 4410 and not 440. Maybe getting the maxima of this spectrum as a list would be useful to check that.
Comment: We're looking at 6th harmonics. I wonder if it has to do with the fact that the hammers typically hit the string at 1/6 – 1/7 of the length? Other than that, indeed top strings of the piano are not muted, so they can resonate freely
Comment: @musicamante This picture is in fact an excellent visualisation of the need for stretched tuning. Perhaps you should add it to the Wikipedia article!
Comment: Question for the pianists in the room: are there several strings under this A key?
Comment: @mins, I have a question: is this the same file repitched, or are you generating and recording new sounds?
Comment: Well that's very interesting.  I can think of a few things to try: (1) use an oscillator plugin in an audio program to generate a complex sound, and run it through the same transform.  (2) try multiple live-recorded piano sounds.  It may be that some kind of compression or other effect might have corrupted the sound or something?
Comment: How about procedural samples, like a multi-oscillating synth?  If those show the same effect, then there's something with the FT.
Comment: @mins All these new samples are so fun to look through, and something I could never do myself.  You're a legend!
Comment: Can you not damp the higher strings with a blanket or similar to see whether the effect is reduced or eliminated as @Aaron suggested about five comments back? If you suspect specific strings of resonating you could just damp those with a piece of rubber. As user1079505 says below it, ttw's answer is not supported by its Wikipedia reference.
Comment: Ah, I see that your problem is apparently that you just have an MP3 file, not the instrument – but that ought not to be insurmountable. If you can test an actual piano, then I suggest you also make separate spectrograms of the strings that might be resonating.
Answer: The harmonic series, 1, 1/2, 1/3, 1/4,... only agrees with the physics for thin low-tension strings. A piano (even at the top) has relatively thick, high-tension strings. The harmonics tend to get sharper. There's a formula taking into account thickness and tension. Basically, the higher frequencies are raised by the square root of the tension over the density.
https://en.wikipedia.org/wiki/String_vibration
From some requests, I've added supplements. (I left out the mechanism of inharmonicity; it comes from the stiffness of the string as discussed in the two references.)
Wiki has a summary: https://en.wikipedia.org/wiki/Inharmonicity
This paper shows in more detail the fourth-order differential equations governing the strings. http://www.simonhendry.co.uk/wp/wp-content/uploads/2012/08/inharmonicity.pdf
Comment: I don't believe the quoted article in the wikipedia discusses inharmonicity at all. The factor of square root of tension over density is constant for each harmonic so it doesn't contribute to inharmonicity.
Inharmonicity is related to string stiffness, which is related to its material, thickness, and also string length.
Comment: The point is that tension and density do cause the string's overtones not to match the harmonic ratios. (The same argument applies to Pythagaros' argument about ringing hammers which do not follow the series either.
Comment: Like @user1079505, I see no dependence on _n_ in that factor, so that the predicted frequencies should just be multiples of the fundamental. Can you find another formula that predicts something else, or do a worked example to show how that formula predicts a 9th overtone that is not a multiple of the fundamental? I have added a [plea for an explanation](https://en.wikipedia.org/wiki/Talk:String_vibration#Explanation_of_inharmonic_overtones%3F) to the discussion page of that article.
Comment: See also this study of actual [piano strings inharmonicity](http://www.afn.org/~afn49304/youngnew.htm).
Answer: The explanation and understanding can be found in the physics of vibrating systems (and a little bit in basic definitions).
A harmonic series is defined by the relationship fn = n*f1m n = 1, 2, 3, ...
If f is a frequency, say 110Hz, then the harmonics are 220, 330, 440, ... etc.
A "simple" wave form or signal has a single frequency in it and is described by a trig function, sin(2 pi f t) or cos(2 pi f t).  In this sequence the lowest frequency is called the fundamental.  The set of all such functions can be used to describe almost any function which is quite amazing.  In math we say that the set of all functions {sin(2 pi f t), cos(2 pi f t)} for a basis for a function space.  Expanding any curve as an infinite series of these basic waves is the foundation of signal analysis or harmonic analysis and synthesis (the latter being the construction of a generic function by adding together sines and cosines).
In algebra the simplest function might be a straight line, having 2 parameters, a slope and intercept.  So describing a line with an infinite series of sines would seem foolish.  But in vibration and wave theory the simplest function is in fact a sine.  The aforementioned functions are the simplest solution to the wave equation and describe a wave train of a single wavelength or frequency.  In music this would be a single pitch, in optics it would be a single color (monochromatic).
Each such eave has three parameters that describe it, a frequency, an amplitude, and a phase.  Frequency you know, amplitude is related to volume or power, and phase just tells you how the wave looks at t = 0 sec.  Two waves with the same f and Amp but different phase are the exact same shape but shifted.
Now for the physics.
All continuous vibrating system, tight string, air column in a tube, stiff plates, etc have an infinite set of solutions to the basic wave equation characterized by the frequency (and some other parameters).  Not all of these frequencies obey the harmonic sequence but the two that come very close are (1) the tight vibrating string, and (2) standing air waves in a long thin tube.  These cover most of the instruments in an orchestra.
So, how do all these vibrations come into a single note?  The presence of multiple harmonics in a single note plucked on a guitar for example are the result of the attack.  The initial conditions that determine how the string is set in motion.  The shape of a plucked string will not be a sine or cosine but can be described as an infinite series of these functions.  So when you play a musical instrument including your voice you excite all these harmonics.
The harmonic relation is pretty simple and actually rare.  Most real material systems, including strings, do NOT obey the simple wave equation but contain stiffness terms that are linear, but higher order.  As a result vibrations in a stiff bar, or very tight short string plucked or hammered with enough force will exhibit non-harmonic over tones.  I've done harmonic analysis on very long tuning forks back in college and you can easily tweak out an octave and an augmented 5th.  In fact if you are a well trained musician you can hear it!  And, since the lobe pattern is frequency dependent if you turn the fork you will hear different notes dominate the sound field at your ear.  It's pretty cool.
I would never expect the "harmonics" of a musical instrument to truly follow the harmonic sequence due to the fact they do not obey ideal physics equations.  There are some good sources that describe the corrections to the simple models.  In particular anything by Fletcher and Rossing.
Answer: First of all-  WOW!  So interesting, I hope you come back here and do a lot more of these!
I think what's happening here is the difference between natural harmonics and equal temperament.  If you can find a sample of someone playing the song in just temperament for a long time and then equal temperament, you might throw up.  Not exaggerating, it's really quite jarring.
Let's start with the relationship between natural harmonics and equal-tempered notes to see if that's our cause:
(from Wikipedia)

So I don't think vibrating high strings are the culprit.  If they were, then I'd expect a variety of reinforced harmonics due to sympathetic vibration, not an even drift.  Even if a (human, I mean) tuner were deliberately sharpening upper notes due to some kind of psycho-acoustic effect, you'd still expect 7th harmonics to be way more off than say octave harmonics.
It seems to me, however, that being very slightly off in the primary pitch would lead to the effect you've found.  Can you take your A440 example and compress the whole graph so that the 12th harmonic lines up properly?  I think you'll just find that you've tuned to a 440.1 or something.
Comment: Look at the answer from my comment by the OP under the question, he tried starting from another frequency (445) but not everything matches. Furthermore, equal temperament is not based on harmonics, even if some land quite close. The op asks why the spectrum he gets is not composed only of clean harmonics being multiple of the fundamental. As only one note is played temperament should not play a role.
Comment: Temperament is irrelevant because the data here concern the spectrum of a single pitch.  The overtones of the A4 do not depend on the frequency to which the E5 is tuned, or the C♯5, or anything else.
Comment: What's the actual source for the natural/equal-tempered pitches? The Wikipedia link just points to the image.
Comment: No, but a single piano note actually consists of between 1 and 3 physical strings.  On my piano (the upright), middle A consists of 3 strings.  If they're detuned, how does that actually work out?  Do they kind of average out, like out-of-synch metronomes which will eventually land on the same beat? or will they show up in the FT as a curve instead of a sharp spike, or does the beat get interpreted as a sub-harmonic, or what?  I'm kind of getting excited about this question, because I know hopelessly little about how strings on a single note interact.
Comment: As you demonstrate, E note is just 2 cents off in the harmonic series of A; it's almost perfectly in tune. So playing A note will certainly excite a string tuned to E. The question is rather whether it explains what the OP observed.
Comment: Give me a couple minutes plz. . . I'm currently editing this answer already but doing some thinkin' and some math.
Comment: Oops. . . try now!
Comment: I know equal temperament is not based on harmonics.  It's based on 2^(n/12), which is why the 3rd is a little off and the 7th and tritone are way off as per the chart I listed.  That's why I concluded that it cannot be resonating high strings which are the culprit-- sympathetic resonance would reinforce overtones of unequal spacing, not a geometric drift.
Comment: @Tom it looks like you arrive at pretty much the same conclusion as me: that it's likely a precision issue?
Comment: No, as the op said, even of you shift that does not match... That's what I thought too, hence the second graph
Comment: Hmmmm. . . looking at the 2nd graph, we can see 2 things right away.  First, the primary is clearly not 458Hz.  2nd, the shift gradually increases, seems to maximize at around the 7th harmonic, and then shifts back the other way.  I'm pretty stumped about that-- is there an EQ effect on the original sound?  Is there any possible precision issue with floats used in the Fourier Transform?  I quite intrigued right now, tbh.  I mean, the loudest overtone, the perfect fifth, is WAY off, which seems pretty unintuitive.
Comment: @Bennyboy1973 I did my own analysis of the sound he linked and got similar results.  And maybe I'm fooling myself because I have prior knowledge, but it sure seems like I can hear the inharmonicity too.  I don't think it's a software issue.
Comment: Yeah, there's a definite beat or wah to it, like piano tuners used to listen for when doing relative tuning.  To me, that means that the strings in a single note aren't pitched exactly the same.  I played an A on my upright, which thanks to Covid hasn't been tuned in well over a year.  It is now officially a honky-tonk piano, and it was beating like crazy.  But I played it on an electric keyboard with concert samples, and I STILL hear that wobble.
Comment: @phoog also I think it's not quite true-- I think higher strings, which aren't dampened, WILL contribute to the waveform of lower notes, through sympathetic vibration.  But if you see my answer above, you'll see why I discounted that as an important contribution.
Comment: That's right, it wont.  I'd expect octaves and fifths to resonate very strongly, and 7ths and tritone to resonate poorly, since the equal-tuned strings would be most off from the natural harmonics.  The 5th is very strong in the provided diagram (seemingly TOO strong), but I think that's due to hammer position, which they say is about 1/6th up the string.


Angular : Error trying to diff '[object Object]'. Only arrays and iterables are allowed

Question: i got
Error trying to diff '[object Object]'. Only arrays and iterables are allowed
 this error when i'm trying to get updated data
Get code:
allDatas
  allData(data) {
    this.allDatas = data
  }

Okay So this is Update Code i Write :
updateTodo(currentTodo){
       // console.log(currentTodo)
        this._todo.updateTask(currentTodo).subscribe(
          data=>{console.log(data);this.allData(data)},
          error=>console.log(error)
        )
  }

This Request Comes From Service.ts
updateTask(todo:TodoModel):Observable<TodoModel>{
    return this._http.put<TodoModel>('http://127.0.0.1:3000/todo/updateTodo/'+todo.id,todo,headerOption)
  }

I checked all the things using cosole.log And at the end i got the line from where i got the error let me show you
updateTodo(currentTodo){
           // console.log(currentTodo)
            this._todo.updateTask(currentTodo).subscribe(
              data=>{console.log(data);this.allData(data)}, //Error Comes from this line----------
              error=>console.log(error)
            )
      }

this is the same update code : when i write  data=>console.log(data) in update code then there is no longer error shows but when i use data=>{console.log(data);this.allData(data)} i got this Error:

HTML : where i bind data:

                    {{t.task}}
                    {{t.date.year+"-"+t.date.month+"-"+t.date.day}}
                     {{t.complited}}

                    {{t.task}}
                    {{t.date.year+"-"+t.date.month+"-"+t.date.day}}
                     {{t.complited}}

So allDatas is A array :

JSON Data: Where all oprations are Performed
[{"id":29,"task":"random 5","date":{"year":2020,"month":5,"day":9},"category":"genral","complited":false},null,{"id":31,"task":"task 32","date":{"year":2020,"month":5,"day":31},"category":"genral","complited":false}]

so in short i got error when i update task and getting updated task but i use the same method for post put other data i get perfect result
please someone help me i'm trying to solve this error since very long...
Comment: You need to show the template where the `this.allDatas` variable is used. It looks like the API is returning an object and you are probably trying to loop over it using `*ngFor` directive.
Comment: Does this answer your question? [Error trying to diff '\[object Object\]' in Angular](https://stackoverflow.com/questions/38216857/error-trying-to-diff-object-object-in-angular)
Comment: i think there is no issue of array or object  because in post method i use the same approach at there its working fine
Comment: type of data you get is not an array ?? i saw in console is an sample object
Comment: i Add HTML code i bind date as Different because of format issue i also check by removing date but it shows the same error
Comment: i post JSON where you got idea in which format data are Get
Comment: As per your suggested question : my data are in Array Format
Comment: Post new screenshots in the question. Also it isn't helpful to see some data in the middle of the response. Please post the beginning of the console log instead of something in the middle.
Answer: Try to initialise allDatas: this.allDatas=[]
updateTodo(currentTodo){
          // console.log(currentTodo)
            this._todo.updateTask(currentTodo).subscribe(
              data=>{
               this.allDatas=[]
               console.log(data);
               this.allDatas.push(data)
}

            )
      }

But the best solution is to change the return type of your API to an array []
Comment: i use .push method but it push new data every time and its a UPDATE api ... Check service.ts its put api
Comment: i update the answer init the list before push data in it
Comment: Okay i tried this but it push the new data not perform the put(Update) method
Comment: [Your Output](https://imgur.com/a/qSSyj7g when i refresh all pushed items are gone and also delete record which i use to update
Comment: I think the error [object object] is resolved now, you still need to find out why the data is not as expected
Comment: in console still shows error. it push the data in Variable not in Database(JSON File) so thats why when i refresh the all data's are gone because actual data comes from database(JSON file)
Answer: From what I can understand from your code, you are getting the error because you are assigning an object to an array in allData method.
In the subscription of the PUT request you receive an object and not an array.
This is how your allData method should look like:
allData(data) {
 this.allDatas.push(data);
}

Comment: i use .push method but it push new data every time and its a UPDATE api
Comment: [Your Output](https://imgur.com/a/qSSyj7g) hey i run your code but its not updating my Record it just push the value repeatedly and when i refresh it delete the value with all pushed value and the original record
Comment: the PUT request (update) returns in the request body a JSON object and not an array. that object is your updated todo. I assume you're getting that behaviour you mention above because you're using the `allData` method also for getting all todos. if is that the case, you should keep that method as you already have it and in the subscription of the update request, you should have `this.allDatas.push(data)` (data, in this case, is the object). if won't work create a stackblitz with a reproduction of your code.
Comment: i do this again what you trying to say i totally understand let me show you code and output both [code & Output](https://imgur.com/a/u86Fwpa) here you find 2 images of code and output so when i click update it push new task every time and when i refresh the page all pushed data are gone because its update in Variable not in actual database (JSON file).
Comment: hmm, it seems to me that you are not getting the data from the server as you should. can you post the code on how you retrieve the whole todos from the server? do you get any errors from the server when you're updating the todo? you should also check your network tab to see if the request gives you 200 status code after update.
Comment: In backend i use NODE.JS and it returns with 200. All good in backed just problem is getting new data after updating the data. and if i write `data=>window.location.refresh()` it works fine but it refresh the page thats the problem `data=>allDatas(data)` from this code i get updated data without refreshing the page
Answer: This error is related to *ngFor loop in your html file.
it basically says that  allDatas is not an array.
Verify the type of allDatas using "typeof" make sure it's an array.
EDIT
I saw the second image and it looks like it's an array.
Please also try to validate that array using an online validation tool.. search Google for json validator.
Also move the *ngFor loop from
 to

good luck
Comment: Its an Array type i also attached image that its an array type please check and tell me if i'm wrong
Answer:
try this
   if you use this.allDatas = data; the allDatas refresh and 'allDatas' equals 'data'.
   if you use this.allDatas.push(data); the 'data' newly added into the 'allDatas'

and first create a array  allDatas : Array = [];

   allDatas : Array<any> = [];

updateTodo(currentTodo){
          // console.log(currentTodo)
            this._todo.updateTask(currentTodo).subscribe(
              data=>{
               console.log(data);
               this.allDatas = data;
});
      }
Comment: Hey, i tried this code but its gives error in code [errorInCode](https://imgur.com/a/v01XUsd) and then i edit your code and at the end i put [](brackets) but still not working properly [output](https://imgur.com/a/hMvNAzy) when i click update task it removes all the records from
Comment: sory mistack is we dont create an array... please add array like this
      allDatas : Array = [];


WinRT Xaml ListViewItem alternating background color

Question: I need to make a ListView alternates the background colors of its rows. I had tried a lot of things and nothing work for me.
The first row must be with a white background, the second must be black, the third white again and so on.
Does anyone know a simple way to do it? I'm sure there's a simple solution as it's a regular feature.
I'm developing WinRT app with C#, and had tried selectors, converters..
Answer: You can do this at runtime using following code if your listview is already populated.  Additional formatting will probably be required in the template of the ListView for padding and what not.
<code>        int i = 1;
        foreach (ListViewItem item in listView.Items)
        {
            if (i % 2 == 0)
            {
                item.Background = new SolidColorBrush(Windows.UI.Colors.Black);
                item.Foreground = new SolidColorBrush(Windows.UI.Colors.White);
            }
            else
            {
                item.Background = new SolidColorBrush(Windows.UI.Colors.White);
                item.Foreground = new SolidColorBrush(Windows.UI.Colors.Black);
            }
            i++;
        }
</code>
Answer: for example:
<code><Grid Background="{Binding color_background}"/>
</code>
just add the property to the collection of elements in ListView


how to use pod package to package third libraries into the target

Question: I have a framework project that has dependency private third libraries, i want to use pod package to pack the project so that users can only add one framework.
But the fact is the third libraries didn't pack into the final framework.
My package commond is 'pod package TestPod.podspec --no-mangle --force'
And this is my spec:
<code>Pod::Spec.new do |s|
  s.name         = "TestPod"
  s.version      = "0.0.1"
  s.summary      = "A short description of TestPod."
  s.authors      = 'wangb'
  s.description  = <<-DESC
                    long desc
                   DESC
  s.homepage     = "http://EXAMPLE/TestPod"
  s.license      = "MIT"
  s.platform     = :ios, "7.0"
  s.source       = { :git => "https:mygitpath/TestPod.git"}
  s.source_files  = "TestPod/TestPod/*.{h,m}"
  s.public_header_files = "TestPod/TestPod/TestPodPublic.h"
  s.vendored_frameworks = "TestPod/TestPod/uAnalytics.framework"
  s.frameworks = "CoreTelephony", "SystemConfiguration"
  s.libraries = "sqlite3"
end
</code>
Answer: I have find the answer, pod package not support for now!
https://github.com/CocoaPods/cocoapods-packager/issues/26


Oversampling a multi-labeled data set

Question: Given a data set where each individual data point can be assigned to more than 1 class (a multi-class, multi-label data set), are there any guidelines for calculating oversampling weights, i.e., the probability with which you sample a data point based on the frequencies of the labels within the data set?
This is in the context of multi-label classification; I have a very imbalanced data set.
An obvious answer would be to calculate the weight for each label as the inverse frequency (i.e. 1 / total_number_of_label_appearances), then average up the weights for a given data point; though I'm unsure if there's any better approaches.
Comment: Better to say that oversampling distorts the sample which ruins predictions on future non oversampled data.
Comment: Sampling existing data is not a valid statistical procedure.   You must honor the observed sample sizes.  Sampling is only relevant before spending the time and money to acquire the data; probability samples can allow targeting of observations that are most valuable to the analysis.  Once you get the sample, don't discard any of the data by over- or under-sampling.
Comment: @FrankHarrell I'm with you on how undersampling discards data, but how do you figure that oversampling discards data?
Comment: See https://datascience.stackexchange.com/q/54450/55122, and replace integer indicator-of-inclusion variables by continuous weight variables, and I think you get a workable solution?
Answer: Calculating the weight for each label as the inverse frequency, then average up the weights for a given data point is done like so with pandas in Python:
from itertools import chain
from collections import Counter
import pandas as pd

def oversample(df, len_mult=2, random_state=0) -> pd.DataFrame:
    value_counts = Counter(chain(*df[label_col].dropna()))
    weights = 1 / df[label_col].map(
        lambda li: sum(map(value_counts.get, li)) / len(li), na_action='ignore'
    )
    # Fill in average weight for rows w/o labels
    weights.fillna(weights.sum() / weights.count(), inplace=True)
    extra_df = df.sample(
        len(df) * (len_mult-1), replace=True, weights=weights, random_state=random_state
    )
    df = pd.concat([df, extra_df])
    return df

df = pd.DataFrame([['x1', [3,4,5]], ['x2', [0,3]]], columns=['x','y'])
oversample(df)

Answer: If you are using a probabilistic classifier, that outputs a probability of class membership for each class, then averaging the weights or choosing the weights to minimise the maximum imbalance both seem reasonable.  However you would likely to end up with a classifier that grossly over-predicts some classes, so I would subsequently post-process the outputs of the trained model on a label-by-label basis to account for the difference in relative class frequencies in training set and under operational conditions (which basically requires multiplying by the ratio of operational and training set prior probabilities and then re-normalising the probabilities to sum to one).  Unlike the re-sampling of the training set, that can be done on a label-by-label basis.

Oversampling a multi-labeled data set


How does the VAR decide which camera to use?

Question: On April 17, 2019, in the UEFA Champions League quarterfinal second leg between Manchester City and Tottenham there were some requests to VAR.
In particular, one was made regarding Llorente's goal in 73', Tottenham's third goal and making the score 4-3, which would (and did) qualify his team to the semifinals.
Cameras show Llorente touching the ball with his arm, but it was attached to his body. Depending on the camera angle, it may look intentional.
In the The Guardian article, Pep Guardiola hits out at VAR after Llorente's disputed goal for Spurs,

"I support VAR but maybe from one angle Fernando Llorente's goal is handball, maybe from the referee's angle it is not," Guardiola said.

Is there a rule on what angle should be used to take the decision? Do teams have the right to ask for a new check with other cameras?
Answer: Law 5.4 states that the VAR uses replay(s), so there is no limitation in what sort of replays are being used. Usually all with a proper perspective on the scene.

The assistance from the video assistant referee (VAR) will relate to
  using replay(s) of the incident.

When you watch the live footage of the VAR or referee in the review area you can clearly see that they watch the scene from different angles, so Pep Guardiola's comment was nonsense. Also the VAR can only overturn a decision when it was an obvious error:

The referee may be assisted by a video assistant referee (VAR) only in
  the event of a 'clear and obvious error' or 'serious missed incident'
  in relation to:

goal/no goal
penalty/no penalty
direct red card (not second caution)
mistaken identity when the referee cautions or sends off the wrong player of the offending team

And my personal two cents: The goal was good. The ball went in from his upper leg and maybe barely touched the arm with no visual evidence.
Comment: Also helpful as evidence, the first 80 seconds of [FIFA's video explaining VAR for the 2018 World Cup](https://youtu.be/YdwOL08NfxQ) is clear that multiple angles are used by VAR and provided to the match referee.
Comment: However, I think Guardiola's comment is not that VAR got the decision wrong, but just that the same incident can appear to be either of two things depending on angle - this is absolutely true when looking at e.g. are shots on target, did balls cross lines, or were tackles legitimate.