MVC: How to populate dropdownlist from sql query stored in a db field

Question: We're using mvc to create a dynamic web form.  One of the controls on the form is a dropdown.  In order to populate this dynamic dropdown control, we've stored the sql statement in a single database field.  It's a long story as to why we're doing it this way, but the general issue we're having is how to get our dropdown to dynamically populate using this sql field value.
For example, here's a sample record from our database.  This image may be too small to read.  If so, try right-clicking & opening the image in a new window (the field we're using is called "Sql"):

As you can see, we have a field called "Sql".  In this record, we need to pull the "product_id" as the dropdown's id field & the "product_name" as the dropdown's text field.  One known, is within the sql statement, the first field will ALWAYS be the dropdown's id.  The 2nd field will ALWAYS be the dropdown's text.
And here's my dropdownlist so far:
@(Html.Kendo().DropDownList()
      .Name("Filterdropdown")
      .DataTextField("Text")
      .DataValueField("Value")
          .OptionLabel("Select")
                                    //.Events(e => e.Change("change"))
      .BindTo(new List<SelectListItem>() {
          new SelectListItem() {
              Text = "",
              Value = "1"
          },

      })

As you can see, currently, I'm not using that field to populate my dropdownlist.  So my question is, how can I set this up to do so?
Thanks
Comment: Your problem is not at combo box, but retrieve the data by the query stored in the table. Write a stored procedure input the ReportFilterId and return a table with 2 columns: id, name by EXEC the query in Sql field. Use EF to retrieve the results then use in your application.
Answer: According to your requirement you have to first get the query from db and than run it and with the result of this query you will bind the dropdown. Here is working code i have tried in same scenario.
Controller Code
Entities ent = new Entities();//This is my dbcontext object
//First i will query the db to get the query stored in table
Query query = ent.Queries.FirstOrDefault();
string sql = query.Query;//I have assigned the query to a string and now i will execute this

//Here i run the query in db against the table employee you need to change this to products.
var list = ent.Employees.SqlQuery(sql).ToList<Employee>();
//Create List of SelectListItem
List<SelectListItem> selectlist = new List<SelectListItem>();
foreach (Employee emp in list)
{
 //Adding every record to list
 selectlist.Add(new SelectListItem { Text = emp.Name, Value = emp.Id.ToString() });
}

ViewBag.SelectList = selectlist;//Assign list to ViewBag will access this in view
return View(list);

View Code
@Html.DropDownList("ddlname",(IEnumerable<SelectListItem>)ViewBag.SelectList)

Here is i have just assigned the ViewBag value to dropdown. I have not used Kendo but i hope this will help you to get on track.
Update
Instead of hitting sql server twice you can get your required data in just one query.These are two calls to sql server

Query query = ent.Queries.FirstOrDefault();
var list = ent.Employees.SqlQuery(sql).ToList<Employee>();

These two can be combined to one like this
var list = ent.Employees.SqlQuery(ent.Queries.FirstOrDefault().Query).ToList<Employee>();

Comment: @Djeroen you can select certain columns like this `ent.Employess.Select(e => new { EmployeeName = e.Field("EmpName"),
                       Age = e.Field("Age") });`
Comment: great answer, i am trying to use this for my application, but i want to select only certain columns, and this throws an error `A member of the type, 'ClientID', does not have a corresponding column` and thats right because i dont want ClientID
Answer: Here I understand that you are trying to populate a dropdown with some data. But, I am not sure of the reason why you are saving SQL query in a DB table. Possible reasons could be that the query to extract data for your dropdown is not always the same and you want that flexibility to modify the query through DB. Though this may not be the best of appraoches to achieve your requirement, hope it serves your purpose for now.
Now, coming to your requirement of extracting data for a dropdown, you could have easily achieved that through a simple subquery/function if you were using ADO.NET with SQL for querying. But, here as your application is build on MVC, you might be using Entity framework for data access which makes you think of only LINQ for querying.
Fortunately, though LINQ is the only direct way of querying DB entities via Entity Framework, you can also execute raw SQL queries through LINQ.! So, all you need to do here is:
Step 1) Get the SQL query stored in DB using LINQ.
sql = DbContextObj.YourQueryTable.ConditionToGetQuery..();

Step 2) Execute the query obtained in step 1 using .SqlQuery(sql) method on your data entity:
DataForDropDown = DbContextObj.YourDataTable.SqlQuery(sql).ToList..();

Now, you can use a HTML helper to generate a Dropdown control binded with your data.
Comment: Thanks.  I've already implemented Mairaj's solution but I wasn't aware of this functionality.  It's good to know :).  In regards as to why I implemented the sql in a db table, the controls on this page are 100% dynamic.  Meaning, the admin goes to the site & says I want to place 3 textboxes, 1 checkbox, & 2 dropdowns on this form.  If they decide to use a dropdown, we ask them how they want to populate each one.  They can either hard code items or query from a db table.  This query is stored in our database, thus the reason we need to retrieve from there.  Thanks again!
Comment: @Mahesh4b7 If you look at my solution i have done the exact same thing which you are describing. I have performed raw query and than executed the query which gets data for dropdown list.


Indexing R dataframes, by boolean

Question: Suppose we have a data frame
a[1:3,2:3]
AWAY HOME
1        CLE       BOS
2        MIL       CHI
3        POR       LAL

If I do
a[1:3,2:3]==c("CLE","BOS")
AWAY HOME
1      TRUE      TRUE
2     FALSE     FALSE
3     FALSE     FALSE

I get as expected. Yet if I do
a[,2:3]==c("CLE","BOS")
AWAY HOME
1       TRUE     FALSE
2      FALSE     FALSE
3      FALSE     FALSE
....(Others left out, as unimportant)....

Why is this so? Shouldn't it give the same answer, with the exception that the other executes on the entire dataframe? Where does this difference come from? Shouldn't both cases return TRUE TRUE as the first line?
Comment: I will accept the answer, as soon as it lets me. Thank you
Comment: `==` works on a single element you need `%in%` on a loop i.e. `lapply(a[2:3], '%in%' , c("CLE", "BOS"))`
Comment: Recycling.  See `help("==")`
Comment: Would you be so kind as to post an answer with a simple example?
Answer: We can use %in% instead of == as is for comparing a single element
a[1:2] <- lapply(a[1:2], '%in%' , c("CLE", "BOS"))
a
#   AWAY  HOME
#1  TRUE  TRUE
#2 FALSE FALSE
#3 FALSE FALSE

Sometimes, == works as we expect, but it is just due to chance because it does the comparison by columns, i.e. in the 'AWAY' column, it compares the first element with "CLE", second with "BOS", third  with "CLE", fourth with "BOS" (due to recycling).  This requires some kind of ordering of the elements to get the output correct, while %in% checks whether those elements are there.

Indexing R dataframes, by boolean


How to install Imagick on XAMPP? [Ubuntu 12.04]

Question: I'm trying to install Image Magick on my Ubuntu machine using XAMPP, but so far no luck.
 I've tried installing the packages php5-imagick, but it states that the dependencies are not met:
The following packages have unmet dependencies:
 php5-imagick : Depends: phpapi-20090626

I've tried compiling the Image Magick package and then using pecl to install it, but it stops.
lampp/bin  » sudo ./pecl install imagick
WARNING: channel "pecl.php.net" has updated its protocols, use "pecl channel-update pecl.php.net" to update
downloading imagick-3.0.1.tgz ...
Starting to download imagick-3.0.1.tgz (93,920 bytes)
.....................done: 93,920 bytes
13 source files, building
running: phpize
grep: /opt/lampp/include/php/main/php.h: No such file or directory
grep: /opt/lampp/include/php/Zend/zend_modules.h: No such file or directory
grep: /opt/lampp/include/php/Zend/zend_extensions.h: No such file or directory
Configuring for:
PHP Api Version:
Zend Module Api No:
Zend Extension Api No:
configure.in:3: warning: prefer named diversions
configure.in:3: warning: prefer named diversions
Please provide the prefix of Imagemagick installation [autodetect] :
building in /tmp/pear/temp/pear-build-root0hHzBG/imagick-3.0.1
running: /tmp/pear/temp/imagick/configure --with-imagick
checking for grep that handles long lines and -e... /bin/grep
checking for egrep... /bin/grep -E
checking for a sed that does not truncate output... /bin/sed
checking for cc... cc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether cc accepts -g... yes
checking for cc option to accept ISO C89... none needed
checking how to run the C preprocessor... cc -E
checking for icc... no
checking for suncc... no
checking whether cc understands -c and -o together... yes
checking for system library directory... lib
checking if compiler supports -R... no
checking if compiler supports -Wl,-rpath,... yes
checking build system type... x86_64-unknown-linux-gnu
checking host system type... x86_64-unknown-linux-gnu
checking target system type... x86_64-unknown-linux-gnu
checking for PHP prefix... /opt/lampp
checking for PHP includes... -I/opt/lampp/include/php -I/opt/lampp/include/php/main -I/opt/lampp/include/php/TSRM -I/opt/lampp/include/php/Zend -I/opt/lampp/include/php/ext -I/opt/lampp/include/php/ext/date/lib
checking for PHP extension directory... /opt/lampp/lib/php/extensions/no-debug-non-zts-20090626
checking for PHP installed headers prefix... /opt/lampp/include/php
checking if debug is enabled... no
checking if zts is enabled... no
checking for re2c... no
configure: WARNING: You will need re2c 0.13.4 or later if you want to regenerate PHP parsers.
checking for gawk... no
checking for nawk... nawk
checking if nawk is broken... no
checking whether to enable the imagick extension... yes, shared
checking whether to enable the imagick GraphicsMagick backend... no
checking ImageMagick MagickWand API configuration program... found in /usr/local/bin/MagickWand-config
checking if ImageMagick version is at least 6.2.4... found version 6.7.9 Q16
checking for MagickWand.h header file... found in /usr/local/include/ImageMagick/wand/MagickWand.h
checking PHP version is at least 5.1.3... yes. found 5.3.8
checking for ld used by cc... /usr/bin/ld
checking if the linker (/usr/bin/ld) is GNU ld... yes
checking for /usr/bin/ld option to reload object files... -r
checking for BSD-compatible nm... /usr/bin/nm -B
checking whether ln -s works... yes
checking how to recognize dependent libraries... pass_all
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking dlfcn.h usability... yes
checking dlfcn.h presence... yes
checking for dlfcn.h... yes
checking the maximum length of command line arguments... 1572864
checking command to parse /usr/bin/nm -B output from cc object... ok
checking for objdir... .libs
checking for ar... ar
checking for ranlib... ranlib
checking for strip... strip
checking if cc supports -fno-rtti -fno-exceptions... no
checking for cc option to produce PIC... -fPIC
checking if cc PIC flag -fPIC works... yes
checking if cc static flag -static works... yes
checking if cc supports -c -o file.o... yes
checking whether the cc linker (/usr/bin/ld -m elf_x86_64) supports shared libraries... yes
checking whether -lc should be explicitly linked in... no
checking dynamic linker characteristics... GNU/Linux ld.so
checking how to hardcode library paths into programs... immediate
checking whether stripping libraries is possible... yes
checking if libtool supports shared libraries... yes
checking whether to build shared libraries... yes
checking whether to build static libraries... no

