Discrete test statistics cannot form a uniform P-value?

Question: I received this feedback on my permutation test design from a collaborator and I'm wondering if his claim is valid. My test statistics are discrete (like counting the number of red marbles found after drawing 100 marbles from a jar), and I validated that my permutation test does not show bias by demonstrating a uniform P-value distribution for 1,000 statistical tests on randomized data. Please let me know your thoughts:
"The null distribution of P-values is only expected to be uniform for statistical tests based on continuously-valued data. For statistical tests based on discretely-valued data, the null distribution is expected to be spiky and not necessarily uniform."
Comment: You can make the p-values truly uniformly distributed by employing a randomized test.
Comment: I recommend visualizing the CDF instead of a histogram.
Comment: There are a finite number of possible values this particular p-value can take, right? Does that sound like $U(0,1)?$
Comment: I see, so albeit the the distribution may be jagged (i.e. 100 possible P-values on a histogram with 100 bins), if smoothed it should resemble more or less a uniform distribution?
Comment: While its not continuous standard uniform like you get under Ho for a continuous test statistic and a point null, a conservative test forms a cdf that just touches the y=x line at each jump (sitting to the right of the uniform line). I've seen a few different names used for this property. e.g. see the terms in Definition 1 here: https://arxiv.org/pdf/1803.06040.pdf though I've also seen some people call it "uniform", albeit using a quite different definition to this one: https://en.wikipedia.org/wiki/Discrete_uniform_distribution
Answer: Your collaborator is technically correct. With a finite number of values, your CDF will have jump discontinuities in it, yet the CDF of a uniform distribution is continuous.
However, a CDF with jump discontinuities can look pretty continuous, so while your collaborator might be technically correct, the difference might not be of practical importance.

The CDF above looks quite continuous and even looks uniform (at least to me). However, there are a finite number of points used to produce that plot.
library(ggplot2)
set.seed(2024)
N <- 10000
x <- runif(N, 0, 1)
cdf <- ecdf(x)(x)
d <- data.frame(
  X = x,
  CDF = cdf
)
ggplot(d, aes(x = X, y = CDF)) +
  geom_point(size = 1/100)

(Yes, the runif command means that the data are simulated from a uniform distribution. However, the data explicitly plotted there do not exhibit a uniform CDF.)
If that is uniform enough to suffice for your purposes is up to you, and the answer might be that it is not, though I would be among those surprised if it is not.
A histogram for these data do exhibit some "spikes" that your collaborator mentioned.
ggplot(d, aes(x = X)) +
  geom_histogram()


Rails: Prioritize/sort collection of records

Question: I have a Post model that belongs to a single category and author.  Users may create "favorites" for categories and authors.  How can I most efficiently query a list of all posts, but with the visitor's preferred categories and/or authors sorted to the top?
class Post < ActiveRecord::Base

  belongs_to :category
  belongs_to :author

end

class Favorite < ActiveRecord::Base

  belongs_to :user
  belongs_to :category # favorite category
  belongs_to :author # favorite author

end

class User < ActiveRecord::Base

  has_many :favorites

end

Comment: Do you have a boolean for preferred or do you want it more complex where it automatically rates them? Please give more information.
Comment: Nope, no boolean for preferred.  It needs to use the Favorite model to determine which posts are preferred, based on the category/author of the post and the "favorited" category/author of that specific user.
Answer: class User < ActiveRecord::Base
  has_many :favorites

  has_many :favorite_categories, :through => :favorites, :source => :category
  has_many :favorite_authors, :through => :favorites, :source => :author
end

class Favorite < ActiveRecord::Base
  belongs_to :user
  belongs_to :category # favorite category
  belongs_to :author # favorite author
end

class Post < ActiveRecord::Base
  belongs_to :category
  belongs_to :author

  named_scope :order_by_user, lambda {|user| where(
    :category_id => user.favorite_categories.map(&:id),
    :author_id   => user.favorite_authors.map(&:id)
  )}
end

user = User.first
posts = Post.order_by_user(user)

Alternate: less number of queries, but user model fetches data from Favorite
class Favorite < ActiveRecord::Base
  belongs_to :user
  belongs_to :category # favorite category
  belongs_to :author # favorite author
end

class User < ActiveRecord::Base
  has_many :favorites

  def favorite_category_ids
    Favorite.where(:user_id => self.id).select(:category_id).map(&:category_id).compact
  end

  def favorite_author_ids
    Favorite.where(:user_id => self.id).select(:author_id).map(&:author_id).compact
  end
end

class Post < ActiveRecord::Base
  belongs_to :category
  belongs_to :author

  named_scope :order_by_user, lambda {|user| where(
    :category_id => user.favorite_category_ids,
    :author_id   => user.favorite_author_ids
  )}
end

user = User.first
posts = Post.order_by_user(user)

This code is not tested, but gives the idea.


Do Kofax Capture Mobile SDK have a trial version for iOS?

Question: I wanted to work on the Kofax Capture Mobile SDK for iOS , but have not bought the product. Mean while i want to start working on it , Do they have a trial version that i can work on till i buy their product? Can anyone help me out?
Answer: Yes, You could sign-up here and get the 30-day trial. You would get a licence key from which you could evaluate.


hierarchical select to display taxonomy tree

Question: I need a similar module as hierarchical select to display taxonomy tree in my view because hierarchical select to drupal 7 doesn't work with views module.
Please help me !
Answer: ASSIGN $child to an select list just set taxonomy id :
$taxonomy_vid = 3;
   /*** A HEADACHE CODE :p arrange the parent child taxonomies****/
 /*      $tree_type =  taxonomy_get_tree($taxonomy_vid);   // taxonomy id here
    $childs["selected"]="Select a Value";
    //$childs[45]="New Launches/Projects";
    foreach($tree_type as $key =>$value) {
$temp_ = taxonomy_term_load($value->parents[0]);       //IF parent is set already
                if($value->parents[0]==0) {                   //if no any parent taxonomy
                        if(is_object($temp_)==TRUE) {
                        if(isset($childs[$temp_->name])) {  //if array key is already set
                                if(is_array($key)!=FALSE) { //if value is not an array
                                    $childs[$temp_->name][$key]=array($key=>$value->name);  // set the parent child array
                                }
                        }else {
                                if(is_array($key)!=FALSE) {    //if value is not an array
                                    $childs[$temp_->name][$key]=array($key=>$value->name);  // set the parent child array
                                }
                            }
                        }else
                        {
                            $childs[$value->name]=array();
                            $childs[$value->name][$key]=$value->name;
                            //drupal_set_message("-------
".$value->name."
-------");
                            }
                    }else {
                        //$temp_ = taxonomy_term_load($value->parents[0]); //IF parent is set already
                        $childs[$temp_->name][$key]=$value->name;       //$childs[$temp_->tid]=$temp_->name;
                    }
        }

Answer: A very quick google search "views tree" will point you to this module, which most probably will get you going.


using DataAdapter to populate table

Question: I have a disconnected dataTable that contains a few records.
I am using the following function to get the dataTable.
static System.Data.DataTable ReadSetUpTable(string queryStr,SqlConnection sc)
{
    try
    {
        var command = new SqlCommand()
                          {Connection = sc, CommandText = queryStr};
        var dataAdapter = new SqlDataAdapter() {SelectCommand = command};
        var dataTable = new System.Data.DataTable();
        dataAdapter.Fill(dataTable);
        return dataTable;
    }
    catch (Exception)
    {
        throw;
    }
}

No issues so far.
What I want to know is if there's an easy to populate this dataTable into another schema using a different connection string.
For the sake of this post, assume that there is a table with two columns
Create Table Student(StudentId NUMBER(6), StudentName varchar2(50));

I wish to fill this table with the dataTable that I have in the above code.
I could do it using a command Object and an insert statement. For example this code:
static int LoadDataTable(OracleConnection oc, System.Data.DataTable dataTable)
{
    try
    {
        var command =
            new OracleCommand
            {
                CommandText = "INSERT INTO STUDENT (STUDENTID, STUDENTNAME) VALUES(:studentid, :studentname)",
                CommandType = CommandType.TableDirect,
                Connection = oc
            };
        var op1 =
            new OracleParameter
            {
                ParameterName = "StudentId",
                Size = 6,
                OracleDbType = OracleDbType.Int32,
            Direction = System.Data.ParameterDirection.Input
            };
        command.Parameters.Add(op1);
        var op2 =
        new OracleParameter
            {
                ParameterName = "studentName",
                OracleDbType = OracleDbType.Varchar2,
                Size = 50,
                Direction = System.Data.ParameterDirection.Input
            };
        command.Parameters.Add(op2);
       /*
        foreach (var row in dataTable.Rows)
        {
            op1.Value = int.Parse(row[0].ToString());
            op2.Value = row[1].ToString();
            command.ExecuteNonQuery();
        }*/
            foreach (System.Data.DataRow row in dataTable.Rows)
            {
                row.SetAdded();
            }

            var dataAdapter = new OracleDataAdapter() {InsertCommand = command};
            dataAdapter.Update(dataTable); //This updates the table, but all column values are NULL.

    }
    catch(Exception)
    {
        throw;
    }
}

Is there a quicker and easier way where I will not have to loop through the records?
Answer: In your first block of code, you're setting the SelectCommand.  There's also an InsertCommand, UpdateCommand, and DeleteCommand.
These commands also exist on OracleDataAdapter objects... Since the DataTable is endpoint-neutral, all you would need to do is create an OracleCommand to do the insert, set it as the OracleDataAdapter's InsertCommand, and call oracleDataAdapter.Update(dataTable).
Will modify this with more details as I check up on them.

A good example of setting the InsertCommand is here.  Note that when you add parameters to the command, the last value you pass to .Add( ... ) is the name of the column you're mapping to.
Because you're retrieving the data into the DataTable, but not changing it, you'll need to change the RowState of each row to 'Added' before calling oracleDataAdapter.Update().  You'll need to do something like this:
foreach (DataRow row in dataTable.Rows) {
    row.SetAdded();
}

Let me know if you need more code examples... from the code you've posted, I think you've pretty much got the gist of where I'm going here.

Edit
When you create the OracleParameters, you need to set the source column to the name of the column in the DataTable.  By default, that's the name returned by the select statment, so:
var op1 = new OracleParameter {
                                ParameterName = "StudentId",
                                Size = 6,
                                OracleDbType = OracleDbType.Int32,
                                Direction = System.Data.ParameterDirection.Input
                                SourceColumn = "StudentId" // If that's what it's called in the DataTable
                              };
command.Parameters.Add(op1);

