Android: Show spinner at actionbar with fixed title

Question: I would like to have a spinner in the action bar showing the title Options always, no matter which one has been selected.
At the moment the upper box shows the choosed option as soon as it is selected.
How could I achive that ?

this is my code
        MenuItem menuItem = menu.findItem(R.id.actionbar_nextevents);
        if (menuItem!=null){
            Spinner spinner = (Spinner) MenuItemCompat.getActionView(menuItem);
            List<String> list = new ArrayList<String>();
            list.add("Option 1");
            list.add("Option 2");
            list.add("Option 3");
            spinner.setAdapter(new ArrayAdapter<String>(this, R.layout.listitem_nextevents, R.id.option, list));
        }

Comment: Override onSpinnerItemSelected. On item selection, set the title of Spinner to be "Option"
Comment: So what happened with above code?
Answer: Have you tries this :
    MenuItem menuItem = menu.findItem(R.id.actionbar_nextevents);
if (menuItem != null) {
    Spinner spinner = (Spinner) MenuItemCompat.getActionView(menuItem);
    List<String> list = new ArrayList<String>();
    list.add("Options ");
    list.add("Option 1");
    list.add("Option 2");
    list.add("Option 3");
    spinner.setAdapter(new ArrayAdapter<String>(this,
            R.layout.listitem_nextevents, R.id.option, list));
    spinner.setSelection(0);
}

Answer: Try following code
open menu.xml and paste below code
<item
        android:title="select city"
        android:id="@+id/my_menu_spinner"
        yourapp:actionViewClass="android.widget.Spinner"
        yourapp:showAsAction="ifRoom"/>

in your activity class override onCreateOptionMenu() method and write below code
 @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        spinner = (Spinner) menu.findItem(R.id.my_menu_spinner)
                .getActionView(); // find the spinner
            citieslist.add(cityName);
        }

        ArrayAdapter mSpinnerAdapter = new ArrayAdapter<String>(
                this.getSupportActionBar().getThemedContext(),                         R.layout.spinner_item, citieslist);
        mSpinnerAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(mSpinnerAdapter);
return true

}
create file spinne_item.xml in layouts and paste below code
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="top"
    android:singleLine="true"
    android:textColor="#455560" />

Comment: did you even try running this code? you use a variable in its' own initializer statement, before it even exists. -1. moreover, when I run this code, `MenuItem.getActionView()` throws NullPointerException.
Answer: Late reply for those who are still struggling!
The first option of your spinner should be your title!
then when your are handling every option simply put this line at the end.spinner.setSelection(0);
This keeps the title the first option every time an option is selected
example:
switch (position) {
                case 0:
                   //my other methods and...

                    spinner.setSelection(0);
                    break;

                case 1:
                    //my other methods and...

                    spinner.setSelection(0);
                    break;
                case 2:
                    //my other methods and...

                    spinner.setSelection(0);
                    break;


Como instruir o eslint a resolver caminhos absolutos com babel-plugin-root-import em monorepos

Question: Possuo um repositório monorepo feito com yarn e neste tenho um projeto frontend criado com o comando create-react-app. Instalei as libs react-app-rewired e customize-cra para injetar as configurações ao babel do plugin babel-plugin-root-import e estas estão funcionado corretamente,  meu projeto é executado sem erros, segue código do meu arquivo config-overrides.js
const { addBabelPlugin, override } = require('customize-cra');

module.exports = override(
  addBabelPlugin([
    'babel-plugin-root-import',
    {
      rootPathSuffix: 'src',
    },
  ])
);

O problema ocorre com o meu eslint que não reconhece os caminhos dos meus arquivos. Instalei a lib eslint-import-resolver-babel-plugin-root-import para lidar com situação, e acrescentei ao meu arquivo .eslintrc.json a seguinte configuração
"settings": {
  "import/resolver": {
    "babel-plugin-root-import": {
      "rootPathSuffix": "src"
    }
  }
}

Apesar das instruções no arquivo de configuração do eslint estarem de acordo com as instruções na documentação, o eslint continua a não reconhecer os caminhos de arquios como válidos. estou importado meus arquivos da seguinte forma
import SignIn from '~/pages/SignIn';
import SignUp from '~/pages/SignUp';
import Dashboard from '~/pages/Dashboard';
import Profile from '~/pages/Profile';

Answer: O problema ocorre por conta da estrutura de monorepo do projeto. Nas configurações do arquivo eslint o parâmetro de rootPathSuffix do babel-plugin-root-import parte da raiz do projeto e NÃO do diretório onde o arquivo eslint se encontra. Para ficar mais claro, a estrutura abaixo representa um modelo monorepo do yarn.
frontend
- src
- package.json
- .eslintrc.json
mobile
- src
- package.json
- .eslintrc.json
package.json
.editorconfig

Os projetos de frontend e mobile possuem configurações diferentes do eslint, para configurar o babel-plugin-root-import para o projeto de mobile por exemplo, a seguinte configuração é necessária:
"settings": {
  "import/resolver": {
    "babel-plugin-root-import": {
      "rootPathSuffix": "mobile/src"
    }
  }
}

Em qualquer estrutura de pastas do seu projeto, adicione o valor do parâmetro rootPathSuffix de modo que todo o caminho do projeto, indo de sua raiz até o diretório desejado, seja contemplado no valor.


How can I enter an email address into text input field in Edge using Selenium WebDriver?

Question: I have the following program:
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Edge;

namespace ConsoleApplication1
{
    static class Program
    {
        static void Main()
        {
            //var driver = new ChromeDriver();
            var driver = new EdgeDriver();
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(20));
            driver.Navigate().GoToUrl("http://www.cornelsen.de/shop/registrieren-lehrer");
            driver.FindElement(By.Id("email")).SendKeys("email@example.com");
        }
    }
}

When I run this in Chrome or any other browser aside from Edge, then the email adress is entered correctly. But if I try the same thing in Edge, the "@" character is missing. The field displays only "dummyuser.de".
Any idea what I can do?
Comment: trying typing slowly.
Comment: Tried it. No effect.
Comment: Check if you can type "@" manually.
Comment: Of course I can. This is a general problem with edit fields in Selenium with Edge.
Answer: As a workaround, you can set the input value directly via ExecuteScript():
IWebElement email = driver.FindElement(By.Id("email"));

IJavaScriptExecutor js = driver as IJavaScriptExecutor;
string script = "arguments[0].setAttribute('value', 'arguments[1]');";
js.ExecuteScript(script, email, "firstname.lastname@example.com");

Or, what you can do is to create a fake input element with a predefined value equal to the email address. Select the text in this input, copy and paste into the target input.
Not pretty, but should only serve as a workaround:
// create element
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
string script = @"
    var el = document.createElement('input');
    el.type = 'text';
    el.value = 'arguments[0]';
    el.id = 'mycustominput';
    document.body.appendChild(el);
";
js.ExecuteScript(script, "firstname.lastname@example.com");

// locate the input, select and copy
IWebElement myCustomInput = driver.FindElement(By.Id("mycustominput"));
el.SendKeys(Keys.Control + "a");  // select
el.SendKeys(Keys.Control + "c");  // copy

// locate the target input and paste
IWebElement email = driver.FindElement(By.Id("email"));
email.SendKeys(Keys.Control + "v");  // paste

Comment: Your first approach is almost cool. Only thing is that you can spare the `argument[1]` and have `email@example.com` in the string directly: `arguments[0].setAttribute('value', 'firstname.lastname@example.com');`

IT WORKS!!! THANKS SO MUCH!

You will get the bounty.
Comment: @Kimmy good to hear that. Yeah, I just wanted the email to come from outside of the script, just in case you will need to have it configurable. But, yes, you can have it hardcoded into the script as you've shown. Thanks.
Comment: In fact the email address is loaded from XML, but I pass it directly into `setAttribute()` and not to the JavaScript, e.g. `"arguments[0].setAttribute('value', " + myEmailString + ");"`. But it's very cool to pass in the web element as an argument. I didn't know this technique.
Answer: It wasn't as easy as I thought after all. Issues with alecxe's answer:

arguments[0].setAttribute('value', '...'); works only the first time you call it. After calling element.Clear();, it doesn't work any more. Workaround: arguments[0].value='...';
The site doesn't react on the JavaScript call like it would on element.SendKeys();, e.g. change event is not invoked. Workaround: Send the first part of the string up to the last "forbidden" character via JavaScript, the rest via WebElement.SendKeys (in this particular order, bc if you do another JavaScript call to the same field after SendKeys(), there will occur no change event either).

