Problema de margin quando gera de pdf

Question: Estou fazendo um relatório, quando to gerando o pdf, tentei implementa a margem, mas continua a corta a tabela no meio e continua na outra pagina.
Está acontecendo isso na margem, mesmo eu colocando ele continua a corta no meio da tabela

Essa é minha controller onde gera o pdf:
var pdf = new ViewAsPdf
            {
                ViewName = "TesteRelatorio",
                PageSize = Size.A4,
                IsGrayScale = true,
                Model = abastecimento.ToPagedList(paginaNumero, abastecimento.Count),
            };
            return pdf;

Minha View:
    @using PagedList.Mvc;
@model PagedList.IPagedList<BlogWeb.Models.Abastecimento>

@{ ViewBag.Title = "Relatório de Vendas";
    Layout = "~/Views/Shared/_Layout2.cshtml"; }

Relatório Venda por Pedido/Período De: @ViewBag.dataInicio á @ViewBag.dataFinal

                        Quant. Total (Litros):
                        Total (R$):
                        Total de Km Percorrido:
                        Media de Litro Consumido:

                        @Model.Sum(t => t.Litro)
                        @ViewBag.TotalGasto
                        @ViewBag.Total
                        @ViewBag.KmMedia

                            N° Carro
                            Quant.
                            Km
                            Valor Unitário
                            Sub Total
                            Data Abastecimento

                        @{foreach (var item in Model)
                            {

                                     @Html.DisplayFor(modelItem => item.NumCarro.NCarro)
                                     @Html.DisplayFor(modelItem => item.Litro)
                                     @Html.DisplayFor(modelItem => item.Km)
                                     @Html.DisplayFor(modelItem => item.VlrUnit)
                                     @Html.DisplayFor(modelItem => item.TotalGasto)
                                     @Html.DisplayFor(modelItem => item.DtAbastecido)

                            }
                        }

Layout2:
<!DOCTYPE html>

Ribeira

        Ribeira Beer Distribuidora de Bebidas Ltda

            @RenderBody()

        Copyright 2017 - RibeiraBeer

@RenderSection("Scripts", false)

Meu CSS:
    @import url(http://fonts.googleapis.com/css?family=Merriweather);
@import url(http://fonts.googleapis.com/css?family=Gloria+Hallelujah);

html{
    height: 100%;
}

body {
    min-height: 100%;
    position: relative;
    padding-bottom: 3em;
    box-sizing: border-box;
}

header {
    /* Altura 480 px  largura: 1920 */
    font-family: 'Gloria Hallelujah', cursive;
    background-image: url(../Imagens/header.jpg);
    background-position: center;
    color: white;
    padding: 1em;
    padding-top: 4em;
}

nav {
    position: absolute;
    top: 0;
    width: 100%;
    background-color: rgba(0,0,0, 0.2);
}

nav a {
    color: #ddd;
    padding: 0.5em 0;
    margin-right: 1em;
    display:inline-block;
}

nav ul {
    padding: 0;
    margin:0 1em;
}

nav li {
    display: inline-block;
}

main{
    margin-bottom: 1em;
}

aside {
    padding: 1em;
    background-color: white;
}
div.static {
    position: static;
    }
footer{
    padding: 1em;
    background-color: #31385a;
    color: white;
    position: absolute;
    bottom: 0;
    width: 100%;
    -webkit-box-sizing: border-box;
    -moz-box-sizing:border-box;
    box-sizing:border-box;
    page-break-after: auto;
}

article {
    background-color:white;
    padding: 1em;
    font-family: Merriweather, 'Times New Roman', serif;
}

.blog-post-meta{
    margin-bottom: 1em;
    color: #AAA;
}

h1 {
    margin: 0;
    font-size: 3em;
    line-height:1em;
}

h2 {
    margin: 0;
}

article + article {
    margin-top: 1em;
}

.conteudo{
    padding: 1em;
    overflow: auto;
    color: #333;
}

aside ul {
    padding: 0;
}
aside li{
    list-style:none;
    margin-left: 1em;
    margin-bottom: 0.25em;
}

table {
    width: 100%;
    margin: 1em 0;
}
tbody tr:hover{
    background-color: #EEE;
}
tr + tr {
    border-top:1px solid #CCC;
}
td {
    padding: .5em;
}

td a:before{
    font-size: 20px;
}
td a{
    font-size: 0;
    text-decoration: none;
}
th{
    color: #666;
    text-align: center;
}

label {
    margin-top: 1em;
    font-weight: bold;
    display:inline-block;
    margin-bottom: .25em;
    color: #666;
}

input[type=checkbox]{
    width: 1.25em;
    height: 1.25em;
    display: block;
}

[type=text],[type=password],textarea, select{
    box-sizing: border-box;
    width:20%;
    border: 1px solid #CCC;
    padding: .5em;
}

input[type=submit]{
    padding: 0.5em 1em;
    margin-top: 1em;
    font-weight: bold;
    color: white;
    background-color:#31385a;
    border: none;
}

.input-validation-error {
    border-color: red;
    background-color: #ffced2;
}

.field-validation-error, .field-validation-valid{
    color: red;
    display: block;
    margin-top: .5em;
}

@media (min-width: 50em){
    .conteudo {
        width: 50em;
        margin: 0 auto;
    }
    main{
        float: left;
        width: 35em;
    }
    aside {
        width: 12em;
        float: right;
    }
    td a {
        font-size: 1em;
    }
}
.pagination {
    display: inline-block;
}

.pagination a {
    color: black;
    float: left;
    padding: 8px 16px;
    text-decoration: none;
}

.button {
    background-color: #294a73;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
}

#customers {
    font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
    border-collapse: collapse;
    width: 100%;
}
#customers2 {
    font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

#customers td, #customers th {
    border: 1px solid #ddd;
    padding: 8px;
}

#customers2 td, #customers2 th {
    border: 1px solid #ddd;
    padding: 8px;
}

#customers tr:nth-child(even){background-color: #f2f2f2;}

#customers tr:hover {background-color: #ddd;}

#customers2 tr:nth-child(even){background-color: #f2f2f2;}

#customers2 tr:hover {background-color: #ddd;}

#customers th {
    padding-top: 12px;
    padding-bottom: 12px;
    text-align: left;
    background-color: #3e4e84;
    color: white;
}

#customers2 th {
    padding-top: 12px;
    padding-bottom: 12px;
    text-align: left;
    background-color: black;
    color: white;
}

@media print {

    * {
        background: transparent !important;
        color: #000 !important;
        text-shadow: none !important;
        filter:none !important;
        -ms-filter: none !important;
    }

    body {
        margin:0;
        padding:0;
        line-height: 1.4em;
        font: 12pt Georgia, "Times New Roman", Times, serif;
        color: #000;
    }

    @page {
        margin: 1.5cm;
    }

    .wrap {
        width: 100%;
        margin: 0;
        float: none !important;
    }

    .no-print, nav, footer, video, audio, object, embed {
        display:none;
    }

    .print {
        display: block;
    }

    img {
        max-width: 100%;
    }

    aside {
        display:block;
        page-break-before: always;
    }

    h1 {
        font-size: 24pt;
    }

    h2 {
        font-size: 18pt;
    }

    h3 {
        font-size: 14pt;
    }

    p {
        font-size: 12pt;
        widows: 3;
        orphans: 3;
    }

    a, a:visited {
        text-decoration: underline;
    }

    a:link:after, a:visited:after {
        content: " (" attr(href) ") ";
    }

    p a {
        word-wrap: break-word;
    }

    q:after {
        content: " (" attr(cite) ")"
    }

    a:after, a[href^="javascript:"]:after, a[href^="#"]:after {
        content: "";
    }

    .page-break {
        page-break-before: always;
    }

    /*Estilos da Demo*/
    .header.print h1{
        width: 100%;
        margin-bottom: 0.5cm;
        font-size: 18pt;
    }

    .header.print:after {
        content: "Bem vindo";
    }

    .artigo {
        margin-top: 0;
        border-top: 1px solid #000;
        padding-top: 1cm;
    }

    h1 a:link:after, h1 a:visited:after {
        content: "";
    }
}

Comment: Tenta colocar margin   PageMargins = new Margins(0, 0, 0, 0),
Comment: @PauloHDSousa Tentei colocar as margens em tudo 0, e continua a corta a tabela ao meio
Comment: Não tem nenhum estilo na view?
Comment: To aplicando o meu layout, vou coloca o codigo na pergunta
Comment: @PauloHDSousa coloquei o layout e a view do pdf
Comment: Tem algum .css externo? na Master ou algo assim?
Comment: @PauloHDSousa Tem um css, quer que eu posto todo ele?
Comment: Sim, acho que nele que está as margens
Comment: Tenta Tirar TODOS os css e gerar o PDF
Comment: @PauloHDSousa Retirei todo Css e o relatorio não corta mais a tabela no meio
Comment: então tem algo no css
Comment: @PauloHDSousa poderia coloca isso como resposta para eu pode positivar?
Answer: Tem algo no .css que está quebrando na geração do seu PDF.

Problema de margin quando gera de pdf


DRF - make an resource alias /me for current user

Question: How to make a resource that will have /user/me url endpoint that will point to current user and behave exactly same as /user/< userid > ( e.g all post, put, delete request done to /user/me should work same way as /user/< userid > ). I see that there is a @detail_route decorator for custom routes, but it seems that inside it i will need to duplicate  code there , for each separate request method, which doesnt seem to be a good option. I just need to make an alias for current user.
Im talking about ModelViewSet
Comment: How have your constructed your views? Are you using ViewSets? Generic class-based views? Function-based view?
Comment: ModelViewSet. Updated the question
Comment: what do you mean by "`/user/me` url endpoint that will point to current user"?
Comment: @iulian ouch, SO eat some symbols.  I mean /user/me endpoint that will point to current user and have all other method that have /user/currentuserid
Answer: I haven't tested this, as I don't use ViewSets myself, but I believe you could do something like this:
In your urls.py:
from django.conf.urls import url
from rest_framework import routers

from . import views

router = routers.SimpleRouter()
router.register(r'users', views.UserViewSet)

urlpatterns = [
    url(r'^users/me/$', views.UserViewSet.as_view(), kwargs={'pk': 'me'}),
    url(r'^', include(router.urls)),
]

In your views.py:
from rest_framework import viewsets

from .models import User
from .serializers import UserSerializer

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_object(self):
        if self.kwargs.get('pk', None) == 'me':
            self.kwargs['pk'] = self.request.user.pk
        return super(UserViewSet, self).get_object()

Again, this is entirely untested, and entirely theoretical, but something of this sort should work.
Comment: Used similar approach. But modified only get_queryset method.

    def get_queryset(self):
        user = self.request.user
        qs = Profile.objects.all()
        if self.kwargs.get("pk", "") == "me":
            self.kwargs['pk'] = user.profile.id
        return qs
Answer: I too wanted a similar feature where I had a bunch of URLs such as:

host_name/api/student/<pk>
host_name/api/student/<pk>/something_else

