char to int conversion - what's happening here?

Question: I want to convert a char value to an int. I am playing with following code snippets:
#include <iostream>
using namespace std;

int main() {
    char a = 'A';
    int i = (int)a;
    //cout<<i<<endl; OUTPUT is 65 (True)

    char b = '18';
    int j = b;
    //cout<<j<<endl; OUTPUT is 56 (HOW?)

    char c = 18;
    int k = c;
    //cout<<c<<endl; OUTPUT is empty
    //cout<<k<<endl; OUTPUT is 18 (Is this a valid conversion?)

    return 0;
}

I want the third conversion, and I got correct output i.e 18. But is this a valid conversion? Can anyone please explain the above outputs and their strategies?
Comment: http://stackoverflow.com/questions/3960954/c-multicharacter-literal
Comment: For the last, you might want to check an [ASCII table](http://www.asciitable.com/). The casting itself (you *type cast*, not converse) is okay though.
Answer: char a = 'A';
int i = (int)a;

The cast is unnecessary. Assigning or initializing an object of a numeric type to a value of any other numeric type causes an implicit conversion.
The value stored in i is whatever value your implementation uses to represent the character 'A'. On almost all systems these days (except some IBM mainframes and maybe a few others), that value is going to be 65.
char b = '18';
int j = b;

A character literal with more than one character is of type int and has an implementation-defined value. It's likely that the value will be '1'<<8+'8', and that the conversion from char to int drop the high-order bits, leaving '8' or 56. But multi-character literals are something to be avoided. (This doesn't apply to escape sequences like '\n'; though there are two characters between the single quotes, it represents a single character value.)
char c = 18;
int k = c;

char is an integer type; it can easily hold the integer value 18. Converting that value to int just preserves the value. So both c and k are integer variables whose valie is 18. Printing k using
std::cout << k << "\n";

will print 18, but printing c using:
std::cout << c << "\n";

will print a non-printable control character (it happens to be Control-R).
Answer: char b = '18';
int j = b;

b, in this case a char of '18' doesn't have a very consistent meaning, and has implementation-dependent behaviour. In your case it appears to get translated to ascii value 56 (equivalent to what you would get from char b = '8').
char c = 18;
int k = c;

c holds character value 18, and it's perfectly valid to convert to an int. However, it might not display very much if you display as a character. It's a non-printing control character.
Comment: No, `'18'` is of type `int` and has an implementation-defined value. That value is converted from `int` to `char`, likely losing information.
Comment: Thanks if _c holds character value 18_ outputting it returns empty, why?
Comment: so the later from `char` to `int` will not return in losing information? though it is outputting the correct value..
Comment: Trying to print ascii value 18 to the screen won't do very much. If you look up in a ascii table, you'll see why.


Integrable functions as sums of measures

Question: Let $(\Omega, \mathcal A, \mu)$ be a measure space and $f: \Omega \rightarrow [0, + \infty] \mathcal A$-measurable.
Let $f(x) \in \mathbb N \cup \{+ \infty\}$ for all $x \in \Omega$. Why does it hold true that $\int f d \mu = \sum_{n=1}^{\infty} \mu (\{x \in \Omega: f(x) \geq n \})$ ?
Answer: If $\mu(\{f=\infty\}) > 0$, then of course both sides of the equation equal $\infty$. Otherwise,
\begin{align}
\int f\,d\mu = \sum_{n=1}^\infty n\mu(\{f=n\}) = \sum_{n=1}^\infty\sum_{k=1}^n\mu(\{f=n\}) = \sum_{k=1}^\infty\sum_{n=k}^\infty\mu(\{f=n\}) = \sum_{k=1}^\infty\mu(\{f\ge k\}).
\end{align}
Comment: Mate, what if $0<f(x)<1$, then your very first equality seems not hold.
Comment: @user284331 What function $0 < f(x) < 1$ satisfies $f(x) \in \mathbb{N} \cup \{\infty\}$ for all $x \in \Omega$?
Comment: I didn't notice that, sorry.
Comment: @BrianMoehring Thanks, edited.


Sum of predicted values to the power of 10

Question: When I take predicted values from a linear model to the power of 10, their sum is always a lot bigger than the original. Is it even allowed to sum, and does anybody have a reference for how this should be done?
E.g. lets say x is log(body.mass) and y is log(population.size). If I from the predicted values need to get the actual population size I would need sum(10^predicted.values) but this is always smaller than the original data.
Simple example in R code:
n = 10000
x = rnorm(n)
y = x + rnorm(n)
m = lm(y ~ x)
p = predict(m)

sum(10^y)/sum(10^p)

Gives results (if run a few times) from 6 to 40 times as many total individuals in the original data than the predicted.
Comment: I think you may be missing two steps between lines "y=..." and "m = ...".  You should put in something like "x2 = log10(x)" and "y2 = log10(y)".  Then your line "m" should be "m = lm(y2 ~ x2)".
Comment: Could you tell us more on why exactly are you doing, what you're doing?
Comment: Yes. I am estimating the total population size from body mass, per species, for species with unknown population sizes but known body masses. And we are using the log(pop.size)~log(body.mass) as regression since that is a pretty strong relationship and body mass is known.
Comment: You mean that the sum or predicted values is *smaller*, right? sum(10^p)<sum(10^y)
Answer: Let's work with natural logarithms, instead of base 10.
You are tripped up by a common pitfall in the lognormal distribution: the expectation of the lognormal is not the exponential of the expectation $\mu$ on the log scale. You need to account for the heavy-tailedness by including the residual variance and calculate $e^{\mu+\sigma^2/2}$.
In R:
sum(exp(y))/sum(exp(p))
sum(exp(y))/sum(exp(p+summary(m)$sigma^2/2))