I also realized that there are more "forbidden" characters in Edge, e.g. accented or Eastern European ones (I'm Central European). The problem with 2. is that the last character might be a forbidden character. In this case, I append a whitespace. Which of course affects the test case behavior, but I haven't had any other idea.
Full C# code:
public static void SendKeys(this IWebElement element, TestTarget target, string text)
{
    if (target.IsEdge)
    {
        int index = text.LastIndexOfAny(new[] { '@', 'Ł', 'ó', 'ź' }) + 1;
        if (index > 0)
        {
            ((IJavaScriptExecutor) target.Driver).ExecuteScript(
                "arguments[0].value='" + text.Substring(0, index) + "';", element);
            text = index == text.Length ? Keys.Space : text.Substring(index);
        }
    }

    element.SendKeys(text);
}

Answer: This problem used to occur in old browsers. Apparently it returned in Edge.
You can try sending the string in pieces
IWebElement email = driver.FindElement(By.Id("email"));
email.SendKeys("dummy");
email.SendKeys("@");
email.SendKeys("user.de");

Or try using @ ASCII code
driver.FindElement(By.Id("email")).SendKeys("dummy" + (char)64 + "user.de");

Answer: Have you tried Copy Paste?
Clipboard.SetText("email@example.com");
email.SendKeys(OpenQA.Selenium.Keys.Control + "v");

Hope it could help.
Comment: Really? I have to try. But for this problem, I'm using the JavaScript workaround.
Comment: It *would* help, but unfortunately I have to be able to run the test case on a remote Win10 machine, too.
Comment: Why it wouldnot work on remote win10 machine? Since it's the script itself, it should work the same way no matter test environment is (remote, local, CI, etc ...)
Comment: Because if I put a string in the clipboard, then it will be in the clipboard of the machine that runs the test case, not of the machine where I remote-control the browser.
Comment: It's not true, Kimmy :). It should set clipboard for the remote control (if you run it remotely); and it should set clipboard local (if you run it locally)
Answer: I just added one extra line to click on text field and then send keys, I tried this and its working for me.
Code is written in java, you can change that to any other, if you want.
//INITIALISE DRIVER
WebDriver driver = null;
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.navigate().to("http://www.cornelsen.de/shop/registrieren-lehrer");
driver.manage().window().maximize();

//CLICK EMAIL FIELD, JUST TO HAVE FOCUS ON TEXT FIELD
driver.findElement(By.id("email")).click();
driver.findElement(By.id("email")).sendKeys("email@example.com");

Comment: You are using `FirefoxDriver`. My problem is with Edge, not with Firefox. My sample code works fine in Firefox, even without your extra `click()` before `sendKeys()`.
Comment: I meant, you can try the same logic with edge also, let me know if it doesn't work
Comment: It works with or without extra click in Firefox and it doesn't work with or without extra click in Edge.
Comment: Can you try this: 1. Apply explicit wait until email is clickable 2. Click on it 3. Then type it. If I am understanding correctly, you could type email till dummy but not after that ??
Comment: No effect! The email field contains "dummyuser.de" only.
Answer: Try to clear the Text field first.
try following
driver.FindElement(By.Id("email")).clear().SendKeys("firstname.lastname@example.com");
Comment: Nope! BTW, I posted the entire source code, so you can try yourself before posting.
Answer: I'm the Program Manager for WebDriver at Microsoft. I just tried to reproduce your issue on my home machine (Windows 10 build 10586) and couldn't reproduce. Your exact test entered the '@' symbol fine.
You should check if you have the latest version of Windows 10 and WebDriver. If you hit the Windows key and type "winver" and hit enter it'll open a popup with the Windows version info. You want it to say
Microsoft Windows
Version 1511 (OS Build 10586.104)
This is the latest version of Windows 10 released to the public. If you have this version you'll also need the corresponding version of WebDriver found here:
http://www.microsoft.com/en-us/download/details.aspx?id=49962
Note that if the build is 10240 that you're on the original release build. Our November update added substantial support for new features (like finding elements by XPath and more!) along with bug fixes which might explain your issues.
Lastly I should note we have an Insiders release as well for WebDriver to match with the Insiders program. If you're subscribed to the Insiders program and want to see the newer features and bug fixes for WebDriver you can find the download here:
https://www.microsoft.com/en-us/download/details.aspx?id=48740
Note that it currently supports build 10547 which was actually before the November update. It'll be updated very shortly (next couple of days) to support the latest Windows Insiders flight, build 14267.
Comment: In order to use the WebDriver 2.0, I *needed* to update my Win10 to version 1511. So I am on the most current releases, definitely. Why is the "insiders" WebDriver older than the official one? Looking forward to the next version.
Comment: It was older (it's not updated) because none of the new flights contained updates to WebDriver, so there wasn't a reason to update it for the newer builds. Going forward it will be updated with every release as we've streamlined the process and new insiders builds should have bug fixes for WebDriver.

If you go to the insiders link now it has the newest build (14267) and if you have the equivalent Windows Insiders installed you can use it.
Answer: Sorry but I not agree with the last comment (Program Manager for WebDriver at Microsoft). I can reproduce the problem. This is my configuration:
Target Machine (Hub node where tests are run):
  Win 10 build 10585.104
  MS Edge 25.10586.0.0
  MS EdgeHTML 13.10586
Selenium framework:
  SeleniumHQ (for Java): 2.48.0
I am using Selenium Grid to run my suite. In this case, I was only doing conceptual test of Egde implementing a basic test:
1. Start Hub in local machine (Win 7) opening console (administrator privileges)
2. Register Node in Hub in target remote machine (Win 10 build 10585) opening console (in this case without administrator privileges because in other way edge hangs when create new session).
Setting up my grid and checking that everything is ok when I try to write my account name in login page I can not see the @ and my basic test fails (wrong credentials).
I have introduced @ by hand in the moment edge is opened (interrupt point) and I can see symbol.
I have sent "@@@@@@@@@@@@@@@" to the text field and I can not see any. In summary, I have tried many things and I can not see @
When I started with Web Automation Testing using Selenium (Java) I remember this behaviour in old versions of Firefox and Chrome. I not really sure which one but it was reproducible in old version.
This partial basic code (implementated with pageobject) IS WORKING with Firefox 35.0 and Chrome 48.0.2564.109 but NOT IS WORKING with Edge's version I put at the beginning of my comment.
WebElement element = WebDriverExtensions.findElement(context, By.cssSelector("input[name='username'][type='email']"));
element.clear();
element.sendKeys(email);
Front Developers are using AngularJS and are validating user's text input to match with a welformatted email:

I afraid that current Edge version does not support sendkeys with this kind of character, maybe the problem is front on-line validation and Edge has to suits these situations because they are really common.
Best regards
Comment: ganesh already proposed the `.clear()` thing, but it doesn't work in Edge.
Answer: None of the above worked for me with the version 2.52. This worked for me :
 EdgeDriver edgeDriver = new EdgeDriver("folder of my edge driver containing MicrosoftWebDriver.exe");
 IJavaScriptExecutor js = _edgeDriver as IJavaScriptExecutor;
 js.ExecuteScript("document.getElementById('Email').value = 'firstname.lastname@example.com'");

Make sure to replace the ".getElementById('Email')" with what you should use to find your field with javascript and replace the "folder of my edge driver containing MicrosoftWebDriver.exe" with the correct path.
Good luck!
Comment: I'm using 2.52, too. Your approach is almost exactly the solution I posted on Feb 18 at 15:25 (the accepted answer), only that you locate the element within JavaScript, whereas I locate it *before* the JavaScript call and then pass it in as an argument to the JavaScript, which is cleaner in my opinion. But that's probably a matter of taste! I'm using Selenium PageFactory for locating all my elements, so your approach would be a consistency breach in my context.


Problemas com a query, eu acho, mas não dá erros de php

Question: O form com as textboxes não está a ser mostrado
$session_Nome = $_SESSION['nome'];

$servername = "localhost";
$username = "root";
$password = "";
$db = "aeac";

// Create connection

$conn = mysqli_connect($servername, $username, $password, $db);

 //Check connection

if (!$conn) {
        die("Falha na ligação: " . mysqli_connect_error());
}
else {
    $sqla = "SELECT * FROM admin WHERE $session_Nome='username_Admin'";
    $result = mysqli_query($conn, $sqla);
    if ($result) {
        while($rowa= mysqli_fetch_assoc($result))
        {
            echo 'Nome: <input required type="text" name="nome" value="<?php echo $session_Nome; ?>"style="width: 300px;">

            Email: <input required type="email" name="email" value="<?php echo $rowa["email"]; ?>"style="width: 300px;">

            Senha: <input required type="password" name="password" value="<?php echo $rowa["password_Admin"]; ?>"style="width: 300px;">

';
        }
    }
}

Comment: muda essa linha `$rowa= mysqli_fetch_assoc($result);` por `while($rowa= mysqli_fetch_assoc($result))`
Comment: Continuo com o mesmo problema
Comment: Porque é que está a usar ``
Comment: @IazyFox, Ta usando sim
Comment: @RedCandy qual é a linha 86?
Comment: A linha 86 é Email:'"style="width: 300px;">
Comment: Neste momento não está a mostrar o form, portanto penso que seja problemas na query?
Comment: Posta um var_dump da variável $sqla
Comment: string(51) "SELECT * FROM admin WHERE RedCandy='username_Admin'"
Answer: Nessa linha
$sqla = "SELECT * FROM admin WHERE $session_Nome='username_Admin'";

troca as aspas simples de lugar
assim:
$sqla = "SELECT * FROM admin WHERE '$session_Nome'=username_Admin";

Comment: Perfeito, obrigado!


Confirming my procedure while doing a surface integral.

Question: "The area bounded by the curve r = 2R cos θ has a surface charge density: $$σ(r, θ)=σ\frac{r}{R}sin^4θ$$
What is the total amount of charge?"
This was a seemingly easy question in an assignment that stumped me. I know it's a physics question, but I was stuck on the math.
My procedure:
Now, the given surface is a circle. Since charge density was given, I just had to integrate over the surface of the circle. Is it correct if I just write $\int_{-\pi/2}^{\pi/2}\int_0^{2Rcos\theta}\sigma(r,\theta)rdrd\theta$ ? Or is there any other way to do this?
My answer came out to be $\frac{32\sigma R^2}{105}$, but I'm not sure if it's right.
Answer: The polar coordinates are the natural way to integrate the total given the functional forms of the boundary and the density. You have the right set up and the result
$$\int_{-\pi/2}^{\pi/2}\int_0^{2Rcos\theta}\sigma(r,\theta)rdrd\theta$$
$$=\frac{\sigma}{R}\int_{-\pi/2}^{\pi/2}\sin^4\theta \int_0^{2Rcos\theta}r^2drd\theta$$
$$=\frac{8\sigma R^2}{3}\int_{-\pi/2}^{\pi/2}\sin^4\theta\cos^3\theta d\theta$$
$$=\frac{8\sigma R^2}{3}\int_{-\pi/2}^{\pi/2}(\sin^4\theta - \sin^6\theta)d(\sin\theta) $$
$$=\frac{8\sigma R^2}{3}\left(\frac25 - \frac27\right)=\frac{32}{105}\sigma R^2$$


How to prove $\mathop {\lim }\limits_{x \to {\rm{ + }}\infty } f'(x){\rm{ = 0}}$

Question: Today I have came across a problem.It is harder than I think.

Given that

(1) $f(x)$ is differentiable on $\left[ {{\rm{0}},{\rm{ + }}\infty } \right)$,
(2) $f'(x)$ is uniformly continuous on $\left[ {{\rm{0}},{\rm{ + }}\infty } \right)$, and
(3) $\mathop {\lim }\limits_{x \to {\rm{ + }}\infty } f(x)$ is existent, prove that $$\mathop {\lim }\limits_{x \to {\rm{ + }}\infty } f'(x){\rm{ = 0}}.$$

If not, is there any counter example? (I've been working on this for a long time.)
Comment: Intuitively, $f$ has a horizontal asymptote at $+\infty$, and uniform continuity of $f'$ means the derivative can't oscillate "too wildly".
Answer: FIRST METHOD :
Just write
$$f(x)=f(0)+\int_0^x f'(t) dt$$
Because $f$ has a limit, you deduce that the integral of $f'$ converges. And because $f'$ is uniformly continuous, this implies that $f'$ tends to $0$ (see for example A uniformly continuous function whose integral $\int_0^\infty f(x)dx$ exists converges to zero)
SECOND METHOD :
Let $\varepsilon >0$.
By uniform continuity of $f'$ applied with $\varepsilon'=\varepsilon/2 >0$, there exists $\delta >0$ such that for all $x,y \in [0,+\infty)$ such that $|x-y| \leq \delta$, then $|f'(x)-f'(y)|\leq \varepsilon/2$.
Then, you know that $f(x)$ has a limit $l \in \mathbb{R}$ when $x$ tends to $+\infty$ : in particular, with $\varepsilon''=\delta\varepsilon/4 >0$, you deduce there exists $A \in \mathbb{R}_+$ such that for all $x\geq A$, $|f(x)-l|\leq \delta\varepsilon/4$. In particular, for all $x,y \geq A$, you have $|f(x)-f(y)|\leq \delta\varepsilon/2$.
Now fix an $x \geq A$. By the MVT, there exists $c \in [x,x+\delta]$ such that
$$\frac{f(x+\delta)-f(x)}{\delta}=f'(c)$$
But $|x-c|\leq \delta$, so $|f'(x)-f'(c)|\leq \varepsilon/2$. You deduce that
$$|f'(x)|\leq |f'(x)-f'(c)|+|f'(c)| \leq \frac{\varepsilon}{2} + \frac{|f(x+\delta)-f(x)|}{\delta} \leq \frac{\varepsilon}{2} + \frac{\delta\varepsilon}{2\delta} = \varepsilon$$
This proves that $\forall \varepsilon >0, \exists A \in \mathbb{R}_+, \forall x \geq A, |f'(x)|\leq \varepsilon$, i.e. that $f'(x)$ tends to $0$ in $+\infty$.
Comment: Thanks.That's great.Emm...But there comes a new challenge: If using intergration is not allowed(since it is an exercise before content of intergration in my textbook), how to solve the problem ?
Comment: I am pretty sure you can solve the question with an $\varepsilon-\delta$ proof. I would say, it *has* to work ! I will think about it if I have time.
Comment: @sraungJo Here is your $\varepsilon-\delta$ proof !
Comment: @TheSliverDoe Thanks a lot!


Por que Arrays implementa IEnumerable mas não implementa IEnumerable?

Question: Estava fazendo uma classe que contém um Array da classe Episode:
public Episode[] EpisodesList;

Aí implementei o IEnumerable<T> na minha classe. E como esperado, implementei o método GetEnumerator()...
        public IEnumerator<Episode> GetEnumerator()
        {
            return ((IEnumerable<Episode>)this.EpisodesList).GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

No entanto, não funciona sem o casting...
Mas só implementando o IEnumerable (sem ser o IEnumerable<T>), funciona normal, sem casting:
    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.EpisodesList.GetEnumerator();
    }

Por que isso?
Answer: Array definitivamente implementa IEnumerable<T>.
Experimente fazer
bool isIEnumerableGeneric = EpisodesList is IEnumerable<Episode>

e verá que o resultado é true.
A razão do comportamento que descreve deve-se, segundo eu entendi da documentação, é que a implementação só é "disponibilizada" (provided) em tempo de execução e por isso a interface genérica não aparece na "declaration syntax" da classe Array.
Trecho retirado da documentação:

Starting with the .NET Framework 2.0, the Array class implements the System.Collections.Generic.IList, System.Collections.Generic.ICollection, and System.Collections.Generic.IEnumerable generic interfaces. The implementations are provided to arrays at run time, and as a result, the generic interfaces do not appear in the declaration syntax for the Array class. In addition, there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations). The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throw NotSupportedException.

Que traduzindo para o português é:

A partir do .NET Framework 2.0, a classe Array implementa as interfaces genéricas System.Collections.Generic.IList, System.Collections.Generic.ICollection e System.Collections.Generic.IEnumerable. As implementações são disponibilizadas para os arrays em tempo de execução, e como resultado, as interfaces genéricas não aparecem na sintaxe de declaração da classe Array. Adicionalmente, não há tópicos referenciados para membros de interface que são acessíveis apenas ao efetuar-se cast de um array para um tipo interface genérico (implementações explícitas de interface). O importante é estar atento que quando você efetua o cast de um array para uma destas interface é que os memebros que adicionam, inserem, ou removem elementos lançam NotSupportedException.
Comment: Tomei a liberdade de adicionar uma tradução do trecho em inglês, caso não se importe.
Comment: De modo algum. Assim ficou mais completa.


How to include a specific range only in a pdf exported from a Google Sheets spreadsheet

Question: I have a sheet that I would like to send a specific range (A1:O44) as a pdf document and leave out further information in other cells. Currently, it is all functioning to send these sheets and all is working fine, however, I cannot seem to get the script correct to limit it to a certain range in the sheet.
There are 2 tabs in the sheet and I would like both of those to be sent in one email as part of the same attachment (as is currently set up). The email is generated by clicking the submit button from the custom submit menu on the top:
https://docs.google.com/spreadsheets/d/1EFJKr9281PND_h8TXNeumaCXb8KWLJQw9Itn0i_AZmI/edit#gid=1494149448
function onOpen() {
  var ui = SpreadsheetApp.getUi();
  // Or DocumentApp or FormApp.
  ui.createMenu('SUBMIT')
      .addItem('SUBMIT', 'menuItem1')
      .addToUi();
}

function menuItem1() {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
     sendSheetToPdfwithA1MailAdress();

}

function sendSheetToPdfwithA1MailAdress(){ // this is the function to call
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheetByName("TEAM1"); // it will send sheet 0 which is the first sheet in the spreadsheet.
  // if you change the number, change it also in the parameters below
  var practiceName = sh.getRange('E2').getValue()
  var startDate = sh.getRange('I4:L5').getValue();
  var emailBody = sh.getRange('I45').getValue();
  var staffName = sh.getRange('c43').getValue()
var shName = Utilities.formatString('%s %s',practiceName, startDate)
var message = ""
        + "
Hi,"
        + "

"
        + " Please find attached the payroll info for " + practiceName + " for the period " + startDate + "."
        + "

"
        + "" + emailBody + "."
        + "

"
        + " If you have any question please let me know"
        + "

"
        + "Thanks, " + staffName + "."
        + "

"
        + "";
  sendSpreadsheetToPdf(0, shName, sh.getRange('A46').getValue(),"Payroll Summary", " " + message + " ");
}
function sendSpreadsheetToPdf(sheetNumber, pdfName, email,subject, htmlbody) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheetByName("TEAM1");
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var spreadsheetId = spreadsheet.getId()
  var sheetId = sheetNumber ? spreadsheet.getSheets()[sheetNumber].getSheetId() : null;
  var url_base = spreadsheet.getUrl().replace(/edit$/,'');
  var email2 = sh.getRange('A47').getValue();
  var email3 = sh.getRange('A48').getValue();

  var url_ext = 'export?exportFormat=pdf&format=pdf'   //export as pdf

      + (sheetId ? ('&gid=' + sheetId) : ('&id=' + spreadsheetId))
      // following parameters are optional...
      + '&size=A4'      // paper size
      + '&portrait=false'    // orientation, false for landscape
      + '&fitw=true'        // fit to width, false for actual size
      + '&sheetnames=true&printtitle=false&pagenumbers=true'  //hide optional headers and footers
      + '&gridlines=false'  // hide gridlines
      + '&fzr=false';       // do not repeat row headers (frozen rows) on each page

  var options = {
    headers: {
      'Authorization': 'Bearer ' +  ScriptApp.getOAuthToken(),
    }
  }

  var response = UrlFetchApp.fetch(url_base + url_ext, options);
  var blob = response.getBlob().setName(pdfName + '.pdf');
  if (email) {
    var mailOptions = {
      attachments:blob, htmlBody:htmlbody, email2:email2
    }
MailApp.sendEmail(
      email,
      subject+" (" + pdfName +")",
      "html content only",
      mailOptions);

MailApp.sendEmail(
      email2,
      subject+" (" + pdfName +")",
      "html content only",
      mailOptions);

MailApp.sendEmail(
      email3,
      subject+" (" + pdfName +")",
      "html content only",
      mailOptions);
  }
}

Answer: Disclaimer: I don't believe the use of query parameters to control the PDF export is officially supported by Google, but this GitHub Gist from Spencer-Easton has the info you need to accomplish your goal.
The issue is in the query parameters stored in url_ext.
You must include the gid, which you can get from the sheet's URL from the sheet editor (/edit#gid=NUMBERS).
You need to add to url_ext:

gid=NUMBERS (look in URL to get numbers)
ir=false (unknown what it refers to)
ic=false (unknown what it refers to)
r1=0 (starting row, zero index)
c1=0 (starting col, zero index)
r2=43 (end row, note change of index)
c2=14 (end col, note change of index)

I added those and was able to email just the selected portions of the selected sheet.
Comment: Awesome! thanks so much for the dwmorrin! it worked perfectly for fitting to the range. So greatful.


Let $S = \{x \in \mathbb{R}| x < a_n \hspace{2mm}\text{for infinitely many $a_n$}\}$. Find a subsequence converging to $\sup S$

Question: Let $(a_n)_{n\in\mathbb N}$ be a bounded sequence. Let $S = \{x \in \mathbb{R}| x < a_n \hspace{2mm}\text{for infinitely many $a_n$}\}$. Prove there exists a subsequence converging to supremum of $S$.
The part about "infinitely many terms" is confusing me a bit. Any help would be appreciated.
Comment: Welcome to the site! The "infinitely many terms" means that if $x\in S$ then there exists infinitely many different $k\in \mathbb{N}$ such that $x<a_{k}$.
Comment: How would I use this fact to construct a subsequence?
Comment: Do you have Bolzano-Weierstrass theorem? In that case can you find a $a_{n_{k}} \in [\sup S-\frac{1}{k}, \sup S]$ for every $k\in \mathbb{N}$?
Comment: "The part about "infinitely many terms" is confusing me a bit"  Consider $A\subset \{a_n\}$ is an infinite subset.  Then if $x < \alpha$ for all $\alpha \in A$ then $x \in S$.  $S = \{x\in \mathbb R|$ so that for *any* infinite subset of $\{a_n\}$, then $x$ is less than all the values in the subset$\}$....  Now the way I see it, you can easily show $\sup S = \sup \{a_n\}$.  Do you see how?
Comment: But then what will the convergent subsequence be? Or how does this imply that a subsequence exists?
Answer: Define
$$
\xi_N:=\sup_{k\ge N}a_n
$$
So $\{\xi_N\}_{N\in\Bbb N}$ is a decreasing sequence, thus it admits limit $L$, which is finite, since $\{a_n\}_n$ is bounded by hypothesis.
Prove by yourself that $\{\xi_N\}_{N\in\Bbb N}$ is (one of the possible) sequence you are searching for, and $L=\sup S$.
Usually one refers to such a limit as $\limsup_{n\to\infty}a_n$.
Comment: Why is this an increasing sequence?
Comment: $\xi_{N+1}$ is the $\inf$ on a strictly smaller subset than $\xi_{N}$
Comment: Consider the alternating sequence $a_n = (-1)^n$. Then the limit of your epsilon sequence would be -1. But this is clearly not the limit superior of $a_n$ which is 1. Did you mean to write sup in your definition of the sequence epsilon?
Comment: I may be wrong somewhere above
Comment: @MattAdamBarnes: you're right, thanks
Answer: Hint: Let $\alpha = \sup S$. There are either (i) infinitely many $a_n$ with $a_n\geq \alpha$ or (ii) infinitely many $a_n$ with $a_n<\alpha$ (both could be true).
Suppose (i) is true. Then for all $k$, we find that $\alpha+\frac1k\not\in S$ so there are only finitely many $a_n$ with $a_n>\alpha+\frac1k$. Considering (i), this means there are infinitely many $a_n$ satisfying $\alpha\leq a_n\leq \alpha+\frac1k$. Construct a subsequence $a_{n_k}$ with $a_{n_k}\to \alpha.$
If (ii) is true, a similar approach is applied to $\alpha-\frac1k$. Since $\alpha-\frac1k\in S$, there are infinitely many $a_n$ with $a_n>\alpha-\frac1k$. If $(\alpha-\frac1k,\alpha)$ contains an infinite number of $a_n$ terms, then the argument is similar to case (i). Otherwise, it must be true that an infinite number of $a_n$ satisfy $a_n\geq \alpha$, in which case we are in case (i).


Select points from Folium map in a PyQt5 widget

Question: I am fairly new to pyqt5 but I am able to display a Folium map using the PyQt5 QWebEngineView widget, and I can place a button on top of the map.
I want to be able to click the button and that the next click on the map saves the place where I clicked, i.e the lat,lon coordinates. But I do not know how to interact with the map in that manner.
I tried obtaining the position of the click in terms of pixels, but I can not translate it to lat,lon because I can not obtain the coordinates of the bounds of the map at the moment I click, note that the map can be moved around with the cursor too. Thank you for your help
class FoliumDisplay(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Folium map in PyQt')
        self.window_width, self.window_height = 1200, 800
        self.setMinimumSize(self.window_width, self.window_height)
        layout = QVBoxLayout()
        self.setLayout(layout)

        coordinate = (51.301100, 5.272991)
        m = folium.Map(
            tiles='Stamen Terrain',
            zoom_start=4,
            location=coordinate)
        # save map data to data object
        data = io.BytesIO()
        m.save(data, close_file=False)

        webView = QWebEngineView() # start web engine
        webView.setHtml(data.getvalue().decode()) #give html of folium map to webengine
        layout.addWidget(webView)

        #### CEATE SELECT  BUTTON
        self.button_select_point = QPushButton(self)
        font = QtGui.QFont()
        font.setFamily("Bauhaus 93")
        font.setPointSize(10)
        self.button_select_point.setFont(font)
        self.button_select_point.setGeometry(QRect(100,20,200,50))
        self.button_select_point.setText("Select one point")
        self.button_select_point.clicked.connect(self.clicked_button_select_point)

    def clicked_button_select_point(self):
        print("Clicked")

Answer: folium is made to produce HTML based on the previous settings but it unnecessarily complicates the communication between the page events and Qt. In these cases it is better to implement the logic using QtWebChannel where a QObject is used to exchange the information.
import json
import os
import sys
from pathlib import Path

from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets, QtWebChannel

CURRENT_DIRECTORY = Path(__file__).resolve().parent

class MapManager(QtCore.QObject):
    clicked = QtCore.pyqtSignal(float, float)

    @QtCore.pyqtSlot(str, str)
    def receive_data(self, message, json_data):
        data = json.loads(json_data)
        if message == "click":
            self.clicked.emit(data["lat"], data["lng"])

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self._was_clicked = False

        self.button = QtWidgets.QPushButton("Press me")
        self.label = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)

        view = QtWebEngineWidgets.QWebEngineView()
        map_manager = MapManager(self)
        channel = QtWebChannel.QWebChannel(view)
        channel.registerObject("map_manager", map_manager)
        view.page().setWebChannel(channel)
        filename = os.fspath(CURRENT_DIRECTORY / "index.html")
        url = QtCore.QUrl.fromLocalFile(filename)
        view.load(url)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.button)
        lay.addWidget(self.label)
        lay.addWidget(view)

        map_manager.clicked.connect(self.handle_map_clicked)
        self.button.clicked.connect(self.handle_button_clicked)

    def handle_map_clicked(self, lat, lng):
        if self._was_clicked:
            self.label.setText(f"latitude: {lat} longitude: {lng}")
        self._was_clicked = False

    def handle_button_clicked(self):
        self._was_clicked = True

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

    w = Widget()
    w.show()

    sys.exit(app.exec_())