and I wanted the user to be able to access any such URL by replacing  with me, and it would automatically substitute 'me' for that user's pk. So I used an improved verison of @Joey Wilhelm's answer.
urls.py:
# original:
path('api/', include(student_router.urls)),

# modified:
path('api/', include(student_router.urls), kwargs={'pk': 'me'}),

views.py:
def dispatch(self, request, *args, **kwargs):
    # we do not want the 'pk' kwarg to appear in non-detail views,
    # since that will give us a "<view> got an unexpected keyword argument 'pk'" error
    if not self.detail:
        kwargs.pop('pk', None)

    else:
        # self.request is not yet populated with the proper user details,
        # so initialize it the same way as in the super method
        req = self.initialize_request(request, *args, **kwargs)

        # replace 'pk' with the user's pk
        kwargs['pk'] = req.user.pk

    return super().dispatch(request, *args, **kwargs)


Quebra automática em menu com ícone e texto alinhados

Question: Estou fazendo um menu com ul e li onde dentro das minhas li tem um a com um span para o ícone e um span para o texto do item do menu. Atualmente quando ele chega em uma resolução xxx ele quebra os itens. Eu gostaria que quando fosse acontecer a quebra, o ícone ficasse em cima da palavra ao invés do que acontece atualmente que é ao lado mas isso sem usar um @media (max-width: 1100px). Abaixo o fonte do menu e uma imagem de como eu queria que ficasse quando houvesse a quebra.

.container {
  max-width: 1100px;
  margin-left: auto;
  margin-right: auto;
}

#nav-root {
  position: relative;
  top: 1px;
}
#nav-root > li {
  display: table;
  float: left;
  font-size: 1.1em;
  white-space: nowrap;
  position: relative;
  border-left: 1px solid #e2e7eb;
}
#nav-root > li:last-child {
  border-right: 1px solid #e2e7eb;
}
#nav-root > li > a {
  display: table-cell;
  color: #585858;
  text-decoration: none;
  text-align: center;
  padding: 20px 16px;
  text-transform: uppercase;
  font-weight: bold;
  /*&.menu-link-1350 .menu-icon {*/
}
#nav-root > li > a:hover {
  padding-bottom: 18px;
  background-color: #f1f5f8;
  color: #e23d80;
  border-bottom: 2px solid #e23d80;
}
#nav-root > li > a .menu-icon {
  width: 27px;
  height: 18px;
  display: table-cell;
  vertical-align: middle;
}
#nav-root > li > a .menu-text {
  vertical-align: middle;
  display: table-cell;
}
#nav-root > li > a.menu-link-803 .menu-icon {
  background: url("http://i.imgur.com/KSiKHuq.png") center top no-repeat;
}
#nav-root > li > a.menu-link-804 .menu-icon {
  background: url("http://i.imgur.com/KSiKHuq.png") center top no-repeat;
}
#nav-root > li > a.menu-link-805 .menu-icon {
  background: url("http://i.imgur.com/dGZs3ZN.png") center top no-repeat;
}
#nav-root > li > a.menu-link-1185 .menu-icon {
  background: url("http://i.imgur.com/Gof729V.png") center top no-repeat;
}
#nav-root > li > a.menu-link-1344 .menu-icon {
  background: url("http://i.imgur.com/wvKgGhL.png") center top no-repeat;
}
#nav-root > li > a.menu-link-1345 .menu-icon {
  background: url("http://i.imgur.com/dGZs3ZN.png") center top no-repeat;
}
#nav-root > li > a.menu-link-806 .menu-icon {
  background: url("http://i.imgur.com/CpJVydF.png") center top no-repeat;
}
#nav-root > li ul {
  display: none;
}

        <meta itemprop="name" content="Smartphones">

            Smartphones

        <meta itemprop="name" content="Celulares">

            Celulares

        <meta itemprop="name" content="Telefonia">

            Telefonia

        <meta itemprop="name" content="Smart Gadgets">

            Smart Gadgets

        <meta itemprop="name" content="Informática">

            Informática

        <meta itemprop="name" content="Hardware">

            Hardware

        <meta itemprop="name" content="Acessórios">

            Acessórios

Como eu gostaria que ficasse com a quebra automática:
Comment: qual é o motivo de não usar o `@media `?
Comment: é que no projeto eu uso 4 resoluções para media fixa onde eu estendo de um arquivo base para todos os outros e tendo as resoluções nos media pré-definidos é 1020px, 800px, 520px, 380px e a quebra está ocorrendo antes do 1020px
Comment: somente com `CSS` acredito que você não vai conseguir. Acho que você terá que usar `JS`, você pode usar?
Comment: posso sim @MoisesGama
Comment: esqueci de te perguntar você tem `JQuery` no projeto? Ou será `JS` puro mesmo?
Comment: @MoisesGama tenho sim
Answer: A melhor maneira de se fazer isso é utilizando @media-queries.
Não precisas necessariamente de seguir essas medidas padrões dos @media-queries que mencionas-te no teu comentário na tua pergunta, podes simplesmente criar uma nova @media-query para isso responsável por essa modificação:
@media screen and (max-width: 768px) {
span.menu-icon {
    margin: 0 auto;
    display: block !important;
}
span.menu-text {
    display: block !important;
}
}

Aqui está um exemplo no JSFiddle. Arrasta a janela do resultado para poderes ver isto em ação.
Para o teu projeto, basta apenas modificar a resolução do @media-query do código acima para a resolução que queres que esta modificação ocorra.
2ª Opção - Utilizando jQuery
$(window).resize(function() {
  width = $(window).width();
  if( width < 768 ) {
    $('.menu-icon ').addClass('smallRes-menu-icon');
    $('.menu-text ').addClass('smallRes-menu-text');
  } else {
    $('.menu-icon ').removeClass('smallRes-menu-icon');
    $('.menu-text ').removeClass('smallRes-menu-text');
  }
});

.smallRes-menu-icon {
    margin: 0 auto;
    display: block !important;
}
.smallRes-menu-text {
    display: block !important;
}

Aqui tens um exemplo no JSFiddle desta segunda opção.
Answer: Consegui o efeito da imagem alterando apenas uma regra CSS (inclui aqui apenas o que modifiquei):
#nav-root > li > a .menu-icon {
  display: block;
  margin: auto;
}

.container {
  max-width: 1100px;
  margin-left: auto;
  margin-right: auto;
}

#nav-root {
  position: relative;
  top: 1px;
}
#nav-root > li {
  display: table;
  float: left;
  font-size: 1.1em;
  white-space: nowrap;
  position: relative;
  border-left: 1px solid #e2e7eb;
}
#nav-root > li:last-child {
  border-right: 1px solid #e2e7eb;
}
#nav-root > li > a {
  display: table-cell;
  color: #585858;
  text-decoration: none;
  text-align: center;
  padding: 20px 16px;
  text-transform: uppercase;
  font-weight: bold;
  /*&.menu-link-1350 .menu-icon {*/
}
#nav-root > li > a:hover {
  padding-bottom: 18px;
  background-color: #f1f5f8;
  color: #e23d80;
  border-bottom: 2px solid #e23d80;
}
#nav-root > li > a .menu-icon {
  width: 27px;
  height: 18px;
  display: block;
  margin: auto;
  vertical-align: middle;
}
#nav-root > li > a .menu-text {
  vertical-align: middle;
  display: table-cell;
}
#nav-root > li > a.menu-link-803 .menu-icon {
  background: url("http://i.imgur.com/KSiKHuq.png") center top no-repeat;
}
#nav-root > li > a.menu-link-804 .menu-icon {
  background: url("http://i.imgur.com/KSiKHuq.png") center top no-repeat;
}
#nav-root > li > a.menu-link-805 .menu-icon {
  background: url("http://i.imgur.com/dGZs3ZN.png") center top no-repeat;
}
#nav-root > li > a.menu-link-1185 .menu-icon {
  background: url("http://i.imgur.com/Gof729V.png") center top no-repeat;
}
#nav-root > li > a.menu-link-1344 .menu-icon {
  background: url("http://i.imgur.com/wvKgGhL.png") center top no-repeat;
}
#nav-root > li > a.menu-link-1345 .menu-icon {
  background: url("http://i.imgur.com/dGZs3ZN.png") center top no-repeat;
}
#nav-root > li > a.menu-link-806 .menu-icon {
  background: url("http://i.imgur.com/CpJVydF.png") center top no-repeat;
}
#nav-root > li ul {
  display: none;
}

        <meta itemprop="name" content="Smartphones">

            Smartphones

        <meta itemprop="name" content="Celulares">

            Celulares

        <meta itemprop="name" content="Telefonia">

            Telefonia

        <meta itemprop="name" content="Smart Gadgets">

            Smart Gadgets

        <meta itemprop="name" content="Informática">

            Informática

        <meta itemprop="name" content="Hardware">

            Hardware

        <meta itemprop="name" content="Acessórios">

            Acessórios


Consequences if linesman interferes with play?