The AcceptChanges() method is on the DataTable, as is the HasErrors property (it also exists on the DataRows, and DataSets, too).
AcceptChanges() only tells the DataTable that you've handled the updates to the database... the changes are committed to the database when you called oracleDataAdapter.Update().  The reason you call AcceptChanges() is to reset the row states... else the next time you updated the DataTable, you'd be trying to add rows that were already added.
The property AcceptChangesDuringUpdate on the OracleDataAdapter will automatically call AcceptChanges() as part of the update to the database... I don't usually do that, because I'm used to testing the HasErrors property and handling those before calling AcceptChanges()... however I'm reading that AcceptChanges() is called by default on the update now.  I'm not familiar with the details of how rows that are in error are handled, if the changes are accepted, or not.
Comment: @James B - Where do you set the data source of the dataAdapter to the dataTable?
Comment: @James: will `dataTable.AcceptChanges()` effectively set all `rows` as Added?
Comment: You don't... Just like you called dataAdapter.Fill(dataTable), you call oracleDataAdapter.Update(dataTable).
Comment: No, that will do the opposite... `AcceptChanges()` will set everything that is marked as 'Added', 'Modified', etc. to 'Unchanged'.  You call `AcceptChanges()` after you've called `oracleDataAdapter.Update(dataTable)` and all rows were successfully updated (use the `HasErrors` property of the DataTable to determine if any of the rows failed).
Comment: @JamesB I have modified my code. Please take a look. I have been able to insert rows in the Student table, but all of the columns are null. There is no AcceptChanges() method on the OracleDataAdapter.There are two properties AcceptChangesDuringFill  and AcceptChangesDuringUpdate. The AcceptChanges is on a dataRow.
Comment: Thanks JamesB. I was missing the SourceCOlumn="StudentID" in my code. I have changed my code now and the rows are no longer being populated with NULL values.

using DataAdapter to populate table


Pandas data frame with repeating sequences: How to do a spaghetti plot?

Question: I've got the data looking like the following data as pandas.DataFrame:
                                  diff_1       diff_2
1949-01-01 06:00:00               -0.555       -0.123
1949-01-01 07:00:00               -0.654        0.230
1949-01-02 06:00:00               -0.879        0.012
1949-01-02 07:00:00               -0.459        0.672
1949-01-03 06:00:00               -0.588        0.980
1949-01-03 07:00:00               -0.068        0.375
1950-01-01 06:00:00               -0.654        0.572
1950-01-01 07:00:00               -0.544        0.092
1950-01-02 06:00:00                0.374       -0.275
1950-01-02 07:00:00                0.562       -0.260
1950-01-03 06:00:00               -0.200        0.240
1950-01-03 07:00:00               -0.226        0.202

Now, I want to do a "spaghetti plot", where the "spaghetti groups" in one color are determinated whether the curve is diff_1 or diff_2 (so x-axis is the time from 01-01 to 01-03, y-axis are the differences, each "spaghetti" is one year).
I tried to orient at this question:
Plot pandas data frame with year over year data
However, I fear I have got one dimension too many. Any ideas how this could work?
EDIT: The following simple image illustrates what I'm looking for. The multiple lines for one color result from the fact that the time period on the x-axis repeat annually.
Comment: Could you give an example of what you are trying to acomplish? Maybe draw something in paint if it is about plotting or an example dataframe if you are trying to transform your dataframe into something easily plottable.
Comment: It is about both. The result should look like the plot in the linked question, just that in my case "diff_1"/"diff_2" appears in the legend  and there is more than one graph in one color (representing the years).
I've added a very simple graphics that illustrates what I desire.
Answer: This is the best I could do, I am not totally satisfied but it might be good enough:
# add a column with the year so you can pivot on it later.
tdf = df.assign(year=df.index.year)
# make all dates have the same year (a leap one just in case)
tdf.index = df.index.map(lambda x: x.replace(year=2004))
# pivot using years as columns and put them in the topmost level.
tdf = (tdf.pivot(columns='year').swaplevel(0, 1, axis='columns'))
print(tdf)

year                  1949   1950   1949   1950
                    diff_1 diff_1 diff_2 diff_2
2004-01-01 06:00:00 -0.555 -0.654 -0.123  0.572
2004-01-01 07:00:00 -0.654 -0.544  0.230  0.092
2004-01-02 06:00:00 -0.879  0.374  0.012 -0.275
2004-01-02 07:00:00 -0.459  0.562  0.672 -0.260
2004-01-03 06:00:00 -0.588 -0.200  0.980  0.240
2004-01-03 07:00:00 -0.068 -0.226  0.375  0.202

# create a list of as many colors as columns in df
color = [c['color'] for c in plt.rcParams['axes.prop_cycle'][:df.columns.size]]
# plot
ax = plt.subplot()
for year in tdf.columns.levels[0]:
    tdf[year].plot(color=color, legend=False, ax=ax)
plt.legend(ax.lines[:df.columns.size], df.columns, loc='best')
plt.show()

Now customize the tick labels to your heart content.
Comment: Okay, indeed, it seems to be a major undertaking, but obviously it works! :-)


Alter a path alias depending on a node property

Question: I use the Pathauto module and I'm trying to get, for the same content type, two different path aliases depending on a Boolean field that content type has.
I would like to have a path alias like mysite/node_name if the Boolean field value is false and  mysite/[a generic term]/node_name if its value is true.
Is there a way to do this?
Comment: Create a custom node token which outputs a blank string if the node field value is false, and the generic string if it's true. Then use that token as the 2nd URL part, and pathauto will take care of removing the extra slash if the token value is empty
Answer: if you don't won't to create a new token as @Clive mentioned in comment, you can use hook_pathauto_alias_alter in your custom module like the following.
/**
 * Implements hook_pathauto_alias_alter().
 */
function MY_MODULE_pathauto_alias_alter(&$alias, array &$context) {
  if ($context['module'] === 'node' && $context['bundle'] === 'MY_BUNDLE') {
    // Get the node.
    $node = $context['data']['node'];

    // Clean string service.
    $clean_string_service = \Drupal::service('pathauto.alias_cleaner');

    $is_checked = $node->field_SOME_NAME->value;
    //   If your field is checked.
    if ($is_checked === 1) {
      $alias = '/mysite/term/' . $clean_string_service->cleanString($node->label());
    }
    else {
      $alias = '/mysite/' . $clean_string_service->cleanString($node->label());
    }
  }
}


Question on Linear Combinations and Vectors

Question: This is a very simple question I just wanted to make sure I was doing correctly.
Express the vector
$$
\underline{v} = \left(\matrix{2\\-1\\5\\-3\\6}\right)
$$as a linear combination of $\mathbf{e_1}, \mathbf{e_2}, \mathbf{e_3}, \mathbf{e_4}$, and $\mathbf{e_5}$ in $\mathbb{R}^5$.
So would I just write it out as
$$
2\mathbf{e_1}-\mathbf{e_2}+5\mathbf{e_3}-3\mathbf{e_4}+6\mathbf{e_5}
$$
or is there more involved here?
Comment: That is correct.
Comment: Whilst we can infer what you mean by $\mathbf{e_i}$ it would be great to explain what you mean exactly i.e. definition.
Comment: I believe it's just referring to the basis vectors.
Comment: Yes. This is the usual notation for the standard basis vectors
Answer: An easy way to see this is to put the standard basis vectors into a matrix.  This may be overkill, but this question is currently unanswered.
Note that taking each standard basis vector in $\mathbb{R}^5$ as columns into a matrix simply yields the identity matrix $I_5$ or some permutation of it.
$
\begin{align*}
I_5 = [e_1, e_2, e_3, e_4, e_5] =
\begin{bmatrix}
1 & 0 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 & 0 \\
0 & 0 & 1 & 0 & 0 \\
0 & 0 & 0 & 1 & 0 \\
0 & 0 & 0 & 0 & 1 \\
\end{bmatrix}
\end{align*}
$
Now a linear combination can be found by simply multiplying:
$
\begin{align*}
\small
I_5\underline{v} =
\begin{bmatrix}
1 & 0 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 & 0 \\
0 & 0 & 1 & 0 & 0 \\
0 & 0 & 0 & 1 & 0 \\
0 & 0 & 0 & 0 & 1 \\
\end{bmatrix}
\begin{bmatrix}
2 \\
-1 \\
5 \\
-3 \\
6 \\
\end{bmatrix}
&=
2\begin{bmatrix}
1 \\
0 \\
0 \\
0 \\
0 \\
\end{bmatrix}
+
(-1)\begin{bmatrix}
0 \\
1 \\
0 \\
0 \\
0 \\
\end{bmatrix}
+
5\begin{bmatrix}
0 \\
0 \\
1 \\
0 \\
0 \\
\end{bmatrix}
+
(-3)\begin{bmatrix}
0 \\
0 \\
0 \\
1 \\
0 \\
\end{bmatrix}
+
6\begin{bmatrix}
0 \\
0 \\
0 \\
0 \\
1 \\
\end{bmatrix} \\
\\
&=
2e_1 -e_2 +5e_3 - 3e_4 + 6e_5
\end{align*}
$


Ping size limit - FreeBSD

Question: In the man page for FreeBSD ping:

 -s packetsize
         Specify the number of data bytes to be sent.  The default is 56,
         which translates into 64 ICMP data bytes when combined with the 8
         bytes of ICMP header data.  Only the super-user may specify val-
         ues more than default.  This option cannot be used with ping
         sweeps.

Does anyone know how I can let non-superusers send pings larger then 56? Can I increase the default size, or somehow allow -s to be used by non-root users? I am aware of the security implications, that this could allow users to start a ping flood, so if I can restrict this to allowing only a single (shell-less) user, all the better.
Answer: You can modify the source code and change the behavior. You can make the default size bigger, it's on line 98 of ping.c in /usr/src/sbin/ping/. Or you can disable this feature on line 446 by replacing the line with if (0) {. After you change it, run make install.
I have to wonder why you would need a normal user to send a large ICMP message.
Answer: Consider using sudo, EX:
coryj  ALL = NOPASSWD: /bin/ping

This should let user coryj run /bin/ping (caveat: using any args he likes, not just -s) without a password.
Note the security implications of this; see man pages for sudo(8) and sudoers(5).
Comment: Accepted this, seems a little cleaner then modifying the source, though modifying the source affords a little more granular control. Both good solutions. Personally I've been convinced to rethink my original reasons for doing this and accomplish my goals a different way.

Ping size limit - FreeBSD


PHP handle "Failed opening ... for inclusion" error

Question: I have a PHP script that triggers some "Failed opening ... for inclusion" fatal errors while using an external library.
Those errors are completely irrelevant and I would like to be able to handle them (doing basically nothing about those) to avoid errors to be raised.
How can I achieve that in PHP?
Thanks,
DaN
Comment: you cannot handle fatal errors
Comment: http://php.net/manual/en/errorfunc.configuration.php... although you should really get rid of those instead of suppressing them
Answer: If you absolutely want to hide the errors you can take a look at PHP's Error Control Operators. There's usually a reason for errors and/or warnings so it might be better to figure out what's causing these instead of just masking them.
Answer: You can suppress errors from individual statements by preceding it with the @ operator.  For instance:
@require_once('somefile.php');


Create webrtc video, voice call and file transfer using node js step by step Q-A

Question:
If any one  need to add information or edit some information they are welcome.

Hi,
First of  all   this  questions main target is  shear my  experience to  other developers who finding good tutorials about webrtc.i'm  not  going  to explain about webrtc. In  this i add  scourse  code that working  webrtc Video, voice call and  file  transfer example tested by me.

I get webrtc  information  from  https://webrtc.org/ and  get nodejs
  from https://nodejs.org/en/

Ok let  get start

Is  web rtc  need  ssl certificated?

If  you  doing  experiment in you local PC server  no need.  but when  you add  the to live server  Yes  you  need  it.

How  i get  ssl certificate?

one  of  my friend   help  me to  get  that SSl. there  plenty of   tutorials for you read and  watch

How  i get  turn and stun server?

if you go production level  you need to setup those server , but  for test your  project you can get  stun server and  turn servers  for  free.
For Stun server  -  https://gist.github.com/zziuni/3741933
For  Turn server   - Use this link and create free one ( http://numb.viagenie.ca/ ).
I add my working code as a an answer below
Answer: This  is  Working  code  for  webrtc with node js

This  code and  comment that in code not by me. They already there when i got the code. I cant  find code original owner.  but i thanks that developer.If  some found  that developer please  edit this  and add that developer link :)