index.html
<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

  <link
    rel="stylesheet"
    href="https://email@example.com/dist/leaflet.css"
    integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
    crossorigin=""
  />

Answer: If you insist or prefer using folium. You can add a custom javascript to your folium map and console.log the click event coordinates. As per this answer by @eyllanesc you can add javascript console message handler.
Sample Code:
import folium
import io
import sys
import json
from branca.element import Element
from PyQt5 import QtCore, QtGui, QtWidgets

from PyQt5.QtWebEngineWidgets import QWebEnginePage, QWebEngineView

class WebEnginePage(QWebEnginePage):
    def __init__(self, parent):
        super().__init__(parent)
        self.parent = parent

    def javaScriptConsoleMessage(self, level, msg, line, sourceID):
        print(msg) # Check js errors
        if 'coordinates' in msg:
            self.parent.handleConsoleMessage(msg)

class FoliumDisplay(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Folium map in PyQt')
        self.window_width, self.window_height = 1200, 800
        self.setMinimumSize(self.window_width, self.window_height)
        layout = QtWidgets.QVBoxLayout()
        self.setLayout(layout)

        coordinate = (51.301100, 5.272991)
        m = folium.Map(
        tiles='Stamen Terrain',
        zoom_start=4,
        location=coordinate)

        #Add Custom JS to folium map
        m = self.add_customjs(m)
        # save map data to data object
        data = io.BytesIO()
        m.save(data, close_file=False)

        webView = QWebEngineView() # start web engine
        page = WebEnginePage(self)
        webView.setPage(page)
        webView.setHtml(data.getvalue().decode()) #give html of folium map to webengine
        layout.addWidget(webView)

        #### CEATE SELECT  BUTTON
        self.button_select_point = QtWidgets.QPushButton(self)
        font = QtGui.QFont()
        font.setFamily("Bauhaus 93")
        font.setPointSize(10)
        self.button_select_point.setFont(font)

        self.button_select_point.setGeometry(QtCore.QRect(100,20,200,50))
        self.button_select_point.setText("Select one point")     self.button_select_point.clicked.connect(self.clicked_button_select_point)

        self.label = QtWidgets.QLabel()
        layout.addWidget(self.button_select_point)
        layout.addWidget(self.label)

    def add_customjs(self, map_object):
        my_js = f"""{map_object.get_name()}.on("click",
                 function (e) {{
                    var data = `{{"coordinates": ${{JSON.stringify(e.latlng)}}}}`;
                    console.log(data)}});"""

        e = Element(my_js)
        html = map_object.get_root()
        html.script.get_root().render()
        # Insert new element or custom JS
        html.script._children[e.get_name()] = e

        return map_object

    def clicked_button_select_point(self):
        print("Clicked")

    def handleConsoleMessage(self, msg):

        data = json.loads(msg)
        lat = data['coordinates']['lat']
        lng = data['coordinates']['lng']
        coords =  f"latitude: {lat} longitude: {lng}"
        self.label.setText(coords)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

    w = FoliumDisplay()
    w.show()

    sys.exit(app.exec_())


Exportar relatório do ReportViewer para CSV

Question: No ReportViewer usando Winforms, quando crio o relatório só tenho a opção de exportar para PDF, Excel e Word e preciso adicionar a opção de exportar em CSV.
Comment: Não consegui nenhuma dica para o RDL ou RDLC. Já com o Crystal Reports (RPT), o CSV já e uma opção natural para exportação.
Comment: pelo q procurei  na net tbm tive isso de resposta...vlw
Comment: Se você tiver o controle do DataSet pode utilizar isso http://stackoverflow.com/a/8810229/6809703, que seria DataSet->CSV, ou então poderia exportar para Excel para depois transformar em CSV, que da pra fazer tudo programaticamente.
Comment: Pode oferecer mais detalhes, afim de que possa montar um exemplo?
Comment: Usando o Report Server é possível exportar para Excel, MHTML, PDF, TIFF, XML, and CSV. Já o Report  local não permite, o jeito é buscar alternativas conforme colocado pelos outros comentários. Este link mostra como fazer um hack que permite exportar local para MSWord, que não é uma opção nativa para o ReportViewer no windows, o processo é trabalhoso mas talvez você consiga reproduzir para CSV: https://www.codeproject.com/Articles/23966/Report-Viewer-generate-reports-MS-Word-formats
Comment: pode te ajudar https://stackoverflow.com/questions/32325592/export-to-csv-in-localreport-of-reportviewer-of-winform
Answer: private void reportViewer_Load(object sender, EventArgs e) { var fieldInfo = typeof(Microsoft.Reporting.WinForms.RenderingExtension).GetField("m_isVisible", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

foreach (var extension in this.reportViewer.LocalReport.ListRenderingExtensions())
{
    if (string.Compare("EXCELOPENXML", extension.Name) == 0)
        fieldInfo.SetValue(extension, true);
}}

Answer: public override IEnumerable<ExcelExportInfo> ListExcelExportInfo()
{
    if (this.ExportToExcel == null)
    {
        List<ExcelExportInfo> list = new List<ExcelExportInfo>();

        Microsoft.ReportingServices.Rendering.ExcelRenderer.ExcelRenderer renderer = new Microsoft.ReportingServices.Rendering.ExcelRenderer.ExcelRenderer();
        list.Add(new ExcelExportInfo("Excel", renderer.LocalizedName, true, typeof(Microsoft.ReportingServices.Rendering.ExcelRenderer.ExcelRenderer), true));

        this.ExportToExcel = list;
    }
    return this.ExportToExcel;
}

Answer: using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Microsoft.Reporting.WinForms;

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // Carregue seu relatório no ReportViewer
        this.reportViewer1.LocalReport.ReportPath = "CaminhoDoSeuRelatorio.rdlc";
        this.reportViewer1.RefreshReport();
    }

    private void ExportToCsv(string filePath, string content)
    {
        File.WriteAllText(filePath, content, Encoding.UTF8);
    }

    private void btnExportToCsv_Click(object sender, EventArgs e)
    {
        // Obtém os dados do relatório
        Warning[] warnings;
        string[] streamids;
        string mimeType;
        string encoding;
        string extension;

        byte[] bytes = reportViewer1.LocalReport.Render(
            "CSV", null, out mimeType, out encoding, out extension, out streamids, out warnings);

        // Salva o conteúdo CSV em um arquivo
        string filePath = "CaminhoDoArquivo.csv";
        ExportToCsv(filePath, Encoding.UTF8.GetString(bytes));

        MessageBox.Show("Exportado para CSV com sucesso!");
    }
}