creating libtool
appending configuration tag "CXX" to libtool
configure: creating ./config.status
config.status: creating config.h
running: make
/bin/bash /tmp/pear/temp/pear-build-root0hHzBG/imagick-3.0.1/libtool --mode=compile cc  -I. -I/tmp/pear/temp/imagick -DPHP_ATOM_INC -I/tmp/pear/temp/pear-build-root0hHzBG/imagick-3.0.1/include -I/tmp/pear/temp/pear-build-root0hHzBG/imagick-3.0.1/main -I/tmp/pear/temp/imagick -I/opt/lampp/include/php -I/opt/lampp/include/php/main -I/opt/lampp/include/php/TSRM -I/opt/lampp/include/php/Zend -I/opt/lampp/include/php/ext -I/opt/lampp/include/php/ext/date/lib -I/usr/local/include/ImageMagick  -DHAVE_CONFIG_H  -g -O2   -c /tmp/pear/temp/imagick/imagick_class.c -o imagick_class.lo
mkdir .libs
 cc -I. -I/tmp/pear/temp/imagick -DPHP_ATOM_INC -I/tmp/pear/temp/pear-build-root0hHzBG/imagick-3.0.1/include -I/tmp/pear/temp/pear-build-root0hHzBG/imagick-3.0.1/main -I/tmp/pear/temp/imagick -I/opt/lampp/include/php -I/opt/lampp/include/php/main -I/opt/lampp/include/php/TSRM -I/opt/lampp/include/php/Zend -I/opt/lampp/include/php/ext -I/opt/lampp/include/php/ext/date/lib -I/usr/local/include/ImageMagick -DHAVE_CONFIG_H -g -O2 -c /tmp/pear/temp/imagick/imagick_class.c  -fPIC -DPIC -o .libs/imagick_class.o