Question: During the 2014 Russian Olympics, the United States faced Canada in hockey.  After a period of pressing on the US goal, the puck was cleared to the side. The linesman got in the way of a Canadian player, and the puck, bouncing off the boards, nearly went into the Canadian net.
Linesmen interfere with the play quite often, but are there any consequences if done so accidentally or purposefully?
Comment: Occasionally it also happens that referee might cause an injury of a player - example: [Tomas Tatar Injured after Collision with Ref](http://www.theredwingsfeed.com/tomas-tatar-injured-collision-ref/#).
Answer: The only rule in the NHL Rulebook that I could find addressing this situation is that a goal is disallowed if it goes in directly off of an official.

78.5 Disallowed Goals – Apparent goals shall be disallowed by the Referee and the appropriate announcement made by the Public Address
  Announcer for the following reasons:
(iii)  When the puck has deflected directly into the net off an
  official.

Based on my understanding (but no explicit mention in the rulebook), otherwise the officials are "in play" and no particular exception exists for stopping play due to linesmen or referees obstructing play.  Clearly they are instructed to avoid doing so whenever possible, but if they're unable to avoid the play, the play stands (unless a goal goes off of an official).
It goes without saying that this only applies to NHL games and other games which take place under NHL rules.
Comment: This is right and a good answer.  But what happens to the linesmen who interferes?  He gets a few extra beers after the game from the home team!
Comment: @Coach-D Haha... I'd be very curious myself to know if they keep track of these things and discipline linesmen who do interfere.
Comment: I don't think it is an NHL issue.  Very big issue at club level.
Answer: Under IIHF Rules, the following applies:

RULE 73 – PUCK STRIKING AN ON-ICE OFFICIAL
i.   Game action will not be stopped because the puck touches an
  on-ice  official during the regular course of play except when:

The puck enters the goal net as a result of that contact;
The puck goes out of play as a result of that contact;
An on-ice official is injured.

ii.   If  the  attacking  team  scores  a  goal  because  the  puck
  deflects  or bounces directly off an on-ice official, the goal will
  not be allowed and  the ensuing  faceoff  will  take  place  at  the
  nearest  faceoff  spot  to   where the puck made contact with the
  on-ice official.
iii.  If the puck hits an on-ice official and is subsequently put into
  the goal  net in any legal manner, the goal will be allowed.
iv.   If the puck leaves the playing area after hitting an on-ice
  official in the neutral zone, the ensuing faceoff will take place at
  the faceoff spot in  the neutral zone nearest to where the puck made
  contact with the  on-ice official.
v.    If  the  puck  leaves  the  playing  area  after  hitting  an
  on-ice  official in either end zone, the ensuing faceoff will take
  place at the faceoff spot in  the  end  zone  nearest  to  where  the
  puck  made  contact  with  the on-ice official.

Should the interference be intentional, the league will probably take action against the linesman.


If a song has no scale degree 6, how to decide between aeolian and dorian?

Question: I don't know what I did to deserve it, but I had "When Johnny Comes Marching Home" stuck in my head this morning (perhaps better known with lyrics about an ant colony, as popularized by a purple dinosaur). I mumbled to myself "Oh yeah, it's Dorian." But as the coffee started to take effect, it occurred to me that, while its melody flaunts its lowered ^7—spends a full measure on it, and gives it metric emphasis—the melody itself contains no ^6. That is, with a tonal center of A, the melody contains plenty of G natural, but has no F, whether natural or sharp.
Setting aside any consideration of how it has been harmonized in the past, and setting aside any question of its historic origins (there's a compelling argument for melodic DNA from "John Anderson, My Jo", which complicates matters with a modulation and eventually a cadential leading tone)— Setting aside any question of historical intent or treatment, and taking this as a sterile exercise in melodic analysis— And taking the "modes" in a contemporary sense, as a mere collection of pitches, without regard to more syntactic historical usages and "reciting tones" and what not— Under these circumstances, should we call this natural minor, Aeolian? It would seem it would have just as much right to Dorian. So is there an "Occam's razor" that prefers Aeolian as "more normative"? Or am I missing some other basis on which to make the decision?
Comment: Don't think you can. It's just 'minor' - same as there's no harmonic or melodic minor *key*, just 'minor'.
Comment: The fact that _John Anderson_ commonly has a raised leading tone today does not imply that it always has.
Comment: Have you tried harmonising the melody line? That may well throw up a 6th of some sort - give that a try.
Comment: I suspect the purple dinosaur is after my time, but in summer camp ca. 1962 we sang "the ants go marching one by one" in a harmonic minor, with raised sixth and seventh degrees.  And to add to the answers below: I don't see any point agonizing about what to call the mode of "Johnny".  It's hexatonic, and I don't know of any terminology that would fit the scale (say) A B C D E G A.
Answer: Deciding between Aeolian and Dorian could very well be the wrong tack when handling a minor-key piece with only non-raised 7th scale degrees but no 6th scale degree - calling the piece a minor-key piece and not bothering to classify it as Dorian or Aeolian could very well be the best thing to do.
Without enough notes in the melody to fully determine which mode a piece is (if any), it's hard to call a piece modal. Sure, we can default to claiming a melody of E-F-G-A-G-F-E-D-E is in E Phrygian instead of E Locrian, but how certain were we of that label? Heck, this particular example could be in C Ionian or C Mixolydian instead!
We're safer off merely claiming that your example is in a minor key instead of being in any one mode.
Comment: How would _When Johnny Comes Marching Home_ be in Ionian or Mixolydian?
Comment: @MichaelCurtis - Admittedly, my example doesn't completely match the one in the question - *When Johnny Comes Marching Home* contains all scale degrees but the 6th one, so you cannot claim that it's in Ionian or Mixolydian when you can validly claim it's in Aeolian or Dorian - but I like to think my point still stands and that you are better off not making mode claims for either example.
Comment: Good point—I guess if I pursued the question to the extreme, you'd have "what mode is a piece with only one pitch in," which is ridiculous.
Comment: @AndyBonner also consider: what mode is Greensleeves in?  It depends on which variant you've encountered.  You could reasonably embellish the melody of _Johnny_ with a raised or lowered sixth degree, or with both in different places.  The modern conception of modes tends to be that they are a strict set of pitches and that using a pitch outside that set means you're not in that mode, but that is not how modes were used between the late middle ages and the 18th century.  In Guido's time, Dorian mode could have a lowered 6th degree; there was no Aeolian in those days.
Comment: @phoog Yup, thus all the disclaimers about "syntactic historical usages." *Maybe* one could argue that a "grab bag of notes" is never an analytically useful concept—even a good tone row has some rhyme and reason to its ordering...
Answer: I think it's hard to look at a question like this and separate Renaissance modal "art" music from modal folk music - historically those genres overlap - and not look at how tunes are harmonized. This particular song, and many others like Greensleeves, aren't unharmonized chant or folk melodies, they were written with harmonizations.
I've been frustrated with studying Renaissance modal music, because it seems the further back in time you go, the harder it is to find music that was clearly categorized by composer's into modes. But, using Fux as a convenient example, in his dorian mode counterpoint examples he always ended with a raised leading tone and sometimes used a lowered sixth degree. Actually, his dorian cantus firmus only spans the tonic to dominant without the sixth or seventh degrees. Fux had no issue with classifying that c.f. as dorian.
I don't mean to digress into Fux, but I just want to make the point that in the Renaissance style Fux was emulating dorian would have been the basic minor mode rather than aeolian, and dorian mode wasn't rigidly defined by the sixth scale degree.
But, is When Johnny comes Marching Home modal in the first place?

|Gm     |Gm     |Bb    |F     |
|Gm     |Gm     |Bb    |D     |
|Bb     |F      |Gm    |D     |
|Bb F/C |Gm/D D |Gm D7 |Gm    |

If we are looking for minor key, tonal confirming traits, we could say the first phrase is a half cadence in the mediant, the second phrase is a half cadence in the tonic, the third phrase is a sequence with first iteration in the mediant and the second in the tonic, the four phrase truncates the progression of the sequence and the concludes it with a perfect cadence.
From the modal perspective the opening doesn't have any tonic/dominant pair, there are a lot of root progressions by third or step, the only descending fifth progression is the final cadence. Melodically the main elements are tonic down to the lowered subtonic, outlining the minor tonic, and descending from the fifth degree to the tonic.
This seems pretty modal to me. IMO this kind of mix of so-called weak, modal progressions with tonal cadential harmony, and juxtaposing the lowered subtonic with raised leading tone, is what you frequently hear in folk music, music that would usually be called modal.
It's interesting to compare it with John Anderson, My Jo, because while there is a similarity with the open melody and the move from tonic to subtonic, the harmony of John Anderson, My Jo clearly cadences three times in the minor tonic, the subtonic, and the tonic again, for the opening. That seems more tonal than modal compared with When Johnny comes Marching Home.
Considering dorian would be the basic minor mode, it seems reasonable to say When Johnny comes Marching Home is in dorian mode. That seems less dubious than saying it's clearly in a minor key when 14 of 16 bars do nothing directly with tonic/dominant harmony.
Comment: Also, I get that the tune could be _generically_ called minor, but that just dodges the question. Given the historical background, I'd tend toward calling modal things dorian unless there was clear reason to call it aeolian.
Comment: Interesting—it's kind of the opposite of what I'd assumed, that Aeolian had a claim as a "default."
Comment: That reminds me of questions on this forum when people say some music is in some key of "natural minor" AKA aeolian mode, like "A natural minor." Or, natural minor is basic minor scale, because those are the tone of a minor key signature. But there is so much to unpack about the fluidity of tones in minor the historical development.
Comment: @AndyBonner but mode is originally a melodic concept.  The idea of "modal harmony," especially as opposed to tonal harmony, arose in the 20th century.  Look at Brahms' harmonization of (Dorian) _Mit Fried und Freud_ in the motet _Warum ist das Licht gegeben._  The soprano part -- the melody -- is definitely Dorian.  The harmonization has all sorts of accidentals, including the raised leading tone in the final cadence.
Comment: Interesting to take this answer along with Dekkadeci's. If my Q came from an attitude of "Don't pay aaaany attention to the harmonization, just looking at melody, what mode is this melody," then I take it your response is "But you can't; modality (in a modern conception) is a tonal construct." And Dekkadeci's is "Who says you have to decide?" So my synthesis of the two is "If you're *just doing* melodic analysis, nailing down a mode doesn't have to be part of it." What do you think?
Comment: If you looked at only the melody, I think you could come to the same conclusion: dorian. The melody is minor "family" by the `^1` to `^5` scale segment, the lower/raised `^7` juxtaposition gives us modal, minor+modal=dorian (provided no lowered phrygian `^2`.) The harmonization just helps confirm that, especially the lack of a minor subdominant in accompaniment in places where is would be possible.
Comment: @AndyBonner look at Bach's harmonizations of modal chorale melodies (and other harmonic treatments of modal melodic material by his contemporaries, predecessors, and successors).  And don't forget that Aeolian and Ionian modes are very late comers to the party.  The default major mode is really mixolydian.  Like Dorian, the chromatic alteration of its leading tone was not seen as robbing it of its identity.
Comment: Michael Curtis: "they were written with harmonizations": really?  How could we know that?
Comment: @phoog Yeah, I was gonna problematize that (especially re Greensleeves), and it seems the origins of "Johnny" are so non-original that there's nothing sacred about Gilmore's harmonies—BUT I guess the point stands that melodic analysis that ignores harmony has to ignore it all the way, including questions of modality.
Comment: @Phoog, in the case of _Greensleeves_ the tricky part is trying to identify one, definitive version. But, my point is even when several versions exists those early versions are often harmonized. In the case of _When Johnny Come Marching Home_, it's easy. That particular song - distinct from its descendants like _John Anderson, My Jo_ - it was published with accompaniment in 1863.
Comment: Coincidentally, I was reviewing folk tunes I have in my own collection. In particular I was researching _Barbara Allen_, _Black is the Colour_, and _Londonderry Air_. The first two are almost impossible to nail down, but the last was manageable, because current versions seem to be based on _one_ version published with accompaniment in 1855. Of course many tunes won't have accompaniment available, but when there is, and the historic sources have solid lineage, I think they should be consulted.


Why can't I change the zIndex here?

Question: I have a bunch of divs positioned on top of an image.
I am trying to make the fraction hidden by the div to appear on the mouse hover. To achieve this I tried setting the zIndex of the div to be lower than the one of the image so it gets revealed. But I can seem to select ALL the divs.
Here is my javascript code:
window.onload = function () {
    var block = document.getElementById('container');

    block.addEventListener('mouseover', function () {
        var blocks = document.querySelectorAll("#container div");
        var index = 0, length = blocks.length;
        for (var index = 0; index < length; index++) {
            blocks[index].style.zIndex = 2;
        }
    });

    for (var i = 0; i < 40; i++) {
        for (var j = 0; j < 40; j++) {
            var div = document.createElement("div");
            div.className = "block";
            div.style.left = j * 25 + 'px';
            div.style.top = i * 25 + 'px';
            div.style.display = "inline-block";
            div.style.verticalAlign = "top";
            div.style.zIndex = "1";
            document.getElementById("container").appendChild(div);
        }
        var jump = document.createElement("br");
        document.getElementById("container").appendChild(jump);
    }
};

Where did I go wrong? Thank you. The div container has the background image that is placed "under" the created inner divs.
Comment: @eithedog - No, that's incorrect. They just need to be positioned (i.e. non-static).
Comment: `mousehover` event does not exist. `mouseover` is the right one.
Comment: Probably because `Array` has no property `style`.
Comment: Also please bear in mind that the elements need to be positioned absolutely for the `z-index` to work at all (huh - thanks to @j08691 for pointing this out - keeping my original comment though)
Comment: The other thing is that if the image is itself in a div, this won't work.
Comment: @Sebas the image is the div's background. How can I solved this?
Comment: @j08691 I keep on confusing, thanks !
Comment: @Predator44, sorry, I mislead you. If it's in a div that is in #container, then it won't work (because you would then change the zIndex of a parent of the image) But if it's in its own div and you don't touch its zIndex, then you're good.
Comment: @Sebas Ah okay! what if the div has the background img? What should I do then?
Comment: I'm not sure. It's not clear to me how your layering is setup. The thing you have to keep in mind is that when you change the zIndex of a given div, everything contained in it (recursively!) cannot appear behind.
Answer: document.querySelectorAll returns an array of elements. You would need to loop through them individually.
var blocks = document.querySelectorAll("#container div");
var index = 0, length = blocks.length;
for ( ; index < length; index++) {
    blocks[index].style.zIndex = 1;
}

If you are only looking for a single element you can also use document.querySelector which returns the first element it finds that matches the selector and you can work directly on it as you originally had in your code.
Comment: I added further explanation in my question. Thanks for the help

Why can't I change the zIndex here?


Are there any benefits in using HTTPS between a load balancer and EC2 targets?

Question: I've spent some time refactoring a load-balanced web application in AWS in order to make it end-to-end HTTPS, CloudFront->ALB->EC2. This was mostly just for fun, to see if I could do it. Having jumped through quite a lot of hoops to make it work, I'm now wondering if it's worth upgrading the production infrastructure to work this way. Currently in production it's just HTTPS at the front-end and between CloudFront and ALB, but between the ALB and the EC2's it's plain HTTP.
Are there any actual benefits to using HTTPS between the Application Load Balancer and the EC2's.
I had originally hoped to have it end-to-end HTTP/2, but I couldn't get this to work to the EC2's, so that part has to be HTTP1.1
Some details about the setup.
The EC2's are running IIS, Win2022. I have a Launch Template with UserData that fully configures them including creating the self-signed SSL's for IIS.
The ALB and CloudFront obviously use ACM for the certificates.
The setup seems stable, but I'm not entirely happy about the amount of complexity I've introduced to support the ALB->EC2 HTTPS. It means it now has extra http bindings for the healthcheck, instead of being able to just use a single binding for the traffic and healthcheck.
The deployment pipeline has also become more complex, with an extra step to retrieve an an SSL cert to apply it to the IIS site.
One potential benefit, is that the site itself knows that it's running over a secure connection, so self-referencing URL's will be generated properly by default. However I've mostly found work-arounds for this anyway by manually updating the server variables in the application code.
It seems to be considered a good practice to use end-to-end HTTPS, but I'm not entirely sure why. I don't want to change the production system unless there's some specific benefits to doing so.
Answer:
It seems to be considered a good practice to use end-to-end HTTPS, but I'm not entirely sure why.

Modern security thinking is that you don't consider your own network / datacenter as more trusted (than your WAN or the regular internet).
Traditionally one would allow for more relaxed security standards in the datacenter, within the "secure" perimeter of your own network. Both internal systems and users would be trusted, implicitly expected to be secure and never abusive or malicious. One only added for example TLS for connections crossing the perimeter and borders of your "secure" internal network.
Your current configuration of terminating TLS on the load balancer and using plain HTTP for the communication between load balancers and the back-end servers fits in that traditional world view and security concept.
Nowadays the increasingly more prevalent security concept is one of "zero trust" and "encryption everywhere", which abandons the concept of a secure and trusted internal networks/systems/users and applies the same rigorous level of security everywhere, regardless.
In a cloud environment you don't have your own physical network but share resources with potentially all other customers of the cloud provider.
You hope that the cloud provider isn't malicious and can be trusted to not eavesdrop on your communication. You hope and expect that the logical separation of your (internal) traffic is robust and your data can't be intercepted by those other customers either, but you have much fewer guarantees there.
You control those risks by not implicitly trusting the security of the (virtual) internal network and rigorously applying TLS encryption, for the traffic from the load balancer to your application server, for the applications  accessing the database, etc. etc.

As a real world analogue:
Your home is in a gated community, protected by a security fence and guards at the gate. Maybe you even have a owners association that vets potential new residents and only allow "the right kind of people" to become your new neighbours.
Would you need to lock your front door at night and when you leave your home?
In traditional security thinking: no you wouldn't need to lock your doors at night because you're safe in your gated community and all the "bad people" will be kept out by the fence and security guards.
And your neighbours won't be nosy gossips that will simply let themselves into your home.
In modern security thinking: yes of course you do lock your front door, because when (no if about it) the fence is breached and/or the guards fail to keep "a bad person" out, then that bad person can't simply enter every single home, but will still need to pick locks, or force entry, which both delays their unwanted access, increases the odds of being detected and reduces the number of house they can burglarise.
Comment: While this is indeed true, I am very sad nobody considers additional CPU cycles spent on this encryption/decryption, which could even happen on the same machine, and various implications: the additional load and delay (and argue for the cases when it could be considered negligible and when it couldn't), its environmental impact (additional CPU work wastes additional energy) and so on. Returning to the analogy, it costs money to put locks to each house, delays the valid entry for those who possess the key, adds the risk of losing the key, and so on. Nothing comes without the price.
Comment: TLS and encryption has become commodity and much cheaper in many aspects, with built-in instruction sets in CPU for example. Their expense has become low enough that most professionals and  would consider it negligent to not set up.  But I'm the first one to preach  that encryption  also is not the secret sauce that will automatically make your applications and infrastructure 100% secure either. Set up encryption but omit to change the default administrator password (or don't  set any access controls at all) and your security is still crap, for example.
Comment: Yes, "security is a process". What I wanted to say is that any security measures set up without the evaluation of the threat model should be treated with no more respect than any premature code optimization.
Comment: Indeed, nothing comes without a price and that also holds true for good/better security. _-_ In a proper risk analyses you would talk about odds and probabilities of certain risks happening and the potential loss that will/could be realised when those risks occur and then make the trade-off : EITHER accept the risks, do nothing and accept the costs when they happen OR accept that preventative measure to completely eliminate or (significantly) reduce those risks come with increased complexity, work and investments and accept those.
Comment: @NikitaKipriyanov Just thought I'd mention that after implementing full end-to-end SSL, I haven't noticed any increase in average CPU usage. My understanding is that this isn't really an issue anymore, with newer generation CPU's.
Comment: @HBruijn That's a point well worth raising, and yes I'm considering all other aspects of security as well. I'm aware that SSL is just one small part of the overall security of an application. Also, as it turned out, the end-to-end SSL setup wasn't all that difficult, and doesn't cost anything extra, or reduce performance in any way, so I'm calling this one a win :-)


Array em php com PDO

Question: precisei mudar minha conexão mysqli para pdo, e estou "apanhando" na hora de apontar qual index que quero imprimir, olhe o exemplo do modelo com mysql:
$Busca = mysql_query("SELECT * FROM OrdemServico WHERE Status = '$Status'", $con -> conexaoMysqlP()) or die (mysql_error());
$Consulta = mysql_fetch_array($Busca);
<?php
do{

<?=$Consulta["RAT"] ?>
<?=$Consulta["Clientes"]?>

}while ($Consulta = mysql_fetch_assoc($Busca));

Agora preciso dele em PDO, mas não consigo imprimir separado, apenas todos e com o index.
$Pesquisar = $pdo->prepare("SELECT * FROM OrdemServico order by Status");
$Pesquisar -> execute();
$result = $Pesquisar->fetchAll();

<?=$Consulta["RAT"] ?>
<?=$Consulta["Clientes"]?>

}while ($result = $Pesquisar->fetchAll());