Neste exemplo:
btnExportToCsv_Click é o manipulador de evento do botão que aciona a exportação para CSV.
ExportToCsv é uma função auxiliar que escreve o conteúdo CSV em um arquivo.
Certifique-se de substituir "CaminhoDoSeuRelatorio.rdlc" e "CaminhoDoArquivo.csv" pelos caminhos corretos do seu relatório e do local onde você deseja salvar o arquivo CSV.
Note que este é apenas um exemplo básico, e a geração de CSV pode variar dependendo da estrutura do seu relatório. Certifique-se de ajustar o código conforme necessário para atender às suas necessidades específicas.
Comment: Parece que o [LocalReport não renderiza CSV](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/ms252172(v=vs.100)) e que os formatos suportados são apenas Excel, PDF, Word e Imagem pois não é extensível.


Best (fastest) way to generate ~billion VIN's in PostgreSQL

Question: How to generate ~billion VIN numbers very-very fast ( < 1hour )?
Now I use this query:
INSERT INTO vins (number)
SELECT p.number FROM (
    SELECT generate_series(1,10000000) AS num,
           upper(substring(md5(random()::text) from 0 for 16)) AS number
    ) p
ON CONFLICT DO NOTHING;

This method is very slow. Besides, it generate only small part of data and need to be manually rerun.
Any ideas?
Comment: It will get much faster if you remove all indexes and constraints from the table first (recreate them afterwards). Besides, entering a billion rows will *always* be time consuming.
Comment: Thanks! Goog hint about indexes & constraints.
Comment: Is your hardware capable of loading a billion rows in less than an hour?
Comment: I don't thing so. Maybe if I will manage this database only with hard limited queries - than yes, I think so.
Answer: In addition to dropping indexes and constraints as suggested by @Laurenz Albe set the table unlogged while inserting.
Storing the vin number as bytea cuts its size by more than half making it faster both for inserting and searching
create table vins (number bytea primary key);