var express = require('express');

var socket = require('socket.io');
var app = express();
var fs = require('fs');
var https = require('https');

// link  your  https  certicate  path
var options = {
    key: fs.readFileSync('/../../etc/ssl/private/apache-selfsigned.key'),
    cert: fs.readFileSync('/../../etc/ssl/certs/apache-selfsigned.crt')
};

var main = https.createServer(options, app);

var server = main.listen(8443, function() {
    console.log('server up and running at %s port', 8443);
});

/*var server = app.listen(443, function () {
});*/
app.use(express.static('public'));
var io = socket(server);
/*************************/
/*** INTERESTING STUFF ***/
/*************************/
var channels = {};
var sockets = {};
/**
 * Users will connect to the signaling server, after which they'll issue a "join"
 * to join a particular channel. The signaling server keeps track of all sockets
 * who are in a channel, and on join will send out 'addPeer' events to each pair
 * of users in a channel. When clients receive the 'addPeer' even they'll begin
 * setting up an RTCPeerConnection with one another. During this process they'll
 * need to relay ICECandidate information to one another, as well as SessionDescription
 * information. After all of that happens, they'll finally be able to complete
 * the peer connection and will be streaming audio/video between eachother.
 */
io.on('connection', function (socket) {
    var channel;
    socket.channels = {};
    sockets[socket.id] = socket;
    console.log("[" + socket.id + "] connection accepted");
    socket.on('disconnect', function () {
        for (var channel in socket.channels) {
            part(channel);
        }
        console.log("[" + socket.id + "] disconnected");
        delete sockets[socket.id];
    });
    socket.on('join-room', function (config) {
        if (config) {
            channel = config.channel;
            var userdata = config.userdata;
            var userID = config.userdata.userID;
            if (channel in socket.channels) {
                console.log("[" + socket.id + "] ERROR: already joined ", channel);
                return;
            }
            if (!(channel in channels)) {
                channels[channel] = {};
            }
            for (id in channels[channel]) {
                channels[channel][id].emit('addPeer-room', {'peer_id': socket.id, 'should_create_offer': false});
                socket.emit('addPeer-room', {'peer_id': id, 'should_create_offer': true});
                console.log("what  is this  id -> ", id);
            }
            console.log(config.userdata.name, ' joining room', config.channel);
            socket.join(config.channel);
            socket.broadcast.in(config.channel).emit('room-users', config);
            channels[channel][socket.id] = socket;
            socket.channels[channel] = channel;
        }
    });
    function part(channel) {
        console.log("[" + socket.id + "] part ");
        if (!(channel in socket.channels)) {
            console.log("[" + socket.id + "] ERROR: not in ", channel);
            return;
        }
        delete socket.channels[channel];
        delete channels[channel][socket.id];
        for (id in channels[channel]) {
            channels[channel][id].emit('removePeer', {'peer_id': socket.id});
            socket.emit('removePeer', {'peer_id': id});
        }
    }

    socket.on('part', part);
    socket.on('relayICECandidate-room', function (config) {
        var peer_id = config.peer_id;
        var ice_candidate = config.ice_candidate;
        console.log("[" + socket.id + "] relaying ICE candidate to [" + peer_id + "] ", ice_candidate);
        if (peer_id in sockets) {
            sockets[peer_id].emit('iceCandidate-room', {'peer_id': socket.id, 'ice_candidate': ice_candidate});
        }
    });
    socket.on('relaySessionDescription-room', function (config) {
        var peer_id = config.peer_id;
        var session_description = config.session_description;
        console.log("[" + socket.id + "] relaying session description to [" + peer_id + "] ", session_description);
        if (peer_id in sockets) {
            sockets[peer_id].emit('sessionDescription-room', {
                'peer_id': socket.id,
                'session_description': session_description
            });
        }
    });
    // this for  file  transfer
    socket.on('file-send-room', function (file) {
        console.log(file);
        socket.to(channel).emit('file-out-room', file);
    });
    socket.on('file-send-room-result', function (file) {
        console.log(file);
        socket.to(channel).emit('file-out-room-result', file);
    });
});
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

<form id="fileInfo">
    <input type="file" id="fileInput" name="files"/>
</form>

Comment: Hi, can you guide me bit more about this? I have to implement it in my Linux operating system. Need guide about the server configuration and where to place the code files?


I deleted a page on website but it's still showing up 24 hours later