Espero que alguém possa me ajudar, e obrigado pela atenção!^^
Answer: Provavelmente você precisa de algo assim:
<?php

  ...

  $Pesquisar = $pdo->prepare( 'SELECT * FROM OrdemServico order by Status' );
  $Pesquisar->execute();
  $result = $Pesquisar->fetchAll();
  foreach( $result as $Consulta ) {
?>

      <?= $Consulta['RAT'] ?>
      <?= $Consulta['Clientes']?>

<?php
  }

A razão é que o fetchAll() já vai trazer todas as linhas por padrão, não adianta executar mais de uma vez. No caso, o foreach vai servir para iterar uma a uma.
Uma maneira mais parecida com seu código original seria usar fetch no lugar do fetchAll:
<?php

  ...

  $Pesquisar = $pdo->prepare( 'SELECT * FROM OrdemServico order by Status' );
  $Pesquisar->execute();
  while( $Consulta = $Pesquisar->fetch(PDO::FETCH_ASSOC) ) {
?>

      <?= $Consulta['RAT'] ?>
      <?= $Consulta['Clientes'] ?>

<?php
  }

Comment: Obrigado amigo, o problema foi resolvido.... coisa simples rsrrs! Mais uma vez um muito obrigado!

Array em php com PDO


Particle moving along an ellipse; negative/positive displacement

Question: I have the following problem.
A particle moves along an ellipse  $$3x^2 + y^2 = 1$$ with a position vector $$\vec{r} (t)= (f(t), g(t))$$ the displacement is such that the horizontal component of the velocity vector in each  instant $ t $ is  $ -g(t)$.
Is the particle having a negative or positive displacement?
Show that the vertical component of the velocity vector in instant  $ t $ is proportional to $ f(t)$. Find the constant of proportionality.
This is what I have:
$$\vec{r} (t)= ( \cos(t)/\sqrt{3} , \sin(t))$$
$$\vec{v} (t) = ( -\sin(t)/\sqrt{3} , \cos(t))$$
Velocity vector with horizontal component  $ -g(t)$:
$$\vec{v} (t) = ( -\sin(-sin(t))/\sqrt{3} , \cos(t))$$
This is equal to:
$$\vec{v} (t) = ( \sin(sin(t))/\sqrt{3} , \cos(t))$$
My conclusion, if I am not wrong, is that since both components of the velocity vector are positive then the particle displacement is positive.
I am still not sure about what to do regarding if the vertical component of the velocity vector in instant  $ t $ is proportional to $ f(t)$, and about finding the constant of proportionality.
Any tips on how to solve that problem?
Edit:
Constant of proportionality