alter table vins set unlogged;

explain analyze
insert into vins (number)
select decode(left(md5(random()::text),16), 'hex')
from generate_series(1,10000000) s
on conflict do nothing;
                                                               QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------------
 Insert on vins  (cost=0.00..37.50 rows=1000 width=32) (actual time=246576.200..246576.200 rows=0 loops=1)
   Conflict Resolution: NOTHING
   Tuples Inserted: 9976941
   Conflicting Tuples: 23059
   ->  Function Scan on generate_series s  (cost=0.00..27.50 rows=1000 width=32) (actual time=1633.756..56257.494 rows=10000000 loops=1)
 Planning time: 0.097 ms
 Execution time: 246661.084 ms

Turn logging back on:
alter table vins set logged;

To search:
select
    encode(number, 'hex') hex_representation,
    pg_column_size(number) bytea_storage_size,
    pg_column_size(encode(number, 'hex')) text_storage_size
from vins
where number = decode('987ce0e63614afbb', 'hex')
;
 hex_representation | bytea_storage_size | text_storage_size
--------------------+--------------------+-------------------
 987ce0e63614afbb   |                  9 |                20


How to integrate many-to-one field into django form

Question: I have three model classes like these: InstallationReportPartInstance has a many-to-one relationship to InstallationReportData.
class InstallationReportData(FormData):
    installationDate = models.DateField(null=True, blank=False, verbose_name="Date of Installation")
    deliveryOrder = models.CharField(null=True, blank=True, max_length=255, verbose_name="Delivery Order")
    unitSerialNumber = models.CharField(null=True, blank=False, max_length=255, verbose_name="Unit S/N")
    unitHours = models.DecimalField(null=True, blank=False, decimal_places=2, max_digits=5, verbose_name="Unit Hours")
    visualInspection = models.BooleanField(default=False, verbose_name="Visual Inspection")
...

class InstallationReportPartDefinition(models.Model):
    deviceType = models.CharField(max_length=3, choices=DeviceProfile.TYPE_DEVICE, default='E', verbose_name="Device Type")
    productCode = models.CharField(max_length=32, blank=False, null=False, unique=True, verbose_name="Product Code")
    itemDescription = models.CharField(max_length=1023, blank=False, null=False, verbose_name="Item Description")
    quantity = models.CharField(max_length=255, blank=False, null=False, verbose_name="Quantity")

class InstallationReportPartInstance(models.Model):
    definition = models.ForeignKey(InstallationReportPartDefinition, on_delete=models.CASCADE, related_name="instances", verbose_name="Definitions")
    installationReport = models.ForeignKey(InstallationReportData, on_delete=models.CASCADE, related_name="parts", verbose_name="Installation Report")
    received = models.BooleanField(default=False, blank=True, verbose_name="Received")
    installed = models.BooleanField(default=False, blank=True, verbose_name="Installed")

I have a form for InstallationReportData that should look like this:
Other form fields...

| Product Code | Description | Quantity | Received | Installed |
|    xxx1      |   desc1     |  2 items |    YES   |     NO    |
|    xxx2      |   desc2     |  1 set   |    NO    |     NO    |
|    xxx3      |   desc3     |  2 items |    YES   |     NO    |

Or, in real:

So, the view is like this:
class InstallationReportView(BaseCreationView):
    model = InstallationReportData
    form_class = InstallationReportDataForm
    template_name = 'mism_web/forms/installation_report.html'
    permission_denied_message = "You do not have permission to fill installation report data."
    parts = None

    # Create and set needed parts as instance variable.
    def get_initial(self):
        super(InstallationReportView, self).get_initial()
        device_type = self.workflow.device.device_type
        if device_type is not None:
            self.parts = InstallationReportPartDefinition.objects.filter(deviceType=self.workflow.device.device_type)

    # set context for parts
    def get_context_data(self, **kwargs):
        context = super(InstallationReportView, self).get_context_data(**kwargs)
        context['parts'] = [InstallationReportPartInstance(definition=p, installationReport=None, received=False, installed=False) for p in self.parts]
        return context

Template code for parts (inside the form) looks like this:
    Other form fields...

            Product Code
            Item Description
            Quantity
            Received
            Installed

        {% for part in parts %}

            {{ part.definition.productCode }}
            {{ part.definition.itemDescription }}
            {{ part.definition.quantity }}

                    <input id="id_part_received_{{ part.definition.pk }}" type="checkbox" />

                    <input id="id_part_installed_{{ part.definition.pk }}" type="checkbox" />

        {% endfor %}

Now, I don't know how to set the part instance values for the InstallationReportData form in form_valid method. Can you help me understand how to get this done? I have been stuck for a day and I can't really figure out how to do this.
Answer: The easiest way is to not create fields manually like that, but rather to use Django's Form fields. The relevant one here is the ModelChoiceField
Comment: I don't think this provides what I need.
Comment: @nakiya can you elaborate? You want a way for users to pick the corresponding model for your foreign key in a form, right?
Comment: @udadub: um, not  really, I not only ant to pick multiple corresponding models for the foreign key, I also want to edit values of those multiple models at the same time.


Can a truly randomized procedure (e.g. random treatment allocation) result in unbalanced distributions?

Question: Thousands of randomized trials are ongoing or in the planning. These trials rely on randomization procedures (e.g. patients being randomized to either placebo or active drugs) to yield two balanced groups, who do not differ significantly for any imaginable variable.
But what are the chances that such a randomization yields unbalanced groups?
Is there a chance that randomness is not random?
What could the causes be? Is it a technical/software issue or is it mere probability?
Comment: The purpose of randomization is not to guarantee unambiguous results. It is to help establish the validity of the statistical model being used to do the analysis.
Comment: There are ways to guarantee balance (or any desired degree of imbalance) while performing random allocation. You can, for example, do the equivalent of having $w$ white balls and $b$ black balls randomly drawn without replacement. This generalizes to multiple different treatment groups (more colors of balls)
Answer: In the following answer, I'm going to discuss imbalances between the number of subjects allocated to the groups. If you're instead interested in imbalances in covariates, see myth 5 in Senn (2013).
The following is adapted from section 3.2 in Rosenberger & Lachin (2016). If you have two groups and subjects are assigned to the two groups by a fair coin toss, you have complete randomization. To see why complete randomization is sometimes unattractive, let $N_A(i)$ be the number of patients randomized to treatment $A$ after $i$ patients have been randomized. In the same manner, let $N_B(i) = i-N_A(i)$ be the number of patients randomized to treatment $B$. By the central limit theorem, $N_A(i)$ is asymptotically normal with mean $n/2$ and variance $n/4$. Letting $D_n=N_A(n) - N_B(n) = 2N_A(n)-n$, we see that $D_n$ is asymptotically normal with mean $0$ and variance $n$. The measure $|D_n|$ can be used to describe the degree of imbalance between the groups. For $r>0$,
$$
\operatorname{Pr}(|D_n|>r)\approx 2\left\{1 - \Phi(r/\sqrt{n})\right\}
$$
where $\Phi$ is the standard normal CDF.
Here is a table of the percentiles of the distribution of $|D_n|$ for complete randomization:
<code>n <- c(50, 100, 200, 400, 800) # Vector of sample sizes
p <- c(0.33, 0.25, 0.10, 0.05, 0.025) # Vector of probabilities
# Calculate percentiles
perccr <- round(
  outer(n, p,
      \(n, p)(qnorm(p/2, mean = 0, sd = sqrt(n), lower.tail = FALSE))
), 1)

rownames(perccr) <- n
colnames(perccr) <- p
perccr

    0.33 0.25  0.1 0.05 0.025
50   6.9  8.1 11.6 13.9  15.8
100  9.7 11.5 16.4 19.6  22.4
200 13.8 16.3 23.3 27.7  31.7
400 19.5 23.0 32.9 39.2  44.8
800 27.6 32.5 46.5 55.4  63.4
</code>
For example: When $n=200$, there is a $5\%$ probability of an imbalance of $\pm 27.7$ or worse.
The important thing to note is that imbalance does not lead to unbiased effects per se but it will decrease the precision of the estimator. Hence, imbalance will negatively affect the statistical power of the trial. But how much?
Let's compare the power curves for a comparison of two normal means with equal variances assumed to be known and significance level $\alpha = 0.05$. Assume that the absolute mean difference between the groups is $0.5$ and $\sigma = 1$. Further, let $Q = n_A/n$ so that $Q$ indicates imbalance as it goes further away from $0.5$.

