Defining traits for templatised classes

Question: I understand how to create type traits and then specialise for a particular class, but in my case I would like to specialise for a class template. The code below does not compile, but the idea is that the specialisation of Traits for MyTemplatisedClass should work for which ever type the user decides to use with MyTemplatisedType.
class Traits
{
public:
    static bool someProperty(void) { return false; }
};

template<typename Type>
class MyTemplatisedClass
{
};

template<typename Type>
template<>
class Traits< MyTemplatisedClass<Type> >
{
public:
    static bool someProperty(void) { return true; }
};

int main(int argc, char* argv[])
{
    std::cout << Traits< MyTemplatisedClass<float> >::someProperty() <<std::endl; //This should be true
    return 0;
}

Is this possible or am I asking too much? According to the compiler the first problem is
error C2989: 'Traits' : class template has already been declared as a non-class template

Which is correct, but how do I fix this? If it makes any difference I don't need it to work for non-templatised classes, just templatised ones is fine. Edit: Actually it would be nice if it worked for both templatised and non-templatised classes.
Answer: Traits needs to be a template in order to be specialized.
In the specialization drop the line with empty <>: this isn't a template nested within a template or something.
template <typename Type> //can only specialize templates
class Traits
{
public:
    static bool someProperty(void) { return false; }
};

template<typename Type>
class MyTemplatisedClass
{
};

template<typename Type>
//template<>  //Too much here
class Traits< MyTemplatisedClass<Type> >
{
public:
    static bool someProperty(void) { return true; }
};

But if you meant the specialization for any template with one type argument, then that would be:
template < template <class> class SomeTemplatizedType, class Type>
//         ^^^^^^^^^^^^^^^^^^^^^^
//         names a template, not type
class Traits< SomeTemplatizedType<Type> >;
//            ^^^^^^^^^^^^^^^^^^^   ^
//             template name        |
//                               argument

Comment: Thanks guys, you've all given the right answer but I can only accept one. I'm going to go with UncleBens for the extra information provided.
Comment: @UncleBens: Could you maybe provide examples for both cases. I don't quite understand what the difference is or what you mean by specializing "any" template with one argument.
Answer: The initial class needs to be the "base case", that is, templated to accept any type argument. Then you can worry about what other specializations you'd like to invoke.
template<typename T> class Traits
{
public:
    static bool someProperty(void) { return false; }
};

template<typename Type>
class MyTemplatisedClass
{
};

template<typename Type> class Traits< MyTemplatisedClass<Type> >
{
public:
    static bool someProperty(void) { return true; }
};

In order to actually use this in compile-time computation, you will need to make it an ICE- integral constant expression. A function cannot be constexpr even if, trivially, it's value is knowable at compile-time. As it stands, I cannot do, for example,
template<typename T> std::enable_if<Traits<T>::value, sometype> somefunc();

Comment: Thanks guys, you've all given the right answer but I can only accept one. I'm going to go with UncleBens for the extra information provided.
Answer: The problem is that you've declared Traits as a class, not a class template. Just add template<typename> to the definition of Traits, and remove the spurious template<> from the specialisation and it should be fine.
template<typename>             // <--- Add this
class Traits
{
public:
    static bool someProperty(void) { return false; }
};

template<typename Type>
class MyTemplatisedClass
{
};

template<typename Type>
// template<>                 // <--- Remove this
class Traits< MyTemplatisedClass<Type> >
{
public:
    static bool someProperty(void) { return true; }
};

int main(int argc, char* argv[])
{
    std::cout << Traits< MyTemplatisedClass<float> >::someProperty() <<std::endl; //This should be true
    return 0;
}

Comment: Thanks guys, you've all given the right answer but I can only accept one. I'm going to go with UncleBens for the extra information provided.

Defining traits for templatised classes


MySQL: creating a user that can connect from multiple hosts

Question: I'm using MySQL and I need to create an account that can connect from either the localhost or from another server, i.e. 10.1.1.1. So I am doing:
CREATE USER 'bob'@'localhost' IDENTIFIED BY 'password123';
CREATE USER 'bob'@'10.1.1.1' IDENTIFIED BY 'password123';
GRANT SELECT, INSERT, UPDATE, DELETE on MyDatabse.* to 'bob'@'localhost', 'bob'@'10.1.1.1';

This works fine, but is there any more elegant way to create a user account that is linked to multiple IPs or does it need to be done this way?
My main worry is that in the future, permissions will be updated for one 'bob' account but not the other.
Answer: If you want to restrict to host and do not want to specify based on a subnet or wildcard using %, that's the only way to do it.  More details are available in the MySQL documentation.
I am still trying to find ways to eliminate overhead when managing authentication to large MySQL installations and have yet to find a perfect solution.
Comment: You can also add multiple privilege entries which allows you to specify multiple IP addresses.  I missed that the OP was able to succeed using this method and wanted to be sure others didn't miss it as well.
Answer: Let's start by making a new user called "chaminda" within the MySQL shell:
CREATE USER 'chaminda'@'%' IDENTIFIED BY 'password';

The first thing to do is to provide the user with necessary permission and here I have given all permission to the particular user.
GRANT ALL PRIVILEGES ON * . * TO 'chaminda'@'%';

Reload all the privileges.
FLUSH PRIVILEGES;

If you want to allow range of IPs to a particular user use as follows 10.1.1.%
GRANT ALL PRIVILEGES ON * . * TO 'chaminda'@'10.1.1.%';

Note: Here host Name = % and that means you can access this database server from any host. Granting all privileges to the user is a big risk and that's not a best practice. Further you can replace user 'chaminda' to 'bob'.
Comment: This doesn't answer the question. It grants access to a user from all IPs, but the OP is asking about a more elegant way to allow a single user to access the database from a list of IPs. Basically, instead of multiple statements to add a user multiple times from multiple IPs, the idea is to add a single user that can access the database from multiple IPs, which makes management easier and less error prone.
Comment: You can also use _ as a wildcard like 10.1.1.1__ to match 100 -199 but for 200 you need to create a seperate account or use the % wildcard and include 0-99 and 201-255 too
Answer: Warner's answer can be refined by using CIDR ranges in your user specification (in 'network'/'netmask' notation),  eg:
CREATE USER 'bob'@'10.0.0.0/255.0.0.0' IDENTIFIED BY 'password123';
CREATE USER 'bob'@'192.168.0.0/255.255.255.192' IDENTIFIED BY 'password123';
This construct allows finer-grained access control.  Warner's answer will allow user 'bob' to connect from any host, anywhere on your network (or from any host on the public internet, if your server is exposed to the public network), which is probably not going to suit all use cases.
It is accepted practice to apply "Defence in Depth", which is furthered by limiting user access from desired and trusted host addresses only.  Also remember to limit incoming connections at a host level by reflecting the desired and trusted host addresses in your host-based firewall (eg. iptables, firewalld, etc).
Answer: MySQL allows multiple wildcards in one row. A possible solution is to set Host for user Bob to be
locahost/10.1.1.1
Reference:
http://dev.mysql.com/doc/refman/5.1/en/connection-access.html
Comment: That is not what the documentation is saying. As listed in the table, the /255.255.255.0 is a netmask. If there is a way to list multiple wildcards in the host definition, that isn't the way to do it.


Reparameterized Surface Changes First Fundamental Form