The last expression will come out around 1.
Comment: Thank you. Does this mean that individual point estimates should also be corrected for the residual variance, if you are looking at a specific species? Further: the axes of the plot makes more intuitive sense by using base 10 for the log, is there a way to correct for residual variance here as well?
Comment: Yes, if you wish to predict the expectation, then you need to correct with the variance. (Note that if you are working with *quantiles*, you don't need the variance - the exponential of the median on the log scale will come out correctly as the median on the original scale.) If you are plotting with log axes, then the data to be plotted are on the log scale, so no correction necessary. [This earlier thread](https://stats.stackexchange.com/q/302902/1352) may be helpful.
Comment: I meant that i prefer to use the $log_{10}$ values in the model instead of $log_e$, is there a way to correct the prediction then?
Comment: There may be. One would need to do the integration. [This thread would be helpful.](https://stats.stackexchange.com/q/22607/1352) I don't really have the time at the moment, perhaps someone would like to chime in? Or you could post a follow-up question on calculating the expectation for a base 10 lognormal. Then again, since the difference is only a multiplicative factor, I personally would not go to the trouble (though I understand that some fields like the interpretability of base 10).
Answer: Differences in averages
You have a function f(x) such that $f(\overline{x}) \neq \overline{f(x)}$. So like the mean squared is not equal to the square of the means you also have that the mean of a power is not a power of the mean.
You estimate the model $y_i = \hat{y}_i +e_i$. Then you compare $\overline{10^{y_i}}$ with $\overline{10^{\hat{y}_i}}$. Or differently written you compare $10^{y_i} = 10^{\hat{y}_i+e_i}$ with $10^{\hat{y}_i}$.
The residual terms $e_i$ are obtained such that they average to zero for $y_i = \hat{y}_i +e_i$ but you do not get $10^{y_i} = 10^{\hat{y}_i} +e_i$ with $e_i$ average to zero. You will get that there is different scaling for negative and positive values because $10^{y+a}-10^y$ is a bigger difference than $10^{y-a}-10^y$.
So most often $\overline{10^{y_i}} > \overline{10^{\hat{y}_i}}$(even while $\overline{y_i} = \overline{\hat{y}_i}$ ), because the residuals do not 'count' the same after taking the power.
Simple example $2^1+2^{-1} = 0.5+2 = 2.5 > 2 = 2^0 + 2^0$
You will always get $\overline{10^{y_i}} > \overline{10^{\hat{y}_i}}$ when all $\hat{y}_i$ are the same. E.g. when you just model $\hat{y}_i = a$ instead of  $\hat{y}_i = a + b x_i$.
Example when you do not get $\overline{10^{y_i}} > \overline{10^{\hat{y}_i}}$ is (note the extra data point with x=100):
set.seed(1)
n = 10000
x = c(rnorm(n),100)
y = x + rnorm(n+1)
m = lm(y ~ x)
p = predict(m)

sum(10^y)/sum(10^p)

giving 0.76 which is due to the data point at x=100 falling far below the line (the other 10000 points have much more weight) but contributing a lot when the power of 10 is taken (then the other 10000 points have much less weight)
What model/average to choose
The choice of the two different averages or the choice of model ($10^{\hat{y}_i} = 10^{a + b x_i + e_i}$ versus $10^{\hat{y}_i} = 10^{a + b x_i} + e_i$) will vary based on what weight you want to give to the different points (high versus low values).
See the below image for another example with the extra data points.
set.seed(1)
n = 200
x = c(rnorm(n),log(100*c(1:5)))
y = x + c(rnorm(n),rnorm(5,-1,0.1))
m = lm(y ~ x)
p = predict(m)

sum(10^y)/sum(10^p)

One of the fit lines is according to a linear model:
$$y_i = a x_i + b + e_i$$
The other is according to a non linear model:
$$(10^{y_i}) =  10^b  (10^{x_i})^a +e_i $$
or rewriting for simplicity $v_i = (10^{y_i})$, $u_i = (10^{x_i})$, and $c=10^b$
$$v_i =  c u_i^a +e_i$$

You see how the lines place different weights on different regions. In the first/left graph you see how the five points on the right have little weight on the linear model. In the second/right graph you see how the five points now have a much larger values (while the 200 points on the left are barely visible) and the residual terms get more weight.
It depends a lot on your goals which representation/model/average you want to choose as well on the original model that generates the data (how are the errors distributed).
Say you want to have a fitted curve to make predictions of $10^{Y}$ in the (entire) range $10^{X}$, then the non-linear model might be better, since the linear model put's more weight on the residuals of the smaller values.

What you want to do with the average of all $y_i$ or $10^{y_i}$ is unclear. To me it makes no sense because they depend on the $x_i$ which may differ from test to test (you say you are computing a population size, but what population is that if there are many $x_i$?) . The model parameters seem to be more relevant, but then again I don't know what you are doing with the average.
Comment: I don't quite understand your answer. If they are only linearly related on a log-log scale how would you then start out by modelling $10^y \sim 10^x$ ?


How to change in Datagridview alignment of a specific Column for printing?

Question: I apologize for my weird code. I'm a complete newbie and just learning how stuff works.
I found this code and changed some stuff to it.
My problem is:
I somehow managed for all columns the alignment to be right but I need for my first Colum "Data1" the alignment to be left. I can change that in the settings or with a click of a button but when printing it's just right aligned with the others.. I have tried everything but my knowledge is maybe 2% so I would really appreciate the help.
I have a Button1, DataGridView1, PrintPreviewDialog1, PrintDocument1, PrintDialog1
Here is a picture of the Form and an example of Print-Preview:
https://drive.google.com/file/d/1VnUzrM9fgiEcJExrXalo7Uo6XKQwT3Sd/view?usp=sharing
This is my Code:

    Private mRow As Integer = 0
    Private newpage As Boolean = True
    Private m_PagesPrinted As Integer = 1

    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        With DataGridView1
           .Rows.Add("Plan 1", "50", "2,99", "28,40", "170,90")
            .Rows.Add("Plan 27 a", "80", "14,99", "227,85", "1427,05")
            .Rows.Add("Plan 27 b", "808", "47,45", "84,85", "14,05")
            .Rows.Add("Plan 27 c", "80", "12,21", "77,10", "27,05")
            .Rows.Add("Plan 27 d", "470", "14,50", "15,40", "227,99")
            .Rows.Add("Plan 27 e", "2", "99,00", "2,84", "4427,67")
            .Rows.Add("Plan 27 f", "4", "10,00", "9,48", "7,74")
            .Rows.Add("Plan 27 g", "54", "150,50", "46,64", "127,50")
        End With
    End Sub

    Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        newpage = True
        'Dim frm As Form = DirectCast(PrintPreviewDialog1, Form)

        PrintPreviewDialog1.PrintPreviewControl.StartPage = 0
        PrintPreviewDialog1.PrintPreviewControl.Zoom = 0.8
        PrintPreviewDialog1.WindowState = FormWindowState.Maximized

        ' sets it to show '...' for long text
        Dim fmt As StringFormat = New StringFormat(StringFormatFlags.LineLimit)
        fmt.LineAlignment = StringAlignment.Center

        Dim newfmt As StringFormat = New StringFormat(StringFormatFlags.LineLimit)
        newfmt.LineAlignment = StringAlignment.Near

        'fmt.Trimming = StringTrimming.EllipsisCharacter
        Dim y2 As Int32 = 200
        Dim rc As Rectangle
        Dim x2 As Int32 = 2
        Dim h As Int32 = 200
        Dim row2 As DataGridViewRow

        ' print the header text for a new page
        '   use a grey bg just like the control
        If newpage Then
            row2 = DataGridView1.Rows(mRow)
            x2 = e.MarginBounds.Left
            For Each cell As DataGridViewCell In row2.Cells
                Dim x As Integer = 170
                Dim y As Integer = 360
                Dim xwidth As Integer = 190
                Dim yheight As Integer = 20
                Dim cellwidth As Integer = 300
                Dim cellheight As Integer = 370

                Dim fon As New Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold)

                Dim rect As New Rectangle(x, 100, xwidth, yheight)

                ''##########################################################################
                ''##########################################################################
                Dim rek1 As New Rectangle(40, 350, 750, 20)
                e.Graphics.DrawRectangle(Pens.Black, rek1)

                Dim rek2 As New Rectangle(40, 370, 750, 100)
                e.Graphics.DrawRectangle(Pens.Black, rek2)
                ''##########################################################################
                ''##########################################################################

                e.Graphics.DrawString("Data1                                                                                Data2             Data3            Data4                 Data5", fon, Brushes.Black, 42, 351)

            Next
            y2 += h

        End If
        newpage = False

        ' now print the data for each row
        Dim thisNDX As Int32
        For thisNDX = mRow To DataGridView1.RowCount - 1
            ' no need to try to print the new row
            If DataGridView1.Rows(thisNDX).IsNewRow Then Exit For

            row2 = DataGridView1.Rows(thisNDX)
            x2 = e.MarginBounds.Left
            h = 0

            ' reset X for data
            x2 = e.MarginBounds.Left

            ' print the data
            For Each cell As DataGridViewCell In row2.Cells
                If cell.Visible Then
                    rc = New Rectangle(x2 - 20, y2, cell.Size.Width, cell.Size.Height)

                    Select Case DataGridView1.Columns(cell.ColumnIndex).DefaultCellStyle.Alignment
                        Case DataGridViewContentAlignment.BottomRight,
                             DataGridViewContentAlignment.BottomRight
                            fmt.Alignment = StringAlignment.Far
                            rc.Offset(-170, -30)
                        Case DataGridViewContentAlignment.BottomRight,
                            DataGridViewContentAlignment.BottomRight
                            fmt.Alignment = StringAlignment.Far
                        Case Else
                            fmt.Alignment = StringAlignment.Far
                            rc.Offset(-170, -30)
                    End Select

                    e.Graphics.DrawString(cell.FormattedValue.ToString(), DataGridView1.Font, Brushes.Black, rc, fmt)

                    x2 += rc.Width
                    h = Math.Max(h, rc.Height)
                End If

            Next
            y2 += h
            ' next row to print
            mRow = thisNDX + 1

            If y2 + h > 500 Then
                e.HasMorePages = True
                mRow -= 1   'causes last row To rePrint On Next page
                m_PagesPrinted += 1
                newpage = True
                Return
            End If
        Next

    End Sub
    Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
        PrintDialog1.Document = PrintDocument1
        PrintDialog1.PrinterSettings = PrintDocument1.PrinterSettings
        PrintDialog1.AllowSomePages = True
        If PrintDialog1.ShowDialog = DialogResult.OK Then
            PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings
            PrintDocument1.Print()
        End If
    End Sub
End Class

Can somebody explain me what needs to be changed so when printing then the first column is left aligned and the rest is on the right side..
Thanks in advance!!
Comment: You have explicitly listed two separate problems in your question. That's not allowed here. You should have taken the site tour when prompted. If you have two separate issues then you need to post two separate questions, each containing all and only the information relevant to that issue.
Comment: Thank you for the Info, I edited my question. I should be right now.
Answer: Your Select Case doesn't make sense. Your first Case matches DataGridViewContentAlignment.BottomRight twice and then your second case matches the same value twice more. In all cases, you're setting the Alignment of your StringFormat to StringAlignment.Far. I would think that it should be more like this:
Select Case DataGridView1.Columns(cell.ColumnIndex).DefaultCellStyle.Alignment
    Case DataGridViewContentAlignment.TopLeft,
         DataGridViewContentAlignment.MiddleLeft,
         DataGridViewContentAlignment.BottomLeft
        fmt.Alignment = StringAlignment.Near
    Case DataGridViewContentAlignment.TopCenter,
         DataGridViewContentAlignment.MiddleCenter,
         DataGridViewContentAlignment.BottomCenter
        fmt.Alignment = StringAlignment.Center
    Case DataGridViewContentAlignment.TopRight,
         DataGridViewContentAlignment.MiddleRight,
         DataGridViewContentAlignment.BottomRight
        fmt.Alignment = StringAlignment.Far


Prevent keyboard event from bubbling (propagating to parents) in Flutter

Question: I am using RawKeyboardListener to detect the escape key to close (pop) windows, but I can't use the event and prevent it from bubbling (propagating) to parent windows, so all parent windows will receive escape and will close!
I tried using Focus element and it's onKey too, but not difference.
<code>return Scaffold(
  body: RawKeyboardListener(
    focusNode: FocusNode(),
    onKey: (RawKeyEvent event) {
      if (event.logicalKey == LogicalKeyboardKey.escape) {
      Navigator.pop(context);
    }},
    autofocus: true,
    child: Container(
      child: Text("blah blah")
      ),
    ),
  ),
);
</code>
Comment: *"I am using RawKeyboardListener to detect the escape key"* - your code does not detect the escape key in any way: you call `pop()` method unconditionally
Comment: just typo in the question, updated it, thanks.
Comment: the events dont bubble to parent window (page): now your `onKey` is called twice (for key down and up)
Comment: Yes, it's bubbled, I added logs.
Answer: you can attach the key listener to focus Node this listener will return a KeyEventResult enum that determines that the key event is handled or not
<code>   var focus = FocusNode(onKey: (FocusNode node, RawKeyEvent event) {
      if (event.logicalKey == LogicalKeyboardKey.escape)
      {
        return KeyEventResult.handled;
      }
      return KeyEventResult.ignored;
    });
</code>
Also here is the KeyEventResult description :
<code>/// An enum that describes how to handle a key event handled by a
/// [FocusOnKeyCallback].
enum KeyEventResult {
  /// The key event has been handled, and the event should not be propagated to
  /// other key event handlers.
  handled,
  /// The key event has not been handled, and the event should continue to be
  /// propagated to other key event handlers, even non-Flutter ones.
  ignored,
  /// The key event has not been handled, but the key event should not be
  /// propagated to other key event handlers.
  ///
  /// It will be returned to the platform embedding to be propagated to text
  /// fields and non-Flutter key event handlers on the platform.
  skipRemainingHandlers,
}
</code>


Agilidade de leitura MVC

Question: Tenho uma aplicação em MVC 4 que não possuí nenhuma operação de adição/exclusão/edição, ela apenas lê e disponibiliza dados (conforme filtros).
Os dados veem basicamente de 4 views.

Sendo a primeira de cerca de 1,5 mil registros - leitura instantânea via query
A segunda de cerca de 15 mil - leitura de cerca de 14 segundos via query
A terceira de cerca de 30 registros - leitura instantânea via query
A quarta de cerca de 1,3 mil registros - leitura instantânea via query

Cada view tem seu respectivo model. Consecutivamente, em cada PartialView necessária, chamo o domínio necessário.
Anteriormente trabalhava de forma parecida com esse exemplo:
var bdModelA = new SegundaViewEF(Contexto); // View da query de 14 segundos
var Todos = bdModelA.ListarTodos();
var Quantidade = Todos.Count();
var NF = Todos.Where(x => x.Tipo == "NF");
var NCC = Todos.Where(x => x.Tipo == "NCC");
var QuantidadeNF = NF.Count();
var QuantidadeNCC = NCC.Count();

foreach(var Item in NF){
// codigo aqui
}

foreach(var Item in NCC){
// codigo aqui
}

Notei lentidão, comecei a trabalhar assim:
var bdModelA = new SegundaViewEF(Contexto);
var Todos = bdModelA.ListarTodos();
var QuantidadeNF = 0;
var QuantidadeNCC = 0;
var Quantidade = 0;

foreach(var Item in Todos){
Quantidade++;
if(Tipo == "NF"){
QuantidadeNF++;
//Codigo aqui
}else if(Tipo =="NCC"){
QuantidadeNCC++;
//Codigo aqui
}
}

Continuou lento.
Gostaria de saber se a melhor prática é a descrita no primeiro exemplo ou no segundo e se há alguma limitação do MVC com relação a leitura de view, pois sempre trabalhei com leitura de tabela.
Eu chamo de um a três domínios diferentes em cada uma de minhas PartialView, sendo que a da maior query (14 segundos), eu chamo ao menos umas 4 vezes. Possuo cerca de 7 a 8 PartialView.
Minha aplicação demora cerca de 8 minutos para abrir (conexão via VPN) e 5 minutos via conexão direta.
O que posso fazer para melhorar?
Answer:
Gostaria de saber se a melhor prática é a descrita no primeiro exemplo ou no segundo e se há alguma limitação do MVC com relação a leitura de view, pois sempre trabalhei com leitura de tabela.

Nenhum dos dois. É a repetição do já manjado erro de encapsular o contexto. Não vai funcionar direito porque assim você retira as opções em código de criar queries já otimizadas para cada consulta que você vai fazer. Do jeito que está, todas as leituras serão TABLE SCAN.
O que eu faria:
// var bdModelA = new SegundaViewEF(Contexto);
// var Todos = bdModelA.ListarTodos();
// var Quantidade = Todos.Count();
var Todos = Contexto.SegundaViewEF.AsQueryable();
var NF = Todos.Where(x => x.Tipo == "NF").ToList();
var NCC = Todos.Where(x => x.Tipo == "NCC").ToList();
var QuantidadeNF = NF.Count();
var QuantidadeNCC = NCC.Count();

