Verificação de vídeos por usuário

Question: Estou desenvolvendo um site para mostrar vídeos inseridos pelos usuários.
Para isso fiz com js:
 $(document).ready(function () {

    var videoContainer_monitor = $("#video_monitor");
    var codigoVideo_monitor = $videos;
    $('#video_monitor').hide();

  $("#video_pendente").click(function(){
    $('#video_monitor').show();
    videoContainer_monitor.html(`
    `);
      })
  });

Ao clicar no botão do html da página:
<button type="button" id="video_pendente" class="btn btn-secondary btn-sm">Videos pendentes</button>

Porém ali em '$videos' quero que selecione com base nos vídeos inseridos pelo usuário que está logado no site.
Segue abaixo a imagem do BD.

Os vídeos que poderiam aparecer, teriam que ser respectivos ao campo "monitor" que serve para identificar o monitor. E em seguida, selecionar todos os campos "link_video". Como faço para verificar o usuário logado e mostrar seus respectivos vídeos cadastrados? (Pode ser com php também, não necessariamente com js).
Não entendi as avaliações negativas, do que adianta negativar se não comentar.. como que a gente vai mudar as perguntas.. por isso tem tanta gente saindo do flow para outra plataforma.
Answer: Olá, Matheus!
Bom, não sei se entendi bem o problema, mas preparei um script para demonstrar como você pode buscar os vídeos pendentes de um usuário logado. Você pode vê-lo coms os códigos abaixo:
Base de dados:
-- MySQL dump 10.13  Distrib 5.7.29, for Linux (x86_64)
--
-- Host: localhost    Database: videos_stackoverflow
-- ------------------------------------------------------
-- Server version   5.7.29-0ubuntu0.18.04.1

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `videos`
--

DROP TABLE IF EXISTS `videos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `videos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nomecomp` varchar(100) NOT NULL,
  `urlvideo` varchar(255) NOT NULL,
  `descricao` text,
  `pendente` tinyint(1) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `videos`
--

LOCK TABLES `videos` WRITE;
/*!40000 ALTER TABLE `videos` DISABLE KEYS */;
INSERT INTO `videos` VALUES (1,'matheus','https://www.youtube.com/watch?v=8iNczzhZmbc','video 1',0),(2,'matheus','https://www.youtube.com/watch?v=8iNczzhZmbc','video 2',0),(3,'matheus','https://www.youtube.com/watch?v=8iNczzhZmbc','video 3 - PENDENTE',1),(4,'matheus','https://www.youtube.com/watch?v=8iNczzhZmbc','video 4 - PENDENTE',1),(5,'macario','https://www.youtube.com/watch?v=8iNczzhZmbc','video 5',0),(6,'macario','https://www.youtube.com/watch?v=8iNczzhZmbc','video 6 - PENDENTE',1),(7,'macario','https://www.youtube.com/watch?v=8iNczzhZmbc','video 7 - PENDENTE',1),(8,'macario','https://www.youtube.com/watch?v=8iNczzhZmbc','video 8 - PENDENTE',1),(9,'macario','https://www.youtube.com/watch?v=8iNczzhZmbc','video 9 - PENDENTE',1);
/*!40000 ALTER TABLE `videos` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2020-04-13  9:22:05

Index.php
<?php

    $servidor = 'localhost';
    $usuario  = 'root';
    $senha    = '';
    $banco    = 'videos_stackoverflow';
    $conexao  = mysqli_connect($servidor, $usuario, $senha, $banco);

    $consulta = "SELECT
                    *
                FROM
                    videos
                WHERE
                    videos.nomecomp     = 'macario'
                    AND videos.pendente = 1";

    $resultados       = mysqli_query($conexao, $consulta);
    $videos_pendentes = array();

    while ($video = mysqli_fetch_assoc($resultados))
        $videos_pendentes[] = $video;

    mysqli_free_result($resultados);
    mysqli_close($conexao);

    $videos_pendentes = json_encode($videos_pendentes);

?>

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vídeos Pendentes</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

Listar vídeos pendentes

Por favor, clique no botão abaixo para listar os vídeos pendentes de um monitor.

                <button id="btn-lista-videos-tabela"   class="btn btn-primary">Mostrar em tabela</button>
                <button id="btn-lista-videos-carousel" class="btn btn-primary">Mostrar em Carousel</button>

                            #
                            Monitor
                            URL
                            Descrição

                        Anterior

                        Próximo

Em resumo criei uma base de dados bem simplificada e inseri alguns registros. Coloquei dois "nomecomps" como monitores desses vídeos. Os nomes desses monitores são matheus e macario.
Suponha que a forma de identificar o usuário logado seja pelo "nomecomp", então, ao carregar a tela que mostra os vídeos pendentes, você já deve ter consultado quais são estes vídeos, aplicando as restrições que você desejar. Por fim, você pode lançar os vídeos consultados no banco de dados pelo PHP, em uma variável JS, como mostrado na linha 90 do arquivo index.php.
Se tiver alguma dúvida, comenta aqui.

Verificação de vídeos por usuário


How to apply or assign custom view mode to user display?

Question: I am using Display Suites. I have created a custom view mode and have made it available to the user display per Display Suite documentation, but I cannot figure out how to apply the custom view mode to the user display.  It always shows in the default view mode.
If I were editing a node, there would be a vertical tab called Display Settings that would have a field for selecting the view mode to use.  When editing an existing user profile, there is no Display Settings tab.

In various Drupal issues queues, specifically Display Suites, Panels and Profile 2, other users have asked essentially this same question: How do I assign a custom view mode to the user profile display?
Is the Drupal core responsible for user data and display?  Perhaps the problem lies there instead of with whatever module.
Comment: Maybe edit [user-profile.tpl.php](https://api.drupal.org/api/drupal/modules!user!user-profile.tpl.php/7) to include your view?
Comment: Thanks @Daniel Rogers.  My issue is that I want to use different view modes to display the user profile differently in different places.  I can add the view to the tpl.php, but I still can't use view modes on the user profile the way they are meant to be used.
Answer: The question is too old, but for those who are still looking similar functionality. We can implement hook_entity_view_mode_alter in our custom module and change the rendered view mode dynamically. Check sample below:
<code>/**
 * Implements hook_entity_view_mode_alter().
 */
function MODULE_NAME_entity_view_mode_alter(&$view_mode, $context) {
  // For nodes, change the view mode when in full display mode.
  // Add/Remove any condition based on requirement.
  if ($context['entity_type'] == 'node' && $view_mode == 'full') {
    $view_mode = 'teaser';
  }
}
</code>


Data Pre-Fetching and State | Vue SSR Guide

Question: Can you tell me what is the usage of created inside the data vue?
<code>created() {
    if (this.$store.state.auth.loggedIn) {
        if ((this.usersId = this.$store.state.auth.user.results.userId)) {
            this.owner = true;
        }
    }
    UserService.getDiscussionDetail(this.$route.params.id).then(
        (response) => {
            this.discussion = response;
        },
        () => {
            this.success = false;
        }
    );
},
</code>
Comment: `https://www.digitalocean.com/community/tutorials/vuejs-component-lifecycle#:~:text=Introduction,DOM%2C%20updated%2C%20or%20destroyed.` please check this. you can understand vue hooks.
Answer: The created hook runs when the Vue instance is created, just before the virtual DOM nodes are available. This is usually the step where async operations in server side generated apps are processed, such as fetching content and other data that have to be included in the finished DOM tree in the hte static output. The steps in a Vue Lifecycle. are: beforeCreate, created, beforeMount, mounted, beforeUpdate, updated, beforeDestroy, and destroyed.


privacyIDEA send noti QR Code via email

Question: Can you help me?
I used privacyIDEA create HOTP and trying to send the QR code as an email, but it simply doesn't display in the email client.
I config Event Handler User Notification:
Events: token_init
Handlermodule: UserNotification
Action: sendmail
To: tokenowner
body:
Hi {givenname} {surname},
You may use the OTP value your new token {serial}.
QR Code

Admin.
Mimetype: html
Error mail client: enter image description here
Thanks,
Toàn Nguyễn
Comment: Obviously you entered some html code, that is not visible here!
Answer: you need to add a tag in the body of the email.
Take a look here at the online documentation:
http://privacyidea.readthedocs.io/en/latest/eventhandler/usernotification.html#options-for-both-actions
You need to use the tag {googleurl_img}, which will add the QR Code as an image to the html mail.
Note: Sending it via email is a bad idea, since the qr code contains the secret key in clear text!. However, you could also add {googleurl_value} which will add the contents of the qr code as link. On a smartphone you could "click" this link.
But again note: This should only be part of a more sophisticated enrollment process, since sending the secret key via an email is a bad idea.
Kind regards
Cornelius
Comment: Thanks Cornelius,
I used the tag  into body but not display images email
Comment: That should do the trick. At least it does in other setups. So you should check the source of the email, then you would see what is up.

privacyIDEA send noti QR Code via email


Initial Value of DateTimePicker wrong

Question: I'm probably missing something obvious but I can't see it.....
I have a DateTimePicker control (Winforms) to display just the Time HH:mm:ss of the DateTime. The properties are as follows
Checked = False
Format = Time
ShowCheckbox = False
ShowUpDown = True
Value = 28/10/2014 08:00
ApplicationSettings.PropertyBinding.Value = pickTime1

Where pickTime1 is a user setting where Properties.Settings.Default.pickTime1 = 28/10/2014 08:00
I'm expecting the control to display 08:00:00 when the form first loads but it displays the current time. How do I ensure the user setting is displayed when first initialized?
Answer: Subscribe to the Form.Load event and set it in there:
private void Form1_Load(object sender, EventArgs e)
{
    dateTimePicker1.Value = Properties.Settings.Default.pickTime1;
}

This will display 8:00:00 AM.
If you want 08:00:00, change Format to Custom, and set the CustomFormat property to "hh:mm:ss".
Answer: The DateTimePicker.Value must be changed either by code or by user input, otherwise it will set to the current date and time (i.e. DateTime.Now)

Initial Value of DateTimePicker wrong


difference between (*head)->next and &(*head)->next in C [LINKED LIST]

Question: typedef struct n {
    int data;
    struct n *next;
}node;

This function deletes all nodes with odd values (without freeing memory or additional variables) :
void deleteOdds (node **head) {

    if (*head == NULL) {
        return;
    }
    while ((*head)->next) {

        if ((*head)->data % 2 != 0) {
            *head = (*head)->next;
        } else head = &(*head)->next;
    }

}

I understand the logic (and already have some assumptions), but I'm not sure how to explain the difference between
*head =(*head)->next;

and
head = &(*head)->next;

