É possivel definir o tipo de retorno de uma Promise?

Question: Bom dia. Gostaria de saber se é possivel definir o tipo de retorno de uma Promise com typescript. Preciso disso pois tenho uma função que retorna uma promise para uma consulta no banco de dados e preciso que quando a consulta seja realizada o retorno seja um objeto (no meu caso um produto), porem o then() retorna um tipo unknown. Segue em anexo um exemplo do código que retorna a promise:

getProtudo(idProduto) {
    return new Promise((res, rej) => {
      this.bancoSrc.banco.find({
        selector: {type: 'produto', _id: idProduto},
        fields: ['_id', 'descricao', 'referencia']
       }).then((result) => {
        this.produto = JSON.parse(result);
        res(this.produto);
       }).catch(err => {
        rej(err);
       });
    });
  }

E aqui vai o código que utiliza essa promise:

this.pickerCtrl.create(opts).then((picker) => {
  picker.present();
  picker.onDidDismiss().then(async (data) => {
    const col = await picker.getColumn('quantidade');
    this.produtoSrc.getProtudo(idProduto).then((prod) => {
      const qtd = col.options[col.selectedIndex].value;
      const pedido: Produto = new Produto(prod._id, prod.descricao, qtd, 10);
      this.listaPedido.add(pedido);
    });
  });
});
  }

Não consigo criar o objeto porque quando tendo usar o prod._id no create do meu objeto, dá o seguinte erro: ": "Property '_id' does not exist on type 'unknown'.
Dessa forma que postei acima esta funcionando. Mas agora tenho outra duvida, o meu objeto esta chegando como undefined quando tento acessar as propriedades dele. Função:
getProtudo(idProduto) {
    return new Promise<Produto> ((res, rej) => {
      this.bancoSrc.banco.find({
        selector: {type: 'produto', _id: idProduto},
        fields: ['_id', 'descricao', 'referencia']
       }).then((result) => {
        res(result);
       }).catch(err => {
        rej(err);
       });
    });
  }

Se eu exibi-lo atrás do console apresenta a seguinte resposta:
docs: Array(1)
0: {_id: "produto-1", descricao: "LANTERNA DIANT DIR", referencia: "KADETTE"}
length: 1
__proto__: Array(0)
__proto__: Object

Alguém consegue me ajudar com isso? Grato desde já.
Comment: Gustavomgu, o seu método `getProtudo` está retornando um array, por isso você não está conseguindo acessar a propriedade `_id` diretamente. Já que a sua função só deveria retornar um objeto, ao invés de fazer `res(result)`, faça `res(result[0])`. Talvez você precise fazer o `JSON.parse` também como você estava fazendo no primeiro exemplo.
Comment: Tem razão, era um array mesmo, para conseguir acessar usei result.docs[0]. (Tive que fazer isso porque estou resgatando a informação de um banco de dados NoSQL)
Answer: Você só precisa fazer o uso de generics para definir o retorno da promise. No caso de uma promise que resolve um número, o tipo do seu retorno seria Promise<number>.
Como você está retornando um objeto, você pode definir as propriedades do seu objeto resolvido na assinatura da própria função:
getProtudo(idProduto): Promise<{_id: string, descricao: string, referencia: string}> {

}

Ou se você já tem o tipo desse objeto definido, você pode utilizar alguns recursos do TypeScript para gerar o tipo dinamicamente a partir de uma interface base:
// exemplo de interface
interface MeuTipo {
    _id: string
    descricao: string
    referencia: string
    outraInformacao: number
    maisInformacao: string[]
}

// Apenas as propriedades que foram buscadas no banco de dados
getProtudo(idProduto): Promise<Pick<MeuTipo, '_id' | 'descricao' | 'referencia'>> {

}

Comment: Muito obrigado pela ajuda. Funcionou bem, porem ainda tive um problema aqui. Eu não estou usando uma interface mas sim uma classe, daí ele apresenta uma mensagem de erro: 'Pick' only refers to a type, but is being used as a value here
Comment: Usar classe ou interface não deveria fazer nenhuma diferença para o `Pick`, talvez se você postar a definição da sua classe eu possa checar o que está acontecendo.
Comment: Por favor, edite a sua pergunta. Interpretar os comentários sem formação fica meio difícil. E inclua a declaração da sua classe `Produto` também.
Comment: Editei a pergunta e removi os comentários com código não formatado.


user/%/edit - remove it from tab and make it an actual menu item