foreach(var Item in NF){
// codigo aqui
}

foreach(var Item in NCC){
// codigo aqui
}

O que posso fazer para melhorar?

Há outra coisa que pode ser feita: Instalar o MiniProfiler.Mvc4 (serve pro MVC5 também) e conferir as consultas.
Veja como configurar o projeto aqui.
Comment: Certo, obrigado Cigano. No MVC trabalhar com view ou tabela, da na mesma ? Acha que minha aplicação estava tão lenta pelos motivos citados?
Comment: O Entity Framework não analisa se o objeto é tabela ou view. Ele simplesmente executa os comandos de banco como um usuário normal faria. Sobre sua aplicação estar lenta, do lado dela o que estava errado já mencionei. Do lado da view, você terá que estudar o plano da consulta e ver o custo de cada operação.

Agilidade de leitura MVC


Need to find out which button was pressed

Question: The following scripts job is to scan the given directory and find out how many files(or characters) are in it. Then it creates a number of buttons equal to the total number of files. Currently my problem is that i have no way knowing which button is pressed during run time.
extends Control

#number of characters to be imported
var characters = 0
#file names of all avalible chararters
var files = []
#buttons associated with said characters
var array = []

# Called when the node enters the scene tree for the first time.
func _ready():
    scan_directory()
    populate()
    setup()

#scans for the number of characters in the folder
func scan_directory():
    var current = ""
    var dir = DirAccess.open("res://Characters/")
    dir.list_dir_begin()
    current = dir.get_next()
    while current != "":
        files.push_back(current)
        current = dir.get_next()
    print(files)
    characters = files.size()

func setup():
    var x = 0
    for i in characters:
        var but = array[x]
        var path = "res://Characters/" + files[x] + "/"+ files[x] + ".gd"
       var char = load(path)
       var dic = char.import()
       x += 1

#creates buttons equal to the number of characters
func populate():
    var x = 100
    var y = 100
    var texture = Texture2D.new()
    texture = load("res://img/button.jpg")

    for i in characters:
        var but = Button.new()
        var path = load("res://Scripts/Character_Select.gd")
        add_child(but)
        but.pressed.connect(self.export)
        but.set_position(Vector2(x,y))
        but.set_button_icon(texture)
        x += 250
        if x > 1250:
            x = 100
            y += 250
        array.push_back(but)
    print(array)

func export():
    var temp = self.get_instance_id()
    print("Current id: " + str(temp))

So im currently looking for a way to either have the button pass a varible when clicked or be able to know the instance id of the button that was clicked so i can compare it to know buttons in the array.
Any help is appreciated.
Answer: When you connect to the signal:
but.pressed.connect(self.export)

What you are passing is a Callable created from the method export. You can bind arguments to it, like this:
but.pressed.connect(self.export.bind(1))

Then when the signal is emitted, it will pass that as argument to the method export. You, of course, need a parameter to receive it, for example:
func export(data):
    prints(data)
    # ...

In your case, you probably want to pass the iterator variable. This is the idea:
for i in blahblahblah:
    # ...
    # stuff
    # ...
    but.pressed.connect(self.export.bind(i))
    # ...
    # other stuff
    # ...

Since each time it would be binding a different value, this allows you know which one it is.
Of course, you can bind something else if you prefer.


Solve $x''+\frac{1}{17} x'=400$

Question: I have no problem finding the general solution $x_{g} = a+be^{-t/17}$, but I'm not sure how I would get the particular solution.
Since $G(x)=400$ I seek a particular solution in the form $x_{p}=C$, where $C$ is a constant. The only problem is that $x_{p}',x_{p}''=0$. So, if I plug them into the original equations I get $0=400$. Obviously I messed up my solution at some point. Any ideas?
Comment: The particular solution has to be of the form $Cx$ because of this exact reason. You can use the substitution $u=x'$ to make this clearer.
Answer: $$f''(x)=a+bf'(x)$$
$$\frac{f''(x)}{a+bf'(x)}=1$$
$$\int\frac{f''(x)}{a+bf'(x)}dx=x+c_1$$
Set $u=a+bf'(x)$:
$$\int\frac{du}{u}=bx+c$$
$$\ln u=bx+c$$
$$a+bf'(x)=e^{bx+c}$$
$$f'(x)=\frac{1}{b}e^{bx+c}-\frac{a}{b}$$
$$f(x)=\frac{e^{c_1}}{b}\int e^{bx}dx-\frac{a}{b}x+c_2$$
$$f(x)=\frac{1}{b^2}e^{bx+c}-\frac{a}{b}x+c_2$$
Use $a=400$ and $b=-1/17$.
Comment: The idea with the substitution is really nice.
Comment: @MarianG. Thank you very much. I am glad you liked it :)

Solve $x''+\frac{1}{17} x'=400$


Android restore animation on activity resume

Question: I have an activity where i do a scale animation on a view when a button is clicked.
I have set fillAfter as true for the animation.
When the animation is done, I start another activity. The problem is when I go back to my original activity, my scaled view is back to its original size.
Is there anyway to leave the activities content view the way it is when we start another activity?
I read the saveInstanceState, but most posts over here refer to saving values and not the UI. Im not really sure how to tackle this issue in a efficient way.
Or should I save the scaled view and restore it on the onResume function of the activity?
Comment: After further inspection, i think my Tabactivity is causing the problem. Normally the activity should look the same way we leave it but i think my implementation of tabactivity is causing the problem. So now looking for a way to properly implement tabs in android.
Answer: I was able to solve this issue by adding the launchMode attribute in the manifest file.
Comment: I just added this to the acitivity tag in the manifest file android:launchMode="singleTask"


Use a different PHP Upstream based on arguments in the URL - NGinx

Question: I run Nginx and PHP-FPM. Nginx runs under www-data and PHP-FPM runs as a separate user for each website. I use Nginx FASTCGI Caching and use the Nginx Helper plugin for WordPress. Unfortunately due to the difference in user we can't use the "Purge All" function in the plugin as the php user doesn't have access to the cache.
Changing permissions isn't an option due to security.
What I want to do is use a different PHP-FPM Pool if the below argument exists in the URL.
nginx_helper_urls=all

My current NGinx Config is below:
    upstream examplebackend {
        server unix:/var/run/php-fcgi-example.sock;
}

upstream cachedeletebackend {
        server unix:/var/run/php-fcgi-cachedelete.sock;
}

server {
        listen 80 default;
        server_name www.example.com;
        return 301 https://www.example.com$request_uri;
}
server {
        listen 80;
        server_name example.com;
        return 301 https://www.example.com$request_uri;
}
server {
        listen 443 ssl;
        server_name example.com;
        return 301 https://www.example.com$request_uri;
        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
}

server {
    listen 443 ssl;
    ssl_protocols TLSv1.2 TLSv1.3;
    server_name www.example.com;
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    access_log   /home/examplecom/logs/example.com.access.log;
    error_log    /home/examplecom/logs/example.com.error.log;

    root /home/examplecom/public_html;
    index index.php;

    set $skip_cache 0;

    # POST requests and urls with a query string should always go to PHP
    if ($request_method = POST) {
        set $skip_cache 1;
    }
    if ($query_string != "") {
        set $skip_cache 1;
    }

    # Don't cache uris containing the following segments
    if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") {
        set $skip_cache 1;
    }

    # Don't use the cache for logged in users or recent commenters
    if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
        set $skip_cache 1;
    }

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        try_files $uri =404;
        include fastcgi_params;
    if ( $args ~ nginx_helper_urls=all ) { fastcgi_pass cachedeletebackend; }
        fastcgi_pass examplebackend;

        fastcgi_cache_bypass $skip_cache;
            fastcgi_no_cache $skip_cache;

        fastcgi_cache WORDPRESS;
        fastcgi_cache_valid  60m;
    }

    location ~ /purge(/.*) {
        fastcgi_cache_purge WORDPRESS "$scheme$request_method$host$1";
    }

    location ~* ^.+\.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
        access_log off; log_not_found off; expires max;
    }

    location = /robots.txt { access_log off; log_not_found off; }
    location ~ /\. { deny  all; access_log off; log_not_found off; }
}

Not sure where I am going wrong or if it is even possible. Thanks
Comment: What happens when you try to call this URL?
Answer: This likely happens because If is evil.
In nginx, most of the if statements should be implemented with map feature instead.
In your case, first define the map in http level:
map $arg_nginx_helper_urls $backend {
    all cachedeletebackend;
    default examplebackend;
}

Then, in PHP location block use:
location ~ \.php$ {
    try_files $uri =404;
    include fastcgi_params;
    fastcgi_pass $backend;

    fastcgi_cache_bypass $skip_cache;
    fastcgi_no_cache $skip_cache;

    fastcgi_cache WORDPRESS;
    fastcgi_cache_valid  60m;
}

The map will assign a value to $backend variable depending on query argument nginx_helper_urls value. By default, examplebackend is used. If the argument value is all, then cachedeletebackend is assigned to the variable.
Comment: This works perfectly on my current server which does only have one website. If I am to use this on my server with multiple sites with multiple different backends per site plus the cachedeletebackend. Where abouts in the config should I place the code to ensure its in the correct location. Would above the server section in each virtualconf file be adaquate?
Comment: You would configure `upstream examplebackend` and `upstream cachedeletebackend` accordingly for each of your virtual hosts. In Debian systems, you can put the `map` section into `conf.d/cachemap.conf` for example and it will work from there.


Proof of the identity $\int_0^{+\infty}\frac{\sin(x)}{x^\alpha}dx=\frac{\Gamma(\alpha/2)\Gamma(1-\alpha/2)}{2\Gamma(\alpha)}$ for $\alpha\in (0,2)$.