thanks in advance!
Comment: @dasblinkenlight OK, I did a desk check and see what's going on now. The code doesn't 'delete' the last node in the list even if it's odd. Thanks for being patient with me :) Agree with your comment that 'head' is a poor name
Comment: `head = &(*head)->next;` is most likely a mistake. Where did you see this code?
Comment: @M.M No, it's not a mistake. `head` is a bad name, a better name should be `current`. `head = &(*head)->next` simply makes `next` the new `current`; the syntax is complex because of a two-star pointer.
Comment: @4386427 Note that `head` is a pointer to pointer, so when we move it to something reachable from the original head, or replace it with another head, our changes remain observable outside the function.
Comment: @dasblinkenlight can you explain why  the parameter is `node **head` and not `node *head` then? It suggests an in-out parameter. The line `*head = (*head)->next;` moves this node pointer, informing the caller.  However after the line `head = &(*head)->next;` , the caller will not see this and the caller's argument will no longer be updated.  So the caller's pointer will advance up to the first even number, and then stay there even though there were later even and odd numbers deleted
Comment: @M.M This is the unfortunate consequence of the need to modify the head in the caller (e.g. `main` would call this function like this: `struct n *head; /* populate the list here*/ deleteOdds(&head);` Without passing a pointer to pointer, i.e. with `deleteOdds(head)` the function wouldn't be able to delete the head node itself if it happens to have an odd value.
Comment: @dasblinkenlight do you not see that writing `head =` in the function now makes it so that the caller no longer will see changes? `head` is a local variable to the function.
Comment: @M.M Of course I see it :-) However, `head`, which is local to `deleteOdds`, is assigned only when `head` from the caller points to a node with even data or `NULL`. Otherwise, the loop keeps assigning `*head`. After the assignment we don't care about changes to the `head` in the caller - in fact, once the first re-assignment of `head` itself has happened, we could stop using a pointer to pointer, and switch to using a regular pointer the way you suggested in your comment.
Answer: The key to understanding what's going on is to see what is being assigned in each case:

*head = (*head)->next; assigns to whatever head is pointing to, which is either the original head pointer, the pointer to which is passed to the function, or a next of some prior node. We modify what is pointed to, while the pointer stays the same. This amounts to deleting from the list (and creating a memory leak in the process).
head = &(*head)->next assigns to the head itself, i.e. it modifies the pointer, not the thing that it points to. This amounts to skipping ahead in the list, without modifying it.

Note: head is not the ideal name for the variable. Since the variable points to head pointer only until the first "skip", a better name for it would be current.
Comment: thanks for clearing that up. head really is a clumsy name.


hook_form_search_block_form_alter is not working with bootstrap theme?

Question: I am facing an issue where hook_form_FORM_ID_alter() code is working in bartik theme while same is not working in Bootstrap theme. Any idea what could be the reason or am I missing something? Very Thanks.
In THEMENAME.theme of bootstrap theme
<?php
/**
 * @file
 * Bootstrap sub-theme.
 *
 * Place your custom PHP code in this file.
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Template\Attribute;

function subtheme_form_search_block_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['keys']['#attributes']['placeholder'] = t('Sentence for placeholder!!!.');
}

OtherWay,
function subtheme_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if($form_id == 'search_block_form'){
      $form['keys']['#attributes']['placeholder'] = t('Sentence for placeholder!!!.');
    }
}

In bartik.theme
<?php

/**
 * @file
 * Functions to support theming in the Bartik theme.
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Template\Attribute;

function bartik_form_search_block_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['keys']['#attributes']['placeholder'] = t('Sentence for placeholder!!!.');
}

Comment: You have two placeholders for the theme name. Are they the same THEMENAME == subtheme?
Comment: @4k4 Hi, yes it is my actual sub theme name.
Comment: I would try a less specific THEMENAME_form_alter() and debug the form_id's that are coming in.
Comment: @4k4  I will try that way and will let you know.
Comment: @4k4 I have tried that way also, but no luck, updated the question with the code which I have used. Any suggestions, thanks.
Answer: You can try a bootstrap plugin:
themes/THEMENAME/src/Plugin/Form/SearchBlockForm.php
/**
 * @file
 * Contains \Drupal\THEMENAME\Plugin\Form\SearchBlockForm.
 */

namespace Drupal\THEMENAME\Plugin\Form;

use Drupal\bootstrap\Annotation\BootstrapForm;
use Drupal\bootstrap\Utility\Element;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * @ingroup plugins_form
 *
 * @BootstrapForm("search_block_form")
 */
class SearchBlockForm extends \Drupal\bootstrap\Plugin\Form\SearchBlockForm {

  /**
   * {@inheritdoc}
   */
  public function alterForm(array &$form, FormStateInterface $form_state, $form_id = NULL) {
    // Call the parent method from the base theme, if applicable (which it is
    // in this case because Bootstrap actually implements this alter).
    parent::alterForm($form, $form_state, $form_id);

    $form['keys']['#attributes']['placeholder'] = t('Sentence for placeholder!!!.')
  }
}

Reference:
http://drupal-bootstrap.org/api/bootstrap/docs%21plugins%21Form.md/group/plugins_form/8


How to convert group of .dat file has 16bit integer data to group of .txt file?

Question: I have a group of .dat files I need to convert to .txt files. I have a directory called "data" that has "210" files (0.dat, 1.dat, ......210.dat), I want to convert these .dat files to .txt files (0.txt, 1.txt ......210.txt), the data type is 16bit integer.
Answer: Ideally you are supposed to try a few steps before coming here asking for a solution. Since this is your first post, I'll give you a few pointers. Next time please Google a few solutions. Try them. Post your code/error if you have any issues to receive help.
From the directory, Load all the contents of the folder using,
files = dir('*.dat');

Add a FOR loop to read each dat file one by one.
fileID = fopen('XXXX.dat');
OneByte = fread(fileID,'*uint16');

Then once the file is loaded you can convert it into .txt file.


Dúvida com lógica para selecionar div

Question: Estou com o seguinte problema, quando clico em uma div a mesma deverá ficar com o background-color preto e o color da cor que realmente é o background, até aí está funcionando normalmente, porém só quando clique em uma div apenas uma vez, no segundo clique a div que é clicada não perde o opacity, haveria algum modo de resolver isto:

$(function() {
  $('.grade:eq(1)').on('click', () => {
     $('.grade:eq(1)').css({
        'background-color': '#000',
        'color': '#EC0080',
        'filter': 'opacity(1)'
     })
     $('.grade:eq(0)').css({
        'background-color': '#009ADE',
        'color': '#FFF',
     'filter': 'opacity(0.4)'
     }).mouseenter(() => {
        $('.grade:eq(0)').css('filter','opacity(1)')
     }).mouseleave(() => {
        $('.grade:eq(0)').css('filter','opacity(0.4)')
     })
     $('.grade:eq(2)').css({
        'background-color': '#FFEA00',
        'color': '#FFF',
     'filter': 'opacity(0.4)'
     }).mouseenter(() => {
        $('.grade:eq(2)').css('filter','opacity(1)')
     }).mouseleave(() => {
        $('.grade:eq(2)').css('filter','opacity(0.4)')
     })
  })

  $('.grade:eq(2)').on('click', () => {
     $('.grade:eq(2)').css({
        'background-color': '#000',
        'color': '#FFEA00',
        'filter': 'opacity(1)'
     })
     $('.grade:eq(1)').css({
        'background-color': '#EC0080',
        'color': '#FFF',
     'filter': 'opacity(0.4)'
     }).mouseenter(() => {
        $('.grade:eq(1)').css('filter','opacity(1)')
     }).mouseleave(() => {
        $('.grade:eq(1)').css('filter','opacity(0.4)')
     })
     $('.grade:eq(0)').css({
        'background-color': '#009ADE',
        'color': '#FFF',
     'filter': 'opacity(0.4)'
     }).mouseenter(() => {
        $('.grade:eq(0)').css('filter','opacity(1)')
     }).mouseleave(() => {
        $('.grade:eq(0)').css('filter','opacity(0.4)')
     })
  })

  $('.grade:eq(0)').on('click', () => {
     $('.grade:eq(0)').css({
        'background-color': '#000',
        'color': '#009ADE',
        'filter': 'opacity(1)'
     })
 $('.grade:eq(1)').css({
        'background-color': '#EC0080',
        'color': '#FFF',
        'filter': 'opacity(0.4)'
    }).mouseenter(() => {
        $('.grade:eq(1)').css('filter','opacity(1)')
    }).mouseleave(() => {
        $('.grade:eq(1)').css('filter','opacity(0.4)')
    })
    $('.grade:eq(2)').css({
        'background-color': '#FFEA00',
        'color': '#FFF',
        'filter': 'opacity(0.4)'
    }).mouseenter(() => {
        $('.grade:eq(2)').css('filter','opacity(1)')
    }).mouseleave(() => {
        $('.grade:eq(2)').css('filter','opacity(0.4)')
    })

  })
})
.grades {
    width: 350px;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-items: baseline;
}
.grade {
    width: 100px;
    height: 100px;
    margin: 5px;
    color: #FFF;
    font-size: 30px;
    text-align: center;
    line-height: 100px;
    cursor: pointer;
}
.grade:nth-child(3n+1) {
    background-color: #009ADE;
    filter: opacity(0.4);
}
.grade:nth-child(3n+2) {
    background-color: #EC0080;
    filter: opacity(0.4);
}
.grade:nth-child(3n+3) {
    background-color: #FFEA00;
    filter: opacity(0.4);
}
.grade:nth-child(3n+1):hover {
    filter: opacity(1);
}
.grade:nth-child(3n+2):hover {
    filter: opacity(1);
}
.grade:nth-child(3n+3):hover {
    filter: opacity(1);
}
.grade:nth-last-child(2) {
    background-color: #000;
    color: #EC0080;
    filter: opacity(1);
}

21h

22h

23h

Answer: Ola LeAndrade tudo certo?
Para fazer o trabalhado de selecionado achei melhor incluir uma classe ".escolhido" que contenha todo o css, então ao clicar em uma ".grade" removo todos as classes ".escolhido"
$('.grade').removeClass('escolhido')

Então eu incluo somente naquela grade clicada
$(this).addClass('escolhido')

Quando o problema que estava dando em seu código, o motivo era por conta dos eventos de mouseenter e mouseleave
espero ter ajudado