Question: Yesterday as I was uploading changes to a website that I'm working on the server stopped showing the changed files. After making several changes to the file and repeatedly uploading it to no avail, I deleted the file on the server. Hoping that it would now show a 404 error when I cleared the cache in my browser and refreshed the page, I was sorely disappointed.
Does anyone have any suggestions on things to try? It is an A2 Hosting reseller account.
Comment: after making sure, that you have uploaded you content into the correct DocumentRoot, the only cause is cache in between. try to send '?' at the end of your address in the browser to make sure that you also bypass any cache, if there is any in between.like: http://www.text.com/??
Comment: @ZarehK This was my first thought. Therefore I cleared the cache and refreshed the page and still got the same result.
Answer: Make sure that you are working on the correct document root path of the website and do a test from another system/proxy URL.
Comment: ALong the same lines, try accessing a file in the same directory that you know is NOT there, and verify you get 404.  Then create the file using the same path and methods; see if the file appears.  If not, most likely you're not editing the working copies.
Comment: @Ryan This wasn't even a question as I had just made changes to the homepage that reflected instantly. When I couldn't get this page to reflect the changes I deleted it on the server and then attempted to access it from a browser hoping to see a 404 error. When the same page still showed up I had friends and family in other states access the link and they saw the same thing.
Comment: @JeffLearman I tried this as well and got the same thing. This is why I'm scratching my head and pulling my hair out.
Answer: I was able to find the culprit. Apparently there was an .htaccess file outside of the root folder that was using a redirect from this URI to a duplicate file of it on the server. After deleting that .htaccess file (as it wasn't needed) and then refreshing the page I now got the desired result. I am working on a redesign of a site that was created by someone else so I'm not quite sure why that .htaccess file was there or why there were duplicate files. Thank you guys for your suggestions though.
Comment: Good one!  Select your answer as the answer to the question so everyone can see that it's handled, and anyone referring to this in the future can see.


GAE Soft private memory limit error on post requests

Question: I am working on an application where I am using the paid services of Google app engine. In the application I am parsing a large xml file and trying to extracting data to the datastore.  But while performing this task GAE is throwing me an error as below.
I also tried to change the performance setting by increasing frontend instance class from F1 to F2.
ERROR:
Exceeded soft private memory limit of 128 MB with 133 MB after  servicing 14 requests total.
After handling this request, the process that handled this request was found to be using too much memory and was terminated. This is likely to cause a new process to be used for the next request to your application. If you see this message frequently, you may have a memory leak in your application.
Thank you in advance.
Answer: When you face the Exceeded soft private memory limit error you have two alternatives to follow:

To upgrade your instance to a more powerful one, which gives you more memory.
To reduce the chunks of data you process in each request. You could split the XML file to smaller pieces and keep the smaller instance doing the work.
Comment: Please, how do you upgrade the Instance class on the Google Cloud Console?
Comment: For AppEngine apps, you cannot do it from the console, you'll need to change it on your app.yaml and re-deploy. Most probably, just like you've done when increasing from F1 to F2
Answer: I agree with Mario's answer.  Your options are indeed to either upgrade to an Instance class with more memory such as F2 or F3 or process these XML files in smaller chunks.
To help you decide what would be the best path for this task, you would need to know if these XML files to be processed will grow in size.  If the XML file(s) will remain approximately this size, you can likely just upgrade the instance class for a quick fix.
If the files can grow in size, then augmenting the instance memory may only buy you more time before encountering this limit again.  In this case, your ideal option would be to use a stream to parse the XML file(s) in smaller units, consuming less memory.  In Python, xml.sax can be used to accomplish just that as the parse method can accept streams.  You would need to implement your own ContentHandler methods.
In your case, the file is coming from the POST request but if the file were coming from Cloud Storage, you should be able to use the client library to stream the content through to the parser.
Answer: I had a similar problem, almost sure it's my usage of /tmp directory was causing it, this directory is mounted in memory which was causing it. So, if you are writing any files into /tmp don't forget to remove them!
Another option is that you actully have a memory leak! It says after servicing 14 requests - this means the getting more powerful instance will only delay the error. I would recommend cleaning memory, now I don't know what your code looks like, I'm trying following with my code:
import gc

# ...

@app.route('/fetch_data')
def fetch_data():
    data_object = fetch_data_from_db()
    uploader = AnotherHeavyObject()

    # ...
    response = extract_data(data_object)

    del data_object
    del uploader
    gc.collect()

    return response

After trying things above, now it seems that issue was with FuturesSession - related to this https://github.com/ross/requests-futures/issues/20. So perhaps it's another library you're using - but just be warned that some of those libraries leak memory - and AppEngine preserves state - so whatever is not cleaned out - stays in memory, and affects following requests on that same instance.


Is there any way to view history of time-zone settings in Windows Server 2008?

Question: One of our servers has been set with an incorrect time zone for months and it has affected some of our data in SQL Server. Is there any way to see when time zone settings were made on the server?
Answer: I changed the time on my workstation and it wrote an event to the windows system event log with an eventId of 1.  Text of log below:
<code>The system time has changed to 2011-08-18T18:49:24.356138400Z from 2011-08-18T18:49:24.356138400Z.
</code>
Answer: if you check the system logs it will show when the time change was done.


How to change Android emulator booting animation

Question: How to change Android emulator booting animation
Comment: I don't think that's a string.
Comment: I don't think you can change it, why would you anyway?
Comment: I think this question would *probably* be a better fit for either [SuperUser](http://superuser.com) or [Android Enthusiasts](http://android.stackexchange.com), but I can't decide which.
Comment: Please don't tell me that is a client requirement.
Comment: That is almost certainly an image, and is most definitely baked into the firmware. If you want to change it, you'll have to create your own ROM.
Answer: The emulator uses an Android OS image to boot. You can't change this without changing the image. This isn't emulator specific, but for Android in general.
For more information on how to do that, you might look here, or just google "android change boot animation".
Once you have a new system image, run emulator -help-disk-images from your sdk/tools folder to see a ton of useful info about using disk images with your emulator. It tells you where to put the file, which differs depending on whether you're using the standard SDK or not.
Answer: That is not a string, it is a bootanimation. You can't set it to another text. You can change it so it is another animation though.
If you want to see other possible boot animations, google android boot animations.
Answer: For some reason, this is what most of my students and trainee ask about in every customization class.
The answer for that is - Of course you can modify that image .
To make a long story short:
You can actually do it for every device by storing a noncompressed zip file at /data/local/bootanimation.zip  (just copy from CyanoGenMod and make sense of the animation layout and timing - that's the easiest way, and it explains much better than any explaination).
As I wrote in some other StackOverflow post, there are a couple of places you can do that (I disregard the encrypted case for the sake of simplicity):
system/media   and /data/local/ .
The latter is preferable as it makes it easier to modify, and does not require the tedious
modification of the system.img (system partition) size.
Note that bootanimation.zip should be lowercase, and -0 compressed.
That is argueably the easiest Android customization (Well, if you have good graphic designers...)
Answer: That's not part of your application, is emulating an device. Remember that each android device have it's own Start up images and icons that can be related to the carrier or the brand of the phone, etc.
You cannot change that image, anyhow for what propose you want to change that?
Comment: Yes you can. Changing boot animations is a common customization for rooted users. For the emulator, it's not much different.
Comment: but what's the purpose of that, when you are developing an app?...no one would see that change.
Comment: I don't think the OP expects users to see it, I think he just wants to change the emulator animation. True, it would probably be better on android.stackexchange.com, since it's not really a programming question. That's why I voted to close it.
Answer: Place a animation file in location /system/media/bootanimation.zip to override boot animation.
If you google around, you will find lot of tools to help you create boot animation (even from videos).


Correlation between Binary and N-dimensional simplexes

Question: I found an interesting correlation between binary numbers and $n$-dimensional simplexes and I'm trying to find where I can find more information on the subject.
I noticed that binary representations of numbers index the elements of an $n$-dimensional simplex in perfect order of construction.
For example take a tetrahedron. $n=3$ as it is three dimensions.
It has the elements:
1 cell
4 faces
6 edges
4 points

That is a total of $2^{n+1}-1$ elements equalling 15.
If you take all binary numbers between from 1 - 15 and count the sum of the digits for each you get:
1 - 1
10 - 1
11 - 2
100 - 1
101 - 2
110 - 2
111 - 3
1000 - 1
1001 - 2
1010 - 2
1011 - 3
1100 - 2
1101 - 3
1110 - 3
1111 - 4

Now count the numbers of times each sum amount appears.
sum - count
4 - 1
3 - 4
2 - 6
1 - 4

The counts are the same as the number of each element in the tetrahedron, therefore any binary number whose digits sum 2 for example, can be used to represent an edge, 3 for faces, 1 for points, 4 for cells etc.
Not only do the sum counts match the number of elements in the simplex but surprisingly the order in which they appear, by counting by 1 binary number at a time, matches the logical order of the simplexes construction.
1 - 1 - point
10 - 1 - point
11 - 2 - edge
100 - 1 - point
101 - 2 - edge
110 - 2 - edge
111 - 3 - face
1000 - 1 - point
1001 - 2 - edge
1010 - 2 - edge
1011 - 3 - face

Notice how no edges appear until there are two free points to connect, no faces until three edges to fill etc.
Can somebody explain to me what applications this has or where I can find material on this subject?
Answer: It seems the following.
Let $n$ be a natural number, $X=\{x_0,x_1,\dots, x_n\}$ be a set of vertices of an $n$-dimensional simplex and $B$ be the set of binary sequences of length $n+1$. Then $|B|=2^{n+1}$. For each sequence $b=(b_0,\dots, b_n)$ let $c(b)=\operatorname{conv}\{x_i: b_i=1\}$ be a convex hull of a set $\{x_i: b_i=1\}$  of vertices of the simplex $S$. Then the map $c$ enumerates vertices, edges, faces, cells, etc. of the simplex $S$. In particular, a total number of faces of the simplex $S$ is equal to $2^{n}$ (here we count the empty set as a unique $(-1)$-dimensional face of the simplex $S$) and a number of $d$-dimensional faces of the simplex $S$ is equal to the number of binary sequences in $B$ with sum $d+1$ of the digits and is equal to ${n+1 \choose d+1}$. Moreover, the set $B$ has two orders. The first of them if the usual order $"\le"$ of binary naturals. The second order $"\subset"$ is a majorization. For each sequences $b,b'$ from $B$ we put $b\subset b'$ provided $b_i\le b_i'$ for each $i=0,1,\dots,n$. Clearly, $b\subset b'$ iff $c(b)\subset c(b')$. Moreover, $b\subset b'$ implies $b\le b'$, which explains your last observation.
Answer: Write an $n+1$-digit binary number using leading zeros
(so there are always $n+1$ digits).
Let each digit correspond to a vertex of an $n$-dimensional simplex.
The binary number then represents a subset of the vertices of the simplex:
if the value of a digit is $1$ then the corresponding vertex is a member
of the subset, and if the digit is $0$ then the corresponding vertex is
not a member of the subset.
Now identify the entire simplex with the set of all vertices.
Identify each of the $(n-1)$-dimensional "faces" of the simplex by the $n$
vertices that lie on that "face";
identify each $(n-2)$-dimensional "faces" of the simplex by the $n-1$
vertices that lie on that "face"; and so forth.
Sooner or later you get down to subsets of $3$ points each,
which you identify with the $2$-dimensional faces on which those
points lie, then subsets of $2$ points each, which you identify with
the edges of which the points are endpoints, and finally
subsets of $1$ point each, each of which you simply identify with a vertex.
And of course the binary number corresponding to any particular subset of $k+1$ elements
has exactly $k+1$ digits whose values are $1$ (and the remaining digits are zeros).
Now to make the numbers look more like "normal" binary numbers, simply don't write
the leading zeros. Any subset of vertices of an $n$-dimensional simplex
then can be identified with a binary number of up to $n+1$ digits.
So not only can you put the "faces" of dimension $k$ in the
$n$-dimensional simplex into correspondence with the
set of binary numbers up to $n+1$ digits (excluding the number $0$),
but there is a simple, straightforward way to make the correspondence.
As you count these binary numbers in numeric sequence from $1$ to $2^{n+1},$
you can "construct" the corresponding objects within the simplex.
A number with $k+1$ digits that are $1$ will be greater than any
number that has only a subset of those digits set to $1$ (and zeros in all other digits),
so you can be assured that no edge will be constructed until both
its endpoints have been constructed,
no $2$-dimensional face will be constructed until all the edges that bound it
have been constructed, and so forth.
Since both the elements of the simplex and the binary numbers up to
$n+1$ digits correspond to subsets of a set of $n+1$ elements,
we can use well-known results on sets to enumerate them.
The number of $(k+1)$-element subsets is $\binom{n+1}{k+1}$ for $0 \leq k \leq n,$
so that is also the number of $k$-dimensional "faces" of the simplex
and the number of binary numbers (up to $n+1$ digits)
in which $k+1$ digits have value $1$.


How to get a list of all displays of every view?

Question: I'm doing some test and I'm trying to get a list of all the displays of every view to do the test things in every display of every view, but I don't have any idea how to do it.
When using views_get_all_views() I only get the first display of every view, but what I want is every view and everything inside that view.
Answer: Please find the following drush one-liner to list all the views including all display names:
drush eval 'foreach (views_get_all_views() as $view) { foreach ($view->display as $display => $data) { print "$view->name: $display\n"; }; }'

Modify the code as required.
Comment: Check: [How to get the path for a view](http://stackoverflow.com/questions/24884091/how-to-get-the-path-for-a-view).
Comment: thanks, its seems getting to what i want but... somehow it only shows me the view name, i cannot (or don't know how to) reach things like title or path
Comment: Use: `var_dump($view);`, `dsm($view);`, `dd($view);` to browse through $view object. It's quite big, so it's a bit painful. Otherwise google what you're looking for, or edit the view, export it, and check in the exported code for the appropriate object paths.
Comment: i've tried with var_dump (using simpletest, not drush, i don't know how to use drush) and i'm tring to get the path using $data->{'handler'}->{'display_options'}['path'] and i get "" i tried every way i know to get that data but i don't get it :S


Painting harmonic waves Android

Question: I am making an app that looks like the pic below, the bottom harmonic wave doesn't change but the top one will by setting the amplitude, omega, omega inverse and phi.

I have x and y lines but I cant seem figure out how to even paint the bottom wave, y = sin(x). I have searched and tried to do it but have failed. Can anyone help or give direction to a resource that will help?
Comment: How did you paint the top one? Should be the same, but with a y offset.
Comment: I didn't paint either waves, that's what I am trying to do
Comment: Look at the sensors/accelerometer thing in legacy sdk samples to get an idea.
Comment: Nothing moves. I am trying to draw a basic harmonic wave
Answer: This is a simple example drawing two sine waves, taking care of view size changes, some axis scaling and  simulation stepping.

<com.pixdart.view.HarmonicCustomView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DDD"/>

public class HarmonicCustomView extends View {

    private Paint mPaint = new Paint();
    private RectF mRectF = new RectF();
    private float scaleY, scaleX;
    public static final float STEP_X = 0.1f;
    public static final int PERIODS_TO_SHOW = 5;

    public HarmonicCustomView(Context context) {
        super(context);
        initialize();
    }

    public HarmonicCustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize();
    }

    public HarmonicCustomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mRectF.set(0, 0, w, h);
        mRectF.inset(mRectF.width() * 0.1f, mRectF.height() * 0.1f);
        scaleX = (float) (2 * Math.PI * PERIODS_TO_SHOW / mRectF.width());
        scaleY = mRectF.height() / 6;
    }

    public void initialize() {
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(2f);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        mPaint.setColor(0xFFFF0000);
        for (float x = 0; x < mRectF.width(); x += STEP_X) {
            float y = (float) (Math.sin(x * scaleX)) * scaleY;
            canvas.drawPoint(x + mRectF.left, y + mRectF.top + scaleY, mPaint);
        }

        mPaint.setColor(0xFF0000FF);
        for (float x = 0; x < mRectF.width(); x += STEP_X) {
            float y = (float) (Math.sin(x * scaleX)) * scaleY;
            canvas.drawPoint(x + mRectF.left, y + mRectF.top + scaleY * 5, mPaint);
        }
    }
}

Painting harmonic waves Android


how to connect two machines together without a switch (opensolaris + linux or solaris or aix or hpux)

Question: I have two machines with same subnets  X.Y.Z.1 and X.Y.Z.2
I connect them directly with a crossover cable.
I can
$ ping X.Y.Z.2
from X.Y.Z.1
and the response is machine 2 is alive
but if I do something like
$ ping -s X.Y.Z.2
it hangs.
machine 1 is open solaris.
Machine 2 has been hpUX, LINUX and Solaris Sparc
second test
$ssh X.Y.Z.2
connects and asks for DSA key, which I accept with "yes", then it hangs
Answer: Your problems are due to not having dns working.  It looks like Solaris ping -s hangs if dns lookups don't work.  ssh also tries to do a reverse dns lookup on connections so it will hang for a long time if dns doesn't work.
To make ssh work, you should be able to edit the /etc/ssh/sshd_config file on the server and add
UseDNS no

and of course instead of using ping -s just use regular ping without the -s to disable the dns lookups.
Answer: Are you sure it is hanging and not just timing out while ssh is attempting to do a DNS lookup? Try waiting 60 seconds and see what happens. I'll bet it works.


Finding a type such that $X + 1 \not\simeq X$ and $X+2\simeq X$

Question: Yesterday, I read the following question : Finding a space such that $X\cong X+2$ and $X\not\cong X+1$, and found the result very astounding.
Does it still hold in homotopy type theory? As a type theorist, I don't really understand the answer…
I tried to redo the proof, translating it in type-theoretic words, but and I don't seem to find a description of Stone-Čech compactification easily translatable to HoTT.
Is there an analogous of SČ-compactification in homotopy type theory (or at least, a description of $\beta\mathbb N$)?
Comment: @Najib See https://groups.google.com/forum/#!topic/HomotopyTypeTheory/Wf-H6rH155g for several thoughtful comments on the "space vs. homotopy type" issue.
Comment: @KevinQuirin - You wrote "$X+1\not\simeq1$ and $X+2\simeq X$", but I suspect you mean "$X+1\not\simeq X$ and $X+2\simeq X$".
Comment: Correct me if I'm wrong, but in HoTT a type is simply a space, and equivalence of types is simply homotopy equivalence of spaces, right? So what makes you think that result holds "in topology" but not "in HoTT"?
Comment: @NajibIdrissi Actually, a type is more a infinity-groupoid than a space, so some results true in usual topology might be false in HoTT, or at least need a generalization
Comment: I've always been taught that an $\infty$-groupoid is "the same thing" as a space (there's a Quillen equivalence, so from the point of view of homotopy there's not much difference). Can you give an example of a result (of a similar nature as this one) holding in topology but not in HoTT?
Comment: @IngoBlechschmidt Ah, I see the problem. I assumed that the question linked at the top was using $\cong$ to denote homotopy equivalence (a rather stupid assumption to be honest, I was probably confused by the context), and that they had constructed a space $X$ such that $X$ was htpy.eq. to $X+2$ but not $X+1$. My mistake. My point (and it's now in Mike Shulman's answer) was that this question is nothing special about HoTT, it's simply a question about spaces and homotopy equivalences of spaces.
Answer: The question you linked to is, if I understand it correctly, asking about homeomorphism of topological spaces (that's what the symbol $\cong$ usually means).  Types in HoTT behave like $\infty$-groupoids, which can (classically) be presented by topological spaces, but only up to homotopy equivalence.  So the first question is whether for the example spaces listed, it might still be the case that $X+1\simeq X$ even though $X+1\not\cong X$.  I don't know.  However, if it does happen that $X+1\not\simeq X$ as well, then it will automatically be true in the "standard" model of HoTT (where types are interpreted by classical $\infty$-groupoids) that such a type exists.  However, that is a very different thing from saying that such a type can be constructed inside the formal system of HoTT.  In particular, the Stone-Cech compactification is an operation on topological spaces, not on $\infty$-groupoids, so there is no obvious way to give it meaning inside HoTT.
Comment: My bad, I thought at first that the original question was about homotopy equivalence, and then realised my mistake. However, I don't seem to find a reason for such a type not to exist, and my only hint so far is to check whether the homeomorphisms presented can be changed into homotopy equivalences
Comment: @KevinQuirin A homeomorphism is a particular case of homotopy equivalence. What you want to show is that there is no homotopy equivalence $X+1 \simeq X$ (so far all you know is that there's no homeomorphism), not that the homeomorphism $X \cong X+2$ "can be changed into a homotopy equivalence" (which is obvious since it's already one).


How can we make an assumption on something undefined?

Question: I have been learning generating functions lately, and I love the concept that when we represent a sequence in the form of a polynomial, the coefficient of $x$ has some meaning, the power of $x$ has some meaning, but $x$ itself does not carry any meaning.. the abstraction is beautiful. But here is where I have a doubt - say we have a generating function of the form -
$$1+x+x^2+x^3+\cdots$$
Now, in almost every text I have read, this generating function is written as -
$$1 + x^2+x^3+ \cdots = \sum_{n=0}^{\infty}x^n =\frac{1}{1-x}$$
I understand that the generating function here is actually a geometric series. And the summation of geometric series is -
$$\frac{a(r^n-1)}{r-1}$$ where $a$ is the first element and $r$ is the common ratio. Now, when $n \rightarrow \infty$, we can say -
$$\frac{a(r^{\infty}-1)}{r-1} \approx \frac{a}{1-r}$$ iff $r \in (0,1)$.
Now, my question is, in case of the generating function stated above, $r=x$ and we have already seen that $x$ itself is not defined. So, how can we write that - $$1+x+x^2+x^3+\cdots =\frac{1}{1-x}$$ without knowing anything about $x$ and obviously without making sure that it lies between $(0,1)$. How can we make assumptions on a variable that is itself undefined? and even if we did make an assumption, where did we prove that our assumption holds good?
Can someone please clarify this to me?.. thank you so much..
Comment: I've seen generating functions in some versions treated like "formal power series", i.e. one disregards convergence issues and only uses such series to keep track of things. One can then define operations on them like Cauchy product, or formal derivative, etc.
Comment: No reputable text could say something converges which doesn't.
Comment: Well typically one only needs such series to have nonzero radius of convergence to justify working with them, I'm saying I've seen treatments where convergence or non-convergence is not even considered. Of course it would be wrong to say one converged if it actually does not. Could you cite any examples where such erroneous statements about convergence are actually made?
Comment: I have looked through Tucker's sections on generating functions, and haven't found any place where it's assumed without proof that the infinite series converge.
Comment: @coffeemath I see.. but there are a lot of problems where the infinite generating polynomials are assumed to converge.. I don't know on what grounds can they do that..
Comment: yes surely! @coffeemath I have been reading Applied Combinatorics by Tucker and a note on generating functions by prof Michel Goemans, I saw it there.. and even in almost every text, I have found it.. say, when we go on to solve some recurrences using generating functions, we assume such erroneous statments.. I will post it in the form of another question.. give me some time..
Comment: Just for fun, here's a demo of using Python's big integers to produce [some Fibonacci numbers via the generating function](https://sagecell.sagemath.org/?z=eJyrULBVMDTQ0jKxVigoyswr0QBxzI0U9PUVNCq0tIx0K3QNNTUBsVUIxg==⟨=python).
Comment: It's there in a certain recurrence relation problem from the same book.. I will post it if needed, give me some time..
Answer: There are a few ways to resolve this issue formally.
(I) Simply say a generating function equals a given formula with the implicit assumption $x$ is in the domain of convergence, whatever that is.
(II) Think of a generating function $\sum f_n x^n$ as a cute shorthand for a function $f$ with domain $\mathbb{N}$. Then the sum and product of generating functions correspond to pointwise sum and convolution of the corresponding coefficient functions. Note different coefficient functions $f$, when turned into power series, can essentially be the same function of $x$ defined on the same domain, for instance $f_n=n!$ and $g_n=n!^2$ both define the constant function $1$ defined on the domain $\{0\}$.
(III) Think of infinite polynomials as elements of the formal power series ring $\mathbb{F}[[x]]$ with the so-called "$(x)$-adic topology." Here, $x$ does not represent an unknown number in the field $\mathbb{F}$ (whatever field you're using), but rather a new transcendental element. The topology is defined by the metric $d(f,g)=c^{-n}$ where $c>1$ is some constant and the first nonzero term in $f-g$ contains the power $x^n$. Thus, the more initial terms two formal power series have in common, the "closer" they are. In particular, higher powers of $x$ are closer and closer to $0$ in this topology (just like for actual numbers $x$ with $|x|<1$, but this is an artificial construction with $x$ not representing a number). Note all nonzero scalars are equally and maximally far away from being $0$ as possible (although this changes if you upgrade to formal Laurent series which may include negative powers of $x$).
In all three settings, the equation $1+x+x^2+\cdots=(1-x)^{-1}$ is to be interpreted as saying the element $1+x+x^2+\cdots$ is the multiplicative inverse of the element $1-x$.
Comment: wow! thank you so much for these interesting interpretations.. although I do not understand the complete picture clearly, I will, with time.. your answer is somewhat advanced for me, but still I will vote it up, since I appreciate your efforts very much, and because I know I will be grasping it in some day's time.. thank you!
Comment: It might be worth noting that both (II) and (III) both describe $\mathbb F[[x]]$ - I've seen both ways used to define formal power series (among other definitions). That is to say, in case the readers might not already be familiar with this, (II) and (III) are essentially different descriptions of the same object*, where (I) is a closely related, but different object. (*Noting that (III) defines sums topologically and (II) does so formally - but the underlying arithmetic system is the same, and one could switch things and use formal sums in (III) or topological ones in (II) if they so wished)
Answer: From an algebraic standpoint, the manipulation of generating functions is nothing more than the algebra on formal power series.
A generating function is fully determined by the infinite sequence of its coefficients (and vice versa). For instance, notice in the treatment on Wikipedia [1] how addition and multiplication of formal series can be defined solely on the sequence of coefficients. Of course you can obtain those formulas by computing as with real or complex numbers with $x$ considered an "indeterminate number."
It's not an entirely trivial algebraic matter though. For instance the Cauchy product that defines multiplication of formal power series can be defined purely algebraically without considerations on convergence because each coefficient in the product of two series only depends on a finite number of coefficients of each factor. In other words, finite sums of finite products of real or complex numbers only require algebra, no analysis.
From that viewpoint, the answer to your question is that we are not making any assumption on $x$. For instance, ${1-x}$ is the inverse formal power series* to the formal power series $1+x+x^2+x^3+\cdots$, meaning that $(1+x+x^2+x^3+\cdots)
(1-x) = 1$.
*A polynomial is a particular case of a formal power series, where coefficients past a certain degree are all zero.
[1] https://en.wikipedia.org/wiki/Formal_power_series#The_ring_of_formal_power_series
Comment: Thank you so much for your explanation! This helped a lot!


Query in writing the test case validations in selenium webdriver using TestNg

Question: I am doing the Automation testing for the web-app made of angular using selenium webdriver with test Ng.In that i find some difficulties in switching between the various views in the web-app.
Suggest me some ideas to switch between the multiple views selenium webdriver using TestNg.
Answer: I recommend you to use protractor to write test for angularJS apps.
Comment: Why then what is the difference between the testNg and Protractor.
Comment: TestNG is a testing framework;
Protractor is an end-to-end test framework for AngularJS applications


Remove date element from datetime while making line graph in r

Question: I have a data frame containing the average steps count of various people by hours of the day. I used the POSIXct function to render by-hour data in date-time readable form, but the function automatically assigns today's date to my variables. I want to create a line graph by ggplot and I don't want the labels to show the date as well.
av_steps_by_hour$time = as.POSIXct(av_steps_by_hour$time, format = "%H:%M:%S")
ggplot(data = av_steps_by_hour) + geom_line(aes(x = time, y = steps))

enter image description here
Answer: You need to first convert the data to POSITXct, then format it.
First convert the data
now <- as.POSIXlt(Sys.time()))

Then format it
format(now, "%H:%M:%S")
[1] "07:52:30"

Here is a reproducible example:
library(ggplot2)

av_steps_by_hour = data.frame(time = (Sys.time()), steps = c(1:4))

av_steps_by_hour$time = as.POSIXct(av_steps_by_hour$time)

av_steps_by_hour$time = format(av_steps_by_hour$time, "%H:%M:%S")

ggplot(data = av_steps_by_hour) + geom_line(aes(x = time, y = steps))

Answer: You can format the dates/times before plotting (as ViviG shows), or specify the format using the scale_x_datetime() function, e.g.
library(tidyverse)
av_steps_by_hour = data.frame(time = as.POSIXct(c("00:00:00", "06:00:00", "12:00:00", "18:00:00"),
                                                format = "%H:%M:%S", origin = "1970-01-01"),
                              steps = c(1000, 1001, 1010, 1500))
# 'Before'
ggplot(data = av_steps_by_hour) +
  geom_line(aes(x = time, y = steps))

# 'After'
ggplot(data = av_steps_by_hour) +
  geom_line(aes(x = time, y = steps)) +
  scale_x_datetime(date_labels = "%H:%M:%S")

Created on 2022-08-18 by the reprex package (v2.0.1)


Problem with Endorsment Policy with Fabric GO SDK

Question: I have a hyperledger fabric testnet with 2 orgs, 3 peers in org1 and 2 peers in org2. The peer0 of each organization is the anchor peer. I want to instantiate a chaincode with an endorsment policy with only one organization: Org1, so I specify the policy: "AND('org1MSP.member')".
I've installed the chaincode in the peers of the org1 only, because org2 is not endorser. However, the chaincode doesn't instantiate because it sending the proposal to the peers that are in the other organization (org2).
The problem is because these peers in the org2 don't have the chaincode installed, but...why the SDK is sending the endorsement request to the peers that not belongs to the endorsement policy?
Here's is my config file, as you can see I only have one peer of the org1: https://gist.github.com/mtnieto/02dd17097de64a73bd627594056598ed
I have add to the config the following features, but it's not working.
channels:

  # multi-org test channel
  examplechannel:

    peers:
      peer0.org1.example.com:
        endorsingPeer: true
        chaincodeQuery: true
        ledgerQuery: true
        eventSource: true
      peer1.org1.example.com:
        endorsingPeer: false
        chaincodeQuery: false
        ledgerQuery: true
        eventSource: true

      peer2.org1.example.com:
        endorsingPeer: false
        chaincodeQuery: false
        ledgerQuery: true
        eventSource: true

      peer0.org2.example.com:
        endorsingPeer: false
        chaincodeQuery: false
        ledgerQuery: true
        eventSource: true

      peer1.org2.example.com:
        endorsingPeer: false
        chaincodeQuery: false
        ledgerQuery: true
        eventSource: true

The logs are the following:

"error": "Error creating Chaincode: sending deploy transaction
  proposal failed: Multiple errors occurred: - Transaction processing
  for endorser [peer0.org2.example.com:8051]: Endorser Client Status
  Code: (23) CHAINCODE_NAME_NOT_FOUND. Description: cannot get package
  for chaincode (examplecc:2) - Transaction processing for endorser
  [peer1.org2.example.com:6051]: Endorser Client Status Code: (23)
  CHAINCODE_NAME_NOT_FOUND. Description: cannot get package for
  chaincode (examplecc:2)"

The code to instantiate the chaincode is the following. (In a previously phase I have already installed the chaincode)
sdk, err = fabsdk.New(config.FromFile("config.yaml"))
    if err != nil {
        log.Errorf("Failed to create new SDK: ", err)
        return nil, err
    }

adminContext := sdk.Context("admin", "org1"))
// Org resource management client
orgResMgmt, err := resmgmt.New(adminContext)
if err != nil {
    log.Errorf("Failed to create resource management client %v: ", err)
    return nil, err

}

ccPolicy, err := cauthdsl.FromString(instantiateReq.EndorsmentPolicy)
if err != nil {
    log.Errorf(" Error parsing endorsment policy %v: ", err)
    return "", err
}

instantiateRequest := resmgmt.InstantiateCCRequest{Name: instantiateReq.Name, Path: instantiateReq.Path, Version: instantiateReq.Version, Args: instantiateReq.Args, Policy: ccPolicy}

This happens when the peer is updated to be anchor. In other words, If I don't execute the following commands in the peers when I init the network, the error is not happening.
(in peer0 org1 context)
peer channel update -o orderer0.example.com:7050 -c $CHANNEL_NAME --tls $CORE_PEER_TLS_ENABLED --cafile $ORDERER_CA -f ./channel-artifacts/org1MSPanchors.tx >&log.txt

in peer0 org2 context
peer channel update -o orderer0.example.com:7050 -c $CHANNEL_NAME --tls $CORE_PEER_TLS_ENABLED --cafile $ORDERER_CA -f ./channel-artifacts/org2MSPanchors.tx >&log.txt

Comment: can you share the chaincode instantiation code?meaning while you could teardown the network and start the network again.
Answer: It's a bug in the 1.4.1 version, the not endorser organization is trying to execute lscc and to endorse the transaction.
I have upgrade the network to 1.4.2 and now it seems that the issue has disappeared.


Mirror a function about x = c axis

Question: I'm trying to mirror a function $f(x)$ about the $x=c$ axis. To mirror it about the $x=0$ axis you just have to plot $f(-x)$.
I tried to mirror $f(x) = x^2$ about the $x = c$ axis. And I found that the mirrored function of $f$ is $(x-2c)^2$.
This just works for the $x^2$ function, but I need to mirror any function. How to do that?
Answer: In general, $f(x)$ mirrored across the line $x=c$ is simply $f(2c-x)$. To see this, note that we can mirror $f(x)$ by translating it down by $c$, flipping it and then translating it back up by $c$, which gives
$$f(x)\to f(x-c)\to f(c-x)\to f(2c-x)$$
Comment: @Cobold The situation is almost identical. Just translate along the $y$ axis instead of $x$.
Comment: Thanks! Do you know how to mirror across the line $y=c$?
Answer: This can be simply evaluated by shifting the function by $c$ units towards negative x-axis or in transformation terms $f(x) \rightarrow f(x+c)$ ,finding the mirror image of this new curve along $x=0$, i.e $f(x+c) \rightarrow f(-x+c)$ and then re-shifting the new curve by $c$ units towards right i.e $f(-x+c) \rightarrow f(2c-x)$.Conclusively, the mirror image of any curve $y=f(x)$ about $x=c$ would be given by $y=f(2c-x)$.
Comment: Here is a MathJax tutorial. Please rewrite your answer.

Mirror a function about x = c axis


How to configure an extra/different migrations folder

Question: A colleague and I are working in different projects that share some models. So, we are sharing the models through a git submodule.
Additionally, we'd like to be able to also share migrations:
In this way, my colleague's migrations would be in the folder db/migrate/other_db of my project.
How can I configure rails migrations to also run the migrations in this extra folder?
Answer: In your config file (config/application.rb for all environments or config/environments/$(environment).rb only for particular environment) add this line:
config.paths['db/migrate'] += 'db/migrate/other_db'

And if you want to change default 'db/migrate' path (config.paths['db/migrate'] is an array with one string 'db/migrate' by default), do this:
config.paths['db/migrate'] = ['db/my_migrate']

Here are default config.paths, which we also can change:
"app" => ["app"],
"app/assets" => ["app/assets"],
"app/controllers" => ["app/controllers"],
"app/helpers" => ["app/helpers"],
"app/models" => ["app/models"],
"app/mailers" => ["app/mailers"],
"app/views" => ["app/views"],
"lib" => ["lib"],
"lib/assets" => ["lib/assets"],
"lib/tasks" => ["lib/tasks"],
"config" => ["config"],
"config/environments" => ["config/environments"],
"config/initializers" => ["config/initializers"],
"config/locales" => ["config/locales"],
"config/routes" => ["config/routes.rb"],
"db" => ["db"],
"db/migrate" => ["db/migrate"],
"db/seeds" => ["db/seeds.rb"],
"vendor" => ["vendor"],
"vendor/assets" => ["vendor/assets"],
"vendor/plugins" => ["vendor/plugins"],
"config/database" => ["config/database.yml"],
"config/environment" => ["config/environment.rb"],
"lib/templates" => ["lib/templates"],
"log" => ["log/development.log"],
"public" => ["public"],
"public/javascripts" => ["public/javascripts"],
"public/stylesheets" => ["public/stylesheets"],
"tmp" => ["tmp"],

Comment: The correct answer is `config.paths['db/migrate'] << 'db/migrate/other_db'` for Rails 3 or 4.
Comment: In Rails 4: `config.paths['db/migrate'] << 'db/migrate/other_db'`
Comment: `config.paths['db/migrate'] += ['db/migrate/other_db'] ` would also work.
Comment: @apocalyptiq is there any way to change images and stylesheets directory alone in assets???

Like 'app/assets/images' => 'apples/assets/images' ?
Comment: Note that until at least Rails 4.2, it was not (easily?) possible to override migrations_path because it _always_ attempts to set the default: https://github.com/rails/rails/blob/4-2-stable/activerecord/lib/active_record/migration.rb#L874
Comment: With Rails 6, it picks up the migrations from subdirectory automatically
Answer: Update for Rails 5/6;
Rails 5 recommends setting additional migration paths in your config/database.yml file. It's very easy, see this example;
development:
  migrations_paths:
  - "db/migrate/other_db"
  - "db/migrate/something_else"

ActiveRecord::Migrator.migrations_path= will be deprecated in Rails 6.
Comment: `migration_paths` appears to have been moved to ActiveRecord::DatabaseConfigurations instead of being deprecated: https://github.com/rails/rails/blob/31b1403919eec0973921ab42251bfbbf3d4422b6/activerecord/lib/active_record/database_configurations/hash_config.rb#L45
Comment: Rails 7 documentation: https://api.rubyonrails.org/classes/ActiveRecord/DatabaseConfigurations/HashConfig.html#method-i-migrations_paths
Answer: based on the answer by Swanand, we can write a migration to load the migrations in an external dir:
class MigrateMetadata < ActiveRecord::Migration
  MIGRATIONS_PATH='db/migrate/metadata'
  def self.up
   Dir["#{MIGRATIONS_PATH}/[0-9]*_*.rb"].
   sort.map{|filename|require filename}.flatten.
   each{|class_name| const_get(class_name).up}
  end

  def self.down
    Dir["#{MIGRATIONS_PATH}/[0-9]*_*.rb"].sort.reverse.
    map{|filename|require filename}.flatten.
    each{|class_name| const_get(class_name).down}
  end
end

Answer: I do not know of a very clean way to do it, but the code that runs migrations looks something like:
@migrations ||= begin
        files = Dir["#{@migrations_path}/[0-9]*_*.rb"]

        migrations = files.inject([]) do |klasses, file|
          version, name = file.scan(/([0-9]+)_([_a-z0-9]*).rb/).first

Where,
@migrations_path = 'db/migrate'

So if you change this to read from config file instead, it may work out in your favour. But as I said, this is definitely not a very clean way to do it.
Answer: By the way, if you are building a gem to work with Rails, you can place a block like the following in your rail tie to add the gem's own migrations.
  root = ... # the path to your gem
  initializer :append_migrations do |app|
    unless app.root.to_s.match root
      app.config.paths["db/migrate"] << File.join(root, 'db/migrate')
    end
  end

There is no need to copy migrations from your gem with generators if you use this technique.
You can make a method to yield the root directory of your gem with some thing like this...
module MyGemName
  def root
    File.expand_path '../..', __FILE__
  end

  module_method :root
end

... in the file lib/my_gem_name.rb in your gem.
Answer: Just add this initializer to your lib/engine.rb:
initializer 'your_engine_name.migrations' do |app|
  config.paths['db/migrate'].expanded.each do |expanded_path|
    app.config.paths['db/migrate'] << expanded_path
    ActiveRecord::Migrator.migrations_paths << expanded_path

    if Rake.application.top_level_tasks.empty?
      ActiveRecord::Migration.check_pending! if ActiveRecord::Migrator.needs_migration?
    end
  end

end


How do I load an external class into the Controller?

Question: I'm playing with module building in Drupal 8, but can't really figure out how to include a custom class which does not extend any other. The class' only purpose is to reduce the amount of code I have in a controller.
However, I get the error:

Fatal error: Class 'Drupal\first\FirstClass' not found in /var/www/drupal/modules/first/src/Controller/DefaultController.php on line 30

How do I let DefaultController.php know where to find FirstClass.php? Should I just do an include_once()?
Routing file:
first.default_controller_hello:
  path: 'first/hello/{name}'
  defaults:
    _content: '\Drupal\first\Controller\DefaultController::hello'
    _title: 'first Title'
  requirements:
    _permission: 'access content'

Controller function:
namespace Drupal\first\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\first\FirstClass;

class DefaultController extends ControllerBase {

  /**
   * hello
   * @return string
   */
  public function hello($name)
  {
    $a = new \Drupal\first\FirstClass();
    dsm($a);
    return "Hello ".$name." !" . $a->getV();
  }
}

Outside Class:
<?php
namespace Drupal\first;

class FirstClass {

    public static function getV() {
        return 'well it works?';
    }
}

Comment: You're using an autoloader - it doesn't matter _where_ you're using a class that's registered in the right place, it just matters that you've registered it in the right place (i.e. see the answer to your previous question)
Answer: Drupal 8 uses a autoloader standard called PSR-4: http://www.php-fig.org/psr/psr-4/
Practically means your namespaces should result in the following directory structure
first
  - src
  --- FirstClass.php
  --- Controller
  ----- DefaultController.php
  - first.info.yml

Comment: I request you to be more descriptive.


Dead zones in a bullet trajectory - unity 2d

Question: I'm making a small shooter for two players, everyone can shoot. The problem is that when a bullet flies at high speed, then there are certain zones in its trajectory in which it does not touch the object, and accordingly OnTriggerEnter2d does not work there. Here is the bullet flight script:
<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bullet: MonoBehaviour
{
    Rigidbody2d rb;
    public int Player;
    public float speed = 0.4f;
    public Vector3 mode; // Direction of the bullet (Vector3.left, right)
    // Start is called before the first frame update
    void Start ()
    {
        rb = gameObject.GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void FixedUpdate ()
    {
        rb.velocity = mode * speed;
    }
}

</code>
Comment: So what you want?
Comment: How to fix it??
Comment: Try this: `Rigidbody2D > Collision Detection > Continuous`
Comment: There is no OnTriggerEnter2D in this script. Did you delete it on purpose?
Answer: High speed physics is always a hard nut to crack. Like Iggy mentions you can/should use continuous collision detection.
If you still have issues and still want fast projectiles it get harder. Here are some options.
You can lower the physics time step in time settings (very expensive not recommended but you can test).
You can make the bullet's colliders dynamically bigger. (Might be the simplest easiest solution). When you spawn bullets, calculate based on their speed how long a box collider should be and dynamically position it behind the bullet sorta like a trail (make sure the bullet has moved forward enough to fully expand so you don't hit things behind the player). The box collider's size should be the same as how much distance it moves every frame. That way after moving a tons in a frame all the positions the bullet has been in the frame will trigger a collision on the box collider. For bullet impact and sfx don't spawn them where the bullet is but at the point of contact.
You can calculate if a collision should have happened. (After the physics update check behind the projectile with like a raycast).
You can do your own physics or hybrid. Unity lets you simulate physics when ever you want manually instead of the normal physics update. With more control over that you could add more calculations for fast moving object.


Similar Matrices and Linear Transformations

Question: There is a theorem in the course notes but the lecturer didn't given the proof:
If $A,B\in M_n(K)$, where $K$ is a field. Then $A\sim B$ if and only if they represent the same linear transformation $T$ of an $n$-dimensional vector space $V$ over $K$ with respect to bases $\mathcal{B}$ and $\mathcal{C}$. i.e.,
$$
A\sim B\iff A=[T]_\mathcal{B},\ B=[T]_{\mathcal{C}}.
$$
I know how to prove the '$\Leftarrow$' but I dont think I can prove the other direction '$\Rightarrow$'.
Could please somebody help me?
Comment: Try with $T=$ multiplication by $A$ in the standard basis of $K^n$.
Answer: $A\sim B$ means that there exists an invertible matrix $P$ such that $B=P^{-1}AP$. An invertible matrix $P$ can be considered as the change of basis matrix $P=[I]^E_C$ from the standard basis $E$ of $K^n$ to the basis $C$ of consisting of the columns of the matrix $P$. Thus if you define the linear transformation
$$T:K^n\to K^n$$
by $$T(v)=B\cdot v$$ you will get that $[T]_E=B$ and $[T]_C=[I]^E_C\cdot B\cdot [I]^C_E=PBP^{-1}=A$.
Comment: his question is from an abstract vector space. Not $T: \mathbb{K}^n \rightarrow \mathbb{K}^n$.
Comment: I don't see your point @JamesS.Cook. The OP wants to show that THERE EXISTS an $n$-dimensional vector space $V$ over $K$ such that... What is the problem with taking the $n$-dimensional vector space $V=K^n$?
Comment: Ah, yes, I retract my stupid comment +1. I suppose I'm interested in the slightly more obtuse question involving an abstract vector space.
Comment: So why do A and B represent the same linear transformation?
Answer: If $A \sim B$ then there exists an invertible matrix $P$ for which $B=P^{-1}AP$. Pick a basis $\beta = \{ v_1, \dots, v_n \}$ for $V$ over $\mathbb{K}$ and let $\Phi_{\beta}: V \rightarrow \mathbb{K}^n$ form the coordinate map defined by linearly extending $\Phi_{\beta}(v_i)=e_i$ where $(e_i)_j = \delta_{ij}$ for all $1 \leq i,j \leq n$. Let $Pe_i = \bar{e}_i$ and define $\bar{v}_i=\Phi_{\beta}^{-1}(\bar{e}_i)$. Suppose $T: V \rightarrow V$ is the linear transformation for which $[T]_{\beta,\beta}=A$. In other words, let $T$ be the linear transformation which is represented by $A$ in the $\beta$ basis. In particular, $A = [ \Phi_{\beta} \circ T \circ \Phi_{\beta}^{-1} ]$ where $[..]$ denotes the standard matrix.

I claim that $B = [T]_{\bar{\beta},\bar{\beta}}$.

Proof: Essentially, by definition,
$$ [T]_{\bar{\beta},\bar{\beta}} = [ \Phi_{\bar{\beta}} \circ T \circ \Phi_{\bar{\beta}}^{-1} ]$$
But, the coordinate maps are isomorphisms and we can insert the $\beta$-maps as follows:
\begin{align} [T]_{\bar{\beta},\bar{\beta}} &= [ \Phi_{\bar{\beta}} \circ \Phi_{\beta}^{-1} \circ \Phi_{\beta} \circ T \circ \Phi_{\beta}^{-1} \circ \Phi_{\beta}^{-1}\Phi_{\bar{\beta}} ] \\
&= [ \Phi_{\bar{\beta}} \circ \Phi_{\beta}^{-1}][\Phi_{\beta} \circ T \circ \Phi_{\beta}^{-1}][\Phi_{\beta} \circ \Phi_{\bar{\beta}}^{-1}]
\end{align}
Ok, but what is $[\Phi_{\beta} \circ \Phi_{\bar{\beta}}^{-1}]$?
Recall $Pe_i = \bar{e}_i$ and $\bar{v}_i=\Phi_{\beta}^{-1}(\bar{e}_i)$. Thus $\bar{e}_i = P^{-1}e_i$ and $\Phi_{\beta}(\bar{v}_i)=\bar{e}_i$
The standard matrix is easily calculated as follows:
\begin{align}
[ \Phi_{\beta} \circ \Phi_{\bar{\beta}}^{-1}] &= [ \Phi_{\beta} \circ \Phi_{\bar{\beta}}^{-1}(e_1) | \cdots | \Phi_{\beta} \circ \Phi_{\bar{\beta}}^{-1}(e_n)] \\
&= [ \Phi_{\bar{\beta}}(\bar{v}_1) | \cdots | \Phi_{\bar{\beta}}(\bar{v}_n)] \\
&= [ \bar{e}_1 | \cdots | \bar{e}_n] \\
&= [ Pe_1 | \cdots | Pe_n] \\
&= P[ e_1 | \cdots | e_n] \\
&= P.
\end{align}
Finally, it is easy to see $[ \Phi_{\bar{\beta}} \circ \Phi_{\beta}^{-1}]^{-1}=P^{-1}$ and my claim follows.


How to get separate fields data with IF() statement in single query

Question: I am trying to get the unpaid and partial amount separately in single query
select
    if(i.status = 'unpaid', sum(i.total_amount), '') unpaid,
    if(i.status = 'partial', sum(i.paid_amount), '') partial
from {CI}invoices i
where
    i.customer_id = ? and
    date(i.invoice_date) < '2014-01-01' and
    i.status not like 'paid%'

But i am getting blank i think that is because i used '' in if statement, i also tried with
if(i.status = 'unpaid', sum(i.total_amount) as unpaid, sum(i.paid_amount) as paid)

which is wrong because i can't use as in IF() condition. Can anyone please help me to resolve this query or suggest any alternative way??
Comment: @hjpotter92 can you please elaborate what you want to say, i have set the `decimal` data type for `total_amount`
Answer: Try the following:
SELECT
    SUM( IF(i.status = 'unpaid', i.total_amount, 0) ) unpaid,
    SUM( IF(i.status = 'partial', i.paid_amount, 0) ) partial
FROM {CI}invoices i
WHERE
    i.customer_id = ? AND
    date(i.invoice_date) < '2014-01-01' AND
    i.status IN ('unpaid', 'partial')

Comment: ahh, now it's working but want to ask one thing, `SUM( IF(i.status = 'unpaid', i.total_amount, 0) )` is it mean `IF(i.status = 'unpaid', sum(i.total_amount), sum(0))` or `IF(i.status = 'unpaid', sum(i.total_amount), 0)` ?
Comment: @jogesh_pi You want to sum "after" filtering out the data, not while going through it.
Answer: Give this a go:
select
    sum(case when i.status = 'unpaid' then i.total_amount else 0 end) as unpaid,
    sum(case when i.status = 'partial' then i.paid_amount else 0 end) as partial
from {CI}invoices i
where
    i.customer_id = ? and
    date(i.invoice_date) < '2014-01-01' and
    i.status not like 'paid%'

Answer: You have to cross join table to itself to get paid and unpaid in the same row:
SELECT
    sum(iu.total_amount) unpaid,
    sum(ip.paid_amount) partial
FROM {CI}invoices iu
   CROSS JOIN {CI}invoices ip
where
    ip.customer_id = ? AND iu.customer_id = ? AND
    date(ip.invoice_date) < '2014-01-01' AND date(iu.invoice_date) < '2014-01-01' AND
    iu.status = 'unpaid' AND ip.status = 'partial'


Error: CMySQLCursor.executemany() missing 1 required positional argument: 'seq_params'

Question: I'am working on flask application, and I want to initilize the db when i start the application, so i create a schema file:
schema.sql file contains:
-- Drops
DROP TABLE IF EXISTS `article`;
DROP TABLE IF EXISTS `book`;
DROP TABLE IF EXISTS `settings`;

-- Article
CREATE TABLE `article` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(150) DEFAULT NULL,
  `text` longtext DEFAULT NULL,
  `created_at` date,

  PRIMARY KEY (`id`)
);

-- Book
CREATE TABLE `book` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(150) DEFAULT NULL,
  `description` longtext DEFAULT NULL,
  `img` longtext DEFAULT NULL,
  `link` longtext DEFAULT NULL,
  `created_at` date,

  PRIMARY KEY (`id`)
);

-- Settings
CREATE TABLE `settings` (
  `id` int NOT NULL AUTO_INCREMENT,
  `title` varchar(150) DEFAULT "تَربيَة الأُمةِ مِنْ جَديدٍ",
  `cover_text` varchar(200) DEFAULT "{فَاعْلَمْ أَنَّهُ لَا إِلَٰهَ إِلَّا اللَّهُ}",
  `admin_username` varchar(50) DEFAULT "Admin",
  `admin_password` varchar(50) DEFAULT "12345",
  PRIMARY KEY (`id`)
);

insert into `settings`(`title`,`cover_text`,`admin_username`,`admin_password`) values ("تَربيَة الأُمةِ مِنْ جَديدٍ","{فَاعْلَمْ أَنَّهُ لَا إِلَٰهَ إِلَّا اللَّهُ}","Admin","12345");

Then i use **executemany()** to create my database tables, I write this code:
def init_db():
    _,mycursor = mysql_connector()

    with current_app.open_resource('schema.sql') as f:
        mycursor.executemany(f.read().decode('utf8'))

But when i run by flask --app flaskr init-db there's problem with mycursor.executemany() function.
The Error says:
mycursor.executemany(f.read().decode('utf8'))
TypeError: CMySQLCursor.executemany() missing 1 required positional argument: 'seq_params'

Note: mysql_connector function in 1st line of the code is a function return the cursor of the mysql connector:
config = {
    data...
}

def mysql_connector():
    try:
        g.db = mysql.connector.connect(**config)
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            site_logger.exception("Something is wrong with your username or password")
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
            site_logger.exception("Database does not exist")
        else:
            print("Error: ", err)
            site_logger.exception(err)
        return
    else:
        # Initialize our cursor
        mycursor = g.db.cursor(buffered=True)
        return g.db, mycursor

I tried to change the sql code in schema.sql file but the same problem.
So where's the problem or what's the solution ?
Answer: You need to execute different SQL queries one by one but with executemany() you execute the same SQL query multiple times.
Modify your code like this
def init_db():
    _, mycursor = mysql_connector()

    with current_app.open_resource('schema.sql') as f:
        # Split the file content by semicolon and filter out empty lines
        sql_commands = [cmd.strip() for cmd in f.read().decode('utf8').split(';') if cmd.strip()]

        for cmd in sql_commands:
            mycursor.execute(cmd)


Is showGroupPanel option available in Angular js ui-grid similar to ng-grid?

Question: Does Angular js ui-grid have showGroupPanel option available similar to ng-grid.
If not then is there any other way to implement this feature in ui-grid?
Answer: You are looking for the ui-grid directive: uiGridGrouping


How to use xpath attribute in odoo 10?

Question: i want to learn Odoo xml but a don't understand a lot of things specially on xpath, for example :
<xpath exp="//field[@name='is_done']" position="attributes">
    <attribute name="invisibl">1</attribute>
</xpath>

what is attribute, how it's work, and what mean the value 1 inside the attribute tag
and if do you have guys some resources to learn more that's great
finally thanks a lot
Answer: You need three skills to successfully work with xml in Odoo:

Xml basics.
Xpath basics.
Knowledge of the way Odoo uses xml and xpath.

Xml and Xpath are standards and you can find lots of tutorials and references for these. A simple xml learning resource is https://www.w3schools.com/xml/.
You can find also Xpath material from same site at https://www.w3schools.com/xml/xpath_intro.asp. When you know basics in xml and xpath, you have a good position to learn how to use xml in Odoo.
Odoo uses xml in multiple places, e.g. Qweb templates, module data files and view definitions. You can learn these from Odoo Developer documentation at https://www.odoo.com/documentation/11.0/index.html:

Data files: https://www.odoo.com/documentation/11.0/reference/data.html
Qweb reports: https://www.odoo.com/documentation/11.0/reference/qweb.html
Odoo views: https://www.odoo.com/documentation/11.0/reference/views.html

Data files are plain xml in Odoo specific structure. Qweb reports use a templating language implemented in xml to build reports and views.
Odoo view inheritance uses xpath to locate places is parent document to modify the inherited view. To specifically learn Odoo xpath, take a close look at the Inheritance Specs at https://www.odoo.com/documentation/11.0/reference/views.html#inheritance-specs. The use of attribute is explained there in attributes section.
For editing xml directly in Odoo database you can use the editor in Odoo. This is available for xml fields, e.g. when editing views. It is not fancy, but it can format xml documents and validate that the xml is valid when you save it. For xml data in your modules, you can use other tools, e.g. VisualStudio Code.
Xml is an important part in Odoo architecture. When you master Xml and know how Odoo uses it, you can easily utilize development and customization capatilities in Odoo.
Answer: i would to recommend this document
https://odoo-development.readthedocs.io/en/latest/dev/xml/index.html
your code not correct
so the correct code should be like this
<xpath exp="//field[@name='is_done']" position="attributes">
    <attribute name="invisible">1</attribute>
</xpath>

Comment: And it should be `invisible`

How to use xpath attribute in odoo 10?


Evaluating Classifiers k fold CV or ROC

Question: I've been doing a project to determine the 'best' classifier for classification on a dataset from UCI.
I used 10 fold stratified cross validation to calculate the mean accuracy. However it was suggested that I use ROC AUC instead.
My questions are:
1)Which is better cross validation or ROC?
2) Do you perform ROC on the test set, the training set or the whole dataset?
3) If it is the training set or test set. Do I perform it using each fold from the cross validation or should I just split the data once?
Answer: AUROC is a measure, just like accuracy, both can be used in a CV setting or outside (validation set, test set).