Question: Let $0<\alpha<2.$ Looking for a proof for the following: $$\int_0^{+\infty}\frac{\sin(x)}{x^\alpha}dx=\frac{\Gamma(\alpha/2)\Gamma(1-\alpha/2)}{2\Gamma(\alpha)}.$$
Any ideas?
Comment: What have you tried so far?
Comment: From the case cases $\alpha=1,\alpha=\frac{1}{2},$ and using $\Gamma$ function, I found $\frac{1}{x^\alpha}=\frac{1}{\Gamma(\alpha)}\int_0^{+\infty}e^{-xy}y^{\alpha-1}dy$
Comment: So in order to use Fubini, taking $w>0,\int_0^w\frac{\sin(x)}{x^\alpha}dx=\frac{1}{\Gamma(\alpha)}\int_{0}^{+\infty}y^{\alpha-1}(\int_0^{w}\sin(x)e^{-xy}dx)dy=\int_0^{+\infty}\frac{1-e^{-wy}(y\sin(w)+\cos(w))}{y^2+1}dy,$ then using Dominated convergence theorem, taking $w \to +\infty,$ we find $\int_0^{+\infty}\frac{\sin(x)}{x^\alpha}dx=\frac{1}{\Gamma(\alpha)}\int_0^{+\infty}\frac{x^{\alpha-1}}{x^2+1}dx$
Comment: Conclusion: Since $\int_{0}^{+\infty}\frac{x^{\alpha-1}}{x^2+1}dx=\frac{1}{2}\int_0^1u^{\alpha/2-1}(1-u)^{-\alpha/2}du=\frac{1}{2}B(\alpha/2,1-\alpha/2)=\frac{1}{2}\Gamma(\alpha/2)\Gamma(1-\alpha/2)$ (Taking $x=\sqrt{(1-u)/u}$)
Comment: Trying to use Fubini theorem, like the cases $\alpha=1,\alpha=\frac{1}{2},$ considering $\sin(x)e^{-xy}$ or $\sin(x)e^{xy^2},$ so looking for a way (an expression to use Fubini).
Comment: Using this formula, we can compute $\int_0^{+\infty}\sin(x^\alpha)dx,$ for $|\alpha|>1$
Answer: The Mellin transform of $\sin{t}$ (as proven here) yields:
$$\mathcal{I}(z)=\int_0^{\infty} t^{z-1} \sin{t} \; \mathrm{d}t =\Gamma\left(z\right)\sin{\left(\frac{\pi}{2}z\right)}, \; -1 < \Re \left(z\right) < 1$$
And your integral is:
\begin{align*}
\mathcal{I}(1-\alpha) &= \Gamma\left(1-\alpha\right)\sin{\left(\frac{\pi}{2}\left(1-\alpha\right)\right)} \\
&= \Gamma\left(1-\alpha\right) \left( \frac{\pi }{\Gamma\left(\frac{1-\alpha}{2}\right)\Gamma\left(\frac{1+\alpha}{2}\right)} \right) \\
&=\Gamma\left(1-\alpha\right) \left(\frac{\pi \sin{\left(\pi \alpha\right)} \Gamma\left(\frac{\alpha}{2}\right) \Gamma\left(1-\frac{\alpha}{2}\right) }{2 \pi^2} \right) \\
&=\Gamma\left(1-\alpha\right) \left(\frac{\Gamma\left(\frac{\alpha}{2}\right) \Gamma\left(1-\frac{\alpha}{2}\right) }{2 \Gamma\left(\alpha\right) \Gamma \left(1-\alpha\right)} \right) \\
&= \boxed{\int_0^{+\infty} \frac{\sin{(x)}}{x^{\alpha}} \; \mathrm{d}x =\frac{\Gamma\left(\frac{\alpha}{2}\right) \Gamma\left(1-\frac{\alpha}{2}\right) }{2 \Gamma\left(\alpha\right)}, \; 0< \Re\left(\alpha\right)<2}
\end{align*}
Where Euler's reflection formula and the Legendre relation were utilized to get the desired form of the answer: $$\Gamma\left(\alpha\right)\Gamma\left(1-\alpha\right)=\frac{\pi}{\sin{\left(\pi \alpha\right)}}$$
$$\pi^2=\Gamma\left(\frac{\alpha}{2}\right)\Gamma\left(1-\frac{\alpha}{2}\right)\sin{\left(\frac{\pi \alpha}{2}\right)} \cos{\left(\frac{\pi \alpha}{2}\right)} \color{blue}{\Gamma\left(\frac{\alpha+1}{2}\right)\Gamma\left(\frac{1-\alpha}{2}\right)} $$
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\bbox[5px,#ffd]{\int_{0}^{\infty}{\sin\pars{x} \over x^{\alpha}}\,\dd x}
\,\,\,\stackrel{x\ \mapsto\ \root{x}}{=}\,\,\,
\int_{0}^{\infty}{\sin\pars{\root{x}} \over x^{\alpha/2}}
\pars{{1 \over 2}\,x^{-1/2}}\dd x
\\[5mm] = &\
{1 \over 2}\int_{0}^{\infty}x^{\pars{\color{red}{1 - \alpha/2}} - 1}\,
{\sin\pars{\root{x}} \over \root{x}}\,\dd x
\end{align}
Note that
$\ds{{\sin\pars{\root{x}} \over \root{x}} =
\sum_{k = 0}^{\infty}\pars{-1}^{k}\,{x^{k} \over \pars{2k + 1}!} =
\sum_{k = 0}^{\infty}\color{red}{\Gamma\pars{k + 1} \over
\Gamma\pars{2k + 2}}\,{\pars{-x}^{k} \over k!}}$.
With Ramanujan-MT:
\begin{align}
&\bbox[5px,#ffd]{\int_{0}^{\infty}{\sin\pars{x} \over x^{\alpha}}\,\dd x} =
{1 \over 2}\,\Gamma\pars{1 - {\alpha \over 2}}
\color{red}{\Gamma\pars{\color{black}{-\bracks{1 - \alpha/2}} + 1} \over
\Gamma\pars{2\color{black}{\braces{-\bracks{1 - \alpha/2}}} + 2}}
\\[5mm] = &\
\bbx{{1 \over 2}\,\Gamma\pars{1 - {\alpha \over 2}}\,
{\Gamma\pars{\alpha/2} \over \Gamma\pars{\alpha}}} =
{\pi \over 2}{\csc\pars{\pi\alpha/2} \over \Gamma\pars{\alpha}} \\ &
\end{align}
Answer:
I thought that it might be instructive to present an approach that relies on a useful property of the Laplace Transform (See Here) to evaluate integrals over the positive reals.  To that end we proceed.

Let $F(s)=s^{-\alpha}$, $0<\alpha<2$ and $f(t)=\sin(t)$.  Then, the inverse Laplace Transform of $F(s)$ is
$$\mathscr{L}^{-1}\{F\}(x)=\frac{x^{\alpha-1}}{\Gamma(\alpha)}\tag1$$
and the Laplace Transform of $f(t)$ is given by
$$\mathscr{L}\{f\}(x)=\frac1{x^2+1}\tag2$$

Then, using $(1)$ and $(2)$ along with This Property of the Laplace Transform, we assert that
$$\int_0^\infty \frac{\sin(x)}{x^\alpha}\,dx=\frac1{\Gamma(\alpha)}\int_0^\infty \frac{x^{\alpha-1}}{x^2+1}\,dx\tag3$$

The integral on the right-hand side of $(3)$ can be evaluated using a host of methodologies See This, and is given by
$$\int_0^\infty \frac{x^{\alpha-1}}{x^2+1}\,dx =\frac\pi{2\sin(\pi\alpha/2)} \tag4$$

Substituting $(4)$ in $(3)$, we find that
$$\int_0^\infty \frac{\sin(x)}{x^\alpha}\,dx=\frac{\pi}{2\Gamma(\alpha)\sin(\pi \alpha/2)}\tag5$$

Finally, using the reflection formula for the Gamma Function (See this answer) as given by $\Gamma(x)\Gamma(1-x)=\frac{\pi}{\sin(\pi x)}$, we arrive at the expected result
$$\bbox[5px,border:2px solid #C0A000]{\int_0^\infty \frac{\sin(x)}{x^\alpha}\,dx=\frac{\Gamma(\alpha/2)\Gamma(1-\alpha/2)}{2\Gamma(\alpha)}}$$
as was to be shown!

ALTERNATIVE METHODOLOGY:  CONTOUR INTEGRATION
We begin by analyzing the closed-contour integral $I(\alpha)$, $\alpha\in (0,2)$ given by
$$\begin{align}
I(\alpha)&=\int_\varepsilon^R \frac{e^{ix}}{x^\alpha}\,dx+\int_0^{\pi/2}\frac{e^{iRe^{i\phi}}}{(Re^{i\phi})^\alpha}\,iRe^{i\phi}\,d\phi\\\\
&-\int_\varepsilon^R \frac{e^{-x}}{(ix)^\alpha}\,i\,dx-\int_0^{\pi/2}\frac{e^{i\varepsilon e^{i\phi}}}{(\varepsilon
 e^{i\phi})^\alpha}\,i\varepsilon e^{i\phi}\,d\phi\tag6
\end{align}$$
If we choose the branch cut of the natural logarithm to originate at $0$ and extend to the point at infinity along the real axis, Cauchy's Integral Theorem guarantees that $I(\alpha)=0$.  Furthermore, it is straightforward to show that as $R\to\infty$, the second integral on the right-hand side of $(6)$ vanishes.
So far, after letting $R\to\infty$ and then taking the imaginary parts of all terms in $(6)$ we have
$$\begin{align}
\int_\varepsilon^\infty \frac{\sin(x)}{x^\alpha}\,dx&=\sin\left(\frac{\pi (1-\alpha)}2\right)\int_\varepsilon^\infty\frac{e^{-x}}{x^\alpha}\,dx\\\\
&+\varepsilon^{1-\alpha}\int_0^{\pi/2} e^{-\varepsilon \sin(\phi)}\cos\left((1-\alpha)\phi+\varepsilon \cos(\phi)\right)\,d\phi\tag7
\end{align}$$
The last term on the right-hand side can be written as
$$\varepsilon^{1-\alpha}\int_0^{\pi/2} e^{-\varepsilon \sin(\phi)}\cos\left((1-\alpha)\phi+\varepsilon \cos(\phi)\right)\,d\phi=\varepsilon^{1-\alpha}\frac{\sin(\pi (1-\alpha)/2)}{1-\alpha}+O(\varepsilon^{2-\alpha})\tag8$$
Using $(8)$ in $(7)$, integrating by parts the first integral on the right-hand side of $(7)$ with $u=e^{-x}$ and $v=\frac{1}{(1-\alpha)x^{\alpha-1}}$, letting $\varepsilon\to0^+$, and exploiting the aforementioned reflection formula $\Gamma(x)\Gamma(1-x)=\frac\pi{\sin(\pi x)}$ yields
$$\begin{align}
\int_\varepsilon^\infty \frac{\sin(x)}{x^\alpha}\,dx&=\frac{\sin\left(\pi (1-\alpha)/2\right)}{1-\alpha}\int_\varepsilon^\infty\frac{e^{-x}}{x^{\alpha-1}}\,dx\\\\
&=\sin\left(\frac{\pi(1-\alpha)}2\right)\Gamma(1-\alpha)\\\\
&=\frac{\pi \sin\left(\frac{\pi (1-\alpha)}2\right)}{\sin(\pi \alpha)\Gamma(\alpha)}\\\\
&=\frac{\pi}{2\Gamma(\alpha)\sin(\pi \alpha/2)}\\\\
&=\frac{\Gamma(\alpha/2)\Gamma(1-\alpha/2)}{2\Gamma(\alpha)}
\end{align}$$
which agrees with the result obtained in the previous section!
Comment: Is there a real analysis method to prove the reflection formula?
Comment: Concerning the above question, I solved it using dominated convergence theorem (more details in the above comments)
Comment: Hi, didn't saw you messages, concerning your answer, it looks good!
Comment: @kurt.w.x Thank you Kurt.  Much appreciated.
Comment: Thanks for your effort
Comment: You're welcome.  My pleasure.


Is D minor also F Aeolian?

Question: If I were to write a song in D minor, could I notate it correctly in F Aeolian? Because the subsequent 4th of the root in F Aeolian would be flat, right? Therefore, D minor and F Aeolian, which in different keys like C Aeolian and A minor are the same, would be different by the B flat? Please correct me if I'm mistaken.
Comment: @Aaron I wonder if you mean "mean" (want to say) rather than "beat" (strike).   ;-)
Comment: While I don't suppose this answers your question, it's worth noting that in the days before Aeolian had been invented, pieces that we'd consider "minor" today were Dorian, but the sixth degree of the scale could be major or minor, that is, B natural or B flat when the center is D.  (Indeed, the same is true today, only we use terms like "natural minor" and "melodic minor" to deal with this variability.)
Comment: I wonder if you beat Ionian (major) rather than Aeolian (minor).
Answer: Key and mode are not the same thing.
In a mode (in the modern/current meaning of the word), your tonic (home note, center pitch) and the intervals around it are fixed in rigid positions, and if you play pitches not included in the fixed set, clearly enough to make a harmonic impact, you're not in the mode anymore.
In a key, only your tonic is fixed, and the third above it, when the harmony is at home, resting at the center of balance. In minor keys it's a minor third above tonic, and in major keys it's a major third above tonic (home note). But all the rest of the intervals can and often do change along the way. However, a key has a default set of notes/pitches, which is denoted by a key signature, and in a minor key, the default set of notes/pitches is the same as in the corresponding Aeolian. But in a key, there can be chromatic alterations, but the listener's feeling still remaining in the same key. The chromatic alterations are denoted with temporary accidentals.
If your sense of tonic does not change, i.e. where home is and if home is minor or major, the key does not change. But if the intervals around the tonic change, the mode changes.
You can have the chords Dm, E7, A7, Dm, in a tune that's in the key of D minor. During the E7 chord, the G note is temporarily sharpened to G#, and during the A7 chord, the C note is temporarily sharpened to C#. But you cannot have that in D Aeolian mode. In a mode, there are no chromatic alterations of notes. Inside a mode, you stick to the given intervals around the tonic and do not change them.
If your song is in D minor, chances are that it will use pitches outside D Aeolian, particularly C#, which is the so-called leading tone for D. And then you'll need to write temporary accidentals in addition to the key signature. Some people would even go as far as to say, if you do NOT raise the C to C# anywhere in the song, your song is not properly in D minor, because there's no leading tone.
Furthermore, the key signature of D minor has the notes of D Aeolian, not F Aeolian. F Aeolian has F, G, Ab, Bb, C, Db, Eb.

With pictures
Edit. The above was apparently not clear enough. I'll try once more, with pictures.
In traditional Western harmony thinking, there are seven scale degrees and a tonal center, tonic. The tonal center is a center of balance - you're supposed to feel when the music's harmony is "at home", resting. (In addition to the tonic being a note, it has a major/minor dimension to it, an expectation of a third being suitable beside the tonic at the resting position.) Each of the scale degrees can be thought to be like a switch that can be in natural, sharp or flat setting. (Let's not worry about double-flat and double-sharp etc. now.)

A key signature specifies settings for the seven scale degrees, but it does not say where the tonal center is. The notes you hear make you feel something about the tonal center. And it is entirely possible to use the same set of seven notes and set the tonal center to any of the notes, in the listener's mind. For some scale degrees it might take more skill than for others, but it's possible. If you feel that D is the tonal center - as you do if your song is, say, in D minor key, then the D note has special meaning to you:

Additionally, you can write temporary accidentals, which change a staff position to something different than what was specified by the key signature. For example, if you started with one flat, i.e. Bb and the rest of the scale degrees in natural, but you play an A7 chord, you'll most likely consider the C note as being switched to sharp position, at least for the duration of the chord. Look what happened to the C note's switch:

You might think something different about other scale degrees if you want, but the sounding pitches don't explicate things about the other notes. If you strongly PLAY a B natural, then the B scale degree's switch in your mind tends to get switched to natural position. You can think that you have harmonic context in your mind, consisting of a set of switches that change between sharp/natural/flat, according to what pitches you hear.
When you're "in a key", you can freely switch the scale degrees to different sharp/flat/natural positions, as long as you don't mess with the feeling of tonal center. If the tonal center moves, then the key changed. That's called a modulation.
Ok, what's a mode then? To stay in a mode, you are NOT free to change scale degrees, and you are NOT free to move the tonal center either. Be careful what you play, if you want to stay in the mode. The swithes should be like they had been superglued in place:

If you DO mess with any of the settings, then you break the mode and you're no longer in the same mode. Let's say you play a C# note. Not D Aeolian anymore.
Comment: @Tim default pitches is what you get, if you don't make any changes with accidentals. Like when something is in default settings. I don't have any better word for it. In D minor you have one flat, as defined by the key signature, if nothing further is said. If you raise the 6th or the 7th, you have to explicitly say so by adding accidentals.
Comment: 'The key has a default set of notes/pitches, which is denoted by the key signature.' Not sure that rings true for minors.
Comment: This is a good description of the modern meaning of "mode."  In the earlier incarnation of modal music, however, from the middle ages through the baroque -- but mostly in the renaissance -- modal music admitted chromatic alteration without losing its modal identity (which led to the major/minor tonal system).  In the middle ages, for example, there was no Aeolian mode, and a piece in Dorian would typically have both B flats and B naturals (with a D final).  In the baroque, you can fin harmonizations of modal melodies that have chromatic alterations but can't be analyzed as major or minor.
Comment: @Tim wouldn't you say that the natural minor is the default set of pitches?  Granted, it's largely a "lie told to children," but like most of those there's a fair amount of truth to it.
Comment: Natural minor *may* be the default set, but in minor *keys* the 6th and 7th notes are often raised, thus not following the key signature (unless it's Bartok) but would still be 'in key'.
Comment: @Tim but that's what "default" means, isn't it?  A default is normally one way but often different.
Comment: Truly not certain! But probably correct. Although there are many, many minor pieces with at least every leading note needing that accidental, making it, at least for me, an intrinsic part of the key - but not key sig.
Comment: @Tim right, this is the lie-told-to-children aspect (though it also has a real historical basis).  There's certainly an argument that the "default" seventh degree in minor is raised, but adapting the key signature system to reflect that would disrupt several centuries of practice.  So the notational default is a lowered seventh degree even if the tonal-music default is raised.
Comment: I think this should be the accepted answer because it's a nice description of a topic which is often very messy
Comment: @Tim, The minor key is described by the key signature and the mutability of steps 6 and 7. Some texts (but I don't remember which) even include both versions of steps 6 and 7 as "diatonic."  I'm not sure how these texts handled raised 7 with lowered 7.
Comment: To be clear: the central claim here is that a "mode" only includes 7 pitches/notes (the ones that would be diatonic in the relative major/ionian), whereas a "key" includes all 12 chromatic pitches of a 12-tone system? And that a "key" is thus only about classifying those pitches relative to the tonic, but a "mode" explicitly selects a subset? Actually, is there anything else being said here that I'm overlooking?
Comment: @KarlKnechtel Not at all. Total, catastrophic misunderstanding. My failure to communicate this idea is in cosmological scale. Galaxies were derailed. If you wait for some time, I'll try to draw pictures.
Comment: Let me at least test the premises first: does a mode "include" pitches? Does a key?
Comment: This is why it can be useful, in more stringent music theory contexts, to replace the layman's term "key" with "tonality." C major and A minor are "keys," and we learn about them along with our key signatures and circle of fifths. But to say that we "have a tonal center of C" allows us to mess around with modal mixture etc., without anybody freaking out about "But the key signature says..."
Comment: @KarlKnechtel I drew pictures for you, does it make more sense now? It's not maths, it's culture. "Key" etc. are really only words that people use to describe things they do. They might do something different than others, or they might describe what they do differently. Anything we say here, only makes sense in a practical context, when someone _does_ something. In a certain harmonic style I call "modal" playing, the scale degrees and the tonic are fixed. There are other styles, and there is more than one way to describe the practices, and people do not agree 100% on the meanings of the words.
Comment: The pictures are fantastic. Please draw pictures in all your answers.
Answer: (Natural) Minor and Aeolian are two words describing the same scale, as are Major and Ionian.
D minor/aeolian and F major/ionian share the same key signature: Bb.
A minor/aeolian and C major/ionian share the same key signature: no sharps or flats.
These major/minor (ionian/aeolian) pairs are called relative modes, meaning that they share the same key signatures.
The third note of a minor/aeolian scale is the first note of the corresponding (relative) major/ionian scale. The sixth note of a major/ionian scale is the first note of the corresponding (relative) minor/aeolian scale.
Comment: I think should be added to answer the title no.
Answer:
If I were to write a song in D minor, could I notate it correctly in F Aeolian?

I think you meant F Ionian or F major, and you mean the key signatures involved.
So, could a song in D minor, which would normally have a key signature of one flat, be written with a F Ionian/F major key signature of one flat? Yes, both key signatures use one flat.

Is D minor also F Aeolian?

Again, assuming you meant F Ionian: no, they are not the same.
They each have different tonics and modes.
D minor has a tonic of D and a mode of minor.
F Ionian has a tonic of F and a mode of Ionian (major.)
Additionally, the dominant seventh chord of each will be different.
D minor has a dominant of A7.
F major has a dominant of C7.
Keys are determined by tonic/dominant harmony, not key signatures.
Some types of modal music - like folk and Renaissance music - work in a similar way but may use other chords as a dominant such as ♭VII or iv rather than V. But the point still remains: the tonality (for lack of a better term, the modal "key") will be determined by the interaction of tonic and modal dominant chords.
One other point. You should understand and make clear whether you mean music that is actually in a minor key or a modal style of harmony in aeolian mode. Using "in minor" and "in aeolian" as interchangeable terms is wrong and confusing. It doesn't have immediate impact on your question, but it makes a jumble of the terminology and concepts of tonality. That could make it hard to understand your intentions if the topic is harmony and tonality.
Comment: "You should understand and make clear whether you mean music that is actually in a minor key or a modal style of harmony in aeolian mode." I'm pretty sure *the entire reason the question is being asked* is because OP didn't perceive those two things as being different.
Answer: No, D minor is the name of a key which is highly compatible with the D Aeolian scale.
"F Aeolian" is not a term which means "the Aeolian mode relative to F major". However, yes, D Aeolian is a mode of the F major scale, or F Ionian.
"F Aeolian" has the simplest possible meaning: the Aeolian mode starting on the F root note. Music emphasizing F Aeolian would be most likely be identified as being in the F minor key.
Answer: I think simple answer should be NO. D minor is also D aeolian which is not F aeolian.

Is D minor also F Aeolian?


Search, Threading and MySQL on android

Question: I'm trying to do a search from my database here is the code it keeps bringing the error below.The data is on a MySQL problem is it keeps crashing can somebody help me please.Here is my code.
public class Main extends MapActivity {
    /** Called when the activity is first created. */
    private Context ctx = this;
    private Context ctx2 = this;
    private ProgressDialog pd, pd2 = null;
    private Object data, data2 = null;private String url;private MapView myMap;
    private Connector http;

    static String searchy;
    String selection;
    // MapView mapView;
    List<Overlay> mapOverlays;
    Drawable drawable;
    Drawable drawable2;
    CustomItemizedOverlay<CustomOverlayItem> itemizedOverlay;
    CustomItemizedOverlay<CustomOverlayItem> itemizedOverlay2;

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        myMap = (MapView) findViewById(R.id.mapview);
        myMap.setBuiltInZoomControls(true);
        // addmarkers();
        // EditText searchInput = (EditText) findViewById(R.id.txtSearch);
        // final String searchitem = searchInput.getText().toString().trim();

        Button search = (Button) findViewById(R.id.searchBtn);
        search.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Log.i("MyApp", "Background thread starting");

                // pd = ProgressDialog.show(Main.this, "Working..",
                // "Downloading Data...", true, false);

                addmarkers();
            }
        });

    }

//adds the searched markers to the map
 public void addmarkers() {
        url = "http://10.0.2.2/therm/searchy.php";
        http = new Connector(ctx);
        http.connect(url, myMap);  }

//class connector that adds overlays and fetches from the database
       public class Connector {
            private Drawable marker;
        private GeoPoint point;
        private List<Overlay> mapOverlays;

        public Connector(Context ctx1) {
            ctx = ctx1;
            marker = ctx.getResources().getDrawable(R.drawable.default_marker);
            itemizedOverlay = new CustomItemizedOverlay<CustomOverlayItem>(
                    marker, myMap);
        }

        public void connect(String url, MapView myMap) {
            // TODO Auto-generated method stub
            InputStream is = null;
            // mapOverlays = myMap.getOverlays();
            // mapOverlays.clear();
            String result = null;
            int ct_id;
            String ct_name = null;
            // String[] ct_namey = null;
            String ct_add = null;
            String ct_lat;
            String ct_long;
            String imageURL;
            // the year data to send
            EditText txt_username = (EditText) findViewById(R.id.txtSearch);
            String woi = txt_username.getText().toString();
            Toast.makeText(getBaseContext(), woi, Toast.LENGTH_SHORT).show();

            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("searchy", woi));
            // http post
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

            } catch (Exception e) {
                Log.e("log_tag", "Error in http connection " + e.toString());
            }

            // convert response to string
            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                    Log.v("log_tag", "Line reads: " + line);

                }
                is.close();
                result = sb.toString();
            } catch (Exception e) {
                Log.e("log_tag", "Error converting result " + e.toString());
            }
            // parse json data
            try {
                JSONArray jArray = new JSONArray(result);
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    Log.i("log_tag","address: " + json_data.getString("address")

                    );
                    if (searchy.equals(json_data.getString("address"))) {
                        ct_id = json_data.getInt("id");
                        ct_name = json_data.getString("name");
                        // ct_namey[i] = json_data.getString("name");
                        ct_add = json_data.getString("address");
                        ct_lat = json_data.getString("lat");
                        ct_long = json_data.getString("lng");
                        imageURL = json_data.getString("imageUrl");

                        Double lon = (Double.parseDouble(ct_long));
                        Double lat = (Double.parseDouble(ct_lat));

                        point = new GeoPoint((int) (lat * 1E6),
                                (int) (lon * 1E6));

                        CustomOverlayItem overlayItem = new CustomOverlayItem(
                                point, ct_name, ct_add, imageURL);
                        itemizedOverlay.addOverlay(overlayItem);
                        mapOverlays.add(itemizedOverlay);
                        myMap.postInvalidate();

                    } else {
                        Toast.makeText(getBaseContext(),
                                "No such address is found", Toast.LENGTH_LONG)
                                .show();
                    }
                }

            } catch (JSONException e) {
                Log.e("log_tag", "Error parsing data " + e.toString());
            }
            return;
        }

    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }
}