For large $n$, there is little loss of power for $Q$ between $0.3$ and $0.7$. The table we calculated above indicates that such a large imbalance is unlikely. However, there exist a number of restricted randomization procedures which try to protect against imbalances while also protecting against biases.
References
Rosenberger WF, Lachin JM (2016): Randomization in clinical trials: theory and practice. 2nd ed. John Wiley & Sons.
Senn, S. (2013). Seven myths of randomisation in clinical trials. Statistics in medicine, 32(9), 1439-1450. (link)
Answer: As for the chances, that is difficult to assess. But one always should run tests on the baseline and attest if the variables that might be related to the treatment hold any difference between treatment and control groups. If you need some correction, you might run a propensity score on your sample in order to match your sample adequately.
Below I will list some of the possibilities of the biases that you might run on randomized experiments.
By Heckman and Smith (1995), in experiments that are also randomized by locality, you might have groups of people who will anticipate the program and move to the region of treatment -- this is a bias that might be hard to overcome, I believe, if that is a possibility.
Also, control groups might change their behavior. Say, when there is a conditionality of schooling frequency to receive the treatment. If the control group knows it will receive the treatment benefit in the near future, the group might behave similarly to the treatment group in order to receive the treatment in the near future. Another bias might be related to other social programs that one of the groups (or both the control and the treatment group) might be receiving.
One more bias that is frequently studied today it is related to spillover effects from the treated to the control groups (the violation of the SUTVA hypothesis). If we are considering a money benefit inside a village in which both control and treatment groups engage, one should consider general equilibrium effects -- for instance, money lending by extended families (thus money going from treatment to control groups), an idea tested by Angelucci and Giorgi (2009).
Edit: As for the 'truly randomized procedure' you mean what exactly?


When is $n\mathbb{Z}_{mn}$ a summand of $\mathbb{Z}_{mn}$?

