Problemas ao dar Post em uma ViewModel para o Controller - Asp.Net Core 2 MVC

Question: Tenho uma ViewModel que utilizo para carregar dados de uma pessoa física ou jurídica. Ela contém algumas propriedades como PessoasNaturezas, dentre outras, que eu utilizo para carregar meus dropdownlists da minha view. O Problema está justamente entre minha view e meu método Create da minha Controller. Quando eu dou um Post, as propriedades da minha viewmodel ficam com NULL... Parece que, ao dar o Post, o sistema limpa e seta as propriedades que são do tipo IEnumerable para null. Como resolver isso????
OBS: Já postei um assunto parecido, mas o problema era na view Create quando eu criava uma viewmodel em branco. Eu não havia inserido um bloco de script javascript.. Por favor, desconsiderem aquele post, pois este é relacionado ao salvamento e está mais detalhado.
Quando a validação dos campos é acionada, os dropdownlists não carregam no Asp.net core MVC

 public class PessoaViewModel
    {
        [DisplayName("Código")]
        public int Id { get; set; }

        [DisplayName("Natureza")]
        [Required(ErrorMessage ="Escolha uma Natureza")]
        public PessoaNatureza PessoaNatureza { get; set; }
        [DisplayName("Natureza")]
        public string PessoaNaturezaDescricao { get; set; }
        [DisplayName("Naturezas")]
        public IEnumerable<SelectListItem> PessoasNaturezas { get; set; }

        public PessoaFisicaViewModel PessoaFisicaViewModel { get; set; }
        public PessoaJuridicaViewModel PessoaJuridicaViewModel { get; set; }
    }

@model SistemaComercial.Application.ViewModels.Pessoa.PessoaViewModel
@{
    ViewData["Title"] = "PessoaFisica";
}

            <input asp-for="PessoaFisicaViewModel.NomeCompleto" class="form-control" />

            <input asp-for="PessoaFisicaViewModel.Apelido" class="form-control" />

            <input asp-for="PessoaFisicaViewModel.DataNascimento" class="form-control" />

            <select asp-for="PessoaFisicaViewModel.Sexo" asp-items="Model.PessoaFisicaViewModel.Sexos" class="form-control">
                <option value="">-- SELECIONE --</option>
            </select>

            <select asp-for="PessoaFisicaViewModel.EstadoCivil" asp-items="Model.PessoaFisicaViewModel.EstadosCivis" class="form-control">
                <option value="">-- SELECIONE --</option>
            </select>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

@using SistemaComercial.Domain.ValueObjects
@model SistemaComercial.Application.ViewModels.Pessoa.PessoaViewModel
@{
    ViewData["Title"] = "Cadastrar Nova Pessoa";
}

Cadastrar nova Pessoa

    <form asp-action="Create">

            @* Replacing classic Validation Summary to Custom ViewComponent as TagHelper *@
            <vc:summary />

                            Dados Pessoais

                            Documentos

                            Endereços

                            Contatos

                                        <input asp-for="Id" class="form-control" disabled="disabled" />

                                        <select asp-for="PessoaNatureza" asp-items="Model.PessoasNaturezas" class="form-control">
                                            <option value="">--SELECIONE--</option>
                                        </select>

                                @if (Model.PessoaNatureza == PessoaNatureza.Fisica)
                                {
                                    @await Html.PartialAsync("_PessoaFisica")
                                }
                                else if (Model.PessoaNatureza == PessoaNatureza.Juridica)
                                {
                                    @await Html.PartialAsync("_PessoaJuridica")
                                }
                                else
                                {
                                    @await Html.PartialAsync("_PessoaFisica")
                                }

                    @*<input type="submit" value="Gravar" class="btn btn-success" />
                        Voltar à Lista*@

                    <button type="submit" class="btn btn-success"> Gravar</button>

                         Retornar à lista

    </form>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

[HttpPost]
        [Authorize(Policy = "CanWriteCustomerData")]
        [Route("pessoa-gerenciamento/cadastrar-novo")]
        [ValidateAntiForgeryToken]
        public IActionResult Create(PessoaViewModel pessoaViewModel)
        {
            if (!ModelState.IsValid) return View(pessoaViewModel);
            _pessoaAppService.RegisterPessoaFisica(pessoaViewModel);

            if (IsValidOperation())
                ViewBag.Sucesso = "Pessoa Cadastrada!";

            return View(pessoaViewModel);
        }

@model SistemaComercial.Application.ViewModels.Pessoa.PessoaViewModel
@{
    ViewData["Title"] = "PessoaJuridica";
}

            <input asp-for="PessoaJuridicaViewModel.RazaoSocial" class="form-control" />

            <input asp-for="PessoaJuridicaViewModel.NomeFantasia" class="form-control" />

            <input asp-for="PessoaJuridicaViewModel.DataAbertura" class="form-control" />

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Comment: Pode colocar o código da PartialView onde estão os combos?
Comment: Atualizei a postagem @Ricardo Pontual...
Comment: Você está usando asp-for="PessoaFisicaViewModel.Sexo" porém pela imagem que colocou, a propriedade que está null se chama "Sexos". Já verificou isto?
Comment: Aí me bateu a dúvida: Eu tenho duas propriedades na minha viewmodel: public Sexo Sexo {get; set;} e public iEnumerable Sexo {get; set;}... Uma uso para Label e a aoutra para o Dropdownlist..
Answer: Quando você posta a Model, só será postado o que foi associado aos elementos na View com nomes correspondentes às propriedades da sua Model.
No código abaixo:
<select asp-for="PessoaNatureza" asp-items="Model.PessoasNaturezas" class="form-control">
    <option value="">--SELECIONE--</option>
</select>

Quem está associado ao select é PessoaNatureza, e somente ele será postado, Model.PessoasNaturezas apenas foi utilizado para montar o select e não está associado a campo algum, por isso não será postado, dai chega vazio.
Nesses casos, você precisa carregar novamente essas listas no seu método Create antes de retornar para a View. Uma solução é fazer isso no construtor da sua Model. Outra solução, bem pior, seria armazenar Model.PessoasNaturezas num campo escondido, por exemplo <input type='hidden' name='Model.PessoasNaturezas' />
Comment: @Ricado Pontual muito obrigado pela dica!!! Funcionou 100% Criei um construtor para a viewmodel e "setei" os carregamentos...  public PessoaViewModel()
        {
            PessoasNaturezas = ExtensaoDeEnumerador.EnumParaSelectListGenerico("U", PessoaNatureza.ToString()).OrderBy(x => x.Text);
        }


Anyone recommend a program to print multiple HTML files at once for end users?

Question: I have some clients with multiple html files in folders that are occasionally updated & printed. They would like to be able to print them all at once without having to open each one.
I typically do this with a quick command for myself, but I'm unaware of any freeware to do this. After a google search, I'm not finding one, so I'm hoping someone can help. I'd rather not use a script to do this for various security/ease of use/familiarity reasons, I'd rather be able to just point to a simple program they can download and use on their windows desktops. Anyone know of one or some other easy solution to do this? Maybe I'm overlooking the obvious.

If anyone's curious, this is what I do for myself (not for my clients):
for %h in (*.html) do type "%h" >> all.htm

then open all.htm & print.
If I need a page break on each doc, I just search and replace in all.htm  with

.
It's quick & simple, but too unfamiliar for them.
Thanks!
Comment: +1: Nice command prompt trick!
Answer: By selecting the web pages to print, right-clicking and selecting Print from the context menu, I was able to print multiple documents to the printer, each starting on a new page.  The documents were sent to my machine's default printer, and a separate print dialog box was generated for each web page.  In that respect, the drag-and-drop option is probably better.
If the print command from the context menu is failing to work you, you may verify what application is registered as the default print command for that document type.
On my machine (Windows Server 2003) I go to Tools | Folder Options | File Types tab and scroll in the list to the file extension I am attempting to print (in my case HTM) and select the Advanced button which opens an Edit File Type dialog.  From there, I click the Print entry in the Actions: list and click the Edit... button.
In my case, the application that prints web pages is msohtmed.  The specific settings for my Print command are as follows:
Action:
&Print

Application used to perform action:
"C:\Program Files\Microsoft Office\Office12\msohtmed.exe" /p %1

Use DDE: Checked

DDE Message:
[blank]

Application:
msohtmed

DDE Application Not Running:
[blank]

Topic:
System

This information directs default printing of HTM documents to be routed through a light-weight editor that is a part of MS Office 2007.  If you installed other HTML editors and indicate that they should become the default handler of files with the HTM extension, then it is possible that this application takes over default printing duties as well.  This dialog box will show you exactly which application you need to blame/fix in order to get your printing from a context menu working again.
Best of luck.
Comment: +1 very informative and helpful. it's what my comment to pjz was getting at, but i stopped exploring b/c the basic process failed on multiple computers with different default "open" handlers (IE vs. Firefox vs. Chrome). unfortunately, i have the EXACT same "edit" settings as you except Office11 vs Office12. i'll check on a few other computers later today and see what i find. thanks for confirming that it's possible!
Answer: Isn't windows the land of drag and drop? what if they drag and drop the folder onto the printer?
Comment: I tried this before on a couple different computers, it does ask me if I want to print multiple files at once. I confirm but then nothing. I also tried selecting several then right click & print but no luck. I guess the default behavior for this action would be to open up the file with it's default extension handler and run the print command, but the default program would have to support this - which may be some do and some don't. Anyway, thanks, but no luck.


How to calculate $\int_0^\infty \frac{1-\cos(x)}{x^2e^x}dx$ (it beats Maxima)?

Question: This is an integration theory practice exam question: Show that
$$\int_0^\infty \frac{1-\cos(x)}{x^2e^x} d\lambda (x)= \frac\pi4-\frac12\ln(2).$$
Hint: You may use without proof that
$$\frac \pi 4=\sum_{n=0}^\infty \frac{(-1)^n}{2n+1}, \quad \ln(2)=\sum_{n=0}^\infty \frac{(-1)^n}{n+1} \quad\text{and}\quad \int_0^\infty x^ne^{-x}dx = n!.$$
I thought it might be a good idea to use the exponential identity of $\cos(x)$, but that seemed to make the situation worse because it introduces complex numbers. Then looking at the hint I thought it might be worth it to insert the power series of $e$ and $\cos$ directly, but (because of the $1-$ term) those power series were "incompatible", nothing seemed to simplify which is always a bad sign.
The first part of this question showed that term by term integration would be justified.
Am I missing some steps before introducing the power series? Or can we simplify the power series expressions somehow?
Comment: you may use the Taylor expansion of cos $\cos(x) =1-\frac{x^2}{2!}+\frac{x^4}{4!}+...$, then simplify expression and integrate it with $\frac{1}{e^x}=e^{-x}$ term by term
Comment: What is $\lambda$?
Comment: @J.G. the Lebesgue measure
Answer: Let $$I(a)=\int^\infty_0\frac{1-\cos ax}{x^2}\,e^{-x}\,dx.$$ Then, $$I'(a)=\int^\infty_0\frac{\sin ax}{x}\,e^{-x}\,dx$$ and $$I''(a)=\int^\infty_0\cos ax\,e^{-x}\,dx=\frac1{1+a^2}.$$ Differentiating under the integral sign is justified, because the resulting integrals are absolutely convergent. The last integral can be evaluated, integrating by parts twice. Since $I'(0)=I(0)=0,$ we have $$I'(a)=\int^a_0 \frac1{1+t^2}\,dt=\arctan a,$$ and $$I(a)=\int^a_0 \arctan x\,dx=a\,\arctan a -\frac12\,\ln(1+a^2),$$ so the original integral is $$I(1)=\arctan 1-\frac12\,\ln 2=\frac\pi4-\frac12\,\ln 2.$$
Comment: @Martin Argerami Imho, it answers the question "Am I missing some steps before introducing the power series?" ;-)
Comment: I was going to take this route myself but you already beat me to it. The occurrence of log suggested to me a nicer analytic answer and sure enough. Great work! Strong early contribution to MSE!
Comment: This is very nice, but it doesn't really  answer the question.
Comment: Darn, as i thought i need to differentiate twice (i have a similar integral)
Answer: Use the Taylor series for the cosine, so your integral is$$\sum_{n\ge0}\tfrac{(-1)^n}{(2n+2)!}\int_0^\infty x^{2n}e^{-x}d\lambda(x)=\sum_n\tfrac{(-1)^n}{(2n+1)(2n+2)}=\sum_n\left(\tfrac{(-1)^n}{2n+1}+\tfrac{(-1)^{n+1}}{2n+2}\right)=\tfrac{\pi}{4}-\tfrac12\ln2,$$where the linear combination of two alternating series is legal because the resulting alternating series still converges by the alternating series test.


Question on additivity of Riemann Integral .