Please excuse my english. Thanks.
Answer: You claim that
$$ \vec r(t) = (f(t), g(t))
   \stackrel?= \left( \tfrac1{\sqrt3} \cos(t), \sin(t)\right). \tag1$$
Therefore you claim that at $t = 0,$ the particle is at
$\left( \tfrac1{\sqrt3}, 0\right)$.
You claim that at time $t = \frac\pi2,$ the particle is at $(0, 1).$
You claim that the particle continues around the ellipse counterclockwise and that if we note the position of the particle at any instant, it takes exactly $2\pi$ units of time for the particle to return to that position.
Very specifically, you claim that $f(t) \stackrel?= \tfrac1{\sqrt3} \cos(t)$
and that $g(t) \stackrel?= \sin(t).$
This is exactly what Equation $(1)$ says.
None of this can be deduced from the statement that
a particle moves along the ellipse  $3x^2 + y^2 = 1$ with a position vector
$\vec{r} (t)= (f(t), g(t))$.
You cannot even deduce it from the statement that the displacement is such that the horizontal component of the velocity vector in each  instant $ t $ is  $ -g(t)$,
because in fact that statement implies that Equation $(1)$ is not the correct equation of motion of the particle.
If Equation $(1)$ were correct, then the horizontal component of the velocity of the particle at any time $t$ would be
$-\tfrac1{\sqrt3} \sin(t).$
But since you have claimed that $g(t) \stackrel?= \sin(t),$ it follows that
$-g(t) \stackrel?= -\sin(t) \neq -\tfrac1{\sqrt3} \sin(t).$
So the horizontal component of the velocity would not be $-g(t).$
I have no idea why you would think the horizontal component of $\vec v(t)$
is $-{\sin(-\sin(t))}/{\sqrt3}.$
According to your other claims, that's $f'(-g(t)),$ not $-g(t).$
What you do know is that the position of the particle at any instant can be described by the formula
$$ \left( \tfrac1{\sqrt3} \cos(\theta), \sin(\theta)\right) $$
for some number $\theta$. If you knew the position of the particle at time $t$ you could find a value of $\theta$ that makes the formula above produce the coordinates of that position, and then you could declare that this defines $\theta$ as a function of $t$. That is, you could conclude that
$$ \vec r(t) = \left( \tfrac1{\sqrt3} \cos(\theta(t)), \sin(\theta(t))\right). $$
You could even reasonably conclude that this should be true for some continuous function, that is, you can suppose that $\theta(t)$ is a continuous function of $t$.
(You could just as easily make it discontinuous by randomly adding multiples of $2\pi$ to some values of $\theta(t)$, but you can choose not to do such a silly thing.)
You could even reasonably assume $\theta(t)$ is differentiable.
There's actually nothing in the problem statement that requires $\theta(t)$
to be differentiable everywhere, but it's a reasonable assumption and it does need to be true in enough places to answer the question.
Assuming that $\theta(t)$ is differentiable, you should be able to apply the chain rule to find components of the particle's velocity,
and setting the horizontal component equal to $-g(t)$ you may then be able to draw some conclusions about $\theta(t)$ which will tell you in which direction the particle travels around the ellipse.
Comment: Thank you David for your explanation, it made me realize how wrong I was.
Answer: Particle moves along $3x^2+y^2=1$
So we define $\vec r(t) = (\frac{1}{\sqrt3} \cos (at), \sin (at))$ where $a$ is a constant. For $a = 1$, it will take $2\pi$ unit of time for the particle to go along the ellipse and return to its starting position.
$\vec v(t) = (- \frac{a}{\sqrt3} \sin (at), a \cos (at))$
We also know that $\vec r(t) = (f(t), g(t))$ such that $x$ component of velocity vector at any given $t$ is $-g(t)$.
So what is the value of $a$? Can you take it from here?
Comment: a is the square root of 3, so the particle moves counter clockwise right? I realize now I made a huge mistake, but could you please explain why "a" is needded? I also added a picture to the post with the constant of proportionality, could you please look at it and tell me if it is correct?
Comment: yes ratio of proportionality is correct. yes it will be counterclockwise. if you do not have $a$ or $a = 1$, what does that mean? you are assuming that it is taking $2\pi$ unit of time to complete one round but that may or may not be right.
Comment: As per given condition, it is taking only $2 \pi / \sqrt3$ unit of time to complete one rotation.
Comment: Thanks a lot for the help with this question and the one about the hyperbola
Comment: you are welcome!


how can i add fontawesome to javascript element?

Question: Good evening guys. I am preparing a todo app. I added delete button but I want to add icon from fontawesome to delete button. Where exactly do i need to add  ? I would be glad if you help me

        <input type="text" id="myInput" placeholder="Title..." />
        <button onclick="newElement()">Add</button>

Answer: There are two things to highlight here is,
First, the code piece to delete a list item is not deleting the actual item, but just hiding it from rendered HTML and that's wrong. You should remove that element completely from the document. The below code is not deleting in actuality.

close[i].onclick = function() {
   var div = this.parentElement;
   div.style.display = 'none';
};

Secondly, answering your query about adding icons using  tag. If you are adding this dynamically it should be done the same way you did with the  tag. You have to do createElement and append that element to its parent. You can link the fontawesome in your HTML document's  part. Here is the generic CDN link.

<link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">

For an updated version of the above link, you can check their official website.


Devemos usar ícones em SVG ou PNG para websites?

Question: É melhor utilizar ícones na formatação SVG ou PNG para websites? Por que?
Comment: como o bigown falou, depende do uso, o que ele disse especifica muito be,.
Answer: Razões para o SVG ser uma boa escolha:

Ele suporta navegadores com janelas de qualquer tamanho suavemente, especialmente com o CSS background-size
Você pode escalá-los para cima/para baixo, como para um efeito hover
Você pode incorporar SVGs e fazer modificações neles em tempo real com JavaScript e DOM
Você pode estilizar SVGs ou partes deles com CSS (mudança de cores, contornos, etc.)
Você pode gerar SVGs dinamicamente no cliente ou no servidor. Devido à sua natureza baseada em texto, você não precisa de bibliotecas de baixo nível ou servidores poderosos para criá-los.

Razões para o PNG ser uma boa escolha:

Suporte melhor em todos os navegadores
Ferramentas existentes para criar spritesheets PNG
A maioria das pessoas tem um editor compatível com PNG em seu computador
Se a imagem é foto ou outras imagens difíceis de vetorizar

Fonte.
Coloquei no GitHub para referência futura.
Comment: Apesar de concordar em grande parte com sua resposta (mas também não estou dizendo que está errada), como ele questiona sobre o uso de `SVG` com ícones, acho que somente o item nº 2 caberia nos itens sobre `PNG`. Se não for um _spritesheet_, não vejo mais por que utilizar _.png_. E lembrando também que para poder usar `SVG` dinâmico, como descrito na resposta, o mesmo deve ser _inline_ e não como referência em uma `img` _tag_.
Comment: Pode ser a sua única razão, a maioria das pessoas possuem outras razões, admito que a terceira realmente é mais uma questão de quem está fazendo e tem solução mais ou menos fácil, mas não tão simples quando não precisa da vetorização. Fotos vetorizadas não costumam ficar boas e pode exigir acerto manual, o que aumenta muito o trabalho. Se acha que não precisa suportar navegadores que não trabalham com SVG, ok, mas é bom a pessoa saber que usando ele estará adaptando para menos navegadores, de fato um problema menor, mas não inexistente. Vale a ressalva.
Comment: Mas para considerar o suporte de navegadores a SVG, creio que seria uma parcela insignificativa que ficaria de fora, pois bem dizer todos os navegadores e versões suportam SVG. [Referência](http://caniuse.com/#feat=svg).
Answer: Particularmente prefiro SVG, pois acaba se tornando mais leve, por ser um vetor, e tambem fica mais facil para trabalhar, como nosso amigo colocou acima, vc tem acesso diretamente ao codigo da imagem, podendo estilizar de acordo com sua criatividade.
Vale ressaltar aqui, que os icones criados e disponiveis para frameworks, sao todos baseados em SVG, bibliotecas como Font Awesome, Material Design, Bootstrap, etc...


Há como exportar um app para teste sem o apple developer program ?

Question: Estou concluindo um app em swift 2 IOS e gostaria de saber se há como exportar e instalar num iphone sem que tenha o apple developer program, tal como pode ser feito no android.
Comment: Sim..  basta compilar diretamente no aparelho. Ou vc que dizer que pretende distribuir em outros aparelhos sem precisar compilar cada um?
Answer: Você pode criar uma conta de desenvolvedor, mas sem pagar os 99 USD. Dessa forma você continua sem poder publicar apps na AppStore, mas pode instalar o app no seu iPhone.
Pra isso, você pluga o iPhone no seu Mac e, no XCode, ao escolher o device, vai aparecer o seu iPhone lá... É preciso que a sua conta de desenvolvedor esteja vinculada ao projeto, mas se eu não me engano o XCode meio que te guia para você fazer isso. ;)
Answer: Tem como você instalar sim e a partir do Xcode 7 não precisa mais pagar a licença!

No Xcode, você adiciona o seu Apple ID em Account preferences.
Selection o projeto que quer colocar no iPhone/iPad e o target no navegador do projeto.
No projeto, clique em General e escolha o seu nome na opção Team.
Só dar play. Se for a primeira vez de um dispositivo as vezes demora um pouco para funcionar e pode até dar um erro, espere mais um pouco e tente de novo.

Os aplicativos são instalados antes de você abrir, e podem ser abertos até mesmo depois de desconectar do computador. Vale lembrar que algumas funções, como o game center, não funcionam sem uma conta de desenvolvedor.
Mais info:
1) https://stackoverflow.com/questions/4952820/test-ios-app-on-device-without-apple-developer-program-or-jailbreak
2)http://blog.ionic.io/deploying-to-a-device-without-an-apple-developer-account/
Answer: Boas, Clever
Sem a conta de Apple developer program não é possível, bem até onde sei.
Também não podes simular um app do Xcode em seu iPhone esse tentei com o SWift 3 Xcode 8.
Comment: Obrigado pelo retorno mas eu tenho conta https://developer.apple.com e consigo testar o app no iphone plugado com o xcode. Porém não sou assinante do apple developer program, o qual tem que pagar $ 99,00. Como o desenvolvimento de app não é o meu forte, não queria gastar em vão com esta conta. Por isso questiono se há alguma forma de instalar o app em aparelhos de teste sem que tenha que pagar. O Android, por exemplo, eu posso repassar o app por email para quem que quiser e instalar como teste.
Comment: No Android e Windows Phone podes, ja na Apple sem a conta do developer program e impossível talvez com jailbreak consigas resolver.