Question: I have done this for different examples like is $2\mathbb{Z}$ a summand of $\mathbb{Z}$?(the answer is no in this case) and is $2\mathbb{Z}_{4}$ a summand of $\mathbb{Z}_{4}$?(the answer is yes in this case). But what about in the more general case of $\mathbb{Z}_{mn}$? Any hints/tips would be appreciated?
Comment: How is $2\mathbb{Z}_4$ a summand of $\mathbb{Z}_4$? If $L+2\mathbb{Z}_4 = \mathbb{Z}_4$ (let alone a direct sum), then $L=\mathbb{Z}_4$. I would not call that a summand.
Comment: Are you taking ${\bf Z}_r$ as a group, or as a ring?
Comment: @GerryMyerson They are modules.
Answer: It wil be true if and only if $n,m$ are coprime integers, which
confirms the fact that $2\mathbb{Z}/4\mathbb{Z}$ is NOT a direct summand of $\mathbb{Z}/4\mathbb{Z}$ (cf. Arturo's comment).
Set $R=\mathbb{Z}/nm\mathbb{Z}$. If $n\cdot R\oplus L=R$, then $L\simeq R/n\cdot R\simeq \mathbb{Z}/n\mathbb{Z}$ (as group. Left as an exercise).
Hence $L$ is in particular a cyclic subgroup of $R$ of order $n$, that is $L=m\cdot R$.This is also an $R$-module.
Now, $n\cdot R\cap m\cdot R=lcm(n,m)\cdot R$, which will be $0$ if and only if $lcm(n;m)=nm$, that is if and only if $n,m$ are coprime (details are left to you).
Conversely, if $n,m$ are coprime, you have $nR\oplus mR=R$: we have $nR\cap mR=0$, and if $u,v\in\mathbb{Z}$ satisfy $un+vm=1$, then for all $\bar{x}\in R$, we have $\overline{x}=n\cdot \overline{ux}+m\cdot \overline{vx}.$


Conditional ISSET issue

Question: In a single product page, the product ID is assigned to the var $productID. The problem is when, staying in one of the fields of the form and push the ENTER key, the page crashes since the script can't find the ID again. So I would implement the script in the following way.
<?php
$product_id = $_GET['product_id'];
include '../sys/conn.php';
$risultato = mysqli_query ($conn, "

(mysql query)

") or die ("Query not valid: " . mysqli_error($conn));
mysqli_close($conn);
$row = mysqli_fetch_array($risultato);
?>

That I implemented in order that if $_GET is not set properly, it is set to  13321 (example value).
<?php

$product_id = $_GET['product_id'];

if(!isset($_GET['product_id']){
$product_id='13321';
}else{
include '../sys/conn.php';
$risultato = mysqli_query ($conn, "
(mysql query)

") or die ("Query not valid: " . mysqli_error($conn));
mysqli_close($conn);
$row = mysqli_fetch_array($risultato);
}
?>

The conditional clause looks like is not accepted and generates errors such like syntax or unexpected variables. Any help?
---VERSION 2----
<?php
$product_id = $_GET['product_id'];

if(!isset($_GET['product_id'])){
    $product_id='13321';}
    else
{

include '../sys/conn.php';
$risultato = mysqli_query ($conn, "

(MYSQL Query)

") or die ("Query non valida: " . mysqli_error($conn));
mysqli_close($conn);
$row = mysqli_fetch_array($risultato)

}
?>

And the error is:
Parse error: syntax error, unexpected '}' in /Applications/XAMPP/xamppfiles/htdocs/gest/pages/singolo_prodotto.php on line 66
Comment: You're missing a closing bracket on this line: `if(!isset($_GET['product_id']){ `
Comment: Does `$_GET['product_id']` come from a form input? It will most likely always be _set_ if so.
Comment: Also, do you have an actual query that you haven't shown in your example code here? Just making sure.
Comment: Hi, the product ID comes from the Products List Page with this : Link
Answer: You missed bracket:
if(!isset($_GET['product_id']){

Should be
if(!isset($_GET['product_id'])){

Comment: $row = mysqli_fetch_array($risultato) you are missing ";" at the end
Comment: Mitch, I implemented the syntax but it still give error on line 66 that is the closing brace parenthesis
Comment: Code you pasted have not 66 lines. I bet error is in file you includes.
Comment: You're right, the 66 line has no sense since it is an excerpt my post. However I resumed only the sql query, the rest is fully reported in the post.
Comment: Mitch, I implemented my original post with code in the part I marked ---VERSION 2--- that is the current one
Comment: Where is sys/conn.php file ?
Comment: It is the the script to get connection to the database. It is stored in a subfolder.
Comment: Paste it on pastebin or something like that
Comment: Mitch did you find something wrong in my conn.php file?

Conditional ISSET issue


Modeling Exponential Equation with 2 given points?

Question: So let's say that the population of rabbits increase according to the law exponential growth.
If a certain population of rabbits has 100 rabbits after the second day and 300 after the fourth day, can we figure out how many rabbits that there were to begin with, or do we not have enough information?
Comment: You do have enough information; see what equations you get from this.
Comment: As a hint, assume the function has the form $f(x)=ax^b$. You have two corresponding values of $x$ and $f(x)$, giving you two equations with which to solve for $a$ and $b$.
Answer: Let us make the problem more general, knowing that at time $t_1$ the population is $P_1$ and that at time $t_2$ the population is $P_2$.
The first thing to decide is wich form of the exponential model you want to use.
Suppose that you select, just as Kajelad commented $P_t=a t^b$. So, the equations are $$P_1=a t_1^b \qquad , \qquad P_2=a t_2^b$$ Making the ratio, you have $$\frac{P_2}{P_1}=\frac{a t_2^b}{a t_1^b}=\left(\frac{t_2}{t_1}\right)^b$$ Taking logarithms $$\log\left(\frac{P_2}{P_1}\right)=b\log\left(\frac{t_2}{t_1}\right)$$ then $b$. Now, use the first equation to get $a=\frac{P_1}{t_1^b}$.
Another (equivalent) model could be $P_t=a e^{b t}$. Doing the same $$\frac{P_2}{P_1}=\frac{a e^{bt_2}}{a e^{bt_1}}=\frac{ e^{bt_2}}{ e^{bt_1}}=e^{b(t_2-t_1)}$$ Taking logarithms $$\log\left(\frac{P_2}{P_1}\right)=b(t_2-t_1)$$ then $b$. Now, use the first equation to get $a={P_1}{e^{-bt_1}}$.
Now, for the initial population (that is to say at time $t=0$), whatever the choosen model, the population is $a$.


Bicommutant of self-adjoint subset of an involutive algebra

Question:
1.1.9. Let $A$ be an involutive algebra and $M$ a self-adjoint subset of $A$... If the elements of $M$ commute pairwise, then $M\subset M'$, so that $M'\supset M''$ and $M''$ is commutative...
Source: Dixmier's

Here $M'$ and $M''$ are the commutant and bicommutant of $M$. $M\subset M'$ is pretty straightforward, because each element in $M$ commutes with $M$, so each of the elements in $M$ must belong to the commutant $M'$.  But how to comprehend $M'\supset M''$?  And why would $M''$ be commutative?
Answer: In general, if $A \subset B$, then $B' \subset A'$. Indeed, if $x \in B'$ then $xb = bx$ for every $b \in B$. Since $A \subset B$, we have in particular, that $xa = ax$ for every $a \in A$. Hence $x \in A'$.
Now, $M \subset M'$, hence $M'' \subset M'$ and finally $M'' \subset M'''$. So $M''$ is contained in its commutant, and hence commutative.
Comment: I understand now why $B'\subset A'$, but where along the way was $M=M''$ proved?
Comment: I was too quick. The answer is now corrected.
Comment: Wow, using the tricommutant (?) here is quite neat. Thanks!


Diagnostic test

Question: I want to calculate the sensitivity, specificity, positive predictive value and negative predictive value of two diagnostic tests. The sensitivity is 0.92 (95% CI, 0.82-1.03)
Is this confidence interval possible?
Comment: Since you are the one doing the calculation, could you please tell us how you computed such a confidence interval?
Comment: I have used this formula ftp://ftp.hrc.es/pub/programas/calcu/prudiag/img/2.jpg
Comment: Just provide us the routine true positive, true negative, false positive and false negative figures and we can easily double check it.
Comment: True positive 24, true negative 70, false positive 0, false negative 2  thanks you
Comment: The issue is that sensitivity cannot exceed 1.  So the upper bound should be truncated at 1.  If an exact interval was generated you would not get 1.03.  What must be happening is that you are using an asymptotic distribution to generate the interval.  So the interval is approximate rather than exact. I think this is the reason whuber wants to know the formula you are using to calculate the interval.
Comment: How can I calculate the confidence intervals correctly?
Answer: To calculate the confidence interval, you used the formula $ Sen \pm 1.96 \sqrt{\dfrac{Sen(1-Sen)}{TP+FN}}$, where $Sen=TP/(TP+FN)$. This is an example of the normal approximation of the binomial distribution used to estimate the confidence interval. This is generally okay when $Sen(TP+FN)>5$ and $(1-Sen)(TP+FN)>5$. In your case, one of the conditions isn't met.
In general, it's much better to use exact binomial methods to calculate confidence intervals. You can do this easily in R.
<code>> binom.test(24,26)

Exact binomial test

data:  24 and 26
number of successes = 24, number of trials = 26, p-value =  1.049e-05
alternative hypothesis: true probability of success is not equal to 0.5
95 percent confidence interval:
 0.7486971 0.9905446
sample estimates:
probability of success
             0.9230769
</code>
You can see that the 95% confidence interval calculated using exact binomial methods is 75% to 99%. Ignore the p-value and alternative hypothesis.
With strong computing power available anywhere, I'm not sure there's a place for normal approximations.

Diagnostic test


"Equality of Opportunity in Supervised Learning" implementation

Question: I'm trying to find some fair/accountable/transparent (FAC) algorithms, and the "Equality of Opportunity in Supervised Learning" seems pretty promissing. I was wondering if there's an implementation of the algorithms somewhere (I personally prefer python, but [almost] any language would do).
[1] Hardt, Moritz, Eric Price, and Nati Srebro. "Equality of opportunity in supervised learning." Advances in neural information processing systems. 2016.
Answer: It turns out people at IBM have implemented it in the AIF360 package (github link).
The resources page lists the paper as one of the algorithms they've implemented.
It's implemented in aif360.algorithms.postprocessing.EqOddsPostprocessing
Answer: The AIF360 package actually only implements the algorithm from section 4.1 in Hardt et al., i.e., the one that operates given a binary classification model. This will generally be suboptimal, and Hardt et al. also present (in section 4.2) an algorithm that takes a score predictor model as an input (i.e., a thing that predicts [0,1] and not {0,1}).
This latter algorithm is not implemented in AIF360, but the fairlearn package has it implemented (and a quite long and nice discussion of what it does and how it works).
Comment: @adrin noticing just now that you're a co-author of fairlearn, haha. Nice job!


Using t() with langcode in Drupal 7

Question: I have a Drupal 7 setup with multiple languages (en and fr). In my template files I have a lot of t() texts which im translating using the i10n_client module. This works perfect for translating texts from en to fr IF the t() texts are written in english. However, what if I want to write my t() texts in Danish and being able to translate them to both en and fr? Meaning that the Danish version never will show up as long my Drupal setup only have en and fr as languages.
I tried using the options parameter with the langcode like this:
<code>print t('Min tekst', array(), array('langcode' => 'da'));
</code>
But the translate-text interface (provided by i10n_client module) wont show up when I'm on the en site. Only on the fr site where I can translate it from en to fr.
Is this possible? And how?
Answer: The string (first parameter) always needs to be in English, from the Drupal 7 API:

$string A string containing the
  English string to translate.

The langcode just means that the string will always be translated to Danish, no matter what the active language is. So if you'd be surfing the French site, you'd see the Danish string.
I'm afraid you'll have to translate your Danish strings back to English strings.

Using t() with langcode in Drupal 7


Asp.Net Core Challenge returns Null URI Exception error

Question: I am creating an ASP.NET core web API and want to integrate microsoft Azure AD authentication services. On compile-time everything works just fine. However, when I access the route meant to return a Challenge, I get a null URI Exception (Stacktrace below). I have tried specifying a challenge URI in my ConfigureServices:
<code> public void ConfigureServices(IServiceCollection services)
        {

            services.AddDbContext<AppContext>(options => options.UseSqlite("Data Source=app.db"));

            // Identity/Authorization Services
            services.AddAuthentication(sharedOptions =>
                {
                    sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
                })
                .AddAzureAD(options =>
                {
                    options.ClientId = Configuration["Authentication:Microsoft:ApplicationId"];
                    options.ClientSecret = Configuration["Authentication:Microsoft:Password"];
                    options.SignedOutCallbackPath = "/api/v1/accounts/signout";
                })
                .AddCookie(options => options.AccessDeniedPath = "/api/v1/accounts/accessdenied");

            services.AddTransient<IRecognitionService, RecognitionService>();
            services.AddTransient<IProfileService, ProfileService>();

            services.AddMvc();

        }
</code>
I have also tried changing the redirect URI in my route:
<code>    [Route("api/v1/accounts/[action]")]
    public class AccountController : Controller
    {
        public async Task<IActionResult> AccessDenied()
        {
            return Unauthorized();
        }

        [HttpGet]
        public async Task<IActionResult> Signin()
        {
            return Challenge(new AuthenticationProperties {RedirectUri = "/accessdenied"},
                AzureADDefaults.AuthenticationScheme);
        }

    }
}
</code>
I cant seem to find the root of the issue, and the stacktrace makes no sense to me:
<code>System.ArgumentNullException: Value cannot be null.
Parameter name: uriString
   at System.Uri..ctor(String uriString)
   at Microsoft.AspNetCore.Authentication.AzureAD.UI.OpenIdConnectOptionsConfiguration.Configure(String name, OpenIdConnectOptions options)
   at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name)
   at System.Lazy`1.CreateValue()
   at System.Lazy`1.LazyInitValue()
   at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.<InitializeAsync>d__42.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationHandlerProvider.<GetHandlerAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationService.<ChallengeAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.<ChallengeAsync>d__54.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationService.<ChallengeAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.ChallengeResult.<ExecuteResultAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeResultAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResultFilterAsync>d__28`2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeResultFilters>d__26.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResourceFilter>d__23.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeFilterPipelineAsync>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()
</code>
I am using ASP.NET Core 2.1.1 with MVC, Cors, Azure AD, and EntityFramework
There is no in-project CSHTML, as we are using a separate front end (Using VueJS)
Answer: I think the problem is because the Instance property is not set on your AzureADOptions
See this link
https://github.com/aspnet/AADIntegration/issues/34
So add, for example
<code>.AddAzureAD(options =>
{
  options.Instance = "https://login.microsoftonline.com"
}
</code>
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/21080720)
Comment: @purplepsycho,  sure , I have added an example, I had exactly this issue and the above solves it for me
Answer: In all likelihood you need to set the URI.
There are three things I suggest you check:

Have you added your database endpoint and key to the config file? It looks like the issue might be with your connection strings. Add the keys within the app settings of your config file if you have not done so already. Ensure that your app settings are there and any web service URLs are being referenced properly.
Do a null check on the URI to ensure that a null value does not get passed in.
Check the system logs on your app server.
Ensure that you are passing in all necessary parameters.
Register the app to a new application pool.

Hope this helps!
Comment: I also am experiencing the same problem. When running in debug mode from VS it successfully redirects and authenticates, but after publishing and running the API (with correct appSettings) I get the exepection as above: System.ArgumentNullException: Value cannot be null.
Parameter name: uriString
   at System.Uri..ctor(String uriString)
   at Microsoft.AspNetCore.Authentication.AzureAD.UI.OpenIdConnectOptionsConfiguration.Configure(String name, OpenIdConnectOptions options)


Creating a category page when using the Search API module

Question: I'm trying to build a Drupal Commerce store which is going to be my first timer with Drupal 8+. However, the approach described in the Drupal Commerce documentation regarding the creation of a filterable product catalog really doesn't seem to be what you usually see on a good e-commerce site.
Having only a page to display products from all categories seems to be SEO counter-intuitive.
How can I create a product catalog with categories that list the products in that particular category but, for example, also list the sub-terms of the currently selected term as well?
There isn't really a showcase where I could look at different shops using Drupal Commerce 2 as if nobody was event using it. All the ones I found on Drupal Commerce official pages are either not working or use Commerce 1.
Comment: I've never actually used it for a serious project (pretty much exactly for the reasons you've mentioned here), but anecdotally, the philosophy for that project seems to be "know Drupal well and you'll know commerce well". Everything is set up to be used like a normal Drupal "thing", with content types, taxonomy, views, search api, facets, and so on. I think the implication is that if you know how to set up a catalogue of content, you'll know how to do the same for products. But they don't seem to offer strong opinions on how that should be done. Again, that's anecdotal, I've never asked them
Answer: I finally found a solution... You can use the https://www.drupal.org/project/tvi module on the vocabulary for product categories. You then set up a Product Index view with a url of taxonomy/term/% and enable a context filter to search in product categories. Works like a charm!
Answer: I found the tutorials at https://www.acromedia.com/article/creating-a-product-catalogue-with-search-api-solr-facets (with video) as well as the official documentation at https://docs.drupalcommerce.org/commerce2/developer-guide/products/marketing-products/product-catalog-facets pretty straightforward to follow.
To summarize: you assign a category to each product, then create a view that lets the customer choose which category to view. I can't explain the details better than those tutorials though.
Comment: Yes I know about this but that's exactly what's not correct about it all. Having just one page with filters is not good for overall SEO since you are not clicking-through the different category pages. You are just filtering the products on the same page with no-follow filter links. This way you don't even have the category terms indexed in a sitemap because when you go to a category page detail, it's just an empty taxonomy since taxonomy pages don't display product entities, only nodes.


Weakly Compact Cardinals and the Extension Property

Question: From $\textit{The Higher Infinite}$ by Kanamori, in his proof (page 39 - 41) that $\kappa$ is weakly compact if and only if $\kappa$ satisfies the Extension Property, the proof does something that I am not entirely sure is necessary:
The relevant portion of this proof is as follows:
Let $\Sigma$ be a $\kappa$ satisfiable set of $L_{\kappa,\kappa}$ sentences. $R_1$ is the definable satisfaction relation for set models of $V_\kappa$. $R_2$ is another relation (but that is not relevant at this point in the proof). He then manages to prove that there is a transitive set $X$ properly containing $V_\kappa$ such that
$\langle V_\kappa, \in, R_1, R_2 \rangle \prec \langle X, \in, S_1, S_2 \rangle$
$\langle X, \in, S_1, S_2) \models \Sigma \text{ has a model }$
I think that the proof should be finished at this point: Let $\mathcal{M}$ in $X$ be such a model. By the absoluteness of the satisfaction relation $S_1$, $\mathcal{M}$ is a model of $\Sigma$ in $V$. This should conclude the proof.
However, Kanamori continues. Since $\kappa$ is inaccessible, $V_\kappa \models ZFC$. By elementarily, $X \models ZFC$. Being inaccessible is absolute for transitive model of $ZFC$, so $X \models \kappa$ is inaccessible. Then he applies the Lowenheim Skolem Theorem in $X$ for $L_{\lambda, \lambda}$ for inaccessible cardinal $\lambda$ to prove that (when $\lambda = \kappa$)
$\langle X, \in, S_1, S_2 \rangle \models \Sigma$ has a model $\mathcal{M}$ with domain $\subseteq \kappa$
Then he applies the absoluteness of the satisfaction relation $S_1$, to claim that $\mathcal{M}$ is really a model of $\Sigma$.
My question is why does he have to produce a model in $X$ of $\Sigma$ with domain a subset of $\kappa$ to apply the absoluteness argument of the satisfaction relation. Would it not be enough just to produce any model in $X$. Thanks for any clarification
Comment: There are about a zillion ways to define weakly compact cardinals, which one are you using? And also is the extension property the existence of elementary end-extensions?
Comment: Yes. The extension property for $\kappa$ is the existence of a transitive $X$ a proper subset of $V_\kappa$  and $S \subset X$ such that $(V, \in, R) \prec (X, \in, S)$. The definition of weakly compact is the $\kappa$ "compactness theorem" for collections of sentences using no more than $\kappa$ no logical sentences.
Comment: It's a shame on the bounty. Perhaps it'd be time to cross this to MathOverflow when the bounty expires?
Answer: The problem is that you cannot conclude "$\mathcal{M}$ is a model of $\Sigma$" from "$X \vDash \mathcal{M}$ is a model of $\Sigma$". The reason is that there is no reason why satisfaction of an $L_{\kappa, \kappa}$ sentence in $\mathcal{M}$ as seen by $X$ will be truly reflected in $V$ unless $X$ can see all of $\mathcal{M}^{< \kappa}$. Choosing the universe of $\mathcal{M}$ to be a subset of $V_{\kappa}$, achieves this.
This issue does not arise in the usual $L_{\omega, \omega}$-satisfaction since every decent transitive class is closed under finite sequences.


Setting up a Dive only Floyd Rose bridge so it Floats

Question: I have an EVH Wolfgang Special Guitar which comes with a dive only floyd rose bridge.
My problem with this is that I like to be able to do tremolo sound with it when soloing.
I can only do this by setting it up so it's slightly floating but when I do this I'm having a big time making it stay in tune.
Is this because I have not setup the bridge properly or is this bridge really not meant to float at all?
Comment: EVH was a dive-only guy. He nailed a quarter under the bridge of Frankenstein just to keep the bridge up. I'd guess that the Wolfgangs were designed for that.
Answer: Its sounds like to me that you are trying to treat a dive only bridge like its floating by raising it abit... This will cause tuning problems as it wasn't designed for use like that, and the string tension will be wrong.
You could continue like this and try but really its just not meant for that kind of tremolo action.
Answer: To be able to properly be able to pull up on such a system, there would need to be a rout in the body for it to sit in, otherwise it's designed to be flush against the top and only able to dive downward.


photo sizes available through Graph API / FQL and display in a custom viewer

Question: I create a photo viewer for fb photos in a FB canvas application. Therefore I care about photo size. It seems all uploaded photos in FB seem to be available in different sizes. I see in the graph API (http://developers.facebook.com/docs/reference/api/photo/) the term in the source property: "maximum width or height of 720px" but as well a width and height property. As well I have several photo sizes in fql photo (http://developers.facebook.com/docs/reference/fql/photo/).

Are the photo sizes available in one category (src_small, normal, src_big) always the same or can they differ? I suppose they can differ.
What are the formats FB supports? I suppose it is small normal and big
How to conceptually deal with different sizes in a viewer? I suppose you need to fix the viewer area, eg. 3 (height) : 4(width). Now size an image inside the viewer by maximizing the height or width.

Am I heading to the right direction?
Answer: Not sure if you noticed, but there's also an "images" field in the Graph API which holds "The 4 different stored representations of the photo" similiar to the FQL.
<code>"images": [
  {
     "width": 720,
     "height": 483,
     "source": "http://a7.sphotos.ak.fbcdn.net/hphotos-ak-ash2/168119_10150146071831729_20531316728_7844072_5116892_n.jpg"
  },
  {
     "width": 180,
     "height": 120,
     "source": "http://photos-g.ak.fbcdn.net/hphotos-ak-ash2/168119_10150146071831729_20531316728_7844072_5116892_a.jpg"
  },
  {
     "width": 130,
     "height": 87,
     "source": "http://photos-g.ak.fbcdn.net/hphotos-ak-ash2/168119_10150146071831729_20531316728_7844072_5116892_s.jpg"
  },
  {
     "width": 75,
     "height": 50,
     "source": "http://photos-g.ak.fbcdn.net/hphotos-ak-ash2/168119_10150146071831729_20531316728_7844072_5116892_t.jpg"
  }
],
</code>

Note that the original image does not have a width of 720px everytime. It's not scaled up if you upload a smaller image.

From the first view it seems that the images stored have a fixed width per representation.
180px for the large, 130px for the medium and 75px for the small size. Also there's a original image which is has a maximum width of 720px.
FB only supports JPEG format.
Conceptually you should have a fixed width window for the image size you want to show (let's take that you show the biggest [large] image to the user using the one with width 180px. Height is then <= 180px. So you can make a 180x180 box and fill the background in black if the image height's is smaller.
OR do it like facebook does. Take the original image and fit is as big as you could into the window. They use a pop-up so they could use up maximum amount of space for the image.
Using valid CSS it'll be easy to play with images different sizes.
So yes, you're heading to the right direction, just analyze Facebook API's and take the most out of them.
If you have any trouble writing the CSS needed or putting together the FQL query, feel free to ask another question :)
Little reading about CSS image resize
Comment: Another question :-) I perceive there are 2 alternatives to keep proportions: 1) introduce boarder to show the full image 2) fit the smaller from height and width and do a center of the image and not show all content. The second is better for the small images. The first is clear how to implement, the second not- do you might have a suggestion how to implement this? Thanks.
Comment: if you want to display just as much as image as can fit into the div use background-image for CSS. You can center it and it won't be resized down if it goes out from the bounds.


Android draw line and then drag it with touch

Question: I am building an Android app that features the line drawing on canvas, which is showing over camera view. The purpose of it is to draw lines which provides an outlines for capturing image in that boundaries.

I am able to draw lines like this that are used as boundaries to take picture within it. But what i want is that i am not able to drag the line that i draw or if i want to scale the line after drawing. As currently have to be very careful when drawing the lines, and slight deviation requires do it again.
So can someone help me how i can implement drag listener on line, how to create line as object that can listen when finger is touched on a line?
Thanks,
Irfan
@Override
public boolean onTouchEvent(MotionEvent event) {

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:

            downx = event.getX();
            downy = event.getY();

            fstTouch = downx;
            fstTouchx = downx;
            fstTouchY = downy;
            break;

        case MotionEvent.ACTION_MOVE:

            break;

        case MotionEvent.ACTION_UP:
            upx = event.getX();
            upy = event.getY();

            if (actionE == 1) {
                actionE = 2;

                canvas.drawLine(downx, downy, upx, upy, Manage_Template.mPaint);
                invalidate();
                editor.putFloat("downx", fstTouchx);
                editor.putFloat("downy", fstTouchY);
                editor.putString("fst", "2");
                editor.putFloat("newDownx", upx);
                editor.putFloat("newDowny", upy);
                editor.commit();

            }
              else {

                fDownx = sharedPreferences.getFloat("downx", 0);
                fDowny = sharedPreferences.getFloat("downy", 0);
                newDownx = sharedPreferences.getFloat("newDownx", 0);
                newDowny = sharedPreferences.getFloat("newDowny", 0);

                fstLate = fstTouch - fDownx; //85-100=15
                scndLate = fstTouch - newDownx;//120-100=30

                st = String.valueOf(fstLate);
                sl = String.valueOf(scndLate);
                st = st.replace("-", "");
                sl = sl.replace("-", "");
                fstLate = Float.parseFloat(st);
                scndLate = Float.parseFloat(sl);

                if (fstLate >= scndLate) {

                    canvas.drawLine(newDownx, newDowny, upx, upy, Manage_Template.mPaint);
                    editor.putFloat("newDownx", upx);
                    editor.putFloat("newDowny", upy);
                    editor.commit();
                    invalidate();
                    Log.d("Action UP","fstlate>");

                } else {
                    canvas.drawLine(fDownx, fDowny, upx, upy, Manage_Template.mPaint);
                    editor.putFloat("downx", upx);
                    editor.putFloat("downy", upy);
                    editor.putFloat("newDownx", newDownx);
                    editor.putFloat("newDowny", newDowny);
                    editor.commit();
                    invalidate();
                    Log.d("Action UP","scndlate");
                }
            }
            // }

            break;
    }
    return true;
}

Comment: Add your test code
Answer: I'd use an onTouchListener to do this. Here's an example I used when I was learning about it: Using OnTouchListener
I think the main thing you want, is to update the line during every MotionEvent.ACTION_MOVE and then leave the line where it is when you get a MotionEvent.ACTION_UP
Hope this helps!
Comment: How do touch listener identify that user has clicked the line, as once a line is drawn on canvas, it is a fixed thing on it.
How do I then know the line is clicked, and then how to clear the already line and move it to other location?
Comment: I would say check this link out:  It helps you find the distance between the click and a line. https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line  Then, for moving it, you'll have to clear the screen and redraw everything, most likely.
Answer: I was also facing the same problem and solved it by using the concept of Distance from point to line (geometry).
All you need to just apply this formula shortestDistance= (event.x-drawingMarginLeft). Update the value of drawingMarginLeft in Action_Move. In my problem, I just move the line horizontal axis.


Why do these highly ranked senior players never enter a national medal tally?

Question: This official list of senior badminton players in India ranks, under Women's Singles, Saina Nehwal as rank 20 and PV Sindhu as 30. As such, there are already 20 players above Saina Nehwal.
However, it is almost one of them only who tops the merit list. Even in the recent National Badminton Championship, Saina was the winner while Sindhu was runner up.
My question: Why are the names of the other top players so unheard? Why don't they take part (and probably win) such national titles?
Answer: For a national ranking to be meaningful, it is desirable to include as many tournaments as possible, so that a form peak - or injury - at the yearly national championship tournament has only limited impact.
Typically, these rankings take into account the average or the best tournament results of the player. For instance, per §6 of the Indian Ranking System regulations, the ranking is determined by the sum of points gathered by the 6 best tournament finishes in the previous 52 weeks.
If a player plays less than 6 tournaments, all of their points count (§6.1). In theory, the regulation could be changed to scale the average points, but that would mean that a player who wins the only tournament they competed in would immediately rank #1, which is not desired.
Top-level badminton players like Saina Nehwal or P.V. Sindhu only play in the national championship tournament. The other national-level tournaments are not a challenge for them, conflict with international tournaments, or do not fit into their long-term training and rest plans; while competing in local tournaments would yield them small amounts of fame and money, it would severely reduce their chances at tournaments that really count.
The Indian regulations do take this into account:

5.1 Additional points shall be added to the points earned by a player as per Indian Ranking System under the following circumstances: The ranking points equivalent to one tenth of the points to the credit of a player as per latest BWF ranking list in the same event. (...)

As of writing, Saina Nehwal has 54720 points in the BWF ranking, which would comfortably give her the first in the Indian ranking on its own with 5472 Indian ranking points, easily before Anura Prabhudesai with 3247 points.
However, it seems these BWF points are not included on the Badminton India ranking website. Most likely, the additional points are only counted for entering and seeding in the national championships.