Question: I am pretty clueless on how drupal handles such things and I can't seem to grasp the context.
I want a menu link to user/%/edit (using menu token already). But as it seems /edit is a 'tab' item of the user/% menu (also saw it in the db). Using theming I have visually removed the unwanted tabs and I've also merged the user/edit form with the profile2 forms I need for extra fields using form_alter.
The problem is that even though I have a menu link called "My Account" linking to user/%/edit,
whenever I click it to go there, the "Edit" menu link appears as active in my main menu instead of the "My Account".
Is there any way to remedy this?
If the question is not clear I will revise it cause it's a pretty confusing issue.
EDIT: to avoid similar answers, the problem is not how to visually remove the tabs, the problem is how to somehow alter or ignore the user/* menu structure so the "Edit" part is not a separate tab anymore and thus it won't show when I click the link that leads to to user/%/edit
Comment: I have hidden the tabs in page preprocess so I wouldn't mind if edit appearead as active as long as it was hidden. No, the buggy part is that the current tab's name (Edit in this case) shows up as a link (furthermore the *current* selected link) in the Main Menu instead of my link (which is also there but not active).
Answer: You want to alter the original menu item that was defined in user.module's hook_menu(). You can do this in hook_menu_alter().
The item's array key is simply the path, so:
function hook_menu_alter(&$items) {
  $items['user/%/edit'] = array(
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'my_custom_page_callback',
    'page arguments' => array(1),
    'access callback' => TRUE,
  ),
}

Comment: This is pretty good, but I think the issue doesn't lie in the page destination, but the active trail being set differently as to how OP wants it.  Great example though!
Comment: Then he simply needs to set the 'type' in the code above to whatever he wants, such as MENU_CALLBACK. That's how the local tasks (tabs) are managed.
Comment: OR he should just unset the menu item altogether. But the answer to changing the default behavior completely lies in hook_menu_alter().
Comment: I've started playing with hook_menu_alter meanwhile, merely setting MENU_CALLBACK doesn't seem to do the trick but I am working on it. I'll come back to you if I manage something.
Comment: Try setting the 'title' attribute to change the breadcrumb / active trail.
Comment: Even if I change edit to "My Account", that particular menu item only shows up when the user clicks the original "My Account" link (which will lead him to this tab hell). So renaming it won't help. I need to somehow bypass the whole tabbing system and lead to the /edit page with the original link being active. Also did a (k)print_r on the $items of menu_alter. The link titled "My Account" (the one I set) has a key of user/%user instead of user/%user/edit (which is the one titled "Edit).
Comment: I can also see that those 2 Arrays ha ve a different structure, like the one contains an item called title_callback wheareas the other one page_callback and more in the similar manner.
Answer: Those that will stumble upon this looking for a way to do this without coding and using existing modules try using:

The Tab Tamer module to remove the account 'edit' tab. It is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also rename tab labels.
The Menu Token module to move the account edit menu item to any other menu. This module provides tokens, that could be used in title or in path of menu items (links). For example, if you create menu item with path: "user/[current-user:uid]/edit", the url will be changed "on fly" to: "user/1/edit" (assuming you are user 1).
Comment: Interesting. I recommended this method only in theory. I just tried it out and it appears that the tab tamer module is extremely buggy at this time. So I guess until that module pulls up it's socks, you will have to remove the edit tab using http://drupal.org/node/68792 and then just use the [current-user:edit-url] token for the menu, which seems to work just fine.
Comment: Tab Tamer does not allow me any action on user/%/edit tab.
Comment: Ok I see it's a bug that I was able to bypass but still this does not solve the issue. The menu item I've created using Menu Token leads me to user/% with the /edit tab preselected. What I need is to *kill* all this tab-behaviour and have a link that will link to user/%/edit. Just that. No tabs.
Comment: Unfortunately, I have a similar function that does just that, but only removes the tabs "visually" so to speak. The menu structure remains so if I click the menu link that uses the token to lead to user/%/edit, an extra item appears on the menu, labeled "Edit". Same happens if I navigate manually to the URL of one of the other tabs that I've unset, their respective tab titles appear as extra menu items.
Comment: @user842, Tab Tammer module works for me. But, it removes secondary tabs from administration menu also.
Answer: If I understand correctly, you might be able to utilise menu_tree_set_path() in a custom module.
EDIT:
It look like the Menu Trail By Path module might do what you want to long as the path is correct!  It utilises menu_tree_set_path() and takes all the legwork out for you!
Comment: If this is right then let me know and I'll expand the answer with an example.
Comment: that's not a hook, right? how can I use it? within another hook?
Comment: ooh...what point version of D7 are you using.  I think prior do Drupal 7.9, this function did pretty much bugger all -_-
Answer: Ok guys figured it out. The 'bug' part was cause I was using Menu Position for various reasons including this portion of the sub-menu and it had a settings tab that I didn't notice before.
Switching from  "Insert the current page's title into the menu tree" - which caused the "Edit" to get inserted - to "Mark the rule's parent menu item as being "active"" fixed it all for me.
Other than that I just had to use menu token as usual to create the actual url to the edit page. But all the fuss was because of that one wrong setting, thanks for your time.


Static Method to Graph

Question: I have created two static methods.
The first one is finding f(x) from a users input for x. This one is done and works.
The second one is giving me problems. It is supposed to graph and connect the points from two arrays, x[] and y[]. It keeps giving me the same graph no matter what I plug in. I am new to the idea of creating methods and don't fully understand graphing in java.
Could someone tell me what I'm doing wrong?
Thanks!
import java.util.*;

public class dummy {

  public static void main (String args[]) {
    Scanner keyboard = new Scanner(System.in);
    //ask user for input and store in xi
    System.out.println("Please enter a value for x.");
    double xi = keyboard.nextDouble();
    double f = f(xi); //call f(x) method
    System.out.println("The equation is:" + f);

    //creating arrays x[] and y[], then filling them with values
    int n = 500;
    double x[] = new double[n+1];
    double y[] = new double[n+1];
    for (int i = 1; i <= n; i++) {
      x[i] = i/n ;
      y[i] = Math.exp(x[i]) * Math.sin(x[i]) - (5*(Math.pow(x[i],3))+2);}
    //calling the draw graph method
    drawGraph(x,y);

  }

  //first method to find f(x) from user input X
  public static double f(double xi){
    double a = xi;

    double b = Math.exp(a) * Math.sin(a) - (5*(Math.pow(a,3))+2);

    return b;}

  //second method to draw the graph
  public static void drawGraph(double x[],double y[]){
    StdDraw.setXscale(-10, 10);
    StdDraw.setYscale(-10, 10);
    StdDraw.setPenRadius(.01);
    StdDraw.setPenColor(StdDraw.BLUE);
    for (int i=1; i<=500; i++){
      StdDraw.line(x[i-1], y[i-1], x[i], y[i]);
      StdDraw.point(x[i],y[i]);}

  }
}

Comment: You have to call a method to make it run. E.g. make two arrays `x` and `y` in `main` and then put `drawGraph(x,y);` in `main`.
Comment: @khelwood Thank you! Now I'm having a problem where it will only draw half the graph and then give me an error. Any suggestions? I posted an answer with the new code.
Answer: Yo are not calling the method in main you have to call it, try creating arrays for x and y and then calling the method somenthing like
double[] x;
double[] y;
//with some data obviously
// and the you call the method

 drawGraph(x,y);

Comment: Thank you! I posted an answer explaining another problem with the same code I am having. Thank you again!

Static Method to Graph


PInvoke in Metro Apps with Windows 8 / WinRT

Question: I have an simple FM Radio Tuner App in Silverlight 5 Out-of-browser that calls code from a Native C++ DLL from my USB FM Receiver using PInvoke. This application works very fine in Windows 8 with Silverlight5.
Now I'm trying to port it to a Metro App using WinRT.
The migration from Silverlight to XAML UI is pretty easy and worked well. The PInvoke signatures and attributes was detected fine with the namespace System.Runtime.InteropServices and the DLLImport attribute.
The problem is that when I'm running the App and call any method from the PInvoked native DLL that used to work in my SL5 app(that works fine even on Windows8), I have this exception:
<code>System.DllNotFoundException was unhandled by user code
  Message=Unable to load DLL 'CarTFTFM.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
  Source=metroradio
  TypeName=""
  StackTrace:
       at MetroRadio.FMRadio.HWInit2(Int32 port, Int32 initVolume)
       at MetroRadio.MediaService.InitializeRadio() in c:\Users\Gutemberg\Documents\Visual Studio 11\Projects\MetroRadio\MetroRadio\MediaService.cs:line 160
       at MetroRadio.MainPage.radio_Click(Object sender, RoutedEventArgs e) in c:\Users\Gutemberg\Documents\Visual Studio 11\Projects\MetroRadio\MetroRadio\MainPage.xaml.cs:line 43
  InnerException:
</code>
So, my question is, what is the problem on this PInvoke? Since it Works well on Windows8 with a SL5 app, I dont see any reasons to have problems with WinRT/Metro Apps.
Comment: Metro apps are not allowed to call just any Win32 function. Perhaps the DLL uses an invalid call when loading (DllMain) which causes the loading to fail. Remember it is not even Beta just yet...
Comment: Sounds like the DLL is missing from the package manifest.  Current docs are too obscure to give a good link.
Comment: Take a look at this question: http://stackoverflow.com/questions/7807361/how-to-p-invoke-to-a-native-dll-from-metro
Comment: Sound similar but still no success...
Comment: @GutembergRibeiro I assume you have found your way around this issue by now, but if not, please have a look at my answer below.
Answer: As per Pavel Minaev's reply to Chris Pietschmann's answer:

P/Invoke and COM Interop are most certainly supported for .NET Metro apps. Win32 API is also supported, and can be called through the above technologies, though it is limited to those functions that are available to Metro apps (i.e. if a C++ Metro app can't call it, neither can a .NET app).

As Morten Frederiksen points out, it is however likely that CarTFTFM.dll contains an unsupported part of the Win32 API surface for WinRT:

Only a subset of Win32 and COM API is supported: msdn.microsoft.com/en-us/library/windows/apps/br205757
Answer: Unless it is a system DLL or otherwise locatable through the system path, you need to make sure that your DLL is copied to the same folder as  your Metro application is deployed in.
I solved the problem by adding the native DLL to my Metro application project, ensuring that Build Action is set to Content and that Copy to Output Directory is set to Copy Always or Copy if Newer.


trouble with vsnprintf on 64bit windows

Question: I'm using (under windows7, VS2010) a time_t type.
So...
If I dump my variable with a simple printf("%d", myvar)
Everything is working fine.
But now, If I use a vsnprintf() (or any code using va_start/va_end and co...)
with time_t as argument, I get wrong values !?
myprintf(">>%d %d", var1_time, var2_time);

(var1_time and var2_time are both wrong !)
my guess: va_xx functions don't know how to handle 64bit !?
Of course I can use "%lld" but... How can I do act like printf ?
Comment: AFAIK "%d" is for int sized objects, on 64 bit system `sizeof(time_t) > sizeof(int)` so you need the `lld` specifier for it. What are you trying to accomplish that need to make vsnprintf behave like printf?
Answer: It's just luck that it worked with printf.
time_t is 64 bit (unless you enable the 32 bit version). So using "%d" is wrong. I'm guessing it appears to work as the stack in that case happens to contains zeroes where printf expects to find the upper 4 bytes of your time_t.
Print it as a 64 bit type in both cases.
If you really must treat it as a 32 bit value, you have to cast it, printf("%d", (int)myvar); . But don't do that, dealing with time is cumbersome enough that you don't need to deliberately try to mess it up.

trouble with vsnprintf on 64bit windows


$N_k$ is the number of pairs $(a,b)$ of non-negative integers such that $ka+(k+1)b=n+1-k$. Find $N_1+N_2+\cdots N_{n+1}$.

Question: Let $n$ be a positive integer. Assume that:
$N_k$ is the number of pairs $(a,b)$  of non-negative integers such that $ka+(k+1)b=n+1-k$.
Find $N_1+N_2+\cdots N_{n+1}$.
I was trying to solve this calculating coefficients of polynomial equations but in vain like:
We know that $N_k$ is the coefficient of $X^{n-k+1}$ in:
$$G_k(X)=(1+X^k+X^{2k}+\cdots)(1+X^{k+1}+X^{2k+2}+\cdots)$$
Now can you help me from here or by any other elegant way. Please help.
Comment: Is the answer $n$?
Comment: Here's a hint: by rearranging, we are trying count the number of solutions $(k,a,b)$ to $k(a+b+1)+b=n+1$ where $k,a,b$ are integers, $k\geq 1$ and $a,b\geq 0$. By making the change of variables $q=a+b+1$ and $r=b$, we are now trying to count the number of integer solutions $(k,q,r)$ to $kq+r=n+1$ where $k\geq 1$ and $0\leq r\leq q-1$. Look familiar?
Comment: @sku the amswer is $n+1$. You are close enough. Please give me the answer in detail.
Comment: @Munchhausen Please give me the answer in detail, if possible. Thanks.
Comment: I took some examples. I got N(5) = 6; N(7) = 8. And so saw a pattern. Couple of things we can conclude. For $n$ even, $N_1 = n/2 + 1$, for $n$ odd, $N_1 = \frac{n+1}{2}$; Also $N_{n+1} = 1$ always. Also, for $ \frac{n+1}{2} < k < n+1, N_k = 0$
Answer: Set $N=N_1+\dots+N_{n+1}$ and notice that $N$ is precisely the number of integer solutions $(k,a,b)$ to $ka+(k+1)b=n+1-k$ where $k\geq 1$ and $a,b\geq 0$. Setting $q=a+b+1$ and $r=b$ and rearranging the expression, $N$ is the number of integer solutions $(k,q,r)$ to $n+1=qk+r$ where $k\geq 1$ and $0\leq r\leq q-1$. But this expression is exactly what you get when dividing $n+1$ by $q$. More specifically, $k$ is the quotient, and $r$ is the remainder. Thus, we know that for every fixed $1\leq q\leq n+1$, there is precisely one integer solutions $(k,q,r)$ to $n+1=qk+r$ where $k\geq 1$ and $0\leq r\leq q-1$, so $N=n+1$.


Qt5 -porting a simple Qt Quick application to Qt5. help needed

Question: I am trying to port a simple Qt Quick application from Qt4.8 to Qt5.0beta.
my initial (Qt4.8) code is similar to what is below:
main.cpp will dipsplay a QDeclarativeView in a frameless window with translucent background
#include <QtGui/QApplication>
#include "qmlapplicationviewer.h"
#include <QtDeclarative>
#include <QDeclarativeContext>

Q_DECL_EXPORT int main(int argc, char *argv[])
{
    QScopedPointer<QApplication> app(createApplication(argc, argv));

    QmlApplicationViewer viewer;
    viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
    viewer.setMainQmlFile(QLatin1String("qml/main.qml"));

    viewer.setWindowFlags(Qt::FramelessWindowHint);

    viewer.setAttribute(Qt::WA_TranslucentBackground);
    viewer.setStyleSheet("background:transparent;");
    viewer.setResizeMode(QDeclarativeView::SizeViewToRootObject);
    viewer.showExpanded();

    return app->exec();
}

and the main.qml will just display a red rectangle inside another transparent rectangle.
import QtQuick 1.1

Rectangle {
    width: 360
    height: 360
    color: "transparent"
    Rectangle
    {
     x: 125
     y: 122
        width: 110
        height: 116
        anchors.centerIn: parent
        color: "red"
  radius: 27
    }

    Text {
     color: "black"
        text: qsTr("Press me!")
        font.pointSize: 14
        anchors.centerIn: parent
    }

    MouseArea {
        anchors.fill: parent
        onClicked: {
            Qt.quit();
        }
    }
}

In order to make it compatible with Qt5 few changes were necessary.
(I have followed http://qt-project.org/doc/qt-5.0/portingqmlapp.html [qt-project.org]
in order not to miss something)
Now main.cpp is similar to:
#include <QtGui/QGuiApplication>
#include "qtquick2applicationviewer.h"
#include <QtWidgets/QtWidgets>
#include <QtWidgets/QLabel>

int main(int argc, char *argv[])
{

    QGuiApplication app(argc, argv);
    QtQuick2ApplicationViewer viewer;
    viewer.setMainQmlFile(QStringLiteral("qml/main.qml"));
    viewer.setWindowFlags(Qt::FramelessWindowHint);
    viewer.showExpanded();

    return app.exec();
}

In main.qml only one line was replaced.
import QtQuick 2.0

but I am not able to find a way of keeping the transparency
setAttribute(Qt::WA_TranslucentBackground);
setStyleSheet("background:transparent;");

setAttribute and setStyleSheet were available for a QDeclarativeView (which is a QWidget)
but not for QQuickView (which is a QWindow)
Comment: Check out this thread where the transparency issue is discussed ...
http://qt-project.org/forums/viewthread/18984
Answer: Try my QuickWidget, if it helps you:
http://code.google.com/p/quickwidget/
Or, even better, use QQuickWidget from Qt 5.3+.


What's the minimum number of vertices in a simple graph with $e$ edges

Question: Describe the minimum number of vertices in a simple graph (no loops or multiple edges) with $e$ edges.
I can't derive a formula for this, I don't even know if this is possible.
Anyway, it's not hard to see that the complete graph is the one that optimizes the use of vertices, for example the minimum for $e=3$ is the number of vertices en $K_3$, the minimum for $e=6$ is the number of vertices in $K_4$, the minimum for $e=10$ is the number of vertices in $K_5$ and so on...so I would know this:
If $2 \leq e \leq 3$ the minimum is $3$
If $4 \leq e \leq 6$ the minimum is $4$
If $7 \leq e \leq 10$ the minimum is $5$ and so on...
But I can't see how to derive a formula...is that possible? If so, how?
Comment: It seems relevant that each edge connects two vertices, and that $\binom{3}{2} = 3$, $\binom{4}{2} = 6$, $\binom{5}{2} = 10$.
Answer: The maximum number of edges in an $n$-vertex simple graph is $\binom n2=\frac{n(n-1)}2=T_{n-1}$ where $T_n$ denotes the $n$th triangular number. It is possible to find $n$ given $T_n$ using what is known as a triangular root:
$$n=\frac{\sqrt{8T_n+1}-1}2$$
Hence the smallest number of vertices that will support a graph with $e$ edges is
$$\left\lceil\frac{\sqrt{8e+1}-1}2+1\right\rceil$$
which can be simplified to
$$\left\lceil\sqrt{2e}+\frac12\right\rceil$$
$\lceil x\rceil$ denotes the ceiling function, the smallest integer greater than or equal to $x$.


Can a confidence interval have boundaries that are different in size in relation to the mean?

Question: I saw a poll for local elections where 9.3% of the respondents said that they would vote for John Doe. The poll put the lower bound at 8.3% and the upper bound at 11.3%. From, what I have learned from introductory stats classes should not the distance of the mean to the lower bound and the distance of the upper bound be the same given that the formula is xbar plus or minus z(s/sqrt(n)). Does this poll have an error or am I missing something?
Comment: Consider the distribution of proportions. Apart from when the population value is 0.5 it will not be symmetric so the confidence interval will not be either.
Comment: How many respondents were there?
Answer: Suppose that the poll used $n = 2400$ subjects of whom $X =223$
favored candidate Doe.
Then a traditional Wald confidence interval would start with a
point estimate $\hat p = 223/2400 = 0.093$ of the proportion in favor and the a 95% CI would be
$$\hat p \pm 1.96\sqrt{\frac{\hat p(1-\hat p)}{n}},$$
which computes to $(0.081,0.104)$ or $(8.1\%, 10.4\%).$
Notice that $\pm 1.96$ cuts 2.5% from each tail of a
standard normal distribution. This CI is sometimes called probability symmetric because
the same probability is cut from each tail of the distribution.
It is by far the most common type of CI.
x = 223;  n = 2400
p.hat = x/n;  q = qnorm(c(.025,.975))
p.hat; q
[1] 0.09291667
[1] -1.959964  1.959964
CI = p.hat + q*sqrt((p.hat *(1-p.hat))/n);  CI
[1] 0.08130184 0.10453150

However, one says a 95% CI because many kinds of CIs are possible For example, one can cut 4%
from one tail and 1% from the other and still have a 95% CI.
Then another 95% CI is $(0.083, 0.107)$ or $(8.3\%,10.7\%).$
For this type of CI, the point estimate is no longer at the center of the CI.
Especially for small percentages, such alternate types of CIs
may be used. (If for no other reason. this might be done to summarize a campaign poll in a way to encourage a candidate
who is not showing well in the polls.)
x = 223;  n = 2400
p.hat = x/n;  q = qnorm(c(.04,.99))
p.hat; q
[1] 0.09291667
[1] -1.750686  2.326348
CI = p.hat + q*sqrt((p.hat *(1-p.hat))/n);  CI
[1] 0.08254203 0.10670270

So either the newspaper reporting the poll had a typographical error or the pollster is not using a probability-symmetric style
of CI. (I'm betting on the typo.)


Graph with $50$ vertices and $392$ edges with no $4$ independent vertices?

Question: I need an example of a graph with $50$ vertices and $392$ edges, with no independent set of size $4$. The graph should be loopless, and I think multiple edges are allowed. I don't know where to begin.
Comment: Multiple edged graphs can't be loopless.
Comment: @ajotatxe I thought a loop was when a vertex is connected to itself?  It seems you can have multiple edges with no loops.
Comment: Sorry, you are right.
Answer: Two copies of $K_{17}$, and a $K_{16}$.
$17+17+16=50$ vertices and $136+136+120 = 392$ edges.
By the pigeonhole principle, of any $4$ vertices selected, two will be in the same $K$ graph and thus connected.
Answer: What would the complement of such a graph satisfy?
It would be a graph with $\binom{50}{2}-392=833$ and no $K_4$. By Turan's theorem the graph with the most edges and no $K_4$ is the complete 3-partite graph $K_{17,17,16}$, and it is unique up to isomorphism. This graph has exactly $17\cdot17+17\cdot16+17\cdot16=833$ edges.
So the only graph that works is the complement of $K_{17,17,16}$ which consists of two copies of $K_{17}$ and one $K_{16}$.
This method can be used to solve the problem in its generality. In other words if you want a graph on $n$ vertices and $e$ edges without independent sets of size $k$ take $k-1$ complete graphs such that the differences between their sizes is at most $1$ and such that the sum of their vertices is $n$, if this graph has more than $e$ edges then the graph you are looking for is unnatainable. Otherwise you can add edges untill you have $e$ edges and that graph will satisfy what you want. This can all be justified using Turan as I did for your example.
Comment: Oh, I have not made it to that theorem yet. So this would also prove that every graph with 50 vertices and *less than* 392 edges has 4 independent vertices.  Nice.
Comment: Yes it would. Happy to help !


Fade out Div / Section in vue.js when reaching target section

Question: With jQuery this was always simple enough to do but am wondering how to accomplish with Vue.js. I have a sticky element on page and when that reaches a certain div id or class on scroll I want to fade it out and when scrolls back above it fade back in. I have a click event scroll currently functioning as expected on the element but am stuck on the scroll position fade in / out. div class="collapsed" is a fixed bottom element on page. When that scrolls to "fade-in-out" I would like "collapsed" to fade out and when scrolls back up past "fade-in-out" fade back in.
HTML:
<transition name="fade">

          lorem ipsum

Nullam sollicitudin a sapien sed

            Etiam ultricies elit vel sapien convallis, nec volutpat lacus imperdiet.

</transition>

OTHER DIV:

js:
export default {
name: 'app',
data() {
return {
  show: true
};
},
methods: {
fadeOut: function() {
  this.show = false;
}
}
};

css:
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease-in-out;
}

.fade-enter,
.fade-leave-active {
  opacity: 0;
}

Answer: The main concept is no difference. If you can do in jQuery so you can do the same in Vue.js.

  <transition name='bottom'>

      {{ lorem }}

  </transition>

{{ lorem }}

new Vue({
  data: () => ({
    show: true,
    lorem: `Lorem Ipsum...`
  }),

  mounted() {
    this.listener = () => {
      let rect = this.$refs.target.getBoundingClientRect()
      let top = window.innerHeight - rect.top
      this.show = top < 0
    }
    window.addEventListener('scroll', this.listener)

    /* with Intersection Observer API

    this.observer = new IntersectionObserver(() => {
      let rect = this.$refs.target.getBoundingClientRect()
      let top = window.innerHeight - rect.top
      this.show = top < 0
    })
    this.observer.observe(this.$refs.target)

    */
  },

  destroyed() {
    window.removeEventListener('scroll', this.listener)
    /* this.observer.unobserve(this.$refs.target) */
  }
}).$mount('#app')