http://www.techtudo.com.br/dicas-e-tutoriais/noticia/2014/04/o-que-e-jailbreak.html
Comment: Andreza, A conta apenas é vinculada caso exista a conta de Developer Program. Se não tiver não ira instalar, simular é o máximo que se pode fazer.
Comment: Cómo mencionei...pode instalar sim no dispositivo mesmo não tendo programa...apenas a conta ativa...pois isso eu fiz. Mas pelo visto enviar a outra pessoa não tem jeito sem aderir ao Apple developer program


MySQL dropping unique pair

Question: In a table of my database I made the unfortunate mistake of making a pair of fields unique when creating the database
UNIQUE(A,B)

I now want to remove this constraint. How can I do this in MySQL syntax?
I know for a single index I can do
ALTER TABLE MyTable DROP Index A

But I'm not sure how to do it for pairs.
Answer: The key still has a name, and it's probably A unless you also made A a key first or gave it a specific name.
ALTER TABLE MyTable DROP INDEX A

should actually work.  Look at the table definition (SHOW CREATE TABLE) to see what the actual name of the key is.

MySQL dropping unique pair


Unable to send keys to div element Selenium - Java

Question: Hi am trying to populate value to text box (check image below) using xpath.
Actions actions = new Actions(driver);
                                        actions.moveToElement(driver.findElement(By.xpath("//*[@class='CzI8E']")));
                                        actions.click();
                                        Thread.sleep(3000);
                                        actions.moveToElement(driver.findElement(By.xpath("//*[@class='_2S1VP copyable-text selectable-text']")));//_2S1VP copyable-text selectable-text
                                        actions.sendKeys(WhatsappConstants.TEXT_MESSAGE);
                                        actions.build().perform();

But i am getting this exception
org.openqa.selenium.WebDriverException: unknown error: ChromeDriver only supports characters in the BMP
Other stackoverflow answers said to use firefox driver but in my case i need you use chrome only.
Comment: I don't see any textbox in the dom hierarchy. Perhaps you need to click the div you focused first then it injects a textbox there - just a guess.
Comment: @SiddhantSwami if you see my code above, I have already clicked on the element
Comment: Update the question with the relevant _HTML_
Comment: Can you share the URL of web site ?
Comment: What is value of WhatsappConstants.TEXT_MESSAGE? Does it contain any non-unicode symbols (chinese, russian alphabet, emoji, etc.)?
Answer: This is a known limitation of the Chromedriver, see http://crbug.com/chromedriver/2269 for the bug report in the official bug tracker.
What you could do is to only limit yourself to supported characters, basically those from: http://www.columbia.edu/kermit/ucs2.html
Alternatively, you could simulate input instead of really sending the keys using front-end JS snippet like the following:
(function (element, text) {
    Array.prototype.forEach.call(text, function (char) {
        element.value += char;
        element.dispatchEvent(new KeyboardEvent("keydown"));
        element.dispatchEvent(new KeyboardEvent("keypress"));
        element.dispatchEvent(new KeyboardEvent("input"));
        element.dispatchEvent(new KeyboardEvent("keyup"));
    });
}).apply(null, arguments);

Which you then call using the JavascriptExecutor:
((JavascriptExecutor) driver).executeScript(JS_CODE, element, text);

The snippet works on elements with a writable .value property, it could be extended to support contenteditable elements.
Note that the fields of the events are set to their defaults, including key codes and such, see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent Also you might have to add additional events to be triggered to even better simulate user input.
Comment: I was managed to do it like so -> https://stackoverflow.com/a/60485967/395804
Comment: "it could be extended to support **contenteditable** elements." - How?
Comment: @Gal Bracha: TBH, I cannot remember anymore, I guess changing the `innerHTML` should suffice but one might think about line-breaks (e.g. doing ``s unless the `white-space` CSS property is set to certain non-standard values) and be smart about wrapping elements (e.g. ``). Should you have a specific use case where this is a problem then it might be worth its own question IMHO.
Answer: I have a similar problem and I solve it in this way.
First, you should add any text to this div with JavascriptExecutor , and then clear this text and use selenium's sendKeys method
WebElement inputDiv = driver.findElement(By.xpath("your_path_to_div"));
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("document.querySelector('your_selector_to_div').innerText='aaa'");

inputDiv.clear();
inputDiv.sendKeys(subject);


Defining destination NAT in fargate container

Question: How can I define a destination nat in a fargate container? If I was creating containers under EC2 instances I would use iptables and create a dnat entry. Can that be done in a fargate container and if so, how?
I have not been able to figure out how to define iptables in a fargate container yet. I cannot use a Net Gateway because I am not trying to do a NAT to an internal address, but I need to define a destination NAT.
Comment: Well, you can't do the trick with Fargate. You simply do not controll the underlying resources. Awsvpc mode only. From networking perspective, a Fargate container is like a EC2 Instances. Can you set a dNat rule in a Subnet level for an Instance?
Answer: I don't think it can be done. I've tried before and didn't find any feature available to do that.
What I ended up doing was adding a Route53 private hosted zone to the VPC for the custom DNS resolution within the VPC.
Comment: That would work, but the networking that needs to be done is all via IP address. Trying to interface with an old Centera protocol that allows me to open using a DNS name, but then gets a redirect using a IP address and cannot intercept the redirect to provide a DNS name for the redirect. The only way I have been able to do this through a DNAT and under EC2 this would be simple.
Answer: You should use a NLB, set up a listener on a port you need, attach a target groupt to the listener. Optionally, put a Global Accelerator with single static IP in front of the NLB and you will get exactly the same networking as you want.
Comment: Will this work for UDP traffic or only TCP? The Centera protocol requires TCP and UDP. It also requires 6 IPs to be mapped.   I have to map IP x.x.x.x to y.y.y.y outbound for both UDP and TCP on a single network port. i have to do this with 6 IPs. The x.x.x.x is not part of my subnet or the subnet that fargate is sitting in. With iptables DNAT, I can do the conversion of x.x.x.x to y.y.y.y within the TCP stack
Comment: UDP and TCP would work on NLB.
Answer: Alright, what about a NAT instance. Once installed you get a full controll on the networning, TCP and UDP, DNAT and SNAT, literally any scenario is possible now. You are able to forward trafic to fargate.


Multiple file upload with okhttp3

