'OpenFileDialog' doesn't take the value at the first time

Question: When selecting a .dll file and press OK, the browsing dialog close and reopen. after it opens again and pressing OK, it take the values without any problem.
this is my code
private void btnBrowse_Click(object sender, EventArgs e) {
            OpenFileDialog dllDialog = new OpenFileDialog();
            dllDialog.Filter = "DLL Files|*.dll";
            dllDialog.InitialDirectory = @"C:\";
            dllDialog.Title = "Please select .dll file.";
            if (dllDialog.ShowDialog() == DialogResult.OK) {
                dllDialog.ShowDialog();
                tbRepTempLibrary.Text = dllDialog.FileName;

            } else {
                MessageBox.Show("error");
            }
        }

Comment: You call `ShowDialog()` twice - what did you expect to happen?
Comment: Are you concerned about that the first time only the FileName is displayed and the second time the FullFileName (including path) ?
Answer: you should not call dllDialog.ShowDialog() twice, use this instead:
if (dllDialog.ShowDialog() == DialogResult.OK)
{
  tbRepTempLibrary.Text = dllDialog.FileName;
}

and if the user click cancel because does not want to select a file you should not show error, it is the user's right to cancel without opening or selecting a file, you simply will not continue with the operation started ;-)
Answer: You're calling ShowDialog() twice. You should just do this:
private void btnBrowse_Click(object sender, EventArgs e) {
        OpenFileDialog dllDialog = new OpenFileDialog();
        dllDialog.Filter = "DLL Files|*.dll";
        dllDialog.InitialDirectory = @"C:\";
        dllDialog.Title = "Please select .dll file.";
        if (dllDialog.ShowDialog() == DialogResult.OK) {
            tbRepTempLibrary.Text = dllDialog.FileName;

        } else {
            MessageBox.Show("error");
        }
    }

Answer: you are calling ShowDialog() twice. You should remove the second one,
private void btnBrowse_Click(object sender, EventArgs e)
{
    OpenFileDialog dllDialog = new OpenFileDialog();
    dllDialog.Filter = "DLL Files|*.dll";
    dllDialog.InitialDirectory = @"C:\";
    dllDialog.Title = "Please select .dll file.";
    if (dllDialog.ShowDialog() == DialogResult.OK)
    {
        tbRepTempLibrary.Text = dllDialog.FileName;

    } else
    {
        MessageBox.Show("error");
    }
}