.bottom {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: hidden;
  padding: 24px;
  color: white;
  background-color: dodgerblue;
  white-space: nowrap;
  text-overflow: ellipsis;

  &-enter-active,
  &-leave-active {
    transition: opacity 0.5s ease-in-out;
  }

  &-enter,
  &-leave-to {
    opacity: 0;
  }
}

.target {
  padding: 24px;
  color: white;
  background-color: crimson;
}

JSFiddle
Comment: this works in a single file but my issue is these are two different vue components. Thanks for the info though, gives me some thought and direction
Comment: This does not work for me. Can you please check my question: https://stackoverflow.com/questions/64776168/hide-navbar-component-when-it-reaches-footer-component-in-vuejs


How to rsync symlinks and their referents but preserving the links

Question: I have the following filestructure in my src directory:
en/
en/a/
en/a/file1 -> ../../en/mp3/file1-longer-name-a
en/a/file2 -> ../../en/mp3/file2-longer-name-a
en/mp3/file1-longer-name-a
en/mp3/file1-longer-name-b
en/mp3/file2-longer-name-a
en/mp3/file3-longer-name-a

I am interested to copy all the files under en/a/ to the destination, preserving symlinks, and also include the referent files (which BTW are all within en/) but not other files under en/mp3/ if they are not referred by any symlinks I am transferring.
I'm using the following command, that does the obvious part of the job:
rsync -avRz "${SRC}./en/a" "${DST}"

this transfers the following files:
en/
en/a/
en/a/file1 -> ../../en/mp3/file1-longer-name-a
en/a/file2 -> ../../en/mp3/file2-longer-name-a

and I hope you'll help me to tweak the rsync args so that the following files will be transferred too:
en/mp3/file1-longer-name-a
en/mp3/file2-longer-name-a

is there a way to achieve this without needing to write an algorythm to loop over the softlinks under en/a/ and transfer the files they point to one-by-one?
Comment: This doesn't exactly answer your question, but you might have a look at rsync's `--copy-links` or `-L` flag. Instead of copying the symlinks it resolves them and copies the files. But that's not a good idea if you've got many links to one file.
Comment: I already tried that, but I need the symlinks to stay symlinks in the en/a/ directory
Answer: You could use find in combination with rsync's --files-from parameter:
find "${SRC}./en/a" -type l -exec readlink {} ';'|sort|uniq|rsync -avRz --files-from=- "${SRC}" "${DST}"

find lists all symlinks in the en/ folder and executes readlink on each of them.
then we sort the list and filter out duplicates (with sort and uniq)
and rsync gets the --files-from param set to - to read the files it should sync from stdin
Comment: OK, it worked, the only thing I had to change was: `rsync -avRz --files-from=- "${SRC}" "${DST}"` (i.e: removed "./en/a", because the files that find gave me already had that)
Comment: Fixed the answer.


get an element by id xml document

Question: Can someone help me get the an elemnt by id?
For example if I have some thing like:
<abc>
    <x>tghgh</x>
    <y>fgghj</y>
    <z>dghj</z>
</abc>

If I say getelement(3) it should return me element.name as Z and element.value as dghj.
Is there already a function which I am missing or is there a way I can code this?
Comment: `3` is not the id of anything here. At best it's an index, but your sample is open for multiple interpretations. Should the index be flattened or are we counting inside `` ?
Comment: Why won't you check out [LINQ to XML](http://msdn.microsoft.com/en-us/library/bb387098.aspx)?
Comment: sorry.. dint see your replies :(.. yeah i need the index.. counting inside abc...
Answer:  using System.Xml.Linq;

 var doc = XDocument.Parse(xmlText);
 var target = doc.Element("abc").Elements().ElementAt(2);

Note the counting starts at 0, so it's ElementAt(2).
Finding the element with tag z is easier and faster:
 var target = doc.Element("abc").Element("z");

In both cases you have target.Name and target.Value

get an element by id xml document


Google Cloud Storage upload a file using java

Question: I'm creating a web app using Java servlets and JSPs and I want to create an upload form in JSP for my clients to be able to upload and download stuff. I'm using Cloud Storage and my default bucket to upload stuff.
I followed Google's tutorial on Reading and Writing to Google Cloud Storage.
This is my Servlet:
public class Create extends HttpServlet {

    public static final boolean SERVE_USING_BLOBSTORE_API = false;

    private final GcsService gcsService = GcsServiceFactory.createGcsService(new RetryParams.Builder()
            .initialRetryDelayMillis(10)
            .retryMaxAttempts(10)
            .totalRetryPeriodMillis(15000)
            .build());

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        GcsFilename fileName = getFileName(req);
        if (SERVE_USING_BLOBSTORE_API) {
            BlobstoreService blobstoreService =  BlobstoreServiceFactory.getBlobstoreService();
            BlobKey blobKey = blobstoreService.createGsBlobKey(
                    "/gs/" + fileName.getBucketName() + "/" + fileName.getObjectName());
            blobstoreService.serve(blobKey, resp);
        } else {
            GcsInputChannel readChannel = gcsService.openPrefetchingReadChannel(fileName, 0, BUFFER_SIZE);
            copy(Channels.newInputStream(readChannel), resp.getOutputStream());
        }
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        GcsFileOptions instance = GcsFileOptions.getDefaultInstance();
        GcsFilename fileName = getFileName(req);
        GcsOutputChannel outputChannel;
        outputChannel = gcsService.createOrReplace(fileName, instance);
        copy(req.getInputStream(), Channels.newOutputStream(outputChannel));
    }

    private GcsFilename getFileName(HttpServletRequest req) {
        String[] splits = req.getRequestURI().split("/", 4);
        if (!splits[0].equals("") || !splits[1].equals("gcs")) {
            throw new IllegalArgumentException("The URL is not formed as expected. " +
                    "Expecting /gcs/<bucket>/<object>");
        }
        return new GcsFilename(splits[2], splits[3]);
    }

    private void copy(InputStream input, OutputStream output) throws IOException {
        try {
            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead = input.read(buffer);
            while (bytesRead != -1) {
                output.write(buffer, 0, bytesRead);
                bytesRead = input.read(buffer);
            }
        } finally {
            input.close();
            output.close();
        }
    }
}