// the .php file
    <?php
mysql_connect("localhost","root","");
mysql_select_db("hospitals");
$q=mysql_query("SELECT * FROM hosi WHERE address like '%".$_REQUEST['searchy']."%'");
    while($e=mysql_fetch_assoc($q))
        $output[]=$e;
print(json_encode($output));
mysql_close();?>

Here's the error I'm getting:
//error04-06 16:04:07.162: V/log_tag(10708): Line reads: [{"id":"1","name":"The Nairobi Hospital","address":"Upperhill","consult":"2000","phone":"+254202846000","desc":"The.... "}]
04-06 16:04:07.162: V/log_tag(10708): Line reads:
04-06 16:04:07.502: I/log_tag(10708): address: Upperhill
04-06 16:04:07.552: W/dalvikvm(10708): threadid=1: thread exiting with uncaught exception (group=0x400287f0)
04-06 16:04:07.572: E/AndroidRuntime(10708): FATAL EXCEPTION: main
04-06 16:04:07.572: E/AndroidRuntime(10708): java.lang.NullPointerException
04-06 16:04:07.572: E/AndroidRuntime(10708): at   com.realestatefinder.plotjson.Main$Connector.connect(Main.java:276)
04-06 16:04:07.572: E/AndroidRuntime(10708):    at com.realestatefinder.plotjson.Main$1.onClick(Main.java:86)
04-06 16:04:07.572: E/AndroidRuntime(10708):    at android.view.View.performClick(View.java:2408)
04-06 16:04:07.572: E/AndroidRuntime(10708):    at android.view.View$PerformClick.run(View.java:8816)
04-06 16:04:07.572: E/AndroidRuntime(10708):    at android.os.Handler.handleCallback(Handler.java:587)
04-06 16:04:07.572: E/AndroidRuntime(10708):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-06 16:04:07.572: E/AndroidRuntime(10708):    at android.os.Looper.loop(Looper.java:123)
04-06 16:04:07.572: E/AndroidRuntime(10708):    at android.app.ActivityThread.main(ActivityThread.java:4627)
04-06 16:04:07.572: E/AndroidRuntime(10708):    at java.lang.reflect.Method.invokeNative(Native Method)
04-06 16:04:07.572: E/AndroidRuntime(10708):    at java.lang.reflect.Method.invoke(Method.java:521)