$(function() {
  $('.grade').on('click', function() {
    $('.grade').removeClass('escolhido')
    $(this).addClass('escolhido')
  })
})
.grades {
    width: 350px;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-items: baseline;
}
.grade {
    width: 100px;
    height: 100px;
    margin: 5px;
    color: #FFF;
    font-size: 30px;
    text-align: center;
    line-height: 100px;
    cursor: pointer;
}
.grade:not(.escolhido) {
    filter: opacity(0.4);
}
.grade:nth-child(3n+1) {
    background-color: #009ADE;
}
.grade:nth-child(3n+2) {
    background-color: #EC0080;
}
.grade:nth-child(3n+3) {
    background-color: #FFEA00;
}
.grade:hover {
    filter: opacity(1);
}
.grade:nth-child(3n+1).escolhido {
    color: #009ADE;
}
.grade:nth-child(3n+2).escolhido {
    color: #EC0080;
}
.grade:nth-child(3n+3).escolhido {
    color: #FFEA00;
}
.grades .escolhido {
    background-color: #000;
    filter: opacity(1);
}

21h

22h

23h

Comment: Olá Thiago, obrigado por tentar ajudar, sua resposta me ajudou em parte, porém precisaria deixar a cor do texto com a cor do **background** e não somente rosa, mas, agradeço muito a ajuda!
Comment: Poxa LeAndrade verdade, acabei não me atentando nesse detalhe do texto em seu exemplo, já faz algum tempinho deve ter conseguido resolver, mas de qualquer forma fiz uns ajustes no CSS acredito que agora esta ok
Comment: Boa Thiago, obrigado pela ajuda, tinha meio que resolvido com js, mas, utilizarei da forma que fez com Css mesmo, valeu man!

Dúvida com lógica para selecionar div


Finding the optimal split threshold for a feature using XGBoost in R

Question: While implementing a gradient-boosted tree algorithm on a dataset, is it possible to learn the optimal value for a feature that best predicts a class?
For example: In the iris dataset, what is the value of sepal length that best predicts the species versicolor? When I run a single tree, I can see what value of sepal width the tree is splitting at at a given node, and what the probability of predicting a species is. How could I get this information when I run a model with 50 trees?
Comment: This will be a hard problem to solve using GBTs because they're not designed to solve that problem. Frank Harrell's *Regression Modeling Strategies* is full of recommendations about how to think about statistical models for medicine.
Comment: @SycoraxsaysReinstateMonica: While RMS *is* a bible, it does not really cover GBMs (or boosting for that matter) at no point. The recommendations about GAMs are easily extendable to GBMs.
Comment: Even in the case of a single tree, it's not sufficient to partition on only one feature because each leaf is composed as a partition of several features in a particular order. All features on the path from leaf to root are involved. Even in a single tree, the same feature can be chosen as a split multiple times. Can you explain what problem you're trying to solve by identifying feature splits?
Comment: @usεr11852saysReinstateMonic Yes, that's my point.
Comment: (Obviously the GBM will also natively include interactions between explanatory variables and what not, while the GAM would expect explicit definition of them so any analogy is to be used critically.)
Comment: Thanks for your reply. The problem that I am trying to solve is in medicine: given a set of covariates (systolic BP, gender, age, presence/absence of a number of diseases), can I use GBTs to understand if there is a specific value of systolic BP around which we can split patients into "higher" and "lower" risk of postoperative death (this being the outcome)?
Answer: Part of what you want can be achieved through the use of partial-dependence plots (PDP) for the "important" features $x_A, \dots, x_Z$ used within the model $M$. Partial dependence plots show the average relationship between a given feature $x_A$ and the response $y$ within the fixed, joint distribution of all the other inputs $x_B, \dots, x_Z$. Particularly for a probability estimation task as the one described one can plot in each case how the final probability of death is affected. (eg. "values of systolic BP above a threshold $z$ are associated with approximately $0.40$ probability of death while below are generally $0.15$", etc.) It is notable thought that the idea of a dichotomising a continious variable is very often problematic. I would suggest presenting the whole range of a feature to describe its association with the response variable rather than focusing on a potentially arbitrary threshold.
Here is an image from the Partial Dependence Plot (PDP) of the excellent Interpretable Machine Learning e-book by C. Molnar showing what I describe above:

Note that what is an "important feature" is a bit of a "how long is a piece of string" question itself; feature importance in a GBDT can be defined with multiple ways (e.g. how many times a feature is used for splitting, what is the average cost reduction observed after splitting that feature, what is the mean SHAP value associated with that feature, what is the feature's permutation importance, etc. etc.)
Both R and Python has a number of partial dependence plot functionality. R has two great packages on that matter pdp and iml. Python has package like pdpBOX but actually since version 0.22 sklearn also supports PDPs.
Anecdotal note: I have found the insights of PDPs to be quite close to those I would get from GAMs. This is not very surprising as the use of a "penalised spline" to encapsulate non-linear relations between an explanatory variable and mean response of an outcome is what both models try to achieve. In the case of a GBDT, the spline is iteratively approximated by step functions, while in the case of GAM, the spline is directly modelled subject to some penalisation by continuity and smoothness penalties.


URL Alias showing on checkout?

Question: Drupal 7.38
Organic Groups
Drupal Commerce
Commerce Node Checkout
I have everything setup and working well.  There's one strange bug.  On checkout, I have Title displayed so the logged in user can create a new group, but URL alias also shows up.  I don't want this.  I have pathauto handling all this automatically.  Screen shot attached.  I've dug through all display settings.  I'm lost.  Any help would be appreciated.  Screen shot below.
Thanks
Answer: It was a permission issue on the content type.

URL Alias showing on checkout?


Can the rhythm of any music with a consistent pulse be represented through a time signature?

Question: I tried this with a lot of world music (I myself am an Indian) and majority of it, that followed a consistent pulse or a well timed rhythm, could be expressed neatly using time signatures.
Can this be applied to all music? If yes, does it mean that any systematic rhythm does follow an underlining pulse?
Comment: You say 'the majority'.  Did you find an example with a consistent pulse that couldn't?  Please show it to us.
Comment: Majority of it that did follow a consistent pulse*
Answer: Merely having consistent time intervals establishes a pulse, but not a meter. You can very well have an irregular succession of groupings of events that defies any single time signature.
Imagine a work song that accompanies rhythmic chopping of something (perhaps logs swimming by, or stones to hew...). The items of work might require one, two, three, etc. chops depending on how big each one happens to be, but the worker would still try to space the chops (and the notes) regularly. This would represent a consistent pulse with an irregular meter that can be described only through changing the time signature for every bar, which becomes pointless.
Comment: Indeed. Consider Danse de la fureur, Messiaen's Quartet for the End of Time's 6th movement. There is no conductor, and the four players play the same rhythm as each other throughout, so, to keep in step, they must imagine a regular pulse which determines when to play each note. But there is no regular metre. Messiaen writes no time sigs. If you wanted to use time sigs, you'd have to either change at (almost) every bar line or have bar-lines which fail to represent the music's stresses.
Comment: Gregorian chant (when sung with a stable underlying pulse, cf. e.g. the solesmes tradition) fits this description well, too.
Answer: Yes, as long as the music's pulse is consistent, it can be expressed with a time signature. Given polymeter music, you might need a separate time signature for each instrument/part, but you can still go for one time signature per instrument!
The time signature can look vaguely ridiculous such as 13/8 or 22/16, but hey, it's only one time signature!
(You'd be surprised how common music with an inconsistent pulse is, though!)
Answer: I think it depends what you mean by 'consistent pulse' and 'represented'!
A single time signature by itself tells you that there are a certain number of a particular note value per bar. The rhythm of the music is then notated with notes and rests within each bar that add up to the length of the bar. Note and rest values in standard notation are fractional, such that any mathematically rational note length can be represented. However, if you had a repeating (and perfectly systematic) rhythm of notes of relative length  1:√2:1:√2:1:√2... , that isn't possible to represent using standard note values within the context of a single time signature. Of course you might consider that this isn't a regular pulse; you could still use some other notational device to represent this; and you could also argue that it's more a limitation of the note value system than the way time signatures work.
However. a time signature also often implies something about the relative strengths of each beat - the meter of the music. The first beat of the bar is usually inferred to be strong; the beats within the bar are then also assumed to follow a certain pattern - for example 6/8 is something like strong-weak-weak-medium-weak-weak. However, it is possible to think of a regular stress pattern that doesn't have a time signature commonly understood to imply it. In these cases, it might be useful to consider the music as a number of different time signatures alternating in a pattern, forming a mixed meter that is still a regularly repeating pattern. This is still expressing the meter through time signatures, but not a single time signature.
Answer: If you're interested in the point at which a time signature no longer makes sense, or at least where the composer decided not to use one in an otherwise (more or less) conventional score, consider this excerpt from the first page of Tristan Murail's "Les Travaux et les Jours" for piano. (Information and score preview here; listen to part I here.)

The sense of pulse and meter in this composition is so elastic that the composer has resorted to non-standard methods to notate the rhythm: there is no time signature, there are no bars (though there is an indication of equal time segments at the top), the note beams indicate a gradual shift from 1/8 to 1/16 to 1/32 note lengths and back, and the horizontal distance between the notes is used as an indication of the pulse.
Also, at some points in the score, the length of pauses is indicated in seconds, and there is a pedal point indicated as "very long". This is mixed with more standard indications of tempo, such as "meno presto", "accel. poco a poco", "rall." and even "♪=66-70".


want to import images from doc/docx in datatable and then in gridview using C#

Question: sample document I have code like this
<code>internal void GetShapesInParagraph(int paragraphIndex)
{
  Application word = new Application();
  object miss = System.Reflection.Missing.Value;
  object path = @"A:\format1.docx";
  object readOnly = true;
  Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss,
                        ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref
                 miss, ref miss, ref miss, ref miss);
  // get the paragraph we want to check
  Paragraph para = docs.Paragraphs[paragraphIndex];
  // validate the object
  if (para != null)
  {
      // the InlineShapes collection exists in the Range of that paragraph
      foreach (InlineShape ils in para.Range.InlineShapes)
      {
           // validate the object
           if (ils != null)
           {
               // validate this is a picture
               if (ils.Type == WdInlineShapeType.wdInlineShapePicture)
               {
                   DataRow dr = dt.NewRow();
                   // now we have a shape in that paragraph, we can do what we want to it
                   int ShapeWidth = Convert.ToInt32(ils.Width);
                   int ShapeHeight = Convert.ToInt32(ils.Height);
                   dr[0] = ils.PictureFormat;
                   dt.Rows.Add(dr);
                }
            }
        }
    }
}
</code>
I am able to import text from a doc/docx file but I'm stuck for images to be imported in datatable first and then in the gridview.
Answer: You need to save the image to the disk and then read it back for getting a base64 string which can be stored in your database.
Consider using the Open XML SDK instead if you deal with open xml documents only. In that case you can read the image content from the disk and get the base64 string which can be stored in the Db, see Using base64 data stored in CustomXMLPart as image in Office for more information.


Can the guitar be a "non-C" transposing instrument?

Question: I do know that the guitar with standard tuning is a transposing instrument sounding an octave below written pitch.
But what about a guitar with transposed standard tuning, can it be considered as a transposing instrument which isn't "in C"?
For example, if all the strings are tuned 3 semitones (minor 3rd) lower, it will sound a minor 10th below the written pitch (written/played C5 will be concert A3 etc.), so can it be named as "guitar in A"? As far as I know, it fits well into the definition of a transposing instrument.
Comment: A ukulele is commonly tuned a forth higher, often described as putting a capo on the 5th fret of a guitar.  So the highest string is tuned to A (440) instead of E.
Answer: Ok, let's clear up some confusion.
First: The guitar is a transposing instrument. It sounds one octave below written pitch.
Second: The guitar is a "C instrument". What this means is that the guitarist reads "C", they play "C", and we all hear "C". Regardless of the tuning of the individual strings, this fact still applies.
In music, with respect to strings, we don't call it a "transposed standard tuning". The fancy word here is scordatura which just basically means "alternate tuning". What you're talking about is merely scordatura, which is something that all string players deal with.
To be absolutely clear with respect to transposition: If you did have a guitar "in Bb", then the guitarist would read a "C", would play a "C", and we would hear a "Bb". Since this is obviously not the case for many styles of music, the guitar therefore is, the large majority of the time, a C-instrument.
However, especially in popular styles (rock & roll, blues, funk), utilizing a capo may cause the guitar to be treated as a transposing instrument (though fairly common, this practice is not a universal standard among musicians). In popular styles, the notation will inform the position of the capo, with the chord-notation indicating the shape of the chord relative to the capo and not the sounding pitch. For example, a 1st-position C-major chord on an open guitar will sound as a C-major chord, but a 1st-position "C-major" chord on a 3rd-fret capo'd guitar will sound as an Eb-major chord.
That said, it should also be noted that even capo notation only relates to chords and that any individual notes traditionally notated on the treble clef will not be transposed, despite the capo.  Further, it should also be noted that in addition to transposition being a non-standard performance practice of guitarists, notation I described in the preceding paragraph (which includes numbered tablature) is also non-standard, with both performance practice and notation usually associated with the lay musician (not a concert-trained classical guitarist).
If anyone here (or elsewhere) knows of specific, traditionally notated "serious" concert music wherein both chords and individual notes are notated for a transposing guitar, please add the resource in the comments. Many thanks to Todd Wilcox for the suggestion.
Comment: A guitar with a capo on it is most commonly treated as a transposing instrument that is no longer in C. The staff, tablature, and chord names usually indicate what to play as if the capo is the nut, rather than indicating the sounding notes. For example, music might say to place a capo on the second fret, and then indicate middle C on the staff and the third fret of the A string on the tablature. That means the player should actually fret the fifth fret on the A string (three up from the capo) and the sounding note will be D above middle C. Sometimes a guitar is not in C.
Comment: @ToddWilcox Quite right, I made my answer with respect to classical guitar style and neglected to specify for popular guitar style. I'll amend my answer to be more specific; thank you for pointing that out!
Answer: Yes, this is--sort of--how it works. I've never seen an actual classical score which calls for a detuned guitar, but if you look at transcriptions of rock and blues, they'll write the music "in C" (i.e., as if the guitar were tuned to the most common pitch level of the tuning it's in) and then tell the player that the music will sound some interval lower or higher. Sometimes you'll actually get two sets of chord labels above the staff, the written and the sounding chords.
I've not seen anybody then actually call the guitar a transposing instrument (i.e., if you tune all strings down a whole step, then it's a "Guitar in Bb"); perhaps this is because the guitar uses so many alternate tunings that the relationship between fingerings and pitches is just too loose for that to be a practically useful concept.
For instance, the baritone guitar, tuned a fourth lower than a regular guitar (B-E-A-D-F#-B), is not considered a "guitar in G." You just have to suck it up and transpose. (This might have been done back in the days of banjo-mandolin-guitar orchestras; anyone know?)


How to prove this definition of the Riemann Zeta Function?

Question: I have to prove that
$\sum_{n=1}^{\infty} \frac{1}{n^s}$ =  $\frac{1}{1-2^{1-s}}  \sum_{n=1}^{\infty} \frac{-1^{n+1}}{n^s} $
I know I am supposed to show my work, but I have no clue on how to proceed.
Thanks!
Answer: $$
\begin{align}
\sum_{n=1}^{\infty} \frac{1}{n^s}&=
\sum_{n=1}^{\infty} \frac{1}{(2n)^s}+\sum_{n=1}^{\infty} \frac{1}{(2n-1)^s}\\
&=\frac1{2^s}\sum_{n=1}^{\infty} \frac{1}{n^s}+\sum_{n=1}^{\infty} \frac{1}{(2n-1)^s}
\end{align}
$$
Hence
$$
\sum_{n=1}^{\infty} \frac{1}{(2n-1)^s}=(1-\frac{1}{2^s})\sum_{n=1}^{\infty} \frac{1}{n^s}
$$
Now we have
$$
\begin{align}
\sum_{n=1}^{\infty} \frac{(-1)^{n+1}}{n^s}&=\sum_{n=1}^{\infty} \frac{1}{(2n-1)^s}-\sum_{n=1}^{\infty} \frac{1}{(2n)^s}\\
&=(1-\frac{1}{2^s})\sum_{n=1}^{\infty} \frac{1}{n^s}-\frac1{2^s}\sum_{n=1}^{\infty} \frac{1}{n^s}\\
&=(1-\frac1{2^{s-1}})\sum_{n=1}^{\infty} \frac{1}{n^s}
\end{align}
$$
Comment: Where does the first equality (\sum_{n=1}^{\infty} \frac{1}{n^s}&=
\sum_{n=1}^{\infty} \frac{1}{(2n)^s}+\sum_{n=1}^{\infty} \frac{1}{(2n+1)^s}) come from?
Comment: I just used the partition of natural numbers into odd and even integers.
Comment: Great, perfectly clear!
Answer: Hint
$$\sum_{n = 1}^{\infty} \frac{1}{(2 n)^s} = \frac{1}{2^s} \sum_{n = 1}^{\infty} \frac{1}{n^s}.$$


Help Creating a Dummy Data Set and Regressing Against It

Question: So I'm studying up on Poisson regressions and my first thought was to create a dummy dataset, then test linear and Poisson regressions against it to understand the difference.
My SAS code to create the dummy set:

%let N = 10;
  %let factor = 100;
data Sample;
call streaminit(4321);
do i = 1 to &N
<code>  spend = rand("Uniform");

  visits = rand("Poisson",spend*&factor);

  output;
</code>
end;
  run;

My regression SAS:
<code>proc glm data=sample alpha=.05;
class weekend;
model visits = weekend spend / solution;
lsmeans weekend / cl;
output out=Linear predicted=Prediction lcl=LowerCL ucl=UpperCL residual=Residual;
run;

proc genmod data=sample;
class weekend;
model visits = weekend spend / dist=poisson link=log;
lsmeans weekend / cl;
output out=PLog pred=Prediction lower=LowerCL upper=UpperCL resraw=Residual;
run;
</code>
So at least the confidence intervals make much more sense for the Poisson regression, which is what I would expect. However, the actual predictions for the Poisson regression get very poor as Factor gets large. Doing a simple MSE on both shows that POisson underperforms the linear predictions substantially. I've tested this at various N's and Factors.
So,

Have I set up my dummy data right? Do I appear to be using genmod
correctly?
Am I misunderstanding the value of the Poisson
regression?
Shouldn't it provide a better model fit than the linear
regression for any Factor (lamda)?

Thanks for your help!
Comment: Part of the reason may be that you're using the log link function in proc genmod while the true model uses the identity link, so your Poisson model is misspecified.  If you want to see how the model performs when it agrees with the true data generating process then set the mean of the Poisson to be $\exp(\text{spend} \cdot \text{factor})$.
Comment: This question seems to be about statistical confusions at least as much as coding ones. IMO, it could stay open here.
Comment: Yup, that definitely makes the model make more sense, thank you dsaxton. I actually thought I had tried that, but must have done it incorrectly.

But let me ask then, given the way I originally set up the dataset, what's the right way to analyze it? I tried using a poisson distribution with an identity link, but that failed, and I assumed it's because it didn't make any sense to do that.
Comment: (by the way, there's a "Class weekend" in the analysis that doesn't mean anything anymore; I'll add that factor back once I have a better hold on what I'm doing)
Comment: I'm not sure why the identity link would fail because that's the true model.  What exactly went wrong?
Comment: When I use the identity link it says:

>WARNING: The specified model did not converge.
>ERROR: The mean parameter is either invalid or at a limit of its range for some observations.

And honestly, I don't know what it means to have an identity link with the Poisson distribution. Like gung says, this is definitely about statistical confusions ;)
Comment: Sorry about the edits, I keep hitting enter too soon.

As a side note, I can work through the math of why the log link is the canonical link for the Poisson distribution. However, that hasn't seemed to impart much understanding. So thanks for your patience.
Comment: I've gotten the GENMOD Poisson with identity link to converge under some situations, and I'm starting to see a little better what's going on here. Although I'm not sure yet why it doesn't converge in all situations.
Comment: This concerns R, not SAS, but I still think it was still helpful to me:

https://journal.r-project.org/archive/2011-2/RJournal_2011-2_Marschner.pdf
Answer: As dsaxton pointed out, the model in the original question is simply misspecified and therefore provides poor results in some domains (large lambda). One solution is to use the identity link instead of the log link. I originally tried this and when the series didn't converge, assumed it was a bad idea.
I'm probably not the first noobie to do this, but I assumed that the canonical link is the best link. That's not necessarily true - the canonical link has many good properties, assuming it actually reflects the relationship in the data. In this case it did not.
Of course, not using the canonical link (identity instead) was correct, but led to difficulties getting a solution. It worked for some lamdas, but not others. This is another topic altogether that I'll research, but the original question has been answered.


Programa para trocar duas colunas de uma matriz como lista de listas: nada acontece!

Question: O que eu fiz (Não é para usar numpy):
from random import randint
    matriz = []
    n = m =5#linhas colunas

    #inicializando
    temp = [i for i in n*[0]]
    for i in range(n):
        matriz.append(temp.copy())################atencao para o copy, senao da problema nos prox passos
        #a matriz vaI FICAR com todas as listas IGUAIS

    for i in range(n):#linha
        for j in range(m):#coluna
            ele = randint(0, 30)
            print(f"Inserindo elemento da {i}{j}: {ele}")
            matriz[i][j] = ele
    print()
    print(" A matriz criada foi: ")
    print()
    for vetor in matriz:
        print(vetor)

    #trocar a primeira e a quarta coluna;
    matriz[:][0], matriz[:][3] = matriz[:][3],matriz[:][0] #Nao fez NADA na matriz
    matriz

Entrada:
[[2, 23, 8, 14, 6],
 [26, 26, 29, 10, 2],
 [12, 9, 11, 8, 23],
 [26, 28, 3, 11, 30],
 [23, 19, 0, 1, 29]]

Saída:
[[2, 23, 8, 14, 6],
 [26, 26, 29, 10, 2],
 [12, 9, 11, 8, 23],
 [26, 28, 3, 11, 30],
 [23, 19, 0, 1, 29]]

No entando, a matriz não foi alterada. O que houve? Alguma forma de resolver isso? Acredito que seja um problema com o slice das listas mas não sei explicar.
Comment: `matriz[:]` cria uma cópia da matriz (ou seja, vc altera a cópia, não a original), mas como vc não atribui esta cópia em nenhuma variável, ela acaba se perdendo. De qualquer forma, como vc está tentando fazer, ele vai trocar as linhas, e não as colunas. No seu exemplo, se fosse para trocar as colunas, o resultado deveria ser `[[14, 23, 8, 2, 6], [10, 26, 29, 26, 2], [8, 9, 11, 12, 23], [11, 28, 3, 26, 30], [1, 19, 0, 23, 29]]`, certo?
Answer: matriz[:] cria uma cópia da matriz (ou seja, vc altera a cópia, não a original), mas como vc não atribui esta cópia em nenhuma variável, ela acaba se perdendo.
Você até poderia fazer matriz[0], matriz[3] = matriz[3], matriz[0], para modificar a matriz original, porém isso vai trocar as linhas, e não as colunas.
Usando a matriz do seu exemplo:
matriz = [
 [2, 23, 8, 14, 6],
 [26, 26, 29, 10, 2],
 [12, 9, 11, 8, 23],
 [26, 28, 3, 11, 30],
 [23, 19, 0, 1, 29]
]

matriz[0], matriz[3] = matriz[3], matriz[0]
for linha in matriz:
    for n in linha:
        print(f'{n:4}', end='')
    print()

O resultado será:
  26  28   3  11  30
  26  26  29  10   2
  12   9  11   8  23
   2  23   8  14   6
  23  19   0   1  29

Repare que o que mudou foi a primeira e quarta linhas. Se você quiser mudar as colunas, terá que percorrer todas as linhas e mudar o primeiro e quarto elementos de cada uma:
matriz = [
 [2, 23, 8, 14, 6],
 [26, 26, 29, 10, 2],
 [12, 9, 11, 8, 23],
 [26, 28, 3, 11, 30],
 [23, 19, 0, 1, 29]
]

# em todas as linhas, trocar os elementos da primeira e quarta colunas
for linha in matriz:
    linha[0], linha[3] = linha[3], linha[0]

for linha in matriz:
    for n in linha:
        print(f'{n:4}', end='')
    print()

E agora sim ele troca as colunas:
  14  23   8   2   6
  10  26  29  26   2
   8   9  11  12  23
  11  28   3  26  30
   1  19   0  23  29

Por fim, não diretamente relacionado, mas listas são dinâmicas e você não precisa alocar espaço antes. Para criar a matriz, poderia ser assim:
from random import randint

matriz = []
n = m = 5 # linhas colunas
for i in range(n):
    linha = [] # cria uma nova linha
    for j in range(m): # adiciona as colunas na linha
        elemento = randint(0, 30)
        print(f"Inserindo elemento da {i}{j}: {elemento}")
        linha.append(elemento)
    # adiciona a nova linha na matriz
    matriz.append(linha)

Comment: esclareceu muito! Realmente nao entendi pq haviam negativado a pergunta! VOu estudar a sua resposta e volto para marcar como resolvido


How to pass functions in Flutter

Question: I really don't understand how function passing works in Flutter.
When to use ()=> function(...); use this notation ?
I am trying to passing a function.This is my code:
        bottomSheetItem(context, 'İşlemi Sonlandır',
            () => _buildEvaluationBottomSheet(context)),

Widget bottomSheetItem(
    BuildContext context, String text, Function()? function) {
  return TextButton(
    onPressed: () {
      Navigator.pop(context);
      function;
    },
    child: Text(
      text,
      style: const TextStyle(fontSize: 12),
    ),
  );
}

_buildEvaluationBottomSheet(BuildContext context) {
  showModalBottomSheet(
    context: context,
    builder: (context) {
      return FractionallySizedBox(....);
    },
  );
}

Why this does not work ?
What are the optional function passing ways?
I tried to use function!; notation but I know that it doesnt work.
It must be function!();.
But why ?
Comment: Can you be more specific about what is not work ?
Answer: There is nothing wrong with the way you passed _buildEvaluationBottomSheet function.
The problem is the way you called it on text button pressed, when you put function; it will not be called, instead you should call it like this:
function?.call();

The "?" is because your function can be null, so it will be called only when it is not null.
As I said there is nothing wrong with the way you passed the _buildEvaluationBottomSheet function but you can improve it by directly pass it without using the expression "() =>"
Here is how your complete code will look like:
bottomSheetItem(context, 'İşlemi Sonlandır', _buildEvaluationBottomSheet);
  Widget bottomSheetItem(
      BuildContext context, String text, Function(BuildContext context)? function) {
    return TextButton(
      onPressed: () {
        Navigator.pop(context);
        function?.call();
      },
      child: Text(
        text,
        style: const TextStyle(fontSize: 12),
      ),
    );
  }
  _buildEvaluationBottomSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return Container();
      },
    );
  }