I can upload and download successfully, but only text and not real files like images, pdfs, etc., which is my problem.
This tutorial is for reading and writing text but i want to upload real files. As you can see from my jsp the enctype is "text/plain":
<form action="/index.html" enctype="text/plain" method="get" name="putFile" id="putFile">

        Bucket: <input type="text" name="bucket" />
        File Name: <input type="text" name="fileName" />

 File Contents:

        <textarea name="content" id="content" rows="3" cols="60"></textarea>

        <input type="submit" onclick='uploadFile(this)' value="Upload Content" />

    </form>

I tried to change it to "multipart/form-data" and put a
<input name="content" id="content" type="file">

but this does not upload the real file only the fake path of the file.
And I want to know how to upload real files, any help would be appreciated.
Answer: Here is one example on how to upload blobs to Cloud Storage:
First you initialize the storage with these lines:
private static Storage storage = null;

  // [START init]
  static {
    storage = StorageOptions.getDefaultInstance().getService();
  }
  // [END init]

You may change the code to accept different file extensions according to your needs on the getImageUrl method in the line String[] allowedExt = {"jpg", "jpeg", "png", "gif"};
/**
 * Extracts the file payload from an HttpServletRequest, checks that the file extension
 * is supported and uploads the file to Google Cloud Storage.
 */
public String getImageUrl(HttpServletRequest req, HttpServletResponse resp,
                          final String bucket) throws IOException, ServletException {
  Part filePart = req.getPart("file");
  final String fileName = filePart.getSubmittedFileName();
  String imageUrl = req.getParameter("imageUrl");
  // Check extension of file
  if (fileName != null && !fileName.isEmpty() && fileName.contains(".")) {
    final String extension = fileName.substring(fileName.lastIndexOf('.') + 1);
    String[] allowedExt = {"jpg", "jpeg", "png", "gif"};
    for (String s : allowedExt) {
      if (extension.equals(s)) {
        return this.uploadFile(filePart, bucket);
      }
    }
    throw new ServletException("file must be an image");
  }
  return imageUrl;
}

Here a timestamp is appended in the filename which can be a good idea if you want to make the filename unique.
/**
 * Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME
 * environment variable, appending a timestamp to end of the uploaded filename.
 */
@SuppressWarnings("deprecation")
public String uploadFile(Part filePart, final String bucketName) throws IOException {
  DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
  DateTime dt = DateTime.now(DateTimeZone.UTC);
  String dtString = dt.toString(dtf);
  final String fileName = filePart.getSubmittedFileName() + dtString;

  // the inputstream is closed by default, so we don't need to close it here
  BlobInfo blobInfo =
      storage.create(
          BlobInfo
              .newBuilder(bucketName, fileName)
              // Modify access list to allow all users with link to read file
              .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))
              .build(),
          filePart.getInputStream());
  // return the public download link
  return blobInfo.getMediaLink();
}

In this documentation you'll find more details: https://cloud.google.com/java/getting-started/using-cloud-storage#uploading_blobs_to_cloud_storage
The complete code for this example is in github: https://github.com/GoogleCloudPlatform/getting-started-java/blob/master/bookshelf/3-binary-data/src/main/java/com/example/getstarted/util/CloudStorageHelper.java
Comment: Thank you, you helped me figure out some stuff, but this is for images only and it's a whole different approach.
Answer: I found a solution.
This is my JSP:
<form action="/create" enctype="multipart/form-data" method="post" name="putFile" id="putFile">

        File Name: <input type="text" name="fileName" />

 File Contents:

        <input type="submit" value="Upload Content" />

</form>

When i submit the form, it goes into this Servlet:
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Part filePart = req.getPart("content"); /*Get file from jsp*/

    /*Get file name of file from jsp*/
    String name = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
    GcsFileOptions instance = GcsFileOptions.getDefaultInstance();
    GcsFilename fileName = new GcsFilename(BUCKET_NAME, name);
    GcsOutputChannel outputChannel;
    outputChannel = gcsService.createOrReplace(fileName, instance);

    /*Pass the file to copy function, wich uploads the file to cloud*/
    copy(filePart.getInputStream(), Channels.newOutputStream(outputChannel));
    req.getRequestDispatcher("download.jsp").forward(req, resp);
}

private GcsFilename getFileName(HttpServletRequest req) {
    String[] splits = req.getRequestURI().split("/", 4);
    if (!splits[0].equals("") || !splits[1].equals("gcs")) {
        throw new IllegalArgumentException("The URL is not formed as expected. " +
            "Expecting /gcs/<bucket>/<object>");
    }
    return new GcsFilename(splits[2], splits[3]);
}

private void copy(InputStream input, OutputStream output) throws IOException {
    try {
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = input.read(buffer);
        while (bytesRead != -1) {
            output.write(buffer, 0, bytesRead);
            bytesRead = input.read(buffer);
        }
    } finally {
        input.close();
        output.close();
    }
}


Is it possible that a stacked LSTM for text generation is performing worse than a one layer LSTM?

Question: Does anyone know if the generated text from a stacked LSTM is performing worse than a one layer LSTM? Is a possible answer that the Model is overfitting?
In my case after the first few epochs the text generated from a one layer LSTM makes much more sense than the text from stacked one (The los is also lower).
I used the code from the following link: https://github.com/rstudio/keras/blob/master/vignettes/examples/lstm_text_generation.R
And after some research I found that one could improve the model in adding layers to the LSTM model. I changed the model architecture to:
<code>model %>%
layer_lstm(512, return_sequences = TRUE, input_shape = c(maxlen,
length(chars))) %>%
layer_dropout(0.2) %>%
layer_lstm(512, return_sequences = TRUE) %>%
layer_dropout(0.2) %>%
layer_lstm(512) %>%
layer_dense(length(chars)) %>%
layer_activation("softmax")
</code>
After checking the results from the first few epochs I realized that the text from the first model makes much more sense. How could this be explained?
Stacked LSTM:
<code> Epoch 2 loss 3.2485
 diversity: 0.500000 ---------------

 hof  ofnfif ffsoffffffssffofff feffollfl fhoffffflhffoefohfffhhof ofaffn
 fefflffefssfnnsnf hlnowfnfnlgfsflfhffonnfhff
 nfinffffhnhfffhffhfoffhfffannsh ff effffehhffghffrffinf fnffffefffffhfff
 fnhd  fiflsfhfff hofhfhffefhfhf sffofhfefohhffffffff  fffffoho  ffffnh  iff
 lf lfnfffffenffcffffffffwfffffsefff
 fffffhffflfnsffnffffofnhfnfhhofflohoffnffnffhhcfhft ffflnnffnf
 fffaynhfhfhfffshlhmoffhhfhnhfhff f
</code>
LSTM from the example:
<code> Epoch 2 loss 1.6497
 diversity: 0.500000 ---------------

 g leaght in them the man and the spirits of the senser the ling of an
 almosing the somethy what is discrient of the most superfice the notion of
 the most former some and to and he
 will and a press to the sense, the spuring of his some proprease of the
 more and be supoiled and evil and and what the supperance of the man
 contination of such and of all the the takent of the simperfulned the
 procratio
</code>
Comment: (1) It's generally true that it's harder to train a model with more parameters. Are you sure that the multi-layer model has converged? (2) Overfitting occurs when the training loss is dramatically lower than the out-of-sample loss. You haven't posted any information about your models, so we can't say whether this has occurred.
Comment: I might have a clue. Can you put the accuracies you get from the two models?
Comment: I have edited my question.
Comment: I'm afraid that your edit doesn't really address the concerns that I raised in my comment.
Answer: You've posted loss values from the second epoch of each network. I wouldn't read too much into the difference, since the loss of the 2-layer network at the second epoch is clearly not converged (it's 3.2, which is enormous for this flavor of language models). With loss that high, it's absolutely typical that the text it generates is nonsense.
I recommend training the 2-layer network until its loss equals or beats the loss of the 1-layer network. It's generally true that it's harder to train a model with more parameters, so this may require some effort to achieve: tweaking the optimizer and learning rate, batch size, sequence lengths and so on.
The primary benefit to a 2-layer LSTM network in this context is that it has more capacity to learn the language; in other words, the minimum loss that it obtains may be substantially lower than the minimum loss of the 1-layer network. On the other hand, this increase in complexity comes at the cost of increased computation time, and a harder optimization problem.


Java : Interface with 2 method with the same erasure but 2 different wildcard

Question: I have some codes with lot of converter having 2 "apply" method to convert :

from DTO to Entity
from Entity to DTO

I need to use them on a new generic service so I want to create an interface to inherit so I write this code :
<code>public interface Converter<T,V> {
    public T apply(V input);
    public V apply(T input);
}
</code>
but now I got an error saying :

apply(T) and apply(V) have the same erasure

the question :
is there a way to do what i want without having to rewrite all the child classes ?
Answer: No.
You have to give them different names.


Erro: não é possível localizar nem carregar a classe principal

Question: Estou em busca da solução do seguinte problema, faço um "OláMundo" no Netbeans e ele está compilando, faço ou outro no Bloco de Notas e no Notepad++, consigo criar a class com o javac Oi.java, mas quando coloco java Oi, aparece o seguinte erro:

"Erro: não é possível localizar nem carregar a classe principal Oi"

OBS: Todos os fóruns que busco fala sobre a configuração da JAVA_HOME, da PATH e da CLASSPATH, todas já foram acertadas, quando coloco para mostrar no Prompt a versão ela aparece normalmente...
Como posso solucionar isso, como consigo rodar no Prompt?
Segue prints abaixo da pasta, do bloco de notas, do prompt e do teste rodando normalmente no Netbeans:
Comment: Edite a pergunta e poste sua classe
Comment: Quem negativou nao entende nada de java ou nao entendeu a pergunta, porque o problema aqui nao tem a ver com codigo e a imagem é válida pra entender o problema.
Comment: Postei o código básico de teste...

Está na pasta o arquivo Oi.java e o Oi.class
Answer: Provavelmente você está tentando rodar a classe sem compilar. É preciso compilar o arquivo .java antes:
javac Oi.java

para depois executar:
java Oi

Veja, a classe está funcionando normalmente:

Obs.: Certifique-se de que a classe tenha o mesmo nome do arquivo, se a classe se chama MinhaClasse, o arquivo também deve se chamar MinhaClasse.java.

No print, seu arquivo se chama Oi.java, mas a assinatura da classe esta com nome diferente(public class Oie)

Obs2.: Se tiver informação de package na classe, o compilador vai procurar por essas pastas, e como não vai encontrar vai dar esse erro. Remova a informaçao de package a nao ser que possua hierarquia de pastas do package.

Tente também com o comando abaixo, onde a jvm vai forçar o classpath como a pasta atual e procurar a classe apenas dentro dela:
java -cp . Oi

Nesta resposta e nesta outra do SOEn tem explicações mais detalhadas sobre os motivos que podem ocasionar esse problema.
Comment: Ok, muito obrigada mesmo!!! :)


Elegant way to add one row DataFrame to another DataFrame