Question: Given a Riemann integrable function , $f:[a,b] \rightarrow \mathbb{R}$ and a sequence ${b_k\to b}$  ( $b_k \in [a,b]$ ) is the following use of additivity of integrals correct ?  $\int_a^bf(x)dx=\int_a^{b_1}f(x)dx +\int_{b_1}^{b_2}f(x)dx+ \int_{b_2}^{b_3}f(x)dx +...+\int_{b_k}^{b_{k+1}}f(x)dx +...$   I realized this issue when I was giving an answer here : Is $\int_a^{b}f(x) dx = \lim_{k\rightarrow \infty } \int_a^{b_k}f(x)$?  Also, what happens if we talk about the same issue in terms of lebesgue integration ?
Answer: The definition of the Riemann integral ensures that if $f$ is Riemann integrable on the interval $[a,b]$ then it is also Riemann integrable on any subinterval. It also ensures that $f$ is bounded, so assume $|f(x)|\leq M$ for all $x\in[a,b]$. Then, for each $k$ we have
$$\int_a^b f(x)\ dx-\int_{b_k}^bf(x)\ dx = \int_a^{b_1}f(x)\ dx+\int_{b_1}^{b_2}f(x)\ dx+\cdots+\int_{b_{k-1}}^{b_k}f(x)\ dx$$
Now, we have $|\int_{b_k}^bf(x)\ dx| \leq (b-b_k)M \to 0$. Thus the sum on the right converges to $\int_a^b f(x)$, as desired.
The same result is true if $f$ is Lebesgue integrable:  set $f_k=\chi_{[a,b_k]}f$. Then
$$\int_a^b f_k(x)\ dx = \int_a^{b_k} f(x)\ dx =  \int_a^{b_1}f(x)\ dx+\int_{b_1}^{b_2}f(x)\ dx+\cdots+\int_{b_{k-1}}^{b_k}f(x)\ dx$$
The left side converges to $\int_a^b f(x)\ dx$ by the dominated convergence theorem, which proves the desired result.


Display MPAndroidChart PieChart horizontally

Question: Is there a chart that looks like PieChart and rather than circle, numbers should be displayed in horizontal bar?
In PieChart, we display numbers in Circle. But how can i display them in single bar(horizontal)?
Anybody can help here?
I need a horizontal chart for this PieChart

I tried updating my code to have horizontalbarchar and got below chart. But the values are showing wrong in the chart and also i dont want to show the other parameters which are marked in Red. Can someone help me here.
My Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.github.mikephil.charting.charts.HorizontalBarChart
        android:id="@+id/chart1"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="@android:color/white" />

</RelativeLayout>

My code:
  super.onCreate(savedInstanceState);
        setContentView(R.layout.horizontal_seekbar_layout);
        mChart = findViewById(R.id.chart1);

        ArrayList<BarEntry> values=new ArrayList<>();
        values.add(new BarEntry(0,new float[]{5,3,1}));

        BarDataSet set1=new BarDataSet(values,"Summary");
        //set1.setDrawIcons(false);
        set1.setStackLabels(new String[]{"Passed","Failed","Skipped"});
        ArrayList<Integer> colors=new ArrayList<Integer>();
        colors.add(Color.GREEN);
        colors.add(Color.RED);
        colors.add(Color.GRAY);
        set1.setColors(colors);
        set1.setValueFormatter(new DecValueFormatter());

        BarData data=new BarData(set1);
        mChart.setData(data);
       // mChart.setFitBars(true);
        mChart.invalidate();

My current chart i am getting:
Answer: It can be done using stacked bar chart of mp android chart. Please follow example below to do that:
ArrayList<BarEntry> barEntries = new ArrayList<BarEntry>();
    barEntries.add(new BarEntry(0, new float[]{2,4,5,3}));

    BarDataSet barDataSet = new BarDataSet(barEntries, "Stacked Bars");
    barDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
    barDataSet.setHighlightEnabled(true);
    barDataSet.setHighLightColor(Color.RED);
    barDataSet.setColors(getColors(4,Color.RED,Color.BLUE,Color.GREEN,Color.CYAN));
    barDataSet.setStackLabels(new String[]{"Bottom","Top","Left","Right"});

    BarData barData = new BarData(barDataSet);
    barData.setValueTextSize(defaultValueTextSize);
    barData.setValueTextColor(getColor("primaryDark"));

    barChart.setDrawValueAboveBar(false); // add this line to show values inside bars
    barChart.getAxisLeft().setAxisMinimum(0);
    barChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTH_SIDED);
    barChart.animateY(1000);
    barChart.setData(barData);

This is for vertical bar just use horizontal bar chart of this library and you are good to go with buddy. Happy Coding :)
Comment: I tried above said sample code and now endup with above picture. Can you please tell me, why in the chart wrong values are show. Ex. the green color portion should show 5, red 3 and grey 1. And also how to not show the one with red color marks in above chart? Also sharing the code which i tried. Thanks for your help in advance.
Comment: I edited the answer and commented to add the line... Add that line to your code.
Comment: I edited the answer and commented to add the line... Add that line to your code.
Comment: Thanks that worked. Initially i thought of array index problem in this line, values.add(new BarEntry(0,new float[]{5,3,1})); But your added line helped me. Is there a way that i can eliminate the extra lines shown(marked in Red) in my above bar chart?


How can I set the discrete graphs of these values without computer programs?

Question: How can I set the discrete graphs of these values without computer programs? (online)
I need to create a discrete graph of the following values.Without the computer, is it possible that I can do this?
I tried Wolfram Alpha, but it is impossible to do so because the number of values is so long.
Thank you..
EXAMPLE
I would like to set up a graph similar to the graphs of the following distribution functions:

$$\text {Plot 1}\left\{ 9,27,67,118,220,348,486,771,825,1214,1373,1633,2257,1906,2554,2557,2737,3353,2728,3572,2798,3278,3935,3040,3969,2675,3469,3713,2907,3630,2491,3269,2647,2733,3408,2315,3043,1931,2584,2710,2155,2789,1904,2566,2473,2331,3061,2134,2871,1939,2595,3186,2249,3031,1967,2575,2440,2253,2909,1827,2398,1549,1992,2595,1593,2098,1248,1661,1819,1347,1741,991,1320,792,964,1310,710,939,507,694,826,473,651,341,468,264,328,494,253,357,179,263,348,180,273,130,193,133,157,209,100,138,63,91,130,58,79,40,67,58,53,77,40,53,24,32,48,22,35,20,25,28,14,17,11,15,5,8,17,7,8,2,2,4,4,8,2,2,0,1,3,1,3,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,1,1\right\}$$
$$\text {Plot 2}\left\{ 10,34,90,176,350,577,871,1436,1657,2534,2966,3764,5358,4882,6698,6791,7702,9604,8231,10947,8918,10913,12958,10509,13828,9786,12794,13566,11358,14039,9970,13110,10714,11362,14112,9696,12748,8299,10977,11669,9297,11941,8009,10755,10446,9502,12403,8392,11276,7651,10182,12325,9126,12174,8067,10627,10042,9292,12137,7975,10516,6945,8760,11373,7282,9587,5943,7862,8529,6461,8474,5139,6852,4337,5341,6935,4055,5350,3019,4024,4776,3023,4058,2251,3039,1851,2247,3039,1720,2289,1249,1742,2273,1290,1830,987,1372,972,978,1372,767,1038,538,722,994,529,710,367,535,509,393,589,316,401,226,297,389,197,290,143,202,226,147,211,103,140,79,101,142,67,106,51,67,75,46,65,32,45,36,42,55,24,34,11,12,25,9,21,8,17,10,9,11,5,14,5,7,6,3,7,4,5,7,6,6,3,2,0,1,2,0,2,2,3,2,2,0,0,0,0,1,1,0,0,0,1,2,1,2,0,0,0,0,1,1,2 \right\}$$
$$\text {Plot 3}\left\{ 11,41,118,251,532,924,1500,2580,3164,5018,6108,8193,12030,11599,16410,16947,20329,25638,23361,31525,26494,33543,39633,33833,44866,33020,43543,45974,41030,50612,37388,49151,40472,44081,54221,38847,51156,33921,44680,48127,38710,48902,33436,44407,43373,39062,50116,34268,45652,30338,40610,47920,36278,48435,32356,42939,41366,37675,49334,33062,43626,29838,37507,48140,31771,42095,26739,35539,37571,29438,38388,24218,32092,21490,26087,33871,20799,27405,16238,21484,25225,16608,22120,12875,17174,10980,13179,17537,10097,13580,7732,10423,13393,7912,10700,6146,8242,6077,6224,8464,4728,6495,3578,4873,6457,3565,4909,2640,3644,3535,2742,3829,2090,2847,1587,2128,2914,1549,2116,1147,1600,1751,1134,1596,838,1190,645,836,1169,600,853,452,668,780,409,581,292,423,278,324,474,242,334,158,234,327,166,234,114,165,110,107,171,84,138,66,86,114,56,78,41,57,70,49,63,26,49,25,36,51,14,22,12,18,23,20,20,6,11,4,10,15,9,10,5,8,11,6,10,6,9,5,8,14,7,14,7,7,5,1,5,1,2,4,1,3,3,3,1,3,3,0,1,0,0,1,1,1,0,0,0,1\right\}$$
Comment: a) What does it mean to *set* a graph? b) What graph(s) are you referring to with these sets (actually lists?) or integers? If these are the vertices, what are the edges?
Comment: If you mean "without programming" by "without computer program", you could use spreadsheet software like MS Excel or LIbreOffice Calc.  Otherwise, whip out a sheet of graph paper.  ;-)
Comment: Would we be correct in thinking that shorter WolframAlpha input, like [Plot 1{9,27,67,118,220,348,486,771}](http://www.wolframalpha.com/input/?i=Plot+1%7B9,27,67,118,220,348,486,771%7D) returns what you want?
Comment: @Hagen von Eitzen yes you are right.I gave incomplete information. These values are the values of the function, where, $x=1,2,3,4,5,.....$
Comment: @Mark McClure yes you are right. But here, $x=1,2,3...$ discrete values. Not a continous. For example, $x≠1.2$ Actually I need a histogram.
Comment: I need a similar poisson discrete distribution plot..
Answer: A quick copy and paste your data to a text file.  Save as .csv file.  Import into LO Calc.  Copy transpose.  Insert/Object/Chart.
Ced
Comment: Thank you very much..which distribution function in Mathematics is more similar?
Comment: @Beginner, is the "dip" around 40 significant?
Comment: Sorry, I can not understand your question..( english is my second language)
Comment: Can you plotting in diagram? ( For in example, which I gave in question..) Thank you!
Comment: @Beginner,Your data does not produce smooth curves.  A probability distribution is going to be a smooth curve to which you find the parameters that make a best fit to your data.  You can now describe your data using those parameters.  The variation of your data from the best fit is what is of interest.  Is it due to noise?  Is it due to an incorrect probability model?  Is it an attribute of the system you are studying?  Your data looks like a Poisson distribution would be a good fit, but right around x=43 you are getting a variation in all three of your sets.
Comment: I think, if we dividing all values by their number, We can obtain probabilistic distribution, isn't it? Which that total of values will equal to $1$.
Comment: @Beginner, I'm not the best at probability distributions.  This is a different question than knowing how to plot values.  I think you should reframe your question and post it as a new question and you are likely (pun intended) to get a better answer than what I can give.
Comment: I need your Help..@Cedron Dawg :( :(..Can you help?
Comment: @Beginner, I've been expecting an email from you.  I'm not sure what I can do, but let's start there:  cedron at exede dot net.
Comment: Perfect.Please send me an empty sms :  email@example.com
Comment: I dodn't not understand your Email clearly. please write me a message : email@example.com


Algo de errado nas referencias usando duas camadas no Entity

Question: Fiz um exemplo em Entity 5.0  e com 1 camada funcionou perfeito.
Agora separei em UI e DAL, mas esta dando erro. A mesma página que funcionou na camada DAL quando feita na UI esta dando erro.
Acredito que seja alguma falta de referência.
O erro é:
Server Error in '/' Application.

Unable to load the specified metadata resource.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.MetadataException: Unable to load the specified metadata resource.

Source Error:

Line 41:    using (var ctx = new DAL.TracesEntities())
Line 42:    {
Line 43:        var lambda = ctx.Traces.Where(q => q.DataBaseName == "megacorretor" || q.DataBaseName == "stats_mega")
Line 44:                               .GroupBy(a => new { a.TextData, a.DataBaseName })
Line 45:                               .Select(b => new { ...

Fiz referencia ao projeto DAL e a DLL:
packages\EntityFramework.5.0.0\lib\net45\EntityFramework.dll

Não lembro se devo copiar algum .tt algo para a UI para funcionar. Estranho que o interlisense na UI funciona perfeitamente com o entity da DAL
Comment: você chegou a mudar o namespace das classes movidas? Se não mudou, é por isso que o Intellisense ainda reconhece
Comment: Não sei a resposta, mas para evitar esse tipo de erro você poderia usar code first. Existe uma ferramenta bem simples que gera as classes pra você e deixa o código mais limpo do que com edmx, é o entity power tools.
Tem um exemplo dele no meu blog http://devrodrigosantos.wordpress.com/2014/03/12/comecando/
Comment: Sim mudei o namespace, alias criei um arquivo novo na UI porém com o mesmo código..intelisense 100% funciona porém ele não acha o recurso!
Creio que aqui todos desenvolvam com várias camadas pra ninguém da esse erro?
Comment: Não tinha como fazer Code first o banco de dados já existe com 20GB de dados.
Answer: Esse erro significa que o resource (refere-se ao EDMX) não foi achado. É nesse arquivo EDMX que ficam guardados os metadados usados para mapear o seu modelo de classes para o modelo do banco de dados.
Verifique se no designer do seu arquivo EDMX, a propriedade MetadataArtifactProcessing está definida para Embed in Output Assembly... é isso que faz o EDMX se transformar em um resource.
Comment: Já estava em 'Embed in Output Assembly' também mudei o Build Action para 'Embedded Resource' e Copy to output em Always e tb não funcionou..continua o erro.
Comment: Passei por esse problema e o diretorio do meu edmx estava com o metada incorreto. Obrigado Pela resposta @Miguel Angelo.


Quotient space from the 8-sided polygonal region of the labelling scheme $abcdad^{-1}cb^{-1}$

Question: This is Exercise 4 of §75 of Munkres' Topology.
It is interesting because unlike the previous exercises, not all the vertices of the polygon are mapped to the same point. So one cannot mechanically apply existing theorems. Below is the exercise.
Let $X$ be the quotient space obtained from an 8-sided polygonal region $P$ by means of the labelling scheme $abcdad^{-1}cb^{-1}$. Let $\pi: P \rightarrow X$ be the quotient map.

Show that $\pi$ does not map all the vertices of $P$ to the same point of $X$.
Determine the space $A = \pi(\text{Bd} P)$ and calculate its fundamental group.
Calculate $\pi_1 (X, x_0)$ and $H_1(X)$.
Assuming $X$ is homeomorphic to one of the surfaces given in Theorem 75.5, which surface is it?
Answer: If we draw the polygon, it is easy to see that its border corresponds to graph $P$ made of three circles as below.

If we pick the intersection of the two left-most circles as $x_0$, $\pi_1(P,x_0)$ is the free product of $\{a, bd, bcb^{-1}\}$. Let $\alpha = bd$ and $\beta = bcb^{-1}$. We have $abcdad^{-1}cb^{-1} = a \beta\alpha a \alpha^{-1} \beta$.
Thus $\pi_1(X, x_0)$ is the same as the quotient space obtained from a 6-sided polygonal region $P$ by means of the labelling scheme $a \beta\alpha a \alpha^{-1} \beta$. Unlike the original problem, this one has all its vertices mapped to the same point.
Applying the standard technique, we see that $H_1(X)$ is the quotient of $\mathbb{Z} \times \mathbb{Z} \times \mathbb{Z}$ by $0 \times 0 \times 2\mathbb{Z}$. $X$ is thus homeomorphic to the 3-fold connected sum of projective planes.


How is a Sparse RBM different from a Gaussian-Bernoulli RBM

Question: Sparse RBM are described in this paper
Gaussian-Bernoulli RBMs are describe (kinda poorly) in this paper as Gaussian Units,
and more clearly in this masters thesis.
Sparse RBM: (Quoting direct from the paper, Page 3)
$$P(v_{i}|\mathbf{h})=\mathcal{N}(c_{i}+\sum_{j}w_{ij}h_{j},\,\sigma^{2})$$
$$P(h_{j}|\mathbf{v})=logistic\left(\frac{1}{\sigma^{2}}(b_{j}+\sum_{i}w_{ij}v_{i}\right)$$
Gaussian-Bernoulli RBMs (Quoting less directly from the masters thesis., pages 38  and 36. Some substitutions/expansions made)
$$v_{i}|\mathbf{h}\sim\mathcal{N}(c_{i}+\sum_{j}w_{ij}h_{i},\,\sigma_{i}^{2})$$
$$P(h_{j}=1|\mathbf{v})=logistic\left(b_{j}+\sum_{i}w_{ij}\frac{v_{i}}{\sigma_{i}^{2}}\right)$$
So the difference would be a scaling factor of $\frac{1}{\sigma}$ on $b_i$. and $b_i$ is a learned factor controlling the threshold, so will learn away a scaling factor.
They seem to have the same PDFs, though to formulation of the energy function is superficially different, I think it simplifies to be the same.
I the difference is $\sigma$ in a sparse RBM is a  definable parameter -- that controls sparseness.
But $\sigma_i$ in a Gaussian-Bernoulli  is the variance of the the features $i$.
They are both trained the same way with Contrastive Divergence.
is this right?
are there more connections between them?
Have i got it all wrong?
Answer: The models in both papers are Gaussian-Bernoulli RBMs. The difference is the sparse variant includes a term in the object which penalizes hidden units whose conditional expectation deviates from a fixed constant, $p$. See equation (4) in section 3.1 of the sparse RBM paper you link.


Procurar objetos no mysql

Question: Boa tarde,
Estou usando o WorkBeanch 6.3 e preciso pesquisar na base de dados MySql se determinada Coluna existe e qual a sua Tabela, preciso saber também se a determinada Coluna é usada em uma Procedure ou View, por exemplo em Sql Server faço assim;
      SELECT O.name as Tabelas
        FROM syscolumns C
  INNER JOIN sysobjects O ON C.id = O.id
       WHERE c.name like '%idConta%'

Answer: Você poderia tentar assim, onde no like passa o idConta
SELECT SPECIFIC_NAME FROM information_schema.routines WHERE ROUTINE_DEFINITION like '%idConta%'

Para descobrir definers de objetos, trabalhe na tabela 'information_schema', onde você consegue as informações dos objetos, você conseguirá muita coisa nela.
Abaixo, exemplos de select para descobrir os definers.
SELECT specific_name, routine_schema, routine_name, routine_type, definer FROM information_schema.routines WHERE definer = 'seu_user';

SELECT trigger_catalog, trigger_schema, trigger_name, definer FROM information_schema.triggers WHERE definer = 'seu_user';

SELECT table_catalog, table_schema, table_name, definer FROM information_schema.views WHERE definer = 'seu_user';

Procurar objetos no mysql


Recursividade em Python 3

Question: Estou com dificuldade em organizar uma fórmula de somatório recursivo em Python. Preciso calcular:

Meu código:
def seq1(n):
    if n == 1:
        return n
    return seq1(n-1)+(-1**(n+1)/n)

Fico recebendo o mesmo erro para quase toda alteração:
RecursionError: maximum recursion depth exceeded in comparison

Gostaria de saber como fazer o cálculo, grato desde já!
Comment: Para qualquer `0 < n < 997` sua função parece funcionar (não verifiquei os resultados). Se precisa calcular para valores fora desse intervalo, recursividade não é a solução, mas para fins didáticos, leia sobre [`sys.setrecursionlimit`](https://docs.python.org/3/library./sys.html#sys.setrecursionlimit)
Comment: Obrigado Anderson!
Answer: A fórmula precisa ser necessariamente recursiva? ou seja, chamar a própria função?
acho que a forma mais elegante seria utilizar um 'for' e calcular a série numericamente.
def seq(n):
  val=0
  for i in range(n):
    val += (-1**(n+1)/n)
  return val

Comment: Precisaria, mas consegui identificar o erro, obrigado!
Comment: Encontrei dois erros na sua alternativa iterativa: (1) você não está usando o `i` na conta, mas sim a constante `n`; (2) `range` com apenas um parâmetro gera números no intervalo `[0, n)`, o que não é a intenção da fórmula, mas sim números no intervalo `[1, n]` (inclusive evitaria uma divisão por zero ao usar a variável de iteração do primeiro item que apontei)
Answer: Consegui analisar o erro. A recursividade iria ao infinito por que não voltava a chamar a fórmula. Para curiosos, o código correto abaixo:
def seq1(n):
if n >= 1:
    if n == 1:
        return (-1**(n+1)/n)
    return seq1(n-1)+(-1**(n+1)/n)

Comment: Ignorando o erro de indentação da sua resposta, devo discordar de que ela é a correção. Como o domínio da função é `N*`, sua solução faria apenas uma garantia de que se está trabalhando no domínio adequado. Concordo com o comentário do @AndersonCarlosWoss na pergunta

Recursividade em Python 3


Qual a lógica por tras desse desafio?

Question: PERGUNTA:
No futebol americano, as equipes brigam por espaço em campo e fazem pontos de duas formas diferentes: através do touchdown, que pode valer 6 ou 7 pontos e através do chute ao gol, que vale 3 pontos. Quando uma equipe entra na área de touchdown do adversário, ela pontua imediatamente 6 pontos e tem direito a um chute ao gol que vale 1 ponto extra. Enfim, os placares dos jogos são montados pela possibilidade de fazer 3, 6 ou 7 pontos, o que significa que alguns placares são impossíveis de acontecer como fazer 5, 13 ou 22 pontos. Sua tarefa será ter uma coleção de placares de um time (array) e identificar se os placares são ou não possíveis de serem realizados.
Ex: 17 → placar inválido, 10 → placar válido
As condições que eu consegui foram várias, mas por se tratar de um desafio eu acredito que o código não fique grande, por isso não coloquei todas:
declarei um array com os placares. O programa apenas precisa dizer se são placares válidos ou não.
 int placarNY[10] = {17, 26, 22, 10, 21, 18, 15, 24, 35, 19};

for(int i = 0; i < 10; i++){
    if((placarNY[i]%3 == 0) ||(placarNY[i]%7 == 0)||(placarNY[i]%10 == 0)){
        cout << placarNY[i] << " <- placar valido !" << endl;
    }else{
        cout << placarNY[i] << " <- placar invalido !" << endl;
    }
}

Comment: A lógica desse desafio é verificar se existem `A`, `B` e `C` inteiros tais que `A*3 + B*6 + C*7 = P`, sendo `P` a pontuação que se deseja saber se é válida ou não
Answer: Em resumo, precisa descobrir se existem números inteiros não negativos a, b e c tais que "score=3*a+6*b+7*c". Ao invés de buscar a solução matematicamente descobrindo possíveis a, b e c, você pode usar recursão para verificar possibilidades de placares ao longo das mudanças (afinal as únicas mudanças isoladas de placares que ocorrem são aumentos de 3, aumento de 6 e aumento de 7 pontos).

Quando num ramo a pontuação é menor que o placar que é verificado, verifica-se os inferiores. Se ao invés de menor for igual, acabou, confirmada a possibilidade de alcançar aquela pontuação. Se ao invés disso for maior, sai desse ramo e verifica outro. Se acabarem os ramos sem encontrar a soma igual ao placar verificado, então não é possível alcançar aquela pontuação.
Edit1: esqueci de falar que acumular 6 pontos é o mesmo que duas vezes acumular três, portanto não precisa ramificar com seis pontos, o de três resolve. Ramos de +3 e +7 são suficientes.
Edit2: há outra alternativa em que você assume possíveis valores de a (números de marcações de +3) de zero a floor(score/3) e calcula o c (número de possíveis marcações de +7). Por exemplo, para formar 15 pontos, assuma a=0,1,...,5 marcações de +3. Com a=0, temos 3*a+7*b=15 ==> b=15/7, sendo b=15/7 não inteiro e portanto solução não aceita. Com a=1, temos 3*a+7*b=15 ==> b=12/7, sendo b=12/7 solução não aceita. Daí em diante até encontrar uma solução válida que confirme a possibilidade do placar ou conferir todos e não encontrar, negando a possibilidade.
Comment: Acredito ter entendido, vou verificar aqui e aplicar no código. Qual que coisa eu aviso ! Valeu, bro!
Answer: A lógica por trás desse desafio é uma variação do Problema da Mochila e do Problema de Frobenius.
Ambos os problemas podem ser resolvidos com métodos de Programação Dinâmica.

Qual a lógica por tras desse desafio?


Progress bar of timer not in sync - React native

Question: I'm currently trying to create a timer with corresponding progress bar.  See this Image : (https://i.stack.imgur.com/WSklt.png)
The logic for my timer works fine:
 const [timerIsRunning, setTimerIsRunning] = React.useState(false);

 let intervalID: NodeJS.Timeout;
  useEffect(() => {
    if (timerIsRunning) {
      intervalID = setInterval(() => {
        setSeconds((seconds) => {
          // Return updated time to parent component
          if (seconds === 0) {
            setTimerIsRunning(false);
            return seconds;
          } else {
            console.log("SET NEW TIME: ");
            return seconds - 1;
          }
        });
      }, 1000);
    }

    // CleanUp
    return () => clearInterval(intervalID);
  }, [timerIsRunning]);

To calculate a smooth progress I try to make steps in the size of 1. My progress should go from 100 to 0.
For example taking a 10 seconds timer. In each second my progress should go down 10 steps.
For this I calculate the interval time for my progress:
  const step = 100 / startTimer;
  const intervalTime = 1000 / step;

  let interval: NodeJS.Timeout;
  useEffect(() => {
    if (timerIsRunning) {
      interval = setInterval(() => {
        setProgress((progress) => {
          console.log("SET NEW PROGRESS: ");
          return progress - 1;
        });
      }, intervalTime);
    }

    // }

    return () => clearInterval(interval);
  }, [timerIsRunning]);

MY PROBLEM:
The problem im facing now is that my timer and progress is desynced.
The progress isnt finished when the timer is. My guess is, that the progress only goes down by 9 steps instead of 10. But I really don't know why.
As u can see in the following logs:
progress 98
TimerButton.tsx:69 progress 97
TimerButton.tsx:69 progress 96
TimerButton.tsx:69 progress 95
TimerButton.tsx:69 progress 94
TimerButton.tsx:69 progress 93
TimerButton.tsx:69 progress 92
TimerButton.tsx:69 progress 91
TimerButton.tsx:72 seconds 9
TimerButton.tsx:69 progress 90
TimerButton.tsx:69 progress 89
TimerButton.tsx:69 progress 88
TimerButton.tsx:69 progress 87
TimerButton.tsx:69 progress 86
TimerButton.tsx:69 progress 85
TimerButton.tsx:69 progress 84
TimerButton.tsx:69 progress 83
TimerButton.tsx:72 seconds 8
TimerButton.tsx:69 progress 82
TimerButton.tsx:69 progress 81
TimerButton.tsx:69 progress 80
TimerButton.tsx:69 progress 79
TimerButton.tsx:69 progress 78
TimerButton.tsx:69 progress 77
TimerButton.tsx:69 progress 76
TimerButton.tsx:69 progress 75
TimerButton.tsx:69 progress 74
TimerButton.tsx:72 seconds 7
TimerButton.tsx:69 progress 73
TimerButton.tsx:69 progress 72
TimerButton.tsx:69 progress 71
TimerButton.tsx:69 progress 70
TimerButton.tsx:69 progress 69
TimerButton.tsx:69 progress 68
TimerButton.tsx:69 progress 67
TimerButton.tsx:69 progress 66
TimerButton.tsx:69 progress 65
TimerButton.tsx:72 seconds 6
TimerButton.tsx:69 progress 64
TimerButton.tsx:69 progress 63
TimerButton.tsx:69 progress 62
TimerButton.tsx:69 progress 61
TimerButton.tsx:69 progress 60
TimerButton.tsx:69 progress 59
TimerButton.tsx:69 progress 58
TimerButton.tsx:69 progress 57
TimerButton.tsx:69 progress 56
TimerButton.tsx:72 seconds 5
TimerButton.tsx:69 progress 55
TimerButton.tsx:69 progress 54
TimerButton.tsx:69 progress 53
TimerButton.tsx:69 progress 52
TimerButton.tsx:69 progress 51
TimerButton.tsx:69 progress 50
TimerButton.tsx:69 progress 49
TimerButton.tsx:69 progress 48
TimerButton.tsx:69 progress 47
TimerButton.tsx:72 seconds 4
TimerButton.tsx:69 progress 46
TimerButton.tsx:69 progress 45
TimerButton.tsx:69 progress 44
TimerButton.tsx:69 progress 43
TimerButton.tsx:69 progress 42
TimerButton.tsx:69 progress 41
TimerButton.tsx:69 progress 40
TimerButton.tsx:69 progress 39
TimerButton.tsx:69 progress 38
TimerButton.tsx:72 seconds 3
TimerButton.tsx:69 progress 37
TimerButton.tsx:69 progress 36
TimerButton.tsx:69 progress 35
TimerButton.tsx:69 progress 34
TimerButton.tsx:69 progress 33
TimerButton.tsx:69 progress 32
TimerButton.tsx:69 progress 31
TimerButton.tsx:69 progress 30
TimerButton.tsx:69 progress 29
TimerButton.tsx:72 seconds 2
TimerButton.tsx:69 progress 28
TimerButton.tsx:69 progress 27
TimerButton.tsx:69 progress 26
TimerButton.tsx:69 progress 25
TimerButton.tsx:69 progress 24
TimerButton.tsx:69 progress 23
TimerButton.tsx:69 progress 22
TimerButton.tsx:69 progress 21
TimerButton.tsx:69 progress 20
TimerButton.tsx:72 seconds 1
TimerButton.tsx:69 progress 19
TimerButton.tsx:69 progress 18
TimerButton.tsx:69 progress 17
TimerButton.tsx:69 progress 16
TimerButton.tsx:69 progress 15
TimerButton.tsx:69 progress 14
TimerButton.tsx:69 progress 13
TimerButton.tsx:69 progress 12
TimerButton.tsx:69 progress 11
TimerButton.tsx:72 seconds 0
TimerButton.tsx:69 progress 10
TimerButton.tsx:69 progress 9
TimerButton.tsx:69 progress 8
TimerButton.tsx:69 progress 7
TimerButton.tsx:69 progress 6
TimerButton.tsx:69 progress 5
TimerButton.tsx:69 progress 4
TimerButton.tsx:69 progress 3
TimerButton.tsx:69 progress 2

Answer: I am not sure you need 2 timers. If your progress depends on a timer where you set seconds you can use useMemo hook to calculate your progress. Something like:
const [seconds, setSeconds] = useState(0)
const progress = useMemo(() => {
 // Place your logic of progress calculation and return new progress value
 return newProgressValue
}, [seconds])

useEffect(() => {
  setInterval(() => {
    // do you logic and set seconds
    setSeconds(newValue)
  }, 1000)
}, [])

Comment: That sounds nice :) I actually found a solution by my self. I now just using React Native Animated Value to calculate the progress.


How to calculate the expectation of the square of the number of heads in N tosses?

Question: Suppose we have a coin that has a probability $p$ of landing head. Let H be the number of heads obtained in N tosses. How to calculate $E(H^2)$? I need this to calculate some other things. But I can't figure out. I know I need to take $\sum x^2p(x)$, but I am unable to evaluate it to a nice expression.
Comment: I assume the tosses are independent, is that right? Is the coin fair?
Comment: @bof the coin has probability of p of landing head
Comment: So you now have three answers using three different approaches, any one of which may or may not be useful to you depending on what "other things" you need this for and exactly why you had trouble getting a "nice expression." If one of the answers gave you the insight you needed, now would be a good time to accept it; if not, you might consider editing the question again to give more detail about what you need and what you were able to find yourself before you got stuck.
Answer: I assume that you're talking about $N$ independent coin tosses. (Actually, the calculation below assumes only that the tosses are pairwise independent.) Let $p$ be the probability that the coin comes up heads, and let $q=1-p$ be the probability that it comes up tails.
Let $H_i$ be the indicator variable which takes the value $1$ if the $i^{\text{th}}$ toss comes up heads, $0$ otherwise. Thus
$$H=H_1+H_2+\cdots+H_N.$$
and
$$H^2=(H_1+\cdots+H_N)^2=\sum_{i=1}^NH_i^2+\sum_{i\ne j}H_iH_j,$$
so
$$E(H^2)=\sum_{i=1}^NE(H_i^2)+\sum_{i\ne j}E(H_iH_j)=\sum_{i=1}^Np+\sum_{i\ne j}p^2$$$$=Np+N(N-1)p^2=Np(1-p)+N^2p^2=Npq+E(H)^2.$$
Answer: $$E_n[H^2] = \sum_{k=0}^{n}\binom{n}{k}p^k(1-p)^{n-k}k^2 =n^2p^2 - np^2 + np $$
Answer: It appears that you know $H$ follows a binomial distribution with parameters $N, p$. Since the variance and the expectation of the binomial distribution are well-known, you can solve the variance formula for $E[H^2]$ and do
$$E[H^2] = \operatorname{Var}(H)+(E[X])^2 = Np(1-p) +(Np)^2.$$
Of course, if you are proving what the variance value is ("calculate some other things"), this doesn't quite work.


Collinearity in time dummies, fixed effect regression

Question:
I am running a fixed effect panel regression with 81 groups x 20 periods, so approx 1620 (unbalanced) observations.
I use the following to create dummies:
*create timedummy
tabulate refper, generate(refdummy)

which to visual inspection looks fine. But when running the xtreg, it removes 6 time dummies due to collinearity. Can anyone explain what is happening here?
Comment: Note that as you've given some Stata syntax, adding the actual `xtreg` command you used would be consistent with that and is in fact the single piece of Stata information that is most relevant. That aside: there is a statistical question here, but what is it precisely? Do want to know what collinearity means? If not, what kind of explanation do you seek? We don't have your data to look at correlations or scatter plots but you can do that.
Answer: From the labelling of your variables, I suspect that the regressors you include are lagged. But the fourth lag of a variable ("_L4") will only be available from the fifth period onwards, so that might explain why the first four time dummies drop out of your regression: you are not actually using any of the data in the first four time periods to estimate the model. Some of the other time dummies might drop out for similar reasons (maybe one of your variables is only available from period 3 onwards, meaning its fourth lag is only available from period 7 onwards). It looks like you might be regressing a differenced variable ("d") on the fourth lag of another differenced variable ("d" and "L4") in which case it makes sense for the first few periods not to be included in estimation. This automatically means you cannot estimate the time dummies for these period.


Let P and Q represent formulas. Would stuff like $(P \wedge \neg P) \models Q$ make sense?

Question: I confess, I am in a state of total confusion right now. And I am still struggling to grasp the underlying distinction between the normal material implication, $\Rightarrow$, and the notion of semantic consequence, $\models$.
I've seen stuff like $(P \wedge \neg P) \models Q$ appear in a book I'm currently reading (A First Course in Logic, by Shawn Hedman), but at the end of the day, it had me wondering what the difference is between material implication and semantic consequence. I mean, really.
We all know that the sentence $(P \wedge \neg P) \Rightarrow Q$ is a tautology. And in a material sense (only thinking in terms of truth values and not in terms of how the two formulas P and Q are connected semantically), this is totally acceptable to me. But to write stuff like $(P \wedge \neg P) \models Q$  blows my entire understanding of the difference between $\Rightarrow$ and $\models$ right out the window. I thought the double turnstile symbol is only to be used in a sense that has more to do with the underlying meaning/interpretation behind the sentences? Like, if we say $P \models Q$ (where P and Q are sentences), then wouldn't it mean that we can see a clear logical connection which allows us to accept that Q follows from P?
If translated into words, the sentence "formula Q is a semantic consequence of $P \wedge \neg P$" is incomprehensible to me. It doesn't have that logical connection that I thought must accompany every use of the double turnstile symbol (for instance, I can easily accept $(P \wedge Q) \models P$, because the logical connection is there, after all if its stated that P and Q are both true, then logically, P must be true). If no logical connection is required for the use of $\models$, then how is it different from the normal material implication?
It feels like I'm missing something crucial, like a bigger picture, or a wider generalization of what the double turnstile symbol represents.
Comment: Well $Q$ is a semantic consequence of $P\land \neg P$ because in every possibility in which $P\land \neg P$ holds (there is no such possibility !) , $Q$ holds as well. Semantics is about possible worlds, so this is why that's called semantic implication
Comment: As far as I can tell, your difficulty comes from the part of your question that says "we can see a clear logical connection". That's far too vague to be mathematics. If, by "clear logical connection", you mean something that includes truth tables, then you're probably OK, because truth tables do allow you to infer $Q$ from $P\land\neg P$. But if you mean something more vague than truth tables, then you need to revise your understanding of $\models$.
Comment: The basic issue is that we may have logical languages **without** the conditional *connective* ($\to, \Rightarrow$): we may use $\land, \lnot$ or $\lor, \lnot$ and they are enough to formalize arguments as well as the concept of *tautology*. But the concept of *logical consequence*: $\vDash$ does **not** change.
Comment: "the double turnstile symbol is only to be used in a sense that has more to do with the underlying meaning/interpretation behind the sentences?" YES... but in propositional logic the only "meaning" of a sentence is its TRUTH-VALUE.
Comment: @DougSpoonwood it should be clear to anyone reading my comment that "same as" here is an abuse of language meaning "equivalent to", please don't bicker about details like that.
Comment: $P\models Q$ means that any model satisfying $P$ also satisfies $Q$. With a completeness/soundness theorem, and a deduction theorem, this is the same as $\vdash P\implies Q$. One of the points of $P\land \neg P\models Q$ (which also holds intuitionistically, where $\implies$ is not material) is that a contradiction should be read as "everything", rather than as "false".
Comment: @Max Hi. I appreciate the response. But i'm still confused, to be honest. Is it possible to explain it in more layman terms? How does one interpret $(P \wedge \neg P) \models Q$ in a way that jibes with the concept of "semantic consequence"?
Comment: @Max "With a completeness/soundness theorem, and a deduction theorem, this is the same as ⊢P⟹Q."  No, inter-derivability does not mean sameness.
Comment: @Max No, your statements are not logically equivalent.  $\vdash$ refers to syntactic provability which means one can *literally* produce whatever is on the right side of the $\vdash$.  One cannot literally produce any formula of the form P⟹Q since no well-formed formula has that form.  Also, P|=Q is meta-linguistic, and abbreviates {P}|=Q, while (P⟹Q) is object-linguistic.  Object language and meta language statements are not equivalent in general.  Usually, meta-language statements has more expressive power, while object language statements are clearer in terms of their validity.
Comment: @DougSpoonwood so you're telling me that $P\models Q$ and $\vdash (P\implies Q)$ are not logically equivalent with a completeness/soundess theorem and a deduction theorem ? (again, the parentheses issue being unnecessary bickering about a technical uninteresting issue here)
Comment: @Max Yes, they are not logically equivalent solely under the conditions you've put forth.  You would need modus ponens as a rule of inference.  And systems of propositional logic exist without such a rule of inference.  Also, logical equivalence is an object-linguistic concept in terms of computable truth values.  I have no reason to suppose it as a meta-linguistic concept.
Comment: @Max That's exactly the difficulty that I'm facing right now. If we were to accept what you said in your second comment, then what difference is there really between $\models$ and $\Rightarrow$? That's just saying that $P \wedge \neg P$ materially implies $Q$, isn't it?
Comment: @Max The ONLY way my befuddled mind can come into terms with everything at this point is that the usage of $\models$ (e.g, $P \models Q$) is to EXPLICITLY state that $P \Rightarrow Q$ is a tautology. Like, we can make compound statements like $P \Rightarrow Q$ everywhere, but the material implication can still be false. And the $\models$ is just a way of saying that the material implication is a tautology? Is that the right way to understand all of this?
Comment: @AndreasBlass

Yes. I definitely need to revise my understanding of $\models$'s usage. In fact, right now I don't even know what I know anymore.

I agree with you that 'clear logical connection' is far too vague and imprecise for mathematics. But sadly that's the only way I can express it. Maybe I should clarify what I meant by that.

Thing is, statements like $(P \wedge Q) \models P$ is comprehensible to me in terms of semantic implication, because we can reason out the truth of $P$ logically. We can infer the truth of P using the truth of $(P \wedge Q)$... (to be continued)
Comment: continued from above...

@AndreasBlass
But how do we do that for $(P \wedge \neg P) \models Q$? We can't reason (or infer) the truth of Q based on $P \wedge \neg P$ (or can we??). I mean, there's just no connection there. All we know from $(P \wedge \neg P)$ is that it is an absurdity, and that's it? There's nothing at all about $Q$.That's what I mean by 'clear logical connection'. I must apologize for the imprecise use of terms here, I have very little background in logic. In fact, this is my first attempt.
Comment: @AndreasBlass

After reading all your constructive comments, I have come to the conclusion that $P \models Q$ is a way to explicitly state that $P \Rightarrow Q$ is a tautological statement. What I mean by this is, that we can have sentences like $P \Rightarrow Q$, but that sentence can still be a falsehood. But if we say $P \models Q$, then there is no chance at all that $P \Rightarrow Q$ can be false? (that it is a tautology) Am I on the right track here? Or is this just another fantasy that my confused mind had conjured upon?
Comment: @DougSpoonwood : mhm no here there's no need for modus ponens here. But nevermind it's clear that you don't understand what all this is about and to not pollute these comments I'll stop answering to you.
Comment: Anthony : the point is that stating "$P\implies Q$" makes no sense because there is no interpretation for $P$, nor for $Q$. So you say $P\models Q$ to say that this doesn't depend on the interpretation. And indeed, with all the theorems that I mentioned, this is equivalent to $\models P\implies Q$ which means exactly that $P\implies Q$ is a tautology. But what else would you want it to mean ? As Andres Blass mentioned, the notion of "logical connection" is not mathematical"
Comment: @Max Modus ponens is usually needed to prove that "If |-(P⟹Q), then P|-Q."
Comment: @Anthony "But how do we do that for (P∧¬P)⊨Q? We can't reason (or infer) the truth of Q based on P∧¬P (or can we??)."  In sound systems, it's possible to reason out (P∧¬P)|=Q.  Something like the following usually works.  We assume (P∧¬P).  Then we assume $\lnot$Q.  Then we get a contradiction from the first assumption.  So, we have ($\lnot$Q$\rightarrow$(P∧¬P)) or ($\lnot$Q$\vdash$(P∧¬P)).  Thus, we discharge $\lnot$Q and have Q under the assumption of (P∧¬P).  So, (P∧¬P)$\vdash$Q.  By soundness, (P∧¬P)|=Q.
Comment: @DougSpoonwood i appreciate the response. But i am new to this topic, and have insufficient background in formal mathematics to know the full implications of concepts such as soundness and completeness. But i will read them up first before coming back and reread your comment. But meanwhile, it will be immensely helpful if you could express your answer in complete layman terms.
Answer: "We all know that the sentence (P∧¬P)⇒Q is a tautology."
I certainly don't know this and gasp when I see statements like this made.  Anyone who claims to is also, simply put, wrong.  Why things work that way helps to illuminate things.
To say that something is a tautology is to imply that something is an object-level sequence of symbols.  If you check your definition of a well-formed formula, or whatever equivalent term gets used, (P∧¬P)⇒Q is not well-formed.  Thus, (P∧¬P)⇒Q is not a tautology, because a tautology is by definition a well-formed formula.  ((P∧¬P)⇒Q) is a tautology.
On the other hand, (P∧¬P)⊨Q is a meta-language construct.  It is not well-formed in the object-language, and since the arity of the predicate |= seems to vary, there might not exist a corresponding well-formed formula (though maybe not also).  Also, |= is a predicate, while ((P∧¬P)⇒Q) doesn't have any predicates.
The difference might also get illuminated by looking at other uses of |=.  For instance, I think you agree that, "{p, (p⇒q)} |= q" makes sense.  Let's suppose that |= is no different from ⇒.  Then, "{p, (p⇒q)} |= q" is no different from "{p, (p⇒q)} ⇒ q".  There's at least three problems,

"{p, (p⇒q)} ⇒ q" is not well-formed, since all well-formed formal implications begin with a '(' and end with a ')'.
q is a proposition, but what we have on the left side of the arrow is a set.  But, sets of propositions are not propositions.  Nor are propositions sets of propositions.  So, again, "{p, (p⇒q)} ⇒ q" is not well-formed, and it's not even apparent how to make into a well-formed formula, or even necessarily the case that it can get made into a well-formed formula, since it would even two different types of entities needing to fall under the same roof... so to speak.  That sounds like a possible category error.

Pece has also commented that:
"... ⊨ is a relation between finite sequences of wffs on the left and wff on the right, while ⟹ is a binary connective in the language that is used to construct formulas."
Comment: Bickering about parentheses really isn't relevant here. Moreover, no one is claiming that $\models$ is the same as $\implies$ here. The OP asks what $\models$ is, why it's called semantic consequence, how it differs from material implication, how a sense of "logical connection" is attained: this has nothing to do with your answer
Comment: @DougSpoonwood Actually most mathematical textbook about model theory or proof theory establishes at some point $P \mathbin{\mathcal B} Q$ as syntactic sugar for $(P \mathbin{\mathcal B} Q)$ when it is not harmful (with $\mathcal B$ a binary connective). Moreover, replace everywhere in OP's question the "wrong" statement by your well-formed variation and still your answer does not address the question. At best, you could have just made it a comment.
Comment: @DougSpoonwood I think I understand what you were trying to say in you answer, namely that $\models$ is a relation between finite sequences of wffs on the left and wff on the right, while $\implies$ is a binary connective in the language that is used to construct formulas. If so, first I will remove my -1 because your answer is not about nitpicking,  but this is not at all clear that this is the message you want to convey, but secondly and more importantly I'm not even sure this is the problem OP is struggling on...
Comment: @Max It's not a bicker.  You can't have a valid rule of uniform substitution without parentheses.  That rule works out as essential for axiomatic systems which only have axioms and rules of inference.  |= is certainly a meta-language symbol, while ⟹ an object language symbol.
Comment: $(p \land \neg p) \implies q$  is a tautology. See the truth table at http://www.wolframalpha.com/input/?i=truth+table+(p+and+~p)+%3D%3E+q
Comment: @DanChristensen No, (p∧¬p)⟹q is not a tautology.  Every tautology is a well-formed formula, and (p∧¬p)⟹q is not a well-formed formula.
Comment: Then you had better write to Wolfram to, ummm... set them straight. Likewise Stanford whose online truth table generator agrees http://web.stanford.edu/class/cs103/tools/truth-table-tool/ Good luck with that. (Hee, hee!)
Comment: @DanChristensen If (p∧¬p)⟹q is a tautology, then by the rule of uniform substitution and substituting  (p∧¬p)⟹q for q, since tautologies can always get substituted for variables, then (p∧¬p)⟹ (p∧¬p)⟹q is a tautology.  But, (p∧¬p)⟹ (p∧¬p)⟹q is not a tautology.  (p∧¬p)⟹ (p∧¬p)⟹q is ambiguous.  The text of wolframalpha is also not consistent.  (p and ~p) => q is not the same as p$\land$$\lnot$p⟹q.  A CS class?  Why aren't you consulting mathematical logic texts by logicians?  Here's sections of Elliot Mendelsohn's text:
Comment: @DanChristensen "A statement form that is always true, no matter what the  truth values of its statement letters may be, is called a tautology."  For the definition of a 'statement form' see p. 13 here: https://www.karlin.mff.cuni.cz/~krajicek/mendelson.pdf  "Statement form" is a synonym for "well-formed formula".  A basic requirement for well-formed formulas lies that they enable us to compute truth values of expressions uniquely.
Comment: In classical logic, $(p \land \neg p) \implies q$ is a wff and a tautology.
Comment: @DanChristensen No, (p∧¬p)⟹q is not a wff.  At least not from any workable definition.  Every wff can get demonstrated as a wff from the formation rules for a wff.  So, since you claim that (p∧¬p)⟹q is a wff, go ahead and *demonstrate* it as one by only using the formation rules.  You've made the claim, and thus the burden of proof lies with you.
Comment: See https://en.wikipedia.org/wiki/Well-formed_formula#Propositional_calculus Is this not a "workable definition?"
Comment: @DanChristensen That's workable.  From that definition, it's clear that every string where the primary connective (the primary connective would be the first symbol were the string to get translated to a prefix notation without parentheses) is binary, starts with a '(' and ends with a ')'.  Thus, if a string S does not start with a '(' and end with a ')', and the primary connective is binary, then S is not a wff.  So, (p∧¬p)⟹q  is not a wff ('⟹' is binary and the primary connective).  So again, where is your demonstration?  I'm not seeing it.
Comment: @Pece I hope you agree that the OP did not understand the concept of a well-formed formula when he wrote it.  The OP writes: "But to write stuff like (P∧¬P)⊨Q blows my entire understanding of the difference between ⇒ and ⊨ right out the window."  But, this would not have happened had the distinction between well-formed formulas and other strings been clearer to the OP.  A difference between  ⇒  and |= lies in that  ⇒ can and does appear in well-formed formulas in propositional logic, while |= cannot and does not.  So-called "syntactic sugar" makes things like that LESS clear.  Also...
Comment: The OP writes: "I've seen stuff like (P∧¬P)⊨Q appear in a book I'm currently reading (A First Course in Logic, by Shawn Hedman), but at the end of the day, it had me wondering what the difference is between material implication and semantic consequence. I mean, really."  Well, in reality, material implication gets represented by symbols which can and do appear in well-formed formulas in propositional logic, while semantic consequence cannot and does not.  Thus, in reality, material implication is object linguistic and semantic consequence is meta-linguistic.
Comment: @DanChristensen You wrote that "((p∧¬q)⟹q) " is a tautology.  It's not.  Suppose q is false, and p is true.  I suppose that's a typo, but one little symbol can make a difference like that.
Comment: @DougSpoonwood So $((p \land \neg p) \implies q)$ with outer brackets is a wff and a tautology. That's what this is all about -- the outer brackets??? OMG
Comment: @DanChristensen OMG you believe that the outer brackets don't matter and you write theorem proving software???!!  Look, consider a simple system with just -> as a connective.  Suppose x->y is a wff.  Suppose the only axiom is (x->(y->x)).  Suppose the only rule of inference is uniform substitution.  And nothing more.  Let's substitute a->b for x in the axiom.  Then we have (a->b->(y->a->b)).  But, let's say we didn't know the substitution history.  We'd have no idea how to compute a->b->(y->a->b).  Oops!  What went wrong?  We didn't have two little parentheses in our definition of a wff!


How can I generate the cucumber json report with karate

Question: At the moment, only hml cucumber reports are generated and also karate reports in json format but I can't get the Cucumber reports in json format to be able to use them in an integration Help!

The runner file looks like this
`
enter image description here
I have the configuration that you showed and the Cucumber reporting dependency, I don't know what else I need

since I am only getting the html report from cucumber and I need the json

<configuration>
    <projectName>karate_automatione</projectName>
    <outputDirectory>${project.build.directory}/cucumber-report-html</outputDirectory>
    <cucumberOutput>${project.build.directory}/cucumber.json</cucumberOutput>
</configuration>

Answer: Look in the karate-reports folder. Any files with the *.json extension are in Cucumber JSON format.
But each Feature will have a separate JSON output. But most tools that handle the Cucumber JSON are able to process multiple at a time.
Comment: hello thanks for answering!! if i have json reports there in that folder but they don't match cucumber json format
Comment: @NAYELYSIBAÑEZ that doesn't make sense to me. follow this process so we can investigate: https://github.com/karatelabs/karate/wiki/How-to-Submit-an-Issue


Reading process.env environment variables in AWS Lambda with Webpack 5 and Node

Question: I'm bundling my Lambda Node project with WebPack. Calls to process.env are now coming back as {} despite there being variables set in the lambda.
I notice that WebPack 5 removed polyfils for a lot of Node functions. I've tried a long list of suggestions without success.
Can someone please provide assistance? Perhaps there's some AWS library which handles reading the environment that I'm might be removing?
Thanks.
Answer: I found the issue.
I was using this webpack.config.js
plugins: [
    new NodePolyfillPlugin()
  ]

It was using browser.js which was setting process.env = {}


What are the exact steps to produce $k = \log_{3/2}n $ from $(\frac{2}{3})^kn = 1$?

Question: What are the procedures to derive $k = \log_{3/2}n $ from $(\frac{2}{3})^kn = 1$?
Is there a well-known formula?
Answer: We can write $$\left(\frac{2}{3}\right)^k=\frac{1}{n}$$ so $$\left(\frac{3}{2}\right)^k=n$$ so $$k\ln \left(\frac{3}{2}\right)=\ln(n)$$
Comment: you've got a typo (missing $1/$)
Comment: Sorry for that typo.
Answer: Pass $n$ to the right and take $log_{\frac{3}{2}}$ in both sides. Now using that
$log(a^b) = b \log(a)$ you get on the left $k *log_{\frac{3}{2}}(\frac{2}{3})$ which is $-k$. On the right you have $log_{\frac{3}{2}}(\frac{1}{n})$ which is
$-log_{\frac{3}{2}}(n)$. So you finally get $k=log_{\frac{3}{2}}(n)$
Answer: It's just definition.
$(\frac 23)^k n = 1$ so
$(\frac 23)^k = \frac 1n$ so
$(\frac 32)^k = n$ so
By definition, $\log_{\frac 32} n = k$.
The formulas $\log_b n = - \log_{\frac 1b} n$ (because $b^k = (\frac 1b)^{-k}$) and $\log_b \frac 1n = -\log_b n$ (ditto) might be useful.
But mustly you should know the definition that $\log_b n = k \iff b^k = n$.  Technically that isnt a "formula" (because it's a definition) but it may be thought of as one.
Answer: $k = \log_{3/2} n$ $\Rightarrow$ $\left( \frac{3}{2} \right)^k = n$ (by definition of logarithm) $\Rightarrow$ $1 = \left( \frac{3}{2} \right)^{-k}n$ $\Rightarrow$ $n\left( \frac{2}{3} \right)^k = 1$
Answer: Manipulate the original equation a bit:
$$\left(\frac{2}{3}\right)^k n = 1 \iff \left(\frac{2}{3}\right)^k = \frac{1}{n} \iff \left(\frac{3}{2}\right)^k = n$$
Now, just use the definition of a logarithm: $a^b = c \iff \log_a c = b$. This gets the desired result: $k = \log_{\frac{3}{2}} n$.


Find $\int_0^1 \mathrm{\frac{x-1}{ln(x)}}\,\mathrm{d}x$

Question: Find $\int_0^1 \mathrm{\frac{x-1}{ln(x)}}\,\mathrm{d}x$
I tryed this:
$\int_0^1 \mathrm{\frac{x-1}{ln(x)}} = \int_0^1 \mathrm{\frac{x}{ln(x)}} - \int_0^1 \mathrm{\frac{1}{ln(x)}}\,\mathrm{d}x$
To $\int_0^1 \mathrm{\frac{1}{ln(x)}}\,\mathrm{d}x$
Let $t=lnx $ then $\frac{dt}{dx}=\frac{1}{x}$ and $dx=e^tdt$
$\int \mathrm{\frac{1}{ln(x)}}\,\mathrm{d}x \equiv \int \mathrm{\frac{e^t}{t}}$$\mathrm{d}t$ and well
$e^t=\sum _{n=0}^\infty \frac{t^n}{n!}$
$\frac{e^t}{t}=\sum_{n=0}^\infty \frac{t^{n-1}}{n!}$
$\int \mathrm{\frac{e^t}{t}}\,\mathrm{d}t=\int \mathrm \sum_{n=0}^\infty{\frac{t^{n-1}}{n!}}\,\mathrm{d}t=\sum_{n=0}^\infty\frac{t^n}{n*(n)!}$
How can I solve $\int_0^1 \mathrm{\frac{x}{ln(x)}}$ ?
Thanks for your help :) have a nice day
Answer: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert #1 \right\vert}%
 \newcommand{\yy}{\Longleftrightarrow}$
$\ds{\int_{0}^{1}{x - 1 \over \ln\pars{x}}\,\dd x: {\large ?}.\quad}$
Whith the change of variables $x \equiv \expo{-z}:$
\begin{align}
\color{#0000ff}{\large\int_{0}^{1}{x - 1 \over \ln\pars{x}}\,\dd x}
&=
\int_{\infty}^{0}{\expo{-z} - 1 \over -z}\,\pars{-\expo{-z}\,\dd z}
=
\int^{\infty}_{0}{\expo{-z} - \expo{-2z}\over z}\,\dd z
\\[3mm]&=
-\int^{\infty}_{0}\ln\pars{z}\pars{-\expo{-z} +2 \expo{-2z}}\,\dd z
=
\int^{\infty}_{0}\ln\pars{z}\expo{-z}\,\dd z
-
\int^{\infty}_{0}\ln\pars{z \over 2}\expo{-z}\,\dd z
\\[3mm]&=
\int^{\infty}_{0}\ln\pars{z}\expo{-z}\,\dd z
-
\int^{\infty}_{0}\bracks{\ln\pars{z} - \ln\pars{2}}\expo{-z}\,\dd z
=
\ln\pars{2}\overbrace{\int^{\infty}_{0}\expo{-z}\,\dd z}^{=\ 1}
\\[3mm]&=
\color{#0000ff}{\large\ln\pars{2}}
\end{align}


How to access all ringtones from iPhone and Populate in UIPickerview?

Question: Is it possible to get accessing all the ring tones. I need to display the name of the ring tones in UIPickerview then user can select and set as ring tone. Any Ideas?
Answer: Apple currently doesn't allow  you to play any alerts in the iPhone OS nor can you access the user's ringtones. You would have to provide your own ringtones for your application.
Answer: The system ringtones are not available in the current iOS SDK. If you want that functionality, you'll need to file an enhancement request for it.


Swift 1.2 -> Swift 2

Question: I'm coding an app for my Kids. I have background in Java but havn't professionally coded in a decade. I don't thoroughly understand how the following line works but it worked in Swift 1.2:
leaderboardRequest.loadScoresWithCompletionHandler({ (scores:[AnyObject]!, error:NSError!) -> Void in
            if (error != nil)
            {

I need help translating this into working Swift 2.0 code. Could someone please post a translation of working Swift 2.0 code for the following method:
func getHighscores(leaderboardID: String) {

    let leaderboardRequest = GKLeaderboard() as GKLeaderboard!
    leaderboardRequest.identifier = leaderboardID

    if leaderboardRequest != nil
    {
        leaderboardRequest.loadScoresWithCompletionHandler({ (scores:[AnyObject]!, error:NSError!) -> Void in
            if (error != nil)
            {
                //println("error in alltimeHighscoreForLevel")
                print(error.description)
                self.updateLocalHighscore()
            }
            else
            {
                if(leaderboardRequest != nil){
                    if(leaderboardRequest.scores != nil ) {
                        if(leaderboardRequest.scores!.count > 0){
                            self.updateHighestForLevel(leaderboardRequest)

                        }
                    }
                }
            }
        })
    }
}

Comment: You'll need to read the Swift 2 documentation, especially where it discusses the new throw / catch syntax.
Answer: I think this will work for you:
leaderboardRequest.loadScoresWithCompletionHandler({ (scores, error) -> Void in
    if let error = error {
         // from here on your code should work

I think the definition of loadScoresWithCompletionHandler changed from the old code.
Answer: Two common ways to solve this:

Comment out the line / method which causes the error and start to retype it. The code completion will reveal the proper signature of the method. Then copy and paste the relevant code from the old line / method to the new one and resolve potential errors / warnings.
Press ⇧⌘0 and type (or copy&paste) the beginning of the method for example loadScoresWithCompletionHandler into the search field. This will take you to the documentation and you can see the whole declaration including the discussion.

Swift 1.2 -> Swift 2


Proving $\gamma_2(t)=(t(t^2-4),t^2-4)$ is an embedding

Question:
Check if the following map is an immersion (injective or not) and an embedding.
1) $\gamma_1:\mathbb{R}\to\mathbb{R}^2,\gamma_1(t)=(t,|t|)$
2) $  \gamma_2:\mathbb{R}\to\mathbb{R}^2,\gamma_2(t)=(t(t^2-4),t^2-4)$

1) The first curve is not differentiable considering all of $\mathbb{R}$. Therefore I would conclude it is not a immersion.
If restrict the domain into an interval such that [0,1], then we would have 1:1 line which is an injective immersion over a compact hence an embedding.So I would conclude that$\gamma_1$ restricted to any closed interval in $\mathbb{R}+$ or $\mathbb{R}-$ is an embedding. If the interval is not closed it is an injective immersion.
2) Computing the Jacobian we get $J\gamma_2(t)=(3t-3,2t)\neq 0,\:\:\forall t\in\mathbb{R}$. Hence the rank of $\gamma_2$ is 1 which implies that $\gamma_2$ is an immersion. According to the jacobian $\gamma_2$ is monotonous increasing function hence injective. So I have an injective immersion. Since both (t(t^2-4),t^2-4) functions are continuous it is only required to prove that the inverse exists and it is continuous. However I am not seeing how to that last step that would give me the homeomorphism into the image.
Questions:
Are my resolutions insofar correct? How should I finish 2)?
Thanks in advance!
Comment: you can gain confidence by looking at their plots
Comment: Why do you think that an injective map from $\mathbb{R} \to \mathbb{R}^2$ needs to be differentiable?
Answer: 1) Actually if $(a,b)\subset (0,\infty),$ then $\gamma_1$ is an embedding. That's because $t\to (t,t)$ is a homeomorphism of $(0,\infty)$ onto $\{(x,y):x>0,y=x\}.$ Same for $(a,b)\subset(-\infty,0).$ Other than that your answer seems good.
2) Usually the term "Jacobian" alone means the determinant of a square Jacobian matrix. I'll just write $\gamma_2'(t)$ here.
You've made an error in calculating $\gamma_2'(t).$ It should be $\gamma_2'(t) = (3t^2-4,2t).$ Nevertheless we still see $\gamma_2'(t)$ is never $(0,0).$ Therefore $\gamma_2$ is an immersion.
I do not know what you mean by "$\gamma_2$ is monotonous increasing function hence injective". How can a vector valued function be monotonically increasing?
But notice $\gamma_2(-2) = (0,0) = \gamma_2(2).$ Thus $\gamma_2$ is not injective, and therefore $\gamma_2$ is not an embedding.


Convergence of $x_{n+1} = x_n + \dfrac{(\vert x_n \vert)^{1/2}}{n^2}$

Question: Let $(x_n)$ be the sequence defined by $x_{n+1} = x_n + \dfrac{(\vert x_n \vert)^{1/2}}{n^2}$ for $n \geq 2$ and $x_1$ be any real number. Then I want to prove that $x_n$ is convergent.
It is obvious that $x_n$ is monotonically increasing. I also wanted to show that $x_n$ is bounded above by using the inequality $x_{n+1} < x_n + \dfrac{\vert x_n \vert}{n^2}$ but I was not successful.
Answer: Suppose $x_m > 0$ for some $m$. Rearrange the recurrence to get $\dfrac{x_{n+1}-x_n}{\sqrt{|x_n|}} = \dfrac{1}{n^2}$.
Since $\dfrac{1}{\sqrt{|x|}}$ is decreasing for $x > 0$, a left endpoint Riemann sum will overestimate the integral.
Hence, $2\sqrt{x_n}-2\sqrt{x_m} = \displaystyle\int_{x_m}^{x_n}\dfrac{1}{\sqrt{|x|}}\,dx \le \sum_{k = m}^{n-1}\dfrac{x_{k+1}-x_k}{\sqrt{|x_k|}} = \sum_{k = m}^{n-1}\dfrac{1}{k^2} \le \sum_{k = 1}^{\infty}\dfrac{1}{k^2} = \dfrac{\pi^2}{6}$.
Therefore, $x_n \le \left(\sqrt{x_m}+\dfrac{\pi^2}{12}\right)^2$ for all $n \ge m$, and thus, $x_n$ is bounded above.
If $x_m \not > 0$ for any $m$, then $x_n$ is bounded above by $0$.
Comment: This was beautiful.
Comment: It is not clear to me why $x_n<(x_m^{1/2}+C)^2$ for $n>m$ implies boundedness
Comment: Since $x_m$ is some finite value, $(\sqrt{x_m}+\tfrac{\pi^2}{12})^2$ is also some finite value. Hence, $x_n < (\sqrt{x_m}+\tfrac{\pi^2}{12})^2$ means that $x_n$ is bounded above for $n > m$, and thus, $x_n \le \max\{x_1,x_2,\ldots,x_m,(\sqrt{x_m}+\tfrac{\pi^2}{12})^2\}$ for all $n$.


CURL: How retain cookies between requests?

Question: I need to login to a page and then submit an entry.
i'm able to login with the following code
curl $HOST -s -L -b $COOKIE -c $COOKIE -d "login=submit&login_name=$USER&login_password=$PASS" -o $OUTPUT

but when i try to submit an entry i'm not logged in anymore
curl $HOSTADDNEWS -L -b $COOKIE -c $COOKIE -A $HEADER -d "title=$TITLE" -o $OUTPUT.add.news

How to retain cookies between requests?
Comment: These commands _do_ retain the cookies (with -b and -c specifying the same file assuming curl has permission to write to it)  - and you could use --trace-ascii to get that shown nicely. Your problem is probably not exactly that...
Comment: Thanks! the problem was with $COOKIE variable it had a "slash"...
Answer: Thanks to  Daniel Stenberg! $COOKIE variable had a "slash" in it... it still saved to file but wasn't able to use it.
Comment: You're welcome, although I didn't really answer the question... :-)


Amstock chart event's text hiding at top

Question: https://i.stack.imgur.com/ymhUv.png
event box hiding and its balloon too .
balloon trying to open up on event box on mousehover.
is there any way to make padding from top to trendline ?
using AmStock chart v.3
thanks
Answer: You can solve this by setting minMaxMultiplier: http://docs.amcharts.com/3/javascriptstockchart/ValueAxis#minMaxMultiplier
for your value axis. If you are using JSON for chart config, add this to panel config:
valueAxes:[{minMaxMultiplier:1.05}]
if you do it using JavaScript API, then set:
var valueAxis = new AmCharts.ValueAxis();
valueAxis.minMaxMultiplier = 1.05;
panel.addValueAxis(valueAxis);
This will increase min and max of value axis by 5% and your event should fit.


Como exibir somente metade do background-color da div

Question: Preciso que mostra somente 50% do bg da DIV, tem como?
#coberturas legend{
    font-family: 'Open Sans', Arial, Helvetica, sans-serif;
    padding:10px 20px;
    display:block;
    position:absolute;
    bottom:0;
    box-sizing: border-box;
    background-color:rgba(55,57,62,0.8);
    width:320px;
    text-transform:uppercase;
    transition:all 0.3s;
    -webkit-transition:all 0.3s;

}

esta div está sobreposta a outra;
Comment: Poderias postar também juntamente com a tua pergunta o código com que estás a tentar fazer isto? E se possível adicionar mais detalhes, porque a pergunta parece estar um pouco vaga...
Comment: O que exatamente você quer fazer? O quem tem dentro dessa div? Definir uma altura com `overflow:hidden;` no css não resolve? Precisamos de mais detalhes pra poder te ajudar
Comment: vou editar o post, com o codigo
Comment: era [**disto**](http://pt.stackoverflow.com/a/71222/11886) que estavas à procura @GustavoCardoso ?
Comment: Votei por reabrir, edição 6 parece que já deixou claro o objetivo.
Answer: Eu não sei se queres que seja 50% da div em termos de ser na horizontal, ou se em termos de 50% sendo na vertical. então vou postar aqui duas possíveis maneiras de se fazer isso de ambas as formas.
Este será o suposto HTML para gerar as 2 divs. O id container é incluído apenas para manter as duas divs filho dentro da div pai - container usando a propriedade position:relative; que irás ver no código CSS abaixo após o exemplo do código HTML:

Se estiveres à procura de fazer isso horizontalmente, o CSS será: http://jsfiddle.net/v7ecw3ah/
#container{position:relative;}
#coberturas1 {
    background-color: rgba(55,57,62,0.8);
    width: 50%;
    height: 300px;
}
#coberturas2 {
    background-color: #efc94d;
    width: 50%;
    height: 300px;

    /* código para mostrar apenas 50% da div Cinzenta (coberturas1) */
    position:absolute;
    top:5px; /* muda este valor para "0" - Isto foi apenas mostrar o que está a acontecer por detrás da div */
    right:25%; /* 25% significa metade (que neste caso será 50%) do tamanho de ambas as divs */
}

Se estiveres à procura de fazer isso verticalmente, o CSS será: http://jsfiddle.net/v7ecw3ah/1/
#container{position:relative;}
#coberturas1 {
    background-color: rgba(55,57,62,0.8);
    width: 50%;
    height: 300px;
}
#coberturas2 {
    background-color: #efc94d;
    width: 50%;
    height: 300px;

    /* código para mostrar apenas 50% da div Cinzenta (coberturas1) */
    position:absolute;
    top:150px; /* 150px significa metade (que neste caso será 50%) do tamanho de ambas as divs */
    left:5px; /* muda este valor para "0" - Isto foi apenas mostrar o que está a acontecer por detrás da div */
}

Comment: Isso não vai me ajudar, preciso que a div ainda esteja la, mas só mostre a metade, ou seja a div vai ocupar todo o espaço, porem o background precisa ficar na metade, tinha errado, peço desculpa
Answer: Sendo uma "cor" você pode usar linear-gradient

.horizontal .inner, .vertical .inner, .diagonal .inner {
    width:320px;
    height: 80px;
    margin: 0 0 10px 0;
}

.horizontal .inner {
    background: linear-gradient(to bottom, #00f 0%, #00f 50%, #f00 51%, #f00 100%);
}

.vertical .inner {
    background: linear-gradient(to right, #00f 0%, #00f 50%, #f00 51%, #f00 100%);
}

.diagonal .inner {
    background: linear-gradient(135deg, #00f 0%, #00f 50%, #f00 51%, #f00 100%);
}

        Olá mundo

        Olá mundo

        Olá mundo

Acaso queira compatibilidade com navegadores mais antigos, use estas propriedades:
/*Fallback para navegadores sem suporte*/
background: #00f;

 /* FF3.6+ */
background: -moz-linear-gradient(left, #00f 0%, #00f 50%, #f00 51%, #f00 100%);

/* Chrome,Safari4+ */
background: -webkit-gradient(linear, left top, right top, color-stop(0%, #00f), color-stop(50%, #f00), color-stop(51%,#f00), color-stop(100%,#f00));

/* Chrome10+,Safari5.1+ */
background: -webkit-linear-gradient(left, #00f 0%, #00f 50%, #f00 51%, #f00 100%);

/* Opera 11.10+ (não webkit/blink) */
background: -o-linear-gradient(left, #00f 0%,#00f 50%,#f00 51%, #f00 100%);

/* IE10+ */
background: -ms-linear-gradient(left, #00f 0%,#00f 50%,#f00 51%, #f00 100%);

/* CSS3*/
background: linear-gradient(to right, #00f 0%,#00f 50%,#f00 51%, #f00 100%);

/* Fallback para IE6 ao IE9 */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00f', endColorstr='#f00',GradientType=1 );

Answer: Você pode utilizar essa ferramenta online, mais muito útil pra emular sua div:
http://makewebsimple.net/cssdivbuilder
Pra gerar o gradiente utilizo essa outra ferramenta online:
http://www.colorzilla.com/gradient-editor/
Exp

.teste{
  width: 200px;
  height: 200px;

  border: 1px rgb(89,89,89) solid;

  background: -moz-linear-gradient(top,  rgba(30,87,153,0) 0%, rgba(35,111,183,1) 24%, rgba(41,137,216,0.66) 50%, rgba(32,124,202,0.65) 51%, rgba(125,185,232,0) 100%); /* FF3.6+ */
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(30,87,153,0)), color-stop(24%,rgba(35,111,183,1)), color-stop(50%,rgba(41,137,216,0.66)), color-stop(51%,rgba(32,124,202,0.65)), color-stop(100%,rgba(125,185,232,0))); /* Chrome,Safari4+ */
  background: -webkit-linear-gradient(top,  rgba(30,87,153,0) 0%,rgba(35,111,183,1) 24%,rgba(41,137,216,0.66) 50%,rgba(32,124,202,0.65) 51%,rgba(125,185,232,0) 100%); /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(top,  rgba(30,87,153,0) 0%,rgba(35,111,183,1) 24%,rgba(41,137,216,0.66) 50%,rgba(32,124,202,0.65) 51%,rgba(125,185,232,0) 100%); /* Opera 11.10+ */
  background: -ms-linear-gradient(top,  rgba(30,87,153,0) 0%,rgba(35,111,183,1) 24%,rgba(41,137,216,0.66) 50%,rgba(32,124,202,0.65) 51%,rgba(125,185,232,0) 100%); /* IE10+ */
  background: linear-gradient(to bottom,  rgba(30,87,153,0) 0%,rgba(35,111,183,1) 24%,rgba(41,137,216,0.66) 50%,rgba(32,124,202,0.65) 51%,rgba(125,185,232,0) 100%); /* W3C */
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#001e5799', endColorstr='#007db9e8',GradientType=0 ); /* IE6-9 */
}

No seu caso ficaria algo assim:

.teste {
  width: 500px;
  height: 200px;

  border: 1px rgb(89,89,89) solid;

  background: -moz-linear-gradient(top,  rgba(239,242,48,1) 0%, rgba(41,137,216,1) 50%, rgba(32,124,202,1) 51%, rgba(34,125,203,0) 52%, rgba(125,185,232,0) 100%); /* FF3.6+ */
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(239,242,48,1)), color-stop(50%,rgba(41,137,216,1)), color-stop(51%,rgba(32,124,202,1)), color-stop(52%,rgba(34,125,203,0)), color-stop(100%,rgba(125,185,232,0))); /* Chrome,Safari4+ */
  background: -webkit-linear-gradient(top,  rgba(239,242,48,1) 0%,rgba(41,137,216,1) 50%,rgba(32,124,202,1) 51%,rgba(34,125,203,0) 52%,rgba(125,185,232,0) 100%); /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(top,  rgba(239,242,48,1) 0%,rgba(41,137,216,1) 50%,rgba(32,124,202,1) 51%,rgba(34,125,203,0) 52%,rgba(125,185,232,0) 100%); /* Opera 11.10+ */
  background: -ms-linear-gradient(top,  rgba(239,242,48,1) 0%,rgba(41,137,216,1) 50%,rgba(32,124,202,1) 51%,rgba(34,125,203,0) 52%,rgba(125,185,232,0) 100%); /* IE10+ */
  background: linear-gradient(to bottom,  rgba(239,242,48,1) 0%,rgba(41,137,216,1) 50%,rgba(32,124,202,1) 51%,rgba(34,125,203,0) 52%,rgba(125,185,232,0) 100%); /* W3C */
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#eff230', endColorstr='#007db9e8',GradientType=0 ); /* IE6-9 */

}
  #coberturas{
    font:Lucida Sans;
    display:block;
    bottom:0;
    box-sizing: border-box;
    background-color:#FF9911;

    width:200px;

  }

 Coberturas

      <legend> 29/05/2015 - TUPACIGUARA MG

EXPO CAPITU
</legend>


It may be a strengthening form of mean inequality

Question: Let $a_{i}>0,i=1,2,\cdots,n>2$,show that following inequality
$$\prod_{i=1}^{n}\left(\dfrac{\displaystyle\sum_{j\neq i}a_{j}}{n-1}\right)^{n-1}\ge\left(\dfrac{\displaystyle\sum_{i=1}^{n}\prod_{j\neq i}a_{j}}{n}\right)^n$$
I have found that this inequality feeling can be handled using mean inequality, but I have, finally, found it difficult to handle. Thanks.
For $n=3$ use well konwn $9-8$inequality
$$9(a+b)(b+c)(c+a)\ge 8(a+b+c)(ab+bc+ca)$$
so we have
$$(a+b)^2(b+c)^2(a+c)^2\ge  \dfrac{64}{81}(a+b+c)^2(ab+bc+ac)^2$$
and
$$(a+b+c)^2\ge 3(ab+bc+ca)$$
so we have
$$(a+b)^2(b+c)^2(a+c)^2\ge \dfrac{64}{27}(ab+bc+ca)^3$$
so we have
$$\left(\dfrac{(a+b)}{2}\right)^2\left(\dfrac{b+c}{2}\right)^2\left(\dfrac{c+a}{2}\right)^2\ge\left(\dfrac{ab+bc+ca}{3}\right)^3$$
Comment: I solved your problem. If you want to see my solution, show please your attempts.
Comment: For $n=3$, this means:$$\left(\frac{a+b}2\right)^2 \left(\frac{b+c}2\right)^2 \left(\frac{c+a}2\right)^2\ge \left(\frac{ab+bc +ca}3\right)^3$$
Comment: Yes, of course, but it's obvious. The general case is more interesting.
Answer: Let $\sum\limits_{i=1}^na_i=nu_1,$ $\sum\limits_{1\leq i<j\leq n}a_ia_j=\binom{n}{2}u_2^2,$ ..., $\prod\limits_{i=1}^na_i=u_n^n,$ where $u_k>0$ for any $k$.
Thus, by the Maclaurin's inequality we obtain:
$$u_1\geq u_2\geq...\geq u_n$$ and we need to prove that
$$\prod_{i=1}^n\left(\frac{nu_1-a_i}{n-1}\right)^{n-1}\geq u_{n-1}^{n(n-1)}$$ or
$$\prod_{i=1}^n(nu_1-a_i)\geq(n-1)^nu_{n-1}^n$$ or
$$n^nu_1^n-n^{n-1}u_1^{n-1}\cdot nu_1+n^{n-2}\binom{n}{2}u_1^{n-2}u_2^2+...+(-1)^n\prod_{i=1}^na_i\geq(n-1)^nu_{n-1}^n$$ or
$$\sum_{i=2}^n(-1)^in^{n-i}\binom{n}{i}u_1^{n-i}u_i^i\geq(n-1)^nu_{n-1}^n.$$
Now, consider two cases.

$n$ is odd.

Since the equality in our inequality occurs for $a_1=a_2=...=a_n=1,$ we obtain: $$\sum_{i=2}^n(-1)^in^{n-i}\binom{n}{i}=(n-1)^n.$$
Now for any natural $k$ such that $2\leq k\leq n$ we see that
$$\sum_{i=2}^k(-1)^in^{n-i}\binom{n}{i}=\left(n^{n-2}\binom{n}{2}-n^{n-3}\binom{n}{n-3}\right)+...+$$
$$+\left(n^{n-2j}\binom{n}{2j}-n^{n-2j-1}\binom{n}{2j+1}\right)+...>0$$
because $$n^{n-2j}\binom{n}{2j}-n^{n-2j-1}\binom{n}{2j+1}>0$$ it's
$$\frac{n\cdot n!}{(2j)!(n-2j)!}>\frac{n!}{(2j+1)!(n-2j-1)!}$$ or
$$n(2j+1)>n-2j$$ or
$$2j(n+1)>0,$$ which is obvious.
Thus, by Maclaurin we obtain:
$$\sum_{i=2}^n(-1)^in^{n-i}\binom{n}{i}u_1^{n-i}u_i^i\geq\left((n-1)^n+1\right)u_{n-1}^{n-1}u_1-u_n^n\geq(n-1)^nu_{n-1}^n;$$

$n$ is even.

Since for all even $n>4$ we have $$7<n^{n-2}\binom{n}{2}-n^{n-3}\binom{n}{3}<(n-1)^n-8,$$
by Maclaurin again we obtain:
$$\sum_{i=2}^n(-1)^in^{n-i}\binom{n}{i}u_1^{n-i}u_i^i\geq7u_1^{n-2}u_2^2+\left((n-1)^n-8\right)u_1^2u_{n-2}^{n-2}+u_n^n.$$
Thus, it's enough to prove that
$$7u_1^{n-2}u_2^2+\left((n-1)^n-8\right)u_1^2u_{n-2}^{n-2}+u_n^n\geq(n-1)^nu_{n-1}^n$$
for which it's enough to prove that:
$$7u_1^{n-2}u_2^2+u_n^n\geq8u_{n-1}^n.$$
Now, for any even $n>4$ we have the following reasoning.
$a_i$ are positive roots of the equation:
$$\prod_{i=1}^n(x-a_i)=0$$ or
$$x^n-\binom{n}{1}u_1x^{n-1}+\binom{n}{2}u_2^2x^{n-2}+...+\binom{n}{n-2}u_{n-2}^{n-2}x^2-\binom{n}{n-1}u_{n-1}^{n-1}x+u_n^n=0,$$ which says that the equation
$$u_n^nx^n-\binom{n}{1}u_{n-1}^{n-1}x^{n-1}+\binom{n}{2}u_{n-2}^{n-2}x^{n-2}-\binom{n}{3}u_{n-3}^{n-3}x^{n-3}+\binom{n}{4}u_{n-4}^{n-4}x^{n-4}-...+1=0$$ has $n$ positive roots and by the Roole's theorem we see that the equation
$$\left(u_n^nx^n-\binom{n}{1}u_{n-1}^{n-1}x^{n-1}+\binom{n}{2}u_{n-2}^{n-2}x^{n-2}-\binom{n}{3}u_{n-3}^{n-3}x^{n-3}+\binom{n}{4}u_{n-4}^{n-4}x^{n-4}-...+1\right)^{(n-4)}=0$$ or
$$u_n^nx^4-4u_{n-1}^{n-1}x^3+6u_{n-2}^{n-2}x^2-4u_{n-3}^{n-3}x+u_{n-4}^{n-4}=0$$ has four positive roots, which says that the equation
$$u_n^n-4u_{n-1}^{n-1}x+6u_{n-2}^{n-2}x^2-4u_{n-3}^{n-3}x^3+u_{n-4}^{n-4}x^4=0$$ has four positive roots.
Let $a$, $b$, $c$ and $d$ be roots of the last equation and let
$$a+b+c+d=4u,$$ $$ab+ac+bc+ad+bd+cd=6v^2,$$ $$abc+abd+acd+bcd=4w^3$$ and $$abcd=t^4.$$
Thus, $$u=\frac{u_{n-3}^{n-3}}{u_{n-4}^{n-4}},$$
$$v^2=\frac{u_{n-2}^{n-2}}{u_{n-4}^{n-4}},$$
$$w^3=\frac{u_{n-1}^{n-1}}{u_{n-4}^{n-4}}$$ and
$$t^4=\frac{u_{n}^{n}}{u_{n-4}^{n-4}}.$$
Now, $$(a-b)^2(c-d)^2+(a-c)^2(b-d)^2+(a-d)^2(b-c)^2\geq0$$ it's
$$t^4\geq4uw^3-3v^4,$$ which gives
$$\frac{u_{n}^{n}}{u_{n-4}^{n-4}}\geq4\frac{u_{n-3}^{n-3}}{u_{n-4}^{n-4}}\cdot\frac{u_{n-1}^{n-1}}{u_{n-4}^{n-4}}-3\left(\frac{u_{n-2}^{n-2}}{u_{n-4}^{n-4}}\right)^2.$$
Id est, it's enough to prove that:
$$7u_1^{n-2}u_2^2+\frac{4u_{n-3}^{n-3}u_{n-1}^{n-1}}{u_{n-4}^{n-4}}-\frac{3u_{n-2}^{2n-4}}{u_{n-4}^{n-4}}\geq8u_{n-1}^n,$$ which is true because by AM-GM and Maclaurin
$$4u_1^{n-2}u_2^2+\frac{4u_{n-3}^{n-3}u_{n-1}^{n-1}}{u_{n-4}^{n-4}}\geq8\sqrt{\frac{u_1^{n-2}u_2^2u_{n-3}^{n-3}u_{n-1}^{n-1}}{u_{n-4}^{n-4}}}\geq8\sqrt{\frac{u_{n-4}^{n-4}u_{n-1}^2u_{n-1}^2u_{n-1}^{n-3}u_{n-1}^{n-1}}{u_{n-4}^{n-4}}}=8u_{n-1}^n$$ and
$$3u_1^{n-2}u_2^2-\frac{3u_{n-2}^{2n-4}}{u_{n-4}^{n-4}}\geq0$$ it's
$$u_1^{n-2}u_2^2u_{n-4}^{n-4}\geq u_{n-2}^{2n-4},$$ which is obvious by Maclaurin.
Thus, it's enough to prove our inequality for $n=4$.
Can you end it now?
Comment: +1  Thanks, why $\sum_{i=2}^{k}(-1)^i n^{n-i}\binom{n}{i}>0$,and the last inequality I can't prove it.Thanks
Comment: @geromty I added something about your first question.  In my proof of the last inequality I found mistake. Sorry
Comment: @geromty I added something again. See now.
Comment: Please check the line after "n is odd": $i=2$ should be $i=0$? (the binomial theorem); In the line 7-8, there is a typo: $nu$ should be $nu_1$.
Comment: @River Li It should be $i=2$. See please the previous inequality. In your second comment you are right. It was typo. I fixed. Thank you very much!
Comment: I found that $i=0$ and $i=2$ are the same because the sum of the first two terms are zero. In detail, according to the binomial theorem, we have $(n-1)^n = \sum_{i=0}^n(-1)^in^{n-i}\binom{n}{i} = (-1)^0 n^n + (-1)n^{n-1}n + \sum_{i=2}^n(-1)^in^{n-i}\binom{n}{i} = \sum_{i=2}^n(-1)^in^{n-i}\binom{n}{i}$.
Comment: @River Li  Yes of course! I wrote it in the eighth  line.
Comment: Well, I would apply the binomial theorem to get the result different from your reasoning.


Views Grouping by Field

Question: I'm looking to display a list of staff grouped by department.  I've figured out how to do this just fine with one exception.
I have a few staff who's time is split between 2 departments.  However, when I edit their department field and enter more than one department, they show up in a new section.  For example.

Outreach

Joe Smith
jane Smith

Technical Services

Joe Johnson

Outreach, Technical Services

Jane Johnson

Instead of having this separate display, I want Jane Johnson to be listed twice, under both Outreach and Technical Services.
Any ideas?
Comment: How are you assigning the departments to the users? Through taxonomy, or a user field, or some other way?
Comment: Can you add a screenprint about how you defined your view (the screen you get when you "edit" the view? That might help to provide an accurate answer / suggestion (apart from the question reformatting I just applied, I hope).
Comment: @longboardnode raises a good point. If you add the department as a multi value taxonomy field and bring in the relationship in views you might pull this off. Taxonomy has the benefit of allowing you to add departments later on, whereas if it is a list of text then you are stuck should departments be added or removed later on.
Answer: I'm not sure if you've had this answered yet, but in Drupal 7 and the latest version of Views, this is possible by doing the following:
Under Fields, click the one you want to configure, in your case it probably looks something like:
Content: Departments
Select Multiple Field Settings and it will drop-down to where you see a check mark in the box labelled:
Display all values in the same row
Uncheck this box and it should list your members twice, once in each department they are specified under.

Views Grouping by Field


Storing Data in AngularJS on Mobile Devices

Question: I'm currently working on a Mobile WebApp built with AngularJS. The basic functionality is similar to a simple ToDo's app: Create a list of items (with ng-repeat) and mark those items as checked or delete them from the list. Checked items are being pushed into a seperate ng-repeat controller.
My current problem is: If you reload the page or close the app, the list contents are gone. I have to be able to store the data of my ng-repeat controllers to localStorage, IndexedDB, WebSQL, Cookies or whatever solution is the most elegant on mobile devices.
I know there are several solutions out there: There's the $cookies / $cookieStore module of the Angular API, there's a solution based on prestistence.js and so on. But I couldn't figure out wich solution is the best for mobile, cross device. I don't want to restrict the app to certain plattform, though I'm primary aiming at Firefox OS atm.
Thanks for any form of advice!
Answer: If you'd like to store your data in the cloud I recommend using Firebase in conjunction with Angularfire. It will get you up and running in a matter of minutes.
First you include Firebase and AngularFire:

Then you declare firebase as a dependency for your angular app:
var myapp = angular.module('myapp', ['firebase']);

Now all you need to do is bind a Firebase URL to a model in your controller:
myapp.controller('MyCtrl', ['$scope', 'angularFire',
  function MyCtrl($scope, angularFire) {
    var url = 'https://MyFirebaseURL.firebaseio.com/foo';
    $scope.foo = angularFire(url, $scope, 'foo');
  }
]);

Answer: I recommend localStorage. The API is simple and widely supported.