Depends on the objective and your data. You said you used accuracy, could it be that your classes are unbalanced? ROC as a measure is usually used when you have imbalanced classes, this may be why they recommended you use it instead of accuracy
Since you mentioned CV (which is done on the training set) then you would perform the ROC on the training set also, that is using CV but estimating ROC instead of accuracy. If you had a test set you would have no need for CV, you would therefore use the test set to evaluate your model (accuracy, ROC, ...)
CV is a better option then using the same exact training set that you used to build your model, so you would still do CV with a ROC estimate.
Comment: yes the data is unbalanced but the CV was stratified would that change anything?
Comment: Stratified CV is better in case of imbalance, doesn't change the answers.
Comment: @Apocryphon The reason they might have mentioned AUROC is because of the imbalance, in this case accuracy is not a good measure. However this does not mean that you should drop CV altogether, instead use a different measure, have a look at the F-score.
Answer:
1)Which is better cross validation or ROC?

ROC AUC is a metric, just as accuracy, F1-score etc., and shouldn't be confused with cross validation. You can still employ CV and use ROC AUC as your success metric for example.

2) Do you perform ROC on the test set, the training set or the whole
  dataset?

When selecting models you plot ROC curves, report ROC AUC etc. You can also use ROC curve (e.g. AUC) to report the final success of your models. But, test data shouldn't be in your model selection.