Question: Suppose $q(r, \theta)$ is a parameterized surface with first fundamental form given as a matrix as
$\begin{bmatrix}
g_{rr} & g_{r\theta} \\
g_{r\theta} & g_{\theta\theta}
\end{bmatrix}
=\begin{bmatrix}
1 & 0 \\
0 & r^2
\end{bmatrix}$
I am asked to show that it is possible to reparameterize $q$ in terms of two other parameters $u,v$ so that we can instead write:
$\begin{bmatrix}
g_{uu} & g_{uv} \\
g_{uv} & g_{vv}
\end{bmatrix}
=\begin{bmatrix}
1 & 0 \\
0 & 1
\end{bmatrix}$.
Now I know how to compute the first fundamental form. What I don't know is how to work out what to write for $u$ and $v$. Help is appreciated.
Answer: Supposed that you define
$$
h(r, \theta) = q(r, \frac{\theta}{r}).
$$
Now $h_{\theta\theta}$ becomes 1, right? What about the other entries of the form?
Doing substitution tricks like this can often help to "fix up" the first fundamental form, at least locally. (Obviously this is useless at $r = 0$, but your first parameterization is invalid there to, so it's probably OK.)
I just realized that in this context, it's not clear what $u$ and $v$ are. I should have written
$$
h(u, v) = q(u, \frac{v}{u}).
$$
Comment: And the first parameterization is invalid at $r=0$ because that implies $\frac{\partial q}{\partial \theta} =0$, which is impossible, yes?
Comment: Yes -- the first fundamental form must have nonzero determinant for the parameterization to be one that's suitable for doing the rest of the differential geometry calculations. (We often divide by $\det g$). Thus $(u, v) \mapsto (u^3, v^3, 0)$ is an invalid parameterization of the $xy$-plane in 3-space, even though it's a bijection and differentiable.


Evaluation of product limit

Question:
$\prod_{n=2}^{\infty} \left(1- \dfrac1 {n^2}\right)= ?$

Attempt:
Simplified it to $\dfrac{(n-1)(n+1)}{n^2}$ , and then wrote some terms to observe the cancelllation pattern, but that didn't help, how to solve it then?
Comment: Hint: Use your simplified form to show
$$\prod_{n=2}^{m} \left(1- \dfrac1 {n^2}\right)= \frac{1}{2}\frac{\Gamma(m)\Gamma(m+2)}{\Gamma(m+1)^2}$$
Answer: Are you allowed to use Euler's infinite product formula for sine? $$\sin x = x \prod_{n=1}^{\infty} \left(1-\frac{x^2}{n^2 \pi^2}\right)$$

Evaluation of product limit


Postgresql does seq_scan when the index applies. Why?

Question: I have a query with a join on a varchar(24) primary key.  The reasons for this being a key are legacy and targeted for change.  However, the postgresql query planner insists on doing a sequential scan which seems unreasonable to me.  I back up my claim of "unreasonable" with the fact that "SET enable_seqscan = off" speeds up this query by a factor of 8.
I've run "vacuum analyze"; I've played with statistics settings, but have had no luck so far.
The query is
select inventry.id, inventry.count, sum(invenwh.count)
from invenwh join inventry on inventry.id=invenwh.id
where inventry.product_c='CAT17'
group by 1, 2;

The following sets up the database for running this query.
drop table if exists inventry;
drop table if exists inwh;
drop table if exists invenwh;
drop table if exists inprodcategory;

-- Create 50 product categories.
create table inprodcategory as
select i as id, concat('CAT', lpad(i::text, 2, '0'))::varchar(10) as category
from generate_series(1, 50, 1) as i;

-- Create 245,000 inventory items
create table inventry as
select
    concat('ITEM', lpad(i::text, 6, '0'))::varchar(24) as id,
    concat('Item #', i::text)::varchar(50) as descr_1,
    c.category as product_c,
    (case when random() < 0.05 then (random()*70)::int else 0::int end) as count
from generate_series(1, 245000, 1) as i
    join inprodcategory as c on c.id=(i%50)::int;

-- Create 70 warehouses
create table inwh as
select concat('WAREHOUSE', lpad(i::text, 2, '0'))::varchar(10) as warehouse
from generate_series(1, 70, 1) as i;

-- Create (ugly) cross-join table with counts/warehouse
create table invenwh as
select id, warehouse,
    (case when random() < 0.05 then (random()*10)::int else 0::int end) as count
from inventry, inwh;

create index on invenwh (id);
create index on inventry (id);

After running the above, you can run the query.  On my hardware with an SSD, i7 and 16gb of ram, it takes 4 seconds, but if I run "set enable_seqscan=off", it takes about 500ms.
Edit:  add explain(analyze, buffers)
HashAggregate  (cost=449773.25..449822.25 rows=4900 width=19) (actual time=4180.006..4181.092 rows=4900 loops=1)
  Group Key: inventry.id, inventry.count
  Buffers: shared hit=4526 read=121051
  ->  Hash Join  (cost=5058.50..447200.75 rows=343000 width=19) (actual time=1285.800..4086.398 rows=343000 loops=1)
        Hash Cond: ((invenwh.id)::text = (inventry.id)::text)
        Buffers: shared hit=4526 read=121051
        ->  Seq Scan on invenwh  (cost=0.00..291651.00 rows=16807000 width=15) (actual time=0.077..1949.843 rows=16807000 loops=1)
              Buffers: shared hit=2530 read=121051
        ->  Hash  (cost=4997.25..4997.25 rows=4900 width=15) (actual time=48.897..48.897 rows=4900 loops=1)
              Buckets: 1024  Batches: 1  Memory Usage: 230kB
              Buffers: shared hit=1996
              ->  Seq Scan on inventry  (cost=0.00..4997.25 rows=4900 width=15) (actual time=21.903..47.031 rows=4900 loops=1)
                    Filter: ((product_c)::text = 'CAT17'::text)
                    Rows Removed by Filter: 235200
                    Buffers: shared hit=1996
Planning time: 4.266 ms
Execution time: 4181.395 ms

Edit:  Specific follow-up questions
Thanks to @a_horse_with_no_name  (big thank you!!) it seems like lowering random_page_cost is the thing to do.  This seems more-or-less in agreement with https://wiki.postgresql.org/wiki/Tuning_Your_PostgreSQL_Server
Q:  Is there any benchmark I can run to discover optimal values for random_page_cost?  In production, I'm on a SCSI disk (LSI MR9260-8i).
Q:  I feel like statistics may also be relevant here, but I'm coming up empty on a pg-stats-for-dummies type page on the internet.  Any hints on learning about stats?
Comment: please show us the output of `explain (analyze, buffers)`.
Comment: I think he means the id column on invenwh
Comment: @a_horse_with_no_name I have an index on product_c in production, but the seq_scan on invenwh (17M records) is killing me on this and other queries.
Comment: I also don't get the hash join, Postgres chooses the nested loop on my configuration. When I run this with `set enable_hashjoin=off` I also get terrible execution times. What is your setting for `random_page_cost` and `work_mem`?
Comment: @a_horse_with_no_name oh, and David guessed correctly about the desired index.  The seq_scan on inventry is acceptable to me (at this point) and this completes with-in 500ms even with a seq_scan on inventry for me as well.
Comment: @a_horse_with_no_name Pretty much system defaults for PG9.4.0 -- random_page_cost = 4.0; work_mem=4MB
Comment: @a_horse_with_no_name  aha, you are on to something! if I change random_page_cost to 2.0 which seems in keeping with having an SSD I get the query plan which uses the invenwh(id) index and the ~500ms query time.
Comment: Yes, with a SSD you should lower your `random_page_cost` at least to `2.0`. I'm running with `1.5`:
Comment: For the primary keys, I would at least force a unique index.
Answer: When the costs estimated by the planner don't match the reality of the execution time, cost settings should be adjusted to better match your hardware.
The various knobs are documented at Planner Cost Constants.
In particular there is this advice on random_page_cost that's relevant to your case:

Storage that has a low random read cost relative to sequential, e.g.
  solid-state drives, might also be better modeled with a lower value
  for random_page_cost.

See also Random Page Cost Revisited for more tuning advice on this parameter with 5 different storage types.
TL;DR: for an SSD, try first 1.5 for random_page_cost .
Comment: Thanks for the links; verbal credit here to @a_horse_with_no_name for the comments on original question as well.


How do I count the number of wins for each, X and O for my program in java?

Question: So I've been trying to figure out a way to count each time someone wins in a tic tac toe GUI game I am making. I already made methods to check the tic tac toe board for any winning combinations for either X or O. I am just stumped on how I could count each time the checkWinsX and checkWinsO are called. I tried to make another method that would add a point to either X or O, but I kinda failed at that lol.
public class ticTacToeFrame extends javax.swing.JFrame {
int turn = 0; //Deterines the turn
int winsX; //Tracks total wins for X
int winsO; //Tracks total wins for O

public ticTacToeFrame() {
    initComponents();
}

public void clearAll() {
    ulBUT.setText("");
    umBUT.setText("");
    urBUT.setText("");
    mlBUT.setText("");
    centerBUT.setText("");
    mrBUT.setText("");
    llBUT.setText("");
    lmBUT.setText("");
    lrBUT.setText("");
    statusTF.setText("");
}

////////////////////////////////////////////////////////////////////////
// I tried to make something of this sort multiple times here to count the checkWins, and so far this is the one that would seem to start off the best in my head
////////////////////////////////////////////////////////////////////////
public static int wins() {
    int winsX = 0;
    int winsO = 0;

}

public void checkWinX(int wins) {
    //Top row horizontal check for winning
    if (ulBUT.getText().equals("X") &&  umBUT.getText().equals("X") && urBUT.getText().equals("X")) {
        statusTF.setText("X Wins Horizontally In The Top Row!");
    }
    //Middle row horizontal check for winning
    else if (mlBUT.getText().equals("X") &&  centerBUT.getText().equals("X") && mrBUT.getText().equals("X")) {
        statusTF.setText("X Wins Horizontally In The Middle Row!");
    }
    //Bottom row horizontal check for winning
    else if (llBUT.getText().equals("X") &&  lmBUT.getText().equals("X") && lrBUT.getText().equals("X")) {
        statusTF.setText("X Wins Horizontally In The Bottom Row!");
    }
    //Diagonal check for winning
    else if (ulBUT.getText().equals("X") &&  centerBUT.getText().equals("X") && lrBUT.getText().equals("X")) {
        statusTF.setText("X Wins Diagonnaly!");
    }
    else if (urBUT.getText().equals("X") &&  centerBUT.getText().equals("X") && llBUT.getText().equals("X")) {
        statusTF.setText("X Wins Diagonnaly!");
    }
}

public void checkWinO() {
    //Top row horizontal check for winning
    if (ulBUT.getText().equals("O") &&  umBUT.getText().equals("O") && urBUT.getText().equals("O")) {
        statusTF.setText("O Wins Horizontally In The Top Row!");
    }
    //Middle row horizontal check for winning
    else if (mlBUT.getText().equals("O") &&  centerBUT.getText().equals("O") && mrBUT.getText().equals("O")) {
        statusTF.setText("O Wins Horizontally In The Middle Row!");
    }
    //Bottom row horizontal check for winning
    else if (llBUT.getText().equals("O") &&  lmBUT.getText().equals("O") && lrBUT.getText().equals("O")) {
        statusTF.setText("O Wins Horizontally In The Bottom Row!");
    }
    //Diagonal check for winning
    else if (ulBUT.getText().equals("O") &&  centerBUT.getText().equals("O") && lrBUT.getText().equals("O")) {
        statusTF.setText("O Wins Diagonnaly!");
    }
    else if (urBUT.getText().equals("O") &&  centerBUT.getText().equals("O") && llBUT.getText().equals("O")) {
        statusTF.setText("O Wins Diagonnaly!");
    }
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    ulPAN = new javax.swing.JPanel();
    ulBUT = new javax.swing.JButton();
    umBUT = new javax.swing.JButton();
    urBUT = new javax.swing.JButton();
    mlBUT = new javax.swing.JButton();
    centerBUT = new javax.swing.JButton();
    mrBUT = new javax.swing.JButton();
    llBUT = new javax.swing.JButton();
    lmBUT = new javax.swing.JButton();
    lrBUT = new javax.swing.JButton();
    statusTF = new javax.swing.JTextField();
    oWinsTF = new javax.swing.JTextField();
    xWinsTF = new javax.swing.JTextField();
    resetGameBUT = new javax.swing.JButton();
    turnTF = new javax.swing.JTextField();
    tiesTF1 = new javax.swing.JTextField();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Tic Tac Toe | John Gironda");
    setBackground(new java.awt.Color(87, 87, 87));

    ulPAN.setLayout(new java.awt.GridLayout(3, 3));

    ulBUT.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            ulBUTActionPerformed(evt);
        }
    });
    ulPAN.add(ulBUT);

    umBUT.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            umBUTActionPerformed(evt);
        }
    });
    ulPAN.add(umBUT);

    urBUT.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            urBUTActionPerformed(evt);
        }
    });
    ulPAN.add(urBUT);

    mlBUT.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            mlBUTActionPerformed(evt);
        }
    });
    ulPAN.add(mlBUT);

    centerBUT.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            centerBUTActionPerformed(evt);
        }
    });
    ulPAN.add(centerBUT);

    mrBUT.setToolTipText("");
    mrBUT.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            mrBUTActionPerformed(evt);
        }
    });
    ulPAN.add(mrBUT);

    llBUT.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            llBUTActionPerformed(evt);
        }
    });
    ulPAN.add(llBUT);

    lmBUT.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            lmBUTActionPerformed(evt);
        }
    });
    ulPAN.add(lmBUT);

    lrBUT.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            lrBUTActionPerformed(evt);
        }
    });
    ulPAN.add(lrBUT);

    statusTF.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            statusTFActionPerformed(evt);
        }
    });

    oWinsTF.setText("Total O Wins: 0");
    oWinsTF.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            oWinsTFActionPerformed(evt);
        }
    });

    xWinsTF.setText("Total X Wins: 0");
    xWinsTF.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            xWinsTFActionPerformed(evt);
        }
    });

    resetGameBUT.setText("RESET");
    resetGameBUT.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            resetGameBUTActionPerformed(evt);
        }
    });

    turnTF.setText("Turn: X");
    turnTF.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            turnTFActionPerformed(evt);
        }
    });

    tiesTF1.setText("Total Ties: 0");
    tiesTF1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            tiesTF1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(16, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                .addComponent(ulPAN, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(statusTF)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(xWinsTF, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addComponent(turnTF, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(tiesTF1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(oWinsTF, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(resetGameBUT, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(16, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(16, 16, 16)
                    .addComponent(ulPAN, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addGap(154, 154, 154)
                    .addComponent(resetGameBUT, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(xWinsTF, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(statusTF, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(oWinsTF, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(tiesTF1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addGap(30, 30, 30)
                    .addComponent(turnTF, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(16, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>

private void ulBUTActionPerformed(java.awt.event.ActionEvent evt) {
    if (ulBUT.getText().equals("")) {
        if (turn % 2 == 0) {
        ulBUT.setText("X");
        } else {
            ulBUT.setText("O");
        }
        turn++;
        checkWinX();
        checkWinO();
    }
}

private void umBUTActionPerformed(java.awt.event.ActionEvent evt) {
    if (umBUT.getText().equals("")) {
        if (turn % 2 == 0) {
        umBUT.setText("X");
        } else {
            umBUT.setText("O");
        }
        turn++;
        checkWinX();
        checkWinO();
    }
}

private void urBUTActionPerformed(java.awt.event.ActionEvent evt) {
    if (urBUT.getText().equals("")) {
        if (turn % 2 == 0) {
        urBUT.setText("X");
        } else {
            urBUT.setText("O");
        }
        turn++;
        checkWinX();
        checkWinO();
    }
}

private void mlBUTActionPerformed(java.awt.event.ActionEvent evt) {
    if (mlBUT.getText().equals("")) {
        if (turn % 2 == 0) {
        mlBUT.setText("X");
        } else {
            mlBUT.setText("O");
        }
        turn++;
        checkWinX();
        checkWinO();
    }
}

private void centerBUTActionPerformed(java.awt.event.ActionEvent evt) {
    if (centerBUT.getText().equals("")) {
        if (turn % 2 == 0) {
        centerBUT.setText("X");
        } else {
            centerBUT.setText("O");
        }
        turn++;
        checkWinX();
        checkWinO();
    }
}

private void mrBUTActionPerformed(java.awt.event.ActionEvent evt) {
    if (mrBUT.getText().equals("")) {
        if (turn % 2 == 0) {
        mrBUT.setText("X");
        } else {
            mrBUT.setText("O");
        }
        turn++;
        checkWinX();
        checkWinO();
    }
}

private void llBUTActionPerformed(java.awt.event.ActionEvent evt) {
    if (llBUT.getText().equals("")) {
        if (turn % 2 == 0) {
        llBUT.setText("X");
        } else {
            llBUT.setText("O");
        }
        turn++;
        checkWinX();
        checkWinO();
    }
}

private void lmBUTActionPerformed(java.awt.event.ActionEvent evt) {
    if (lmBUT.getText().equals("")) {
        if (turn % 2 == 0) {
        lmBUT.setText("X");
        } else {
            lmBUT.setText("O");
        }
        turn++;
        checkWinX();
        checkWinO();
    }
}

private void lrBUTActionPerformed(java.awt.event.ActionEvent evt) {
    if (lrBUT.getText().equals("")) {
        if (turn % 2 == 0) {
        lrBUT.setText("X");
        } else {
            lrBUT.setText("O");
        }
        turn++;
        checkWinX();
        checkWinO();
    }
}

private void resetGameBUTActionPerformed(java.awt.event.ActionEvent evt) {
    clearAll();
}

private void statusTFActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
}

private void xWinsTFActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
}

private void oWinsTFActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
}

private void turnTFActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
}

private void tiesTF1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
}

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(ticTacToeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(ticTacToeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(ticTacToeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(ticTacToeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new ticTacToeFrame().setVisible(true);
        }
    });
}

// Variables declaration - do not modify
private javax.swing.JButton centerBUT;
private javax.swing.JButton llBUT;
private javax.swing.JButton lmBUT;
private javax.swing.JButton lrBUT;
private javax.swing.JButton mlBUT;
private javax.swing.JButton mrBUT;
private javax.swing.JTextField oWinsTF;
private javax.swing.JButton resetGameBUT;
private javax.swing.JTextField statusTF;
private javax.swing.JTextField tiesTF1;
private javax.swing.JTextField turnTF;
private javax.swing.JButton ulBUT;
private javax.swing.JPanel ulPAN;
private javax.swing.JButton umBUT;
private javax.swing.JButton urBUT;
private javax.swing.JTextField xWinsTF;
// End of variables declaration

}
Answer: I have to tell you you are going about this all wrong. Start with a GameModel
public class TicTacToeModel {
  Boolean[][] board; //use Boolean class rather than boolean primative so you can set board spaces that haven't been taken yet null
  public void setSpace (int x, int y, boolean isX) throws SpaceTakenException { ... }
  public boolean getSpace(int x, int y) { ... }
  public Boolean calculateWinner() { ... } // calculate if there's a winner, and return its Boolean value if so. Otherwise null
}

Once that's done and working, you can adapt a GUI to your model.
Answer: In your wins() method, you could pass in a parameter indicating X or O and increment the respective counter variable.
For example:
public int win(int player) {
    if(player == 0) {
        winsX++;
    }
    else {
        winsY++;
    }
}

And then call this every time you check and find that a player has won.


how to make auto fill field in wordpress login form using "theme my login" plugin?

Question: I have created a login form using  plugin "theme my login" in wordpress. I would like to make a field in login form in which if some one registering as new user then according to provide details of registering user the consequent field must be auto filled if any data match with any previous created user.
For example : There is two field in login form first " Introducer" and second "Introducer ID" if new user filled Introducer "ABCD" and if "ABCD" is already existed in user data as "username" then consequent fieled i.e. "Introducer ID"  will automatically filled by existed User ID form user data base. If That "Introducer" text is not available in user data then error message displays that introducer not exists.
Answer: You could use theme-my-login template in order to add code :

Copy wp-content/plugins/theme-my-login/templates/login-form.php in your wordpress theme folder root (the plugin will check your theme path before the plugin path).
Add your code to get your current_user meta data ( check get_user_meta(); )
Check if user has already this value with WP_user_Query :
$user_query = new WP_User_Query( array( 'meta_key' => 'country',
   'meta_value' => 'France' ) );

Hope it will help you !


Add a wrapper around two panes

Question:
I want to add a wrapper around the panes which are shown in red box in the given image. How to achieve it.
I have already tried Panels Extra Styles module but it is not providing a wrapper around two or more panes.
Comment: possible duplicate of [Panels content wrapper](http://drupal.stackexchange.com/questions/52045/panels-content-wrapper) If you're not happy with the previous answer then you need to explain why yours is different. And: "Didn't work" is not enough.
Comment: The panel extra styles is making one pane id div as child div of other pane id but it is not wrapping the both panes.I want a parent div wrapping two panes.
Answer: Create mini Panel, and add that. In mini panel you give classes, so you can wrap a class.
Answer: You can do it with panels extra styles module, and fences module, here is an image explaining how to do it. wrapper div image, both modules are avilable for D7 and D8
Comment: That didn't explain it at all FYI
Comment: Complete Answer: https://drupal.stackexchange.com/a/81963/10316
Comment: See also my answer without using additional modules: https://drupal.stackexchange.com/a/261082/10316

Add a wrapper around two panes


Convolution equality

Question: If $k$ is an squared or absolutely integrable kernel are the belo equalities true ?
 $$z(s)=\int_{R}^{} \! k(u-d) x(u).du \ \ =\int_{R}^{} \! k(u+d) x(u).du \ \ $$
and
$$\int_{R}^{} \! k(u-d) k(u-d^{'}).du \ \ =\int_{R}^{} \! k(d-u) k(d^{'}-u).du \ \ $$
Comment: There is at least one typo (perhaps $z(d)$). Simple answer is no.
Answer: Consider $k(u) = \delta(u)$ the delta function. If you do not like this, you can find a sequence of smooth rapidly decaying functions that approximate it. Then, $\int k(u-d) x(u) du = x(d)$ while $\int k(u+d) x(u) du = x(-d)$, assuming $x$ is integrable.
The other one will hold if the kernel is symmetric.

Convolution equality


How do I make a python scrip to alphabetize these files. They are little complicated

Question: I have a file with text like this and would like it to be sorted first numerically and second alphabetically. I would like to make a python script for this but have failed.
Each of the items has a name which begins with a 't'.
This is an example of the file currently:
t24KAssetType =
    (I1    (11)    "boats and boating equipment",
     I2    (12)    "bicycles",
     I3    (13)    "caravans, motorhomes, or trailers",
     I4    (14)    "sporting equipment",
     I5    (15)    "musical instruments",
     I6    (16)    "cameras and photographic equipment",
     I7    (17)    "hobby equipment")

t1Mths10Yrs =
    (I1     "12 months",
     I2     "10 years")

tQAnotherSourceIncome =
        (I1     "Enter up to 5",
         I2     " ")

tDAllExpensesComma  =
        (I1     "after deducting all expenses,",
         I2     "")

tKExpenses =
        (I1     " <underline> after</underline> expenses such as rates and insurance",
         I2     "")

tAgain =
        (I1    " again",
         I2    "")

tLots_Looking =
        (I1    "Again, looking",
         I2    "Looking")

tApe_Remember =
        (I1     "<BlueLight22>IF NECESSARY:</BlueLight22> Again",
        I2      "Remember")

tzoo =
        (I1    " and ",
         I2    "")

tPool =
        (I1     "Apart from any owned or leased by the business or farm you work for, do",
         I2     "Do")

tStuff =
        (I1  (11)  "jewellery",
        I2   (12) "art works",
        I3   (13) "antiques",
        I4   (14) "collectibles",
        I5   (15) "other collectibles")

And here is an example of how i would like it to look:
t1Mths10Yrs =
    (I1     "12 months",
     I2     "10 years")

t24KAssetType =
    (I1    (11)    "boats and boating equipment",
     I2    (12)    "bicycles",
     I3    (13)    "caravans, motorhomes, or trailers",
     I4    (14)    "sporting equipment",
     I5    (15)    "musical instruments",
     I6    (16)    "cameras and photographic equipment",
     I7    (17)    "hobby equipment")

tAgain =
        (I1    " again",
         I2    "")

tApe_Remember =
        (I1     "<BlueLight22>IF NECESSARY:</BlueLight22> Again",
        I2      "Remember")

tDAllExpensesComma  =
        (I1     "after deducting all expenses,",
         I2     "")

tKExpenses =
        (I1     " <underline> after</underline> expenses such as rates and insurance",
         I2     "")

tLots_Looking =
        (I1    "Again, looking",
         I2    "Looking")

tPool =
        (I1     "Apart from any owned or leased by the business or farm you work for, do",
         I2     "Do")

tQAnotherSourceIncome =
        (I1     "Enter up to 5",
         I2     " ")

tStuff =
        (I1  (11)  "jewellery",
        I2   (12) "art works",
        I3   (13) "antiques",
        I4   (14) "collectibles",
        I5   (15) "other collectibles")

tzoo =
        (I1    " and ",
         I2    "")

Can anyone help please?
Comment: Can you please format the code correctly?
Answer: You could try this:
with open('input.txt', 'rt') as file:
    text = []
    block = ''
    for line in file:
        if (line.lstrip().startswith('t')
            and line.rstrip().endswith('=')):  # Start of new item-block
            if block:
                text.append(block)
            block = ''
        block += line
    text.append(block.rstrip() + '\n\n')  # Special treatment of last item-block

with open('output.txt', 'wt') as file:
    file.write(''.join(sorted(text)).rstrip())

First the file is chopped into item-blocks, which are collected in a list text. Then the list content gets written back sorted (sorted(text)) into a new file. The decision about when a new item-block starts is based on the line starting with 't' (line.lstrip().startswith('t')) and ending with '=' (line.rstrip().endswith('=')). Maybe you can just rely on the first part, the second is a precaution.
Answer: since your that specific format i have written this code
with open("something.txt") as file:
    data = file.readlines()
    a={}
    for i in data:
        if i[0] !=" " and i != "\n":
            b=i[:-1]
            a[b]=[]
        elif i != "\n":
            if i[-1]==")":
                a[b].append(i)
            else:
                a[b].append(i[:-1])

with open("something.txt","w") as file:
    for i in sorted(a.keys()):
        file.write(i+"\n")
        for j in a[i]:
            file.write(j+"\n")

Comment: Hey, thanks for this. I do need the format to be the same could you please help with that? - As in yes I need the tstuff in different lines

Also the above code is returning an empty file for some reason
Comment: i have edited my answer and it meets your every requirement ... and it does not return an empty file in my case but if it still return an empty file in your case you can try writing second with statement again yourself and in the worst case it still didn't work just tell me and i will look into that matter too
Comment: That is amazing. Than you so much, it works perfectly!


Use Socket.IO and Redis in multiples instances behind ELB

Question: I set up two EC2 Instances on AWS running behind the Load Balancer, but socket.io breaks when twos instance are running. I assume that as ELB round robins between instances and Socket.io sends requests before updating to Websockets this is causing socket io to break (Session ID unknown).
I thought that by using shared session store on Redis , Socket.io would work since all instances would have access to sessions.
I have a small app developed in Node.js(more specifically Sails.js) just for testing.
I managed to configure ELB to support Websockets in TCP mode, forwarding the requests to (Phusion Passenger + NGINX) which runs the Sails.js app.
The app uses Redis running on amazon Elasticache for SESSIONS and SOCKETS.
If I test both instances separately without ELB, I see that Redis is working for Sockets as the messages are sent and received in both instances.
Is shared sessions enough to make Socket.io work? Or I need sticky sessions in the ELB to forward clients to same instances?
I chose ELB because is easier to add and remove instances dynamically, which is complicated with NGINX(Free) or HAProxy.
Any Ideas?
Comment: I have the same problem.  How did you fix the problem ? Do you use socket.io-redis ?
Comment: @grégoire-motot, I ended up using socket.io and socket-io-redis with websockets only. To use other transports such as XHR Polling or JSONP Polling you need to have sticky sessions. You might find this article useful [Load-balancing Websockets on EC2](https://medium.com/@Philmod/load-balancing-websockets-on-ec2-1da94584a5e9)
Answer: When you run a server in a cloud that has a load-balancer/reverse proxy, routers etc, you need to configure it to work properly, especially when you scale the server to use multiple instances.
One of the constraints Socket.io, SockJS and similar libraries have is that they need to continuously talk to the same instance of the server. They work perfectly well when there is only 1 instance of the server.
When you scale your app in a cloud environment, the load balancer (Nginx in the case of Cloud Foundry) will take over, and the requests will be sent to different instances causing Socket.io to break.
To help in such situations, load balancers have a feature called 'sticky sessions' aka 'session affinity'. The main idea is that if this property is set, then after the first load-balanced request, all the following requests will go to the same server instance.
In Cloud Foundry, cookie-based sticky sessions are enabled for apps that set the cookie jsessionid.
Note: jsessionid is the cookie name commonly used to track sessions in Java/Spring applications. Cloud Foundry is simply adopting that as the sticky session cookie for all frameworks.
So, all the apps need to do is to set a cookie with the name jsessionid to make socket.io work.
app.use(cookieParser);
app.use(express.session({store:sessionStore, key:'jsessionid', secret:'your secret here'}));
So these are the steps:

Express sets a session cookie with name jsessionid.
When socket.io connects, it uses that same cookie and hits the load balancer
The load balancer always routes it to the same server that the cookie was   set in.
If you are using Application Load Balancer then Sticky session settings is at target group level


URL Amigável não carrega conteúdo

Question: Bem, estou aqui com um problema na url amigável, estou a fazer as rotas através do ficheiro .htaccess e pegar os valor por $_GET.Só que quando entro na url o conteúdo não me é carregado, fica a pagina sempre a tentar carregar e nada.
Ficheiro htaccess
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^estabelecimentos\/([a-zA-Z-0-9-_]+)\/ index.php?controller=estabelecimentos&option=tipo&tipo=$1 [QSA,L]

Comment: Não dá nenhum erro de PHP ou erro 500 do apache, por exemplo?
Comment: Não apresenta qualquer erro por ver o que acontece neste link http://sabeonde.pt/estabelecimentos/bares/
Answer: A sua página não carrega porque dá erro de javascript. Como sua URL amigável contém um "subdiretório", os caminhos relativos dos seus arquivos .js acabam se tornando inválidos.
Você precisa adicionar uma tag base na seção head do seu HTML.
<base href="http://sabeonde.pt/">

Essa tag vai colocar http://sabeonde.pt/ antes de cada URL relativa na hora de carregar o conteúdo.
Comment: foi isso mesmo corrigiu, só uma pergunta e possível na url que agora esta assim http://sabeonde.pt/estabelecimentos/bares/ ficar so http://sabeonde.pt/bares/
Comment: @CésarSousa Não testei, mas acho que simplesmente removendo `estabelecimentos\` do `.htaccess` vai funcionar.
Comment: Tentei ai como você disse e nao funcionou
Comment: @CésarSousa Troque a linha do `RewriteRule` por `RewriteRule ^([a-zA-Z-0-9-_]+)$ index.php?controller=estabelecimentos&option=tipo&tipo=$1 [L]`
Comment: Amigo e isso mesmo valeu pela sua ajuda foi preciosa mesmo
Comment: Estou aqui com outro problema relativamente a essa linha que me deu para trocar resolveu um problema mas agora tentei criar a mesma linha mas para outro ficheiro mas cai sempre nessa regra estabelecimentos como posso resolver isso
Comment: @CésarSousa Esse já é um problema diferente. Crie outra pergunta e descreva isso lá.
Comment: Já coloquei uma pergunta nova

URL Amigável não carrega conteúdo


Evaluate limit of the form $0^{\infty}$

Question: $$\lim_{n\to\infty}\left(\frac{n^4-3\cdot n^3-n^2+2\cdot n-1}{n^5+n^4-n^3-3\cdot n^2-3\cdot n+1}\right)^{\frac{6\cdot n^5-2\cdot n^4-2\cdot n^3+n^2-2\cdot n}{9\cdot n^4-2\cdot n^3+n^2+3\cdot n}}$$
It is $$\lim_{n\to \infty}\left(\frac{1}{n}+o\left(\frac{1}{n^2}\right)\right)^{(n+o(1))}$$
How can I bring it to a form that I can compute?
Comment: Hint: the function is decreasing and never negative, so...
Comment: Well, $1/n$ goes to $0$, and you are raising it to an even greater power, so there isn't much to do.
Comment: @orion maybe to take $e^{ln(\frac{1}{n})^n}$?
Comment: Your sequence is $$
\frac{1}{{n^{\frac{2}{3}n - \frac{2}{{27}} + O\left( {\frac{1}{n}} \right)} }}\left( {1 - \frac{4}{n} + O\left( {\frac{1}{{n^2 }}} \right)} \right)^{\frac{2}{3}n - \frac{2}{{27}} + O\left( {\frac{1}{n}} \right)}  = \frac{{e^{ - 8/3} }}{{n^{\frac{2}{3}n - \frac{2}{{27}}} }}\left( {1 + o(1)} \right) \to 0.
$$
Answer: All limits of the form $0^\infty$ have $0$ as limit. This is not an indeterminate form, like $\infty^0$ or $\frac\infty\infty$.
To have some notation and formality, let $a_n\to 0$ and $b_n\to \infty$ be two sequences, and for simplicity assume that $a_n, b_n> 0$. Then $a_n^{b_n}\to 0$. You can show this, for instance, by comparison:

Option 1: Since $a_n\to 0$ and $b_n\to \infty$, there is some point $N$ where $a_n\leq \frac12$ and $b_n\geq 1$ for all $n\geq N$. Thus we get $$a_n^{b_n}\leq \left(\frac12\right)^{b_n}$$for all $n\geq N$. And the right-hand side certainly goes to $0$.
Option 2: There is some point $N$ where $a_n\leq 1$ and $b_n\geq 1$ for all $n\geq N$. Then
$$
a_n^{b_n} \leq a_n
$$
for all $n\geq N$. And the right-hand side certainly goes to $0$.

(These arguments work more or less unchanged for negative or zero $a_n, b_n$ as well, as long as $a_n^{b_n}$ makes sense. But I skipped it as I feel it's more difficult to type corrrecly, more difficult to read, and doesn't actually give that much more value to this post.)
Comment: Ah, yes, of course. (But maybe then change "negative" to "nonpositive" in order to allow for values equal to $0$?)
Comment: In the parenthetical paragraph at the end, I think you only mean to mention letting the $a_n$s be negative, not the $b_n$s too.
Comment: @BarryCipra Why not? Sure, only finitely many of the $b_n$ can be negative by definition of $b_n\to\infty$, but one can't, in general, exclude the possibility.
Answer: This is one of the many cases where composition of Taylor series is useful.
We have $y_n=A_n^{B_n}$ where
$$A_n=\frac{n^4-3 n^3-n^2+2 n-1}{n^5+n^4-n^3-3 n^2-3 n+1}\quad \text{and} \quad B_n=\frac{6 n^4-2 n^3-2 n^2+n-2}{9 n^3-2 n^2+n+3}$$
We shall work with
$$\log(y_n)=B_n \log(A_n)$$
Using the long division, we have that
$$A_n=\frac{1}{n}-\frac{4}{n^2}+\frac{4}{n^3}+O\left(\frac{1}{n^4}\right)$$
$$\log(A_n)=-  \log(n)-\frac{4}{n}-\frac{4}{n^2}+O\left(\frac{1}{n^3}\right)$$
$$B_n=\frac{2 n}{3}-\frac{2}{27}-\frac{76}{243 n}-\frac{377}{2187
   n^2}+O\left(\frac{1}{n^3}\right)$$
$$\log(y_n)=-\frac{2}{3} n \log (n)+\frac{2 }{27}\log (n)-\frac{8}{3}+\frac{4 (19 \log (n)-144)}{243 n}+O\left(\frac{1}{n^2}\right)$$ Now,using the expansion to $O\left(\frac{1}{n}\right)$
$$y_n=e^{\log(y_n)}={e^{-8/3}} n^{2/27}n^{-2 n/3}=n^{\frac{2(1-9 n)}{27} }e^{-8/3}$$ as @Gary wrote in comments.
For $n=100$, the relative error is $0.97$% and for $n=1000$, it is $0.02$%.
Edit
We can make it more general for the case where
$$A_n=\frac{a}{n}+\frac{b}{n^2}+O\left(\frac{1}{n^3}\right)\quad \text{and} \quad B_n=c n+d+O\left(\frac{1}{n}\right)$$ and get
$$y_n=e^{\frac{b c}{a}} \left(\frac{a}{n}\right)^{c n+d}$$
Answer: There is no hesitation with $0^\infty$, which can be read as $\dfrac1{\infty^\infty}$.

Evaluate limit of the form $0^{\infty}$


Median of the sum vs. sum of the median for Gaussian variables

Question: This is a problem I stumbled upon in my research. Consider $n$ Gaussian random variables $x_i \sim \mathcal{N} (\mu_i, \sigma_i^2)$, each with its own mean $\mu_i$ and variance $\sigma_i^2$. Can we say that
\begin{equation}
\text{Median} \left( \sum_{i=1}^n x_i^2 \right) \ge \sum_{i=1}^n \text{Median} \left( x_i^2 \right) \; ?
\end{equation}
If the $x_i$ were standard normal variables ($\mu_i = 0$ and $\sigma_i^2=1$) we could compute $\text{Median} (x_i^2) \simeq 0.4549$, and the sum $\sum_{i=1}^n x_i^2 $ would follow the $\chi^2$-distribution with $n$ degrees of freedom, which is reported to have median $\simeq n \left( 1 - \frac{2}{9n}\right)^3$. The above inequality would be
\begin{equation}
\left( 1 - \frac{2}{9n}\right)^3 \ge 0.4549
\end{equation}
which is satisfied $\forall n \in \mathbb{N}$. The question is whether the inequality is true even for non standard normal variables. The fact that it holds for standard normal variables is related to the heavy-tailedness of the distribution of $x_i^2$, so I think it might hold also for general Gaussian variables.
Comment: I think a first step would be to prove the statement for normal variables centered in zero, i.e. $\mu_i = 0$.
Comment: One possible approach: the means of both sides are equal, but the skewness of the left side must be less than the skewnesses of any of the components of the right side.  By relating smaller skewness (a standardized third moment) to a smaller relative difference between the mean and the median, the inequality would result.
Answer: Here is a simple proof, by comparison with appropriate symmetric variables.
For a normal variable $X$, let $m$ be the median of $X^2$. The graphs show $X\sim N(4,1)$.
Now we take a variable $Y$ which is a version of $X^2$ but symmetrized from right to left about $m$:

In formulas:
$$
f_Y(y) =
\begin{cases}
f_{X^2}(y)\phantom{2m-\, }\ \text{ if }\, y>m\\
f_{X^2}(2m-y)\ \text{ if }\, y<m\\
\end{cases}$$
$$F_Y(y) =
\begin{cases}
\phantom{1-\, }F_{X^2}(y)\phantom{2m-\, }\ \text{ if }\, y>m\\
1-F_{X^2}(2m-y)\ \text{ if }\, y<m\\
\end{cases}
$$
Since the $Y_i$'s are symmetric with median $m_i$, the values near $(y_1, \ldots y_n)$ and $(2m_1-y_1, \ldots 2m_n-y_n)$ are equally probable and on opposite sides of $m_1+\cdots+m_n$. So $m_1+\cdots+m_n$ must be the median of their sum.
Also $X^2$ dominates $Y$, i.e. $F_{X^2}(y)\le F_Y(y)$, as can be seen in graphs like the above. Thus:
$$
\begin{align}
\text{median}\left(\sum X_i^2\right)
&\ge \text{median}\left(\sum Y_i\right)\ &\text{ (by the dominance of the }X\text{'s)}\phantom{\ \square}\\
&=\sum\text{median}(Y_i)\ &\text{ (by the symmetry of the }Y\text{'s)}\phantom{\ \square}\\
&=\sum\text{median}(X_i^2)\ &\text{ (by the construction of the }Y\text{'s)}\ \square
\end{align}
$$


Preg Callback Issue

Question: Great Mates...
I need your help.. please let me know why this code is not getting in to the callback function...
  wppp_content_hook('

');

  function wppp_content_hook($content) {

    $fileTypes        = array('\.bmp|\.gif|\.jpg|\.jpeg|\.png');
    $pattern          = array();
    $rel              = 'wp-prettyPhoto';
    $pattern[]        = "//i";
    $pattern[]        = "/]*?)>/i";

    return  preg_replace_callback($pattern,'_regexCallback',$content);
  }

  function _regexCallback($matches) {
   echo "
";
    print_r($matches);
   echo "
";
    global $post;
    $fileTypes        = array('\.bmp|\.gif|\.jpg|\.jpeg|\.png');
    $rel            = 'wp-prettyPhoto';
    $pattern        = array();
    $replacement    = array();
    $pattern[]      = "//i";
    $pattern[]      = "/]*?)>/i";
    $replacement[]  = 'ID.']">';
    $replacement[]  = '';

    return !strpos($matches['0'], '_blank')? preg_replace($pattern,$replacement,$matches['0']) : $matches['0'];
  }

Comment: Do you get any error? Just saying *here is the code, tell me what is wrong* is neither nice nor helpful.
Comment: No didn't get error..but not it dosn't do anything..
Comment: if you can send any alternative that would be great aswell..
Comment: When do you expect _regexCallback to be called? There's no reference to it in your code.
Comment: You are never calling `_regexCallback` anywhere and you are using `preg_replace` and not `preg_replace_callback`.
Comment: Sorry Mates,, i have updated the code.. please look into it again..
Comment: Hey, Guys... got something..? please let me know.. i will great thankfull to you...
Answer: Because your $pattern does not match $content
Look precisely at your actual regexps by var_export'ing $pattern
Callback will only be executed if your content will be matched by regular expression. No reason to execute callback function otherwise since there are no matches.
Part of your actual regex:
([A-Za-z0-9\\/_\\.\\~\\:-]*?)(Array)
It seems like not desired "Array" sneaked into your pattern (both of them).

Preg Callback Issue


Display Value in Excel TextBox in one excel file while reading data from another excel file

Question: I've a Excel VBA generating results into one excel file which keeps on running few SQl querie and keeps on refreshing every 10-15 minutes threshold. I would like to read/refresh the results periodically say every 10-15 mins into second excel file?
Not sure I explained properly but is this possible? I've VBA code running and generating results fine in one excel file, refreshing every 10 mins at the moment. But I stuck on second step where I like to read results from this file and display it into my new excel file.
Any thoughts or inputs welcome.
Thank you.
Zulfiqar

Above is the dashboard excel file where I want to display results into a textboxes which are in the other excel file (values in B2, B3,..in below screen shot attached)
Comment: Use `Workbooks.Open` to open the workbook and paste the value over
Comment: Are you after just reloading it every 10/15 min? if so use
Application.Wait Now + #0:10:01#
Comment: Yes, i've that working. My issue @Kyoujin is I want to display this results into another excel file. how do i do that?
Answer: How about something like below, it will copy your A1 from your current workbook and place the value into B2 of your template workbook:
<code> Sub sb_Copy_Save_Worksheet_As_Workbook()
    Dim workbookName As String
    workbookName = "C:/User/Me/test/mynewworkbook.xlsx"
    'set the path to your workbook
    Set otherWorkbook = Workbooks.Open(workbookName) 'open it
    otherWorkbook.Sheets("Sheet1").Range("B2") = ThisWorkbook.Sheets("Sheet1").Range("A1")
    'change the sheet name above to the sheet you want to copy
    otherWorkbook.Close SaveChanges:=True
    'change the path above to where you want the new file saved
End Sub
</code>
Comment: Updated my answer, this will take value from A1 in your current workbook and put it into B2 of your template,...
Comment: thanks @Xabier the thing is I've a template dashboard excel file ready and I would like to just read the value from the first sheet and render it into template dashboard excel file at a defined location where i've texfboxes placed.
Comment: I've updated my answer to open your existing template and save your worksheet into it. Hope this helps.
Comment: I've updated my question with the screenshot and bit of explanation to get clear idea as to what I am trying to achive.
Comment: ThisWorkbook.Sheets("Summary").TextBox_188.Text = otherWorkbook.Sheets("Instrument Search Result").Range("B2") doesn't seem to work. any idea?
Comment: its a form control for sure
Comment: I would have written it as `otherWorkbook.Sheets("Instrument Search Result").Range("B2").Value = ThisWorkbook.Sheets("Summary").TextBox_188.Value` try it and let me know if you are still having issues...
Comment: Doesn't seem to work. It gives error on that line saying "Object doesn't support this property"
Comment: @ZulfiqarDholkawala Would you be able to share your spreadsheet, so I can have a look at it? I've tested it and it does work for me...
Comment: Upload it to somewhere like Google Drive and comment a link to it here...
Comment: ok will do from home as no permission to external drives. But when i do below it works fine:
Worksheets(1).Range("A1").Value = otherWorkbook.Sheets("Instrument Search Result").Range("B3")

But when i do:  Worksheets(1).TempNAV.Value = otherWorkbook.Sheets("Instrument Search Result").Range("B3")

I get error: Run-Time error '428'
Object doesn't support this property or method
Comment: @ZulfiqarDholkawala it is to do with the way you reference your Textbox, which if it is an ActiveX control then the code above will work fine, but as you used a Form Control, which needs to be referenced differently,...
Comment: got that @Xabier. works as expected with ActiveX control. I'll post my spreadsheet later when i get a chance from home to show exactly what I am trying to do. thanks for your help mate.


Let $hf=g$ and let $hfh^{-1}=f$ then what does this say about the relation between $f$, $g$ and $h$?

Question: I was studying composition of the functions:
$f(x)=2x+1$
$g(x)=\frac{2x-1}3$
$h(x)=\frac{x-2}3$
in a 2-adic setting but I guess the 2-adic part is largely irrelevant here and this applies more generally to groups.

Let $hf=g$ and let $hfh^{-1}=f$ then what does this say about the relation between $f$ and $g$?

My Attempt
My first observation is that the statement seems to say $f,h$ commute.
So I substituted $h$ and $h^{-1}$ into $hfh^{-1}=f$:
$h=gf^{-1}$
$h^{-1}=fg^{-1}$
$gf^{-1}ffg^{-1}=f$
giving me:
$gfg^{-1}=f$
So then by symmetry, I wondered if $ghg^{-1}=h$ as well and I was able to verify all elements commute with each other.  This doesn't appear to be a standard property of function composition. I have a tentative notion of a commutator group here or a conjugacy class but would appreciate a pointer that maps the elements of this structure on to some relevant literature. Coming back to the specific $f,g,h$ at the top (subject to domain / range), are there infinitely many other examples that commute with these functions?
I'm half expecting somebody to hit me with some linear algebra at this point showing the reflections of a triangle in its bisectors.
Just to add something on the 2-adic component of this, we have $f:\Bbb Z_2\to\Bbb Z_2^\times$ and $g:\Bbb Z_2\to\Bbb Z_2^\times$ but $h$ maps $\{x:\nu_2(x)=1\}$ to $\{x:\nu_2(x)>1\}$ and leaves the 2-adic value of everything else unchanged.
Answer: I am not sure this is what you are asking for, still.
You are dealing with affine functions of the form
$$
f_{a, b}  : x \mapsto a x + b.
$$
Now it is immediately seen that $f_{a, b}$ and $F_{c, d}$ commute iff
$$
b (c - 1) = d (a - 1).
\tag{eq}
$$
If you start with $f = f_{2,1}$, you see that a function $f_{c, d}$ commutes with $f$ iff $c = d + 1$. It is then immediate to see that all these functions commute with each other.
One readily sees that in general the affine functions that commute with a fixed $f_{a, b}$ also commute among themselves, except of course when $a = 1, b = 0$, and $f_{1, 0}$ is the identity function.
Let us see that details. If $a = 1$, so that $b \ne 0$, we get from (eq) that $f_{c, d}$ commutes with $f_{a, b}$ iff $c = 1$, so the functions that commute with $f_{a, b}$ are the translations, which obviously commute pairwise.
Suppose then $a \ne 1$, and let $f_{c, d}$ and $f_{e, g}$ commute with $f_{a, b} \ne f_{1, 0}$. We get from (eq)
$$
b (c - 1) = d(a-1), \quad b(e-1) = g(a-1).
$$
Multiplying the first relation by $(e - 1)$, we get
$$
d (a - 1) (e - 1)
=
b (c - 1) (e - 1)
=
g (a - 1) (c - 1),
$$
so that $d ( e -1) = g (c - 1)$, as $a \ne 1$, and thus by (eq) $f_{c, d}$ and $f_{e, g}$ commute.

Addemdum
The above works for coefficients in a domain. Perhaps I should add that if we are working over a field $F$, we are dealing with the affine group $G = \operatorname{Aff}(1, F)$. If $g \in G$ is not a translation, then it has exactly one fixed point, and this has to be fixed by any element in the centraliser of $g$. Conversely, a $1$-point stabiliser is isomorphic to the corresponding general linear group, which in this case is (the abelian group) $F^{\star}$.
Comment: The usual representation of $\operatorname{Aff}(1, F)$ is by $2 \times 2$ matrices $\begin{bmatrix} a & b \\ 0 & 1\end{bmatrix}$ acting on $\begin{bmatrix} x \\ 1\end{bmatrix}$ as $\begin{bmatrix} a & b \\ 0 & 1\end{bmatrix} \cdot \begin{bmatrix} x \\ 1\end{bmatrix} = \begin{bmatrix} a x + b \\ 1\end{bmatrix}$.
Comment: Hi, I didn't see the notification of this answer so I have only just seen it. Thank-you, most useful and especially the addendum.
Comment: @samerivertwice you're welcome!
Comment: Do I understand correctly I can let $q\in\Bbb Q_2$ 2-adic field and write $2x+1$ like $\begin{pmatrix}2 & 1\end{pmatrix}\begin{pmatrix}q \\ 1\end{pmatrix}$ and then in that form, $\begin{pmatrix}2 & 1\end{pmatrix}$ is an element of the affine group of $\Bbb Q_2$?
Comment: Thanks for confirming Andreas and for correcting my representation. Lots of this is really useful for me.


Seasons in which all teams in a division made the playoffs

Question: During the 2014-2015 NBA season, each team in the Southwest Division (Houston, Memphis, San Antonio, Dallas, New Orleans) of the Western Conference made the playoffs.
Has this happened before? If so, in which seasons has all teams in a division made the playoffs? I recognize there was a realignment that took place for the 2004-2005 NBA season, but during the 2003-2004 NBA season, almost all teams in the Midwest division (6 of 7 teams) of the Western Conference made the playoffs.
Comment: The east was so bad that year... only 2 teams in the west wouldn't have made the playoffs in the east, and I wouldn't be surprised if either one would've won enough more games playing the weaker competition to have won the 7 or 8 more games needed to make it.
Answer: Yup. The 2005-2006 Season, the 1985-1986 season, and the 1983-1984 season.
In 2006:

All five teams in the Central Division made the playoffs, marking the first time all teams in a division made the playoffs since the entire Midwest Division made it 20 years before. 1

In 1986:

All Midwest Division teams make the playoffs, the first time an entire division had done this since the 1983-84 season when all Atlantic Division teams made the playoffs. 2

In 1983, playoff expansion resulted in the entire Atlantic division making it:

The NBA Playoffs were expanded from 6 teams per conference to 8, where it stands to this date. As a result, the 'first round bye' system was eliminated. 3
Comment: @pacoverflow It's not particularly hard to look at the standings for each year if you want to see if it's correct or not.  The 1983 year makes sense, because prior to 1983 only six teams made the playoffs from each conference, making it a lot less likely.
Comment: @Madmanta You need to source quotations.   Otherwise it's plagiarism.  Please do not edit out others' sourcing of your quotations.
Comment: So, 2005-2006 and 1985-1986?
Comment: Also 83-84.  And that is it since the realignment in the 1960s where there were no divisions
Comment: Edited the original answer for completeness
Comment: Is there a source for this answer?
Comment: @pacoverflow there was a wikipedia source that was quoted that had been removed (see revisions)
Comment: @edmastermind29 That source only mentions the 05-06 and 85-86 seasons.  How do we know the 83-84 season is the only other one?
Comment: Ah thanks @Joe for the edit, I was going to come back when I saw the source request and link to the three wikipedia entries that clearly showed the answers.


How to prove $\sum_{k=1}^\infty \frac{2^k a^{2^k}}{1+a^{2^k}}=\frac{a}{1-a}$ for $-1<a<1$?

Question: How to prove $$\sum_{k=1}^\infty \frac{2^k a^{2^k}}{1+a^{2^k}}=\frac{a}{1-a}$$ for $-1<a<1$?
It gives a hint: $2^{k+1}-1=1+2+\cdots+2^k$. How can we use this hint to cancel some terms?
Comment: I am pretty sure that the sum should begin from $k = 0$ in order for the identity to hold.
Comment: See https://math.stackexchange.com/questions/2447271/how-to-prove-sum-k-1-infty-frac2k-a2k1a2k-fraca1-a-for
Answer: If $\displaystyle S=\sum_{r=0}^n\dfrac{2^ra^{2^r}}{1+a^{2^r}}$
$$\dfrac a{1-a}-S=\cdots=\dfrac{2^{n+1}a^{2^{n+1}}}{1-a^{2^{n+1}}}$$
Now $\lim_{n\to\infty}\dfrac{2^{n+1}a^{2^{n+1}}}{1-a^{2^{n+1}}}=?$
Comment: I guess you have a small sign mistake: $$ \frac{a}{1-a} - \sum_{r=0}^{n} \frac{2^r a^{2^r}}{1 + a^{2^r}} = \frac{2^{n+1} a^{2^{n+1}}}{1 - a^{2^{n+1}}}. $$ But otherwise it is a really cool solution! (+1)
Comment: @SangchulLee, Thanks a lot and there is a mistake in the question, right?  $k$ should start from $0$
Answer: Here is a brutal-force computation: Expand everything and group according to the exponent of $a$.
$$
\sum_{k=0}^{\infty} \frac{2^k a^{2^k}}{1+a^{2^k}}
= \sum_{k=0}^{\infty} 2^k \sum_{j=1}^{\infty} (-1)^{j-1} a^{j \cdot 2^k}
= \sum_{n=1}^{\infty} \left( \sum_{(j,k) \ : \ j \cdot 2^k = n} (-1)^{j-1} 2^k \right) a^{n}.
$$
Now write $n = m \cdot 2^r$, where $m$ is odd and $r \geq 0$. Then

If $0 \leq k < r$, then $j = m \cdot 2^{r-k}$ is even and hence $(-1)^{j-1} = -1$.
If $k = r$, then $j = m$ is odd and hence $(-1)^{j-1} = 1$.

So we have
$$ \sum_{(j,k) \ : \ j \cdot 2^k = n} (-1)^{j-1} 2^k
= 2^r - \sum_{j=0}^{r-1} 2^j
= 1 $$
and hence
$$
\sum_{k=0}^{\infty} \frac{2^k a^{2^k}}{1+a^{2^k}}
= \sum_{n=1}^{\infty} a^n
= \frac{a}{1-a}.
$$


Limit $\lim_{(x, y) \to (0, \infty)} (xy)$

Question: $$\lim_{(x,y) \to (0, \infty)} (xy) = [x\to\frac{1}{x}\Rightarrow x\to \infty] = \lim_{(x,y)\to(\infty, \infty)} (\frac{y}{x}) = [x = r\cos\theta, y = r\sin\theta] = \lim_{r\to\infty}\frac{r\sin\theta}{r\cos\theta} =\lim_{r\to\infty}\tan\theta$$
Therefore, limit does not exist. Is substitution in the beginning viable here?
Comment: Not really. If $x\to 0^+$ (from one side) then $\frac{1}{x}\to +\infty$, but if $x\to 0$ oscillating around zero, then the limit $1/x$ does not exists.
Comment: Change $y$ to $1/y$.
Comment: You're assuming $x\to 0^+$.
Comment: This limit doesn't exist or $0\cdot\infty$ would not be an indeterminate form.
Answer: The best way of saying things is this : $\lim_{(x,y) \to (0,\infty)} xy$ exists and equals $L$, if and only if for every subsequence $x_n \to 0$ and $y_n \to \infty$ we have $x_ny_n \to L$, where the latter is convergence of a sequence, in which case we have the $\epsilon-N$ definition of convergence.
Of course, one sees that taking $x_n = \frac 1n$ and $y_n = kn$ for any $k \in \mathbb R_{> 0}$, we have $x_n \to 0$, $y_n \to \infty$ and $x_ny_n \to k$. Therefore, the limit in question does not exist, since different choices of subsequences give different limit values.

As to what you have done, unfortunately as $x \to 0$ it is not true that $\frac 1x$ goes to $\infty$, since $x$ can approach $0$ from below, in which case $\frac 1x$ assumes negative values and cannot converge to any positive value, let alone positive infinity.
Furthermore, the part where you set $(x,y) = (r \cos \theta,r \sin \theta)$ : The point is that change of variable in limits only works in certain situations. In particular, since the variable $\theta$ has no particular limit as $(x,y) \to (0,\infty)$, I do not think that this change of variable is correct.
Answer: More simply we have that as $t\to \infty$

$x=\frac1t\to 0 \quad y=t\to \infty$

$$xy=\frac1t \cdot t \to 1$$

$x=\frac1t\to 0 \quad y=t^2\to \infty$

$$xy=\frac1t \cdot t^2=t \to \infty$$
and therefore the limit doesn't exist.


How to derive weak form of the Poisson's equation?

Question: I want to derive weak form of the Poisson's equation. I saw this article, but didn't help much.
$$
-\frac{\partial}{\partial x} \bigg( \frac{\partial u}{\partial x} \bigg )
-\frac{\partial}{\partial y} \bigg( \frac{\partial u}{\partial y} \bigg )
= f \hspace {10pt} \text {in } \Omega
$$
I started by multiplying by weight function $w$ and integrating it over $XY$ space. So,
$$
w\int_\Omega \bigg[ -\frac{\partial}{\partial x} \bigg( \frac{\partial u}{\partial x} \bigg )
-\frac{\partial}{\partial y} \bigg( \frac{\partial u}{\partial y} \bigg )
- f \bigg] dxdy =0
$$
Next step should be using integration by parts using identity
$ \int udv = uv - \int vdu $. But I am not getting how to use this in the above equation. If I just consider this part of the equation,
$$
w\int_\Omega -\frac{\partial}{\partial x} \bigg( \frac{\partial u} {\partial x} \bigg ) dxdy=0
$$
I don't understand how to proceed further as integration is in $x,y$. Any help is appreciated.
Comment: It is probably difficult to do with the 1D integration by parts. Use the green formulas instead, they are the multidimensional generalization of integration by parts.
Comment: I wouldn't say it's difficult, if only $w$ has compact support (which it should, but OP didn't mention that). The formulas should be corrected so that $w$ is inside the integral.
Answer: It is possible to derive the 'multidimensional integration by parts formula' or the Green's formula using the Gauss divergence theorem. Let $a$ and $b$ be arbitrary smooth enough functions. We have by the product rule (using index notation)
$$\int_{\Omega} (ab)_{,j} \,\mathrm{d}x = \int_{\Omega} a_{,j} b + ab_{,j} \,\mathrm{d}x.$$
Using Gauss divergence on the LHS term gives
$$\int_{\Omega} ab n_j \,\mathrm{d}x = \int_{\Omega} a_{,j} b + ab_{,j} \,\mathrm{d}x.$$
Rearranging the terms gives
$$\int_{\Omega} a_{,j} b \,\mathrm{d}x =  \int_{\Omega} ab n_j \,\mathrm{d}x - \int_{\Omega} ab_{,j} \,\mathrm{d}x.$$
Notice the similarity of this and the one-dimensional integration by parts formula (hence the casual nomenclature).
Apply this in your second equation with $b \rightarrow w$ and $a \rightarrow \frac{\partial u}{\partial x}$ or $a \rightarrow \frac{\partial u}{\partial y}$ depending on the term. The boundary term will either vanish or not vanish depending on the boundary condition (for $u=0$ on boundary it will vanish). By the way, your $w$ should be inside the integral, not outside.


Is there a way to call "access callback" with parameters?

Question: I have:
function hook_menu()  {
    $items = array();
    $items['experiment-2'] = array(
        'title' => 'Experiment 2',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('experiment_form'),
        'access callback' => 'user_can_access_experiment',
        'file' => 'includes/experiment-2.form.inc',
        'type' => MENU_NORMAL_ITEM,
      );

    ...

This will call:
function user_can_access_experiment() { }

But I want to be able to call it something like:
function user_can_access_experiment($experimentID) { }

And then somehow let hook_menu call the function as user_can_access_experiment(1) or user_can_access_experiment(2) or whatever.
Is this possible?
Comment: This is covered in [How should I implement hook\_menu()?](http://drupal.stackexchange.com/questions/62473/how-should-i-implement-hook-menu)
Answer: If I understand your query right the access callback needs to accept a parameter based on which it decides whether or not to return TRUE for the menu path. This should be achievable using access arguments, like
'access arguments' => array($experimentID),
quoting from the hook_menu API documentation

"access arguments": An array of arguments to pass to the access
  callback function, with path component substitution as described
  above. If the access callback is inherited (see above), the access
  arguments will be inherited with it, unless overridden in the child
  menu item.

The passed argument, in your case the $experimentID could be either from any custom computation like a value from the user object or even a part of your query parameters.
Comment: Given '/foo/bar/barfoo' as path and `'access callback' => '_mymodule_check_arg'`, `'access arguments' => array(2)` would pass 'barfoo' into `_mymodule_check_arg($arg_from_path)`.
Answer: You should use "access arguments" to indicate it.
This array key is waiting for an array.
cf : https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7
Answer:
"access callback": A function returning TRUE if the user has
  access rights to this menu item, and FALSE if not. It can also be a
  boolean constant instead of a function, and you can also use numeric
  values (will be cast to boolean). Defaults to user_access() unless a
  value is inherited from the parent menu item; only
  MENU_DEFAULT_LOCAL_TASK items can inherit access callbacks. To use the
  user_access() default callback, you must specify the permission to
  check as 'access arguments' (see below).
"access arguments": An array of arguments to pass to the access
  callback function, with path component substitution as described
  above. If the access callback is inherited (see above), the access
  arguments will be inherited with it, unless overridden in the child
  menu item.

This example may helps you:
function hook_menu()  {
    $items = array();
    $items['experiment-2'] = array(
        'title' => 'Experiment 2',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('experiment_form'),
        'access callback' => 'user_has_role',
        'access arguments' => array(array('Role 1', 'Role 2')),
        'file' => 'includes/experiment-2.form.inc',
        'type' => MENU_NORMAL_ITEM,
      );

    return $items;
}

function user_has_role($roles) {
    if (user_is_logged_in()) {
        global $user;
        if (in_array('administrator', $user->roles)) {
            return TRUE;
        }
        foreach ($roles as $role) {
            if (in_array($role, $user->roles)) {
                return TRUE;
            }
        }
    }
    else {
        return FALSE;
    }
}


When can we expect Official Magento Forum to start?

Question: With the Magento forum being closed since long, I am wondering when will the official Magento forum start? Is there any targetted date when they are going to start the forum back?
Moreover, I wonder what was the use of closing the forum. They could have created a new forum and have replaced it with the Old one, instead of closing the old forum which is the life line of Magento Community.
I doubt they are really intending to start a new forum, they might be intending to migrate the whole traffic to Magento Stack Exchange, so the forum maintenance cost can be reduced.
Comment: Have you tried emailing to email@example.com and asking? I think it will be more reliable then our guesses here.
Comment: No i haven't.... i guess i will do that...
Answer: There will be new forums, and there is not yet a date for when those will be live. We are currently evaluating several SaaS platforms, which will be a considerable investment but will prevent us from having to maintain our own software and hardware and will help fight our never-ending battle against spam.
The next announcement from me will include our chosen platform and a target launch date.
Also, I/we did look at Stack as a possible forum replacement. There are too many barriers to this:

English only (confirmed with Stack management)
No allowance for questions of opinion ("What's the best...?")
Sophisticated technical culture

The last point can be confirmed by any of the moderators who regularly delete questions such as "how I make product in magento" and "how do I make a site like ebay with magento"
Comment: Thanks for the reply.. its good to have an assuring answer from a core team member..
Comment: I had one more query though its not related to question.. will all the old questions be migrated to new forum or will they be kept in an archive?
Comment: Archived, for lots of reasons.
Comment: Great!!! i will be waiting for new forum... You should suggest inclusion of point system as stack exchange.. it will encourage lot of members to answer and keep forum alive


Cracking the Coding Interview 6th Edition, 8.2

Question: Problem States: "Imagine a robot sitting on the upper left corner of grid with r rows and c columns. Robot can only move in 2 directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom right."
My solution was to do something like the following:
while grid[r-1, c] !=null && grid[r-1][c] !=false
{
     moveRobotDown();
}
while grid[r, c-1] !=null && grid[r][c-1] !=false
{
     moveRobotRight();
}

----after both while loops I'll then throw in a recursive call to the function with the new r,c coordinates.
It seems like a pretty simple implementation, but the answer key has a pretty lengthy and complicated solution. Can anyone explain to me why mine doesn't work?
Comment: When happens if going down as your first move leads you to a dead-end?  Where's your logic to back-track and try another route?
Answer: It wouldn't work if you had a 'map' like this (where | is the path and * is where the robot would end up)
   |
   |
   |
   *X
   XX

The 'robot' would move as far down as possible and then would be unable to move right and your algorithm would fail.
I would recommend reading up on tree traversal, especially A*.
Comment: You don't need A* for this problem, since it's dealing with a DAG.
Answer: Easy. About 10 lines of code, and time proportional to rows x columns.
Definition: A cell is "fine" if you can reach the bottom right corner from it. In a first pass, you determine all the cells that are fine. Just examine the rows from top to bottom, the columns of each row from right to left: A cell is fine if it is not "off limits", and if it either is the bottom right corner, or if it is above or to the left of a cell that is fine.
If the top left corner is not fine then there is a solution. Otherwise, start with the top left corner. And as long as you haven't reached the bottom right corner, at every turn you go either down or right to a cell that is fine.
Answer: try using bfs or dfs. Consider this problem as: shortest path from one point to another.
Using recursion and visited array, that is dfs can resolve this problem quickly.


Test projects building to common output directory?

Question: I have set the build output path of all projects to common debug and release directories:
<code><OutputPath>$(SolutionDir)BuildOutput\Release</OutputPath>
</code>
Should the test projects also output to this directory or should they build to their own release (bin) directories?
I am using VS 2013.
Answer: Test projects should build to their own Release \ Debug directory.  This is because they are separate project; they are executed separately (ie with a Test Runner) and are deployed separately.  If you have a project called Mvc and a project called Mvc.Test, you're probably not going to want to deploy Mvc.Test to your web server.


How can I extend the background of an element beyond its container?

Question: I have a div that contains an h3 tag, and i want the h3's background to extend beyond the containing div tag to the edge of the page. Is there a way to do this in CSS?
I considered absolutely positioning the h3, but I don't know the size from the edge of the screen to the edge of the div (where I want it to be) since the div is centered.
Answer: On this page, I used Firebug to change the question title's css.
#question-header h2 {
    background:lime;
    margin-bottom:-1000px;
    padding-bottom:1000px;
}

This is what happened:
(source: zastica.com)
There is a #question-header div that only extends to the top of the question ("I have a div..."). The key is having a large padding-bottom and a large (negative) margin-bottom.
This also works for side-to-side backgrounds. You just have to make sure the container doesn't have overflow: hidden set.
Edit: To get this effect left and right, set:
html {
    overflow-x: hidden;
}

#question-header h2 {
    padding: 0 1500px;
    margin: 0 -1500px;
}

The html { overflow-x: hidden; } prevents the page width from getting really big due to the padding.
Comment: While this didn't solve my problem, it did point me in the right direction.
Comment: I'm happy to know that it was helpful. Glad you figured it out!
Answer: An elements background cannot extend beyond it's bounding box.
You could in some cases extend the H3 beyond it's container by setting negative margins, but you would need the exact width of the page.
Seems like you may just want to reorganize your HTML to make this possible.
Answer: Unfortunately what you are trying to do is impossible with plain CSS as you need to know the distance to the right edge. Absolute positioning would then work just fine. Of course, you can do this easily using some JavaScript, and even easier if using jQuery:
$(function() {
    $('h3').each(function() {
        $(this).width($(window).width() - $(this).offset().left);
    });
});

And in CSS:
h3 {
    position: absolute;
    ...
}


How to display values for single attribute across multiple columns in ActiveAdmin Rails

Question: For a resource page in ActiveAdmin (Rails3 currently), I have a single column display table of a list of values for a single attribute on the resource object, displayed as a string row for each value in the list in view mode and when in edit mode it is a list of checkboxes of a larger collection to select the values. The values are from a single model attribute that is a serialized array stored in the database as a text field.
For show handler

    show do |company|
     attributes_table do
      ...
      row 'Strategies', :strategy_codes do
        table_for company.strategy_codes do
          column do |code|
            code
          end
        end
      end
      ...
    end
   end

For form handler

  form do |f|
    ...
    f.inputs 'Strategies' do
      f.input :strategy_codes, label: false, as: :check_boxes,
              collection: f.object.available_strategy_codes
              .collect { |l| ["#{l}",l]}.unshift(["Select All"]),
              hint: 'Select the desired strategies',
              input_html: { multiple: true }
    end
    ...
    f.actions
  end

Each of the above displays the values for strategy_codes as single column (i.e. 30 or more rows).
In both cases, for show and edit, I would like to organize the values across multiple columns of the table instead of a single column of values because the values list can be 30 items or more and they are short values (5 characters). I would like to be able to specify it be spread across 2, 3, or 4, etc columns so that it is a shorter, but wider, multicolumn display for this one attribute's values.
Is this possible as a modification or addition to ActiveAdmin's view methods?
Update
I managed to get the show handler working for this "display a list of values across multiple columns" challenge as:
  row 'Strategies', :strategy_codes do
    column_count = 4
    row_count = (company.strategy_codes.count / column_count).ceil
    table_for company.strategy_codes.in_groups_of(row_count).transpose do
      (1..row_count).each_with_index do |c,i|
        column do |code|
          code[i]
        end
      end
    end
  end

Since I wanted each column to fill up with rows before moving to the next column, I transposed the array produced by in_groups_of.
I haven't had much luck yet however trying to get a collection of checkbox option values for the form handler to be displayed across columns in the same manner.
I am wondering if it would be better to try get the client-side to handle this by injecting some css or javascript into the mix.
If I was able to get a form checkboxes solution working that didn't have the "fill the columns up vertically first" capability and instead filled each row up then moved down to the next row, I would fine with that approach as well.
Ideas?
Comment: did you try to do this? what is your code?
Comment: I haven't tried to split across multiple columns. I added the current code blocks that displays a single column for `show` and `edit`
Answer: I ended up doing this using CSS as you considered.
active_admin.scss
    form{
        fieldset.inputs{
            ol{
                li.check_boxes{
                    fieldset.choices{
                        ol {
                        -moz-column-count: 4;
                        -moz-column-gap: 20px;
                        -webkit-column-count: 4;
                        -webkit-column-gap: 20px;
                        column-count: 4;
                        column-gap: 20px;
                        }
                    }
                }
            }
        }
    }


creating Fusion Table from iOS

Question: I work on ios application that use Google fusion tables. in previous question I got advice and made progress but still struggle with creating fusion table. my code:
NSString *url = @"https://www.googleapis.com/fusiontables/v1/tables";

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myTableDict options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonDataString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *postData = [jsonDataString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
GTMHTTPFetcher *fetcher = [GTMHTTPFetcher fetcherWithRequest:request];
[fetcher setAuthorizer:self.auth];
[fetcher setPostData:postData];
void(^createHandler)(NSData *data, NSError *error) = ^(NSData *data, NSError *error){
    if (error) {
        NSLog(@"error creating table %@", [error localizedDescription]);
    }
};
[fetcher beginFetchWithCompletionHandler:createHandler];

But I am getting error: "The operation couldn't be completed. (com.google.HTTPStatus error 400.)". what am I doing wrong?
Answer: looks like a good progress. in your code you seem to be missing setting the http header content type, should be:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
GTMHTTPFetcher *fetcher = [GTMHTTPFetcher fetcherWithRequest:request];

also, when doing GTMHTTPFetcher error processing you might get more info using:
NSData *data = [[error userInfo] valueForKey:@"data"];
NSString *errorDataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

creating Fusion Table from iOS


How to fill in NA values according to a categorial variable in R

Question: I have some NA values in my data that I would like to fill in according to the filename column. In order words, every observation with the same filename should have the same values in the discipline, nativeness, year, and gender columns.
structure(list(TA = c("future_perfect", "future_progressive",
"future_simple", "past_perfect", "past_perfect_progressive",
"past_progressive", "past_simple", "present_perfect", "present_perfect_progressive",
"present_progressive", "present_simple", "future_perfect", "future_progressive",
"future_simple", "past_perfect"), filename = c("BIO.G0.01.1",
"BIO.G0.01.1", "BIO.G0.01.1", "BIO.G0.01.1", "BIO.G0.01.1", "BIO.G0.01.1",
"BIO.G0.01.1", "BIO.G0.01.1", "BIO.G0.01.1", "BIO.G0.01.1", "BIO.G0.01.1",
"BIO.G0.02.1", "BIO.G0.02.1", "BIO.G0.02.1", "BIO.G0.02.1"),
    discipline = c(NA, NA, "BIO", "BIO", NA, "BIO", "BIO", "BIO",
    "BIO", "BIO", "BIO", NA, NA, "BIO", NA), nativeness = c(NA,
    NA, "NS", "NS", NA, "NS", "NS", "NS", "NS", "NS", "NS", NA,
    NA, "NS", NA), year = c(NA, NA, "G0", "G0", NA, "G0", "G0",
    "G0", "G0", "G0", "G0", NA, NA, "G0", NA), gender = c(NA,
    NA, "F", "F", NA, "F", "F", "F", "F", "F", "F", NA, NA, "M",
    NA), n = c(0L, 0L, 9L, 6L, 0L, 2L, 76L, 34L, 1L, 2L, 265L,
    0L, 0L, 10L, 0L)), row.names = c(NA, -15L), class = c("tbl_df",
"tbl", "data.frame"))

I know that I can fill() up or down, but some of the missing values are above and some are below, so this would not work. I also know how to fill in the columns based on the value in the filename column.
For instance:
mutate(discipline = case_when(
  stri_detect_fixed(filename, "BIO") ~ "Biology",
  stri_detect_fixed(filename, "PHY") ~ "Physics"))

However, this would not work for the gender and nativeness columns, as this info is not contained in the filename.
Answer: We may group by  fill and use OP's code
library(dplyr)
library(stringi)
library(tidyr)
 df1 %>%
   group_by(filename) %>%
   fill(discipline:gender, .direction = "downup") %>%
   ungroup %>%
   mutate(discipline = case_when(
  stri_detect_fixed(filename, "BIO") ~ "Biology",
  stri_detect_fixed(filename, "PHY") ~ "Physics"))

Comment: I understand now. It's the correct output.
Comment: I see how that works for discipline but how would that work for nativeness and gender? That info is not contained in the filename.
Comment: The same values as every other row that contains the same filename. In other words, every observation with the same filename has the same nativeness, year, gender, and discipline values.
Comment: I don't need to incorporate my original code, as this serves the same purpose. However, how can I be sure the fill has chosen the correct values? This is a tibble of over 5000 rows and I'm concerned that it will sometimes fill according the the wrong filename if that row is adjacent to another row with a different filename.
Comment: @LilyLew that is the reason I used group by fill.  If this is not hte correct output, you need to provide the expectedd output


"distributing" ftp server?

Question: Is there an ftp server that behaves as a 'distribution front end' to multiple other servers? So that when I upload a file, it accepts the contents, puts them on all of a list of other ftp servers and (importantly) does not confirm success of the upload until it's on all of the other servers?
Alternatively, if it could wait until (say) rsync  had replicated the uploaded file to all the other servers before returning success (or, more generically, wait for some external command to complete before returning success).
Background:
We have an app that uploads files to a repository (using ftp or sftp), then immediately instructs a device to download the file (via http).
We need the repository to be load-balanced/highly-available/resilient. Our corporate hosting standards do not permit shared storage.
What we do with other related apps is have several ftp/http servers, and manually upload files to all of them before telling the app (and then the device) to use them.  A load balancer distrbutes download requests. This works becasue those apps do not do the uploading, instead we configure them to use the  URL of the previously uploaded files.  The problem app doesn't do this, it does the upload itself.
We could use rsync or similar to replicate the files uploaded by the problem app to the multiple servers, but the use of these files is immediate, so they may not have replicated to the other servers when a request for them is received. The app cannot be configured to have a delay here.
But if the ftp server didn't return until the file had been replicated (either by the server itself doing all the replication/upload to other servers, or by it waiting for an external command to complete), then the app wouldn't tell the device to use the files until we knew they were everywhere. And it would all work.
Any pointers to suitable servers? Other ideas for solving the problem? (altering the app isn't possible in the timescales, unfortunately)
Answer: If you need to use FTP, you could write a script (perhaps a Python program, or in any language that offers a convenient FTP library) that your upload program runs immediately after completing the upload to the 'master' server.  This script would scan the FTP sites that are supposed to be replicated to, and won't exit until it sees those files.  On the master server, you would have another script that monitors the filesystem (such as using Linux's inotify) and when it sees new or modified files, it uploads them to the slave servers.
Alternately, you could use a replicated filesystem.  This moves the problem from a homebrewed set of scripts at the application layer to a layer designed to deal with replicating files.  Check out Tahoe-LAFS.  I quote the relevant sentence:

Users do rely on storage servers for availability. The ciphertext is erasure-coded into N shares distributed across at least H distinct storage servers (the default value for N is 10 and for H is 7) so that it can be recovered from any K of these servers (the default value of K is 3). Therefore only the failure of H-K+1 (with the defaults, 5) servers can make the data unavailable.
Comment: I thought the replicated filesystem approach was much the best, provided the FS didn't return confirmation on the write until the replication had happened.  Nice approach!
Comment: Running a script after the upload isn't good enough. That's the same (in effect) as rsync. The file may well get used/retrieved from one of the slave servers before that script has completed running.  The replicated file system might be interesting, but "In the period after the close but before the upload has finished, the closed file may not appear in directory listings, or may appear with an incorrect modification time. " seems to suggest it does not guaranteee the ftp session will finish only when the file is properly available. It's not very clear from the site what really happens here.
Answer: I think the true answer is "no". You're asking for more than the FTP protocol provides. If the client sends a TCP segment and the server says "I got it", the client sends the next one. When all of them are received, the transfer is done. There's no hook in the existing protocol for the server to say "Please wait while I fiddle around."
If you modified the FTP server so that it slowed down the TCP ACKs until it had written the bytes everywhere else, you might get what you want, but I worry that you might also turn your transfers into even more of a crawl than needed, due to TCP sliding window.
You're essentially asking for a two-phase commit for a file transfer operation inside FTP, and that doesn't exist.
Perhaps you could look at a virtualized/replicated storage system instead, as suggested above.
Comment: I only need it consistent after the file is closed, so I don't think it us necessarily more than the protocol provides. The server could upload the file locallly (or to one of the underying servers), then copy it on close. This seems pretty much what Tahoe-LAFS does for ftp front-ends, for instance. I ran across DRBD (www.drbd.org) which is another alternative approach
Comment: Those are fixing this at the file-storage layer, which is what I am getting at with my last sentence.

"distributing" ftp server?