In file included from /tmp/pear/temp/imagick/imagick_class.c:21:0:
/tmp/pear/temp/imagick/php_imagick.h:40:17: fatal error: php.h: No such file or directory
compilation terminated.
make: *** [imagick_class.lo] Error 1
ERROR: `make' failed

I don't know what php.h file is missing, or why it's missing.
I also tried with a topic I found from two years ago, but when I download the source code, there are no any configure files, so I can't go on.
I'm really desperate as nothing works, I do have another PHP version installed (5.4.6), but I don't think that's the issue.
Can you guys provide some light on this?
Thank you!
Answer: Ubuntu is based on Debian and one thing I dislike with Debian is that sometimes official (stable) packages are too far behind what vendor provides. Fortunately for both Debian and Ubuntu you can use dotdeb repository, which stays up to date with all the most popular packages (like mysql, php etc). If you are not familiar, simply take a look at dotdeb repository (or directly on their setup instructions) and install PHP and related stuff from there. If any package is missing, here their step-by-step instruction on how to make one yourself.
Answer: Why not use Advanced Packaging Tool ?
Installation setups for Ubuntu 12.04:

Install imagemagick:
sudo apt-get install imagemagick
Install imagemagick PECL extension:
sudo apt-get install php5-imagick


Showing $f(x,y)$ satisfies the Lipschitz condition with respect to $y$

Question: In order to prove that a certain ODE has a unique solution, I want to show that the function $f(x,y)=x\sin |y|-(x^2-2) \arctan y$ satisfies the Lipschitz condition with respect to $y$.
My attempt: Let $D=(\alpha,\beta)\times(-\infty,\infty)$ , $\alpha<\beta$. We need to show that there exists $L$ such that $|f(x,y_1)-f(x,y_2)|\leq L |y_1-y_2|$ holds for all $(x,y_1)$ and $(x,y_2)$ in $D$.
$$|f(x,y_1)-f(x,y_2)|=|x\sin |y_1|-(x^2-2)\arctan y_1-x\sin|y_2|+(x^2-2)\arctan y_2|\\\leq |x| |\sin|y_1|-\sin|y_2||+|x^2-2| |\arctan y_1 - \arctan y_2|\leq \\ \leq 2 |x| \left |\sin \left(\frac{|y_1|-|y_2|}{2} \right) \right |\left |\cos \left(\frac{|y_1|+|y_2|}{2} \right) \right |+|x^2-2| |\arctan y_1 - \arctan y_2|\leq \\ \leq |x| |y_1 - y_2| + |x^2-2| |\arctan y_1 - \arctan y_2|\leq |x| |y_1 - y_2| + |x^2-2| |\arctan y_1 - \arctan y_2|$$
The problem is with the $|x^2-2| |\arctan y_1 - \arctan y_2|$ term. I can't think of a way to get a proper bound for it, that is something like $|x^2-2| |\arctan y_1 - \arctan y_2|\leq f(x) |y_1-y_2|$. Any suggestions?
Comment: @polfosol - "And for these two functions, it is easy to obtain $L=1$" - how do you prove that $|\arctan y_1 - \arctan y_2|\leq |y_1-y_2|$?
Comment: You only need to show that $\sin |y|$ and $\arctan y$ are Lipschitz with respect to $y$. And for these two functions, it is easy to obtain $L=1$. Note that if $f$ is Lipschitz, then $cf$ is also Lipschitz
Comment: If $f$ is a smooth and analytical function and its derivative has a global maximum, then it can be shown that $f$ is Lipschitz and $L\le\sup{f'}$. I am using the mobile app right now and posting an answer is a pain in the butt for me. I will write it as soon as I reach my laptop
Answer: In general, it is better to divide the problem into simpler parts. I think these two statements will help:

If $f$ and $g$ are Lipschitz, then $h=\alpha f+\beta g$ with $\alpha,\beta\in\mathbb R$ is also Lipschitz. This is evident from the triangle inequality:
$$\begin{align}
\lVert h(x_1)-h(x_2)\rVert&= \lVert\alpha f(x_1)+\beta g(x_1)-\left(\alpha f(x_2)+\beta g(x_2)\right)\rVert \\
 & = \lVert\alpha\left(f(x_1)-f(x_2)\right)+\beta\left(g(x_1)-g(x_2)\right)\rVert \\
 & \le |\alpha|\cdot\lVert f(x_1)-f(x_2)\rVert+|\beta|\cdot\lVert g(x_1)-g(x_2)\rVert
\end{align}$$
If $g$ is analytical and $\lVert g'(x)\rVert\le L$ for all $x$, then $g$ is Lipschitz (see here, the first sentence).

To show that $f(x,y)=x\sin{|y|}-(x^2-2)\arctan{y}$ is Lipschitz with respect to $y$, first note that since we are only concerned about $y$, then $x$ can be set fixed. We also know that the $\arctan{y}$ is analytical on $\mathbb R$ and its derivative, $\frac{1}{1+y^2}$ is always positive and has a maximum at $y=0$.
It seems we only need to show that $\sin{|y|}$ is Lipshitz. The sine is an odd function, i.e. $\sin{|y|}=|\sin{y}|$. In this other post on MathSE, it has been shown that $|\sin|$ is Lipschitz.
Answer: Alternative method:
Since $\arctan $ is differentiable, by MVT there exist $y_0$ between $y_1,y_2$ such that
$$
\left|\frac{\arctan y_1 - \arctan y_2}{y_1 - y_2} \right| \ \leq \ \arctan'y_0 \ = \ \frac{1}{1+y_0^2} \ \leq \ 1
$$


dhtmlxgrid table header do not move horizontally with column in mobile application

Question: My DHTMLXGrid table header do not move horizontally with column when I am using in mobile application but in case of desktop browser grid work fine. Can anyone suggest the correct solution?
<code>mygrid = new dhtmlXGridObject('gridbox');
    mygrid.setImagePath("../dhtml/dhtmlxGrid/codebase/imgs/");
    mygrid.setHeader(thead_name_arr.join());
    mygrid.setColumnIds(colID.join());
    mygrid.setColAlign(rowColAlign.join());
    mygrid.setInitWidths(rowColWidth.join());
    mygrid.enableTooltips(toolTips.join());
    mygrid.setSkin("light");
    mygrid.enableColumnMove(true);
    mygrid.setEditable(false);
    mygrid.attachEvent("onRowSelect", doOnRowSelected);
    mygrid.init();
</code>
Answer: Unfortunately the dragging of the columns/rows in dhtmlxGrid is not supported on touch devices.
You can move the columns using the API
https://docs.dhtmlx.com/api__dhtmlxgrid_movecolumn.html
Here you can find an example:
https://dhtmlx.com/docs/products/dhtmlxGrid/samples/16_rows_columns_manipulations/13_pro_grid_moveCol.html


Como comparar todos os valores de um array com uma variável

Question: Gostaria de saber se é possível eu ter um array com várias datas e saber se uma outra data é maior que todas as datas dentro do array.
Por exemplo:
Date[] datas = {"02/02/2000","03/03/2000","04/04/2000"};
Date data1 = "03/01/2000";

Teria como eu saber se a data1 é menor que todas as datas do array datas?
Answer: Primeiramente, não dá para converter diretamente de String para Date. Por isso, precisaremos de uma etapa de conversão:
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    sdf.setLenient(false);

    Date[] datas = {sdf.parse("02/02/2000"), sdf.parse("03/03/2000"), sdf.parse("04/04/2000")};
    Date data1 = sdf.parse("03/01/2000");

Assim sendo, há pelo menos 3 formas de se testar se a data1 é menor que as que estão no array.
A primeira é percorrer as datas do array e compará-las com a data desejada:
        boolean menor1 = true;
        for (Date d : datas) {
            if (d.compareTo(data1) < 0) {
                menor1 = false;
                break;
            }
        }
        System.out.println(menor1 ? "Era a menor." : "Não era a menor.");

A segunda é colocar todas essas datas em um Set ordenado e ver se a que você quer é a primeira (e portanto a menor):
        SortedSet<Date> datas2 = new TreeSet<>();
        for (Date d : datas) {
            datas2.add(d);
        }
        datas2.add(data1);
        boolean menor2 = data1.equals(datas2.first());
        System.out.println(menor2 ? "Era a menor." : "Não era a menor.");

A terceira é semelhante à primeira, mas valendo-se de um Stream:
        boolean menor3 = Stream.of(datas).allMatch(d -> data1.compareTo(d) < 0);
        System.out.println(menor3 ? "Era a menor." : "Não era a menor.");

O código completo para mostrar esses exemplos é esse:
import java.util.Date;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Stream;
import java.text.SimpleDateFormat;
import java.text.ParseException;

class TesteDatas {

    public static void main(String[] args) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        sdf.setLenient(false);

        Date[] datas = {sdf.parse("02/02/2000"), sdf.parse("03/03/2000"), sdf.parse("04/04/2000")};
        Date data1 = sdf.parse("03/01/2000");

        // Exemplo 1.
        boolean menor1 = true;
        for (Date d : datas) {
            if (d.compareTo(data1) < 0) {
                menor1 = false;
                break;
            }
        }
        System.out.println(menor1 ? "Era a menor." : "Não era a menor.");

        // Exemplo 2.
        SortedSet<Date> datas2 = new TreeSet<>();
        for (Date d : datas) {
            datas2.add(d);
        }
        datas2.add(data1);
        boolean menor2 = data1.equals(datas2.first());
        System.out.println(menor2 ? "Era a menor." : "Não era a menor.");

        // Exemplo 3.
        boolean menor3 = Stream.of(datas).allMatch(d -> data1.compareTo(d) < 0);
        System.out.println(menor3 ? "Era a menor." : "Não era a menor.");
    }
}

Veja aqui todas elas funcionando no ideone.
Por fim, recomendo migrar para os tipos do pacote java.time. Veja mais sobre isso nessa outra pergunta.
Para saber se é maior que todas as outras ao invés de menor, na primeira e na terceira abordagem, basta trocar o < por >. Na segunda, basta trocar first por last.
Você também pode querer considerar se a primeira e a terceira abordagem devem usar < por <= para o caso de a data já estar no array dado e mesmo assim ser considerada menor que todas (ou >= se quiser verificar se é maior ao invés de menor).
Comment: Obrigado, amigo. A segunda opção me serviu muito bem.


TypeError: Cannot set property 'usingClientEntryPoint' of undefined

Question: In react-18.0.0 version app I'm writing test case for index.js file I'm getting following error
● Application root › should render without crashing
TypeError: Cannot set property 'usingClientEntryPoint' of undefined

   5 | import reportWebVitals from "./reportWebVitals";
   6 |
>  7 | const root = ReactDOM.createRoot(document.getElementById("root"));
     |                       ^
   8 |
   9 | root.render(
  10 |   <React.StrictMode>

and My index.test.js
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";

jest.mock("react-dom", () => ({ render: jest.fn() }));

describe("Application root", () => {
  it("should render without crashing", () => {
    const div = document.createElement("div");
    div.id = "root";
    document.body.appendChild(div);
    require("./index.js");
    expect(ReactDOM.render).toHaveBeenCalledWith(<App />, div);
  });
});

how to fix the issue.
Comment: I am also facing the same error. Strange not much information is available on this.
Comment: Were you able to solve this? Looks related to https://github.com/facebook/react/issues/24372
Answer: As you are mocking react-dom and since createRoot is exposed from react-dom/client, you would need to do this way instead:
jest.mock("react-dom/client", () => ({
  createRoot: jest.fn().mockImplementation(() => ({
    render: jest.fn()
  }))
}));

describe('Application root', () => {
  it('should render without crashing', () => {
    // render your app here
    expect(renderFn).toHaveBeenCalled();
  });
});

Comment: Could you please update a index.test.js file code
Comment: updated the code to have a test case


sp_send_dbmail succeding but sometimes failing

Question: Also posted in Stack Overflow. Any feed back would be much appreciated.
I have a need for a SQL job to send multiple emails, and I have come across this error that I am unable to find any solutions for. When I send emails this way is succeeds every time I have tested.
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'AzureManagedInstance_dbmail_profile',
@recipients = '*Valid Email Address*',
@body = 'test',
@subject = 'Testing';

When I add a query to the email occasionally the job will fail.
I have pulled out a snippet and simplified the SELECT query that replicates the issue.
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'AzureManagedInstance_dbmail_profile',
@recipients = '*Valid Email Address*',
@body = 'test',
@query =
'
SELECT GETDATE()
',
@subject = 'Testing';

When I run this it successfully sends me an email with the date time, if I run the code again I get the generic error, but not always.

Failed to initialize sqlcmd library with error number -2147467259.

I did some digging with SQL Server Profiler and came across this error message

The connection has been dropped because the principal that opened it subsequently assumed a new security context, and then tried to reset the connection under its impersonated security context. This scenario is not supported. See "Impersonation Overview" in Books Online.

I am currently using a SA account but started with minimal viable privileges.
I have tried running the job under the generic email profile, with the same results.
The job that runs this code will succeed and fail for no apparent reason that I can find. There doesn't seem to be a pattern to the job running successfully or not either.
Has anyone come across this issue and managed to resolve it? Or is anyone able to point me in a direction to solve this?
Answer: Try setting @query_result_header to 0 and @query_no_truncate to 1.
@query_result_header = 1
@query_no_truncate = 0

query_result_header specifies whether the query results include column headers.
The ´query_result_header´ value is of type "bit". When the value is 1, query results contain column headers. When the value is 0, query results do not include column headers. This parameter defaults to 1 (and is only applicable if @query is specified).


Lateral Passes in the NFL

Question: Why are lateral passes so rare in the NFL?
I've seen quite a few situations in which it would seem advantageous.
For example in a 2v1, 2v2 setting when the ball carrier is about to be tackled, why not pass the football to another player who is wide open?
Is the risk of a fumble that high, even in a 3-10 yard pass? Or is it the risk of losing yards?
Comment: You probably want to watch some rugby and the number of times "simple" passes go astray - and that's from professionals who have to have lateral passes as a primary skill.
Comment: @PhilipKendall - and the defense must only interrupt from the forward position.  In football I can sit behind a player and wait for a lateral.
Answer: Yes, I think the risk of turning the ball over would be fairly high.  When one player is running with the ball, all of his teammates are probably trying to block for him.  They may not be prepared to catch a lateral from him.  There will also be defenders chasing him, and they may be in a position to intercept or knock away the lateral.
In addition, a player who wants to throw a lateral needs to turn his head around to see if any teammates are behind him who can catch the lateral.  Then he needs to move the ball from his protective grasp into a position where he can throw it.  This leaves the ball exposed, and since he's no longer paying attention to the defenders in front of him, they may be able to knock the ball loose if he doesn't throw the lateral in time.
There's also a risk of injury.  When a player is running with the ball, he can see the defenders in front of him and can brace himself for a tackle.  But if he turns his head around to see if he can lateral the ball, then he may get hit unexpectedly.  This increases the chances of an injury.
Answer: Using this method often evolves into the read option play. This is more common in college football but has made its way into NFL playbooks on and off over the years. If used as part of a team's playbook, defensive coordinators on the opposing teams will prepare their team by developing plays where the have a "Spy" who plays man coverage on each potential ball carrier (A RB, a WR, and the QB). This most notable reason why this is not more prolific in the NFL is because you need multiple "options" who could be quality ball carriers. Many NFL teams employ a QB who is a strong "pocket passer" but does not have a strong suit in running the ball. Additionally, many NFL teams are reluctant to have their QB exposed to defensive hits for fear of injury. (see RGIII's first season in the league)
Answer: There are two types of passes in american footbal the forward pass and the backwards pass (laterals)
Forward Passes:
Only one forward pass per play is permitted and must be made prior to the ball crossing the line of scrimmage. A forward pass can be made without passing initial line of scrimmage. Gadet plays are used and must be executed properly to avoid penalty.
EX.  Player A passes to Player B who passes long downfield to Player C.    A must throw pass before crossing LOS and B must catch behind spot of A's throw to legally throw to C.
Laterals must always be backwards and if ball touches ground it is considered a fumble and therefore either team can gain possession.
Laterals are high-risk low-reward and rarely used outside of designed QB /HB option runs.
Note: If player on Team A laterals and ball touches ground any player from Team B can advance ball for advantage but only the Team A   player who made missed lateral can advance for advantage.
.
Comment: This seems to be an explanation of the two types of pass in American Football, and doesn't actually answer the question at all.
Comment: it answers by explaning a lateral is more a pitch and less a pass, and explains how the reward is not worth risk unless is last resort
Comment: It *asserts* they are high risk, low reward. What data do you have to support this assertion?
Comment: "Each lateral equated to an average gain of 0.92 EP per play". That sounds like they're a very good idea, not "high risk, low reward" (and yes, I do understand what EP means).
Comment: What you quote is based on laterals made by defensive players following a turnover and does not include offensive plays in in statical breakdown.

Also original question references "3-10 yard pass" which would require a forward pass (illegal forward pass) so describing passing types was answering question along with my  "opinion" on risk/reward. Opinion since as no official lateral stats are kept to support my claim.
But oartial data doea not equal fact making it as unreliable as opinion
Comment: No, the question is referring to a pass which travels 3-10 yards total, not 3-10 yards forward. The OP clearly knows what a lateral is.
Comment: Yes, you're right, it is obvious to me now that it is referring to a backwards pass of 3- 10 yards, just the "wide open" player is a teammate has chosen to stay as far away from the play as possible and provide zero effort in effort to move the football in hopes of catching a pass of -8 yards hoping. Go BillyBoB.
And why make the rugby reference about laterals going astray?
Answer: Laterals are more risky because of the nature of the rules. There's no incomplete lateral, the ball hits the ground it is a fumble. Pass interference rules don't apply, so the defender could hit the person trying to catch a lateral before the ball arrives. A player attempting a forward pass has more protection than someone attempting a lateral because they've declared themselves as a runner. You're no longer considered to be in a defenseless position.
In college, most triple option teams (those that lateral a lot) tend to lead the NCAA in rushing each season. 2014: Georgia Tech, Navy, Army, Airforce, Georgia Southern (converted to spread but runs the option) are all in the top 10 for team rushing.
I'm not sure the typical option play where it is fairly controlled who will be doing the lateraling (usually the QB) and under what circumstances (a targeted defender who is left unblocked) the ball is pitched/lateraled. Also, if you designate players to be behind the ball carrier, they're no longer blocking. It can be difficult to make the right choice and accurate lateral in a freelancing situation. I definitely wouldn't recommend it when running into the line because having so many defenders there, it is easier to disrupt the play from many angles.
Answer: I am not in much agreement with the answers you have gotten.  I think there are three main issues with implementing laterals in the NFL.

Most NFL players do not have the throwing/lateraling ability to do this.  These are not NBA players.  Some have trouble catching the ball let alone throwing it.  Their strong suits are running and strength not hands skills.  This could be improved greatly from practice as I have implemented plays with lateraling at the youth level - and after a while it does become natural.  But now that the NFL has strict guidelines on practice you would never see this implemented as a weapon other than your trick play variety.
From an offensive perspective the lateral puts the defense at an advantage.  The person awaiting the lateral is not FULLY occupying a defender.  Now ball carrier has their guy to beat and possibly another and at the very least has to make a decision.  For this decision making process to happen fast it takes tons and tons of practice.  I have coached every option imaginable from triple wing option to your run of the mill spread read option and the first few weeks of implementation are brutal.
And then the biggest reason we won't see it much in the NFL - speed.  The NFL players are just too fast.  They cover too much space.  Their speed vs. the speed at which the ball travels during a lateral is just too close.  This goes along with why guys like Jay Cutler get paid a lot of money.  He's not the smartest QB but GMs know the speed at which he throws the ball gives their offense an advantage in a very fast game.
Comment: NFL may have strict guidelines for team practice but individuals have an unlimited amount of time to practice a particular skill on their own or getting help from an external coach.

Lateral Passes in the NFL


Como remover uma frase dentro de um arquivo TXT

Question: Opa galerinha,
Estou necessitando de um help, quero remover uma KEY dentro de um arquivo TXT porem não estou conseguindo.
keys.txt:
aLZkGWPXTLVdpVl
w17AzQZIy22soy9
rAcEiWHwopYz2Pk
uKPhbc0Xok5a2aO

meu codigo .php:
<?php
    $texto = "w17AzQZIy22soy9";

    $linha_n = $texto;
    echo $linha_n;

    //Ler o arquivo
    $linhas = explode("\r\n", file_get_contents("youtube.txt"));

    // Abre o arquivo e coloca o ponteiro no final
    $arquivo = fopen('keys.txt','r+');
    if ($arquivo) {
        while(true) {
        $linha = fgets($arquivo);
        if ($linha==null) break;

    // Busca o conteudo que vai ser alterado
    if(preg_match("/$linha_n/", $linha)) {
    $string =+ str_replace("$linha_n", "", $linha);
    } else {
    // Vai colocando tudo numa nova string
    $string =+ $linha;
    }
    }
    // Move o ponteiro para o inicio pois o ftruncate() nao fara isso
    rewind($arquivo);

    // Apagar todo o conteudo
    ftruncate($arquivo, 0);

    // reescreve o conteudo do arquivo
    if (!fwrite($arquivo, $string)) die('Não foi possível atualizar o arquivo.');
    echo 'Arquivo atualizado com sucesso';
    fclose($arquivo);
    }

?>

Poderiam me ajudar galerinha?
obs: ja pesquisei aqui na comunidade e em outros forums nao e encontrei a solucao!
Comment: Importante você [edit] sua pergunta reduzindo o código a um [mcve] do problema com a tentativa de solução. Para aproveitar melhor o site, entender e evitar fechamentos e negativações vale a pena ler o [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045/70).
Answer: Código comentado.
$search = "w17AzQZIy22soy9";
$filename="keys.txt";
$contents = file_get_contents($filename);
$new_contents = "";
if (strpos($contents, $search) !== false) { // se o arquivo contem $search
    $contents_array = explode(PHP_EOL, $contents);
    foreach ($contents_array as &$record) {    // para cada linha
        if (strpos($record, $search) !== false) { // se encontramos a linha correta
            continue; // encontramos a linha a ser excluída - portanto, não adicionaremos ao novo conteúdo.
        } else {
            $new_contents .= $record . "\r"; // não é a linha que queremos excluir, então a mantemos
        }
    }
    $new_contents=trim($new_contents);
    file_put_contents($filename, $new_contents); // salve os registros no arquivo
    echo json_encode("Arquivo atualizado com sucesso!");
}
else {
    echo json_encode($search ." não existe no arquivo!");
}

PHP_EOL - Disponível a partir do PHP 5.0.2

Versões mais antigas $contents_array = explode("\n", $contents);
Comment: resposta aceita significa exito. Retiro os comentários com links
Comment: @GustavoAlves, você testou o que sugeri no comentário acima?
Comment: @GustavoAlves, mas vi o arquivo txt no meu servidor e a linha foi excluida.
Comment: resultado final: consegui arrumar, o erro em si era a VPS que limitava edição de arquivos, comprei outra VPS... Obrigado por ajudar!


Completeness relation and expansion theorem

Question: Why is $$\sum_a u_a(y)u_a^*(x)=\delta(x-y)$$ (the completeness relation) equivalent to saying that for any arbitrary $f(x)$ s.t. $\int_{-\infty}^{\infty}|f(x)| = 1$, $f(x)$ can be expanded as $$\sum_ac_au_a(x)$$, where $c_a$'s are constants (the expansion theorem)?
Thanks.
Symbols:
{$u_a(x)$} are orthonormal eigenfunctions
$\delta(x-y)$ is the Dirac delta function
Comment: Would you please specify what your symbols mean?
Comment: Sure, specification added.
Answer: For any such $f(x)$, multiply both sides by $f(x)$ and integrate with respect to $x$, doing the left hand side term by term. You obtain
$$\sum_a c_a u_a(y) = f(y)$$
Here $c_a = \int f(x)u_a^*(x)\,dx$.
Comment: Thanks! I am having a brain-dead day... sigh...


Polynomial problem with vieta formulas

Question: I was working on an algebra problem set and I came across this question:
let
$$
P(x)=\sum_{i=0}^{20} a_i x^i.
$$
Where $a_{20}=1$ and $a_0=1$ and all coefficients are real numbers. The roots of this polynomial are
$$
-r_{10}, -r_9, \ldots, -r_1, r_1, r_2,\ldots,r_9, r_{10},
$$ where all $r_j$ are positive reals.
Question. Show that $a_2 \cdot a_{18}>100$
I tried using Vieta's formulas but I wasn't really getting anywhere. Some help would be appreciated.
Comment: Please do not vandalize the question after receiving answers.
Comment: this is false, take all the roots arbitrarily close to zero.
Comment: It should also be given that $a_0=1$
Comment: Yeah thanks, I forgot about that. Added it in though.
Answer: Assuming $a_0=1$
Let $\alpha_1,\alpha_2,...,\alpha_{20}$ be the roots of $P(x)=0$
$\Rightarrow\alpha_1+\alpha_2+...+\alpha_{20}=0$
Also, $\frac{1}{\alpha_1}+\frac{1}{\alpha_2}+...\frac{1}{\alpha_{20}}=0$
$$a_{18}=\sum (\alpha_i)(\alpha_j)=\frac{(\alpha_1+\alpha_2+...+\alpha_{20})^2-\alpha_1^2-\alpha_2^2-...-\alpha_{20}^2}{2}=\frac{-\alpha_1^2-\alpha_2^2-...-\alpha_{20}^2}{2}$$
Replacing $x$ by $\frac{1}{x}$ in $P(x)$ we get an equation whose roots are $\frac{1}{\alpha_1},\frac{1}{\alpha_2},...,\frac{1}{\alpha_{20}}$
So, $$a_2=\sum\frac{1}{\alpha_i \alpha_j}=\frac{(\alpha_1^{-1}+\alpha_2^{-1}+...\alpha_{20}^{-1})^{2}-\alpha_1^{-2}-\alpha_2^{-2}-...-\alpha_{20}^{-2}}{2}=\frac{-\alpha_1^{-2}-\alpha_2^{-2}-...-\alpha_{20}^{-2}}{2}$$
$$a_2a_{18}=\left(\frac{-\alpha_1^2-\alpha_2^2-...-\alpha_{20}^2}{2}\right)\left(\frac{-\alpha_1^{-2}-\alpha_2^{-2}-...-\alpha_{20}^{-2}}{2}\right)=\left(\frac{\alpha_1^2+\alpha_2^2-...+\alpha_{20}^2}{2}\right)\left(\frac{\alpha_1^{-2}+\alpha_2^{-2}+...+\alpha_{20}^{-2}}{2}\right)$$
$a_2a_{18}=\left(r_1^2+r_2^2-...+r_{10}^2\right)\left(r_1^{-2}+r_2^{-2}+...+r_{10}^{-2}\right)\geq 100$
(Using the inequality $A.M\geq H.M$)
If $a_1,a_2,...,a_n$ be positive real numbers then $A.M\geq H.M$
$$\frac{a_1+a_2+...+a_n}{n}\geq \frac{n}{\frac{1}{a_1}+\frac{1}{a_2}+...+\frac{1}{a_n}}$$
Comment: Could you elaborate on the last step? (Using AM-HM to prove the product is greater than 100)
Comment: @Cherry . I have edited. Does this meet your requirement.
Comment: I don't get what you are saying. coefficient of $x^{18}$ is sum of product of roots taken two at a time.
Answer: Let $P(x)$ be the given polynomial of degree $20$. Note the roots (of $P$) are all of the form $\{s, -s\}$. It follows that $P$ is a even polynomial, or in other words $a_{19}=a_{17}=a_{15}=\cdots=a_1=0$.
Let $H$ be the set $\{r_1,-r_1, r_2, -r_2, \cdots, r_{10}, -r_{10}\}$. From Vieta's formulae, $a_{18}$ should be the product of roots, each term (taken from $H$) two at a time, that is $r_{1}(r_2+r_3+\cdots+r_{10}-r_1-r_2+\cdots -r_{10})+r_2(r_1+r_3+\cdots+r_{10}-r_1-r_2+\cdots -r_{10})+\cdots$. Hence $a_{18}=-r_{1}^2-r_{2}^2+\cdots-r_{10}^2$. Note that $1=a_{20}=a_{0}$ means $r_1^2r_2^2 \cdots r_{10}^2=1$. As all the roots are positive (that is $r_i>0$) we see $r_1 r_2 \cdots r_{10}=1$.
And similarly $a_2$ is $r_1(r_2r_3\cdots r_{10}(-r_1)(-r_2)\cdots (-r_{9}))+r_1(r_2r_3\cdots r_{10}(-r_2)\cdots (-r_{9})(-r_{10}))+r_1(r_2r_3\cdots r_{10}(-r_1)(-r_2)\cdots(-r_{8})(-r_{10}))+\cdots$.
Hence $a_2$ is $[-(\frac{1}{r_1}+\frac{1}{r_2}+\cdots+\frac{1}{r_{10}})+(\frac{1}{r_2}+\cdots+\frac{1}{r_{10}})]+\cdots$. The dots in the previous sentence come from the terms created by the roots $r_2, r_3$ and so on. Hence $a_2=-\frac{1}{r_1}-\frac{1}{r_2}+\cdots -\frac{1}{r_{10}}$.
So $a_2 \times a_{18}=(\frac{1}{r_1}+\cdots+\frac{1}{r_{10}})(r_{1}^2+r_{2}^2+\cdots+r_{10}^2)$.
Applying the AM-GM inequality, to $\sum_{1 \le i \le 10}r_i^2$, we see $(r_{1}^2+r_{2}^2+\cdots+r_{10}^2) \ge 10$ and again applying the AM-GM inequality to $\frac{1}{r_1}+\cdots+\frac{1}{r_{10}}$, we note $\frac{1}{r_1}+\cdots+\frac{1}{r_{10}} \ge 10$. This gives the desired result.

Polynomial problem with vieta formulas


How to show $\gcd(ac, bd) = \gcd(a,d) * \gcd(b,c)$

Question: Given that $\gcd(a,b) = 1$ and $\gcd(c,d) = 1$, show that $\gcd(ac,bd) = \gcd(a,d) * \gcd(b,c)$.
The work that I have done so far goes as follows.
We write
$$\gcd(ac,bd) = acv + bdu$$
then
$$\gcd(a,d) = ax + dy\quad\text{and}\quad\gcd(b,c) = bs + ct$$
and so
\begin{align}
\gcd(a,d) * gcd(b,c) &= (ax + dy) * (bs + ct) \\
&= axbs + axct + dybs + dyct
\end{align}
I tried to factor out some terms, and get $ax(bs+ct) + dy(bs+ct)$
but then I am stuck here. I don't know what else to use to prove the answer.
Comment: Please consider using [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to format your question - it will make your formulas much more readable
Answer: Let $x = \gcd(a,d)$ and $y= \gcd(b,c)$, then $xy\mid ac$ and $xy\mid bd$ so $\boxed{xy\mid z}$ where $z=\gcd(ac,bd)$.

Vice versa:
We can write $a=xa'$ and $d=xd'$ where $\gcd(a',d')=1$ and $b=yb'$ and $c=yc'$ where $\gcd(b',c')=1$
Now since $z\mid ac = xya'c'$ and $z\mid bd = xyb'd'$
Now if there is prime $p$ such that $p\mid z$ and $\gcd(xy,p)=1$ then $p\mid a'c'$ and $p\mid b'd'$. If $p\mid a'$ then $p\mid b'$ since $\gcd(a',d')=1$. But then $p\mid a$ and $p\mid b$ so $p\mid \gcd(a,b)=1$ a contradiction. So there is no such $p$ and thus $\boxed{z\mid xy}$
Comment: What is the property you are using in the first line where $xy|ac$ and $xy|bd$ so $xy|z$ ?
Comment: $xy$ divide $ac$ and $bd$ so it must divide the greates common divisor of them.
Comment: The greatest common divisor is a multiple of every other common divisor.
Answer: Take all prime factors in turn. We have the following relations between the multiplicities:
$$\gcd(a,b) = 1\iff\min(\alpha,\beta)=0,$$
$$\gcd(a,b) = 1\iff\min(\gamma,\delta)=0,$$
$$\gcd(ac,bd) = \gcd(a,d)  \gcd(b,c)\iff\min(\alpha+\gamma,\beta+\delta)=\min(\alpha,\delta)+\min(\beta,\gamma).$$
If we consider the case $\alpha=\gamma=0$, the last identity reduces to
$$0=0+0.$$
Then with $\beta=\gamma=0$,
$$\min(\alpha,\delta)=\min(\alpha,\delta).$$
By symmetry the other cases hold.
Answer: Let $\gcd(a,d) = g$ so that $a = a'g$ and $d = d'g$ and $\gcd(a',d') =1$.  (why?)
And let $\gcd(b,c) = h$ so that $b =b'h$ and $c= c'h$ and $\gcd(b',c') =1$ (why?).
Then $\gcd(ac,bd) = \gcd(a'c'gh, b'd'gh) = gh*\gcd(a'c',b'd')$. [$\gcd(m*k, n*k) = k\gcd(m,n)$.  (why?)]
And if you take any prime factor of $a'c'$ then it is a prime factor of $a'$ or $c'$ so it is not a prime factor of either $b'$ or $d'$ (as those both coprime to both $a'$ and $c'$; $a$ and $b$ are coprime, $c$ and $d$ are coprime, and so are $a'$ and $d'$ and so are $b'$ and $c'$).  So it is not a prime factor of $b'd'$.  Likewise no prime factor of $b'd'$ is a prime factor of $a'c'$.  So $\gcd(a'c', b'd') = 1$.
So $\gcd(ac, bd) = gh = \gcd(a,d)\gcd(b,c)$.
Comment: How come you can say that $gcd(a',d') = 1$ ?
Comment: @MarioG Isn't it true that the gcd is 1? so $ a = a'*1 $ which is already known since g must be 1.
Comment: @PossiblyDakota The only gcd that is known is $gcd(a,b) = 1$ and $gcd(c,d) = 1$ That is not the $gcd(a,d) = 1$
Comment: @MarioG oh, yes. I misread it.
Comment: "How come you can say that gcd(a′,d′)=1" Because it is.  And I say "why" because I want you to work it out for yourself.  But... see next comment....
Comment: If $a = a'g$ and $b=b'g$ then $\gcd(a',b')|a'$ and $\gcd(a',b')|b'$ so $\gcd(a',b')\times g|a'g = a$ and $\gcd(a',b')\times g|b'g = b$.  So $\gcd(a',b')*g$ is a common divisor of $a$ and $b$.  But $g$ was the *greatest* common divisor $a$ and $b$.  Basically....
Comment: ... If you divide two numbers by their greatest common divisor, can the results have any factors in common?  If they can than that *wasn't* the greatest common divisor, was it?
Answer: Consider (a, d) = d¹ and  (b, c) = d²
In (ac, bd)   we know (a, b) =1 and
(a,d) =d¹ and (c, d) =1 with (c,b)=d²
Then (ac, bd) =d¹d²


Google Spreadsheet - Time zones find text

Question: I have a Google Form where I ask people to tick their time zone and to tick their time slot. An anser may be (each answer is given in one cell):
Time Zone = UTC+8 (Perth, Beijing, Manial, Borneo, Singapore, Taipei)
   Time Slot = Morning (8am - 10am), Late Morning (10am - 12pm), Noon (12pm - 2pm), Afternoon (2pm - 4pm)
Now, I understand that having so much text instead of just a number, isn't helping any spreadsheet use, but somehow people get confused and this seems to be the only way I can get everyone to check the correct box. So in name of userfriendliness..
From these two cells I would like to calculate the time-slot into one particular time zone so I can compare them all(for example Amsterdam being UTC+1). I thought if I can use a function to lookup text, I can turn these cells into numbers.
IF cell CONTAINS "UTC+8" THEN = 8,
and doing the same for the time-slot, I can work with a modulo function or something and go ahead. But I just crossed over from Exel, and I must say Google Search isn't the same and I am a bit confused.
Answer: If you are working with local dates and times, you either need to have an offset for each and every value, or you need to use the full time zone id (not just the offset) to know what those local times represent.  Simply doing math against the UTC offsets is not enough.  That won't take into account all of the different rules involved with time zones, such as daylight savings / summer time.
I am not very fluent with Google Spreadsheet - but it does appear that they have some functions for time zone conversion built in.  I am not sure how accurate they are, but you should review this blog post, which has some good information.


Efeito (animação) no click em aplicativos Windows Phone

Question: Estou criando um aplicativo para o Windows Phone 8.1, usando a linguagem C#. Porém minha aplicação está com itens "estáticos" e ao clicar, ele não cria aquele efeito de entortar mostrando que selecionou algo. Alguém sabe como consigo inserir isso ?
Answer: No código XAML existem as opções de ClickMode:
<code> <Button Content="Button" HorizontalAlignment="Left" Margin="191,161,0,0" VerticalAlignment="Top" ClickMode="Hover"/>
    <Button Content="Button" HorizontalAlignment="Left" Margin="31,161,0,0" VerticalAlignment="Top" ClickMode="Press"/>
    <Button Content="Button" HorizontalAlignment="Left" Margin="31,161,0,0" VerticalAlignment="Top" ClickMode="Release"/>
</code>
Você também pode fazer estas alterações por meio da propriedade do elemento
Comment: Obrigado Anderson. No meu caso seria o efeito do click em uma imagem por exemplo que será levado a uma outra página. De toda forma pode ajudar futuramente.
Answer: Voce pode utilizar o Microsoft.Phone.Controls.Toolkit.
Baixe aqui: The Windows Phone Toolkit
Exemplo de utilização:
Nokia Developers


Combining False Discovery Rates (FDR)?

Question: Suppose we have a population of patients.  For each patient, we measure 1000 features and observe if they suffer from any of 10 diseases.  We wish to determine which features, if any, are significant in predicting each disease.
Because of the multiple hypotheses (the 1000 features), we need to correct our $p$-values.  For example, we might focus on the false discover rate and apply the Benjamini-Hochberg procedure
My question is: do we need to treat this as a single multiple hypothesis problem (1000 features $\times$ 10 diseases = 10,000 hypotheses), or can we treat it as 10 individual problems (each with 1000 hypotheses)?  I'd certainly prefer the latter, since the $p$-value correction will suppress fewer terms.
It's pretty clear that to compute the family-wise error rate, we'd need to combine all the hypotheses.  I was hoping that the FDR might behave differently, and allow me to analyze each disease independently.
More broadly, I would appreciate any pointers towards different statistical tool in case this general approach is off-base.
UPDATE:
I'm treating Michael Lew's thoughtful answer below as correct, but I subsequently stumbled across a more (statistically) powerful tool for handling FDR.  It seems to be very relevant for my problem.  Anyone interested in this problem may find these papers helpful:

Panning for Gold: Model-X Knockoffs for High-dimensional Controlled Variable Selection, 2016.
Gene Hunting with Knockoffs for Hidden Markov Models, 2017.
Answer: You are not testing hypotheses, but fishing for interesting findings. There is nothing wrong with that. Do not do things that are often demanded by those who cannot tell the difference between a preliminary scientific investigation and bad statistics. See my commentary on the ASA's statement on P-values for more detail. (It's in the supplementary material and takes a ridiculous amount of clicking to reach, so here is a direct link to a preprint of it I found online.)
'Correction' of P-value for multiplicity burns the power to detect real effects. Never do it unless you have no alternative, where no alternative comes from an inability to do any sort of follow-up and the absence of any corroboration from other data or theory. Do not dichotomise the results into 'significant' and 'not significant', but show all of the observed effect sizes. (I suspect this response will be voted down, but it is not wrong.)
Treat this as a preliminary investigation. Do not adjust the P-values, but rank the statistical 'interestingness' of the features in order of smallness of the P-values. Then follow up with a study designed to investigate just those features that are statistically and/or scientifically interesting. In this case I would say that even if no follow-up study is possible you should publish the raw P-values so that other investigators can use your data as corroboration for their findings.
Comment: Thank you for that link (which eventually lead me to [this](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3419900/) and several other interesting papers of yours). Your specific suggestion of sharing the raw P-values is definitely a good one. Your broader point about recognizing exploratory statistics is excellent. This question was motivated by a reviewer's request for corrected p-values; instead of providing that, I think I will try to echo some version of your points above. Thank you! (I am left a little mystified as to when one uses the FDR; the "discovery" part lead me to expect this case)
Comment: PS: I updated my question; if you're not already aware of them, you may find the linked papers interesting.

Combining False Discovery Rates (FDR)?


Cannot get hook for custom twig template to work

Question: I have a custom template with the following twig file:
views-view-unformatted--offices_contact_us_page_.html.twig
The view is added as part of extra fields module inside of a Drupal paragraph. I have tried everything but simply cannot get the hook to work, however, the .theme file is loaded correctly as I can add an exit to the preprocess_page() function and that works.
I have tried:

_preprocess_views_view_unformatted()
_preprocess_views_view_unformatted__offices_contact_us()
_proprocess_node()
_preprocess_views()

I am able to inject my variables through the _preprocess_page, but then the variable is not available inside the above view, so need to alter that hook. Any ideas as to what I am doing wrong or alternatively is there a way for me to "print" all hooks that are loaded (like their names) during the request so that I can better determine what I am doing wrong?
Comment: If the view does have a trailing underscore in the name, the preprocess would need to match, e.g. `_preprocess_views_view_unformatted__offices_contact_us_()`
Comment: Template names normally don't contain underscores. Also not in the end. If you put `Foobar` into the template does it get printed or not? Have you enabled Twig debugging? There you'll see next to the template suggestions which hook you can hook in. Where exactly did you place the hooks? And how are they named exactly? Please update your question.
Answer: you can try to debug a possible hook name. To do this, you should enable Twig templates debugging. You can enable it in a next way:

Open the sites/default/services.yml file. If you don't have it - copy sites/default/default.services.yml into sites/default/services.yml.
Find twig.config -> debug parameter, set it as 'true', and save the file.
Clear caches and refresh the page.

Then, please open the browser inspector, and try to find the comment to your template file. You'll see something like this:

THEME HOOK from the comment is the correct one for debugging.
So your preprocess function name should consist of: theme name, "preprocess" word + theme hook from the comment:
<code>THEME_NAME_preprocess_THEME_HOOK
</code>


iOS: Local Notifications Don't Fire On Time

Question: The issue is that my notifications aren't going through when they are set up to. I put a date picker in the nib and a button underneath it. The user is supposed to set the date in the picker, and clicking the button set up the notification to fire 60 hours before the date. So, it looks like I'm just having issues with getting the firedate to recognize the date in the date picker. Here is the code, it is in my view controller:
- (IBAction)scheduleNotifButton:(id)sender {
UILocalNotification *localNotif = [[UILocalNotification alloc] init];

NSDate *selectedDate = [self.datePicker date];

localNotif.fireDate = [selectedDate  dateByAddingTimeInterval:-60*60*60];
localNotif.timeZone = [NSTimeZone defaultTimeZone];

localNotif.alertBody = @"Event is in three days!";

localNotif.alertAction = nil;

localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 0;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Event scheduled."
                                                message:@"You will be notified three days before the event."
                                               delegate:nil
                                      cancelButtonTitle:@"Okay."
                                      otherButtonTitles:nil];
[alert show];

}

And here is some additional code if that helps, this is more code from my view controller that deals with saving the date in the picker that the user entered:
- (IBAction)dateChanged:(id)sender
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    NSDate *selectedDate = [self.datePicker date];

    [defaults setObject:selectedDate forKey:@"ImportantDatesViewController.selectedDate"];
    [defaults synchronize];

}
- (void)viewDidLoad {
    NSDate *storedDate = [[NSUserDefaults standardUserDefaults]
                          objectForKey:@"ImportantDatesViewController.selectedDate"];
    if (storedDate == nil) {
        storedDate = [NSDate date];
    }

    [self.datePicker setDate:storedDate animated:NO];

}

I've been digging through this code for 3 days now and cannot figure out why my notifications aren't going through when they are supposed to. Any help is very much appreciated, thank you!
Answer: Do you understand that UILocalNotifications and remote notifications are different things?
In didRegisterForRemoteNotificationsWithDeviceToken you get the device token to be used for remote notifications. Remote notifications are sent from a server so you have to save that token on your server and then use your server to send any remote notifications.
Why don't you change this:
localNotif.fireDate = [eventDate dateByAddingTimeInterval:-630*60];

to this:
localNotif.fireDate = [[NSDate date] dateByAddingTimeInterval:60];

Then the local notification should go off in a minute. Maybe the problem  is the date that you are setting.
Comment: Thanks. It sends the alert, but it doesn't seem to be dependent on the date the user enters in the picker at all.
Answer: How do you know your notifications aren't working?
Local and push notifications are different. If your app is currently active, a local notification won't actually show an alert message. It will just call a UIApplicationDelegateMethod
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification

Comment: Yeah, that's should be the cause. Anyway, if you want to show an alert in this case, you can manually create a UIAlert and display it manually inside that `- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification` method.


How can I see a visual representation of the difference between Euclidean and Affine geometry?

Question: I have just started studying different types of geometry with the first to I have covered being Euclidean geometry and Affine geometry. I am aware that Euclidean geometry is what we have used the most up until degree-level maths and Affine geometry is to do with the preservation of parallel lines but beyond this I am struggling to visualise the differences between these geometries. I was wondering if anybody knew a good way of explaining this or some resources to aid in my understanding.
Answer: First of all, it can be very useful to know that there is an even more general geometry including Euclidean and affine geometry: Projective geometry (shortly said: the geometry of perspective).
This said, I think that there at least two ways to consider this issue.
First point of view attached to figures :

Euclidean geometry: the image of a square can be a/any square.

Affine geometry: the image of a square is a/any parallelogram.

Projective geometry: the image of a square is a/any quadrilateral.

Second point of view attached to group of transformations (The "modern" point of view developed by Klein in the so-called Erlangen program):

Euclidean geometry is characterized by the group of transformations generated by rotations, symmetries, translations, all of them preserving (Eucledean) norm:

$$\begin{cases}x'&= &a x - \varepsilon b y + e\\y'&=& b x + \varepsilon a y +f\ \end{cases} \ \text{with} \ a^2+b^2=1 \ \ \text{or} \ \ \begin{cases}x'&=&x+ e\\y'&=&y +f\ \end{cases}$$
(with $\varepsilon = +1$ for a rotation, $\varepsilon = -1$ for a symmetry with respect to a straight line ; the second case deals with pure translations).

Affine geometry is characterized by any transformation of the form :

$$\begin{cases}x'&=&ax+by+e\\y'&=&cx+dy+f \end{cases}$$

Projective geometry is characterized by any transformation of the form :

$$\begin{cases}x'&=&(ax+by+e)/(gx+hy+i)\\y'&=&(cx+dy+f)/(gx+hy+i) \end{cases}$$
(please note that if, in the common denominator, we take $f=h=0$ and $i=1$, we are back to an affine transformation).


Soundcloud API - geo tag filtering on tracks returns 503 service unavailable

Question: I cannot seem to search by geotags using Soundcloud's API. Here's what I'm trying:
http://api.soundcloud.com/tracks?client_id=YOUR_CLIENT_ID&tags=geo:lat=41.8819,geo:lon=87.6278
I'm getting a 503 Service Unavailable for only geo tags -- other tags work fine. Any advice?
--
Unanswered related questions
March 8th
Soundcloud api: Geo Tag search not working
April 9th
Search by geo filter with soundcloud api
Comment: Have you tired contacting soundcloud support?
Comment: Have you find any solution?
Answer: Their documentation isn't too great, but if you do it this way it works
http://api.soundcloud.com/tracks?client_id=YOUR_CLIENT_ID&geo:lat=41.8819geo:lon=87.6278
Comment: This returns an empty array for me.


"Android license status unknown" in flutter doctor

Question: I am getting an error with Android Sdk when I run flutter doctor on command-line
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v1.4.9-hotfix.1, on Mac OS X 10.14.4 18E226, locale zh-Hans-CN)
[!] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    ✗ Android license status unknown.
      Try re-installing or updating your Android SDK Manager.
      See https://developer.android.com/studio/#downloads or visit
      https://flutter.io/setup/#android-setup for detailed instructions.
[✓] iOS toolchain - develop for iOS devices (Xcode 10.2)
[✓] Android Studio (version 3.3)
[✓] VS Code (version 1.33.1)
[!] Connected device
    ! No devices available

! Doctor found issues in 2 categories.

After following several possible fixes from the stackoverflow community, i still couldn't get it to work.
Please i need assistance.
Answer: Here's what worked for me
Fix 1:

Launch Android studio & Open the SDK manager (Top-right of Android studio)
Navigate to SDK Tab and look for Android SDK Platform-Tools
If it's checked, unchecked it and click 'Apply' (We're trying to uninstall the previous version)
Now the "SDK Tools" is uninstalled. Let's re-install it by checking the box and clicking 'Apply'
Hit Ok & Restart Android studio
Navigate to SDK install location at %USERPROFILE%\AppData\Local\Android\Sdk for windows, you should see a new folder tools
Note: If you don't see the tools folder don't panic, i got you covered.
Open the tools folder & navigate to bin
Copy the folder path (i.e C:\Users\USERNAME%\AppData\Local\Android\Sdk\tools\bin)
Add that path to Environmental variables
Now you should have access to sdkmanager in the command-line. Try it out by typing sdkmanager & hitting enter in CMD.
If you get 'sdkmanager' is not recognized as an internal or external command, operable program or batch file. you probably made a mistake while adding the path to System Environmental Variables. Fix that.
Go to Flutter sdk folder (i.e c:/src/flutter) & launch the flutter_console.bat file
Now type the command flutter doctor --android-licenses and it should work. Accept all by typing y and hitting ENTER
And don't forget to run flutter doctor

Fix 2:
PS: Only if Fix 1 does not work for you!

Open your browser & goto Command line tools only (bottom of the page)
Download the appropriate package for your platform
Unzip it & Yes! You should see the tools folder
After extraction, copy the tools folder to C:\Users\USERNAME%\AppData\Local\Android\Sdk
Now the same as Fix 1 above,
Open the tools folder & navigate to bin
Copy the folder path (i.e C:\Users\USERNAME%\AppData\Local\Android\Sdk\tools\bin)
Add that path to Environmental variables
Now you should have access to sdkmanager in the command-line. Try it out by typing sdkmanager & hitting enter in CMD.
If you get 'sdkmanager' is not recognized as an internal or external command, operable program or batch file. you probably made a mistake while adding the path to System Environmental Variables. Fix that.
NO you're not done
The SDK Platform tools you downloaded is probably outdated (as you can see when you run the sdkmanager command from the command-line)
Now let's handover to Android Studio to do the rest. Restart Android Studio, so it can recognize the tools folder you added.
After Restart, Android Studio should automatically detect the outdated Platform-tools and prompt you to update (You must be connected to the internet!).
IF UPDATE PROMPT DOES NOT SHOW UP
Open SDK Manager in Android studio,
Go to UPDATES
Click Check Now
And you should get the PROMPT to update Platform-Tools

Fix 3:

Do everything in Fix 2
Open Environmental Variables, Create a new Variable JAVA_HOME and set the value to the JRE/bin (get it from Android studio install location in Program Files)
Open the command line type set JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee' for windows & export JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee' for Linux

And that's it you can now run flutter doctor --android-licenses on the command-line; Accept all licenses by typing y and hitting ENTER. And don't forget to run flutter doctor
THAT'S THE FIX. I HOPE IT WORKS FOR YOU TOO

“Android license status unknown” in flutter doctor


Guitar: using the same finger to pluck

Question: I've learned playing the guitar by myself, but now I'm following some book courses. In the books you never play a note with the same finger (right hand), but for example like the pattern MIMIMI...
Is there a good reason to break this habit? (and that's really difficult, my left hand is not a problem, just having to concentrate on my right hand to be alternating between fingers is a problem)
Any thoughts?
Answer: No, and yes. Alternating the plucking fingers, like most of the tried and tested techniques for playing musical instruments, is about efficiency and maximising musical expression. While M is making the return trip, I is plucking, so this doubles the plucking speed over one finger plucking and makes string crossing more efficient. The result is greater musical fluency. Yes, it is hard, but it is well worth the effort. It will be easier to learn two fingers now, in the early days of your guitar experience, than trying to swap later. It's important to practise it MI and also IM because some passages, especially those requiring string crossing, will require it. I also get my students to practise plucking like a drum paradiddle: IIMI  MMIM to open up more possibilities.
As for the Yes, plenty of wonderful music has been made by one fingered pluckers. Many have no choice: they may only have one finger. The bass lines for a significant number of the big Motown pop hits were played by James Jameson plucking with one finger. But why make it hard on yourself?
Finally there is the one finger tremolo involving both downstrokes and upstrokes. This is certainly worth practising, but I'd master the two finger method first.
Answer: Alternating fingers is essential for maintaining higher speeds.  Take this video of a classically plucked version (a lot of versions you can find do hammer-ons instead) of Rimsky-Korsakov's "Flight of the Bumblebee".
The right hand is quite busy making sure that every note is actually being plucked and even alternating just two fingers would make it hard maintaining the resulting speed.
Imagine just using a single finger here.

Guitar: using the same finger to pluck


SQLite syntax for "ALL"

Question: Is there a way to do the following in SQLite?
select name
from   table
where  number >= ALL (<subquery, "such as select x from table ...">)

Specifically, I'm getting a syntax error after the ALL operator, no matter how I format my query. In my googling for a solution, I found some mention that the syntax for ALL is different in SQLite, but I can't seem to figure it out.
Can someone show me how a basic ALL (<subquery>) statement works in SQLite? Or let me know if they don't work at all?
Answer: I doubt that there is an ALL() operator in SQLite.  However, you can write something that is functionally equivalent using MAX() and MIN().
SELECT name
FROM table
WHERE number >= (SELECT MAX(another_number) FROM another_table WHERE ...)

Comment: This query **not** equivalent when the subquery has zero results. In that case, `number >= ALL ...` would be true, but `number >= (SELECT MAX(...` would be false. The max of nothing is null, and any comparison with null is unknown (which gets turned into false).
Answer: SQLite does have an ALL keyword; but, it does not do what you want it to. (Fortunately, @lawrence's answer does.)
While the ALL keyword is not permitted as part of the WHERE expression, the keyword can appear a couple of other places.
From http://www.sqlite.org/lang_select.html:
SELECT ALL * ...

One of the ALL or DISTINCT keywords may follow the SELECT keyword in a simple SELECT statement. If the simple SELECT is a SELECT ALL, then the entire set of result rows are returned by the SELECT. If neither ALL or DISTINCT are present, then the behavior is as if ALL were specified.

SELECT ... UNION ALL SELECT ...

A compound SELECT created using UNION ALL operator returns all the rows from the SELECT to the left of the UNION ALL operator, and all the rows from the SELECT to the right of it. The UNION operator works the same way as UNION ALL, except that duplicate rows are removed from the final result set.
Answer: SQLite does not have an ALL operator. You might be tempted to write something like this:
select ... where number >= (select max(...) from ...);

However, this is not equivalent to the original query in all cases. If the subquery has no results, then number is greater than all of them (vacuously true). But the maximum of zero numbers is NULL, and number >= NULL is false (or rather, unknown in ternary logic, which gets treated as false in the end).
The following query is equivalent to the one using ALL, including for the empty result case:
select ... where not exists (select * from ... where number < X);

SQLite syntax for "ALL"


MCU packet capture

Question: I am trying to do a packet capture of a video conference hosted with CISCO [Codian] MCU. The instructions for capturing SIP packets with Wireshark are available. I also configured MCU to accept SIP calls.
I have installed X-Lite as a SIP client and set the host to the IP address of my MCU. I configured the softphone to not register with a proxy, and place calls using the same credentials that I use to sign into the MCU.
When I call my conference, it seems to INVITE and ACK go thru. Sorry, I don't know SIP.
Either way, it appears that MCU answers the call and my client is sending video - only I get nothing in return.
Please advise.
Answer: It seems that my residential ISP was blocking SIP traffic. From my office, everything works fine. Sorry for bothering.
Comment: most probably it's the NAT traversal. I don't believe that an ISP in Czech Republic would block anything. It's happening in Arab countries, but I can guess it's not your case by looking at your name :-)
Comment: @StanislavSinyagin
Port blocking is pretty common in Europe. Wireless do this more than residential, either not rare at all. For example, I know that LycosMobile blocks VPNs. Some Telcos have plans without blocking that cost more... STUN/TURN work fine from my home. Otherwise, I would be screwed capitally. :)

MCU packet capture


Effective way to learn spin in table tennis

Question: I am 25 and I started playing table tennis 6 months ago. Since then I've played almost every weekday for at least 20 minutes. Currently I can play the standard shots. But I am not winning matches against the best players. It is mainly due to two reasons for me:

Serve: while serving, very often I tend to serve a "no-spin easy serve", or a service fault.
Return of serve: while returning side spin serves and other heavy spin serves, I mishit.

I know this is a fairly big question. But I feel it will be useful for the beginners like me to go in the right direction for improving further.
Answer: I understand your problem, that's common for all beginners.
There are some training exercises for you:

Firstly, FEEL THE BALL: Try to master all of these services: topspin, no spin, and backspin serve. By doing the serve yourself, you can feel the "gesture" of the serve; you can also feel the speed, the spin of this type of spin.
Secondly, when you master the serving game, now, master the receive game. Ask your partner, at the same level of yours, to serve only topspin for 1 hour, only backspin for 1 hour, no spin for 1 hour, and you try to master your own return. Then finally mix them randomly.

With these two exercises, you will soon decrease your weakness in the match-game. It takes time, but firstly try it slowly in the training session. Don't rush and you will succeed.
Answer: The only way to master and play a sport to the best of your ability is PRACTICE, PRACTICE and more PRACTICE.
20 minutes of play time for 5 days a week is far too little to compete and give a fight against better players. You need to increase this practice time and make it more effective.
Find a player who is of your competence level in the sport and practice with him/her. Have a practice schedule: for example, one person can try out different spin serves while the other can receive it for the first 10 minutes. In the next 10 minutes, you can reverse roles. You can then move on to chops, rallies, smashes, etc. This helps keep the routine mixed so you don't get bored with one thing, as such. At the end of the practice session, both of you can have a match, where you can try out all the things that you might have practiced in the day.
When you don't have a table to play on, you can practice against the wall. Another way would be to for two players to play on a thin long horizontal stool/table, instead of the normal table. This will help you place the ball better and perfect your direction choosing abilities and the angles with which you play the shot, as the table is much narrower than the original table used in table tennis.
Comment: Not sure [Allen Iverson](http://espn.go.com/blog/playbook/fandom/post/_/id/2026/allen-iversons-practice-rant-10-years-later) would approve...


Activerecord :include additional conditions

Question: How do you specify a JOIN ON clause in ActiveRecord?
When using the :include parameter to the ActiveRecord.find method, the created SQL uses the JOIN operation with the ON clause of foreign key=primary key. For example:
A.find(:include => :B)

results in
select ... from A
  left outer join B on B.a_id=A.id

Now to my example:
A.find(:include => { :B => { :include => :C } } )

results in:
select ... from A
  left outer join B on B.a_id=A.id
  left outer join C on C.b_id=B.id

But, I only want some of the records in C, but if none are found then I still want A and B
This does not work
A.find(:include => { :B => { :include => :C } },
  :condition => "C.rec<10" )

Because that results in:
select ... from A
  left outer join B on B.a_id=A.id
  left outer join C on C.b_id=B.id
  where C.rec<10

How do I instruct AcriveRecord to create a query like this?
select ... from A
  left outer join B on B.a_id=A.id
  left outer join C on C.b_id=B.id and C.rec<10

Answer: I don't know of a way to add an ON clause with association methods.
For your example, the easiest way to eager-load only some records in C is to define an association with conditions in B.  (See the "Eager loading of associations" section of this ActiveRecord::Associations API documentation.)
class A < ActiveRecord::Base
    has_many :bs
end

class B < ActiveRecord::Base
    has_many :cs
    has_many :cs_with_rec_less_than_10, :class_name => 'C', :conditions => ['rec < 10']
end

class C < ActiveRecord::Base
end

You can call:
A.includes(:bs => :cs_with_rec_less_than_10)

This will generate 3 queries, one to each table, rather than joining them in 1 query.  For example, if A and B each contain 2 records with IDs 1 and 2:
SELECT "as".* FROM "as"
SELECT "bs".* FROM "bs" WHERE ("bs".a_id IN (1,2))
SELECT "cs".* FROM "cs" WHERE ("cs".b_id IN (1,2) AND (rec < 10))

If it's important to make a single query using left joins I would write the query manually, execute it with ActiveRecord::Base.connection.execute, and handle the result directly.
Answer: This is probably not the most Railistic solution, but I find it handy when I am in despair of searching for Railstic sulutions.
I trust you can figure out what to do with below example and hope you can find it useful somehow.
@visits = Visit.select("v.*, c.*" ).
  where("u.id = ?", session[:user_id]).
  joins( %{ as v inner join customers as c on (v.customer_id = c.id)
      inner join businesses as b on (v.business_id = b.id)
      inner join managers as m on (b.manager_id = m.id)
      inner join users as u on (m.user_id = u.id)
      } ).
  order(' v.created_at DESC')


Auto update time in SQL Server

Question: I would like to have two columns in my table to store the add-time and update-time. As the name suggests, the add-time is the time when a row was first added; the update-time is the last time a row was updated. I can implement first by defaulting value to GETDATE(). As for the second, @Jeremy suggested using triggers here:
On Update: Auto Update Date/Time Field

Is there any easier way?
If I implement a trigger, does that mean two UPDATE statements (or one INSERT and one UPDATE in case the row is just created) have to be executed?

Thanks.
EDIT: For the second part of the question, this is the trigger I have in my database:
CREATE TRIGGER [dbo].[TR_AddUpdateTime]
   ON [dbo].[AddUpdateTime]
   AFTER UPDATE
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for trigger here

    UPDATE r
       SET UpdateTime = GETDATE()
      FROM AddUpdateTime r
      JOIN inserted i
        ON i.Id = r.Id
END

Does this mean that an additional update statement will be executed whenever I make an update to AddUpdateTime table, or MSSQL is smart enough to recognise that I am updating the same record and save both changes at the same time?
Comment: Are you always updating/inserting through a stored proc? You could just get that to insert the time.
Comment: No, I am using Entity Framework actually.
Comment: I edited my answer to have an option for entity framework.
Answer:
You could make sure all inserts and updates go through a stored procedure that inserts the time.
No, the insert trigger will modify the values so that it's only one statement.

Edit: For entity framework could you implement the OnSavingChanges event to insert the update-time field (see here)? This is moving the responsibility from the DB to the Code which you may or may not be comfortable with.
Comment: So there seems to be some confusion. You said that the trigger will not cause an extra UPDATE statement to be executed, but that is the opposite of what @gbn said above!
Comment: I edited my question for you to see the trigger I added to the database.
Answer:
Other ways:

Use a stored procedure to wrap the updates
You can do UPDATE MyTable SET ..., UpdatedWhen = DEFAULT...

You need an UPDATE trigger that itself has one more UPDATE. Using a default on the table means you don't need a trigger for INSERT
Comment: As I mentioned in my comment on @paulsm4's answer, I don't want to use a stored procedure. I also don't want to manually set the UpdateTime whenever I want to update a record, as I want the solution to be generic to use it in many tables.
Comment: As for your second comment, I am only using the default value for the add-time, because it is only set the first time a record is created. But the update-time needs to be updated whenever I make any change to a record.
Comment: @Promather: you can use the DEFAULT keyword in a update to set it. SO if the default is GETDATE(), then UpdatedWhen will be *updated* with the latest date. Even if you use a trigger, this means that the GETDATE is only mentioned in the constraint: not in code.
Comment: Yes, that's a good point. But still I need to always add UpdatedWhen = DEFAULT to each UPDATE statement, which is not a good practice.
Comment: @Promather: It sounds like your default value on the 'add-time' will take care of that field on INSERT.  An UPDATE trigger, as gbn suggests, will fire whenever a row is updated.  The trigger, in turn, needs to do an UPDATE to set the 'update-time'.  Makes sense?
Comment: OK, it makes now. But the problem is that the answer to the second question seems to contradict that of Ray's below, so not sure which one is correct! I edited my question to include the trigger I created in my database.
Comment: @Promather: your trigger looks correct and is all you need. An insert trigger is not needed. Note: if you use the DB server for the GETDATE() then the same server generates it. You could get discrepancies if the server running EF generates the values between multiple client servers or between DB and client server.
Answer: In entity framework, you can use the partial class to extend the business logic. In this case, you can use OnPropertyChanged to set the update-time to DateTime.Now. You can use this article on MSDN as a guidance.
Answer: 1) "Auto update" and "triggers" doesn't really sound like the way to go.
2) SQL Server has a (relatively new) "merge" statement.  But that doesn't really sound like what you're looking for, either.
3) Instead:
a) If primary key doesn't exist (if "new"), then INSERT.  In this case, first time = last time = GETDATE().
b) Otherwise, if the primary key already exists, then UPDATE.  Your update will update only the "last time" column (along with the rest of the fields you need to update for this record.
4) Perhaps you can wrap this logic in a stored procedure?
5) Again - the key is to update BOTH "first time" and "last time*, the FIRST TIME, and then update ONLY "last time" all SUBSEQUENT times.
Comment: Well, I want my record to get automatically updated, without having to write a stored procedure as I am using Entity Framework and I am not sure how to make Entity Framework use my stored procedure for inserting/updating records.
Answer:
They might be an easier way but using triggers will be more effective and will guarantee no mater how records inseted or updated (from .net code or direct table inserts/updates), those two fields are populated
To Gurantee that only one trigger get fired each time, combine insert and update trigger
 CREATE TRIGGER <trigger name> ON TableA for INSERT,UPDATE

And do conditional checking to distinguish between two actions
 IF UPDATE

Auto update time in SQL Server


Can larger p-values suggest higher similarities?

Question: I'm comparing the means of two groups--A and B, using t-test. Can I say a larger p-value (e.g. 0.94) suggests higher tendencies towards similarity than a smaller p-value (e.g. 0.08)? I understand that the p-value is the probability of the observing the data when the null is true (A=B), but not sure if I can infer that from this statement. Thanks!
Comment: What are "higher tendencies towards similarity" supposed to be when you are comparing two means?  Please note that the p-value is not as you have characterized it.  For more information, please [search our site](http://stats.stackexchange.com/questions/tagged/p-value?sort=votes&pageSize=50).
Comment: If the null hypothesis is true then a high $p$-value simply tells you that the two *samples* are similar, indeed if it greater than $0.5$ then the samples are more similar than would happen half the time.  There is not much special about this: it happens half the time.
Answer: If the P-value is small then either the Null Hypothesis is True and you have observed a rare event, or the Null Hypothesis is False.
If the P-value is less than significance level (alpha) you reject the null hypothesis
· If the P-value is more than significance level (alpha) you fail to reject the null hypothesis.
A low p-value is a low probability. This means your data is unusual and is closer to the alternative hypothesis than the null.
As whuber suggests, "higher tendencies towards similarity" is not meaningful in this context.


Select 2 empty value in dropdown

Question: I want to display option in my dropdown without value, but select 2 prohibits it.
<select name="searchcategory[]" multiple="multiple" class="js-example-basic-multiple">
          <option value=''>All Category</option>
</select>

my select2 js
$(".js-example-basic-multiple").select2({
    placeholder: "Choose category",
});

Comment: Just put something like `-1` or zero on it....
Comment: i want to perform it without any value
Comment: Possible duplicate of [Reset select2 value and show placeholder](http://stackoverflow.com/questions/17957040/reset-select2-value-and-show-placeholder)
Comment: Any solutions to this problem? i am currently stump on this issue as well
Answer: Use selected in the <option selected> tag like this:
<select name="searchcategory[]" multiple="multiple" class="js-example-basic-multiple">
  <option value='' selected>All Category</option>
</select>

Hope this helps!
Comment: sorry no it ruined my style
Answer: To reset simply call again select2
$(".js-example-basic-multiple").select2("val", "");

Reference from:
Reset select2 value and show placeholder

Select 2 empty value in dropdown


How can I introduce a band into working with a drummer?

Question: I auditioned for a band the other day, this band has music that they wrote, BUT they had never wrote the material with Drums in mind. The band never had a drummer before.
This wasn't that much of an issue until it came to rehearsing their material... the timing was so odd and choppy it was quite hard for me to stay in time with them and them with me. They also seemed to not have much experience with timing a song with drums...
How can I introduce the theory of drumming and timing to the band without:
A: insulting their music playing and/or their Music Experience
B: confusing them too much with how to keep time with a drummer (ie what timing signatures they play in comparison to the timing signatures I stick with)
Also how can I train their ear so that we can write in better harmony in the future?
I managed to figure out what timings they were playing but it ranged from 4/4 to 7/4 to 10/4 and back again... as a drummer I am used to 4/4 and 7/4 but 10/4? that is an unnecessary leap if not and a tad out of my experience range I would like to build up to that but am not sure how...
Answer: I joined a band, as a bass player, where we DID have a drummer but I was the only member with any sort of "formal" music training (rhythm exercises, reading music, etc.) and we had similar problems. Our timing was off, and we'd drag sometimes. We'd all stay together, but we couldn't play anything tight.
What worked for me, to get the issue of rhythm into the forefront of their minds, when they didn't think there was a problem:

Get them excited about playing some technically demanding music. For us, it was some funky stuff from Stevie Wonder. I showed them the song, got them excited, and then we went to play it and it was a disaster, but they didn't know why. I did - we had bad rhythm. So we broke the song down, with a metronome, and worked through it.
Try to record their songs with a clicktrack. We laid down a 5 song EP, but the realities of the recording studio caused them quite a bit of stress. When we play primarily just by feel it ends up being hard for people to adjust to a clicktrack when they've never done that sort of thing before.

Just what worked for me. Primarily, I think you need to find a way for them to hear that there's a problem, without you telling them there is. That's tough, but once they're on board you should be well on your way.
Answer: This question is probably more about etiquette than music. They way to avoid giving offence is to frame it as your problem, not theirs - "I'm having some trouble with the rhythm here, I wonder if you can help me..."
What you need to work out is whether the complex time signature changes are deliberate or accidental. Perhaps they're prog-heads who enjoy deviating from a regular 4/4 beat; or perhaps they're "instinctive" musicians who play what they feel rather than being confined by an unchanging beat.
Whichever it is, it sounds as if they can keep together without a drummer - to it makes sense to assume that once you've communicated properly, a drummer will be able to keep together with them too.
There are two scenarios here:

Their intention is not to have weird timing. You get to say "OK, I'll stay in 4/4 no matter what. If we go out of sync, it was you. We'll keep trying until you get it right."
Their intention is to have the occasional long or short bar; you're going to have to learn to play them. But to help you, they're going to have to be write down the arrangements (maybe you work on this together) so you have a clear notation of where the changes happen.

It's possible that there's a chasm in ability that means the band can't work.

If you're not ready for the complex time changes they want: they need to simplify their songs or, I'm sorry, get a more experienced drummer.
Or if they're not capable of sticking to a rhythm: you need to be very patient with them, and they need to practice with a drum machine (or a metronome that has a different click for the first beat of a bar).
Answer: I guess they've not recorded and listened to their renditions. If they did that, and tapped along or tried to dance to the tunes, it may bring some home truths. They have probably played together for so long and rehearsed so much that anomalies in timing have crept in. 'Practice makes perfect' - it also makes unknown mistakes indelible.
On the other hand, they may be so advanced in what they're doing that it's exactly as it should be. This being the case, you need to ask them to explain, in graphic detail, what that particular bar consists of "so I can understand and play it right". Then, a penny may drop, and they may have to try to understand what they are actually doing : it will be the same for anyone else playing with that band, obviously.
One way or the other, as slim intimates, you may find your paths diverging. Been there too many times...
Answer: At the end of the day, there is nothing wrong with frequent time signature changes, as long as it's groovy, nor with tempo changes, as long as everyone does them together.
If you're going to have that kind of weird stuff, though, it will probably be as off-putting to a listener as it was to you.
Whether or not the way they currently have arranged it is the best, the road forward is pretty much the same.
The best thing for the band to do is to record themselves, and try to dance, or at the very least tap, along to the music. This will help them see how weird it is.
The best thing for **you* to do is to record the band, and then listen to it over and over and over again until you're familiar enough to play along and follow them. You might have to give up your comfort zone of playing a repetitive beat.


Correlating two questionnaires with grouped items

Question: I need to correlate employee engagement (gathered data using the 9 item UWES questionnaire) and organizational commitment (gathered data using the 18 item Organizational Commitment Scale).
The both of them can be divided into different components;

UWES - Vigour (3-items in questionnaire), Dedication (3 items in questionnaire) & Commitment (3 items in questionnaire).
OCS - Affective Commitment (6 items in questionnaire), Continuance Commitment (6 items in questionnaire) & Normative Commitment (6 items in questionnaire).

I have an R-matrix set up correlating all the individual questions from both questionnaires, using Pearson's r. However I would like to correlate the components, and not individual items from the questionnaires.

What would you recommend I use?
Thanks!
Answer: Depends on how much (many?) data you have. If your sample is rather small, you'll probably need to settle for the classical test theory (CTT) assumptions. I've reviewed these in a few other answers to:

Correlational study or ordinal data using 5-point Likert scale
Regression testing after dimension reduction

Basically, you'd treat your ordinal data as numeric, take the sum or average of individuals' responses to items intended to measure the same latent factor (which you refer to as a component), and use that as your score for the individual on that factor. Repeat for the other factors and proceed to calculate your correlations among the scores, if that's all you're really after. Schaufeli and Bakker (2003) seem to describe similar procedures for the 9-item UWES (but I've just skimmed it TBH), so this may be the best approach despite the assumptions it makes, because it would probably make your measurement model maximally comparable to that used in other studies with this measure.
If you have plenty of data, you might consider other methods of estimating factor scores like I've discussed on yet another answer to "Factor analysis of questionnaires composed of Likert items". chl's answer there is well worth considering too, since all sorts of response bias can affect Likert ratings. There's a surprising amount of correction you can perform with enough data.
Bias corrections aside, you could implement the factor analytic approach by calculating a polychoric correlation matrix of your 27 items. Feed that into a confirmatory factor analysis, and estimate correlations among the latent factors. Getting accurate estimates will require a lot of data, but these estimates won't involve as many assumptions as the CTT approach. They'll accommodate the ordinal nature of Likert data, estimate factor scores using only common variance among items, estimate how much unique variance each item has that doesn't belong to the intended factors, and estimate how much item covariance is explained by the model. That's a lot of extra info, if you have the data for it.

Reference
Schaufeli, W. B., & Bakker, A. B. (2003). Utrecht work engagement scale: Preliminary manual. Occupational Health Psychology Unit, Utrecht University, Utrecht.


Feeds Importer Xpath import where guid is at the top of the context

Question: Trying to import from an XML feed using Feeds Importer XPath XML. I have had an import working from this same feed before but with uniqueness based on a title field which is no longer apropriate.
I'm trying to alter the import so that I now use a guid. The problem is that the ID I need to use is only located within the top level element where the context starts.
XML looks like:
<vacancies>
  <vacancy id="111427">
    <uri>https://data.ox.ac.uk/id/vacancy/111427</uri>
    <url>https://data.ox.ac.uk/doc/vacancy/111427</url>
    <webpage>https://www.recruit.ox.ac.uk/pls/hrisliverecruit...</webpage>
    Postdoctoral Scientist - Protein Biochemistry
    <opens>2014-01-16T09:08:14+00:00</opens>
    <closes>2014-02-17T12:00:00+00:00</closes>
    ...

My context is
    /vacancies/vacancy
and I am mapping my guid to @id which I think is the correct syntax.
The import doesn't work correctly, I get no nodes and no errors. What am I doing wrong (if anything)? There is nothing I can do about the XML schema incidentally, if that is where the problem is.
Comment: Have you gone through the issue queue?  We have had trouble with this module, and have had to use some of the patches from the queue.
Answer: I just did a quick test of this, with your sample data, and it works correctly.
In the debug options you can enable error reporting, as well as, show the outputs of various queries.
Comment: OK, what was the syntax you used for the context and the guid mapping where it worked?
Comment: I've abandoned the XML approach and tried with a JSON version of the same feed... which has let to a new issue...


Can Android TV display portrait? (flutter)

Question: Is it possible to make an application on Android TV but the display must be portrait according to the size of the TV, using the Flutter programming language
Example AndroidManifest.xml

```
<activity
   android:name=".MainActivity"
   android:exported="true"
   android:launchMode="singleTop"
   android:theme="@style/LaunchTheme"
   android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
   android:hardwareAccelerated="true"
   android:windowSoftInputMode="adjustResize"
   android:screenOrientation="portrait">
```

Results:

Thank you very much
Comment: Do you mean you want to use the TV sideways or something?
Comment: Yes, sideways like the portrait position of a phone
Answer: we get the idea of the position we rotate
Example AndroidManifest.xml
<activity
   android:name=".MainActivity"
   android:exported="true"
   android:launchMode="singleTop"
   android:theme="@style/LaunchTheme"
   android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
   android:hardwareAccelerated="true"
   android:windowSoftInputMode="adjustResize">

Example page.dart
@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Center(
      child: RotatedBox(
        quarterTurns: 3,
        child: Container(
          padding: const EdgeInsets.all(8.0),
          color: const Color(0xFFE8581C),
          child: const Text('data'),
        ),
      ),
    )
  );
}

Results