3) If it is the training set or test set. Do I perform it using each
  fold from the cross validation or should I just split the data once?

If your success metric is ROC AUC, then you calculate it for each fold and take the average. After model selection, you can finally plot ROC curve, calculate AUC, on the whole training (or test) data based on your choice of analysis.

Evaluating Classifiers k fold CV or ROC


Demonstrating convergence of an infinite series

Question: I have the series
$$
\sum_{n=2}^\infty \frac{1}{n [\log(n)]^p}\;\;.
$$ I know that it will converge if and only if $p>1$ , but how can this be demonstrated?
My first intuition was to rearrange the denominator of the series to get $ \frac{1}{(\log(n))^{np}}$ - since $\log n$ will be positive, surely if $p$ is also positive, the fraction converges to 0 and then the series is convergent? I don't know how to formalise this argument, or if this is even the correct one.
Comment: Cauchy condensation test, if you aren't yet allowed to use integrals.
Answer: The series
$$
\sum_{n=2}^{\infty} \frac{1}{n(\ln n)^p}
$$
can be tested using integral test, since
$$
\int_2^{N} \frac{1}{x(\ln x)^p}dx=\int_{\ln 2}^{\ln N}\frac{1}{t^p}dt
$$
converges when $p>1$, and diverges when $p\le1$ as $N\to\infty$.