Answer: In your case:
Widget bottomSheetItem(
    BuildContext context,
    String text,
    void Function()? function,
) {
  ...
}

you are trying to pass function(that could be null) without ANY params. but as function is nullable, you should use null checking and then call this function:
...
return TextButton(
        onPressed: () {
          Navigator.pop(context);
          function?.call();
        },
        child: Text(
          text,
          style: const TextStyle(fontSize: 12),
        ),
      );
...

more info: dart functions
Comment: The problem is not with the nullability.I write function(null) to holding place.You can think it like function()

How to pass functions in Flutter


Trigonometric inequality has different solutions, depending on the "path" to solution.

Question: The inequality
$$sin(x) + \sqrt3*cos(x) > 1  $$
has two solutions:
1st solution:
divide the inequality by 2
$$\frac 12*sin(x) + \frac{\sqrt{3}}{2}*cos(x) > \frac12$$
$$\frac 12$$ is $$sin(\pi/6)$$, $$\frac {\sqrt{3}} 2$$ is $$cos(\pi/6)$$ therefore
$$sin(30)*sin(x) + cos(30)*cos(x) > \frac 12$$
we can use the addition formula here (sin(a+b)) therefore
$$sin(30 + x) > \frac 12  $$
we get one solution from this:
$$\frac {\pi}{6} + 2*k*\pi< x < \frac {\pi}{2} + 2*k*\pi$$
2nd solution:
try to get just one function (turn cos into sin)
$$ sin(x) + \sqrt{3*(1-sin^2(x)} > 1 $$
$$3*(1-sin^2(x)) > 1-2*sin(x)+sin^2(x)$$
$$ 2*sin^2(x) - sin(x) - 1 < 0 $$
this quadratic inequality has two solutions:
$$ sin(x) = 1$$
$$ sin(x) = \frac{-1}{2}$$
so we get two solutions from this
$$ \frac{-\pi}{6} + 2*k*\pi < x < \frac{\pi}{2} + 2*k*\pi $$
$$ \frac{\pi}{2}+2*k*\pi < x < \frac{7*\pi}{6}+2*k*\pi  $$
How is this possible?
Comment: It should be $\cos(x - 30)$, not $\sin(x + 30)$.
Answer: That's because the equaliy $\cos x=\sqrt{1-\sin^2x}$ only holds when $\cos x\geqslant 0$.
Comment: I can't believe I haven't realized that.Thank you for the (very quick). answer.
Answer: The solution of $\sin x>\sin\theta$ $\;(0<\theta<\frac\pi2$) is not $\;\theta+2k\pi<x<\frac\pi2+2k\pi$ (b.t.w. why eliminate $\frac\pi 2$?), but (make a drawing with the trigonometric circle!):
$$\theta+2k\pi<x <\pi-\theta+2k\pi\qquad(k\in\mathbf Z).$$
Similarly
$$\sin x<\sin\theta \iff -\theta-\pi+2k\pi<x<\theta+2k\pi.$$


Why 110-hurdles for men and 100-hurdles for women?

Question: I was watching IAAF World Championship at London 2017 and I notice that men will run 110-metres hurdles while women women the 100-metres hurdles.
What is the meaning of this difference?
The longest distance for hurdles is 400 metres both for men and women
Answer: TL;DR: 110 m was set for historical reasons and women had the distance set to 100 m to both use metric units and keep consistency with the number of hurdles run by men (10).

110 metres hurdles in Wikipedia explains that the distance of 110 metres comes from a 120 yards standard defined in the mid-1800s:

The first standards were attempted in 1864 in Oxford and Cambridge: The length of the course was set to 120 yards (109.7 m) and over its course, runners were required to clear ten 3 foot 6 inch (1.07 m) high hurdles. The height and spacing of the hurdles have been related to Imperial units ever since. After the length of the course was rounded up to 110 metres in France in 1888, the standards were pretty much complete (except for Germany where 1 metre high hurdles were used until 1907).

My interpretation is that technique and spacing became so standard that changing the distance would have made it a completely new competition, hence it was kept.
Time passed and women's 100 metres hurdles appeared:

The Olympic Games had included the 80 m hurdles in the program from 1932 to 1968. Starting with the 1972 Summer Olympics the women's race was lengthened to 100 m hurdles.
The hurdles sprint race has been run by women since the beginning of women's athletics, just after the end of World War I. The distances and hurdle heights varied widely in the beginning. While the men had zeroed in on the 110 m hurdles, the International Women's Sport Federation had registered records for eight different disciplines by 1926 (60 yards/75 cm height, 60 yards/61 cm, 65 yards/75 cm, 83 yards/75 cm, 100 yards/75 cm, 100 yards/61 cm, 120 yards/75 cm, 110 metres/75 cm). At the first Women's World Games in 1922 a 100 m hurdles race was run.

The article follows with some interesting insight and follows with:

During the 1960s some experimental races were run over a distance of 100 metres using hurdles with a height of 76.2 cm. During the 1968 Summer Olympics a decision was made to introduce the 100 m hurdles using hurdles with a height of 84 cm and the first international event in the 100 m hurdles occurred at the European Athletics Championships, which were won by Karin Balzer, GDR. The modern 100 m race has an extra 2 hurdles compared to the 80 m race, which are higher and spaced slightly further apart. The home stretch is shorter by 1.5 m.

My interpretation is that they wanted to increase the number of hurdles to 10 but also keep the spacing. To do so they could just increase to 100 metres.
This reasoning is also followed in the debate 80 meter hurdles?:

I don't know why, but if, as you speculate, the aim was to harmonize with the men's hurdles, I think it has been achieved in the most practical manner. With the change, the women now face ten obstacles, just as the men do. Furthermore, by increasing the overall distance only twenty meters, the women can still three-step the hurdles, just as the men do. The key parameter is distance between hurdles.

I took the official spacing for hurdles and did some calculations to see what other combinations could have been used.
The total distance comes from:
<code>start + (hurdles-1)*distance_hurdles + finish
</code>
so it is like this:
<code>          hurdles   start   distance hurdles   finish   total metres
80m  (W)        8      12        8              12           80
100m (W)       10      13        8,5            10,5        100
110m (M)       10   13,72        9,14           14,02       110
</code>
If we were to have a 110m (W) with the same amount of hurdles, 10, it should be like:
<code>          hurdles   start   distance hurdles   finish   total metres
110m (W)       10      12       10              12          110
</code>
The problem is that the bigger distance between hurdles makes it hard to combine with the typical 4-step and may make them need an extra, smaller step that would break speed.
If we were to have a 110m (W) with similar spacing, it should be like:
<code>          hurdles   start   distance hurdles   finish   total metres
110m (W)       12      12        8              10          100
</code>
so this is completely doable and would make the distance equivalent to men's. However, it may be way harder since the amount of hurdles to skip is bigger.


Baseline predictors parametres

Question: I've implemented baseline predictors model.
It trains on data: "user_number item_number rating_ui"
And then I need to predict raiting for "user_number item_number".
I use following formulas for biases:
b_ui = average_rating + b_i + b_u;
b_i = (sum_(by all items)(rating_ui-average_rating))/(lamda_2+items_count);
b_u = (sum_(by all users)(rating_ui-average_rating-b_i))/(lambda_3+users_count);

I tried to use Netflix constants lambda_2 = 25 and lambda_3 = 10. But it gives not enough accuracy. How can I optimize lambda_2 and lambda_3 using training data? There are to much data to use gradient descent.
Comment: @Chiffa I used SVD instead of baseline predictors at the end
Answer: In chapter 5, page 149 of "Recommender Systems Handbook" by F. Ricci, L. Rokach, B. Shapira and P. B. Kantor it is suggested to use cross-validation over the dataset in order to find the best values for the regularization parameters

Baseline predictors parametres


Is $\{0,1\}^{\mathbb{N}}$ compact in $\mathbb{N}^{\mathbb{N}}$?

Question: Is $\{0,1\}^{\mathbb{N}}$ compact in $\mathbb{N}^{\mathbb{N}}$ ?
How can i proof that?
Comment: Which topology are you considering?
Comment: product topology of the discrete metric
Comment: This space is homeomorphic to the Cantor's set which is compact. See here https://math.stackexchange.com/questions/69905/the-cantor-set-is-homeomorphic-to-infinite-product-of-0-1-with-itself-cy
Answer: The topology of $\mathbb N ^{\mathbb N}$ and $\{0,1\}^{\mathbb N}$ are both same as product topologies. Tychonof's Threorem says product of compact spaces is compact. Hence the answer is YES.
Comment: This page (listed at pi-base as "countable power of a countable discrete space") https://topology.jdabbs.com/spaces/S000100/properties says that $\mathbb{N}^{\mathbb{N}}$ is not compact. (It says that it is actually homeomorphic to the irrationals.) But Tychonoff's theorem implies $\{0, 1\}^{\mathbb{N}}$ is compact. So I believe you may be mistaken when you say these are the same as product topologies. Another SE question states that $\{0, 1\}^{\mathbb{N}}$ is homeomorphic to a cantor set, and another SE question says a cantor set minus its endpoints is homeomorphic to the irrationals.
Comment: I missed a better way of showing $\mathbb{N}^{\mathbb{N}}$ is not compact. If it were then a projection map from it to one of its factors $\mathbb{N}$ would preserve compactness. But infinite discrete sets are not compact. (In general, this argument shows Tychonoff's theorem goes both directions.)
Answer: $\{0, 1\}^{\mathbb{N}}$ is a product of closed sets of $\mathbb{N}$, and so is closed in $\mathbb{N}^{\mathbb{N}}$. https://proofwiki.org/wiki/Product_of_Closed_Sets_is_Closed
It is compact by Tychnoff's theorem, so clearly the closure is compact. We conclude it is relatively compact in $\mathbb{N}^{\mathbb{N}}$.


How to get list of people those are more than 40 year old in PHP Codeigniter

Question: Hi I am calculating age of the people in Codeigniter by their Date of Birth. I want to Separate the people where age is more than 40 years. I have used the simple condition if($age>40){my code block} but it does not work for those whose age is 40 years and  month>0 or you may say 40 years and 0 month and days>0
is their any built-in function in CodeIgniter for this purpose or any solution..?
thanks in advance...
Comment: And you say that as if it was an actual problem/issue, because ...?
Comment: Well one solution you got right there in your own question already ... write code that checks those additional conditions as alternatives then?
Comment: sure but I'll have to write more than one condition.
Comment: Can you not use `$age >= 40`?
Answer: It also depends on where you get the age data from.
Is it stored as 40 years, 2 months or is that a calculation made from a birth date?
Did you try if ($age >= 40) ?
Answer: here is my solution that works for me if age is 40 and month is greater than 0 or day is greater than 0.
if ($ageyear > 40 || ($ageyear == 40 && ($agemonth > 0 || $agedays > 0))) {
$isOverAge = "Over age";
}


A problem about independent, i.i.d, random variables and exponential distribution.

Question:
Let $X_{1}, \ldots, X_{n}$ be independent and identically distributed random variables, with exponential distribution of the parameter $\lambda$. Consider $Y_{(1)}, \ldots, Y_{(n)}$ the associated order statistics and define $$Z_{1} = Y_{(1)}  \quad \text{and} \quad Z_{j} = Y_{(j)} - Y_{(j - 1)}, j = 2, \ldots , n$$ Show that $Z_{1},\ldots, Z_{n}$ are independent and $Z_{j} \sim \textbf{Exp} (\lambda (n -j +1)), j= 1,\ldots, n$.

My approach:  Let, $X_{i}\overset{i.i.d}{\sim}$ with $i=1,2,\ldots,n$ and $X_{i}\sim \textbf{Exp}(\lambda)$. So, since that $X_{i}'s$ are independent and indentically distributed, then $f$ is the common density function (this mean that $X_{i}'s$ has the same density).
Since $Y_{(1)},\ldots, Y_{(n)}$ are the associated order statistic to $X_{1},\ldots,X_{n}$, so the joint density is $$f_{Y_{(1)},\ldots,Y_{(n)}}(y_{1},\ldots,y_{n})=n!f(y_{1})\cdots f(y_{n}), \quad y_{1}<y_{2}<\cdots<y_{n}$$

How can I continue or solve this problem?
Really, I don't know how to continue.
I think I can use some transformation theorem, but I don't sure how can use that.

I was studying a book and I found similar problem where using that ${n!}$ =$\prod_{1}^{n}(n-i+1)$ and $\sum_{1}^{n}Y_{i}$ = $\sum_{1}^{n}(n-i+1)(Y_{i}-Y_{i-1})$ ,so the joint p.d.f of the $Y_{i}$
${n!}\lambda^nexp(-{\lambda}\sum_{1}^{n}y_{i})$  may be expressed as $\prod_{1}^{n}{\lambda}(n-i+1)exp(-{\lambda}(n-i+1)z_{i})$ ($z_{0}=0$ )
But I don't know how to adapt that to the solution of my problem.
Answer: I answered quite the same question here. The only differences are that in the original post the distribution was $Exp(1)$ and the requeste distribution was the law of $Z_j=Y_{(j+1)}-Y_{(j)}$
Unfortunately this forum is an Italian forum...but I think you can understand the solution because formulas are formulas....in any language.
On the contrary please advice and I will repost the solution in English

Solution details

Just to simplify the notation, let's set $Y$ and $X$ the two order statistics and $Z=Y-X$ the rv we are looking for distribution ($Y>X$).
Using the known result on the joint density of two Order Statistics we get
$$f_{XY}(x,y)=\frac{n!}{(j-2)!(n-j)!}(1-e^{-\lambda x})^{j-2}e^{-\lambda(n-j)y}\lambda e^{-\lambda x}\lambda e^{-\lambda y}\cdot\mathbb{1}_{(x;\infty)}(y)$$
In order to get the CDF of the rv $Z=Y-X$ we have to integrate the joint density over the desired support, say:
$$F_Z(z)=\frac{n!}{(j-2)!(n-j)!}\int_0^{\infty}(1-e^{-\lambda x})^{j-2}\lambda e^{-\lambda x} \Bigg[ \int_x^{x+z}\lambda e^{-\lambda(n-j+1)y} dy\Bigg] dx$$
The integral is not difficult...it is enough to sove the inner integral in $dy$ (very easy) and get out of the sign of integral all what does not depend on x.
You get
$$\frac{n!}{(j-2)!(n-j+1)!}[1-e^{-\lambda(n-j+1)z}]\int_0^{\infty}(1-e^{-\lambda x})^{j-2}\lambda (e^{-\lambda x})^{n-j+2}dx$$
Now substitute
$1-e^{-\lambda x}=u$
and you get
$$F_Z(z)=\frac{n!}{(j-2)!(n-j+1)!}[1-e^{-\lambda(n-j+1)z}]\underbrace{\int_0^1 u^{j-2}(1-u)^{n-j+1}du}_{=Beta(j-1;n-j+2)}=1-e^{-\lambda(n-j+1)z}$$
As
$$Beta(j-1;n-j+2)=\frac{\Gamma(j-1)\Gamma(n-j+2)}{\Gamma(n+1)}=\frac{(j-2)!(n-j+1)!}{n!}$$
That is exactly the CDF they ask you to show.
Comment: @Ramanujan : I added full solution in my answer
Comment: Right now I'm trying to read the solution.
But suggestions with many jumps appear in the demo itself. It's making it difficult for me to follow your solution.
Comment: A question, the independence of the random variables. Is there a simple way to prove it? Thank you very much for the solution with details, it is a very clear solution.
Comment: I think that $f(z_{1},z_{2},\ldots,z_{n})=\prod_{1}^{n}f_{Z_i}(z_{i})$ so $Z_{i} \perp Z_{j}, i\not=j$, so the $Z_{i}$ are rv independent. Is it correct for last part?


Parsing Through JSON Object From Retrofit Response

Question: I'm pretty new to android dev and I first made a weather app that displays the horly forecast along with the current forecast. I wanted to add a button that allows the user to see the daily forecast but from the API call it looks like it returns a JSON object. I have been stuck on this for days and I have no idea what to do.
<code>        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.weatherapi.com/v1/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        APICall apiCall = retrofit.create(APICall.class);
        Call<WeatherModel> call = apiCall.getHourAndAstroDetails(latlong, "7");
        System.out.println(call.request().url());
        call.enqueue(new Callback<WeatherModel>() {
            @Override
            public void onResponse(Call<WeatherModel> call, Response<WeatherModel> response) {
                if (days == 1) {
                    weatherList = response.body().getForecast().getForecastday().get(0).getHour();
                    System.out.println("this is the size of weatherList" + weatherList.size());
                    setAdapter(weatherList);
                } else if (days == 7) {
                    dailyForcast = response.body().getForecast().getForecastday().get(0).getDay();
                }

                String sunriseTime = response.body().getForecast().getForecastday().get(0).getAstro().getSunrise();
                String sunsetTime = response.body().getForecast().getForecastday().get(0).getAstro().getSunset();
                sunriseTextView.setText(sunriseTime);
                sunsetTextView.setText(sunsetTime);
            }

            @Override
            public void onFailure(Call<WeatherModel> call, Throwable t) {
            }
        });
    }