Question: I have two DataFrames and one of them is a single row DataFrame. I want to add the one row dataframe across all the rows of the bigger one. I can solve it, but I am looking for a simpler solution:
import pandas as pd
df1 = pd.DataFrame({'C':['car'],'D':['bus']})
print(df1)
     C    D
0  car  bus

df2 = pd.DataFrame({'A':[1,2,3],'B':[8,2,0]})
print(df2)
   A  B
0  1  8
1  2  2
2  3  0

I want to join the line line DataFrame one across the bigger one. The result should be.
   A  B    C    D
0  1  8  car  bus
1  2  2  car  bus
2  3  0  car  bus

My attempt: I created a dummy column in both DataFrames and did a left join, but that's inelegant. I am sure there will be simpler solutions.
Answer: I think the most elegant is use DataFrame.assign, but is necessary strings columns names:
df2 = df2.assign(**df1.iloc[0])
print (df2)
   A  B    C    D
0  1  8  car  bus
1  2  2  car  bus
2  3  0  car  bus

df1.columns=[1,8]
print (df1)
     1    8
0  car  bus

df2 = df2.assign(**df1.iloc[0])
print (df2)

TypeError: assign() keywords must be strings

Another solution working if match first index values:
df2 = df2.join(df1.reindex(df2.index, method='ffill'))
print (df2)
   A  B    C    D
0  1  8  car  bus
1  2  2  car  bus
2  3  0  car  bus


Get total count of assertions made in a React app using Jest

Question: I am currently using the built-in Jest testing environment that comes with the generated boilerplate by create-react-app. With Jest's integration with Istanbul, one can get the unit test coverage by total number of statements, functions, lines, and branches covered. Aside from these, is there any way to get the total number of assertions used in all the unit test files? Thanks!
Answer: I'm not aware if jest has this functionality built in, but we can probably mimic this with grep and wc.
Grep searches files for specific text.
 grep [options] PATTERN [FILE...]

 -r --recursive
 -c --count
 -i --ignore-case
 --include=PATTERN
   Recurse in directories only searching file matching PATTERN.

wc - print newline, word, and byte counts for each file
wc [OPTION]... [FILE]...

-l, --lines
print the newline counts

Print the count of "expect" pattern matches in each file:
grep -r -i -c --include \*.test.js "expect" . matches
Print the sum of total "expect" pattern matches.
grep -r -i --include \*.test.js "expect" . | wc - l
Comment: I am actually looking for an API reference from Instanbul and Jest, and this is not it. But, it gave me an idea of a workaround so I gave it an upvote. Thanks, anyway!


Show soft keyboard in Android with Delphi OpenGL app (no FMX)

Question: Hiyas.
Does anyone know how to achieve this?
I'm creating a "context" (a draw surface) with something like the following code:
Initially:
FApp:= Pandroid_app(PANativeActivity(DelphiActivity)^.instance);

FApp.userData:= Self;
FApp.onAppCmd:= OnAppCmd;

After receiving APP_CMD_INIT_WINDOW in OnAppCmd:
FDisplay := eglGetDisplay(EGL_DEFAULT_DISPLAY);
eglInitialize(FDisplay, nil, nil);
eglChooseConfig(FDisplay, @attribs[0], @config, 1, @numConfigs);
eglGetConfigAttrib(FDisplay, config, EGL_NATIVE_VISUAL_ID, @format);

ANativeWindow_setBuffersGeometry(FApp.window, 0, 0, format);

FSurface := eglCreateWindowSurface(FDisplay, config, FApp.window, nil);
FContext := eglCreateContext(FDisplay, config, nil, nil);

if  (eglMakeCurrent(FDisplay, FSurface, FSurface, FContext) = EGL_FALSE) then
    begin
    Abort;
    end;