Comment: What error are you getting.  Please edit your question and provide it.
Comment: Which line is 276 in `Main`?  Have you debugged this code to see which of the objects on that line are `null`?
Comment: i have updated the code please have a look at it
Comment: yes i have the error is on this line mapOverlays.add(itemizedOverlay);
Answer: Looks like you are getting a NPE because you've failed to initialize your mapOverlays collection.  You commented out the initialization:
 // mapOverlays = myMap.getOverlays();
 // mapOverlays.clear();

Your error shows:
java.lang.NullPointerException
at   com.realestatefinder.plotjson.Main$Connector.connect(Main.java:276)

and you said that line 276 is:
   mapOverlays.add(itemizedOverlay);

I think you learn how to use the Android debugger so you can trace this sort of code in the future.  Best of luck.

Search, Threading and MySQL on android


relative url path

Question: In my anchor tag I have hard coded like this <a href="/escorts'.my_link'", I want to get the relative url path. Whenever if the path is some like this in the url http://drupal.stackexchange.com/questions/ask and I clicked on the above mentioned link then instead of http://drupal.stackexchange.com/questions/ask/my_link it gives me escorts/my_link. I know I did not convey my question properly. Hope anybody get my scenerio. Thanx
Answer: I didn't fully understand your question. But I imagine two cases:

If you need a url that works in any page on your website, no matter where you are, you
need to use this code:
<?php
        global $base_url;
?>
       <a target="_blank" href="<?php print $base_url;?>/escorts'.my_link'"

On the other hand if you want to attach the url to the current address, use this code
<?php

        $path = current_path();
?>
       <a href="<?php print $path ;?>/escorts'.my_link'"

Comment: Thanku @Drupalist, I got the required url by using first method. But not locally it works but when I deploy it to other machine it is not clickable on the same window, I have to right click that item and open it in a new tab or window.As I am accessing using ``
Comment: I updated the answer and it opens the link another tab. just add `target="_blank"` to ``
Comment: Sorry @Drupalist, I did a mistake above. Locally it is working and links are opening in same window and in a new tab as well, this is right. But when I deployed it to other machine they are not clickable on the same window. I always have to open it in a new link or tab. I want to make working in a same window as well.
Comment: @nomeer it is about html `` tag,By specifying `target` you can determine how to open the new page. for more information visit http://www.w3schools.com/tags/att_a_target.asp
Answer: Just use the l function it will take care of everything for you, in your example use:
print l('Text', 'escorts/' . my_link);

Answer: Solution:
It will be like this
print l('Anchor text', 'my_link');

relative url path


Problem with enabling the Optimizing js files

Question: I have installed the events and signup modules. The events appears in a calender. All were working fine. But when I enabled the optimizing JS files on the performance page Now the events does not display for the anonymous and authentication user. Now they are only available for the administrator.
I again the disabled the optimizing JS files on performance page but still events are not displaying.
Can someone tell me what is the problem?
I am using drupal 6.
Comment: did any of MPD's suggestions give you more information you could share?
Comment: After enable JS optimization I check the status report there all things are fine, still don't know what is the problem?
Comment: What were the answers to the first two questions below, and specifically whether you can read the JS file when you do a view source?
Answer: Give AdvAgg a try. If JS Aggregation doesn't work, go to admin/reports/status and see what AdvAgg says; it has tests for just about every scenario that would cause JS optimizations to not work.
Answer: Is you sites/default/files directory writable by the webserver?
If you enable JS opt, view source, do you get valid output when you try to view the JS itself?
Does http://whatever/admin/reports/status list anything unusual?


Squeryl fails to reflect in debug mode only

Question: I can't debug (simple run works fine) my unit tests. Squeryl fails with the following exception:
<code>error while reflecting on metadata for (Some(private scala.Option
com.company.play.model.db.mapping.Position.orgUnit2id),Some(public scala.Option
com.company.play.model.db.mapping.Position.orgUnit2id()),None,Set(@org.squeryl.annotations.ColumnBase(optionType=class java.lang.Object, name=, length=-1, scale=-1, value=ORG_UNIT2ID))) of class com.company.play.model.db.mapping.Position

java.lang.RuntimeException: error while reflecting on metadata for (Some(private scala.Option com.company.play.model.db.mapping.Position.orgUnit2id),Some(public scala.Option com.company.play.model.db.mapping.Position.orgUnit2id()),None,Set(@org.squeryl.annotations.ColumnBase(optionType=class java.lang.Object, name=, length=-1, scale=-1, value=ORG_UNIT2ID))) of class com.company.play.model.db.mapping.Position
    at org.squeryl.internals.PosoMetaData$$anonfun$4.apply(PosoMetaData.scala:115)
    at org.squeryl.internals.PosoMetaData$$anonfun$4.apply(PosoMetaData.scala:80)
    at org.squeryl.internals.PosoMetaData.<init>(PosoMetaData.scala:80)
    at org.squeryl.View.<init>(View.scala:66)
    at org.squeryl.Table.<init>(Table.scala:29)
    at org.squeryl.Schema$class.table(Schema.scala:340)
    at com.******.play.model.db.mapping.DBLibrary$.table(DBLibrary.scala:5)
    ...
Caused by: scala.MatchError: null
    at org.squeryl.internals.FieldMetaData$$anon$1.build(FieldMetaData.scala:466)
    at org.squeryl.internals.PosoMetaData$$anonfun$4.apply(PosoMetaData.scala:112)
    ... 22 more
</code>
I debug using IntelliJ IDEA latest version (13.1.4). Running both in IDEA & in console (sbt clean compile test) works fine.
Comment: What version of Squeryl?  It's difficult to help without more information about the model it is failing on.  I use Intellij's debugging with Squeryl all the time without issue by the way.
Answer: Switching from jdk 1.8 to jdk 1.7 solved the issue.


Solving a PDE - do you have an idea?

Question:

Do you have an idea how to solve
    $$
v_{\xi\eta}=\frac{1}{2} v_{\xi}\cdot\xi?
$$