</code>
Comment: Just to add since I think I left some info out. I need to get into the Day{} but i need to get a List so I can attach it to a recyclerView. I'm either coming at this the wrong way or something It's so frustrating.
Answer: I think you should create a model class for all the data that you are getting from the api, so you can work with data more easily.
This article explains that,
https://medium.com/swlh/basic-usage-of-retrofit-in-kotlin-for-fetching-json-8b9d37999058
Comment: The solution was so simple. I used jsonschema2pojo and for some reason, I forgot I can create a custom class. Thanks for the reminder.
Comment: Glad it worked!


Duvida com ng-repeat AngularJS

Question: possuo um array de objetos, que dentro dele tem outro array de objetos. Segue:`
$scope.menu = [{
    titulo: 'Comercial',
    submenus: [{ nome: 'Clientes', url: 'url/clientes' },{ nome: 'Proposta', url: 'url/proposta' }]
},
{
    titulo: 'Frota',
    submenus: [{ nome: 'Veiculos', url: 'url/veiculos' },{ nome: 'Ocupacao', url: 'url/ocupacao' }]
},
    {
        titulo: 'Logistica',
        submenus: [{ nome: 'Agente de Serviço', url: 'url/agente' },{ nome: 'Proposta', url: 'url/propostaLogistica' }]
    }
];

Para exibição destes itens, estou usando ng-repeat conforme abaixo:

      {{item.titulo}}

        {{sub.nome}}

Na view, só está exibindo 1 item de submenu, como se não fizesse o looping do segundo ng-repeat. É correto e funciona utilizar ng-repeat dentro de ng-repeat?
Answer: Brother boa tarde, aparentemente funcionando como esperado.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.menu = [{
      titulo: 'Comercial',
      submenus: [{
        nome: 'Clientes',
        url: 'url/clientes'
      }, {
        nome: 'Proposta',
        url: 'url/proposta'
      }]
    },
    {
      titulo: 'Frota',
      submenus: [{
        nome: 'Veiculos',
        url: 'url/veiculos'
      }, {
        nome: 'Ocupacao',
        url: 'url/ocupacao'
      }]
    },
    {
      titulo: 'Logistica',
      submenus: [{
        nome: 'Agente de Serviço',
        url: 'url/agente'
      }, {
        nome: 'Proposta',
        url: 'url/propostaLogistica'
      }]
    }
  ];
});

        {{item.titulo}}

          {{sub.nome}}

Duvida com ng-repeat AngularJS


Interpreting logistic regression results when explanatory variable has multiple levels

Question: When an explanatory variable in logistic regression is binary, the interpretation is relatively straightforward.
For example, when your response variable is college admission (binary: yes or no) and explanatory variable is gender (with two levels: female and male), you can say that being male increases (or decreases) the odds of being admitted by a factor of n, holding other variables constant.
But what is the explanatory variable has multiple levels / categories? For instance, your response variable is college admission, but explanatory variable is ethnicity (with levels: Caucasian, African_American, Hispanic, and Asian). R (or any other software) will still run the model, automatically choosing one one of the levels as reference (in R it will be African_American unless specified otherwise). The results will tell us how not being African_American (or vide versa) affects the odds of admission, but says nothing for being Causasian, Hispanic, or Asian.
What's the best way of dealing with this problem? Should one create dummy variables for each ethnic group, or is there a better way?
Answer: The interpretation for categorical variables with more than 2 levels is very similar to the binary case you mention; for a $k$-level categorical variable, you will have $k-1$ regression coefficients each of which compare the odds of the outcome to the reference group.  For the example you state, ethnicity (Caucasian, African-American, Hispanic, and Asian), let us assume your referent (baseline) group is African-American. Many software packages for logistic regressions will give you 3 Odds ratios (for a 4-level categorical predictor) once you run the regression. Let us quickly look at how this is done in R based on simulated dataset:
<code>    ###########Simulate Data###########
    set.seed(123) # set seed if you want to re-produce
                  #simulation results
    x1 <- sample(c("AF","AS","HI","CA"),10000,replace = T) #Caucasian (CA), African-American(AA), Hispanic(HI),
# and Asian(AA)
    x1 <- factor(x1,levels =c("AF","AS","HI","CA"))
    # ensure the ordering by setting AF as reference

    x1.fac <- model.matrix(~ x1) # generate dummy variables for
      #simulation purposes (in practice you may not need to do
      #this)
    betas <- c(.2,.5,.53) # log odds comparing the three groups
      #to the referent level of AF (these are just made up
      #values for illustration and simulation purposes!)
    xbeta <- x1.fac[,-1]%*%betas #need only k-1 dummies for a
                                 #variable with k-levels
    y <- rbinom(n = 10000, size = 1, prob =
            exp(xbeta)/(1+exp(xbeta))) # Simulate outcome (Y)

#Finally we have the following sample data:

    example_data <- data.frame(y,x1)

    ####Run regression of outcome against ethnicity
    model1 <- glm(y~x1,family = binomial,data = example_data)
    exp(coef(model1))[-1] ###Odds Ratios comparing each group
                          #with the reference group of AF
    x1AS     x1HI     x1CA
    1.229610 1.800985 1.796416
</code>
So what does the odds ratio of 1.23 for Asians mean? This means, compared to African-Americans Asians had 23% higher odds of the outcome. Equivalently, you can interpret as Asians have 1.23 times the odds of the outcome compared to the referent group of African Americans. The odds of 1.800 and 1.796 for Caucasians and Hispanics, respectively, are interpreted in the same manner. The most important part of modeling categorical variables is identifying the proper referent group. You can always change the reference group by using the relevel() command in R. See example here.
In order to make comparison between two groups where one of them is not a referent group, there are a few ways to go:

Use relevel() function and re-run the regression changing the reference group to your variable of interest (not my favorite approach when there are many levels in your categorical predictor)

Use already built in packages to do this comparison.

I am not sure how this is done in Stata or SAS (probably contrast statement for SAS) but you can easily do this in R using the car package. For example, if you want to test if the odds of the outcome differ between Caucasians and Hispanics, use the following commands:
<code>    library(car)
    linearHypothesis(model1, c("x1CA - x1HI = 0"))

    Linear hypothesis test

    Hypothesis:
    - x1HI  + x1CA = 0

    Model 1: restricted model
    Model 2: y ~ x1

      Res.Df Df  Chisq Pr(>Chisq)
    1   9997
    2   9996  1 0.0018     0.9658
</code>
In this case, we fail to reject the null hypothesis of no difference in the odds of the outcome between Caucasians and Hispanics (p-value=0.9658).
Answer: For a categorical variable that is not nominal, a logistic regression will output coefficients to a One Hot Encoded version of it.
Therefore the logic remains the same: there will be a coefficient for "Caucasian" / "Not caucasian", another for "Hispanic" / "Not hispanic" and so on. The encoding makes it impossible to have "Caucasian" and "Hispanic" at the same time.
Comment: I disagree.  Most software creates a dummy variable encoding (num categories -1), and the comparison for each category is to a reference category.
Comment: I'm not sure if I like the one-hot, because biracial folks would be excluded.  :)  There are cases where more than one category applies, though that should show up in the data capture, before the analysis.
Comment: @Glen My bad then, I'm a python user and I apply a One Hot Encoder myself :) I don't know about most other softwares. Rather do it yourself so you know what you're dealing with imo. The logic remains in this context. @ EngrStudent if there is only one categorical variable it cannot show that, except if there is a "Caucasian and hispanic" level for instance.
Answer: This is a good question, I've had it myself.  Note if you only have one categorical variable then the intercept term corresponds to the reference category.  If you have more than one categorical variable in your model then it becomes tricky.
One way is to rerun the model with different reference levels (clunky).
A better way is to create a dummy variables for each category (one hot encoding) as you mention.  However, if you estimate the model this way you need to remove the intercept term or else it is overparameterized.
Comment: I suggest keeping both variables in the model instead of separate analyses.  Try one hot encoding ethnicity and then remove the intercept from the model (you don't need to one hot encode binary variables).  Your estimate for a specific gender/race from this model should be the same when estimating the model without one hot encoding so be sure to check this.
Comment: Not that I know of.
Comment: Thanks for this. Am I understanding correctly that, if I want to estimate `glm(admission~ethnicity+gender...`., then I should recode ethnicity as separate dummy variables (in contrast to @user3487564 above)? If I'm not all that interested in the effect of both ethnicity and gender, isn't it easier to run two models separately [`glm(admission~ethnicity...` and `glm(admission~gender...`] and follow @user3487564 's solution?
Comment: Indeed. Thank you again, Glen. A quick search suggests that there are different methods of removing the intercept in R. Is any of them in any way superior than the obvious `glm(admission~ethnicity+gender-1...`?


Prove: $\sum\limits_{cyc}\frac{1}{b^2+bc+c^2} \ge \frac{2}{ab+bc+ca}+\frac{a+b+c}{3(a^3+b^3+c^3)}.$ with $a,b,c \ge 0 : ab+bc+ca>0.$

Question:
Let $a,b,c \ge 0 : ab+bc+ca >0.$ Prove that $$\dfrac{1}{a^2+ab+b^2}+\dfrac{1}{b^2+bc+c^2}+\dfrac{1}{c^2+ca+a^2} \ge \dfrac{2}{ab+bc+ca}+\dfrac{a+b+c}{3(a^3+b^3+c^3)}.$$

The big problem here is inequality holds iff $a=b=c$ and $a=b, c=0$ and permutations.
I tried Cauchy - Schwarz:
$$\sum\limits_{cyc}\dfrac{1}{b^2+bc+c^2} \ge \dfrac{(a+b+c)^2}{\sum\limits_{cyc}a^2(b^2+bc+c^2)}.$$
But the following is not nice.
I also tried full expanding and checked it by Maple, It's true.
But I don't have any nice solution for it.
Please help me. Thank you very much.
Comment: $uvw$ method can prove it.
Comment: That's right. But it's very ugly :(.
Answer: Let $a+b+c=3u$, $ab+ac+bc=3v^2$ and $abc=w^3$.
Thus, we need to prove that:
$$\frac{\sum\limits_{cyc}(a^2+ab+b^2)(a^2+ac+c^2)}{\prod\limits_{cyc}(a^2+ab+b^2)}\geq\frac{2}{ab+ac+bc}+\frac{a+b+c}{3(a^3+b^3+c^3)}$$ or
$$\frac{27(3u^4-3u^2v^2+v^4)}{27(3u^2v^4-u^3w^3-v^6)}\geq\frac{2}{3v^2}+\frac{u}{27u^3-27uv^2+3w^3}$$ or $f(w^3)\geq0,$ where $$f(w^3)=\frac{3u^4-3u^2v^2+v^4}{3u^2v^4-u^3w^3-v^6}-\frac{2}{3v^2}-\frac{u}{27u^3-27uv^2+3w^3}.$$
But $$f'(w^3)=\frac{u^3(3u^4-3u^2v^2+v^4)}{(3u^2v^4-u^3w^3-v^6)^2}+\frac{3u}{(27u^3-27uv^2+3w^3)^2}>0,$$ which says that $f$ increases(we can see it also without derivative) and it's enough to prove our inequality for a minimal value of $w^3$, which by $uvw$ happens in the following cases.

$w^3=0.$

Let $c=0$ and $b=1$.
We obtain: $$(a-1)^2(3a^4+5a^2+3)\geq0.$$

Two variables are equal.

Let $b=c=1$.
We obtain: $$(a-1)^2a(2a^3+a^2+7a+11)\geq0$$ and we are done!
About $uvw$ see here: https://artofproblemsolving.com/community/c6h278791
Comment: Thanks @Michale Rozenberg.
Comment: @Nguyễn Thái An  You are welcome!


Como receber um input durante uma função do R?

Question: É possível fazer uma pergunta e receber um input durante a execução de uma função?
Exemplo:
formateCdoispontos<-function(){
  print('Tem certeza que quer fazer isso? (S/N)')
  ...
  if(resposta=='N')break
  ...
  }

Ou toda a informação está restrita ao input da função? Assim:
formateCdoispontos<-function(certeza = 'N'){
  if(resposta=='N')break
  ...
  }

Answer: Sim,uma forma de fazer isso é aplicar a função readline() para adquirir input do terminal do usuário.
formateCdoispontos <- function(){
  resposta <- readline(prompt = "Tem certeza que quer fazer isso? (S/N)")
  if(resposta=='N')break
  ...
print(paste("Sua resposta foi" resposta))
}

Answer: Tambem podemos usar menu():
pergunta <- function(){

  sel <- c("Sim", "Não")

  ans <- menu(sel, title = "Tem certeza que quer fazer isso? (S/N)")

  return(paste0('Sua resposta foi ', tolower(sel[[ans]])))
}

No console:
> pergunta()
Tem certeza que quer fazer isso? (S/N)

1: Sim
2: Não

Selection: 1
[1] "Sua resposta foi sim"


$(window).scroll event not triggered in android WebView

Question: In android app I have webView page that use jquery plugin for lazyload. In mobile browser it work fine but not in webView. After debug I find out that even this doesnt trigger alert.
$(window).scroll(function() {
    alert("Scrolled");
}

Does there is special way to handle  scroll events in webView?
PS For lazy load i use this plugin http://www.appelsiini.net/projects/lazyload
Comment: Hi Alex, Did you find any workaround to solve this problem?
Answer: window.onscroll works with the WebView. Some things to check:

you have placed the WebView in a ScollView and/or set it's height to wrap_contents,
the contents of the WebView is too short to scroll,
you haven't implemented the WebChromeClient.onJsAlert callback to handle alert. By default the WebView doesn't display a popup.


Primitive of $dz/z$ is a branch of log

Question: Let $D$ a connected open set of $\mathbb{C}$. A continuous function $f:D\to \mathbb{C}$ is a branch of log if $e^{f(t)}=t$ on $D$.
In my book (Cartan) it is written that if $F$ is a primitive of the 1-form $dz/z$ on $D$ then $F$ is a branch of log on $D$.
It is easy to show that if $f$ is a branch of log on $D$, then $f'(t)=1/t$. So I'd like to prove the converse statement. Any suggestions?
Answer: The converse is actually false. For example, define $f(z)=\int_1^z\frac{dt}{t}+1$ in the open disc $D=\{z\in\mathbb{C}:|z-1|\lt 1\}$. It is clear that $\int_1^z\frac{dt}{t}$ is a branch of the logarithm on $D$, so
$$
e^{f(z)}=e^{\int_1^z\frac{dt}{t}}e^1=ez\neq z.
$$
However, the assertion is true with the additional assumption that $e^{f(t)}=t$ for some $t$ (e.g. if $f(1)=0,2\pi i,\dots$).
Let $g(t)=te^{-f(t)}$ on $D$, so that
$$
g'(t)=e^{-f(t)}-tf'(t)e^{-f(t)}=e^{-f(t)}\left(1-tf'(t)\right)=0.
$$
This shows that $g$ is constant on $D$, i.e. $e^{f(t)}=kt$ for some constant $k\in\mathbb{C}$. Assuming $e^{f(t_0)}=t_0$, we have $k=1$ as desired.

Primitive of $dz/z$ is a branch of log


Problemas ao fazer chamada ajax com checkbox

Question: Tenho vários checkbox que vão fazer uma chamada ajax, mas só o primeiro checkbox é que faz a chamada.
Alguma solução nos IDs para que esta lista faça a mesma chamada ajax?
Script:

Html:
<input type="checkbox" id="SelectDias" name="SelectDias" value="Domingo" class="checkbox-inline" />
 @Html.Label("Domingo", new { @class = "control-label" })

<input type="checkbox" id="SelectDias" name="SelectDias" value="Segunda-Feira" class="checkbox-inline" />
@Html.Label("Segunda-Feira", new { @class = "control-label" })

<input type="checkbox" id="SelectDias" name="SelectDias" value="Terça-Feira" class="checkbox-inline"  />
@Html.Label("Terça-Feira", new { @class = "control-label" })

<input type="checkbox" id="SelectDias" name="SelectDias" value="Quarta-Feira" class="checkbox-inline" />
@Html.Label("Quarta-Feira", new { @class = "control-label" })

<input type="checkbox" id="SelectDias" name="SelectDias" value="Quinta-Feira" class="checkbox-inline" />
@Html.Label("Quinta-Feira", new { @class = "control-label" })

<input type="checkbox" id="SelectDias" name="SelectDias" value="Sexta-Feira" class="checkbox-inline"  />
@Html.Label("Sexta-Feira", new { @class = "control-label" })

<input type="checkbox" id="SelectDias" name="SelectDias" value="Sábado" class="checkbox-inline" />
@Html.Label("Sábado", new { @class = "control-label" })

Answer: O atributo id serve (como seu próprio nome diz) como uma identificação única para a página, não deveria ter dois elementos no mesmo frame com o mesmo id. Em vez de $("#SelectDias") prefira usar $(".checkbox-inline"), se houver algum input que use a classe checkbox-inline e ele não faz parte de SelectDias, cogite criar um class específico para ele, como um class dia-da-semana.
Comment: Perfeito, entra na função, não percebo porque é que na chamada ajax leva sempre o primeiro valor da minha primeira checkbox, ou seja "Domingo".
Comment: data: { diasPertendidos: $(".checkbox-inline").val() }
Comment: SimãoLopes nesse caso, use conforme a resposta do Diego, fazendo um $(this) para pegar o elemento que disparou o evento. O contexto this no caso de eventos no jQuery é o elemento que dispara o evento (cuidado com as pegadinhas do Event Bubbling, mas aqui não é o caso).
Comment: Perfeito. Obrigado :)
Answer: Dando um improving na resposta do Gabriel, tem que definir uma classe, como no próprio exemplo dele, dia-da-semana.
E dentro do seu método do click event você pega a instancia do checkbox que foi clicada para usar o valor que você selecionou:

Comment: Perfeito. Obrigado :)


Jquery selectbox value update cakephp

Question: In my cakephp 1.3 project i am doing following.
<?php
echo $this->Form->input('city',array('type'=>'select','label'=>false,'class'=>'input2','id'=>'city','options'=>$cities));
?>

And its my script.

Script action:onchange event is fired with select box and current page is reloaded with other parameter from selectbox.But pronlem is as page get reloaded,select box is again set back to default value.
   What i am trying to do is set value to select box.I am trying to do this with code:
$("#mySelect").val("London");

Answer: You are reloading the page, any code you call after the window.location line won't affect the page when it reloads. JS is not persistent. Try and avoid reloading the page if at all possible. Otherwise you could pass the parameters of the page along with the reload, and re-set them up when the document is ready (I really don't see any plausible application for this).
Comment: I have much more returning from tjat url wit passed variable...I got confused with decoding iterative json data.And setting it...I have used params['pass'][0]); ?>
    It solved my problem almost.But now i am having another problem.
Comment: Its that when i have this URL http://localhost/cityportal_v1.0/index.php/companies/city/London/page:2  then my passed jquery parameter is appending on that link and its become  http://localhost/cityportal_v1.0/index.php/companies/city/London/page:2/Germany   And i am really messed up with this actually

Jquery selectbox value update cakephp