Answer:  if (dllDialog.ShowDialog() == DialogResult.OK) {
            dllDialog.ShowDialog(); // This shouldn't be here

You show the dialog twice.


Update the database with new values after a migration

Question: I have a table in my database called sessions with two columns (start_time and end_time) in it and I already have lots of data in my table. I then generated a migration:
$ rails g migration AddDurationToSessions duration:integer

My model session.rb looks like this:
class Session < ActiveRecord::Base
   before_save :calc_duration

   def calc_duration
     return self[:end_time] - self[:start_time]
   end
end

My question is: how do I apply calc_duration to all of my older elements in my table? Do I update them manually or is there a best practice for this?
Answer: You can do it in migration:
class AddDurationToSessions < ActiveRecord::Migration
  def change
    add_column :sessions, :duration, :integer

    # Find and update all older session record
    Session.find_each do |s|
      # new duration
      calc_duration = s.end_time - s.start_time
      # update session with new duration
      s.update(duration: calc_duration.to_i)
    end

  end
end

Comment: After coding in Rails for more than a year, I've learned not yo use class methods in migrations, but SQL statements instead. The reason for this is because methods can change (after the migration was executed), thus make the migration unusable. Also read [this](http://jacopretorius.net/2014/07/patterns-for-data-migrations-in-rails.html).


How to write advance complex SQL Query for below data?

Question: How to write a complex SQL Query?
Below information is the old data of users working on different services with service status and last change date on particular Service_Area and Service_Sector.
All users are working on multiple services where some of the services are still active for a particular Service_Area and Service_Sector.
Requirements in words:
I require to select all columns when the Service of the user is inactive and only record on that particular Service_Area and Service_Sector of that user.
As earlier mentioned that a user can have multiple services on a Service_Area and Service_Sector combined. In case if there are more than one services on Service_Area and Service_Sector for the user, then we need to select the record that was last changed if all the services are inactive (I mean, when there is a record in between whose service status is active, then we cant select any user data from that Service_Area and Service_Sector of that user).
Scenarios:
Case 1:
When there are 5-services, all of them are inactive then, we need to select the last changed record.
Case 2:
When there is at least one service with active status among 5-services then, we cant select that user data from that particular Service_Area and Service_Sector of that user.
Case 3
When there is only one service on that Service_Area and Service_Sector of that user, it's inactive then, the record will also get selected.
About Table:
Location_Code, User_Id, Service_Area, Service_Sector, Service will always make a unique combination. And there may be many services on this combination Location_Code, User_Id, Service_Area, Service_Sector.
Please find the sample table below with the result table (display expected output).
Sample Table:

Loc_Code
User_Id
Service_Area
Service_Sector
Service
Status
Last_Changed

101
1001
C
1
PAINT
INACTIVE
11/28/2020

101
1002
A
1
WOOD
INACTIVE
12/7/2020

101
1002
A
1
CLEANING
ACTIVE
11/23/2020

101
1002
A
1
PEST
INACTIVE
12/7/2020

101
1002
A
2
LIGHT
INACTIVE
12/7/2020
`

101
1002
B
2
AC
INACTIVE
11/28/2020

101
1002
B
2
HEATER
INACTIVE
11/30/2020

Result Table:
Total 3-records are selected.

The first record is selected as the user was working on a single inactive service on a particular Service_Area and Service_Sector.
The second record is selected because Location_Code, User_Id, Service_Area, Service_Sector combination has only one service on it, which is inactive.
The third record selected because Location_Code, User_Id, Service_Area, Service_Sector combination list 2-inactive services, selected the service which was last changed.

Loc_Code
User_Id
Service_Area
Service_Sector
Service
Status
Last_Changed

101
1001
c
1
PAINT
INACTIVE
11/28/2020

101
1002
A
2
LIGHT
INACTIVE
12/7/2020

101
1002
B
2
HEATER
INACTIVE
11/30/2020
Comment: Welcome, to improve your experience on SO please read [how to ask](https://stackoverflow.com/help/how-to-ask),
an [On Topic question](https://stackoverflow.com/help/on-topic), then look at the
[Question Check list](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist),
the [perfect question](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/),
how to create a [Minimal, Complete and Verifiable Example](http://stackoverflow.com/help/mcve) and [take the tour](http://stackoverflow.com/tour)
Answer: SQL | WITH clause
Last Updated: 05-09-2019
The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database. The SQL WITH clause allows you to give a sub-query block a name (a process also called sub-query refactoring), which can be referenced in several places within the main SQL query.

The clause is used for defining a temporary relation such that the output of this temporary relation is available and is used by the query that is associated with the WITH clause.
Queries that have an associated WITH clause can also be written using nested sub-queries but doing so add more complexity to read/debug the SQL query.
WITH clause is not supported by all database system.
The name assigned to the sub-query is treated as though it was an inline view or table
The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database.
Syntax:

WITH temporaryTable (averageValue) as
    (SELECT avg(Attr1)
    FROM Table),
    SELECT Attr1
    FROM Table
    WHERE Table.Attr1 > temporaryTable.averageValue;

In this query, WITH clause is used to define a temporary relation temporaryTable that has only 1 attribute average value. averageValue holds the average value of column Attr1 described in relation Table. The SELECT statement that follows the WITH clause will produce only those tuples where the value of Attr1 in relation Table is greater than the average value obtained from the WITH clause statement.

Note: When a query with a WITH clause is executed, first the query mentioned within the  clause is evaluated and the output of this evaluation is stored in a temporary relation. Following this, the main query associated with the WITH clause is finally executed that would use the temporary relation produced.

Queries

Example 1:  Find all the employee whose salary is more than the average salary of all employees.
Name of the relation: Employee

EMPLOYEEID  NAME    SALARY
100011  Smith       50000
100022  Bill        94000
100027  Sam         70550
100845  Walden      80000
115585  Erik        60000
1100070 Kate        69000

SQL Query:

WITH temporaryTable(averageValue) as
    (SELECT avg(Salary)
    from Employee),
        SELECT EmployeeID,Name, Salary
        FROM Employee, temporaryTable
        WHERE Employee.Salary > temporaryTable.averageValue;
Output:

EMPLOYEEID  NAME    SALARY
100022  Bill        94000
100845  Walden      80000
Explanation: The average salary of all employees is 70591. Therefore, all employees whose salary is more than the obtained average lies in the output relation.

Comment: I tried the above scenario earlier but WITH clause is not supported as I am working on as400 system.
Answer: Test
WITH cte AS ( SELECT *,
                     !SUM(status != 'INACTIVE') OVER (PARTITION BY loc_code, user_id, service_area, service_sector) only_inactive,
                     ROW_NUMBER() OVER (PARTITION BY loc_code, user_id, service_area, service_sector ORDER BY last_changed DESC) rn
              FROM test )

SELECT *
FROM cte
WHERE only_inactive
  AND rn = 1

fiddle

how this query is working?

WITH is a clause which creates... think that this is a subquery.
What I do in it? I calculate 2 additional columns.  Both uses window functions - it is similar to aggregate function, but with its own grouping and ordering.
First summarises the result of checking does a column not contain specified value. For 'INACTIVE' the checking result is FALSE which is treated as zero, for all another it is TRUE and 1 respectively. So if none 'INACTIVE' in this group the sum is zero, and above zero if at least one another value meet. NOT inverts this result.
Second enumerates rows in a group by specified ordering.
In outer query I simply select rows which have non-zero checking result (i.e. the rows from groups which have no another statuses than 'INACTIVE'), and from these rows only the row which number is 1 (taking into account the ordering - the most recent row).
That's all.
Comment: Hi Akina. Thank you. It worked for me but can you please help me how this query is working?
Comment: @user14788075 Some explanations added.


Why does music sound slightly sharper when played through headphones?

Question: Why does my music appear to very slightly rise in pitch when I switch from computer speakers to computer headphones (cheap foam, mic boom integrated)?
Ideas:

Might this be due to a pressure change on my eardrum as another poster noticed when he yawns?
Maybe my headphones actually change the frequency of the output?  I can't picture how that would work...
Maybe I'm perceiving the doppler shift as I move the speaker toward my ear, and I'm distracted from the reverse shift by the mechanics of putting the earphones in place?
Comment: Re: 1. I once had an ear infection that had me hearing left & right at about ¼ tone apart, for a week. I wouldn't have believed it possible if I hadn't experienced it.
Comment: It's a known thing, apparently: http://www.healthyhearing.com/report/51055-Understanding-diplacusis  Very weird!  Probably unrelated to this question, though.
Answer: Most likely you are either imagining the pitch change or you are unusually sensitive to pitch, which is a subjective interpretation that is also dependent on volume. So you might try turning down the volume when you switch to headphones.
You might also or instead hearing a change in frequency balance and interpreting it as a slight pitch change. All speaker and headphone systems have different frequencies they emphasize, so you will hear a difference any time you change your playback system.
Answer: Well, I used to mix with closed-cup headphones, and I did notice after extended wearing that all the pitches seem to have gone sharp, compared to when I checked the mix without them afterwards.
Makes sense since warmer air is less dense, I guess.
I switched to open-cup headphones last year, and the side-effect has lessened a lot.  I can keep them on for over 30 min. at a time w/o pitch-shifts.  I was surprised how quickly the air inside headphones heat up once you put 'em on, but what do I know!


Render comment parts individually with Panels/Page manager?

Question: Is there any way to create panels template for comments (comments attached to node). So far I've only found that "Node comments" thing under the node tab (Variants -> content) which outputs default comments and Mini panels block which renders only one comment from random node.
I'm trying replace forum node template with panels and render node and comments with same layout.
Thanks.
Comment: I dont have the time to figure out the details at the moment, but it is definitely possible. I don't understand "renders default comments", and I _very_ much doubt there is a Panels provided pane that renders _random_ content.
Comment: With default comments output I meant the same as `print render($content['comments']);` in node.tpl.php and with that "Mini panels" thing I meant Mini panels block with the following settings: http://i.imgur.com/rPSiE.jpg which obviously doesn't work because it has no relation to that node we are viewing.
Comment: I must be missunderstanding still, how is `$content['comments']` not what you need? You can add the relation to the minipanel, and it will output the same thing.
Comment: I've never used panels before, so that might really be what I need but I just don't know it yet.

The thing I'm trying to do is: replace comment with same panels layout I'm using to view nodes (show comment fields to be more precise). That `$content['comments']` outputs comments exactly same way the theme does and that should be replaced with mini panels or anything that let me put each comment field where I want to. Ie. comment title to the top and username to the left and comment body to the left etc.
Comment: Ah, I see. There's no out of the box solution for that. Nodes are a special case as they have been the most used element. Historically, one had to write a great deal of element specific code. In D7 it should be possible to generalize this to any entity, but I don't believe that has been done.
Answer: There's no out of the box solution for doing this today.
If you look at a file like ctools/plugins/content_types/node_context/node_links.inc you'll see how it's done for nodes and their links. The other files in the same directory do the same but to different pieces of nodes. For historic reasons, there's a lot of Node specific content in there.
Today it should be possible to generalize the same approach onto all entities, but as far as I know, that hasn't happened anywhere.


Variance of sample moments - clarification on Serfling (1980)

Question: In "Serfling, R. J. (1980). Approximation theorems of mathematical statistics", we read

In Theorem A, as one suspects, $k=1,2,...$, indicating the integer-moments, while $n$ is the sample size. As regards the $m_k$ and $\mu_k$ symbols, we have, drawing i.i.d from the distribution of some random variable $X$,
$$m_k = \frac 1n \sum_{i=1}^n (X_i-\bar X)^k, \;\;\;\mu_k = E[(X-E(X)]^k$$
Theorem A is concerned with each separate central sample moment, Theorem B is concerned with their joint limiting distribution.
Suppose that $k=3$. Then, from Theorem A we have
$$\text{AVar}(m_3) = \mu_6 - \mu_3^2 - 6\mu_2\mu_4 + 9\mu_2^3$$
But from Theorem B, setting $i=j=3$ we get
$$\text{AVar}(m_3) = \mu_8 - \mu_4^2 - 8\mu_3\mu_5 + 16\mu_3^2\mu_2$$
I don't see how the two can coincide, and some quick simulated checks show that they don't.
Question:is it possible that the expression in Theorem B is meant only for the off-diagonal covariance terms and not for the diagonal variance terms?
The author makes no such clarification.
Answer: Posting questions on CV has this magic effect many times: a little after you post them, you find the answer.
ANSWER: both expressions are correct, and the expression in Theorem B holds also for the diagonal variance terms. The catch?
...In the variance-covariance matrix expression, we realize that the numbering of the variables starts from $2$, while the $i,j$ indices start from $1$.
This means that when we want to obtain the variance of $m_3$ we must set $i=j=2$, and when we want to obtain, say, the covariance of $(m_3, m_4)$, we must set $i=2, j=3$.
In general, for $k,\ell$ moments, set $i=k-1, j=\ell-1$ in the variance-covariance expression.
Comment: Re "must notice:" you don't seem to have supplied enough information to enable your readers to notice anything like that.
Comment: @whuber The information is all in the statement of Theorem B: the 1st variable is $m_2$, not $m_1$, and no explicit numbering is given for the $i,j$ -in which case, one starts the counting from $1,...$. Strictly speaking, Serfling wrote everything correctly, but he should have anticipated the possible confusion here.
Comment: The principal problem is that in Theorem A, the meanings of the symbols--and especially the indexing conventions--are impossible to deduce from its mere statement.
Comment: @whuber But immediately after the two theorems, I explicitly write what $m_k$ and what $\mu_k$ is, so I don't understand where the problem is.
Comment: I still cannot see *anything* in your post that gives any clue to the indexing convention in Theorem A.


ADB via Wi-Fi desconecta quando ligo acessório USB

Question: Estou a utilizar o ADB através de Wi-Fi para poder trabalhar com acessórios USB (Android Open Accessory). Para alguns testes é necessário desligar e voltar a ligar o cabo USB ao telemóvel. Sempre que ligo o acessório USB ao telemóvel, o ADB desliga-se e tenho de voltar a ligar o ADB; isto apesar de estar conectado ao ADB através de Wi-Fi e não cabo.
O comando utilizado é <code>$ adb connect 184.108.40.206:5555; adb -s 184.108.40.206:5555 logcat -v threadtime MinhaApp:V *:S</code>.
Como fazer com que o ADB, ligado via Wi-Fi, não se desligue ao conectar/desconectar acessórios USB?
Comment: Porque é que a pergunta não se encaixa no tema do site se Android+AOA é desenvolvimento de software?
Comment: Concordo com você, acho que a pergunta pode sim fazer parte do escopo. Votei para reabrir, assim pelo menos pode ser que alguém deixe uma opinião do por quê ela não deve ser reaberta, que no momento não consigo ver.
Comment: @Daniel Bem-vindo ao [pt.so]! Creio que a pergunta foi fechada porque alguns usuários confundiram sua pergunta com um pedido de suporte técnico do tipo "meu aparelho está com defeito".
Answer: isso acontece por que quando você conectar o cabo USB, o device ira detectar novamente o USB e ativalo como porta de entrada do adb automaticamente. para isso nao acontecer você precisa forçar o device a utilizar TCP/IP, mas para isso o device precisar ter acesso root. Você pode criar seu proprio script ou pode utilizar algum app já pronto para isso.
how-can-i-connect-to-android-with-adb-over-tcp
Espero ter ajudado


t-sne embedding to medium-dimensions (e.g. 100 dimensions)?

Question: I am using t-sne on 252 dimensional data to embed to lower-dimensions. I am curious to know if it is academically justifiable to embed it into medium dimensions such as 100 dimensions, or 80 dimensions, instead of 2 dimensions.
I have read many examples of t-sne that embeds high-dimensional data to 2 dimensions for plotting. However, I haven't seen much examples of embedding data from 252 dimensions to 100 dimensions.
Can we academically justify embedding to medium-dimensions(e.g. 100 dimensions) using t-sne?
Answer: Here's an idea I am currently pursuing. I have large biological data sets (in about 20,000 dimensions, one for each gene). The mental model is that the actual data lives on (or at least near) a manifold of dimension smaller than 20,000. There are some existing mathematical/statistical tools to try to compute the "local dimension" of that manifold near any data point. (See Ellis and McDermott, Computational Statistics & Data Analysis, Volume 17, Issue 3, March 1994, Pages 317-326.) These frequently give local estimates in the range of 20-30 or more dimensions. In that case, we know that shrinking things down to 2 dimensions will destroy some (possibly all) of the topological structure of the manifold.
By the Whitney Embedding Theorem, we can embed any N-dimensional real manifold into 2N-dimensional Euclidean space. So, there must exist a way to put those 20-30 dimensional data manifolds into 40-60 dimensional space.
So, there's your potential mathematical justification. In practice, finding such an embedding may be an open problem. I found your question because I was searching for an implementation of either t-SNE or UMAP that would reduce from large dimensions down to moderate dimensions. (The existing implementations, at least in R, seem to only believe in 2 or 3 for visualization purposes.)
In my case, I can easily reduce from 20,000 dimensions to M-dimensions, where M is the number of samples. (Just use principal components analysis, and that is the maximum number of components you can get.) It's not clear what happoens when you take fewer PCs, since explainng less variance may fail to be an embedding of the data manifold.
Answer: WHY?
A troubling point with t-SNE is that it does not give a functional relationship between the high-dimension space and the reduced-dimension space, limiting the usefulness of t-SNE. For instance, if you want to reduce the dimension of a predictive model, when you go to predict on new data, you do not have a way to do so. This is in contrast to, say, PCA (Principal Components Analysis), where you can apply the eigenvectors from some training data to extract features from new data (either for out-of-sample testing or on entirely new data being predicted in production).
Consequently, t-SNE is at its most useful when you just want to visualize high-dimensional data, hence the emphasis on reducing to the two dimensions where our vision operates. You can't visualize data in $80$ or $100$ dimensions, and you can't do much beyond visualize with the t-SNE results, so I wonder why one would bother to reduce to a dimension where visualization is not feasible.
An alternative to t-SNE that does allow you to apply the transformation to new data is UMAP: Universal Manifold Approximation and Projection.


Simpliest way to display thumbnail images without spaces

Question: I am trying display images seamlessly in a checkerboard fashion.  All images are same size.  Can't seem to eliminate spacing between rows.
The overall goal is compact code.
Here is the original code.
<?php build();

function build(){
for($x=1;$x<=11;$x++){
for($y=1;$y<=11;$y++){
?><form action="$_SERVER['PHP_SELF']" style="float:left;"
><input type="image" name="data" value="var" src="images/blue.png"
></form><?php }}}?>

Here is what I have after trying several other things to eliminate the spacing.
<?php build();

function build(){
for($x=1;$x<=11;$x++){
?>
<?php
for($y=1;$y<=11;$y++){
?><form action="$_SERVER['PHP_SELF']"
><input type="image" name="data" value="var" src="images/blue.png"></form
><?php }?>
<?php }}?>

Per request, html translation..  (values changed to 3 to reduce length.)
<form action="$_SERVER['PHP_SELF']" style="float:left;"
><input type="image" name="data" value="var" src="images/blue.png"
></form><form action="$_SERVER['PHP_SELF']" style="float:left;"
><input type="image" name="data" value="var" src="images/blue.png"
></form><form action="$_SERVER['PHP_SELF']" style="float:left;"
><input type="image" name="data" value="var" src="images/blue.png"
></form><form action="$_SERVER['PHP_SELF']" style="float:left;"
><input type="image" name="data" value="var" src="images/blue.png"
></form><form action="$_SERVER['PHP_SELF']" style="float:left;"
><input type="image" name="data" value="var" src="images/blue.png"
></form><form action="$_SERVER['PHP_SELF']" style="float:left;"
><input type="image" name="data" value="var" src="images/blue.png"
></form><form action="$_SERVER['PHP_SELF']" style="float:left;"
><input type="image" name="data" value="var" src="images/blue.png"
></form><form action="$_SERVER['PHP_SELF']" style="float:left;"
><input type="image" name="data" value="var" src="images/blue.png"
></form><form action="$_SERVER['PHP_SELF']" style="float:left;"
><input type="image" name="data" value="var" src="images/blue.png"
></form>

Here is what ended up working.  It works now because all inputs have been lumped into a single form.
<?php solutionbuild();

function solutionbuild(){
for($x=1;$x<=11;$x++){
?><form method="POST" action="<?php $_SERVER['PHP_SELF'] ?>">
<?php
for($y=1;$y<=11;$y++){
?><input type="image" name="data" value="9" src="images/green.png"><?php
}?>
<?php }}?>

html version (yikes)
<form method="POST" action="">
<input type="image" name="data" value="9" src="images/green.png"><input type="image" name="data" value="9" src="images/green.png"><input type="image" name="data" value="9" src="images/green.png">
<form method="POST" action="">
<input type="image" name="data" value="9" src="images/green.png"><input type="image" name="data" value="9" src="images/green.png"><input type="image" name="data" value="9" src="images/green.png">
<form method="POST" action="">
<input type="image" name="data" value="9" src="images/green.png"><input type="image" name="data" value="9" src="images/green.png"><input type="image" name="data" value="9" src="images/green.png">

I don't know exactly why consolidation of the forms eliminates the spacing issue.  If anyone knows, please let me know.  Thanks
Comment: Why not show the resulting html?
Comment: The html would provide us a mean do answer the question. As it is in the resulting html your problem lies.  If you then experience problems translating that correction to your php code, that can be a follow-up question.   Do not expect us to try and execute random php-snippets in order to understand your question better.  Hope that helps as an explanation.
Comment: Are you sure you need to use a form for each image input? You have 11 rows and 11 images per row, 11*11 = 121 forms.
Comment: for clarification.  there is quite a bit of redundancy included in the second example to help illustrate what has been tried before presenting the question.
Comment: I'm not sure if I understand the context of what you are asking.  Sorry, I'm new.. first post..  If you are asking why I didn't post the translated html version of the php, it's because I'm having trouble figuring out the proper way to tie the styles into the for loops.  If I just show the html I wouldn't be sure if the divs should be inside or outside the loops, ect.  If you were asking something else, let me know and I see if I can add it.
Comment: added html.  reduced to 3x3 to reduce code.
Comment: It's possible that I will want different input triggers to have different form actions.  I am not aware of a more compact way to achieve that with php.  I'm new though, if their is a better way to implement that, please let me know.
Comment: I get that you want to do different things based on which image is selected but you don't need multiple forms `` to do that. Do what you have done and have each input share a name but have a different value, ie `name="foo" value="1"` then `name="foo" value="2"` etc. When the form is submitted `foo` will equal the value of the image clicked on. This may no longer be true but the value passed by `input type="image"` may be inconsistent across platforms. As an alternative you could use the `` element, example here http://jsfiddle.net/jty4qrfp/.
Answer: The space you are seeing below your images is because they are inline elements. Inline elements include space for the descender in text like the lowercase letters j and g.
Float your image inputs to or set them to display block to remove this extra space.
Edit
Not sure why you want to use a form for each image input. I would wrap a form tag around the whole thing myself (that is, without further info) so I left them out.
Here's an example:

.no-float,
.float {
  margin: 25px 0;
}
.float input {
  float: left;
}
.float .row {
  clear: left;
}

    <input type="image" src="http://lorempixel.com/30/30/abstract/">
    <input type="image" src="http://lorempixel.com/30/30/abstract/">
    <input type="image" src="http://lorempixel.com/30/30/abstract/">

    <input type="image" src="http://lorempixel.com/30/30/abstract/">
    <input type="image" src="http://lorempixel.com/30/30/abstract/">
    <input type="image" src="http://lorempixel.com/30/30/abstract/">

    <input type="image" src="http://lorempixel.com/30/30/abstract/">
    <input type="image" src="http://lorempixel.com/30/30/abstract/">
    <input type="image" src="http://lorempixel.com/30/30/abstract/">

    <input type="image" src="http://lorempixel.com/30/30/abstract/">
    <input type="image" src="http://lorempixel.com/30/30/abstract/">
    <input type="image" src="http://lorempixel.com/30/30/abstract/">

    <input type="image" src="http://lorempixel.com/30/30/abstract/">
    <input type="image" src="http://lorempixel.com/30/30/abstract/">
    <input type="image" src="http://lorempixel.com/30/30/abstract/">

    <input type="image" src="http://lorempixel.com/30/30/abstract/">
    <input type="image" src="http://lorempixel.com/30/30/abstract/">
    <input type="image" src="http://lorempixel.com/30/30/abstract/">

Comment: I have tried both display:block; and float:left; in   that doesn't seem to do anything.  I'm assuming I need to change the scope of the div, but I can't figure out where I need to move it.
Comment: I also tried both float and display in the form style.
Comment: You need to apply it to your inputs, ``. If this does not work then you have applied it incorrectly or there is more going on than what you have provided in your question. I have added an example code snippet to my answer.
Comment: I think that using multiple forms resulted in extra white space somewhere, but still am not sure.  For some reason it works with one form, but not with multiple.  thanks for the help.
Comment: As mentioned before, I don't think you need to use multiple forms, but for the issue as to why removing forms eliminated the spacing issue I'm going to suggest that you have some CSS that is causing this that you're unaware of. Please, if my answer solved your issue please accept it as the accepted answer.


How does variation of doping testing effect effect fairness of sports?

Question: I have read on the internet that due to the variation of doping testing between countries and the disparity between testing standards at an international level and local level, many sports similarly turn out unfair.
People often cite examples such as East Germany and Soviet Union when they want to justify this point.
However, what about today? Is this still actually a problem today? If so, how?
Answer: Unfortunately, doping is still a high occurrence, weakly enforced problem in sports. One recent study comparing doping and socioeconomic variables points out that the WADA (World Anti Doping Association) testing protocols produce less than 1% positive results, but anonymous surveys and questioning puts the number of intentional intake at 39% (And likely higher actual value).
Another study on testing frequency shows that testing standards and frequency is vastly different from nation to nation.
Speaking at a personal n=1 level, I was a competitive cyclist (Cat 3, almost Cat 2 in the United States, so just below elite level), and I know as a fact that half the peloton at any given time was doping to some extent. Unless you are competing at a national event or in the USADA random testing pool, you aren't going to be tested.
Short answer, yes it is still a problem, and one that is not likely to be solved. Every time a new test comes out, new ways to get around it are created.


Is a written music theory exam noisy?

Question: I haven't taken a written music theory exam, and I never will, but I don't understand how it would work.  You've got a lot of people in a room, all trying to answer the same questions.  And if half of them are like me, then half of them are humming or whistling in order to figure out if this passage sounds major or minor, or what the underlying chords are, or whatever.  That's how I work and I would find any other technique much harder.  Judging by their recordings, I think Thelonius Monk and Glenn Gould feel the same way, so I'm definitely not alone.  So I imagine a cacophony of people all doing this at once, distracting each other.  Is that what it's like, or do you have to remain quiet, or what happens?
Comment: Which country are you taking your exam in?  In UK, exams are taken in silence.
Comment: Did my last one over 60 yrs ago. 100 candidates in a school hall. No noise allowed (aloud?). It wouldn't have been fair to even hum audibly. And, theory exams must all be taken en masse, otherwise questions could be related to later groups!
Comment: So many great answers - thank you everyone <3
Answer: I've taken a fair number of classroom music theory exams, and they were generally quiet. Any humming would have been done very, very quietly.
But since the exams are primarily analytical, there's also an expectation that they'll be answered near entirely by analysis.
Theory curricula are often combined with ear training and rhythm training. Those exams are typically done separately and individually.
Comment: (To elaborate: "ear training"/"aural skills" exams necessarily have out-loud content. Anything requiring the student to listen—like, to hear and write down melodies or chords—can be administered to a whole class at once, but anything requiring the student to "perform," like to sing a melody using solfege, has to be done in private with one student at a time to avoid students "getting the answer" from others' performances. In my undergrad, these skills were actually a separate course from music theory classes and had their own exams.)
Answer: One of the goals of music theory is to be able to tell whether a passage is major or minor and to completely analyze without needing to hum or whistle at all.
Cadences often have to be heard, though. In the class I took where score analysis required finding cadences, our professor set aside a portion of the exam time for playing recordings of the excerpts in question. No humming needed.
Note that in American university ear training courses, humming is generally prohibited but overlooked if done quietly by beginners. By the third semester the expectation is that students can audiate, that is hear the music completely in their heads right from the page. During sight singing juries, points may be deducted for any noises made before beginning the excerpt.
Comment: So many great answers - thank you everyone. But this one gets the check mark for reminding me about audiation.
Answer: I see what you're getting at!   But no, theory exam rooms are generally pretty quiet.
Here's the sort of thing you're asked to do. (Grade 5 is the 'everyone needs to know this much' level.)
Sample ABRSM grade 5 theory paper
Comment: Thanks for taking me back 60 yrs! Amazing how much gets forgotten...+1.
Comment: (Unfortunately, that link no longer works.)
Answer: Generally, written music exams are silent, just like any other exam. The extent of permitted humming or quiet whistling is generally up to the examiner and governing body.
Some other types of exams are taken using computers, which may include audio components with headphones.
Performance-based examinations are necessarily different.
People with the Aphantasia condition (about 4% of the population) have limited sensory recall/imagination, varying in degree and type. For those with audio aphantasia, exam conditions can be very challenging indeed.
Comment: I thought aphantasia is mainly a visual condition (or rather: lack of an ability, namely lack of visual imagery). I don't know whether there is a term for the auditory analogue, but I would say that the auditory analogue to visual imagery is either *relative pitch* (which comes in degrees, of course) or something closely related to it.
Comment: @LoverofStructure What are you talking about? The auditory analogue of visual imagery is audiation. Aphantasia can affect any sense or all of them.
Comment: @the-baby-is-you It seems like in research, the term "aphantasia" is only applied to visual imagery. According to the little I can read online about "audiation", that term is more vague and applied far more broadly than relative pitch, and relative pitch or "inner ear" seem to be more fitting for a music theory exam, though I would add "hearing multiple voices at the same time or imagining harmonies".
Comment: @LoverofStructure That's why relative pitch isn't the right term here. That's like saying visual imagery is distance.
Comment: @the-baby-is-you Your assertions are too strong. Actually, thinking about it, relative and absolute pitch as terms imply high musical ability, at least in common usage.
Comment: @LoverofStructure The term is fairly new and the definiton varies depending on who you ask. Loosely speaking it's the inability to imagine (project senses mentally, especially visual, but there are plenty of people for whom it's audible also). There are many different types and manifestations of the condition. I've experienced aphantasia temporarily myself (very strange). Normally I'm mild hyperphantasiac which is the opposite to aphantasia. I've been studying aphantasia for several years and personally know various people with the condition.
Comment: So far as so-called absolute or perfect pitch, this is the same as learning experientially what visual frequency of light corresponds to the word 'red'; It's a learnt ability but easier for some people (I work with a world expert in this space).
Comment: (I've worked in education for decades and have helped set up for exams many times.)
Comment: @AndrewKingdom [Visual] aphantasia is very independent of the auditory analogue, as evidenced from the many people who have one but not the other. One doesn't imply the other at all. As for perfect pitch, some people fail miserably in learning, just like you can't learn painting if your brain's memory span for visual material is effectively zero. You also can't expand your short-term memory span for digits etc unless you cheat by chunking (requiring extreme practice), and the result is very domain-specific (non-transferable chunking of whatever you practiced), not a generally wider STM span.
Comment: @LoverofStructure There is a huge variety of different types of aphantasia and I've not seen any useful paper covering the various types (I've been collecting details on such types for several years, speaking regularly to those with the condition). There is much ongoing research in the field (I know this first hand from speaking with various researchers and from my own studies). At present Aphantaisia is also used to cover the auditory as there is no standandard term for such yet in any significant papers I've seen. This is mainly as the research is recent and ongoing.
Answer: Just to clarify the kind of "music theory exam" we're talking about, this does NOT include "ear training" / "aural test" which @AndyBonner described well in his comment:

(To elaborate: "ear training"/"aural skills" exams necessarily have out-loud content. Anything requiring the student to listen—like, to hear and write down melodies or chords—can be administered to a whole class at once, but anything requiring the student to "perform," like to sing a melody using solfege, has to be done in private with one student at a time to avoid students "getting the answer" from others' performances. In my undergrad, these skills were actually a separate course from music theory classes and had their own exams.)

@Laurence's answer provided a sample ABRSM grade 5 exam where the only possible benefit from humming comes in section 5 (chords) but you can mitigate by visually counting the steps in the ledger lines between the notes.
In higher grades, like this grade 8 exam, you need to do:

some simple composition (example: Section 1.1 and 2.1),
harmonization (example: Section 4.1, also this ABRSM Grade 8 Trio Sonata question), and
analysis (example: Section 5)

where humming or playing the score on the keyboard would have been helpful.  BUT THEN, as you advance in your training, you are ALSO expected to be more proficient in hearing the music in your head, although not to the extent that Beethoven was able to do when he became deaf.
I admit that when I took those ABRSM exams, as well as college level ones, I sometimes wish that the exam room would provide a keyboard with headphones for anyone to use during the exam, but alas, it's not provided.  I think it's part of the training to be able to do all those tasks in your head.  My fellow exam takers and classmates have been absolutely courteous to maintain a quiet environment like in the library.

Is a written music theory exam noisy?


Only sort views after selected

Question: I am looking to sort nodes in a view, but only after the user has selected the sorting value.
So the nodes are currently listed in posting order, but I would like to provide the user to sort by price, but only once selected the price sorting?
Creating a standard sort by price, sets this from the initial page load and does not give the use a chance to see recently posted items.
How could this be achieved?
Answer: Two ideas:
(1) Expose the sort to the user to allow them to control sorting. You need to enable "Expose this sort to visitors, to allow them to change it" for the sort criterion in views. See below for more detail on how to get the two sorts grouped together.
(2) Present the data in a table and make the columns you want the user to be able to sort, "sortable". You'll find this option under Format: table > Settings.
With both approaches, you can set an initial sort, so the user will see content in the order you wish when the page first loads.
Edit: more detail for #1: by default, views will sort the output based the first sort criterion, and clutter the exposed form with sort order controls. To get the default sort you want, and to clean things up, you can try:

Add both sort fields and expose to visitors (post date first)
Under exposed form options: enable autosubmit and hide the submit button
Under exposed form options: disable "Expose sort order"
Adjust exposed sort labels if needed for clarity

(exposed form options are in the Advanced section of the view)
When the view loads, the user will see a single select list that contains both sort options, and no submit button. The view will be sorted according to the first option.
Comment: Perhaps there was not enough emphasis on an important point. The sorting by price should only take effect if the user was to use this option. When adding in a sort and exposing it you are forced to select either Asc or Dsc. This should be optional.
Comment: I added some more detail to idea #1. I'm not sure this will work exactly as you like, but the result would be a view ordered by post date by default, with a select list to change to order by price.

Only sort views after selected


How to redirect to search result page?

Question: I've activated the search form block on my Drupal home page.
When a user enters a keyword and presses search button, I would like to redirect to the search page result.
How can I do that?
Comment: Can you explain what you mean by "validate button"? What sort of redirection do you need, as submitting the search form will automatically direct the user to the search results page.
Answer: function MyModuleName_form_alter(&$form, &$form_state, $form_id)
{
   if ($form_id == 'search_form_id') {
     $form['#submit'][] = 'MyModuleName_custom_serch_form_submit';
   }
}

function MyModuleName_custom_serch_form_submit($form, &$form_state)
{
  if(isset($_GET['q']) && !empty($_GET['q']))
  {
     $string_serch= $_GET['q'];
    drupal_goto("http://yourdomain.com/search?q=".$string_serch);
  }
}

Answer: You can redirect search result by using hook_search_box_form_submit
function mytheme_search_box_form_submit($form, &$form_state) {
   $form_state['#redirect'] = 'path of redirect';
}

How to redirect to search result page?


Moving from Spring 3.1 with Eclipse Gemini Blueprint to Spring 4.2.5

Question: I have a project that used Spring 3.1 and Eclipse Gemini 1.0.2 for an OSGi project. I recently moved to Java 8 and found that Spring asm could no longer scan my classes because I was using Java 8 lambdas and that I needed to upgrade to Spring 4.x to get Java 8 support.
I upgraded to Spring 4.2.5 and am being told that Eclipse Gemini 1.0.2 will no longer work, it wants Spring 3.0 <= x < Spring 4.
It seems Gemini is dead, when I go to Eclipse, I see a download for 1.0.2 and then a milestone for 2.0.0, but no other releases.
What OSGi Blueprint container should I use if I am using Spring? My project uses Spring MVC, Spring Webflow, Spring transactions, etc.
Thanks!
Answer: It seems the Eclipse Gemini Blueprint project is still alive.
Version 2.0 was released soon after you posted your question.
Version 2.1 was released just two months ago, and supports Spring 4.3.x.
Reference: ECLIPSE GEMINI BLUEPRINT CHANGELOG
Comment: Many thanks for the pointer! I upgraded to Blueprint 2.1 and hence to Spring 4.3 after I saw your post and can now use Java 8 and Scala 2.12.
Answer: Afaik, there is no implementation today of blueprint which supports Spring 4.

There is an official Gemini 2.0 which seem to support it (a milestone 2.0.0.M3 not released to a public repository). See this commit
There is too an unofficial component of Aries-blueprint which seem to support Spring namespace (but not released too - or at least, I never see any documentation about it). See ARIES-1456 or this bundle

Personally, I am looking for a working version too, but unfortunately, blueprint/spring-dm is more or less deprecated. The Aries implementation looks like the more stable today, but I am slowly migrating my component to Declaratives-Services, and embedding Spring myself.
Comment: Hmm, sounds like maybe I should roll back to the previous Spring, do the work I actually want to get done, and plan on a project to remove Spring. Definitely have wanted to remove Spring MVC and Webflow and use Angular over websockets. What are you doing to plug your springbeans into declarative sevices?


Integral gaussian hypergeometric function

Question: How can we define integral with interval $[b,\infty)$
$$
\begin{align}
C(b,\alpha) & = \int_b^\infty \frac{1}{1+w^{\alpha/2}}\,\mathrm{d}w \\[8pt]
& = 2\pi/\alpha \csc(2\pi/\alpha)-b_2 F_1 (1,2/\alpha;(2+\alpha)/\alpha;-b^{\alpha/2})
\end{align}
$$
where $_2F_1(\cdot)$ is the Gaussian hypergeometric function
Can anyone help me step by step with this or give some hint where to start since i'm still studying math
best,
Comment: Where you wrote $2\pi/\alpha\mathrm{csc}\cdots$, the lack of space between $\alpha$ and $\mathrm{csc}$ would not have happened if instead of \mathrm{csc} you had coded it as \csc.  I changed it. ${}\qquad{}$
Comment: I don't know about the result you mentioned; but  you can start by inverting the limits to [0,1/b] then normalize so that it's [0,1] then assign z*t=(normalize*w)^(-a/2).  Then carry through to put it into the form of DLMF 15.6.x.
Comment: Do you want to do contour integration (which probably is intended) or a direct integration using Hypergeometric functions?  The last is easy but probably restricting in terms of the signs and values of $\alpha$
Answer: I rename the parameter for convenicence:
$$I(a,b)=\int_b^\infty \frac{dw}{1+w^a}=\frac{1}{a} \int_{b^a}^\infty \frac{u^{1/a-1}du}{1+u}=$$
$$=\frac{1}{a} \int_{0}^\infty \frac{u^{1/a-1}du}{1+u}-\frac{1}{a} \int^{b^a}_0 \frac{u^{1/a-1}du}{1+u}=$$
$$=\frac{1}{a} B\left(\frac{1}{a},1-\frac{1}{a} \right)-\frac{b}{a}\int^{1}_0 \frac{v^{1/a-1}dv}{1+b^a v}=$$
$$=\frac{1}{a} \Gamma \left(\frac{1}{a}\right) \Gamma \left(1-\frac{1}{a}\right)-\frac{b}{a} B\left(\frac{1}{a},1 \right) ~{_2F_1} \left(1,\frac{1}{a};1+\frac{1}{a} ;-b^a\right)=$$

$$=\frac{\pi}{a \sin \frac{\pi}{a}}-b  {_2F_1} \left(1,\frac{1}{a};1+\frac{1}{a} ;-b^a\right)$$

All of this directly follows from the definition of the Beta function and the Euler integral for the Hypergeometric function.


Asymptotic inner product of correlated random vectors

Question: Suppose $\mathbf{x}$ and $\mathbf{y}$ are N-dimensional non-white complex random vectors independent of each other i.e., covariance matrices $\mathbf{C_{xx}}\neq\mathbf{I}$, $\mathbf{C_{yy}}\neq\mathbf{I}$, $\mathbf{C_{xy}}=\mathbf{0}$. Is there any results on asymptotic orthogonality $\mathbf{x}^H\mathbf{y}=\mathbf{u}^H\mathbf{C_{xx}}^{\frac{1}{2}}\mathbf{C_{yy}}^{\frac{1}{2}}\mathbf{v}=0$ where $\mathbf{u}$ and $\mathbf{v}$ are independent white vectors. Thanks.
Answer: I came up with this:
We have $\mathbf{x}^H\mathbf{y}=\mathbf{u}^H\mathbf{C_{xx}}^{\frac{1}{2}}\mathbf{C_{yy}}^{\frac{1}{2}}\mathbf{v}=tr\{\mathbf{C_{xx}}^{\frac{1}{2}}\mathbf{C_{yy}}^{\frac{1}{2}}\mathbf{v}\mathbf{u}^H\}\leq tr\{\mathbf{C_{xx}}^{\frac{1}{2}}\mathbf{C_{yy}}^{\frac{1}{2}}\}tr\{\mathbf{v}\mathbf{u}^H\}$ $=tr\{\mathbf{C_{xx}}^{\frac{1}{2}}\mathbf{C_{yy}}^{\frac{1}{2}}\}tr\{\mathbf{u}^H\mathbf{v}\}=0$.
Is this correct?
Thanks.
Answer: I Think using the Theorem 3.4 in [1] (page 45), we can say:
$\boldsymbol x^H\boldsymbol y\xrightarrow{a.s.}tr(\boldsymbol C_{xx}^{\frac{1}{2}}\boldsymbol C_{yy}^{\frac{1}{2}})$
[1] Couillet R, Debbah M. Random matrix methods for wireless communications. Cambridge University Press; 2011 Sep 29.


How can I resolve these errors when updating the module?

Question: I want to update Drupal Commerce to 8.x-2.0-beta7 from a clean, Composer-based installation of 8.x-2.0-beta6, following the documentation on http://docs.drupalcommerce.org/v2/getting-started/update.html.
I noticed that composer update drupal/commerce --with-dependencies did not update drupal/core. This surprises me. Isn't drupal/core a dependency? Anyway, says it's white-listed so I then ran composer update drupal/core.
Now I am hitting a problem with updates.

drupal update:debug
Fatal error: Cannot use Drupal\Console\Core\Bootstrap\DrupalConsoleCore
      as DrupalConsoleCore because the name is already in use
      in/pathto/commerce8/vendor/drupal/console/src/Bootstrap/Drupal.php on
      line 11

drupal update:execute
Fatal error: Cannot use Drupal\Console\Core\Bootstrap\DrupalConsoleCore
      as DrupalConsoleCore because the name is already in use in
      /pathto/commerce8/vendor/drupal/console/src/Bootstrap/Drupal.php on
      line 11

I have since run update.php, but the Composer errors persist.
I am learning about Composer, and I don't know yet anything about Drupal Console.
What am I doing wrong?
Comment: These are Drupal Console errors, not Composer errors, whole different program. Please update the question title.
Guessing that Drupal Console broke because you forgot to do --with-dependencies when you updated drupal core. You need "composer update drupal/core --with-dependencies"
Answer: It sounds like Drupal Console someone was installed improperly, based on the duplicate class name error.
Can you try removing the /pathto/commerce8/vendor directory. Then run composer install once more. That'll fixup all third party dependencies, hopefully resolve this.
Comment: Thank you Matt. I did what you suggested and found exactly the same errors after running both drupal update:debug and drupal update:execute. Could it be that I have Drupal Console installed (elsewhere) globally?
Comment: It is possible. See https://github.com/hechoendrupal/drupal-console/issues/3181,


The last/largest semi-prime of the form $16^n+1$?

Question: Mr. David Norata of south Borneo conjectures that $16^{317}+1$ is the last/largest semi-prime of the form $16^n+1$. But he didn't give any clue why he is so sure about this, he just said that he has a rough proof.
Note that $16^n+1$ can be a semi-prime if and only if $n$ is a prime number, and some values of $n$ for which $16^n+1$ is a semi-prime are $3,5,7,23,37,89,149,173,251,307, 317, \ldots$.
Can you prove or disprove Mr. Norata's conjecture?
Comment: It's unclear how you might expect a concise treatment of such a question.  You give no actionable reference by which an interested Reader might assess for themselves a work by "Mr David Norata of [S]outh Borneo", by which you presumably mean the Indonesian portion of the island.
Comment: One may note that $16^n+1$ is divisible by $17$ for all odd $n$. I find the conjecture dubious, however, being given no reason to believe it.
Comment: Googling David Norata pretty much just leads back to this post. Could the original asker by any chance be the mysterious Mr. Norata?
Comment: The claim that $16^n + 1$ can be semiprime only if $n$ is prime is incorrect unless $n$ is assumed odd.  The fifth Fermat number $2^{2^5} + 1 = 16^8 + 1$ has the two prime factors $641$ and $6700417$ (Euler), and other examples are found in the Wikipedia article on [Fermat numbers](https://en.wikipedia.org/wiki/Fermat_number#Factorization_of_Fermat_numbers).
Comment: Why does anyone care who Mr Norata is?  It's just a math question.
Comment: Use LATEX please.
Comment: @Rajada, this is the first time for me to post question to this site
Comment: Okay I will try to edit it.
Comment: I'm also really unclear as what you would expect this question to amount to. Do you want someone to prove or disprove someone's suggested conjecture? This is not really what this website is for.
Comment: The primality of $~\dfrac{16^{317}+1}{17}~$ can be verified using the [elliptic curve method](http://www.alpertron.com.ar/ECM.HTM).
Answer: Mr. David Norata's conjecture is false, since $16^{956}+1 = 65537\cdot\text{P1147}.$
Answer: I can confirm via numerical testing that $(16^n+1)/17$ is prime for odd $n<2000$ only if $n=3,5,7,23,37,89,149,173,251,307,317$.


Apache - mod_rewrite - backreferences understanding

Question: httpd Apache server -> mod_rewrite -> backreferences
The following picture is about understanding the reference to parentheses ([Flags] are omitted).

If you use parentheses, backlinks are made to what is in parentheses and then you can use it somewhere in the conditions using %1 and $1.
The origin of the image is in the unofficial documentation for httpd Apache 2.2
https://publib.boulder.ibm.com/httpserv/manual70/rewrite/rewrite_intro.html#InternalBackRefs
There is no such picture in official httpd Apache 2.4 documentation
https://httpd.apache.org/docs/2.4/rewrite/intro.html#InternalBackRefs
The essence of this post is just to verify that I understood it correctly and whether it works in httpd Apache 2.4.
Would anyone know?
Answer: This is a fundamental principle of how mod_rewrite works, whether you are using Apache 1.3, 2.2 or 2.4. So, yes, it does work the same in Apache 2.4.
(Although the diagram you posted, based off an IBM "copy"(?), not Apache's "official" document is arguably ambiguous as it's not clear in what order the RewriteCond directives are processed (blue arrows). Top-down or bottom-up? EDIT: Although you've clarified that this represents backreferences only; not the order of processing.)

The origin of the image is in the documentation for httpd Apache 2.2
https://publib.boulder.ibm.com/httpserv/manual70/rewrite/rewrite_intro.html#InternalBackRefs

As noted above, that's not the "official" documentation for Apache 2.2. The official docs for 2.2 and Apache 2.4 contain the same diagrams. These diagrams and the accompanying text describe the same process as outlined above.

The diagram from the IBM docs (which looks like an early "copy" of the Apache docs and is very much incomplete) contains the following diagram, which your diagram appears to be based:

That blue line (that goes up from the RewriteRule pattern) is ambiguous IMO - is it going to the bottom condition first or the top? I would modify that diagram to be a bit more clear as to the order of processing. For example:
Comment: >>>01. In my diagram, it is not about the process of rewriting but about the use of backlinks %1 and $1. >>>02. As for the rewriting process, I have a second diagram. To maintain clarity, I have drawn each logic separately. Putting two such complicated matters on one diagram was wrong with me. >>>03. Thank you for notifying me of the official Apache 2.2 documentation.
I don't know why I thought the documentation I mentioned (IBM) was official.
(my fault).
It seems to be a fork in which various useful information is added.
Comment: About the process of rewriting, (See, both links)
>01< https://httpd.apache.org/docs/2.2/rewrite/tech.html#InternalRuleset
>02< https://httpd.apache.org/docs/2.4/rewrite/tech.html#InternalRuleset
Comment: 01. OK, fair enough. Thanks for clarifying. I suppose I tend not to differentiate it so much so was looking at it from both sides. 03. Actually, those IBM docs, seem to be more closely related to the [Apache 2.0 docs](https://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewriterule) - perhaps an early version of 2.2(?), since it does say 2.2 at the top (although I noticed it did not mention the `DPI` flag, which was introduced later in 2.2.12).
Comment: An additional (important) consideration with `%n` backreferences, is that they derive from the "last _matched_ CondPattern", which is not necessarily the _previous_ CondPattern, as depicted in the diagram. (Although this isn't something that should/could be represented in the diagram.)
Comment: If I understand correctly, %N comes only from the last CondPattern. The same is apparent from the picture from documentation IBM Apache. Do not forget: If CondPatern is not met, the entire RewriteRule is not executed. See https://httpd.apache.org/docs/2.2/rewrite/tech.html#InternalRuleset or https://httpd.apache.org/docs/2.4/rewrite/tech.html#InternalRuleset
Comment: "%N comes only from the last CondPattern" - Not necessarily, as mentioned above, and in [the docs](https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#rewriterule), it comes from the "last _matched_ RewriteCond pattern". Conditions can be skipped entirely if they are part of an "OR" block and negated patterns are non-capturing (they don't "match" anything). In both cases, captured patterns from the last _matched_ CondPattern are essentially _passed through_.


Finding correct weights given standard errors

Question: I have a two stage model where coefficients of model 1 become the $y$-vector for model 2. I have standard errors for those coefficients, and I want to weigh the observations in model 2 according to the standard error that the corresponding coefficient had in model 1. I believe the correct way to do this is weigh the observations in 2 by 1/SE, where SE is the standard error of the corresponding coefficient in model 1.
Now, the data for model 1 actually gets artificially created by me. I therefore know that coefficients with a SE of $\geq X$ are completely useless (I know this given my setup). Now, in model 2, giving those useless observations a weight of $1/\text{SE}$, with $\text{SE}\geq X$, seems like giving them too much weight, since their actual weight should be 0
What is the best method to weigh observations in such a case?
Comment: This looks to be quite an odd experiment I have to say.  I've had a go at answering because I think there is useful information in my answer on using inverse of variance to weight.  But to give more meaningful advice we'd need to know exactly what you're trying to do - for example, why do you know that coefficients with a SE >=X are completely useless whereas those just below that threshold presumeably aren't.  But most importantly what is the point of this whole thing?
Comment: I know that coefficients > X are useless because of the way I artificially create that dataset: \n
Comment: I know that coefficients > X are useless because of the way I artificially create that dataset: I create "fake coefficients" using random.gauss with mean Z, stdv X. I then create the y-vector using the fake coefficients while also adding some noise. If the finally computed SE for that coefficient is >= the stdv I created it with, I'm assuming it's useless for model 2
Answer: First, you should probably use the inverse of the variance as your weights; that is, the square of what you are proposing.  See for example the discussion on this question or any general discussion of weighted least squares regression.
Second, it's not clear to me how you can be so sure that the coefficients where SE > X are completely useless - in fact, I would have thought simply weighting these like others by the inverse of the estimated variance was ample.  However, if you really are sure that this hard cut-off point is meaningful then you are saying that the real variance of those points is infinite (rather than the actual number you estimated in stage 1), so go ahead and give them zero weight.


Use part of the user_profile_form on another page

Question: My users enter a phone number on registration. The amount of values that can be entered is set to unlimited. Setting this changes the field so that you can add another field below to add additional phone numbers.
I would like the users to be able to add more numbers after registration without having to go to /user/%user/edit
I am trying to return just the phone number field on another page.
However I cannot seem to get any of that form displayed on another page.
When I have been displaying other forms I have called them like this:
drupal_render(drupal_get_form('user_profile_form'));

This does return part of the form, First Name, Last Name, Country (all custom fields) but not the phone number field. I also get quite a few errors
Undefined index: user_profile_form in drupal_retrieve_form()
Undefined index: #user_category in block_form_user_profile_form_alter
Undefined index: #user_category in overlay_form_user_profile_form_alter()
Undefined index: #user_category in system_form_user_profile_form_alter()
Undefined offset: 0 in uc_roles_form_user_profile_form_alter()
Obviously I am doing something very wrong...
Comment: `module_load_include('inc', 'user', 'user.pages');` should be added to `hook_init()` otherwise all profile form functionalities that require AJAX calls will return the error "Call to undefined function user_profile_form_validate()."
Answer: I made this work based on the work by Erik. I guess you could do ['#access']=false for all the values you don't want.
//Provide a custom page at /custom-profile to access our custom profile form
function mymodule_menu() {
  $items['custom-profile'] = array(
   'title' => 'Custom Profile!',
   'page callback' => 'mymodule_custom_profile',
   'access callback' => TRUE,
   'type' => MENU_NORMAL_ITEM,
 );
}

//displays the custom form at /custom-profile
function mymodule_custom_profile() {
  module_load_include('inc', 'user', 'user.pages');

  global $user;
  $user = user_load($user->uid);

  $form = drupal_get_form('user_profile_form', $user, 'account', 'custom');

  return $form;
}

function mymodule_form_user_profile_form_alter(&$form, &$form_state){
  //modifies the form_user_profile DO CUSTOM STUFF BELOW!
  if(isset($form_state['build_info']['args'][2]) &&
           $form_state['build_info']['args'][2] = 'custom'){

   //rename submit button
   $form['actions']['submit']['#value'] = t("dooo it!");

   //remove a few account things from this page
   $form['account']['#access']=FALSE;

   //needs to be there for the picture to work
   form_load_include($form_state, 'inc', 'user', 'user.pages');
  }
}

Comment: I get Call to undefined function user_profile_form_validate() when submitting the form. Have you any idea ?
Comment: Follow-up question here: http://drupal.stackexchange.com/questions/116156/create-a-custom-form-based-on-user-fields
Answer: Try this
module_load_include('inc', 'user', 'user.pages');
global $user;
print(drupal_get_form('user_profile_form', $user));

This will work.
Comment: Excellent, yes this does display the user_profile_form. Do you know how to return a single field? In this case a field with the values limit set to unlimited. Also I have just noticed, the custom fields added to this form do not display their content.
Comment: The AJAX on the 'unlimited' values field does not work also.
Call to undefined function user_profile_form_validate()
Comment: I think we cant return a single field only. Make a hook_form_alter and preload the values. Get values using user_load
Comment: Try print drupal_render(drupal_get_form('user_profile_form'));
Comment: I'm afraid drupal_render has no affect, I still have the Call to undefined function user_profile_form_validate() error. Do I have to load the validation for the form separately? I assumed that getting the form would automatically load the validation function.
Comment: I thought this would be the awesome answer I searched, but if I use it, nothing gets displayed ... no error .. no form .. just nothing. Any ideas?
Answer: drupal_get_form('user_profile_form',$user,'account', 'my_parameter');

function my_module_form_alter((&$form, &$form_state, $form_id) {
  switch($form_id) {
      case 'user_profile_form':
        $info =  $form_state['build_info']['args'][2];
        if ( $info == 'my_parameter' ) {
           //do something with the form
           $form['my_field']['#access'] = false ;
           //prevent ajax errors
           form_load_include($form_state, 'inc', 'user', 'user.pages');
        }
      break ;
   }
}

Comment: This doesn't work for me but does result it lots of php warnings...
Answer: Based on @pawel-dubiel comment I added user.pages.inc directly to hook_menu():
function mymod_menu() {
   return array(
     'my-path' => array(
        'page callback' => 'mymod_page_callback',
        'file' => 'user.pages.inc',
        'file path' => drupal_get_path('module', 'user'),
     )
   );
}

Works like a charm and using hook_init() is avoided.
Answer: Trying to fetch a single field from a form doesn't make sense IMHO.
If you want to update a single value in the database for this field, you'd better code your own form and manage the submit and validate functions to update the database yourself.


How does using a variable for file paths work?

Question: ifstream inFile;
inFile.open("C:/FilePathThatWorks");

The above seems to work in C++. But if I try and take a String, or CString, or anything else, and plug it in for inFile.open(ExampleString), it fails at compile time (error at the bottom of this question). The question is not about my code, but how to make C++ accept a variable for inFile.
If it only ever accepts char* variables, then is there perhaps a method that takes input from the user in the form of a char* with the null terminator and everything.
error: no matching function for call to 'std::basic_ifstream<char>::open(std::__cxx11::string&)'

Comment: ExampleString.c_str() may be what you are looking for
Comment: Which version of C++ are you using? If you check the reference here: http://www.cplusplus.com/reference/fstream/ifstream/open/ you'll see that C++98 only supports ```const char*``` while C++11 supports ```const string&.```
Comment: The error seems to suggest that the compiler supports C++ 11 because the string seems to be C++ 11, but that contradicts the fact that the file stream doesn't. Even though you seem to have solved your immediate problem, the behaviour is still unclear.
Answer: The method open in fstream does not accept std::string. You need to pass a char*.
So just call c_str() on string.
Comment: [This is only true before C++11](https://en.cppreference.com/w/cpp/io/basic_fstream/open). std::strings are perfectly acceptable for a long time now.
Comment: Huh. I wonder why so many tutorials used different libraries for CString when it's inbuilt to String. Thank you immensely. This works.
Comment: `CString` is the name of a class from MCF. I don't know what `String` might refer to. If you elaborated a bit on that, you could improve your chance at getting answers.
Answer: ifstream requires a char* param for the filename. see http://www.cplusplus.com/reference/fstream/ifstream/ifstream/
most string classes have some way to convert to this kind of string (e.g. c_str())
Answer: If you want to use CString:
CString path = "c:\\FilePathThatWorks";

ifstream inFile;
inFile.open(static_cast<const char*>(path));

The cast is not needed here.
CString can represent two different strings depending on the project settings. If it is a string of char the code should compile, if the character type is wchar_t compiling should fail.


How to read space separated integers in racket

Question: I looked at the documentation https://docs.racket-lang.org/reference/input-and-output.html but I find it to be very confusing and I feel like it contains a lot of extra information I don't need for such a simple task.
I would like to read two space separated integers and store them in variables.
example input:
1 2
I would like to define and x and y whose values are 1 and 2 respectively.
Comment: It would help to know where you are getting these from. A file? User interaction in DrRacket? Etc.
Comment: Is it part of the source code or something that is passed in by the user when the program runs?
Answer: There are a lot of ways to do this. I'll give you three.
Option 1: Use the built-in read
The read function reads s-expressions. Conveniently, integers are valid s-expressions, and it skips whitespace, too. This means you can just call read twice on an input port to produce two datums:
> (let ([in (open-input-string "1 2")])
    (values (read in) (read in)))
1
2

This has a drawback, though: there are a lot of things that are valid s-expressions that aren't numbers, so you might get a lot of garbage back if you're not careful. For example:
> (let ([in (open-input-string "#f (hello world)")])
    (values (read in) (read in)))
#f
'(hello world)

You'd probably need to do some post-processing to ensure what you get back is what you expect. This also won't necessarily consume all the input, so if it's important there's nothing else after the numbers, you'd need to check that separately, too.
Option 2: Use a regular expression
Regular expressions are a pretty easy way to handle simple cases like this. In this example, the regexp literal #px"^(\\d+) (\\d+)$" is a simple way to express the pattern you mention in your question. You can use this to extract the numeric parts of the string:
> (regexp-match #px"^(\\d+) (\\d+)$" "1 2")
'("1 2" "1" "2")

You can combine this with string->number to get numbers out:
> (let ([matches (regexp-match #px"^(\\d+) (\\d+)$" "1 2")])
    (values (string->number (second matches))
            (string->number (third matches))))
1
2

This has the advantage of ensuring the input matches precisely, and it's safe, fast, and simple. However, one downside is that it will not provide good error messages if the parsing fails, regexp-match will simply produce #f.
Option 3: Use a parser combinator library
Racket has a number of libraries designed for parsing. These can scale to parsing far more complicated things that two numbers, but they also work fine for simple situations. I will show an example using megaparsack, since it's my library, and I like it.
You can use megaparsack to write a parser that parses two integers separated by a space:
(require data/applicative
         data/monad
         megaparsack
         megaparsack/text)

(define 2-integers/p
  (do [x <- integer/p]
      (char/p #\space)
      [y <- integer/p]
      (pure (cons x y))))

This parser is obviously more complicated than the regexp, but it also does more, and it's much more extensible and composable. You can use this parser to get the numbers you want:
> (parse-result! (parse-string 2-integers/p "1 2"))
'(1 . 2)

However, unlike the regular expression, it will automatically provide good error messages when a parse fails:
> (parse-result! (parse-string 2-integers/p "1 "))
string:1:1: parse error
  unexpected: end of input
  expected: integer


Can I walk a file path (/foo/bar/baz) backward looking for a particular file in each directory in cmake?

Question: I have a collection of cmake files I use to build a large number of projects. Currently, my cmake code doesn't support nested sub projects. In my build, each project installs its libraries into a top level directory called "devel_artifacts". Since all of the projects are currently at the same level, they each do something like this:
get_filename_component(DEVEL_INSTALL_PATH_PREFIX_ABSOLUTE "../devel_artifacts" ABSOLUTE)
to convert the relative ../devel_artifacts into an absolute path. To support nested sub projects I'd like to write a cmake function that looks in the current directory for devel_artifacts and if it doesn't find it, removes the final directory off the path and tries again... and keeps doing that until it either finds the path to devel_artifacts or fails (in which case it can simply terminate). Is this possible in cmake?
Answer: You can build up a list of search paths starting from your current source dir and adding each parent iteratively, then pass that list to find_file:
set(SearchPath "${CMAKE_CURRENT_SOURCE_DIR}")
while(NOT "${SearchPath}" STREQUAL "${PreviousSearchPath}")
  list(APPEND SearchPaths "${SearchPath}")
  set(PreviousSearchPath "${SearchPath}")
  # use legacy 'PATH' arg instead of 'DIRECTORY' for CMake version <= 2.8.11
  get_filename_component(SearchPath "${SearchPath}" DIRECTORY)
endwhile()

find_file(DevelArtifacts
          NAMES devel_artifacts
          PATHS ${SearchPaths}
          DOC "Path to devel_artifacts found by iterating up through dirs from ${CMAKE_CURRENT_SOURCE_DIR}"
          NO_DEFAULT_PATH)


Terms query(ElasticSearch) not working for some field values

Question: This is my Mapping where i have already declared my required field as keywordbut yet my terms query is not working for category_name and storeName but it is working fine for price.
<code> "mappings": {
            "properties" : {
            "firebaseId":{
            "type":"text"
            },
                "name" : {
                   "type" : "text",
                   "analyzer" : "synonym"

                },
                "name_auto" : {
                "type": "text",

    "fields": {
      "edgengram": {
        "type": "text",
        "analyzer": "edge_ngram_analyzer",
        "search_analyzer": "edge_ngram_search_analyzer"
      },
      "completion": {
        "type": "completion"
      }

    }
                },

                "category_name" : {
                            "type": "text",
                                "fields": {
                                  "keyword": {
                                    "type": "keyword"
                            }
                }
                },
                "storeName" : {
                      "type": "text",
                                "fields": {
                                  "keyword": {
                                    "type": "keyword"
                }
                }
                },
                "sku" : {
                    "type" : "text"
                },
                "price" : {
                    "type": "text",
                        "fields": {
                            "keyword": {
                                "type": "keyword"
                            }
                }
                },
                "magento_id" : {
                    "type" : "text"
                },
                "seller_id" : {
                    "type" : "text"
                },
                "square_item_id" : {
                    "type" : "text"
                },
                "square_variation_id" : {
                    "type" : "text"
                },
                "typeId" : {
                    "type" : "text"
                }
            }
    }
}
}
</code>
This is my query below :
<code>{
  "size": 0,
  "aggs": {
    "Category Filter": {
      "terms": {
        "field": "category_name",
        "size": 10
      }
    },
    "Store Filter": {
      "terms": {
        "field": "storeName",
        "size": 10
      }
    },
    "Price Filter": {
      "range": {
        "field": "price",
        "ranges": [
          {
            "from": 0,
            "to": 50
          },
          {
            "from": 50,
            "to": 100
          },
          {
            "from": 100,
            "to": 200
          }
        ]
      }
    }
  }
}
</code>
which returns as follows :
"reason": {
                "type": "illegal_argument_exception",
                "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [category_name] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead."
Answer: You need to use the <code>.keyword</code> sub-field, like this:
<code>{
  "size": 0,
  "aggs": {
    "Category Filter": {
      "terms": {
        "field": "category_name.keyword",    <-- change this
        "size": 10
      }
    },
    "Store Filter": {
      "terms": {
        "field": "storeName.keyword",        <-- change this
        "size": 10
      }
    },
    "Price Filter": {
      "range": {
        "field": "price",
        "ranges": [
          {
            "from": 0,
            "to": 50
          },
          {
            "from": 50,
            "to": 100
          },
          {
            "from": 100,
            "to": 200
          }
        ]
      }
    }
  }
}
</code>


Proof verification: Number of minimal selfish set.

Question: From the 1996 Putnam B1:

Define a selfish set to be a set which has its own cardinality as an element.  A minimal selfish (m.s.) is a selfish set with no proper subset selfish.  How many subsets of $\{1,2,\dots,n\}$ are m.s.?

My proof is below.  I appreciate comments on the accuracy of the proof, the method I use, and the writing.
Lemma: Let $s$ be a subset of $\{1,2,\dots,n\}$, and let $l$ be the least element in $s$.  $s$ is m.s. iff $l = |s|$.
Proof: If $l = |s|$, $s$ is clearly selfish.  Any proper subset $t$ of $s$ will have cardinality $k < l$, implying that $k$ is not a member of $s$ or $t$, and that $t$ is not selfish.  Hence, $s$ is m.s.
Conversely, if $l \neq |s|$, $s$ is not m.s.  For if $l > |s|$, $s$ is not even selfish.  And if $l < |s|$, there exists a subset $t$ of $s$ with cardinality $l$ and with $l$ a member, making $t$ selfish and hence $s$ not m.s.
Therefore, the number of m.s. subsets of $\{1,2,\dots,n\}$ are precisely the number of subsets whose least element $l$ equals their cardinality.  These subsets can be constructed by:

Choosing any element as $l$
Choosing $l-1$ elements from the remaining $n-l$ elements greater than $l$.  There are ${n-l \choose l-1}$ ways to do this, defining ${n \choose r}$ as 1 if $r=0$ and as 0 if $r>n$.

Therefore, there are $\sum_{l=1}^{n} {n-l \choose l-1}$ m.s. subsets of $\{1,2,\dots,n\}$.
Answer: Your argument is correct, but your final result can be improved:
$$\sum_{\ell=1}^n\binom{n-\ell}{\ell-1}=\sum_{k\ge 0}\binom{n-1-k}k\overset{(*)}=F_n\,,$$
the $n$-th Fibonacci number. (There is a proof of $(*)$ here.)
By the way, you don't have to mention that $\binom{n}0=1$ and $\binom{n}r=0$ if $r>n$: those definitions are standard.


MSSQL database mirroring

Question: Reading over (and then testing out on a test database) the setup for mirroring it appears that one is supposed to leave the mirror database in restoration mode for normal operations.
is this correct?  at whatever point it becomes necessary to initiate the failover (im not using a witness), will the primary database be put into restoration mode?  this seems goofy.
Answer: Yes, mirroring is where transactions are replicated from primary to mirror. So one database will be in restoration mode
Perhaps a read of 2 whitepapers may assist One and Two
Comment: its explicitly mentioned in the second link.  everywhere just says 'restore with noreceovery' but then doesnt mention a) that it should remain in restoration mode or b) why.  thanks!
Comment: b is obvious - so that the master can keep pushing changes into the permanent recovery. THis is how the db is kept in sync. By permanently restoring it.
Comment: i get that its continually replicating the data, it just seems odd that it has to be in restore mode.  if the other server is getting sql queries, why does it have to be 'restored' instead of just shipping the query down to the mirror DB.
Comment: It doesn't ship queries as such: it ships data changes. And it is continual. The effect id that the mirror is never consistent enough to query...
Comment: exactly. The backup mirror is nEVER queried until the primary fails / a switch over happens. Only data changes (log file updates) are shipped and consolidated all the time.
Answer: If you have Enterprise Edition, you can create database snapshots of the mirror, and report off these. But these are point-in-time, and read-only. You need to manually implement some way of rolling them over regularly (creating a new one and deleting the oldest etc), and you must devise some way of redirecting the clients to the new snapshot.
Readable mirrors are coming in SQL 11.

MSSQL database mirroring


Oracle date seems equals

Question: there is a table INCASSO in my database:
CREATE TABLE "GEC_AP"."INCASSO"
("ID_INCASSO" VARCHAR2(50 BYTE) NOT NULL ENABLE,
 "ID_FATTURA" VARCHAR2(50 BYTE) NOT NULL ENABLE,
 "ID_PIANO_RATE" VARCHAR2(22 BYTE) DEFAULT -1 NOT NULL ENABLE,
 "DATA_ESECUZIONE" DATE DEFAULT SYSDATE NOT NULL ENABLE,
 ...)

The primary key includes four fields:
CONSTRAINT "PK_INCASSO" PRIMARY KEY ("ID_INCASSO", "ID_FATTURA", "ID_PIANO_RATE", "DATA_ESECUZIONE")

It seems there is a duplicated record when I run the following query:
select id_incasso, id_fattura, id_piano_rate, data_esecuzione
from incasso
where id_incasso = 'TO_20110521258225'

But with another query, 0 records are extracted:
select id_incasso, id_fattura, id_piano_rate, data_esecuzione, count(*)
from incasso where id_incasso = 'TO_20110521258225'
group by id_incasso, id_fattura, id_piano_rate, data_esecuzione
having count(*) > 1

The database is on Oracle 188.8.131.52.0 and I'm using SQL Developer 18.104.22.168.
In SQL Developer, the date format is:

I would to know if the records are different or there is a format date problem in the editor. If the records are different based on the date, in which part of the date they are different? If it's a format date problem in the editor, how can I fix it?
Comment: And NLS format won't matter. the datatype is date. Second query must've shown the records if the dates were from different century
Comment: Just query dump(id_incasso), dump(id_fattura),... and you will see difference
Comment: It is not necessarily the date.  There could be hidden characters in the string fields as well.
Comment: @Gordon - His second query returned zero rows. why? If records were any different, then second query should've shown it.
Comment: Try changing the date format to `DD-MON-YYYY HH24:MI:SS` - using `RR` might hide that one date is `11 AD` and the other is `2011 AD`.
Comment: @GurV The first and second query aren't equal and dump will show why the first returns several rows. Output of SQL Developer misleading OP.
Comment: @niespolo What happens if you change the group by clause to: `group by trim(id_incasso), trim(id_fattura), trim(id_piano_rate), data_esecuzione` in your second query?
Answer: Change the date format to DD-MON-YYYY HH24:MI:SS and you are likely to see the difference in that the dates have different centuries.
Using RR to format the year can hide that one date is 1911 and the other is 2011
Try:
SELECT TO_CHAR( DATE '2011-01-01', 'RR-MM-DD' ),
       TO_CHAR( DATE '1911-01-01', 'RR-MM-DD' )
FROM   DUAL

Both will output the same although they are different dates and will not be grouped together.
If the dates are still the same then look for additional spaces or other hidden characters in the strings; you can use LENGTH() to check the size of the strings or DUMP() to get the byte values of the contents:
select id_incasso,
       id_fattura,
       LENGTH( id_fattura ) AS f_length,
       id_piano_rate,
       LENGTH( id_piano_rate ) AS pr_length,
       TO_CHAR( data_esecuzione, 'YYYY-MM-DD HH24:MI:SS' ) AS data_esecuzione
from   incasso
where  id_incasso = 'TO_20110521258225'

Comment: The DATE column is unlikely to be the cause of the OP's problem, since the values shown in the results of the first query include the time and are the same for both rows. IMHO, it's the varchar2 columns which are suspect.
Comment: @GurV The `GROUP BY` query would not have returned two rows as it also has a `HAVING COUNT(*) > 1` clause so any unique rows would **not** be shown.
Comment: they're varchars, so trailing spaces should not occur. date does not have milliseconds, or does it, so this answer shows a very reasonable possibility.
Comment: @dlatikay DATE doesn't store milliseconds
Comment: @Boneist it is just as likely that someone input a date as the string `'11-AGO-11'` and oracle converted it (using the `YYYY` or `RR` year mask) and inserted it as `DATE '0011-08-11'` or `DATE '1911-08-11'` (if this is a legacy database that had data entered in the 90's) and the other row is `DATE '2011-08-11'`.
Comment: @dlatikay `VARCHAR2` columns can store a variable number of trailing spaces - you are probably thinking `CHAR` columns which right-pad with trailing spaces.
Comment: @MT0 So, if that's the case, the group by query must've given two rows, but it didn't
Comment: @MT0 ah, now I see where you were coming from; duh - I missed the fact that the years were two digits
Answer: I've changed the date format used in SQL Developer to DD-MON-YYYY HH24:MI:SS
and the following query:
select id_incasso, id_fattura, id_piano_rate, data_esecuzione from incasso where id_incasso = 'TO_20110521258225'

show that the difference is in the year:
Thanks everyone.

Oracle date seems equals


Is it possible to create annotation which would check if user is authenticated? Kotlin

Question: I am writing an app, and some parts of it require the user to be authenticated. Is it possible to write an annotation for a method, which would check user status, and depending on it either function would be called or it would navigate to the login screen -> if login success it will come back and call the function? like this:
<code>@RequiresAuth
fun commentOnTask(){
    ...
}
</code>
Comment: Annotations don't do anything themselves. They provide you a way to do things using reflection. This is not a case where they would help you.
Answer: No, by this time I could not find a way of how to do it with annotation.
The only workaround is to use such a pattern https://codelabs.developers.google.com/codelabs/advanced-android-kotlin-training-login-navigation/index.html?index=..%2F..index#9


Redeliver message to queue on error with Message Driven Bean

Question: I need return a message to the queue when something wrong happend.
I am working with Message Driven Bean on Weblogic 11G (EJB3.0) , Java 1.6, javaee-api 6.0, the queue is on Oracle database (AQJMS)
I dont want send the message to an error queue.
public void onMessage(Message message) {
        try {
            this.processMenssage(message);
        } catch (ServiceInternalException e) {
            // I need return the message to the queue because something wrong (anything) happend
        }
}

I know the message will be recovered again and again until I solve the problem.
The MDB is configured with annotations
@MessageDriven(
    name = "MyBeanMDB",
    activationConfig = {
            @ActivationConfigProperty(propertyName  = "destinationType",
                    propertyValue = "javax.jms.Queue"),

            @ActivationConfigProperty(propertyName  = "connectionFactoryJndiName",
            propertyValue = "AqJms3FSCF"), // External JNDI Name

            @ActivationConfigProperty(propertyName  = "destinationJndiName",
            propertyValue = "myque/REQ_JMSQ") // Ext. JNDI Name
    }
    )
public class MyBeanMDB implements MessageListener{....

And because my driver datasource is oracle.jdbc.xa.client.OracleXADataSource I have a file weblogic-ejb-jar.xml with
<?xml version = '1.0' encoding = 'windows-1252'?>
<weblogic-ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.bea.com/ns/weblogic/weblogic-ejb-jar http://www.bea.com/ns/weblogic/weblogic-ejb-jar/1.0/weblogic-ejb-jar.xsd"
xmlns="http://www.bea.com/ns/weblogic/weblogic-ejb-jar">
<weblogic-enterprise-bean>
    <ejb-name>MyBeanMDB</ejb-name>
    <message-driven-descriptor>
        <pool>
            <max-beans-in-free-pool>1</max-beans-in-free-pool>
            <initial-beans-in-free-pool>1</initial-beans-in-free-pool>
        </pool>
    </message-driven-descriptor>
</weblogic-enterprise-bean>

I tried with setRollbackOnly()
Adding
 @TransactionManagement(value=TransactionManagementType.CONTAINER)
 @TransactionAttribute(TransactionAttributeType.REQUIRED)

and
@Override
public void setMessageDrivenContext(MessageDrivenContext ctx) throws EJBException {
    this.myctx = ctx;
}

and inside exception
public void onMessage(Message message) {
        try {
            this.processMenssage(message);
        } catch (ServiceInternalException e) {
            this.myctx.setRollbackOnly(); // the message is not redelivered
        }
}

The RollbackOnly is invoqued, the log says:
####<Sep 13, 2015 11:40:33 AM ART> <Info> <EJB> <el01cl03> <AdminServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<anonymous>> <> <39d906d31eb822f1:-27a94574:14fc3fbcefe:-8000-0000000000000b8a> <1442155233307> <BEA-010213> <Message-Driven EJB: MyBeanMDB's transaction was rolled back. The transaction details are: Name=NewJMSMessagePoller.MyBeanMDB,Xid=BEA1-2BC2680CDDBA895EF953(294629023),Status=Rolled back. [Reason=weblogic.transaction.internal.AppSetRollbackOnlyException: setRollbackOnly called on transaction],numRepliesOwedMe=0,numRepliesOwedOthers=0,seconds since begin=0,seconds left=60,XAServerResourceInfo[aqjmsuserDS_e2eSOADomain]=(ServerResourceInfo[aqjmsuserDS_e2eSOADomain]=(state=rolledback,assigned=AdminServer),xar=aqjmsuserDS,re-Registered = false),SCInfo[e2eSOADomain+AdminServer]=(state=rolledback),properties=({weblogic.transaction.name=NewJMSMessagePoller.MyBeanMDB}),local properties=({weblogic.jdbc.jta.aqjmsuserDS=[ No XAConnection is attached to this TxInfo ]}),OwnerTransactionManager=ServerTM[ServerCoordinatorDescriptor=(CoordinatorURL=AdminServer+10.10.10.150:7001+e2eSOADomain+t3+, XAResources={eis/tibjms/Queue, NIICommonDS-rac0_e2eSOADomain, eis/activemq/Queue, 10gDataSource_e2eSOADomain, eis/fioranomq/Topic, eis/jbossmq/Queue, eis/Apps/Apps, eis/aqjms/Topic, eis/webspheremq/Queue, eis/AQ/aqSample, eis/tibjms/Topic, eis/aqjms/Queue, eis/aqjms/colasjmsuser3, ITM_e2eSOADomain, eis/sunmq/Queue, WSATGatewayRM_AdminServer_e2eSOADomain, NIICommonDS_e2eSOADomain, eis/jms/ReprocessJMSQueue, eis/tibjmsDirect/Queue, eis/wls/Queue, aqjmsuserDS_e2eSOADomain, eis/tibjmsDirect/Topic, eis/wls/Topic, eis/pramati/Queue, NIICommonDS-rac1_e2eSOADomain, eis/jms/ReprocessJMS11gQueueCF},NonXAResources={})],CoordinatorURL=AdminServer+10.10.10.150:7001+e2eSOADomain+t3+).>

But the state in the queue (AQJMS) after that is 3 (Processed)
maybe the problem is :
 aqjmsuserDS=[ No XAConnection is attached to this TxInfo ]

Comment: If you throw a RuntimeException in your catch block, the message should be redelivered.
Comment: I tried with RuntimeException, but the message was not recovered again.
Comment: Can you provide processMenssage(message) code also ? I am interested to know what exceptions that method might throw ?
Comment: anything in weblogic logs? something may be wrong with transaction, so rollback never happens.
Comment: In the weblogic log I can see the rollback happend, but the MDB do not get again the message  :(
Answer: The problem was the creation of the queue, the queue was creatred like this
BEGIN DBMS_AQADM.CREATE_QUEUE_TABLE(
 Queue_table        => '"JMSUSER"."SALES_JMSQTAB"',
 Queue_payload_type => 'SYS.AQ$_JMS_MESSAGE',
 storage_clause     => 'PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 TABLESPACE USERS',
 Sort_list          => 'PRIORITY,ENQ_TIME',
 Compatible         => '8.1.3');
END;

BEGIN DBMS_AQADM.CREATE_QUEUE(
 Queue_name          => 'JMSUSER.SALES',
 Queue_table         => 'JMSUSER.SALES_JMSQTAB',
 Queue_type          =>  0,
 Max_retries         =>  0,
 Retry_delay         =>  0,
 Retention_time      =>  86400,
 dependency_tracking =>  FALSE);
END;

And the problem with this is the field MAX_RETRIES, when is 0 then no retries (rollback) are permited.
A better way to create a queue is :
BEGIN DBMS_AQADM.CREATE_QUEUE_TABLE(
 Queue_table        => 'JMSUSER.SALES_JMSQTAB',
 Queue_payload_type => 'SYS.AQ$_JMS_MESSAGE',
 storage_clause     => 'PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 TABLESPACE USERS',
 Sort_list          => 'PRIORITY,ENQ_TIME',
 Compatible         => '8.1.3');
END;

BEGIN DBMS_AQADM.CREATE_QUEUE(
 Queue_name          => 'JMSUSER.SALES_JMSQTAB',
 Queue_table         => 'JMSUSER.SALES_QTAB',
 Queue_type          =>  0,
 Max_retries         =>  2147483647,
 Retry_delay         =>  5,
 Retention_time      =>  259200,
 dependency_tracking =>  FALSE);
END;

Answer:
Can you check the below code helps which handles java.lang.Exception
  as well, which catches non-ServiceInternalExceptions. Also add a
  logger to actually find that this exception has been caught:

    public void onMessage(Message message) {
     try {
        this.processMenssage(message);
     } catch (ServiceInternalException e) {
        Logger.error(e);
        this.myctx.setRollbackOnly();
     } catch (Exception e) {
        Logger.error(e);
        this.myctx.setRollbackOnly();
     }
  }


Can a violin imitate the sound of an Erhu?

Question: I don't know if this is "impossible" due to the different construction of the two instruments, but do you know if the violin can imitate the sound of the Chinese erhu? Here is a YouTube video for reference. I just love the sound of this instrument and was wanting to see if I could add this sound to my technique on the violin.
Answer: Yes and no.  Yes, you can imitate the erhu style of playing on the violin: lots of glissandi, lots of vibrato on certain notes, very quick appoggiaturas, pentatonic melodies, and so forth.  What you can't so easily imitate is the tone color: since the erhu has a snakeskin belly and silk strings (at least traditionally), it sounds different from a violin.
Comment: The erhu seems to have a subtly softer, more nasal timbre that could maybe be approximated with a mute (Con sordino)? There seems to be a variety of mutes available, both in terms of design and material, so one might fit the bill.
Comment: @ABragg- I'm sure you're right.  But I don't know how close you could get.  It's worth experimenting with for sure.
Comment: Mutes damp down the body resonance of the violin and therefore make the instrument quieter, but "good" mutes don't change the basic tone quality as much as "poor" ones. But "poor" ones tend to give a nasal sound, which seems to be going in the wrong direction for imitating an erhu sound.
Comment: @ScottWallace I thought it would be near impossible to imitate the tonal texture of the erhu because of its build. Would silk strings work on a violin?
Comment: @Briard- well, of course it depends on what is close enough to count as "imitation".  I suspect that nothing you could do to a violin without electronic help is going to make it sound so much like an erhu that it will fool experts. It's not just the tone color- due to the construction with the bow hair between the two strings, there are kinds of articulation possible that I doubt are perfectly fakeable on a violin.  But as I said, I bet you could get pretty close.  ABragg's suggestion of trying different mutes is a good one, and yes- you could use silk strings- violins used to have them.
Comment: The problem is finding silk strings of the right diameter.  But nowadays, most erhu players use steel and wound steel strings anyway, so that is not a problem, if you are trying to imitate modern erhu players.
Answer: You might get closer with an electric violin, and some sound processing.
With an acoustic violin, the tone depends mainly on the vibration response both of the wooden body of the instrument and the air cavity inside the body, which are both completely different from the erhu.
Filling the violin body with acoustic wadding (used to damp the air resonance in loudspeaker cabinets, etc) might work, but inserting and removing the wadding through the sound holes could be difficult, and taking the violin apart just to try to experiment is a bit drastic, even if you are a luthier and have the capability to do it yourself!
Comment: I actually have a "spare" violin that a music store appraised for a "violin shaped object.  :P I could try what you said with that.