Edit: How to integrate $\displaystyle\int_{\ln 2}^{\ln N}\frac{1}{t^p}dt$
If $p\ne 1$, then $\int \frac{1}{x^n}dx = \frac{1}{n+1}x^{n+1}+C$, and $\int \frac{1}{x} dx = \ln|x|+C$. Thus$$\int_{\ln 2}^{\ln N}\frac{1}{t^p}dt=\begin{cases}
\frac{1}{1-p}((\ln N)^{1-p}-(\ln 2)^{1-p}),&p\ne 1\\
\ln\ln N - \ln \ln 2,&p=1
\end{cases} $$
Comment: How do you know that the latter interval converges and diverges when $p>1$ and $p\leq 1$ respectively?
Comment: @user3677952 Well... because the series converge or diverge respectively, of course! :-)
Comment: @user3677952 I edited my post. Can you proceed from this?
Comment: I can't see how you know the behaviour of the integral depending on p; you've shown that it behaves differently at p=1, but I can't see how you use that to distinguish p>1 and p<1.
Comment: If $p > 1$, then $\frac{1}{(\ln N)^{p-1}}$ goes to zero as $N\to\infty$, and if $p <1$, then $(\ln N)^{1-p}$ goes to $\infty$ as $N\to\infty$.
Answer: One misconception I should dispel from your question is that the series converges if the 'fraction' or individual summand tends to zero, which is not true. Unless I misunderstood
Answer: Let's use Cauchy Condesation Test
: being $a_n=\frac1{n\log^pn}$ positive and not increasing, we have that
$$
\sum_{n=1}^{+\infty}a_n<+\infty\;
\Longleftrightarrow\;\sum_{n=1}^{+\infty}2^na_{2^n}<+\infty\;.
$$
But
$$
2^na_{2^n}=\frac{2^n}{2^n[\log(2^n)]^p}=\frac1{\log^p2}\frac1{n^p}
$$
hence
$$
\sum_{n=2}^{+\infty}2^na_{2^n}=
\frac1{\log^p2}\sum_{n=2}^{+\infty}\frac1{n^p}
<+\infty\;
\Longleftrightarrow\;p>1
$$
as wanted.


How to initialize keycloak with locale in i18n Angular app?

Question: We use keycloak [https://www.keycloak.org/] server for user authentication in our Angular 6 app. We also use this wrapper library https://github.com/mauriciovigolo/keycloak-angular to interact with the underneath JavaScript keycloak Adapter and initialization.
Keycloak is the first thing in the app that gets initialized (from provided configuration) via Angular's APP_INITIALIZER provider.
Since we use Angular with internationalization and ahead of time compilation, we have deployed our apps like this:

   https://my-site/en
   https://my-site/fr

I want to render login page in respective locale when navigated. If navigated to my-site/fr keycloak login page should render in french and so on. But there is no way to provide locale in keyclaok config while app initialization.
PS: Keycloak realm is already configured to allow internationalization and user can change language from login page. I know keycloak adapter's login method takes "locale" param but I can only access that after app has been initialized.
Has anyone encountered this problem?
Thank you
Answer: For those facing a similar problem, the resolution may be found at How to initialize keycloak with locale in i18n Angular app.
Comment: Perfect. I totally forgot to update my question here. Thanks for doing it. @mauriciovigolo
Comment: I should thank you, @h3ll0w0rld, for sharing your resolution to this problem!