First I thought of using
$$
v_{\xi\eta}=v_{\eta\xi},
$$
substituting $z:=v_{\xi}$ and then getting
$$
\frac{dz}{d\eta}=\frac{1}{2}z\cdot\xi.
$$
First I thought that I can solve this by separation of variables, but it is not the needed form to do so...
Answer: \begin{align}
v_{\xi \eta} &= \frac 12 v_\xi \xi \\
\frac {v_{\xi \eta}}{v_\xi} &= \frac 12 \xi \\
\left( \ln v_\xi \right )_\eta &= \frac 12 \xi \\
\ln v_\xi &= \frac 12 \xi \eta + C_1(\xi) \\
v_\xi &= e^{C_1(\xi) + \frac 12 \xi \eta} \\
v &= \int e^{C_1(\xi) + \frac 12 \xi \eta} d\xi + C_2 (\eta)
\end{align}
Comment: @math12 $\exp(C_1 (\xi)) \ne C_2(\eta)$. $\xi$ and $\eta$ are two independent variables.
Comment: Okay, thats what I have. But I set $\exp(C_1(\xi))=:C_2(\xi)$, getting $v(\xi,\eta)=\int_a^{\xi}C_2(\tau)\exp(\frac{1}{2}\tau\eta)\, d\tau + C_3(\eta)$ where $a\in\Omega, C_2, C_3\in C^1(\Omega)$ are arbirtrary and $\Omega$ is the domain on which the PDE is valid.
Comment: Sorry I meant $C_2(\xi):=\exp(C_1(\xi))$.
Comment: @math12 Yes, you can do that, but you still need to integrate $C_1(\xi)$, so you cannot just say it's $\frac 2 \eta e^{\frac 12 \xi \eta}$ as you accepted as a right answer.
Answer: These ($v,z,\xi,\eta$) are scalars? (otherwise the pde is 'derivative of vector = scalar' which doesn't make sense)
In this case, the equation is separable, and the solution is $z = e^{\frac{1}{2}\xi\eta}$, and $v$ is then something like $\dfrac{2}{\eta}e^{\frac{1}{2}\xi\eta} + g(\eta)$.
EDIT: as kaster points out, I forgot to include a $C(\xi)$ term when taking the first anti-derivative. His answer gives the correct approach for solving this.
Comment: You forgot an arbitrary function $C(\xi)$ when integrated over $\eta$.
Comment: Yes, they are indeed scalars. Ah, separation of variables is possible when considering $\xi$ as a parameter and the ODE only in $\eta$?
Comment: Whoops, yes, you're correct. OP, you should consider kaster's solution the correct one.

Solving a PDE - do you have an idea?


How can I restrict users to some parents node with node hierarchy?

Question: I have the Node Hierarchy module on my Drupal installation, and I am using the following hierarchy:

Main Navigation (menu)

Art & Sciences

Art
Sciences

Economy

News

World wide
Other

What I want is that:

Stephanie can add/edit/delete content any content from "Art & Sciences" section
Stephanie can NOT add/edit/delete any content from other sections
John can add/edit/delete content any content from "Economy  " section
John can NOT add/edit/delete any content from other sections

I tried to install Workbench access; it creates me sections, but users can choose any node for parent, whatever the hierarchy.
Node Hierarchy obviously add nodes to the "Main navigation" menu as menu links. Despite of editors, everyone can add a node in every menu, but I want to restrict each user to their section. I can assign only the section I want to a node, but in the hierarchy it's not correct.
Is there any module (even if I have to use more than one) I can use to achieve what I want?
Comment: That would be a fair amount of code to write, very unlikely that anyone will do it all for you here. I suggest you post this as a feature request to the [Node Hierarchy issue queue](https://drupal.org/project/issues/nodehierarchy?categories=All)
Comment: Thanks, but I'm in a hurry, I can't wait I think. Maybe I will have to use taxonomy access control :-/
Comment: Sorry but this site doesn't exist because you can't wait to go through the proper channels - we don't provide a support forum or code-writing service here, please either add the code you're already using to the question, along with a full description of what parts aren't working, or submit this as a feature request to the Node Hierarchy Module. Thanks.
Comment: I'm sorry, I meant that I have to figure it out quickly, but with standard module, so I don't ask for code or whatever, just if a solution exists, because I thought it was very current to do what I want, but I couldn't find anything on the web.
I'll edit my question to be more specific.
Answer: I suggest you attach a taxonomy vocabulary to your content type and use the Taxonomy Access module.
So, create your vocabulary:

Arts & Science
Economy
News

Create roles based on taxonomy:

arts_role
economy_role
news_role

Assign permissions to roles:

Edit terms in Arts & Science to arts_role
Delete terms from Arts & Science to arts_role
Edit terms in Economy to economy_role
Delete terms from Economy to economy_role
Edit terms in News to news_role
Delete terms from News to news_role

Assign your users to your roles:

Stephanie gets arts_role
John gets economy_role
Comment: I know this way, but the problem is that I don't want the contributors to choose a parent node AND a taxonomy term. It's not user friendly...
Comment: it makes sense to me that the admin would define the user roles...
Answer: Have you evaluated Organic Groups for this use case? Maybe you can implement your sections as groups.
Users join groups/sections. Inside their group, they are allowed to add+edit (because nodes belong to this group they are in). But nodes outside of their group, they can only view.
The "main site" can display all group content to visitors.
OG basicaly categorizes your nodes into access categories.
Comment: Thanks, but it only helps me for one point. I also want to display menus items etc.
I found a solution, I'll post it soon!
Comment: OG offers solutions for many of the related challenges that will follow.

Menus, for example, can be turned into "category-specific menus" (a menu for "Art", a menu for "Sciences") using the og_menu module. (https://drupal.org/project/og_menu)

But a solution which you already have built, is better than every other suggestions that anybody tries to sell to you, I agree :)
Comment: I used OG for another project and I must tell it's great for this case.


What happens when 2 balls partially fall into a pocket and then get stuck?

Question: In a recent game of pool, my opponent hit a shot that resulted in 2 balls getting stuck in between a pocket's walls.  They were both still touching the table surface, while at the same time partially below the table surface (partially in the pocket).
Here is what happened:

What is the ruling in this situation?  Both balls pocketed?  Neither ball pocketed?
Answer: The Billiard Congress of America has a rule for a "jawed balls" situation:

3.33     JAWED BALLS
If two or more balls are locked between the jaws or sides of the pocket, with one or more suspended in air, the referee shall inspect the balls in position and follow this procedure: he shall visually (or physically if he desires) project each ball directly downward from its locked position; any ball that in his judgement would fall in the pocket if so moved directly downward is a pocketed ball, while any ball that would come to rest on the bed of the table is not pocketed. The balls are then placed according to the referee's assessment, and play continues according to specific game rules as if no locking or jawing of balls had occurred.

This rule says "one or more suspended in air" though, so it doesn't exactly match my situation where the balls are still touching the table.
The International Billiards Association has a rule for a "jammed balls" situation:

j) Jammed Balls:
It is possible for two or more balls to
become clustered in the jaws of a pocket  in such a way
that one or more of these balls would fall into the pocket
if the other balls were not preventing this. Any ball that
both players agree would otherwise fall into the pocket
should be placed in the pocket  before the next stroke.

Based on this rule, the situation I described should have resulted in both balls being pocketed, since the center of each ball was over the pocket and not the table surface.
Answer: Nothing special. The game progresses a usual ! I.e.

If you made the ball which you called and the pocket you get a shot otherwise the opponent takes the shot.
Comment: Could you provide a reference to the rules which supports this answer?
Comment: This does not answer the question, given that it is not clear whether a ball that is still touching the table and partially in the pocket should be considered "made".


Montar Query para ultimo registro NoSQL Google Datastore

Question: Estou trabalhando com o Datastore do Google e não estou conseguindo montar uma Query para retornar o que preciso.
Situação
Tenho uma Entity, com par de chave {"item": codItem, "item": id}, ainda dentro dessa Entity tenho a propriedade codCliente.
Para exemplificar poderíamos ter um JSON assim sendo salvo (id é o campo do registro que google gera):

[
  {"id":2137847312334,"codItem":12,"codCliente":1,"dataRegistro":2017-04-23T18:25:43.511Z},
  {"id":2183462352427,"codItem":15,"codCliente":1,"dataRegistro":2017-04-23T18:25:43.511Z},
  {"id":9128734678236,"codItem":10,"codCliente":1,"dataRegistro":2017-04-23T18:25:43.511Z},

  {"id":2137847312334,"codItem":12,"codCliente":1,"dataRegistro":2017-03-20T18:25:43.511Z},
  {"id":2183462352427,"codItem":15,"codCliente":1,"dataRegistro":2017-03-20T18:25:43.511Z},
  {"id":9128734678236,"codItem":10,"codCliente":1,"dataRegistro":2017-03-20T18:25:43.511Z}
]

Problema
Quando eu monto a query para fazer a busca desses resultados filtrando por cliente, com o codCliente eu ainda não tenho a informação de quais os codItem que ele tem.
E o que eu preciso é uma forma de apenas buscar um (apenas um) resultado de cada codItem do codCliente referenciado com a dataRegistro mais nova. Desta forma com o exemplo acima eu deveria ter de retorno os três primeiros registros do JSON.
Estou aberto a mudanças de estrutura  e chaves do documento json. Única coisa que não há como mudar é sobre ter a informação de quais codItem o cliente tem antes de fazer a consulta. Alguma ideia?
Answer: Resolvi da seguinte forma:

Uma query que retorna apenas os códigos dos itens filtrando pelo codCliente, usando as funções do google cloud Projection e DistinctOn
Uma segunda query que retorna apenas um registro, usando FetchOptions.Builder.withLimit(1), filtrados pelo codItem e codCliente ordenado pela data

Query para buscar apenas o codItem:
public QueryResults<ProjectionEntity> getItem(int codCliente) {

   Query<ProjectionEntity> query2 = Query
    .newProjectionEntityQueryBuilder()
    .setKind("Item")
    .setProjection("CodItem")
    .setDistinctOn("CodItem")
    .setFilter(PropertyFilter.eq("codCliente", codCliente))
    .build();

  QueryResults<ProjectionEntity> tasks = getDatastore().run(query2);
  return tasks;

}


Importing another project in IntelliJ IDEA's buildpath/module?

Question: I've been using Eclipse for awhile but I looking to possibly switch to IDEA. Eclipse has been a workhorse but its bugginess is driving me crazy.
My setup in Eclipse usually involves 2-3 projects being open, and one project being in the buildpath of the two other projects to serve as a library. How do I make this happen in Intellij? I think I'm supposed to create modules but it this is coming very counter-intuitively to me.
Answer: It's a little bit different in IDEA.
Here's a link that'll help you understand:
https://www.jetbrains.com/idea/help/intellij-idea-vs-eclipse-terminology.html
Basically in IDEA project is a number of modules like workspace in eclipse.
So you need to add modules to your project and in the module settings(<F4>) add a module dependency.


Vim: inoremap works in buffer, not in .vimrc

Question: I'm really eager to include the following in my .vimrc file:
inoremap <Tab> <C-x><C-u>

If I set it within a buffer (via :inoremap <Tab> <C-x><C-u>) it works exactly as I'd hoped.
But, if I place it in my .vimrc, it doesn't seem to be acknowledged at all.
I've attached my .vimrc below. A few things:

Other changes to the .vimrc file are picked up, so it's not the wrong file
Have tried adding at the very bottom of the .vimrc & still doesn't work, so it's not being overwritten

Any ideas appreciated. Many thanks.
" When started as "evim", evim.vim will already have done these settings.
if v:progname =~? "evim"
  finish
endif

" Word complete
" :autocmd BufEnter * call DoWordComplete()
" let g:WC_min_len = 4

" Use Vim settings, rather than Vi settings (much better!).
" This must be first, because it changes other options as a side effect.
set nocompatible
map j gj
map k gk

set showmatch " Show matching brackets
set mat=5 " Bracket blinking
set noerrorbells " No noise

" Ruby autocomplete

" Autocomplete behaviour
set completeopt=longest,menuone
open omni completion menu closing previous if open and opening new menu without changing the text
inoremap <expr> <C-Space> (pumvisible() ? (col('.') > 1 ? '<Esc>i<Right>' : '<Esc>i') : '') .
            \ '<C-x><C-o><C-r>=pumvisible() ? "\<lt>C-n>\<lt>C-p>\<lt>Down>" : ""<CR>'
" open user completion menu closing previous if open and opening new menu without changing the text
inoremap <expr> <S-Space> (pumvisible() ? (col('.') > 1 ? '<Esc>i<Right>' : '<Esc>i') : '') .
            \ '<C-x><C-u><C-r>=pumvisible() ? "\<lt>C-n>\<lt>C-p>\<lt>Down>" : ""<CR>'

autocmd FileType ruby,eruby set omnifunc=rubycomplete#Complete
autocmd FileType ruby,eruby let g:rubycomplete_buffer_loading = 1
autocmd FileType ruby,eruby let g:rubycomplete_rails = 1
autocmd FileType ruby,eruby let g:rubycomplete_classes_in_global = 1
" highlight Pmenu ctermbg=238 gui=bold "improve autocomplete menu color

" Colours
highlight Pmenu ctermfg=6 ctermbg=238 guibg=grey30

" allow backspacing over everything in insert mode
set backspace=indent,eol,start

" if has("vms")
"   set nobackup        " do not keep a backup file, use versions instead
" else
"   set backup      " keep a backup file
" endif

" Set backupdir to tmp
" Do not let vim create <filename>~ backup files
set nobackup
" set nowritebackup

set history=50      " keep 50 lines of command line history
set ruler       " show the cursor position all the time
set showcmd     " display incomplete commands
set incsearch       " do incremental searching

" Set tab to 2 spaces
set ts=2
set shiftwidth=2

" Ignore case
set ignorecase
set smartcase

" Menu autocomplete
set wildmode=longest,list
set wildmenu

" Call pathogen
call pathogen#infect()

" For Win32 GUI: remove 't' flag from 'guioptions': no tearoff menu entries
" let &guioptions = substitute(&guioptions, "t", "", "g")

" Don't use Ex mode, use Q for formatting
map Q gq

" CTRL-U in insert mode deletes a lot.  Use CTRL-G u to first break undo,
" so that you can undo CTRL-U after inserting a line break.
inoremap <C-U> <C-G>u<C-U>

" In many terminal emulators the mouse works just fine, thus enable it.
if has('mouse')
  set mouse=a
endif

" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
  syntax on
  set hlsearch
endif

" Turn syntax highlighting on (Added by John Bayne, 18/08/2012)
syntax on

" Only do this part when compiled with support for autocommands.
if has("autocmd")

  " Enable file type detection.
  " Use the default filetype settings, so that mail gets 'tw' set to 72,
  " 'cindent' is on in C files, etc.
  " Also load indent files, to automatically do language-dependent indenting.
  filetype plugin indent on

  " Put these in an autocmd group, so that we can delete them easily.
  augroup vimrcEx
  au!

  " For all text files set 'textwidth' to 78 characters.
  autocmd FileType text setlocal textwidth=78

  " When editing a file, always jump to the last known cursor position.
  " Don't do it when the position is invalid or when inside an event handler
  " (happens when dropping a file on gvim).
  " Also don't do it when the mark is in the first line, that is the default
  " position when opening a file.
  autocmd BufReadPost *
    \ if line("'\"") > 1 && line("'\"") <= line("$") |
    \   exe "normal! g`\"" |
    \ endif

  augroup END

else

  set autoindent        " always set autoindenting on

endif " has("autocmd")

" Convenient command to see the difference between the current buffer and the
" file it was loaded from, thus the changes you made.
" Only define it when not defined already.
if !exists(":DiffOrig")
  command DiffOrig vert new | set bt=nofile | r ++edit # | 0d_ | diffthis
          \ | wincmd p | diffthis
endif

" My customisations
" No backup files
set nobackup
set nowritebackup
set noswapfile

" Whitespace identifier
:highlight ExtraWhitespace ctermbg=darkgreen guibg=lightgreen
:match ExtraWhitespace /\s\+$/

" Colour options
" color codeschool
" set guifont=Monaco:h12
" let g:NERDTreeWinPos = "right"
" set guioptions-=T " Removes top toolbar
" set guioptions-=r " Removes right hand scroll bar
" set go-=L " Removes left hand scroll bar
" autocmd User Rails let b:surround_{char2nr('-')} = "<% \r %>" " displays <% %> correctly
" :set cpoptions+=$ " puts a $ marker for the end of words/lines in cw/c$ commands

" Tab behaviour for ultisnips
let g:UltiSnipsExpandTrigger="<tab>"
let g:UltiSnipsJumpForwardTrigger="<tab>"
let g:UltiSnipsJumpBackwardTrigger="<s-tab>"

inoremap <Tab> <C-x><C-u>

Answer: In this case, :scriptnames, while useful, is not the best way to see where a mapping was last set.
:verbose map <tab>

is a lot more precise.
Comment: Every time I answer a _Vi_ question, I basically assume that somebody will come along with a better answer real soon.  Thanks!
Comment: That's the main reason I'm hanging around here, actually. The points or whatever they are called are not as valuable as all the stuff I'm learning from trying to answer, reading other people's answers. And getting my butt kicked by ZyX.
Comment: This might be obvious, but you can also use `:verbose imap`, and `:verbose inoremap`, etc. That's what I needed!
Comment: This comment is exactly what I needed to figure out why my `` and `` imappings weren't working. It showed that another plugin, `vim-latex`, was overriding those keys.
Answer: Maybe another script is overwriting it after your .vimrc is read.
You can use :scriptnames to see what files are read on startup.
Comment: Many thanks - I didn't know about :scriptnames. Adding it to the end of the last called script works. ...Now I just need to narrow it down to where the overwrite is occurring
Comment: In case anyone runs into the same thing: It was the UltiSnips plugin
Comment: @PlankTon - Thanks for asking the question... I didn't know about `:scriptnames` either until just now!  I think it would have saved me a bunch of time in the past.


Remove drag table in field collection module drupal 7

Question: Hihi. Hi all. I have a content type and in which I created a collection field using field collection module. I set the value for the field collection that is unlimited. In field collection including some certain fields. Then I proceeded to create content for this content type. I discovered that the field collection module enables drag row and show weight of the current row. Now I want to remove drag and drop function and the weight of that row without knowing how processing. Expect people to help me handle this problem. Thank all.
Answer: To removing ajax dag and drop table widget for multiple value field you need use "hook_theme_registry_alter" to override theme registry function. Here you can find all information regarding your question.


Finding perimeter when the hypotenuse is 1 and is the sum of the altitude and side of a triangle

Question: Let us say the hypotenuse of a triangle is 1, which is also equal to the sum of side $a$ and the altitude $h$ when taking the hypotenuse as the base. How would I find the length of side $a$ and $b$ (the other side), and thus the triangle's perimeter?
I've tried making a triangle inscribed in a circle, where the hypotenuse is the diameter of the circle so it's right-angled, and making $a$ and $b$ chords. But it leads nowhere for me. Also tried using the geometric mean theorem. I split the hypotenuse into two lengths, $p$ and $q$, where $$h^2+q^2=a^2$$ Then I defined $h=pq$ based on the theorem, which can be rewritten as $h=(1-q)q=q-q^2$. Therefore$$(q-q^2)^2+q^2=a^2\\q^4-2q^3+2q^2=a^2\\\sqrt{q^4-2q^3+2q^2}=a$$ And because $a+h=1$, we can replace them with what we derived $$\sqrt{q^4-2q^3+2q^2}+q-q^2=1\\(\sqrt{q^4-2q^3+2q^2})^2=(q^2-q+1)^2\\q^4-2q^3+2q^2=q^4-2q^3+3q^2-2q+1\\q^2-2q+1=0\\(q-1)^2,\;q=1$$ I've gone wrong somewhere but I don't know where, and I also have no idea how to solve this problem. I don't think any angle related formulas like Law of Sines or Law of Cosines would help as I also don't know how to find any angles.
Answer: You made a mistake with $h=pq$, which should be $h^2=qp=q(1-q)$. Then, you have
$$q^2+q(1-q) = a^2$$
which leads to
$$q =a^2=\left(1-\sqrt{q(1-q)}\right)^2$$
Then, you could solve for $q$.
Answer: From given, $a+h = 1$ and $a^2 + b^2 = 1$.
From similar triangles inside the right-angled triangle,
$$\begin{align*}\frac b1 &= \frac ha\\
ab &= h\\
a+ab &= 1\\
b &= \frac{1-a}{a}\\
a^2 + \left(\frac{1-a}{a}\right)^2 &= 1\\
a^4 + 1 - 2a + a^2 &= a^2\\
a^4 - 2a + 1 &= 0\\
(a-1)(a^3 +a^2+a-1)&=0
\end{align*}$$
There is one real root where $0<a<1$:
$$a\approx 0.543689012692076$$
Answer: You have three equations relating $a$, $b$, and $h$:
$$\begin{align}
a+h&=1\\a^2+b^2&=1^2\\ab&=1\cdot h
\end{align}$$
The first one is given, the second is Pythagoras' theorem, the third one is the area of the triangle.
$$\begin{align}h&=1-a\\b&=\frac ha=\frac{1-a}{a}\\b&=\sqrt{1-a^2}\end{align}$$
This yields $$a^3+a^2+a-1=0$$
You can solve this numerically or use the cubic equation formalism. You will get $$a\approx 0.54369$$The perimeter is $$p=a+b+1=a+\frac 1a-1+1=a+\frac 1a\approx 2.382973$$
Answer: The area of the triangle is $\frac{1}{2}\times 1\times h$ (considering hypotenus as base). And is also $\frac{1}{2}\times a\times b$. Thus $ab=h$ and $a^2+b^2=1$. Therefore $a+b=\sqrt{a^2+b^2+2ab}$. Thus $a+b+1=1+\sqrt{1+2h}$ is the perimeter. Hope its correct.
Comment: It's incomplete. You should get rid of $h$ as well. You know $a+h=1$
Comment: I though $h$ was given. My bad.


Classe não registrada - Imagelist

Question: Ao personalizar a minha imagelist e listview aparece o seguinte erro:

Classe não Registrada. Procurando Objeto com CLSID:{7EBDAAE0-8120-11CF-899F-00AA00688B10}

Acredito que seja porque meu Office é 64bits, alguém com Office 64 bits já conseguiu contornar uma situação semelhante?
Answer: Pelo que pesquisei dizem que é necessário registar o

Msstkprp.dll file.

Vê algumas dicas neste link http://www.visualbasicsource.net/KnowledgeBase/q188331.txt

Classe não registrada - Imagelist