Question: I've been struggling with this code for many hours. Can someone guide me where i missed? If upload one file, it's successful. When i change code to multiple file, it will error.
Here is my okhttp JSONParser.java
public static JSONObject uploadImage(ArrayList<String> photoCaptions) {

    try {

            String photoUrl = photoCaptions.get(0);
            String photoUrl2 = photoCaptions.get(1);
            String photoUrl3 = photoCaptions.get(2);

            File sourceFile = new File(photoUrl);
            File sourceFile2 = new File(photoUrl2);
            File sourceFile3 = new File(photoUrl3);

            final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/*");

            String filename = photoUrl.substring(photoUrl.lastIndexOf("/")+1);
            String filename2 = photoUrl2.substring(photoUrl2.lastIndexOf("/")+1);
            String filename3 = photoUrl2.substring(photoUrl2.lastIndexOf("/")+1);

            Log.d("TAG", "File...::::" + sourceFile.getName() + " : "+ photoUrl + " - " + sourceFile.exists());

        MultipartBody.Builder multipartBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);

        RequestBody requestBody = multipartBuilder
                .setType(MultipartBody.FORM)
                .addFormDataPart("image1", filename, RequestBody.create(MEDIA_TYPE_PNG, sourceFile))
                .addFormDataPart("image2", filename2, RequestBody.create(MEDIA_TYPE_PNG, sourceFile2))
                .addFormDataPart("image3", filename3, RequestBody.create(MEDIA_TYPE_PNG, sourceFile3))

                .build();

        Request request = new Request.Builder()
                .url(URL_UPLOAD_IMAGE)
                .post(requestBody)
                .build();

        OkHttpClient client = new OkHttpClient();
        Response response = client.newCall(request).execute();
        String res = response.body().string();
        Log.e("TAG", "Error: " + res);
        return new JSONObject(res);

    } catch (UnknownHostException | UnsupportedEncodingException e) {
        Log.e("TAG", "Error: " + e.getLocalizedMessage());
    } catch (Exception e) {
        Log.e("TAG", "Other Error: " + e.getLocalizedMessage());
    }
    return null;
}

Here is the error
02-15 02:15:20.425 27709-27821/com.domain.appgallery E/TAG: Other Error: End of input at character 0 of

Here is my PHP code
<?php

//importing dbDetails file
require_once 'dbDetails.php';

//this is our upload folder
$upload_path = 'uploads/';

//Getting the server ip
$server_ip = gethostbyname(gethostname());

//creating the upload url
$upload_url = 'http://'.$server_ip.'/gallery/'.$upload_path;

//response array
$response = array();

if($_SERVER['REQUEST_METHOD']=='POST'){

    //checking the required parameters from the request
    if(isset($_FILES['image']['name'])){

        //connecting to the database
        $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...');

        //getting name from the request
        //$name = $_POST['name'];

        //getting file info from the request
        $fileinfo = pathinfo($_FILES['image']['name']);

        //getting the file extension
        $extension = $fileinfo['extension'];

        //file url to store in the database
        $file_url = $upload_url . getFileName() . '.' . $extension;

        //file path to upload in the server
        $file_path = $upload_path . getFileName() . '.'. $extension;

        //trying to save the file in the directory
        try{
            //saving the file
            move_uploaded_file($_FILES['image']['tmp_name'],$file_path);
            $sql = "INSERT INTO `photos` (`id`, `url`, `name`) VALUES (NULL, '$file_url', NULL);";

            //adding the path and name to database
            if(mysqli_query($con,$sql)){

                //filling response array with values
                $response['error'] = false;
                $response['url'] = $file_url;
                //$response['name'] = $name;
                $response['result'] = 'success';

            }
        //if some error occurred
        }catch(Exception $e){
            $response['error']=true;
            $response['message']=$e->getMessage();
        }
        //displaying the response
        echo json_encode($response);

        //closing the connection
        mysqli_close($con);
    }else{
        $response['error']=true;
        $response['message']='Please choose a file';
    }
}

/*
    We are generating the file name
    so this method will return a file name for the image to be upload
*/
function getFileName(){
    $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...');
    $sql = "SELECT max(id) as id FROM photos";
    $result = mysqli_fetch_array(mysqli_query($con,$sql));

    mysqli_close($con);
    if($result['id']==null)
        return 1;
    else
        return ++$result['id'];
}

Answer: This is my bad.
I haven't look at php code at all.
Added for loop to handle images.
And alter some type in android.
Now it works.

Multiple file upload with okhttp3


Generic Handlers (.ashx) intellisense issue on Visual Studio 2010

Question: I am trying to expand and collapse methods and other things on an ashx file like any other code behind file. When I do tools > options > text editor and adding ashx as an extention of visual studio c#, everything seems ok at the beginning. I can expand and collapse the methods also see the properties and methods at the top of the file. But then I lost most of intellisense. I cant reach my userdefined objects and methods.
Similar Issues that I have found did not help me to solve this problem
Visual Studio ASP.Net expand and collapse issue in ashx generic handlers
i can't add #region to .ashx in visual studio 2010
Answer: Ran in to this same annoyance.
To take @brichins solution/reference a little further,
instead of using inheritance in your ashx just reference the class in the AppCode folder directly.
the ashx file would only contain the following
<%@ WebHandler Language="C#" Class="MyHandler" %>

Then create that class/MyHandler.cs file in the AppCode folder
using System;
using System.Web;

public class MyHandler : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World");
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

Use namespaces to avoid class name conflicts if needed.
Answer: Had the same issue - this answer (to the first question you mentioned, but posted after you asked) seems to be the best option for me.
To summarize: create a separate class in a (preferably dedicated) .cs file to use as "code-behind", do all the work there (including implementing IHttpHandler) and have your actual handler in the .ashx just inherit it without doing anything else:

public class MyHandler : MyIHttpHandlerCodeBehindClass{}

This gives you full code-folding and IntelliSense for your handler class without the issues you mentioned. Only downside is an additional file, but to me it's worth it.
Answer: I changed most of my ashx to aspx, just so it can have CodeFile (separate .cs file).
Comment: ASPX could call masterpages and it has additional overhead which is not wanted...


More than 2 orientations on exotic manifolds?

Question: If I understood the exotic manifolds correctly we have a following situation.
Say we have a manifold M with regular atlases $\{(U_i,\phi_i)\}_\alpha$, that are diffeomorphic to each other, and some exotic atlases $\{(\tilde{U}_i,\tilde{\phi}_i)\}_\beta$ that are diffeomorphic to each other, but not to regular atlases. Such that for $U_i\cap \tilde{U}_j$ the transformation map $\tilde{\phi}_i\circ \phi_j^{-1}$ is not a diffeomorphism.
There is a theorem, that states that a connected orientable manifold has only two orientations. Then we know that regular atlases must define two equivalence classes of orientations.
Take, for example this two definitions from Loring W. Tu: An Introduction to Manifolds:
Definition 21.9:
An atlas on M is said to be oriented if for any two overlapping charts $(U,\vec{x})$ and $(V,\vec{y})$, the Jacobian determinant $det[\partial y^i/\partial x^j]$ is everywhere positive on intersection.
Definition 21.11: Two oriented atlases $\{(U_i,\phi_i)\}$, $\{(V_i,\psi_i)\}$ on a manifold M are said to be equivalent if transformation functions $ \phi_i\circ \psi_k^{-1} $ have positive Jacobian determinants for all i,k.
In the last definition we know that the transformation map and its Jacobian is well defined for regular atlases.
Now we want to know the orientation of an exotic atlas. But for the transformation map
$\tilde{\phi}_i\circ \phi_j^{-1}$ the Jacobian can be undefined. This means that we have 2 equiv. classes of orientations on regular atlases, and 2 other classes on exotic atlases, and we cannot (in general) compare these pairs.
Does this mean: # of orientations = 2*(# of non-diffeomorphic smooth structures)?
For example, $S^7$ has 28 non-diffeomorphic smooth structures. Then should it have 56 orientations?
Answer: An orientation on a smooth manifold is a continuous orientation of its tangent spaces, so it depends of its smooth structure: you can't compare the orientations between your regular manifold and your exotic one, even if they have the same topology.
Comment: So by the definition of a smooth manifold it is a topological manifold with a maximal atlas. Exotic and regular atlases are in different maximal atlases so they are different manifolds. Did I get your right?
Comment: Yes, this is exact!
Comment: Orientation is depend on topological manifold, as a continuous choice of generator of $H^n(M, M-\{p\})$. I don't see how it depends on the smooth structure.


error: index.js: [BABEL]: Cannot find module 'node:fs' in react-native

Question: I am trying to run react native app on Andriod but I am getting this error   presets: ['module:metro-react-native-babel-preset'],, Could someone please help me to how to resolve this issue.
const {getDefaultConfig} = require('metro-config');
module.exports = {
  transformer: {
    getTransformOptions: async () => ({
      transform: {
        experimentalImportSupport: false,
        inlineRequires: true,
      },
    }),
  },
};
module.exports = (async () => {
  const {
    resolver: {sourceExts, assetExts},
  } = await getDefaultConfig();
  return {
    transformer: {
      babelTransformerPath: require.resolve('react-native-svg-transformer'),
    },
    resolver: {
      assetExts: assetExts.filter(ext => ext !== 'svg'),
      sourceExts: [...sourceExts, 'svg'],
    },
  };
})();

Answer:
Please check metro-react-native-babel-preset dependency was
installed in your package.json file.
If not, install it using this command: npm i metro-react-native-babel-  preset --save-dev

Please check babel.config.js file
There should be this code:

module.exports = {

 presets: ['module:metro-react-native-babel-preset'],

 ....

}

Answer: Just update node to the latest version
using sudo n latest

Comment: And how did you came to the conclusion it's not the latest version? And why does your suggestion solve this problem?


Integrating $\int_0^{\pi/2}\frac{x^2}{\sin x}dx$

Question: I have trouble evaluating $$I=\int_0^{\pi/2}\dfrac{x^2}{\sin x}dx$$ What I did was I applied integration by parts where $u=x^2$ and $dv=\csc x dx$, thereby obtaining $$I=-2\int_0^{\pi/2}x\ln\left(\tan\dfrac{x}{2}\right)dx$$
However, I don't know how to solve this integral. Any ideas are welcome.
Comment: Note that $\ln \Big( \tan{\frac{x}{2}} \Big) = \ln \Big( \sin{\frac{x}{2}} \Big) -  \ln \Big( \cos{\frac{x}{2}} \Big)$. [This question](https://math.stackexchange.com/questions/3572727/integral-int-0-frac-pi4x-ln-cos-xdx) is the second integral (after substitution); I assume the first is similar.
Comment: Integral calculator gives results in terms of the polylog function so... probably not pretty. https://www.integral-calculator.com/#expr=x%5E2%2Fsin%28x%29&lbound=0&ubound=pi%2F2
Comment: https://math.stackexchange.com/questions/2714146/evaluate-int-0-frac-pi2-fracx2-sin-xdx?noredirect=1
Comment: $\ln(\tan x)=-2\sum_{n=0}^\infty\frac{\cos((4n+2)x)}{2n+1}$
Answer: Let $t= \tan\frac{x}{2} $ \begin{align}J=&\int_0^{\pi/2}x\ln\left(\tan\dfrac{x}{2}\right)dx\\
=&\ 4\int_0^1 \frac{\tan^{-1}t\ln t}{1+t^2}\ \overset{t\to 1/t}{dt}
=4 \int_1^\infty \frac{(\frac\pi2-\tan^{-1}t)(-\ln t)}{1+t^2}\ dt\\
=&-\pi\int_1^\infty \frac{\ln t}{1+t^2}dt+ 2 \int_0^\infty \frac{\tan^{-1}t\ln t}{1+t^2}dt=-\pi G+2K
\end{align}
where
\begin{align}
K=&\int_0^\infty \frac{\tan^{-1}t\ln t}{1+t^2} dt \\
=& \int_0^\infty \frac{\ln t}{1+t^2} \int_0^1 \frac t{1+ t^2 y^2}dy
\overset{t^2\to t}{dt}\\
=& \ \frac14\int_0^1 \int_0^\infty \frac{\ln t}{(1+t)(1+ t y^2)} \overset{t\to 1/(y^2t)}{dt ~dy}\\
=& \ \frac14\int_0^1 \int_0^\infty \frac{-\ln t -2\ln y}{(1+t)(1+ t y^2)}dt ~dy \\
=& \ \frac14\int_0^1 \int_0^\infty \frac{-\ln y}{(1+t)(1+ t y^2)}dt ~dy\\
 =& \ \frac12\int_0^1 \frac{\ln^2 y}{1-y^2}dy
= \frac12\cdot \frac74\zeta(3)=\frac 78\zeta(3)
\end{align}
Thus $J= -\pi G +\frac74\zeta(3)$ and
$$I=\int_0^{\pi/2}\dfrac{x^2}{\sin x}\ dx =-2J= 2\pi G -\frac72\zeta(3)$$
Answer: You could also make a series using
$$\frac 1 {\sin(x)}=\frac 1x+2\sum_{n=0}^\infty (-1)^n \,\frac{\left(2^{2 n+1}-1\right) B_{2 n+2}}{(2 n+2)!}x^{2n+1}$$ leading to
$$\int \frac {x^2} {\sin(x)}\,dx=\frac 12x^2+\sum_{n=0}^\infty (-1)^n \,\frac{\left(2^{2 n+1}-1\right) B_{2 n+2}}{(n+2) (2 n+2)!}\,x^{2n+4}$$ The definite integral converges very fast since, asymptotically, the ratio of two consecutive terms tends to  $\frac 14$. The infinite summation leads to the result already given by @Quanto
$$I=\int_0^{\frac \pi 2}\dfrac{x^2}{\sin (x)}dx=2 \pi  C-\frac{7 }{2}\zeta (3)=1.54798$$
If you compute the partial sums, you get this number adding $6$ terms only.
Using the above series, you can approximate very accurtely compute $\forall k>0$
$$I_k=\int_0^{\frac \pi 2}\dfrac{x^{k+1}}{\sin (x)}dx $$
For the fun of using my favored $1400^+$ years old approximation of the sine function
$$\int_0^{\frac \pi 2}\dfrac{x^2}{\sin (x)}dx \sim  \int_0^{\frac \pi 2} \frac{x \left(5 \pi ^2-4 (\pi -x) x\right)}{16 (\pi -x)}\,dx=\frac{30 \log (2)-16}{96} \pi ^3 =1.54851$$


How to find the variance and mean of a min function

Question: Problem
Let $Y_1, Y_2, . . . , Y_n$ be i.i.d. with p.d.f.
$f(y; θ) = \frac1θ e^\frac{-y}θ , y>0 $
Consider two estimators for the parameter θ,
$\hat θ_1 = n \min_{i=1,2,..,n} Y_i $
$\hat θ_2 = \frac{Y_1 + Y_2 + . . . + Y_n}n$
Show that $\hat θ_1$  is indeed an unbiased estimator, and find its efficiency relative to $\hat θ_2$
My progress
The expected value of $f$ is $θ$ because it is an exponetial distribution  with the rate parameter of $\frac1θ$
Now I need to find the the variance and mean of $\hat θ_1$ but I have no idea how to do that because we have a min function if someone could explain that to me.
For $\hat θ_2$ I can write it a $Y_1$ which is just $f$ because we are adding $n$ $Y$ components and dividing by $n$. So the mean is $θ$ and variance is ${θ^2}$
Answer:
Now I need to find the the variance and mean of $\hat{\theta}_1$ but I have no idea how to do that because we have a min function if someone could explain that to me.

The CDF of the min of $n$ iid rv is
$$F_{min}=1-(1-F)^n$$
Thus in your case, setting $U=min(\mathbf{y})$
$$F_U(u)=1-e^{-\frac{yn}{\theta}}$$
and consequently, derivating,
$$f_U(u)=\frac{n}{\theta}e^{-\frac{yn}{\theta}}$$
Now you have all the tools to proceed by yourself

$\hat{\theta}_2$ is the sample mean...thus its mean is $\theta$ the same of the population's one but its variance is $\frac{\theta^2}{n}$
In fact:
$$\mathbb{V}\Bigg[\frac{1}{n}\Sigma_i Y_i\Bigg]=\frac{1}{n^2}n\theta^2$$
(The expectation is a linear operator but the variance is not. It's a quadratic operator)


Expected Value of Random Process when allowed to retry

Question: Let's say there is a random process that has 36 possible outcomes.
33 of these outcomes give you a value of 50
and rest three give a value of 60, 75 and 100.
What is the expected value of this process, when we are allowed to retry it once. And the same outcome cannot appear again on retrying.
So the average value of the process without retrying is 52.36. But I am not able to calculate what would the expected value be if we can retry.
For example, if we get 50 on the first time, and we choose to retry then the possible outcomes is reduced to 35, with the expected value being
((50*32) + 60 + 75 + 100 )/35 = 52.42
And considering that in the first place we can only get 50 33/36 times means the expected value over the entire process should be
(33*52.42 + 60 + 75 + 100)/36 = 54.57 ?
Comment: When the result in the first run is $50$, shouldn't the possible values in the second run be only $60, 75$ and $100$?
Comment: When we retry does the second-try outcome is taken? Or greater from those 2 tries? Do we have a strategy, e.g. when we got >50 then we won't retry?
Comment: The reason that I believe we should retry only when we get 50 is because that is the only value less than the expected value ~ 52. If we get 60, 75 or 100 we would not want to retry as it is greater than the expected value.
Answer: Presumably if you get more than $50$ on the first try you keep it.  You have $\frac 1{36}$ chance of getting $60$ on the first try and $\frac {33}{36}\cdot \frac 1{35}$ chance of getting $60$ on the second try because you have to get a $50$ on the first to get $60$ on the second.  The chance of getting $60$ is then $\frac 1{36}+\frac {33}{36}\cdot \frac 1{35}=\frac {68}{1260}$.  The chance of getting $75$ or $100$ is the same.  The chance you are stuck with $50$ is then $1-3\cdot \frac {68}{1260}=\frac {1056}{1260}$  Now we can calculate the expected value as you have the chance of each outcome.  It is $\frac {1056}{1260}\cdot 50+\frac {68}{1260}(60+75+100)=\frac{68780}{1280}\approx 54.5873$
You can also calculate the chance you end with $50$ by noting you have to get $50$ twice, so it is $\frac {33}{36} \cdot \frac {32}{35}=\frac {1056}{1260}$.  Of course it agrees.
Answer: From your equations, I interpret the situation as: (a) if you get $>50$ the first time you won't retry, and (b) if you get $50$ the first time you retry and your overall result is the second-try result (which necessarily $\ge$ your first result of $50$).
First of all, is my interpretation correct?
If so, your method is entirely valid.  However you have some rounding errors.
$$((50 \times 32) + 60 + 75 + 100 )/35 = \color{red}{367 \over 7} = 52.42\color{red}{8571}... \approx 52.4\color{red}{3}$$
$$(33\times \color{red}{367 \over 7} + 60 + 75 + 100)/36 = \color{red}{3439 \over 63} = 54.5\color{red}{87301}...$$
So as you can see, after fixing the rounding issues your answer agrees with the alternate method in the answer by @RossMillikan


dbinom(x, N, phat) in R returns "NaNs produced". How can I solve this?

Question: Hope I find you well, and happy new year!
I have a little problem with R. I just started using it for university and I'm trying to find the binomial distribution law using the CL column of the crabs table from the MASS library. Here's what I wrote until now:
x<-c(crabs$CL)
N<-max(x)
n<-length(x)
xbar<-mean(x)
phat<-xbar/N
pteor<-dbinom(x,N,phat)

After trying to executethe last line, im getting the following error message:

Warning message:
In dbinom(x, N, phat) : NaNs produced

Could you tell me, please, what I did wrong?
Thank you! Have a nice day!
P.S.: This is an assignment we had for university, and I am doing the requirements listed by her step-by-step. Since we have done, and we'll finish this semester online because of COVID-19, the teacher hasn't put in much effort in explaining to us what to do exactly, so what I'm trying to do doesn't make much sense for me either.
The steps are:

choose a column,
find the N of the binomial law,
estimate the parameter p (assuming that the random variable X associated with data follows the following law: Binomial Bi(N, p) with N the value of point 2),
make a distribution test for the binomial law,
find a 95% confidence region for the parameter p, so the confidence region will be relative to the parameter p.

So far we have:
N=47.6
phat=0.6744853
xbar=32.1055

Comment: The binomial distribution applies to integer data. In the ```crabs``` dataset, you could code the ```sp``` or ```sex``` columns as binary variables (i.e. choose one value to be 1 and the other to be 0), but the other columns are continuous values and so the binomial distribution does not apply. So, your issue may just be the choice of column (or dataset).
Comment: agreeing with everyone else: `CL` is "carapace length". It doesn't make any sense to model it as a binomial distribution
Comment: `crabs$CL` does not contain integers so what you're doing does not make much sense.
Comment: $N$ should have been integer
Comment: is any of x, N or phat NaN?
Comment: We cannot explain what went "wrong" until you describe what you think "right" might be.  Indeed, even when the data `crabs$CL` might consist of integers, this calculation has little meaning--but that doesn't tell us much about what you intended this calculation to do.
Comment: Alright, I added a few more details to explain my confusion a bit better.
Answer: Partially answered in comments:

Agreeing with everyone else: CL is "carapace length". It doesn't
make any sense to model it as a binomial distribution

Ben Bolker


How to read data from datagrid in specific date range using java and selenium webdriver

Question: Scenario : for example want to fetch Column name: Owner Name | Shared Held | Date from data grid of website: nasdaq.com/symbol/ctsh/institutional-holdings In date range say 01/01/2014 to 31/12/2014 or 01/01/2013to 31/12/2013 and want put it into excel sheet. please guide me on this.
==============
Code I designed this code to read data from data grid and all pages now am looking for solution for above mention Scenario.
 public class NasdaqReadTabaleData {

    // extends Nasdaqe_InvesterListData{
public static WebDriver driver = new FirefoxDriver();

@Test
public void NasdaqeTable() throws Exception {

    driver.get("http://www.nasdaq.com/symbol");
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
   /* for (int i = 1; i < s.getRows(); i++)
    {
    //Read data from excel sheet
    String s1 = s.getCell(0,i).getContents();*/
    driver.findElement(By.id("stock-search-text")).clear();
    driver.findElement(By.id("stock-search-text")).sendKeys("CTSH");
    driver.findElement(By.id("stock-search-submit")).click();

    JavascriptExecutor jsedown = (JavascriptExecutor)driver;
    jsedown.executeScript("scroll(0, 250)");

    //Click on holdings link.
    driver.findElement(By.id("holdingslink")).click();
    System.out.println("Action should counduct once  ");
    Thread.sleep(3000);

    try
    {
        JavascriptExecutor jsedownsmall = (JavascriptExecutor)driver;
        jsedownsmall.executeScript("scroll(0, 950)");

        WebElement Webtable =driver.findElement(By.id("secfilingContainer"));
        if(Webtable.isDisplayed()){

            // Replace TableID with Actual Table ID or Xpath
        List<WebElement> TotalRowCount=Webtable.findElements(By.tagName("tr"));
        System.out.println("No. of Rows in the WebTable: "+TotalRowCount.size());

        // Now we will Iterate the Table and print the Values
            int RowIndex=1;
            for(WebElement rowElement:TotalRowCount)
            {
                  List<WebElement> TotalColumnCount=rowElement.findElements(By.xpath("td[3]"));
                  int ColumnIndex=1;
                  for(WebElement colElement:TotalColumnCount)
                  {
                       System.out.println("Row "+RowIndex+" Column "+ColumnIndex+" Data "+colElement.getText());
                       ColumnIndex=ColumnIndex+1;

                   }
                  RowIndex=RowIndex+1;
            }

            // Paging functionality For All Paages

        // locator for last page button
        List<WebElement> lastPage = driver.findElements(By.xpath("html/body/div[4]/div[2]/div[9]/form/div[15]/div/ul/ul/li"));
        System.out.println("Paging functionality");

        for(int i=1; i<=(lastPage.size()); i++)
            {
            if (lastPage.size()>=0){
                //locator for next page button
                List<WebElement> nextPage = driver.findElements(By.id("quotes_content_left_lb_NextPage"));
                if(nextPage.size() >= 1){
                    Thread.sleep(2000);
                    nextPage.get(0).click();

                    JavascriptExecutor jsedownsmall1 = (JavascriptExecutor)driver;
                    jsedownsmall1.executeScript("scroll(0, 950)");

                    WebElement Webtable1 =driver.findElement(By.id("secfilingContainer"));

                    if(Webtable1.isDisplayed()){
                        List<WebElement> TotalRowCount1=Webtable1.findElements(By.tagName("tr"));

                            System.out.println("No. of Rows in the WebTable: "+TotalRowCount1.size());

                            // Now we will Iterate the Table and print the Values
                            int RowIndex1=1;
                            for(WebElement rowElement:TotalRowCount1)
                            {
                                List<WebElement> TotalColumnCount=rowElement.findElements(By.xpath("td[3]"));
                                int ColumnIndex=1;
                                for(WebElement colElement:TotalColumnCount)
                                {
                                    //System.out.println("Current Page ::"+lastPage);
                                    System.out.println("Row "+RowIndex1+" Column "+ColumnIndex+" Data "+colElement.getText());
                                    ColumnIndex=ColumnIndex+1;

                                    WebElement excelData[][] = new WebElement[1][10];
                                    excelData[0][0] = colElement;

                                }
                                RowIndex1=RowIndex1+1;
                            }
                    }
                }else lastPage.get(0).click();
            }
            }
        }
        }
    catch(Exception e){
        e.printStackTrace();
        }
    }
}

Comment: You will not get full ready made code here , did you try by yourself? then please share your code with question and you will get help to correct that code according to your need.
Comment: Hi I added my code , please help me to achieve my scenario
Comment: Okay , now tell please that what error you are getting in that code?
Answer: am trying below mention code to read data in date rang , but i think it is not proper .
@Test
     public void print_data() throws Exception{
         String startDate = "01/01/2014";
         String endDate = "09/30/2014";
String final_xpath = first_part+k+forth_part;
String Table_data = driver.findElement(By.xpath(final_xpath)).getText(); (Hear am reading three column Owner Name | Shared Held | Date )

if(Table_data.contains(startDate)||Table_data.contains(endDate)){ (Want to write logic pick data in date range 01/01/2014 to 31/12/2014)
System.out.print(Table_data1 +"  ");// to print on console
excelLog(i,Table_data2,Table_data3,Table_data4); // To print in excel sheet