However, I seem to need a "view" in order to make it focused such that I can then tell the Android system to enable and show the keyboard for it.  The following code does not work (because I don't have focus, I believe):
ANativeActivity_showSoftInput(PANativeActivity(DelphiActivity), 0);

Does anyone know how to get a view without any FireMonkey code?
I found a reference that seemed to suggest that FApp^.window is a SurfaceHolder (because that's what you pass to eglCreateWindowSurface in their example code) but that didn't seem to work or take me very far.
Do I need to do something like in Java and create a GLSurfaceView descendant?  But how do I do that?
Any help very much appreciated.
Daniel.
Edit:
I'm still trying to get this to work.  All of the examples I can find are in Java so I've attempted to replicate them.
After APP_CMD_GAINED_FOCUS in OnAppCmd I'm using the following code:
    CallInUIThread(procedure
    var
    wnd: JWindow;
    ctx: JContext;
    ctxcls: JContextClass;
    imm: JInputMethodManager;
    immcls: JInputMethodManagerClass;

    begin
    wnd:= TJNativeActivity.Wrap(PANativeActivity(System.DelphiActivity)^.clazz).getWindow;
    wnd.getDecorView.setFocusable(True);
    wnd.getDecorView.setFocusableInTouchMode(True);

    ctx:= wnd.getContext;
    ctxcls:= JContextClass(ctx.getClass);

    imm:= JInputMethodManager(TJNativeActivity.Wrap(PANativeActivity(System.DelphiActivity)^.clazz).getSystemService(ctxcls.INPUT_METHOD_SERVICE));
    if  Assigned(imm) then
        begin
        immcls:= JInputMethodManagerClass(imm.getClass);
        imm.showSoftInput(wnd.getDecorView, immcls.SHOW_FORCED);
        end;
    end);

It uses some of the FireMonkey framework (for executing in the "UI" thread because trying to access the window otherwise gives a system error that views can't be touched by any other thread) but I should be able to replace that by implementing a JRunnable.  I also still don't have a "logical" view...
However, the real problem with this code is that imm is not assigned a value when I try to get it from the context.  All of the Java examples assume that it will be.
Further edit:
I think as a last-ditch effort, I have modified the AndroidManifest.template.xml file with the following lines:
    android:configChanges="orientation|keyboard"
    android:windowSoftInputMode="stateAlwaysVisible">

It still doesn't appear.
Answer: Eureka!  I have it!
I should have gotten it sooner because I'm copying what FMX does but I thought at the time that I could do it more simply, i.e. do what they do in Java.
It seems that instead of using the InputMethodManager, I need to access the "TextEditorProxy" of the native activity instance that Delphi creates for Android apps.
I'm still using a part of the FireMonkey framework here in order to call CallInUIThread but I will replace it in time with my own JRunnable and call to the Activity's runOnUiThread.
Without further ado, here is the code:
    CallInUIThread(procedure
            var
            fmx: JFMXNativeActivity;
            TextView: JFMXTextEditorProxy;

            begin
            fmx:= TJFMXNativeActivity.Wrap(FApp^.activity.clazz);
            TextView:= fmx.getTextEditorProxy;
            TextView.setFocusable(true);
            TextView.setFocusableInTouchMode(true);
            TextView.requestFocus;
            TextView.showSoftInput(true);
            end);

I still don't know for sure where the input goes to but I shall find out, I hope.
Daniel.
Answer: after googled 2 days, I stitch up a solution that works with Delphi XE11.1.
here is the code, make use of it:
CallInUIThread(
procedure
var
  wnd: JWindow;
  ctx: JContext;
  ctxcls: JContextClass;
  imm: JInputMethodManager;
  immcls: JInputMethodManagerClass;
  view: JView;
  ret: Boolean;
begin
  wnd := MainActivity.getWindow;
  view := wnd.getDecorView;
  view.setFocusable(True);
  view.setFocusableInTouchMode(True);
  ret := MainActivity.getVirtualKeyboard.showFor(View);
end);


Laravel 5 - View [home] not found

Question: I ran composer update and now I'm running into an issue. I'm getting this error when I'm trying to load my home view:
InvalidArgumentException in FileViewFinder.php line 140:
View [home] not found.

Yes, files exists in my directory (resources/views, etc.). Name is home.blade.php.
My controller:
<?php namespace Hulahoop\Http\Controllers;

use Hulahoop\Http\Requests;
use Hulahoop\Http\Controllers\Controller;

use Illuminate\Http\Request;

class HomeController extends Controller {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        return view('home');
    }

}

Route:
Route::get('/', 'HomeController@index');

This was working fine and it's very basic function. What happened? Running on local homestead FYI.
UPDATE: When I run php artisan serve, I can view the home page view fine (i.e. on http://localhost:8000). But on homestead, no dice. What gives?
Comment: I cannot replicate this problem.
Comment: Are you sure you have the latest version of laravel 5? This was a bug people were experiencing a few months ago. Also what happens if you change your namespace to App?
Comment: Def latest version. Just got it last week. I was able to change the namespace to App. But got an error in 'AppServiceProvider', which looks like it had my previous namespace still. i.e. storage/framework/config.php and `storage/framework/services.json.php`. I changed all instances to App. Still same error...
Comment: 3 things, laravel 5 is now at 5.0.1, make sure you have that version. `composer update` will ensure this. `composer dump-autoload` should fix namespace change issues. And finally make sure that your homestead VM has write access to the storage folder and all of it's sub folders.
Comment: Did all of that. Also checked, folder have read&write...agh.
Comment: It's weird actually. I installed a new larval project via composer, called `test`. Pointed to that folder in the `homestead.yam` file, but it's still giving me the same error - for the other project...what...the
Comment: You and me both - or rather can't figure out what it is anyways. :p
Comment: You can't replicate your own problem?
Comment: So if I change the mapped domain in the homestead.yam file to something else (i.e. http://test.app), new project will run. Is there some cache I don't know about for that previous domain that the problematic project was running on? Mac OS user here, if that helps.
Answer: There seem to be a problem with vagrant and php artisan config:cache.
If you run php artisan config:clear and then try to open the page - you should see it working fine - just make sure you don't cache it via artisan.
Comment: Here's the explanation for this answer:
The reason is that the `config:cache` command sets all of the paths in the config files to be the paths on whichever machine the command was run. If you run artisan on the *host* machine and use `php artisan serve` on the *host* machine as well, then everything will work because the paths will be correct. However, those paths will not be the correct ones for inside the virtual machine so Laravel won't know where to find anything.
Comment: Ty @seb! This really helped me when migrating from one env to another
Comment: No problem @Maky - glad I could help.
Comment: And the money answer is here folks
Comment: If you have copied the project from local to somewhere, be SURE to rename/remove config.php to config.php_ from your /bootstrap/cache directory. That was the trick for me!
Comment: Worked great! I am running Homestead on Windows 10, and started getting this error after renaming the repo. Running this command fixed it!
Answer: Check out [ vendor/config.php ] it's hard-coded for local development.
Comment: i am unable to run `php artisan config:clear` command in my production server and by editing paths in `vendor/config.php ` file i solved my problem. It may be not the direct solution but we can use it. @lhab Shoully your answer helped me.
Answer: You need to give executable permission for the view folder 755

Laravel 5 - View [home] not found


What function does python -m unittest execute?

Question: In python 2.6, I've been reading through the unittest documentation. But I still haven't found this answer.
What function does pyton -m unittest execute?
For example, how would I modify this code such that just executing python -m unittest would detect it and run the test?
import random
import unittest

class TestSequenceFunctions(unittest.TestCase):

    def setUp(self):
        self.seq = range(10)

    def test_shuffle(self):
        # make sure the shuffled sequence does not lose any elements
        random.shuffle(self.seq)
        self.seq.sort()
        self.assertEqual(self.seq, range(10))

    def test_choice(self):
        element = random.choice(self.seq)
        self.assertTrue(element in self.seq)

    def test_sample(self):
        self.assertRaises(ValueError, random.sample, self.seq, 20)
        for element in random.sample(self.seq, 5):
            self.assertTrue(element in self.seq)

if __name__ == '__main__':
    unittest.main()

EDIT:
Note this is just a example, I'm actually trying to get it to detect and run multiple tests as a suite, here is my starting point - but python -m  unittest doesn't detect it nor does python -m unittest discovery work with it. I have to call python discovery.py to execute it.
discovery.py:
import os
import unittest

def makeSuite():
    """Function stores all the modules to be tested"""
    modules_to_test = []
    test_dir = os.listdir('.')
    for test in test_dir:
        if test.startswith('test') and test.endswith('.py'):
            modules_to_test.append(test.rstrip('.py'))

    all_tests = unittest.TestSuite()
    for module in map(__import__, modules_to_test):
        module.testvars = ["variables you want to pass through"]
        all_tests.addTest(unittest.findTestCases(module))
    return all_tests

if __name__ == '__main__':
    unittest.main(defaultTest='makeSuite')

Comment: `python -m unittest your_test_module_name`.
Comment: @falsetru yes that would work, but I don't want to actually specify each test... `python -m unittest -h` seems to imply there is a "default"... so what is that default...
Comment: If you use Python 2.7+, you can use `python -m unittest discover`. But that's introduced in Python 2.7.   How about using `py.test` / `nose` ?
Comment: I'd have to get `py.test` or `nose` pushed through security. If I don't have to do that... I'd be happier :-) Maybe I could write my own "discover" I think I'm half way there, but calling `python -m unittest Suite` or `Suite.makeSuite` fails for some reason...
Answer: python -m something executes the module something as a script.  i.e. from python --help:

-m mod : run library module as a script (terminates option list)

The unittest module can be run as a script -- And the arguments that you pass to it determine which files it tests.  The commandline interface is also documented in the language reference.
Comment: Ah I see that `-m unittest` is documented in 2.7 (I'm stuck with 2.6). Seems that I'm stuck writing my own discovery widget... Now I just need to get my current code to work for `-m unittest`...


Is it allowed to take the LED stumps to home after winning the match?

Question: Is it permitted for a player to take the LED stumps or at least bails to home after winning the match at least in the final?
I heard it costs  Rs. 25 lakhs.
Answer: As I said in my previous answer, Zings, the new high-tech LED stumps, are very costly. The entire set-up during a match costs US$ 40,000. That's why Bronte EcKermann, the inventor of Zings doesn't allow players to uproot them after winning the match. He also denied to take them even after winning the final.
But as an exception he said that he will allow MS Dhoni, the captain of the Indian Cricket team, to take the stumps only if India win the T20 World Cup 2014:

"Well, this is a very costly system. The entire set-up during a match costs US$ 40,000 (Rs 25 lakh approx), so I don't allow the players to uproot it during any celebrations. But I know Dhoni loves keeping a souvenir stump. If India can win the final, I might get into some arrangement with Dhoni," EcKermann, the inventor of LED stumps, said.

Source
Comment: But, the srilankan players took all the LED stumps.;(


Gradients of functions involving matrices and vectors, e.g., $\nabla_{w} w^{t}X^{t}y$ and $\nabla_{w} w^t X^tXw$

Question: I have encountered these two gradients $\triangledown_{w} w^{t}X^{t}y$ and $\triangledown_{w} w^t X^tXw$, where $w$ is a $n\times 1 $ vector, $X$ is a $m\times n$ matrix and $y$ is $m\times 1$ vector.
My approach for $\triangledown_{w} w^{t}X^{t}y$ was this:
$w^{t}X^{t}y$ =

$= y_1(\sum_{i=1}^{n}w_ix_{1i}) + y_2(\sum_{i=1}^{n}w_ix_{2i}) + ... + y_m(\sum_{i=1}^{n}w_ix_{mi})$
$= \sum_{j=1}^{m}\sum_{i=1}^{n} y_jw_ix_{ji}$

And I'm stuck there, not knowing how to convert it to matrix notation. I'm not even sure if it is correct.
How can I get the actual gradient $\triangledown_{w} w^{t}X^{t}y$ out of that partial derivative? Is there an easier way to get the gradient (maybe using some rules, like in ordinary calculus), because this way using summation seems tedious, especially when you have to calculate $\triangledown_{w} w^t X^tXw$?
How do I then work out $\triangledown_{w} w^t X^tXw$ ?
Comment: Your derivation is correct. It's simple to convert this result back into matrix notation $$\sum_j X_{ja}y_j=X^Ty$$ it just takes a little bit of practice. Now try the second one, just remember to handle the 2 $w$'s seperately.
Answer: Let
$$f (\mathrm x) := \rm x^\top A \, x$$
Hence,
$$f (\mathrm x + h \mathrm v) = (\mathrm x + h \mathrm v)^\top \mathrm A \, (\mathrm x + h \mathrm v) = f (\mathrm x) + h \, \mathrm v^\top \mathrm A \,\mathrm x + h \, \mathrm x^\top \mathrm A \,\mathrm v + h^2 \, \mathrm v^\top \mathrm A \,\mathrm v$$
Thus, the directional derivative of $f$ in the direction of $\rm v$ at $\rm x$ is
$$\lim_{h \to 0} \frac{f (\mathrm x + h \mathrm v) - f (\mathrm x)}{h} = \mathrm v^\top \mathrm A \,\mathrm x + \mathrm x^\top \mathrm A \,\mathrm v = \langle \mathrm v , \mathrm A \,\mathrm x \rangle + \langle \mathrm A^\top \mathrm x , \mathrm v \rangle = \langle \mathrm v , \color{blue}{\left(\mathrm A + \mathrm A^\top\right) \,\mathrm x} \rangle$$
Lastly, the gradient of $f$ with respect to $\rm x$ is
$$\nabla_{\mathrm x} \, f (\mathrm x) = \color{blue}{\left(\mathrm A + \mathrm A^\top\right) \,\mathrm x}$$
Comment: Thank you Rodrigo! Even though you didn't answer my question directly, you provided me with a method to evaluate gradients that I was able to use and compute them correctly.

Is this method going to work generally on any kind of matrix-vector expression? Furthermore, why is it that you have to express it in a form of inner product like ⟨v, *some expression*⟩ to get the actual gradient?
Comment: This works for functions that take matrices or vectors and produce scalars. Using the Taylor expansion, $$\lim_{h \to 0} \frac{f (\mathrm x + h \mathrm v) - f (\mathrm x)}{h} = \langle \mathrm v , \nabla_{\mathrm x} \, f (\mathrm x) \rangle$$
Comment: Oh, I see, thank you! Is there a similar way to get the derivative of a vector-valued or a matrix-valued function?
Comment: Take a look at [these](https://math.stackexchange.com/search?q=user%3A339790+%5Bmatrix-calculus%5D+jacobian).
Comment: I will, thank you so much man!
Answer: By the definition of what is to be the gradient vector of the application $$
\mathbb{R}^{n\times 1}\ni w \mapsto w^tX^ty=
\sum_{i=1}^n\sum_{j=1}^m w_{i1}\cdot X_{ji}\cdot y_{1j}\in\mathbb{R}
$$
we have
$$
\nabla_w \big( w^tX^ty \big)
=
\left(
\frac{\partial}{\partial w_{11}} ( w^tX^ty ),
\frac{\partial}{\partial w_{21}} ( w^tX^ty ),
\ldots,
\frac{\partial}{\partial w_{i1}} ( w^tX^ty ),
\ldots,
\frac{\partial}{\partial w_{21}}( w^tX^ty ),
\right)
$$
For $i_0=1,2,\ldots,n$;
\begin{align}
\frac{\partial}{\partial w_{i_0}} ( w^tX^ty )
=&
\frac{\partial}{\partial w_{i_01}}
\left(
 \sum_{i=1}^n\sum_{j=1}^m w_{i1}\cdot X_{ji}\cdot y_{1j}
\right)
\\
=&
 \sum_{i=1}^n\sum_{j=1}^m \frac{\partial}{\partial w_{i_01}} (w_{i1}\cdot X_{ji}\cdot y_{1j})
\\
=&
\sum_{j=1}^m \frac{\partial}{\partial w_{i_01}} (w_{i_01}\cdot X_{ji_0}\cdot y_{1j})
\\
=&
\sum_{j=1}^m X_{ji_0}\cdot y_{1j}
\\
\end{align}
Then
$$
\nabla_w \big( w^tX^ty \big)
=
\left(
\sum_{j=1}^m X_{j1}\cdot y_{1j},
\sum_{j=1}^m X_{j2}\cdot y_{1j},
\ldots,
\sum_{j=1}^m X_{ji_0}\cdot y_{1j},
\ldots,
\sum_{j=1}^m X_{jn}\cdot y_{1j},
\right)
$$
With similar calculations, we get the gradient vector of the application
$$
\mathbb{R}^{n\times 1}\ni w \mapsto w^tX^tXw=
\sum_{1\leq k\leq m} w_{1k}^2\cdot X_{k k}^2
+
2\sum_{1\leq k<\ell \leq m} w_{1k}\cdot X_{\ell k}\cdot X_{k\ell}\cdot w_{1\ell}
\in\mathbb{R}.
$$
Answer: Better use $w^tX^ty=(w^tX^ty)^t=y^tXw$


Drupal::request()->request->all() returns an empty array

Question: I have a custom controller that expects POST data. I had it working fine in 8.1.0 retrieving the data using \Drupal::request()->request->all() and \Drupal::request()->request->get($myvar).
Now, without any changes in my custom module, \Drupal::request()->request->all() is returning an empty array, and \Drupal::request()->request->get($myvar) is returning NULL.
Between the time it was working and when the issue arose, my hosting service Pantheon updated their Drupal 8 version from 8.1.0 to 8.1.1 and then 8.1.2. I suspect something may have changed then that affected this.
How can I fix this?
EDIT: Thanks for the comments, still not quite working...
Route YAML:
mymodule.foobar:
  path: '/foobar'
  options:
    _auth: [ 'basic_auth' ]
  defaults:
    _controller: '\Drupal\mymodule\Controller\FooBarController::foobar'
    _title: 'foobar'
  requirements:
    _user_is_logged_in: 'TRUE'
    _permission: 'administer site configuration'

Controller:
<?php
namespace Drupal\mymodule\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
/**
 * Class FooBarController.
 *
 * @package Drupal\mymodule\Controller
 */
class FooBarController extends ControllerBase {
  /**
   * Provides content for the /mymodule/foobar path.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request
   */
  public function foobar(Request $request) {
    $content = $request->getContent();
    $data = array();
    $data['a'] = $request->get('foo');
    $data['b'] = $request->request->get('foo');
    $data['c'] = \Drupal::requestStack()->getCurrentRequest()->request->get('foo');
    $data['e'] = $request->request->all();
    $data['f'] = $content;

    $request = \Drupal::requestStack()->getCurrentRequest();
    $content = $request->getContent();
    $data['g'] = $request->get('foo');
    $data['h'] = $request->request->get('foo');
    $data['j'] = $request->request->all();
    $data['k'] = $content;

    return new JsonResponse((object) $data);
  }
}

Postman Request:

Note: This was working before with this exact code, correctly using basic HTTP authentication. There have been no changes other than these variations to my controller, and core updates.
Any more ideas?
Comment: Can you show us the routing yml as well, and also the url with query you type in the browser? (eg //localhost/foo?foo="hello")
Comment: @ssibal good point. Added.
Comment: Can you var_dump please the $_REQUEST variable?
Comment: Aha, both $_REQUEST and $GLOBALS['_REQUEST'] are empty arrays. I've openned a ticket with my host to see if there is perhaps some PHP server configuration issue here...
Comment: I'm having the same issue except I only see data when using form-urlencoded which corrupts the posted data. The request parameters are always empty when I use json.
Comment: Does this answer your question? [How to get $\_POST and $\_GET parameters](https://drupal.stackexchange.com/questions/207044/how-to-get-post-and-get-parameters)
Answer: I had the same issue and the request parameters were always empty. I think it could be due to using it in a controller rather than a REST endpoint but I'm not sure.
The following line of code worked for me:
$request->getContent();

Answer: Try this:
$request = \Drupal::requestStack()->getCurrentRequest()->query->all();

Sidenote: Using a Controller you shouldn't use "\Drupal::..." static request call. Instead, you always have in your controller's enter point function a "Request $request" object as a last argument.
Comment: "query" is for GET parameters, the question asked about POST parameters.


Solve the congruence by using the method of completing the square

Question: Actually, I found a open problem which is the same as my problem, see Solve quadratic congruence equation by completing square. But I can not understand the answers...they are too brief...
My typical method to solve a prime power $p^r$ modulus congruence is first solve the corresponding $p$ modulus congruence and then rise the solution in some way. For example, to solve the congruence $x^2 +x+7=0$ (mod $27)$, I will first solve the congruence $x^2 +x+7=0$ (mod $3)$ and the only solution is $1$. Then, with the same trick used in the open problem, we can rise the solution, and finally get the solutions of the congruence modulo $27$.
But my textbook requires me to solve this problem with the method of completing the square. And it provides me of a hint that $4x^2+4x+28=(2x+1)^2+27.$ However, I have no idea about this hint. And the textbook never mentions the method of completing the square.
Thanks in advance.
Comment: Isn't it $2\times 14\color{red}-1\equiv 0\bmod 27$ @J.W.Tanner
Comment: Yes, I meant 13
Comment: @J.W.Tanner Your argument makes more sense. I found a flaw in my reasoning. Because $u$ may not be powers of a prime, I can not argue in that way. Thanks a lot Tanner, sincerely. You helped me a lot in my study of elementary number theory.
Comment: So you want to solve $$4x^2+4x+28\equiv 0\pmod{27}\ \text{ or } \ x^2+x+7\equiv 0\pmod{27}$$?
Comment: Note $2\times14+1\equiv0\pmod{27}$
Comment: @Dr.Mathva Sorry for my late reply. I wanted to solve the second one but actually these two congruence are equivalent in that $(4,27)=1$, right?
Comment: @J.W.Tanner Good inspection too :) But, hmmm, it seems like that we missed the other two solutions, i.e. $x\equiv 4$ mod $27$ and $x\equiv 22$ mod $27$...
Comment: You're right @Sam Wong
Comment: Since $27$ isn't prime, there can be more solutions to $u^2\equiv0$ besides $u\equiv0$
Comment: @J.W.Tanner I see. Can you help me check if my comment below the post of WillJagy is correct? Thanks!
Comment: @SamWong:  How about this:  If $9$ does not divide $u$ then $81$ does not divide $u^2$ so $27$ does not divide $u^2$
Answer: Completing the square is simply adding some amount and subtracting it in order to get partially a square. Consider for instance $x^2+2x=x^2+2x\underbrace{\color{green}{+1-1}}_{=+0}=(x\color{green}{+1})^2-1$...
Your textbook suggests that $$x^2+x+7\equiv 0\bmod{27}\stackrel{\cdot 4}{\iff}4x^2+4x+28\equiv0\bmod {27}$$ $$\iff \underbrace{(2x+1)^2}_{=4x^2+4x+1}+27\equiv(2x+1)^2+0\equiv(2x+1)^2\equiv0\bmod 27\iff \ldots$$
I obtained $$x\equiv\begin{cases}4\\13\\22\end{cases}\bmod 27$$
Comment: You mean mod $\color{red}27$
Comment: mod 27 for the last part perhaps
Comment: $\color{red}{27}$
Comment: And again, thanks for pointing the typo out!
Answer: if $$  u^2 \equiv 0 \pmod {27} $$
then
$$ u \equiv 0 \pmod 9  $$
so
$$ u \equiv 0,9,18 \pmod {27}  $$
Comment: I came up a reasoning and can you help me see if it works. Since $27=3\cdot 3\cdot 3$ and $27\vert u^2 \iff (3\cdot 3\cdot 3)\vert (u\cdot u)$, we know $3\vert u$ and $(3\cdot 3)\vert u$. And so $9\vert u$. Is my reasoning correct? Thanks!
Comment: Thanks Jagy. Your post helped me understand Dr. Mathva's post. But I still have problems in understanding your first step. i.e. How do we know $u\equiv 0\,($mod $9)$ provided  $u^2\equiv 0\,($mod $27)\,?$ Thanks for your elaboration in advance.


add dynamic order to add remove html input field

Question: i have this code for add/remove dynamic input:
JS:
$(function () {
    $("#btnAdd").bind("click", function () {
        var div = $("
");
        div.html(GetDynamicTextBox(""));
        $("#TextBoxContainer").append(div);
    });
    $("body").on("click", ".remove", function () {
        $(this).closest("tr").remove();
    });
});
function GetDynamicTextBox(value) {
  var number = Math.random();
    return '<input name = "DynamicTextBox" type="text" value = "' + value + '" class="form-control" />	' + '<select name="" class="form-control"><option> Select</option><option> Male</option><option> Female</option></select>	' + '<input name = "DynamicTextBox" type="radio" value = "' + value + '" />	' + '<input name = "DynamicTextBox" type="checkbox" value = "' + value + '" />	'+'<input name = "order" type="number" value = "" />	' + '<button type="button" class="btn btn-danger remove"></button>	'
}

HTML:

Dynamic Control : Text Box, Dropdown List, Radiobox and Checkbox

        TextBox
        Dropdown List
        Radio
        CheckBox
        Order
        BTN

    <button id="btnAdd" type="button" class="btn btn-primary" data-toggle="tooltip" data-original-title="Add more controls">  Add </button>

this code work true for me but how do can i add dynamic order(from 1 to ...) for each row(td). my mean add order input from number 1 and add +1 number from last order number.
demo is here
update: (my need)
Comment: Please update your code and show us your best attempt at resolving this issue yourself.
Comment: @devlincarnate: see my update
Answer: You need to just modify the JS code logic. The below example shows the use of variable count and its usage.
Here, the variable count is declared as 1 initially and as per the "Add" click the count value has been incremented by 1. Same way the count is been decremented by 1 when we are deleting/removing the the "tr" column.
$(function () {
  var count = 1;
  $("#btnAdd").bind("click", function () {
    var div = $("
");
    div.html(GetDynamicTextBox("", count));
    $("#TextBoxContainer").append(div);
    count++;
  });
  $("body").on("click", ".remove", function () {
    $(this).closest("tr").remove();
    count--;
  });
});

The click function will have one more argument count which is used for the rendering/displaying of the count value in the order field.
function GetDynamicTextBox(value, count) {
  var number = Math.random();
  return '
            <input name = "DynamicTextBox" type="text" value = "' + value + '" class="form-control" />
          	' + '

            <select name="" class="form-control">
              <option> Select</option>
              <option> Male</option>
              <option> Female</option>
            </select>
          	' + '

            <input name = "DynamicTextBox" type="radio" value = "' + value + '" />
          	' + '

            <input name = "DynamicTextBox" type="checkbox" value = "' + value + '" />
          	'+'

            <input name = "order" type="number" value = "' + count + '" />	' + '

            <button type="button" class="btn btn-danger remove"></button>
          	'
}

The above code works when we are removing the row from the last column.
If you are removing in-between the row from the list of tr tags you will find the order columns values are not arranged properly.
The below code is used for the removing the tr tag in-between the row and as well as the from the last tr tag. This code will be flexible for removing the tr row from anywhere in the list as well as updating the order row in the incremental way.
 $("body").on("click", ".remove", function () {
    var deleteElement = $(this).closest("tr");
    var countOfDeleteElement = $(deleteElement).find("#order").val();
    var lastElementCount = count - 1;
    if (countOfDeleteElement !== lastElementCount) {
      // It will come inside this if block when we are removing inbetween element.
      var remainingElements = deleteElement.nextAll('tr');  // get all the below elemnts from the removing element.
      // updating all remainingElements value of the order column
      remainingElements.each((i, ele) => {
        $(ele).find("#order").val(countOfDeleteElement);
        countOfDeleteElement++;
      })
    }
    deleteElement.remove();
    count--;
});


How to set max width of tooltip in primefaces?

Question: How to set max width of tooltip in primefaces?
<code><p:tooltip for="#{c.id}_checkBox" value="#{c.tooltipText}"/>
</code>
Comment: Which one? `p:tooltip` or `pe:tooltip`?
Comment: Using CSS? `p:tooltip` has `style` and `styleClass` attributes.
Answer: <code>                            <style type="text/css">
                            .ui-tooltip {
                                    max-width: 400px;
                                    white-space:pre-wrap;
                                }
                        </style>
</code>


Same perimeter and area for a circle and an ellipse

Question: For a given circle, is there exist an ellipse with same perimeter and area as to that circle?
If not, that is my suspicion, is in three-dimension parallel question: For a given sphere, is there exist an ellipsoid with same surface area and volume as to that sphere?
Comment: I don't know a proof, but I would assume this is impossible.  A circle is the shape which has the most area for the smallest perimeter. Similarly for a sphere.  So, changing the shape and keeping the perimeter should decrease the area.
Comment: Circle is an ellipse with $0$ eccentricity.  So you are asking if exist two ellipses with the same area and perimeter while eccentricity is different.
Answer: No, because the isoperimetric quotient $A/P^2$ is smaller for a non-circular ellipse than for any circle.
Comment: So bad, that is still a Chinese for me...
Comment: https://en.wikipedia.org/wiki/Isoperimetric_inequality .  The circle is the unique curve for which the maximum value is attained.
Comment: Amazing stuff! Thank you!
Comment: The answer in higher dimensions is the same, for the same reason.  The pair (n-dimensional volume, (n-1)-dimensional surface area) is unique to the sphere in n dimensions and cannot be attained by any other shape.
Comment: In 2 dimensions it is possible that Area and Perimeter determine the ellipse uniquely.  A more difficult question.
Answer: No there isn't because the sphere is optimal in relation to the ratio of circumference to area. You can check this simply by writing the equation of the circumference divided by the area and differentiating with respect to the width to see that the minimum occurs when the width and length are equal.
Although technically a circle is an ellipse so the actual answer is yes, the circle.
Answer: I cannot give you a deep rigourous argument, but surface tension is the reason a soap-bell is spherical so...
A circle has a specific eccentricity, and you choose another eccentricity while the area is fixed, there are no more parameters left to adjust for the perimeter.


Pagination Not Tied to database queries

Question: I would really like to:

to create a paginated table of nodes, displaying only those that the user has 'update' permission to; displaying title, content type, and path alias
the path for nodes may be different depending on the content type. More specifically, I have created a content type 'file' to wrap an uploaded file; I would like to display the url alias associated to the actual file, rather than the url alias of node that wraps it.

There are a few approaches that I have considered,

Creating views. However, the above behavior seems to require merging two views --- one for nodes of type file, one for node of content type not equal to file. I have no idea how to merge two views. Also, this method seems to create a dependency of the output of the view on the content type 'file'.
Use database query + pagination. In many of the examples that I have seen, if I want to add pagination to a table, I can do the following (see this very excellent tutorial):

run a database query using either pager_query or the extend method for the SelectQuery object
theme the query results, and use theme to generate the pager based on the query

The problem with this approach is making theme('pager') play well with filtering the database entries by node_access. For example, for an user with relatively few nodes that she can edit, the table displays many empty pages.
Database query, filter into array, then use pagination on array as suggested by this post. This does get the table to work correctly. However, it is really expensive, because the entire query is run at this point, and the pager is purely for aesthetic purposes; seems a bit wasteful.

Now (thank you for bearing with me so far), is there a some way to create this table this without using views, but faster than method 3? I can also accept 'no' for an answer; in this case, it would be nice to know why not.
Answer: I realise the question is more than a year old...
Create a view with no content type filter.  Add fields for Title, Type, Link, and File field in that order.  In the Link field settings, check the Exclude from Display box.  In the File field settings, under No Results Behavior, use the token of the Link field in the Rewrite Output space.  The available tokens will be listed in an expandable space below the text field.  Tokens include all fields listed before the current field, which is why the order matters.  Set display to a table and turn on paging.
Views will automatically check access permissions, so this should do what you want.  This will pull in all nodes, filter by access, look for the file and use that link if it finds it, and then in the cases where that field is empty (content of another type) it will use the node link instead.

Pagination Not Tied to database queries


ESLint and Prettier indent clashing with multi-line class definition

Question: I've got a class definition that is too long for a single line. Prettier tries to wrap it but when it does it adds an indentation, which I think is correct. But ESLint doesn't like this so it throws an indent error.
There seems to be no config in ESLint to change this behaviour.

Prettier output:
// ESLint throws an error
export default class FormFieldTemplateCheckboxList
    implements ClassComponent<FormFieldTemplateCheckboxListProps> {}

ESLint output:
// Prettier formats to the above on save
export default class FormFieldTemplateCheckboxList
implements ClassComponent<FormFieldTemplateCheckboxListProps> {}

It's a loop of ESLint and Prettier clashing with what they think is correct.
Partial Fix
This fix requires the eslint-config-prettier plugin, and removing indent from the eslint rules.
My old .eslintrc.json included the following;
"rules": {
    "indent": ["error", "tab", { "SwitchCase": 1 }]
}

Now prettier controls the indentation. Now there is no error being thrown, which is what I want to occur.
Comment: Most devs use prettier for formatting and eslint for linting and use this module to achieve it. https://github.com/prettier/eslint-config-prettier - might help.
Comment: Yeah that helps, also removing the indent rule from eslint will stop the error. I used the `eslint-plugin-prettier` for eslint and added a rule `"prettier/prettier": "error"` to throw the indent errors again.
Answer: I haven't found a solution that keeps the indent rules in eslint, but what I've found in my opinion is better.
Remove the indent rule from .eslintrc.json
"rules": {
    // "indent": ["error", "tab", { "SwitchCase": 1 }]
    // ...
}

This will now not show any errors with indents. To fix this I installed eslint-plugin-prettier.
Put prettier in the plugins list, and then add prettier/prettier in the rules and set it to either error or warn.
This will show an error or warning based on any prettier issues, including indent.
"plugins": [
    "prettier"
    // ...
],
"rules": {
    "prettier/prettier": "error",
    // ...
}

I'm not sure if there's a way to change the severity based on the prettier rule.


Why top number of time signature/dividing music into bars is required?

Question: As i know the only thing that top number of time signature defines is beats in a bar.
But i can read a music sheet without bar lines. So only the bottom number of time signature is required.
Why top number of time signature/dividing music into bars is required?
Comment: http://music.stackexchange.com/questions/31745/why-are-time-signatures-needed/ may be of interest.
Answer: You can (theoretically) read a score without bar lines, and indeed bars (or measures) and bar lines, in the sense that we use today, are a relatively new invention, from the mid of 17th century. Before that, "bar" lines were not used at all, or were used only to visually divide a piece into sections or phrases. In fact if we go all the way back to Gregorian chant, even the concept of beat, or regular time counting, is somewhat vague or even non existing.
But as European erudite music evolves, a number of things happen:

Stylistically, the beat or pulse of the music becomes more important and a distinctive integral part of each particular musical style. The rhythmic division (binary and ternary) and the existence strong and weak beats, important in popular music such as dances and work songs, is also incorporated in erudite music.
Musical composition becomes more complex, with multiple instruments/singers performing different parts and polyphony (two or more simultaneous lines of independent melodic parts) becomes more and more important.

And so it became necessary to have a notation device that allowed for the correct understanding by the performers of the intended rhythm and synchronization of the different performers.
Today the concepts of measure and time signature and the bar notation are fundamental parts of western music, that makes possible in a very practical way, for example:

To identify a binary meter, like a march, or ternary meter, like a
waltz.
To identify at a glance the strong and weak beats of each measure.
To notate extremely complex rhythmic figures (including polyphonically), with irregular subdivisions, while at the same time maintaining a clear perception of the beat.
To precisely notate pieces with complex signature (5/4, 7/8, etc.).
For an orchestra or ensemble to rehearse (measure numbering is a fundamental part of instrument-parts scores).
Answer: Here's a little test of your ability to read music without a time signature. This is the theme from a piece by a very well known composer - note, I transposed it into a different key because the original key might frighten some people. Which is the correct version - 3/4 time or 4/4?
(I'll add a link to the original after a day or so, to give the OP time to answer the question)

Apparently the OP didn't bite, but it's not a (rather insipid) little waltz or minor-key ballad in 3/4 time, which is what the first version would suggest.
The 4/4 version is actually the subject of a Bach fugue (BWV 853): see page 3 of
https://www.pianoshelf.com/sheetmusic/735/bach-bwv-853---wtc,-book-1--prelude-and-fugue-no.-8-735
Answer: Most (Western) music divides neatly into regular sections. We call those bars. Without them, there would be no particular emphasis on the first beat of each bar, which is where the composer got the top number from. When he wrote the music, he felt it had a rhythm, and translated that into number of beats - the top number. The bottom number, as you state, tells what sort of beats those are.
A vague analogy is writing some sentences without punctuation or a gap between each word. Yes, it could probably be read, but where's the advantage?
If you were presnted with a piece of music written with no barlines, how would you know whether it was, say, 3/4, 4/4 or 5/4? There would be few clues, and the feel between even those three are very different, so you wouldn't be playing it in the intended way.
Answer: Why, in that case, is the bottom number required either?    Use time signatures and bars if they help organize the rhythmic patterns of your music.  Most composers find they do, both for musical and practical reasons - what would you prefer, "go from bar 123" or "go from the 1,103rd note"?  :-)


How do I go to Checkout Page without product in cart?

Question: I am using Commerce Donate and configured it to show donation form on checkout page. That is what actually I need. Donation form, contact info and payment form on same page.
But we cannot go to the checkout page without having some product in cart.
How can I do that?
Comment: Please follow next article: [Express checkout with Drupal Commerce](http://atendesigngroup.com/blog/express-checkout-drupal-commerce)
Also you can use sandbox projects: 1. [Commerce Single Page Checkout](https://drupal.org/sandbox/rj/1886778) 2. [Commerce Single Page](https://drupal.org/sandbox/tmsimont/1891418) 3. [Commerce Checkout Complete Page](https://drupal.org/sandbox/drugan/2111003)
Answer: You can add the following code to a custom module:
<code>/**
 * Implements hook_menu_alter().
 */
function YOURMODULE_menu_alter(&$items) {
  // Alter the default checkout callback to allow checkout without products.
  $items['checkout']['page callback'] = 'YOURMODULE_checkout_router';
}

/**
 * Implements hook_commerce_checkout_order_can_checkout().
 */
function YOURMODULE_commerce_checkout_order_can_checkout($order) {
  return TRUE;
}

/**
 * Displays the checkout form and create the user a cart if none exist.
 */
function YOURMODULE_checkout_router() {
  global $user;
  // Load the shopping cart order.
  if (!($order = commerce_cart_order_load($user->uid))) {
    $order = commerce_cart_order_new();
  }
  drupal_goto('checkout/' . $order->order_id);
}
</code>


How to serve a file read with fs.readFile

Question: i'm developing an application with nodejs. I have to read a local file on server, i'm using this function:
fs.readFile(path, "utf8", function (err,data) {}

how i can serve the 'data' to client? is good to open it in a new tab or downloading it on client.
--UPDATE--
I'm trying to use this solution, too.. is a good way?
res.writeHead(200, {"Content-Type": "application/pdf"});
res.write(data);
res.end();

Answer: Assuming you're using some sort of HTTP server here, you'll receive a response object in the handler.  This object is actually a stream.  I'm using the built-in node HTTP server here for my example.
http.createServer(function(req, res){
    fs.createReadStream(path).pipe(res);
});

In express and hapi there is a specific send-file response type if you're using those:
Hapi: reply.file
Express: res.sendFile
Comment: fs = require('fs'); var path = "W:\\xxxx" ;
fs.createReadStream(path).pipe(res);   is correct in this way?


What makes us recognize the composer of a song?

Question: Here is the situation: I'm at a friend's house, and he plays a song in the guitar. I never heard it before, but somehow I know it's John Mayer, even though I don't like him very much (I can't even name one song of his).
Based on this kind of situation I have always wondered what is there in a song, that lets us know who composed it, even when another person is playing. Most songs are very "generic", but some have something special, so that my brain tells me who the composer is, but I can't find out why.
So, is it possible to enumerate aspects of a song that might give away its composer? How can I know it and not know why I know? Is it too broad or too subjective to be put down in words?
Comment: Humans are very very good at pattern-recognition. Not perfect, but very good. They like to find patterns, they like to pigeon-hole things with similar patterns. When a pigeon-hole reaches a small enough size, it becomes easy to figure out other things that will fit in it. That's why you hear comments like "Wow! The new Arctic Monkeys song sounds just like Bowie" [It does, btw, but because there are sufficient match-points to be close, even though there are many non-matching points too]
Comment: @Tetsujin These matching points you are talking about, is there a limited set of them in case of music? Or there could be infinite?
Comment: now that's a question... I'd guess almost infinite, because humans can apply finer & finer gradation to pretty much anything. It's more 'general psychology' than music, but look at the current 'need' for people to divide music into smaller & smaller pigeon holes, which I'm sure is a failure to dare listen to anything that doesn't 'fit what I'm supposed to like this week' in case you don't look cool.
Comment: As this is a question about listening to music, it's borderline whether it's more appropriate here or at musicfans.stackexchange.com. I think it's practically impossible to prevent some of our personality from coming through in our work, so music will generally reflect some mix of the composer, the performer(s), and even the engineers and producers. When one person does several of those jobs, the imprint is even deeper.
Comment: It's not just pop music this applies to. If you've listened to Bach, Beethoven, Mahler, et al, there's a good chance you'll guess who may have written another piece you're listening to. Bit like painters (artists).
Comment: @Tim Yes, exactly!
Comment: @coconochao Yes, the set of *dimensions* of similarity between musical compositions is not too large - it's basically all those things that music theory is about. For instance, there was an infamous German duo in the 80s with literally a dozen hits reusing the exact same chord progressions. (Usually it's a *bit* more subtle than that.)
Comment: The show segment "The Piano Puzzler" is premised on this very idea.  The guy takes a well known tune and rewrites it in the style of a famous classical composer.  The game is to guess the tune and the composer.  That's fun unto itself, but then the question is asked, "What makes this in the style of [...]" and they discuss, that makes it enlightening.
Answer: An artist's musical signature is comprised of the patterns they typically use in melody, harmony, rhythm and every other aspect of music.
This might shed some light:
What contributes to an artist's melodic "signature?"
Comment: Does anybody care to comment on why this answer was downvoted? I can't learn if you don't provide feedback.