Increment date in row by 1 day each time

Question: In SQL I have an output table like the following:

MemNo | PipNomDt                 | PIPStrtDt
1739  |  2007-03-31 00:00:00.000 |  2009-02-01 00:00:00.000
1739  |  NULL                    |  2007-04-01 00:00:00.000
1739  |  NULL                    |  2008-04-01 00:00:00.000
1739  |  NULL                    |  2009-04-01 00:00:00.000
1739  |  NULL                    |  2010-04-01 00:00:00.000
1739  |  NULL                    |  2011-04-01 00:00:00.000
1739  |  NULL                    |  2012-04-01 00:00:00.000
1739  |  NULL                    |  2013-04-01 00:00:00.000

I need to update this table so that when the first row of Date1 is populated, all of the rows below are populated with an increment of 1 day so it would appear as the following.

MemNo | PipNomDt                 | PIPStrtDt
1739  |  2007-03-31 00:00:00.000 |  2009-02-01 00:00:00.000
1739  |  2007-04-01 00:00:00.000 |  2007-04-01 00:00:00.000
1739  |  2007-04-02 00:00:00.000 |  2008-04-01 00:00:00.000
1739  |  2007-04-03 00:00:00.000 |  2009-04-01 00:00:00.000
1739  |  2007-04-04 00:00:00.000 |  2010-04-01 00:00:00.000
1739  |  2007-04-05 00:00:00.000 |  2011-04-01 00:00:00.000
1739  |  2007-04-06 00:00:00.000 |  2012-04-01 00:00:00.000
1739  |  2007-04-07 00:00:00.000 |  2013-04-01 00:00:00.000

I did try the following code but I'm not really sure how to actually go about doing this
            UPDATE  pip
            SET     PIPNomDt = DATEADD(DAY, rn - 1,
                                       ( SELECT TOP 1
                                                n.PIPNomDt
                                         FROM   dbo.wtPIPNomDt_List n ,
                                                dbo.wtPIPStrtDt_List s
                                         WHERE  n.RowID = s.RowID
                                       ))
            FROM    dbo.htPensionInputPeriod pip
                    JOIN ( SELECT   ROW_NUMBER() OVER ( ORDER BY MemNo ) rn ,
                                    MemNo
                           FROM     dbo.htPensionInputPeriod
                         ) t2_numbered ON t2_numbered.MemNo = @MemNo

Comment: What defines the "first" row? Do you have any type of unique key that can be used to order your rows?
Comment: This comes from the UI, but if the top row is populated, we then want to fill the rest.
Comment: How is the UI ordering the rows? Why did it put any particular row on top? Relational theory forbids any type of implicit order on a set of data...it has to be explicitly defined in the query.
Comment: This is irrelevant, the order of the rows has been signed off and is coming out correctly, I just want to know how to update the proceeding rows with the first date with the day incremented by one.
Comment: Seems to me it's ordered by `PIPStrtDt`, so you could use that in the `ROW_NUMBER` function?
Comment: Philip, it IS relevant. Why else would you need `ROW_NUMBER() OVER ( ORDER BY MemNo )`? The issue is that since your `MemNo` column seems to contain duplicate values, SQL Server will _arbitrarily_ order these rows. A relational database is not a spreadsheet.
Comment: @NickyvV ordered by Month then Year?
Answer: Are you looking for this?
WITH cte AS
(SELECT *,
            Row_number()
              OVER(
                partition BY memno
                ORDER BY CASE WHEN pipnomdt IS NULL THEN 1 ELSE 0 END,
              pipstrtdt)
            AS
               RN
     FROM   table1
)
,cte_next AS
(SELECT *
     FROM   cte
     WHERE  rn = 1
     UNION ALL
     SELECT C1.memno,
            dateadd(day,1,c1.pipnomdt),
            c2.pipstrtdt,
            c2.rn
     FROM   cte_next c1
            JOIN cte c2
              ON c1.memno = c2.memno
                 AND c1.rn = c2.rn - 1
)
SELECT *
FROM   cte_next

SQL Fiddle Here
Comment: I like the ordering in the `Row_number()`, however you could've formatted the answer a bit so that it would become more readable.. And i'm missing the new date column (PipNomDt) I believe?
Comment: @NickyvV Point taken, Thanks
 and I dont think column is missing
Comment: Thanks, and I see your `c1.pipnomdt + 1`, but I don't believe that's working for date(time) datatypes. You'll have to use `DATEADD` for that.
Comment: @NickyvV, Changed to dateadd. However question had a datetime datatype and +1 works well with datetime, I believe
Comment: You might wanny try February 28th+1 :)
Comment: It works
declare @datetime datetime='20120228';
select @datetime+1
Comment: Only tested that one? :) Please try `@datetime datetime='20130228'; select @datetime+1` then? >> Hmm.. sorry on that one, then SQLFiddle just doesn't work :D
Comment: I get 2013-03-01 00:00:00.000,what's the issue?
Comment: @NickyvV, SQLFiddle  works fine. You either remove the semicolon or change query terminator to "GO"
Comment: @SatheeshVariath thanks, this is implemented and working fine.
Answer: My following test was able to produce results similar to those you are looking for: I'm not sure if I've correctly understood the relationship between MemNo and RowID, but it should give you a start. I made the assumption that you only wanted to update values with a matching MemNo, in the order of RowID - you can change that if necessary.
CREATE TABLE pip
  (
RowID INT IDENTITY(1,1) NOT NULL,
MemNo INT NOT NULL,
Date1 DATETIME NULL
  )

INSERT INTO pip (MemNo, Date1) VALUES (1, '8/3/2013')
INSERT INTO pip (MemNo) VALUES (1739)
INSERT INTO pip (MemNo) VALUES (1739)
INSERT INTO pip (MemNo) VALUES (1739)
INSERT INTO pip (MemNo) VALUES (1739)
INSERT INTO pip (MemNo) VALUES (1739)
INSERT INTO pip (MemNo) VALUES (1739)
INSERT INTO pip (MemNo) VALUES (1739)
INSERT INTO pip (MemNo) VALUES (1739)
INSERT INTO pip (MemNo) VALUES (1739)

GO

CREATE TRIGGER T_pip ON pip
    FOR UPDATE
AS
  BEGIN
    UPDATE pip2
    SET pip2.date1 = DATEADD(DAY, s.RowNum, inserted.Date1)
    FROM
        inserted
         INNER JOIN
          (
            SELECT
                RowID,
                MemNo,
                ROW_NUMBER() OVER (PARTITION BY MemNo ORDER BY RowID )     RowNum
            FROM pip
          ) s ON
            inserted.RowID < s.RowID AND
            inserted.MemNo = s.MemNo
         INNER JOIN
        pip pip2 ON
            s.RowID = pip2.RowID

  END

GO

SELECT * FROM pip

UPDATE pip
SET Date1 = '3/31/2007'
WHERE pip.RowID = 2

SELECT * FROM pip

-- DROP TABLE pip


Cannot create new RAID with LSI3008 after initial setup

Question: I have a LSI 3008 Raid Controller on my server mainboard, and 6 HDDs installed.
4 of them in RAID10 and 2 in RAID1. Now I'm trying to add 2 more HDDs with 2TB each, and after installing them into the machine I enter the LSI config utility.
Now all online sources tell me to go to RAID properties and then set up a new RAID. Only problem is, there is no such option. I'm 99% sure that that's exactly the way I set up the first two RAIDs, but it just doesn't show the option anymore.
I already went through pretty much every single dialog in the utility, there is no such thing as set up new RAID or anything along those lines.
The drives are recognized though and show up in the SAS topology. They are from the same manufacturer but are different drives. Both 2TB.
They are also not new, there might be data on them, which I don't need.
Any ideas?
edit: The HDDs are SATA, but connected through a SAS controller.
Answer: I've been messaging the SuperMicro support the other day and today they told me that those RAID controllers always support up to two RAIDs, not three. So that's the answer, after two RAIDs you cannot create a new one.


ScrollView jumps to the top of the page when change button backgroundImage

Question: ScrollView jumps to the top of the page when I click a button at the bottom of the page. It also happens when I click on a uitexfield always at the bottom of the page. What can I do to make it stand still?
In viewDidLoad():
<code>self.scrollView.pagingEnabled=NO;
</code>
in iewDidLayoutSubviews:
<code>  -(void)viewDidLayoutSubviews{
       [super viewDidLayoutSubviews];

   self.scrollView.frame=CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
   self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, 1150);

 }
</code>
The problem is while change ImageBackground of the button here:
<code> - (IBAction)pressedData:(id)sender {

   if ( !self.checkDataIsPressed ) {
        self.checkData =true;
        [self.checkDataPerson setBackgroundImage:
        [UIImage imageNamed:@"check_on"]forState:UIControlStateNormal]; //the jumps scrollview is here
   }else{
        self.checkData =false;
       [self.checkDataPerson setBackgroundImage:
       [UIImage imageNamed:@"check_off"]forState:UIControlStateNormal]; //the jumps scrollview is here
    }

}
</code>
Comment: What is the view did layout subview method for,,
Comment: Is a uiscrollview with dynamic height
Answer: on button Click
<code>[scrollView setContentOffset:CGPointMake(320,0) animated:YES];
</code>


rsh for windows 7

Question: I am looking for rsh client for windows 7. It should be GNU.
I also can't run setup on that machine, so this file must be copied.
Reasons: I had a windows XP batch file with rsh commands that executed commands on a remote  machine.
I am not allowed to install the "Windows Services for Unix" package in my system. Therefor I am looking for an exe file that I could copy to my win7 machine and my batch file would be able to run without changes.
Comment: I found this perfect replacement:
http://www.ccs.neu.edu/home/bchafy/rsh_vista.html
Comment: As you found your answer yourself: post it as an answer and accept it.
Answer: I would consider using Putty, it should do what you want. I haven't used rsh in many years, but i suppose it should work as expected.
You can download the exe-file here
Comment: If Hirschkaefer wants something to use from the command-line instead of interactively, maybe Plink is a better choice from the PuTTY suite of programs.
Answer: You can install Cygwin which will let you run GNU programs inside Windows. I used it on Windows 7 and it didn't ask for administrator permission. In cygwin you can install rsh or upgrade to openssh.
Answer: I found this perfect replacement: ccs.neu.edu/home/bchafy/rsh_vista.html

rsh for windows 7


PHP-FPM and continuos "exited on signal 11"

Question: I've a Hp web server with Xeon E5504 2ghz and 8gb ram, with freebsd 8.2-p9
amd64, nginx 1.2.1, PHP 5.3.14, mysql 5.5.25, apc, memcached and other
package installed using freebsd ports. (conf file at the end of that message)
My trouble are simple, I've a lot of "exited on signal 11" in
/var/log/messages and when php-fpm child die I've "502 gateway error" on my
website, that's really boring because I've a lot of that errors in a day,
in that php-fpm conf I've forced it to an heavy configuration with a 150 of
php-fpm's child in static mode, and pm.max_requests = 10000000, but in my
php-fpm log I found for each child:
[19-Jul-2012 18:58:14.666913] NOTICE: pid 84563, fpm_children_make(), line
421: [pool www] child 84717 started
[19-Jul-2012 18:58:14.666984] DEBUG: pid 84563, fpm_event_loop(), line 409:
event module triggered 1 events
[19-Jul-2012 18:58:17.403217] DEBUG: pid 84563, fpm_event_loop(), line 409:
event module triggered 2 events
[19-Jul-2012 18:58:17.407442] DEBUG: pid 84563, fpm_got_signal(), line 72:
received SIGCHLD
[19-Jul-2012 18:58:17.407552] WARNING: pid 84563, fpm_children_bury(), line
252: [pool www] child 84563 exited on signal 11 (SIGSEGV) after 39.849444
seconds from start

and in /var/log/message for the same pid:
Jul 19 18:58:14 web1 kernel: pid 84563 (php-fpm), uid 1001: exited on signal 11

to be sure that isn't a configuration files (php.ini and php-fpm.conf) troubles, I restored it with the original one that I found in the archive, but nothing, than I tried to use spawn-fcgi, but same trouble!
Than I tried to generate a php-fpm.core running "gdb /usr/local/sbin/php-fpm", when the child exit with "exited on signal 11" php-fpm main process exit with "exited on signal 5 (core dumped)" (that only when I run it throw GDB!), here logs and gdb backtrace results:

/var/log/messages (see above)
php-fpm.log
gdb

As you can see in last link, that are last rows:
#659 0x0000000801534de0 in ?? () from /lib/libc.so.7
#660 0x0000000000000001 in ?? ()
#661 0x00007fffffffec08 in ?? ()
#662 0x000000000000000f in ?? ()
Cannot access memory at address 0x800000000000

Any ideas?
Thanks!
/var/log/messages:
Jul 24 17:58:41 web1 kernel: pid 3887 (php-fpm), uid 1001: exited on signal 11
Jul 24 17:58:42 web1 kernel: pid 3998 (php-fpm), uid 1001: exited on signal 11
Jul 24 17:58:42 web1 kernel: pid 3895 (php-fpm), uid 1001: exited on signal 11
Jul 24 17:58:42 web1 kernel: pid 3892 (php-fpm), uid 1001: exited on signal 11
Jul 24 17:58:43 web1 kernel: pid 3889 (php-fpm), uid 1001: exited on signal 11
Jul 24 17:58:43 web1 kernel: pid 3898 (php-fpm), uid 1001: exited on signal 11
Jul 24 17:58:44 web1 kernel: pid 3886 (php-fpm), uid 1001: exited on signal 11
Jul 24 17:58:44 web1 kernel: pid 3999 (php-fpm), uid 1001: exited on signal 11
Jul 24 17:58:45 web1 kernel: pid 3896 (php-fpm), uid 1001: exited on signal 11
Jul 24 17:58:45 web1 kernel: pid 4000 (php-fpm), uid 1001: exited on signal 11
Jul 24 17:58:45 web1 kernel: pid 3893 (php-fpm), uid 1001: exited on signal 11
Jul 24 17:58:55 web1 kernel: pid 3885 (php-fpm), uid 0: exited on signal 5 (core dumped)

php.ini (only difference from original file)
[PHP]
memory_limit = 128M

apc.enabled=1
apc.shm_size=128M
apc.ttl=0
apc.mmap_file_mask=/tmp/apc/apc.XXXXXX

error_reporting = E_ALL & ~E_DEPRECATED & ~E_NOTICE
display_errors = On
display_startup_errors = On
track_errors = On
html_errors = On

upload_max_filesize = 4M

[Date]
date.timezone = Europe/Rome

[browscap]
browscap = /home/serverweb/etc/php/browscap.ini

php-fpm.conf (only difference from original file)
[global]
error_log = /home/serverweb/log/php-fpm/error.log
log_level = debug

emergency_restart_threshold = 10
emergency_restart_interval = 1m
process_control_timeout = 10s

process.max = 0

[www]
user = web
group = web

listen = 127.0.0.1:9999
listen.allowed_clients = 127.0.0.1

pm = static
pm.max_children = 16

pm.max_requests = 10000000

slowlog = /home/serverweb/log/php-fpm/$pool.log.slow

Answer: PHP 5.3.14 has a serious bug that leads to segfault in php-fpm. It was fixed in 5.3.15 and 5.4.5.
Comment: 5.6.14, same here :{
Comment: i use php 5.3.5, and now was confronted with the same problem...
Comment: I use php 5.4.41 and have the same problem.
Comment: ok, thank you, I just updated to .15, but before that I does a lot of work, as disabling APC, Memcached and calendar extension, and now looks like that php-fpm goes really well.
Answer: If it's still happening in the recent version of PHP, try running:
$ dmesg | grep segfault | tail -10
php-fpm[327]: segfault at 834ac30 ip 000000000834ac30 sp 00007ffc112d1b78 error 14 in libnss_nis-2.23.so[7fe02b461000+b000]
php-fpm[329]: segfault at 834ac30 ip 000000000834ac30 sp 00007ffc112d1b78 error 14
php-fpm[331]: segfault at 834ac30 ip 000000000834ac30 sp 00007ffc112d2278 error 14 in libnss_nis-2.23.so[7fe02b461000+b000]

At the end of the lines you can see in which library the crash is happening, e.g.

error 14 in libnss_nis-2.23.so

So you may try to upgrade that library e.g. by following these commands as example:
$ locate libnss_nis-2.23.so
/lib/x86_64-linux-gnu/libnss_nis-2.23.so
$ dpkg -S /lib/x86_64-linux-gnu/libnss_nis-2.23.so

Then depending to which affected library belongs to, try upgrading that. If that won't help, try searching or reporting the relevant bugs.
For newrelic-X.so, see: PHP Agent Segfaults.

Please note that PHP 5.6 and below are no longer supported. See: PHP Supported Versions page. For example PHP 5.6 branch support was until 19 Jan 2017, so it's recommended to upgrade your PHP to the recent stable branch.
Alternatively when you can't upgrade your versions, enabling and investigating core dumps with lis of backtraces could point you to the right direction of the root of the crashes.


Require entered password to have a capital letter and a number?

Question: I have a working registration on my application and the following code is a small part of that. As you can see there are a bunch of requirements to validate the password/username.
Three of them are similar and do not work. Those are the three strings: upperCaseChars, lowerCaseChars and numbers. I tried to make it so that the password has to contain a uppercase letter, a lowercase letter and a number before it calls the 'insertToDatabase'.
I have searched all over the internet and could not find what I was looking for. P.S: I want to add it in a similar fashion as the other requirements in the if statement.  Any way to do this?
 public void invokeRegister(View view) {
        String name = editTextName.getText().toString();
        String pass = editTextPass.getText().toString();
        String pass2 = editTextPass2.getText().toString();
        String upperCaseChars = "(.*[A-Z].*)";
        String lowerCaseChars = "(.*[a-z].*)";
        String numbers = "(.*[0-9].*)";

        if (name.length() >= 4 && name.length() <= 12 && (pass.length() >= 6 && pass.length() <= 18 && (pass2.length() >= 0 && (pass.equals(pass2)) && pass.contains(upperCaseChars) ))) {
            insertToDatabase(name, pass);

Comment: Are you trying to use `String.matches` as `String.contains` doesn't use a regex?
Comment: If you want safer passwords, the longer the better. May be 100 is a reasonable limit.
Comment: Do you really want a maximum password length of 18?
Comment: Still in the testing phase. You reckon 18 is too long?
Comment: I'm pretty sure 99% of people's passwords are no longer than 18. I could up it a bit, but 100 seems a little overkill!
Comment: True, but why place a limit at all other than to protect yourself from really crazy inputs.
Answer: Checking for the presence of an uppercase letter is easier than you'd think. Convert the entire String to lowercase and see if it matches the original string.
Example:
String pass = "password"
if( !pass.equals(pass.toLowerCase()) ) //fails

String pass = "passWord";
//lower casing becomes "password" and as a result, "passWord" doesn't match "password"
if( !pass.equals(pass.toLowerCase()) ) //passes

And perform the opposite to check for a lower case letter:
if( !pass.equals(pass.toUpperCase()) )

Next for your criteria to ensure the password contains a number, try this:
String pass = "pa55w0rd";
if( pass.matches(".*\\d+.*") ) //passes

Click here to see how this regex works.

The conditions combined:
if( !pass.equals(pass.toLowerCase()) &&
    !pass.equals(pass.toUpperCase()) &&
    pass.matches(".*\\d+.*")
  )

Answer: The way you have it set up now won't work because it's looking for the entire string of letters (A through Z) in the password. What you can do is create your own method that will return true if three booleans become true (ex: hasCapital, hasLowercase, hasNumeral). I'd recommend using an array of chars and then comparing each char in the password string to each char in an array of the valid characters for each condition.
Keep in mind, there are likely far better solutions than this one.. But it will work.


Restoring the model in tensorflow, Attempting to use uninitialized value Variable Error message

Question: I have trained my model and saved it with using
    saver = tf.train.Saver()
    saver.save(sess, '/final_model', global_step = i)

Then I rebuild the exact same graph and try to restore the model to reproduce my result, restoring is working but as long as try to access to any value of the network parameters or operations, it gives me an error saying trying to use the uninitialized variable.
After rebuilding the graph, the code I use to restore is:
    sess=tf.Session()
    new_saver = tf.train.import_meta_graph('final_model-699.meta')
    new_saver.restore(sess, tf.train.latest_checkpoint('./'))

However, the following any of them give me an error of attempting to use uninitialized variable
    print(sess.run(weights['hidden1']))
    print(sess.run(loss_f, feed_dict={x: train_x, y_: train_y}))

Any idea?
As a simple example, here is the training and saving the model:
train_x = np.random.rand(200,2)
w= np.array([2,3])
train_y = np.dot(train_x, w)
train_y = np.reshape(train_y, [200,1])
feature_dim = 2
output_dim = 1

x = tf.placeholder(tf.float32, [None, feature_dim])
y_ = tf.placeholder(tf.float32, [None, output_dim])
weights = {
    'hidden1': tf.Variable(tf.random_normal([feature_dim, output_dim], stddev=1 / np.sqrt(feature_dim)))
}

def network1(data):
    output = tf.matmul(x, weights['hidden1'])
    return output
y = network1(x)

loss_f = output_dim * tf.reduce_mean(tf.squared_difference(y, y_))
optimizer_f = tf.train.AdamOptimizer(1e-4).minimize(loss_f)
saver = tf.train.Saver()
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(10000):
    batch_x = train_x
    batch_y = train_y
    sess.run(optimizer_f, feed_dict={x: batch_x, y_: batch_y})
    print(sess.run(loss_f, feed_dict={x: batch_x, y_: batch_y}))
saver.save(sess,'./savedmodel/', global_step = i)

Restoring and reproducing the result
import scipy.io
import numpy as np
import tensorflow as tf
import random
train_x = np.random.rand(200,2)
w= np.array([2,3])
train_y = np.dot(train_x, w)
train_y = np.reshape(train_y, [200,1])
feature_dim = 2
output_dim = 1
x = tf.placeholder(tf.float32, [None, feature_dim])
y_ = tf.placeholder(tf.float32, [None, output_dim])

weights = {
    'hidden1': tf.Variable(tf.random_normal([feature_dim, output_dim], stddev=1 / np.sqrt(feature_dim)))
}

def network1(data):
    output = tf.matmul(x, weights['hidden1'])
    return output

y = network1(x)
loss_f = tf.reduce_mean(tf.squared_difference(y, y_))
optimizer_f = tf.train.AdamOptimizer(1e-4).minimize(loss_f)
sess = tf.Session()
saver = tf.train.import_meta_graph('./savedmodel/-9999.meta')
saver.restore(sess, tf.train.latest_checkpoint('./savedmodel/'))

print(sess.run(loss_f, feed_dict={x: train_x, y_: train_y}))

The error:
FailedPreconditionErrorTraceback (most recent call last)
<ipython-input-5-17910473afab> in <module>()
----> 1 print(sess.run(loss_f, feed_dict={x: train_x, y_: train_y}))

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in run(self, fetches, feed_dict, options, run_metadata)
    776     try:
    777       result = self._run(None, fetches, feed_dict, options_ptr,
--> 778                          run_metadata_ptr)
    779       if run_metadata:
    780         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _run(self, handle, fetches, feed_dict, options, run_metadata)
    980     if final_fetches or final_targets:
    981       results = self._do_run(handle, final_targets, final_fetches,
--> 982                              feed_dict_string, options, run_metadata)
    983     else:
    984       results = []

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1030     if handle is None:
   1031       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1032                            target_list, options, run_metadata)
   1033     else:
   1034       return self._do_call(_prun_fn, self._session, handle, feed_dict,

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _do_call(self, fn, *args)
   1050         except KeyError:
   1051           pass
-> 1052       raise type(e)(node_def, op, message)
   1053
   1054   def _extend_graph(self):

FailedPreconditionError: Attempting to use uninitialized value Variable
     [[Node: Variable/read = Identity[T=DT_FLOAT, _class=["loc:@Variable"], _device="/job:localhost/replica:0/task:0/gpu:0"](Variable)]]
     [[Node: Mean/_15 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_7_Mean", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

Caused by op u'Variable/read', defined at:
  File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/usr/local/lib/python2.7/dist-packages/ipykernel_launcher.py", line 16, in <module>
    app.launch_new_instance()
  File "/usr/local/lib/python2.7/dist-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelapp.py", line 477, in start
    ioloop.IOLoop.instance().start()
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 888, in start
    handler_func(fd_obj, events)
  File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 283, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell
    handler(stream, idents, msg)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 399, in execute_request
    user_expressions, allow_stdin)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/zmqshell.py", line 533, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2718, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2822, in run_ast_nodes
    if self.run_code(code, result):
  File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2882, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-3-7d229041d9bb>", line 6, in <module>
    'hidden1': tf.Variable(tf.random_normal([feature_dim, output_dim], stddev=1 / np.sqrt(feature_dim)))
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/variables.py", line 197, in __init__
    expected_shape=expected_shape)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/variables.py", line 316, in _init_from_args
    self._snapshot = array_ops.identity(self._variable, name="read")
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 1338, in identity
    result = _op_def_lib.apply_op("Identity", input=input, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value Variable
     [[Node: Variable/read = Identity[T=DT_FLOAT, _class=["loc:@Variable"], _device="/job:localhost/replica:0/task:0/gpu:0"](Variable)]]
     [[Node: Mean/_15 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_7_Mean", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

In [ ]:

print(sess.run(weights['hidden1']))
In [ ]:

same error for:
print(sess.run(weights['hidden1']))

Answer: Ran into similar issue just recently with TF v1.5. It appears, that variables an ops should be added to a global collection for them to be restored properly. Below are two snippets for MNIST dataset that train, save and restore a model.
Train and persist
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import os

train_dir = 'train'
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

x = tf.placeholder(tf.float32, [None, 784], name='x')
W = tf.Variable(tf.zeros([784, 10]), name='W')
b = tf.Variable(tf.zeros([10]), name='b')
y = tf.nn.softmax(tf.matmul(x, W) + b, name='y')

saver = tf.train.Saver(tf.trainable_variables())
sess = tf.InteractiveSession()

tf.add_to_collection('x', x)
tf.add_to_collection('yt', yt)
tf.add_to_collection('accuracy', accuracy)

with tf.Session() as sess:
    latest_checkpoint = tf.train.latest_checkpoint(train_dir)
    meta_path = '%s.meta' % latest_checkpoint

    saver = tf.train.import_meta_graph(meta_path)
    saver.restore(sess, latest_checkpoint)

    x = tf.get_collection('x')[0]
    yt = tf.get_collection('yt')[0]
    accuracy = tf.get_collection('accuracy')[0]

    feed_dict={x: mnist.test.images, yt: mnist.test.labels}

    print(sess.run(accuracy, feed_dict))

Restore and evaluate
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import os

train_dir = 'train'
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

with tf.Session() as sess:
    latest_checkpoint = tf.train.latest_checkpoint(train_dir)
    meta_path = '%s.meta' % latest_checkpoint

    saver = tf.train.import_meta_graph(meta_path)
    saver.restore(sess, latest_checkpoint)

    x = tf.get_collection('x')[0]
    yt = tf.get_collection('yt')[0]
    accuracy = tf.get_collection('accuracy')[0]

    feed_dict={x: mnist.test.images, yt: mnist.test.labels}

    print(sess.run(accuracy, feed_dict))

Here is a link to related TF documentation
Answer: Finally what I find is that seems every variable or operations we want to get access later need to be given a name, so is the placeholder, then we do not have the need to redefine the graph. The following is working finally, please give me more hints if there is an even more simple way to do that.
import scipy.io
import numpy as np
import tensorflow as tf
import random

train_x = np.random.rand(200,2)
w= np.array([2,3])
train_y = np.dot(train_x, w)
train_y = np.reshape(train_y, [200,1])
feature_dim = 2
output_dim = 1

x = tf.placeholder(tf.float32, [None, feature_dim], name="input")
y_ = tf.placeholder(tf.float32, [None, output_dim], name="output")
weights = {
    'hidden1': tf.Variable(tf.random_normal([feature_dim, output_dim], stddev=1 / np.sqrt(feature_dim)), name="weights")
}

def network1(data):
    output = tf.matmul(data, weights['hidden1'])
    return output

y = network1(x)

loss_f = tf.reduce_mean(tf.squared_difference(y, y_), name="op_to_restore")

optimizer_f = tf.train.AdamOptimizer(1e-4).minimize(loss_f)
saver = tf.train.Saver()
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(100):
    batch_x = train_x
    batch_y = train_y
    sess.run(optimizer_f, feed_dict={x: batch_x, y_: batch_y})
    print(sess.run(loss_f, feed_dict={x: batch_x, y_: batch_y}))
saver.save(sess,'./savedmodel/', global_step = i)

with tf.Session() as sess:
    saver = tf.train.import_meta_graph('./savedmodel/-99.meta')
    saver.restore(sess,tf.train.latest_checkpoint('./savedmodel/'))
    graph = tf.get_default_graph()
    x = graph.get_tensor_by_name("input:0")
    y_ = graph.get_tensor_by_name("output:0")
    feed_dict={x: train_x, y_: train_y}
    op_to_restore = graph.get_tensor_by_name("op_to_restore:0")
    print(sess.run(op_to_restore, feed_dict))

Comment: The error you experienced was because you created variables (`weights`) before restoring and did not initialize them before running the graph. It was not because you did not explicitly name the placeholders. TensorFlow will always pick a name, even if you don't specify one.
Comment: As a better reference: [link](http://cv-tricks.com/tensorflow-tutorial/save-restore-tensorflow-models-quick-complete-tutorial/)


Menu bar attached to window. Qt 6 / macOS

Question: I have updated the qt version of Mac program to 6.3 and menubar is now located at the top edge of the window, not native top macOS bar. How to move the menu to the top of macOS screen next to the 'apple icon'?
This is my code. It worked on qt 5.15.
ApplicationWindow {
    id: window
    width: 320
    height: 260
    visible: true

    menuBar: MenuBar {
        Menu {
            title: qsTr("&File")
            Action { text: qsTr("&New...") }
            Action { text: qsTr("&Open...") }
            Action { text: qsTr("&Save") }
            Action { text: qsTr("Save &As...") }
            MenuSeparator { }
            Action { text: qsTr("&Quit") }
        }
        Menu {
            title: qsTr("&Edit")
            Action { text: qsTr("Cu&t") }
            Action { text: qsTr("&Copy") }
            Action { text: qsTr("&Paste") }
        }
        Menu {
            title: qsTr("&Help")
            Action { text: qsTr("&About") }
        }
    }
}

Comment: maybe [these notes](https://doc.qt.io/qt-6/macos-issues.html#menu-bar) can help you?
Answer: There is a special window flag for this. Try the following:
ApplicationWindow {
    width: 320
    height: 260
    visible: true
    flags: ~Qt.AA_DontUseNativeMenuBar
    menuBar: MenuBar {...}
}

Comment: In Qt 6.3.1, this makes the title bar vanish, but the menu stays on the window!  :-(
Answer: Use the Qt.labs.platform MenuBar instead of the default. As of Qt 6.3.1, the QML syntax is:
import Qt.labs.platform as Labs
...
ApplicationWindow {
    ...
    Labs.MenuBar  {
        Labs.Menu {
            title: qsTr("&File")
            Labs.MenuItem {
                text: qsTr("&New")
                onTriggered: doNew()
            }
            Labs.MenuItem {
                text: qsTr("&Open")
                onTriggered: fileOpenDialog.open()
            }
            ...
        }
        Labs.Menu {
            title: qsTr("&Edit")
            ...
        }
        ...
    }
    ...
}

The docs say this is only available on macOS, Android, and some flavors of Linux, but it's working properly on Windows, too.


Forward one RDP port on one machine to multiple external users at the same time

Question: We have a windows server 2003 machine with rdp service listening on the standard port 3389.
For security reasons this port is not opened on the router, but we have freesshd service running and a remote admin can login via ssh and this port is forwarded to external port 33001 for the first external user. This works great.
Now we have another admin who wants to work remote (he uses a different windows account, and connects from a different location, where he wants to use a dekstop, but needs to work on the same server.)
So this is basically a ssh port forwarding question.
Will the other user be able to login at the same time forwarding the same port 3389 to his machine?
Please keep in mind that there will be a second tunnel, and this second tunnel will also use the local port 3389 on the windows server.
Comment: Maybe I'm not reading this correctly but it seems to me that it would be simpler to just have the admins create an SSH tunnel from the client end.
Comment: Yes, this is the plan. I will have to update the question and make it clearer, maybe add adrawing.
Answer: Yes, it will work. Local port in ssh port forwarding is a port on ssh client, in your case your administrator's workstation. Since they obviously can't use the same machine at the same time, local ports can be the same.
Comment: Aleksander, I am not sure if I understand your answer right. Windows server RDP was designed to accept 2 simutaneuos connections at the same time (on the same port) and that is exactly what we are trying to do. 2 people can work on 2 different desktops under their respective user accounts.
Comment: Those are different levels, the number of RDP user sessions has nothing to do with TCP ports. Former is OSI layer 7 while the latter is layer 4, see http://en.wikipedia.org/wiki/Osi_layers


Angular 5 / HttpInterceptor / Detect (cancelled) xhr

Question: In my angular app I'm seeing chrome (cancel) api calls that fire off too rapidly. I also have an HttpInterceptor that triggers a loading indicator with every HttpClient request after 500ms if the request has not completed. However, on the requests that get (cancelled) there does not seem to be any new event to subsequently hide my loading indicator.
Is there a way to detect 'cancelled' requests in the HttpInterceptor so I can hide my loading indicator again?
<code>  export class GlobalHttpInterceptor implements HttpInterceptor {
    constructor(
      private sessionService: SessionService,
      private loadingService: LoadingService
    ) { }

    intercept(
      req: HttpRequest<any>,
      next: HttpHandler
    ): Observable<HttpEvent<any>> {

      setTimeout(() => {
        if (showLoading) {
          this.loadingService.show();
        }
      }, 500);
      let showLoading = true;

      if (this.sessionService.headers.length > 0) {
        for (const x of this.sessionService.headers) {
          req = req.clone({
            headers: req.headers.set(x.key, x.value)
          });
        }
      }

      return next.handle(req)
        .do(
          (response) => {
            if (response instanceof HttpResponse) {
              showLoading = false;
              this.loadingService.hide();
            }
          },
          (error) => {
            showLoading = false;
            this.loadingService.hide();
          }
        );
    }
  }
</code>
Comment: Wrapping the handler response in another Observable, as outlined [here](https://stackoverflow.com/a/49536421/4811678), seems to work pretty well
Comment: Have you figured out a way to do this yet?
Answer: Just encountered the same problem. The finalize operator seems to trigger even when the http request is cancelled.
<code>    public intercept(
        request: HttpRequest<any>,
        next: HttpHandler
    ): Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {
        // request starts

        return next.handle(request).pipe(
            finalize(() => {
                // request completes, errors, or is cancelled
            })
        );
    }
</code>
Comment: But how do I differentiate between responses/requests?  Logging them logs all the requests sent, with no difference between completed/failed/canceled requests.
Answer: Expanding on Davy's answer, this is how I'm detecting an aborted request.
As he stated, finalize will always run on the observable source completing, which in this case is either a success response, an error response, or an aborted request.
The key to my approach is tracking what you have received so far.
<code>intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  let lastResponse: HttpEvent<any>;
  let error: HttpErrorResponse;

  return next.handle(request)
    .pipe(
      tap((response: HttpEvent<any>) => {
        lastResponse = response;
        if (response.type === HttpEventType.Response) {
          console.log('success response', response);
        }
      }),
      catchError((err: any) => {
        error = err;
        console.log('error response', err);
        // TODO: error handling if required
        return throwError(err);
      }),
      finalize(() => {
        if (lastResponse.type === HttpEventType.Sent && !error) {
          // last response type was 0, and we haven't received an error
          console.log('aborted request');
        }
      })
    );
}
</code>
Comment: Nice one! Used in a similar scenarion as OP (Http traffic status indicator which must return to idle especially dificult when requests get cancelled, on purpose/by design).
Answer: Not sure why the answer provided by @Davy hasn't been marked with a green tick yet.
It's a working solution that can be used without adhering to the abortable fetch.
Here is a working demo built with Angular 8.
Try it out with the network throttling (say, "Slow 3G") and notice the fancy animated circle that is being shown each and every time when there is at least one HTTP request in the application's requests queue (see more details in the source code).
If you look closely to the network requests you'll see that the previous pending XHR requests will have been canceled upon receiving a new input from a user (note that GitHub API imposes a limit for a number of HTTP GET requests so use wisely, otherwise you'll have 403 HTTP status code back).
The approach proposed by @Davy works fine unless you do something fancy and press Cmd+S (Ctrl+S on PC) while there is a pending request.
In that case, the finalize handler won't be invoked because the whole process was interrupted by a native modal dialog.
Comment: Accepting answers: people dont seem to do that anymore ;)


How hips generate power while punching?

Question: I have been hearing this things a lot. But don't know:

How it works?
How is it possible (science, body mechanics behind it)?
How to practice it, if its the most effective of punching?

I understand leg and head movement, eye co-ordination, concentration. But this I don't get. Any experienced boxer or martial art expert please answer.
Answer: I do not practice boxing or martial arts, but I am a tennis player, and every coach will say the same about hitting the ball as a martial arts coach will about hitting an opponent - the power should come from your core and lower body, rather than your arm/shoulder. The idea is to use large muscle groups (quads, hamstrings, glutes, core) to create movement. These are the strongest muscles in your body, so they will allow you to hit with not only more power, but more stability as well. If all your power comes from your arm and shoulder, it will be easy for someone to deflect the hand or stop it altogether, as they will be fighting rather small and (relatively) weak muscles.
The physical mechanism is simple - using your legs and core, you can force your upper body to rotate. If your body is rotating, then one shoulder is moving towards your opponent. Hold out your hand and use your arm/shoulder muscles to guide it as you rotate, and you will have a more powerful punch than if you kept your shoulders stationary and punched with your arm muscles.
I do not have any training suggestions, other than practicing with this in mind. It helps to keep a slight bend in the knees so that your quads are already engaged. Your legs should be tired at the end of a practice session. As far as conditioning goes, I would suggest rotation exercises with a medicine ball (holding the ball in both hands, rotate it from one hip to the other). To step it up, do it on an upside-down bosu ball.

How hips generate power while punching?


GraphQL returns data but undefined in code

Question: I am making a GraphQL request using below gql query.
export const GET_DETAILS = gql`
  query ($id: String) {
    country(id: $id) {
      currency
      phone
    }
  }
`;

When I check its response in network tab of chrome dev tools I see something below:
dev tools image
But when I log it out in code below, it returns undefined.
render() {
    return (

        <Query query={GET_DETAILS} variables={{ id: `${this.props.match.params.code}` }}>
            {(loading, error, data) => {
              {console.log(data)} // ----> Here it is undefined

              return (

              );
            }}
        </Query>

    );
  }

Any idea what am I doing wrong and how to fix?
Comment: Hey did you resolve? If yes, post the response.
Answer: I had a similar scenario.
I copied a React component from one project to another, along with the gql query.
const { loading, data } = useQuery<NotificationsData>(GET_NOTIFICATIONS);

This was working fine on the older project and not in the new one. I could see the data being returned in the network tab, but it was still undefined in my component. Even when loading changed to false.
This was my gql query
query UserDetails {
  userDetails {
    id
    username
    first_name
    last_name
    avatar_url
    initials @client
  }
}

The issue here was the line
initials @client

so, i forgot to add the resolver for the @client field here, in my index.tsx file.
something like:
const client = new ApolloClient({
  cache: new InMemoryCache(),
  resolvers: {
    UserEntity: {
      initials: (user, _args, { cache }) => {
        let initials = user.first_name[0];
        if (user.last_name && user.last_name.length) {
          initials = initials + user.last_name[0];
        }
        return initials;
      },
    },
  },
});

After adding this, the data started to show up just fine in my component.
Answer: Like all API requests, GraphQL queries are asynchronous, so the data cannot be logged if it has not arrived from the server yet, which it looks like you are trying to do.
If you check to make sure the data exists before logging it it will work.
if (data) {
   console.log(data);
}

Answer: The render props function used by the Query component is passed an object as its first and only parameter. loading, error and data are all properties on that object. In other words, using destructuring syntax, you can access them like this:
{({ loading, error, data }) => {
  console.log(data)
  ...
}

This is equivalent to
{(props) => {
  console.log(props.data)
  ...
}

Of course, because GraphQL requests are asynchronous, data will be undefined until the request completes so your code needs to reflect that fact as well.


Given smallest eigen value, give a bound on largest element of $A^{-1}$

Question: I've been looking at this question for hours now, but I can't grasp it:
Let A be a symmetric matrix with minimum eigenvalue $\lambda_{\text{min}}$ . Give a bound on the largest element of $A^{−1}$.
I was looking at the spectral decomposition where $A=VDV^T$ with D a diagonal matrix, however I don't think this is the rightway since for this case is not always true that $A^{-1}=A^T$
Comment: To avoid ambiguity, try to replace the word "smallest" in your question by "smallest-sized" (if you mean smallest in magnitude) or "minimum" (if you mean the leftmost on the real line), and similarly for the word "largest".
Comment: If I don't have a better idea, and here I don't, I try small cases to see if they are enlightening.  If $A$ is $1 \times 1, A^{-1}=\lambda_{min}^{-1}$.  You know $A$ can be diagonalized with entries $\lambda_{min}$ and $a  \gt \lambda_{min}$.  Rotate and invert that and see how big an entry can get.
Comment: As @user1551 pointed out you have two different questions depending on what you mean by "smallest". Luckily, you got great answers to both interpretations.
Comment: I edited the question a while ago, thank you for pointing that out.
Answer: The $(i,j)$ entry of a matrix $B$ can be written as $e_i^\top B e_j$ where $e_i$ is the $i$th standard basis vector.
By Cauchy-Schwarz, we have $|B_{ij}| = |e_i^\top B e_j| \le \|B e_j\| \le \sigma_{\max}(B)$ where $\sigma_{\max}(B)$ is the largest singular value of $B$. If $B$ is symmetric, this is the largest eigenvalue of $B$ in absolute value.
We apply the above with $B=A^{-1}$.
If $\lambda_{\min}$ is the smallest eigenvalue of $A$ in absolute value, then the maximum singular value of $A^{-1}$ is $|\lambda_{\min}|^{-1}$.
(Note that we must have $|\lambda_{\min}|>0$ in order for $A$ to be invertible.)
Answer: If a matrix $M$ is symmetric then the operator norm of $M$ is given by
$$\|M\| = \max_{\lambda \in \sigma(M)} |\lambda|$$
The $(i,j)$-th entry of a matrix $M$ is given by $\langle Me_j, e_i\rangle$ where $\{e_1, \ldots, e_n\}$ is the canonical basis.
Therefore $$\left|\langle Me_i, e_j\rangle\right| \stackrel{CSB}{\le} \|Me_i\|\|e_j\| \le \|M\|$$
If your matrix $A$ is symmetric, then $A^{-1}$ is also symmetric. Furthermore, its spectrum is given by $$\sigma(A^{-1}) = \frac{1}{\sigma(A)} = \left\{\frac1\lambda : \lambda \in \sigma(A)\right\}$$
If $\lambda_{\text{min}}$ is the smallest (by absolute value) eigenvalue of $A$, then $\displaystyle\frac1{\lambda_{\text{min}}}$ is the largest (by absolute value) eigenvalue of $A^{-1}$.
Hence:
$$\left|\langle A^{-1}e_i, e_j\rangle\right| \le \|A^{-1}\| = \frac{1}{|\lambda_\text{min}|}$$
Answer: There is no limit.  Let $\lambda_{min} \lt 0$ and $A=\begin {pmatrix} \lambda_{min}&0\\0&\epsilon \end {pmatrix}$.  We can make $\epsilon$ as small as we want in absolute value and $A^{-1}=\begin {pmatrix} 1/\lambda_{min}&0\\0&1/\epsilon \end {pmatrix}$


Fourier Transform of $\exp(iwx)$

Question: I have seen that:
$\mathfrak{F} \{e^{i\omega_0x}\} = \sqrt{2 \pi} \delta(\omega_0+\omega)$, using the convention: $\mathfrak{F} \{f(x)\} = \frac{1}{\sqrt{2 \pi}}\int_{-\infty}^{\infty} f(x) e^{i\omega x} dx$
I understand this result by using the property:
$ 2\pi \, \delta(\alpha) = \int_{-\infty}^{\infty}  e^{i\alpha x} dx$
But I used the following procedure and got a different answer:
$\mathfrak{F} \{e^{i\omega_0x}\} = \frac{1}{\sqrt{2 \pi}}  \int_{-\infty}^{\infty} e^{i\omega_0x+i\omega x} dx =\frac{1}{\sqrt{2 \pi}} \int_{-\infty}^{\infty} e^{ix(\omega +\omega_0)}dx$
Using: $u = - ix(\omega + \omega_0)$ and $du = -i (\omega + \omega_0) dx$ I got:
$\mathfrak{F}\{e^{i\omega_0x}\} =\frac{1}{\sqrt{2 \pi}} \int_{-\infty}^{\infty} e^{-u} \frac{1}{- i(\omega + \omega_0)}du =  \frac{1}{\sqrt{2 \pi}}\frac{1}{- i(\omega + \omega_0)} \int_{-\infty}^{\infty} e^{-u} du = \frac{1}{\sqrt{2 \pi}}\frac{1}{- i(\omega + \omega_0)} \sqrt{\pi} $
So my result is:
$\mathfrak{F}\{e^{i\omega_0x}\} = \frac{i}{\sqrt{2} (\omega_0 +\omega)}$
Can anyboday tell me if I am wrong in some step of my procedure or if my result is equivalent to the answer in the first equation.
Comment: I think you're thinking of $\int_{-\infty}^\infty e^{-u^2}du=\sqrt{\pi}$.
Comment: I also used: $\int_{-\infty}^{\infty} e^{-u}du = \sqrt{\pi}$
Comment: That is correct, there is the mistake.
Answer: There are several problems. Here are three:
1) The integral you try to compute is not convergent. You must use distributions, and I suggest you to learn to use them correctly, not via some $\int_{-\infty}^{+\infty}e^{i\alpha x}\,dx=2\pi\delta(\alpha)$ that does note really make sense.
2) You do a change of variables $u=-ix(\omega+\omega_0)$. Complex changes of variables do not work that way. When you have complex functions you should rather think of the integrals as path integrals. So the "change of variables" will typically mean that you also change the contour you integrate along.
3) The integral $\int_{-\infty}^{+\infty}e^{-u}\,du$ is also divergent. The function is very large for (large) negative values of $u$.
Comment: I am curious about the down vote. Please help me to get a better answer.

Fourier Transform of $\exp(iwx)$


What is the significance of the number 802 in IEEE networking specifications?

Question: Why is the number 802 used for IEEE 802 and what is its meaning? Can you explain how these numbers are assigned in general as well as what 802 in particular is?
Answer: From Wikipedia:

The number 802 was simply the next
  free number IEEE could assign,
  though "802" is sometimes associated
  with the date the first meeting was
  held — February 1980

IEEE = Institute of Electrical and Electronics Engineers and is a professional association chartered for the advancement of technology.
802 is specific to networks with variable packet sizes and is not all-encompassing for networking specifications in general.
Answer: Actually, the answer to this question was recently given by Bob Metcalfe, Ethernet Inventor, at the November 2013 802 Plenary session in Texas. The wikipedia article is a misstatement in that 802 was available, not the "next available".

Why the 802 number? Because first meeting was in the 2nd month of
  1980. via @BobMetcalfe

Here is a link to the tweet from the official IEEE Standards Association twitter account mentioning the etymology of 802.
Comment: I checked [the source](http://grouper.ieee.org/groups/802/802%20overview.pdf); Wikipedia is correct, and Bob Metcalfe is quite possibly wrong.
Comment: *Bob Metcalfe is quite possibly wrong.* - that's a phrase you don't see every day.
Comment: @RobM Well, how much of 1980 do you remember accurately? :)


Convolutional Neural Networks trained with vital data eg. EKG?

Question: I am wondering if CNN are a right tool for classification of human vital data. My data base consists of vector measurements and has a dimension of
$$ \mathsf{3000 \times 1 \times  1 \times  numberOfSamples}$$
My concern is that data units are so low dimensional that resourcing to deep learning techniques is pointless. On the other hand our team tried before many other machine learning alorithms but without success. Maybe somebody wants to share their opinion and possibly a suggestion regarding network architecture and hyper parameters.
Comment: @noumenal I wish to classify 15sec overlapping ekg signals taken from a 50 min survey, i separated a cluster of people having similar reaction and want to classify to classes first- ekg signal while the person was being instructed/explained a task, second- during the task, there is approximately twice as much data of class 1 as of class 2. There is a similar paper http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=7318926 but what surprises me they dont use any relu, bnorm or dropout layers in their network.
Comment: This is very broad, and probably not answerable in its present form. Can you narrow this down from "somebody wants to share their opinion"?
Comment: Well, I mean is it possible to train a cnn using only ekg vector measurments and if so what would be a suitable architecture ?
Comment: @jojo That sounds like a research question to me. Why don't you try some alternative models and report back your findings here?
Comment: Well this is what I am currently working on, I asked in case anybody could give me a hint. In any case I can keep you posted :)
Comment: Could you give an example of the type of data that you wish to classify. The dimensionality is less interesting than the factors. How many time-series and how much data (length = sample rate x samples) do you have per subject? What hypothesis do you have for your classification or will you be using an explorative approach?
Comment: Convolutionals might turn out to be the right tool for this job, but their main application to date has been in imaging. This isn't surprising, given that the receptive regions that serve as one of its distinguishing marks were inspired by the structure of optic nerves (specifically cat eyes at first, I think). I'm wondering if an explicitly time-dependent family of algorithms like spiking or echo state networks might be more suitable for this? Time structures, phases, waves etc. are mentioned far more often in the literature on those methods. Just a thought.
Comment: @SQLServerSteve yes, but other methods have failed us so far. The hope is that magic tool - CNN will somehow detect what we couldn't.
Comment: @jojo Have you tried spiking or echo state networks yet to solve this problem? I'm just curious since I'm doing  a lot of reading on these topics right now. So far I haven't run into any case studies of them being used in EKG analysis, but that doesn't mean there aren't any out there. They're both fairly recent technologies so the academic papers are still more focused on theory than applications. I doubt that convolutionals will be useful for this, since  filtering by receptive regions breaks down in information in a granular way that is well-suited to spatial but not temporal analysis.
Answer: One thing that's useful for analysis of time series like this is to explicitly break out the frequency dependent features, rather than trusting that your model will discover them. Do a wavelet transform and you'll quickly get both enough data that deep learning is sensible and you'll expose a number of useful features for the model.
I am not yet aware of papers investigating what sort of masks are most useful for CNNs on wavelet data, but I haven't looked. You might be able to find some prior work.


When does ast.fix_missing_locations change the tree?

Question: I am trying to find an example where a visit by a NodeTransformer inheritor will differ from a visit by a NodeTransformer inheritor and using fix_missing_locations on the tree.
Here's an example from the documentation (which for some reason does not work, i.e. the tree does not change, depending on whether we apply fix_missing_locations or not):
from ast import *

class RewriteName(NodeTransformer):

    def visit_Name(self, node):
        return Subscript(
            value=Name(id='data', ctx=Load()),
            slice=Constant(value=node.id),
            ctx=node.ctx
        )

tree = parse('foo', mode='eval')
new_tree = fix_missing_locations(RewriteName().visit(tree))
new_uncorrected_tree = RewriteName().visit(tree)

new_tree_str = dump(new_tree, include_attributes=True)
new_uncorrected_tree_str = dump(new_uncorrected_tree, include_attributes=True)

print(new_tree_str == new_uncorrected_tree_str)  # True

Comment: [When I try it](https://ideone.com/DL5vbT), the `dump(new_tree, include_attributes=True)` call fails with an AttributeError due to missing line numbers.
Comment: @user2357112supportsMonica Everything works for me locally up to version 3.6 (3.9-3.7), and only on it the same error appears.
Answer: The problem with the above code is as follows:
...

tree = parse('foo', mode='eval')
new_uncorrected_tree = RewriteName().visit(tree)
new_uncorrected_tree2 = RewriteName().visit(tree)
new_tree = fix_missing_locations(new_uncorrected_tree2)

print(
    tree is new_uncorrected_tree,   # True
    tree is new_uncorrected_tree2,  # True
    tree is new_tree)               # True

tree, new_uncorrected_tree1, new_uncorrected_tree2, and new_tree are the same object, therefore, they are equal and all operations with them (such as creating a string representation) will produce the same result.
If we use different objects initially, then the result will be two completely different strings:
...

tree1 = parse('foo', mode='eval')
tree2 = parse('foo', mode='eval')
new_tree = fix_missing_locations(RewriteName().visit(tree1))
new_uncorrected_tree = RewriteName().visit(tree2)

print(tree1 is tree2)  # False

new_tree_str = dump(new_tree, include_attributes=True)
new_uncorrected_tree_str = dump(new_uncorrected_tree, include_attributes=True)

print(dump(new_tree) == dump(new_uncorrected_tree))  # True
print(new_tree_str == new_uncorrected_tree_str)      # False

print(tree1 is tree2) - Since tree1 and tree2 are different objects, new_tree and new_uncorrected_tree are also different objects.
print(dump(new_tree) == dump(new_uncorrected_tree)) - Although the string representation (and most likely the value) of these objects are the same.
print(new_tree_str == new_uncorrected_tree_str) - And it is here that we can see that the RewriteName did not fill in attributes in new_uncorrected_tree, while fix_missing_locations did it, which is why we see the difference.
We can see the difference even more clearly if we print out the trees:
print(dump(new_tree, include_attributes=True, indent=4))
print(dump(new_uncorrected_tree, include_attributes=True, indent=4))

Expression(
    body=Subscript(
        value=Name(
            id='data',
            ctx=Load(),
            lineno=1,
            col_offset=0,
            end_lineno=1,
            end_col_offset=0),
        slice=Constant(
            value='foo',
            lineno=1,
            col_offset=0,
            end_lineno=1,
            end_col_offset=0),
        ctx=Load(),
        lineno=1,
        col_offset=0,
        end_lineno=1,
        end_col_offset=0))
Expression(
    body=Subscript(
        value=Name(id='data', ctx=Load()),
        slice=Constant(value='foo'),
        ctx=Load()))

But we can also get such a result simply by creating an object of the same type from the same values:
class RewriteName(NodeTransformer):
    def visit_Name(self, node):
        return Name(node.id, node.ctx)

This is because when creating the node object, we did not specify all of its attributes, which is exactly what happens in the parse function.


Use CKEditor for textareas in custom form

Question: I'm using the CKEditor module, and I would like to have the CKEditor in my custom textarea. I tried hard but it just doesn't work...
This some of the code I tried:
    $form['body'] = array (
        '#type' => 'textarea',
        '#title' => 'Item Snippet',
        '#default_value' => $body,
        '#cols' => 80,
        '#rows' => 7
    );
    $form['']['format'] = filter_form();

Comment: As side note, `$form['']['format']` should probably be `$form['body']['format']`.
Comment: CCKeditors are easily configurable through admin panel, no need of code modification
Answer: Use the text_format element type and CKEditor will catch your field:
  $form['body'] = array(
    '#type' => 'text_format',
    '#title' => t('Body'),
    '#format'=> 'full_html',
  );

If you have issues with showing CKEditor in popup use additional #pre_render:
  $form['body'] = array(
    '#type' => 'text_format',
    '#title' => t('Body'),
    '#format'=> 'full_html',
    '#pre_render' => array('ckeditor_pre_render_text_format'),
  );

Comment: It worked. How I can attach a field to my form? For example, I have created a user field under account settings. The field name is field_oembed_link I will show the uploaded link with this field in views. This way I will be able to create a list of content containing the uploaded links. Just for extra information, I want to allow users to upload a link, which will be converted to an oembed content automatically.
Answer: u need to use "text_format" instead of "textarea"
text_format

Description: A text-format-enabled version of a textarea.
Comment: This is the correct answer
Comment: @exlord It worked. How I can attach a field to my form? For example, I have created a user field under account settings. The field name is field_oembed_link I will show the uploaded link with this field in views. This way I will be able to create a list of content containing the uploaded links. Just for extra information, I want to allow users to upload a link, which will be converted to an oembed content automatically.
Comment: @Umair Don't use comment to ask a new question. Create a new Question. And u gana need to provide a sample and more clear explanation about what you want ...
Answer: In Drupal 8.6.x my solution was:
$form['Description'] = [
  '#type' => 'text_format',
  '#title' => $this->t('Description'),
  '#format' => 'rich_text',
];

Answer: just in case somebody only wants a basic_html format one and does not want show format selection ('#allowed_formats' => ['basic_html'] is the point),
$form['description'] = [
  '#type' => 'text_format',
  '#title' => $this->t('message'),
  '#format' => "basic_html",
  '#allowed_formats' => ['basic_html'],
  '#required' => TRUE,
];

Answer: You can try this
 $form['body'] = array(
   '#type' => 'textarea',
   '#title' => 'Item Snippet',
   '#default_value' => $body,
   '#cols' => 80,
   '#rows' => 7,
   '#wysiwyg' => TRUE, // just add this and you'll get the CKeditor
 );
 // …

I was facing the same problem; when I added '#wysiwyg' => TRUE, it worked.
Answer: Some of the methods discussed above do get the CKEditor in the textarea, but if it is a configuration form, the values don't get saved properly.
If you are stuck with same problem you can use a second CKEditor from DNS as explained here:
http://naikacademy.blogspot.com/2018/09/how-to-add-text-editor-to-custom-form.html
Answer: There is a setting page for CKEdiors. You can configure there. You need to give the path to that form and select include from dropdown and it will apply Rich Text editors to all text areas in that path.
Comment: I did not find any options at admin/config/content/ckeditor. Could you please explain it in more detail?


area to the right of $r\cos\theta=6$ and $r=10$

Question: I have been trying to solve this question for a while and I seem to get stuck although it does not seem hard Given $r\cos\theta=6$ and $r=10$ we need to find the area inside the circle and on the right of $r\cos\theta=6$.
I am self-learning calculus with analytic geometry so  I don't know if my ways are correct.
first I took $r=10$ and made it $x^2+y^2=100$ the center is $(0,0)$ and radius is $10$ and also $r\cos\theta=6$ to $x=6$, I found where they intersect and got $6^2+y^2=100$ and we get $y=8$ so the intersection point is $(6,8)$.
since we know that we have $x=6$ and the radius of the circle is $10$ we can use Pythagorean theory to find the area of a triangle inside the circle, we get that the area of the triangle is $0.5\times8\times4=16$.
which leaves a small area between the triangle and the circle which I cannot seem to find. I am still not sure how to find the needed $\theta$ for the integral and I am not sure how to use it.
The final answer according to the book should be $100\left(\cos^{-1}\left(\frac3{5}\right)\right)-48$ thanks for any tips and help!
Answer: Let $A_\Delta=\frac{1}{2} \cdot 6 \cdot 8 = 24=$ area of triangle
and $A_\text{circle}=100\pi$ be the area of the circle.
The area of the circle to the left of the line is thus
$$A_\text{L} = 100\left(\pi - \cos^{-1} \frac{3}{5} \right) + 2 A_\Delta$$
The area to the right is
$$A_\text{circle} - A_\text{L}  = 100 \cos^{-1}\frac{3}{5} - 48.$$
Comment: The area of a circle is $\pi r^2$.  The area of a sector is thus $\frac{r^2}{2}(\omega_1-\omega_0)$ where $\omega_{0,1}$ are the angles defining the sector.  The "area to the left" in the upper half plane goes from $\omega_0=\cos^{-1} 3/5$ to $\omega_1=\pi$. We need to also add the area of a triangle.  Double this to include the area in the lower half of the circle to the left of the line.
Comment: can you please explain the $A_L$ side a bit please?


ReferenceError: jQuery is not defined while trying to run jquery code in console on wordpress site?

Question: The ollowing jquery code runs perfectly on all other sites except for wordpress based site.

!function(t,e){function n(e,n,h){e||(e="div");var
  i,o,a=t(n.container),c=a.offset()||{left:0,top:0},s=[c.left+a.width(),c.top+a.height()],f={x:0,y:1,w:0,h:1};for(i
  in
  f)f.hasOwnProperty(i)&&(o=r.exec(n[i]),o&&(n[i]=s[f[i]]*o[1]/100));var
  u=a.find(e),l=[],d=!!n.furthest,p=!!n.checkHoriz,y=!!n.checkVert,v=d?0:1/0,x=parseFloat(n.x)||0,g=parseFloat(n.y)||0,k=parseFloat(x+n.w)||x,w=parseFloat(g+n.h)||g,F=n.tolerance||0,H=!!t.fn.each2,S=Math.min,m=Math.max;!n.includeSelf&&h&&(u=u.not(h)),0>F&&(F=0),u[H?"each2":"each"](function(e,r){var
  h,i,o,a,c=H?r:t(this),s=c.offset(),f=s.left,u=s.top,M=c.outerWidth(),j=c.outerHeight(),z=f+M,O=u+j,P=m(f,x),V=S(z,k),W=m(u,g),X=S(O,w),Y=V>=P,b=X>=W;(p&&y||!p&&!y&&Y&&b||p&&b||y&&Y||p&&n.onlyX||y&&n.onlyY)&&(h=Y?0:P-V,i=b?0:W-X,o=n.onlyX?h:n.onlyY?i:Y||b?m(h,i):Math.sqrt(h*h+i*i),a=d?o>=v-F:v+F>=o,a&&(v=d?m(v,o):S(v,o),l.push({node:this,dist:o})))});var
  M,j,z,O,P=l.length,V=[];if(P)for(d?(M=v-F,j=v):(M=v,j=v+F),z=0;P>z;z++)O=l[z],O.dist>=M&&O.dist<=j&&V.push(O.node);return
  V}var
  r=/^([\d.]+)%$/;t.each(["nearest","furthest","touching"],function(r,h){var
  i={x:0,y:0,w:0,h:0,tolerance:1,container:document,furthest:"furthest"==h,includeSelf:!1,checkHoriz:"touching"!=h,checkVert:"touching"!=h};t[h]=function(r,h,o){if(!r||r.x===e||r.y===e)return
  t([]);var a=t.extend({},i,r,o||{});return
  t(n(h,a))},t.fn[h]=function(e,r){var h;if(e&&t.isPlainObject(e))return
  h=t.extend({},i,e,r||{}),this.pushStack(n(this,h));var
  o=this.offset(),a={x:o.left,y:o.top,w:this.outerWidth(),h:this.outerHeight()};return
  h=t.extend({},i,a,r||{}),this.pushStack(n(e,h,this))}})}(jQuery);

above fails on wordpress sites with ReferenceError: jQuery is not defined
The jQuery gets injected into the  header, but when I try to run any jquery code, it will not run.
I've been reading it and it seems like wordpress has something to do with it.
Comment: @DrCord: That won't do anything if `jQuery is not defined`.
Comment: Are you trying to run this on the front-end or back-end of your WordPress site?
Comment: Try using `jQuery.fn.jquery;` in the console and seeing what jQuery version it outputs.
Comment: duh, I am trying to help them find out if it is defined and something else is wrong.
Comment: Show us your `jquery` code. And where you have placed your custom `jquery` code? before `` or ``
Comment: It all depends on how and where said code is being included.
Comment: I copy pasted it in to my console. usually it works without complaints but on wordpress site, it seems to not work. jquery gets injected inside
Answer:
Make sure you load jquery before load your jquery code. When you say - "The jQuery gets injected into the header" - I hope it does not mean you are using some js to inject jquery on-fly
I caught this once - if you setup your server improperly, the js file header become [Content-Type:application/javascript] , however, it needs to be [Content-Type:text/javascript]; If you are using Nginx, you may need look into the settings for [default_type]


How I can get correctly return value from HoughCircles

Question: I was clone this project from GitHub but it doesn't working now. I don't yet know the cause of HoughCircles opencv (cv2) function return None.
Can anyone help me understand HoughCircles and solve this problem? Thank you.
img = cv2.imread('download.png', 1)
#img=cv2.resize(img,None,fx=2, fy=2, interpolation = cv2.INTER_CUBIC)
img_grayscale=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img_inverse=cv2.bitwise_not(img_grayscale)

#Circle Detection Part
circles = cv2.HoughCircles(img_inverse,cv2.HOUGH_GRADIENT,1,20,param1=50,param2=200,minRadius=0,maxRadius=0)
circles = np.uint16(np.around(circles))

Comment: Check this solution out to understand Hough circles better https://stackoverflow.com/a/67768649/10333818. Your parameters are messed up.
Answer: If the circle is None that means your image didn't return any circle present in it. also, upload img for better understanding.
for this error you can do this
if circle is not None:
    circles = np.uint16(np.around(circles))


What is the use of optimist module in Node.Js

Question: https://github.com/substack/node-optimist

Optimist is a node.js library for option parsing for people who hate
  option parsing. More specifically, this module is for people who like
  all the --bells and -whistlz of program usage but think optstrings are
  a waste of time.

var argv = require('optimist').argv;

if (argv.rif - 5 * argv.xup > 7.138) {
  console.log('Buy more riffiwobbles');
}
else {
  console.log('Sell the xupptumblers');
}

In this code, is rif and xup are two arguments.
Is it like passing command line arguments to your script, rather than doing that in the script itself.
What is the main purpose of this module, any real-time examples
build in some other languages could be helpful.
Comment: Did you actually read the whole README.md? It shows you how the example is called...
Answer: It's a quick-and-dirty way to access command line arguments without defining them in your code before actually using them. The second part of the example (which you omitted in your question) actually answers your first question:
$ ./xup.js --rif=55 --xup=9.52
Buy more riffiwobbles

$ ./xup.js --rif 12 --xup 8.1
Sell the xupptumblers

So those arguments end up in argv.rif and argv.xup.


Error assigning scatter plot to specific bins

Question: I am trying to count the number of scatter points in specific binned areas. The code works when I use a single row of XY data but when I try to iterate the same script over numerous rows a TypeError gets returned:
TypeError: only length-1 arrays can be converted to Python scalars

Example:
import math
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

np.random.seed(42)
X = np.random.randint(-80, 80, size=(100, 10))
Y = np.random.randint(0, 120, size=(100, 10))

fig, ax = plt.subplots()

BIN_23_X = 0
ang1 = -60, 60
ang2 = 60, 60
angle = math.degrees(math.acos(2/9.15))
E_xy = 0,60

Halfway = mpl.lines.Line2D((BIN_23_X,BIN_23_X), (0,125), color = 'white', lw = 1.5, alpha = 0.8, zorder = 1)
arc1 = mpl.patches.Arc(ang1, 70, 110, angle = 0, theta2 = angle, theta1 = 360-angle, color = 'white', lw = 2)
arc2 = mpl.patches.Arc(ang2, 70, 110, angle = 0, theta2 = 180+angle, theta1 = 180-angle, color = 'white', lw = 2)
Oval = mpl.patches.Ellipse(E_xy, 160, 130, lw = 3, edgecolor = 'black', color = 'white', alpha = 0.2)

ax.add_line(Halfway)
ax.add_patch(arc1)
ax.add_patch(arc2)
ax.add_patch(Oval)

ov1 = mpl.patches.Ellipse(ang1, 70, 110, alpha=0)
ov2 = mpl.patches.Ellipse(ang2, 70, 110, alpha=0)
ax.add_patch(ov1)
ax.add_patch(ov2)

for px, py in zip(X, Y):
    #Error occurs in the line below
    in_oval = Oval.contains_point(ax.transData.transform(([px, py])), 0)
    in_left = ov1.contains_point(ax.transData.transform(([px, py])), 0)
    in_right = ov2.contains_point(ax.transData.transform(([px, py])), 0)
    on_left = px < 0
    on_right = px > 0
    if in_oval:
        if in_left:
            n_bin = 1
        elif in_right:
            n_bin = 4
        elif on_left:
            n_bin = 2
        elif on_right:
            n_bin = 3
        else:
            n_bin = -1
    else:
        n_bin = -1

def bin_counts(xA, yA):
    bc = dict()
    E = Oval.contains_points(ax.transData.transform(np.array([xA, yA]).T), 0)
    E_l = ov1.contains_points(ax.transData.transform(np.array([xA, yA]).T), 0)
    E_r = ov2.contains_points(ax.transData.transform(np.array([xA, yA]).T), 0)
    L = np.array(xA) < 0
    R = np.array(xA) > 0
    bc[1] = np.sum(E & E_l)
    bc[2] = np.sum(E & L & ~E_l)
    bc[3] = np.sum(E & R & ~E_r)
    bc[4] = np.sum(E & E_r)
    return bc

for xr, yr in zip(X, Y):
    print(bin_counts(xr, yr))

Error occurs in this line
in_oval = Oval.contains_point(ax.transData.transform(([px, py])), 0)

Traceback:
Studies/Datasets/codes/untitled4.py", line 73, in <module>
    in_oval = Oval.contains_point(ax.transData.transform(([px, py])), 0)

  File "/Users/jeremyalexander/anaconda/lib/python3.6/site-packages/matplotlib/patches.py", line 154, in contains_point
radius)

  File "/Users/jeremyalexander/anaconda/lib/python3.6/site-packages/matplotlib/path.py", line 493, in contains_point
return _path.point_in_path(point[0], point[1], radius, self, transform)

TypeError: only length-1 arrays can be converted to Python scalars

Comment: Please consider simplifying your code so people can more easily understand it and help you.
Comment: @EdgarR.Mondragón, I've taken out some of the plotting code but the rest is essential to the problem.
Comment: Maybe try showing 2 blocks of code: "Code that works: ..." and "Code that doesn't work: ..."
Comment: One of the parameters that you are giving a function has more values that it can accept.  It expects a scalar or something it can convert to a scalar.  Review the requirements of the relevant function call, and review the type and shape of the inputs.
Comment: Doyou know what a traceback is?  Or how to tell us exactly where in your code the error is occuring?
Comment: @hpaulj, this has been added
Comment: Doesn't the stacktrace tell you whether problem occurs in `transform` or `contains_point`?  One guess is that `contains_point` expects one point, as opposed to 'points', and that the `transform` call produces multiple points.  And that the `px` and `py` values reference several points.
Answer: I copy-n-pasted your code, and got this traceback - the FULL traceback, not just the last 2 lines!.
Traceback (most recent call last):
  File "stack52695533.py", line 35, in <module>
    in_oval = Oval.contains_point(ax.transData.transform(([px, py])), 0)
  File "/usr/local/lib/python3.6/dist-packages/matplotlib/patches.py", line 154, in contains_point
    radius)
  File "/usr/local/lib/python3.6/dist-packages/matplotlib/path.py", line 493, in contains_point
    return _path.point_in_path(point[0], point[1], radius, self, transform)
TypeError: only size-1 arrays can be converted to Python scalars

See the line in patches.py about contains_point?  Just going by the name I'm guessing it expects ONE point.  So now we need to test its inputs.
Adding
print(px, py)
print(ax.transData.transform(([px, py])))

right before the problem line, produces:
[ 22  12 -66  26  -9 -60  22  41  -6   7] [111  67   4 119  36  71 105 112  91  30]
[[ 10992.    4488. ]
 [-32656.    9662.4]
 [ -4384.  -22123.2]
 [ 10992.   15206.4]
 [ -2896.    2640. ]
 [ 55136.   24816. ]
 [  2064.   44035.2]
 [ 17936.   26294.4]
 [ 52160.   41448. ]
 [ 45216.   11140.8]]

As I suspected, you are trying to test for multiple points, not just one at a time.
X and Y are (100,10); you iterate on the first dimension, but still pass 10 values to transform.
Fortunately you provided a runnable example, otherwise I'd still be waiting for your response to my last comment.
Comment: Sorry hpaulj. As the code works with a single row of XY data, can it work with numerous rows or does it have to be rewritten?
Comment: A starting point would be to study the `contains_point` code, and see if it can adapted to work with multiple points at once.  I haven't done that, so can't help you.
Comment: No worries. Thanks for your help.


Prove that a function that is equal almost everywere to a measurable function is measurable

Question:
If $f: [a,b] \rightarrow \mathbb{R} $ is Lebesgue measurable and for $g:[a,b] \rightarrow \mathbb{R}$ we have $ f = g $ almost everywhere, then $g$ is Lebesgue measurable.

Here is my proof:
Let $E$ be the set such that $f(x) = g(x)\ $ for $x\in[a,b]\backslash E$.
Since $f$ is measurable, the set $$\{x\in[a,b]: f(x) > \alpha \}$$ is measurable, and $$\{x\in[a,b]: f(x) > \alpha \} \cap E^c$$ is also measurable because it is the intersection of measurable sets. Finally $$\{x\in[a,b]: f(x) > \alpha \} \cap E^c = \{x\in[a,b]\backslash E: f(x) > \alpha \} = \{x\in[a,b]\backslash E: g(x) > \alpha \} $$ as required.
Is that correct? I mean I did not use the fact that $m(E) = 0$.
Comment: You have to use the hypothesis somewhere, because all functions are equal somewhere ($\emptyset$!), but not all functions are measurable.
Comment: You have to use that every subset of a measurable set which has zero measure is measurable (and has zero measure too).
Answer: I think your idea is good. Note that $\{x\in[a,b]: g(x) > \alpha \} = (\{x\in[a,b]: g(x) > \alpha \} \cap E^c) \cup (\{x\in[a,b]: f(x) > \alpha \} \cap E)$. The second set in the union in the RHS is measurable by your argument, and the first set is measurable because is a subset of $E^c$, which has zero measure.


Remove translation from the title field

Question: Is there a way to disable translations from Title field in each content type.
In the /admin/config/regional/content-language, when I remove translations from Title fields it gives Fatal error:  Maximum execution time of 120 seconds exceeded. No matter what time I give in the ini file this always happens. Is there a way to correct this? Or is there a way to remove Title fields translation without going to content-language
Answer: Yes, there is another way to do this in configuration. You can change
  translatable: true

in core.base_field_override.node.[content-type].title.yml.
If you don't find this configuration file, then there are no changes made so far for the title field. You can do this for example by modifying "Title field label" in the content type, which is also stored in this configuration and if it doesn't exist it will be created, so that you'll find the yaml in the exported config.
After you've changed the field label, export the configuration, open for each content type the mentioned yaml file, change translatable to false and reimport the configuration again.
See https://www.drupal.org/docs/8/configuration-management/workflow-using-the-drupal-ui or if you have installed drush use these two commands:
drush config-export
drush config-import

see https://www.drupal.org/docs/8/configuration-management/workflow-using-drush.
Comment: Mhh, I do know what you are talking of, as I'm using configuration export/import on a regular base. I only fear, a beginner might have some trouble understanding your answer.
Comment: OK, but what should we do, if a possible solution needs some medium level skills?
Comment: Telling him where to find configuration export/import or how to create the above mentioned files. ;) - Or just a link for further reading https://www.drupal.org/docs/8/configuration-management/managing-your-sites-configuration
Comment: @MarioSteinitz Don't underestimate Batman. He will find a way.
Comment: @leymannx Yeah. Batman always has a way :p This worked man thanks :)

Remove translation from the title field


Perl, minor modification - data 9999.9 changed to 999-999, now dropping zero value element

Question: I'm new to this site, so hope to make my question clear! I've inherited some Perl programs that I have had to make modifications to over the last few years - and I've had great success doing so... until now.
The program in question reads GL codes from an .ini file, then reads a database table to pull the values associated with those GL codes for the prior day, placing results in a hash, ultimately creating a file to be imported to another system. The GL codes were formatted as 9999.9, but now they are formatted as 999-999. This caused the GL code NOT to be recognized as numeric. I made minor changes to accomodate for that:
Changed IF statement from
foreach my $num ( @glnums )
{
    if ( $num == $amt[4] )
}

to
foreach my $num ( @glnums )
{
   if ( $num = $amt[4] )
}

which corrected my first error. I also changed:
 my @srtkeys = sort keys %ccsales;

to
 my @srtkeys = sort { $a cmp $b } keys %ccsales;

which did result in the GL codes being in the correct order.
The program compiled and is pulling the correct results, and putting them in the right order - happy for that.
What it is suddenly NOT doing is putting a 0 in place for any GL code that has no value. I need a column output for each GL code, so the record layout stays consistent. I do see a statement initializing the hash values with zeros, which I have not modified:
foreach ( @glnums ) # my GL codes array
{
    $ccsales{ $_} = 0.00;
}

I've googled my issue several different ways, and been searching through prior issues on this site, in the hope of finding something that would point me in the right direction, but have not found anything. Help, please? I hope I've given you enough information, but please let me know if I have not. Thank you, in advance!
Comment: `if ($num = $amt[4])` is very unlikely to be correct.
Comment: your change of the `if ( $num == $amt[4] )` is wrong. The check you do now (`if ( $num = $amt[4] )`) is just a check, if `$num` is assigned to `$amt[4]`, which should be always true.
Comment: @Paulchenkiller, Re "which should be always true", No, only when `$amt[4]` isn't zero.
Comment: `sort keys %ccsales` is short for `sort { $a cmp $b } keys %ccsales`, so claims that switching from one of the other changed the program's behaviour are false. (Well, perhaps if you use `my $a` or `my $b`. You shouldn't do that.)
Comment: @ikegami i never did an assignment in an if statement :P - but it makes sense, thanks for pointing that!
Comment: @Paulchenkiller: You have almost certainly used an assignment in a conditional test before, in `while (my $line = <$fh>) { ... }`. It isn't too big a stretch from `while` to `if`
Comment: Was just a phrase... :P ... of course i did.. `if ( open(my $fh ... ` ;)
Answer: Your question doesn't give any context to the fragments of code that you show, and all I can see is that
if ( $num = $amt[4] )

is probably wrong because it is an assignment, not a comparison. It is also likely that this is the cause of your missing zeroes, because a value of zero, undef or an empty string "" in $amt[4] evaluate as false, and the block will not be executed. You probably need a string comparison, like this
if ( $num eq $amt[4] )

Also, your change to the sort
my @srtkeys = sort { $a cmp $b } keys %ccsales

has made no difference as it is the same as a bare sort like this
my @srtkeys = sort keys %ccsales

Beyond that I cannot help. You should show much more of your code if you need additional assistance
Comment: You guys are good! Although you said I didn't send along enough code, you still gave me my answer! Changing the = sign to eq was all I needed to get my zeros to show. Not a Perl programmer, I am surprised those are not the same, but happy to have learned it. I cannot explain why my sort is correct now, but it is. Thank you very much.
Comment: @trg: I'm glad to help. Like most languages, `=` is assignment while `==` is numeric comparison. Perl has an additional `eq` for string comparison.
Comment: My primary languages are RPG and SQL. I've not seen it, but will remember it! Thanks, again.


Is there any way to solve this problem?

Question: Find out a 4 digit perfect square number in which the first two digits are same. Again the last two digits are also same.
Comment: The solution is $88^2=7744$. Note that the square must be divisible by $11$, hence you only have to check the numbers $11^2,22^2,33^2,\cdots ,99^2$
Answer: $$x^2 = \overline{aabb}$$
$$x^2 = 1000 a + 100a + 10b + b = 1100a + 11b = 11(100a + b)$$
$$x^2 = 11 \cdot \overline{a0b}$$
11 divides $x^2$ so it divides $x$ as well. It also means that 11 divides $\overline{a0b}$. Divisibility rule says that 11 also divides $a+b$.
You don't have to check all combinations because a perfect square ends only with   1, 4, 5, 6 and 9. The first option ($b=1$) can be discarded because $a<10$.
It means that you have to test only 4 possible solutions: 7744, 6655, 5566 and 2299. Only 7744 is a valid solution.

Is there any way to solve this problem?


Arc length equal to distance travelled by a particle in a cycloid

Question: How can I prove that the arc length is equal to the distance travelled by a particle in a cycloid.
I know the definition of arc length and that I can get it by multiplying the angle (radians) and the radius.
And with that I can get $x = r(t-\sin(t))$ and $y = r(1-\cos(t))$.
But I want to know, using math, why the distance travelled in the $x$-axis is equal to the length of the arc.
Thanks.
Cycloid
Comment: Yes, it's precisely what I said. The arclength of the arc of the circle equals the distance the circle rolls along the ground. This is a physical notion, not a mathematical one. How do you say that the wheel/circle never slips?
Comment: This is horribly written. I believe you are asking about what it means for an object to roll without slipping. You form a cycloid by following a dot on the edge of a circle as the circle rolls along the $x$-axis without slipping.
Comment: Yes it is horribly written, this is not my first language, I have posted a link "Cycloid" with an image explaining what I am saying, why the radius times theta is equal to the magnitude of vector OQ
Comment: "This is a physical notion, not a mathematical one." Im just learning about it in Vector calculus, if you think this is the wrong site for this question please let me know. What I want to know is how can I prove that "The arclength of the arc of the circle equals the distance the circle rolls along the ground", I know this is a fact, but is there a way that I can demonstrate this?
Answer: I'm not sure where you got that the distance traveled in the $x$-direction is equal to the arc length of a cycloid.
The distance traveled in the $x$-dimension is just the circumference of the generating circle, or $2\pi r$. We can confirm this using the parametrization in the question. We're given $x(t) = r(t-\sin(t))$, so through one rotation, we go from $t = 0$ to $t = 2\pi$, and we have:
$$ x(2\pi) - x(0) = 2r(2\pi-\sin(2\pi))-2r(0-\sin(0)) = 2\pi r .$$
To get to the arc length $S$ of one arch, we can integrate the differential $dS = \sqrt{{\left(\frac{dx}{dt}\right)^2 + \left(\frac{dy}{dt}\right)^2}} $ from $t = 0$ to $t = 2\pi$:
$$ S = \int_0^{2\pi} \sqrt{{\left(\frac{dx}{dt}\right)^2 + \left(\frac{dy}{dt}\right)^2}} \ dt $$
$$ = \int_0^{2\pi} {\sqrt{{\left(r-r\cos(t)\right)^2 + \left(r\sin(t)\right)^2}}} \ dt $$
$$ = \int_0^{2\pi} {\sqrt{r^2-2r^2\cos(t) + r^2\cos^2(t) + r^2\sin^2(t)}} \ dt $$
$$ = \int_0^{2\pi} {\sqrt{2r^2-2r^2\cos(t)}} \ dt $$
$$ = r\int_0^{2\pi} {\sqrt{2-2\cos(t)}} \ dt $$
$$ = 2r\int_0^{2\pi} {\sin\left(\frac{t}{2}\right)} \ dt $$
$$ = 4r \left[-\cos\left(\frac{t}{2}\right) \right]_0^{2\pi} $$
$$ = 8r . $$
Then, $2\pi r \neq 8r$, so the distance traveled in the $x$-dimension is not equal to the arc length.
Comment: I think I'm missing the word "particle", I mean "the distance travelled by a particle". x=r (t−sin(t)) comes from the asumption that the arc length (radius times theta) is equal to the distance travelled by the particle
Comment: "Radius times theta" would be $rt$, not $r(t-\sin(t))$. The equation $x = r(t-\sin(t))$ isn't giving you a distance, it's the parametrization of the $x$-coordinate of the cycloid in terms of the angle $t$. It's just saying that after the circle has gone through a rotation of $t$, the $x$-coordinate on the cycloid is at $r(t-\sin(t))$.
Comment: Maybe I am not making myself clear, this is not my first language, I have posted a link to an image explaining what I mean
Comment: My question is how can I prove that the radius times theta is equal to the magnitude of vector OQ
Comment: Ahhh, I see. I think this is what Ted Shifrin is getting at above with regards to the circle rotating without slipping. Imagine a piece of string wrapped around the circle, and as you roll the circle along the $x$-axis, the string unravels and is left behind. How much of the string has been unwrapped after a rotation through an angle of $t$? The proportion of the circumference of the circle that is represented by the angle $t$, i.e., $\frac{t}{2\pi}$. The total length is then that proportion times the circumference, which is $\frac{t}{2\pi}*2\pi r = rt$. Does that make it a bit clearer?
Comment: Thanks man it actually does make it clearer, although I was thinking maybe there is way to demonstrate the same thing by doing what you did earlier with the formula to get S, or maybe not, I am just starting with this subject, please forgive me.
Comment: No worries! Glad I could help. You can show that the arc length is that proportion of the circumference using calculus, but I don't think there's a way to demonstrate that's the same as the distance traveled through $x$, that's more of a physical assumption as Shifrin said.


Proof that $G_\delta$ sets in $\mathbb{R}$ are either countable,finite, or have cardinality of the continuum.

Question: Let $U$ be a $G_\delta$ set. We assume that it has empty interior and it's not countable. We have that $U=\bigcap_{i\in\mathbb{N}} A_i$ where $A_i$ are open. Wlog we can assume that $A_{i+1}\subseteq A_i$. Every open set in $\mathbb{R}$ is the countable disjoint union of open intervals. Set $A_i=\bigsqcup I^i_{a}$. Consider the tree $T=\{ I^i_a:i,a\in \mathbb{N}\}$ ordered by $\supseteq$. Given any maximal branch $\{I_{a_i}^i\}_{i\in \mathbb{N}}$ it's intersection is either empty or contains a single point. We can prune $T$ without affecting $U$. There is a bijection between the elements of $U$ and the branches of the now pruned $T$ where $x\in T$ is sent to $\{I_{a_i}^i\}_{i\in \mathbb{N}}$ where for each $i\in \mathbb{N}$ $I_{a_i}^i$ is the interval of $A_i$ that contains $x$ (the inverse of this map is the intersection of a given branch). We search for an appropriate subtree.
For each $i\in\mathbb{N}$ there exists an $I^i_a$ such that the number of branches that contain $I^i_a$ is uncountable since at each $i$ there can be at most a countable amount of $I^i_a$. Given a node $I^i_a$ that is contained in uncountably many branches there exist $I^j_x,I^j_y\subseteq I^i_a$ that are disjoint and are contained in uncountably many branches (as a short hand we say $I^j_x,I^j_y$ "split" the branches of $I^i_a$). We define a subtree where at the first step $J^0_0$ is any node that is contained in uncountably many branches and we set $S_0=\{J^0_0\}$. At the $n+1$-th step for all $J^n_x$ in $S^n$ we find any two $J^{n+1}_{x^\frown 0}$ $J^{n+1}_{x^\frown 1}$ that "split" the branches passing by $J^n_x$ (the bottom index will be a sequence in $\{0,1\}$). This subtree will have cardinality of the continuum.
Is this a correct proof? And would there be a more elegant way in constructing the subtree?
Edit: Looking back I realized that the "pruning" I did at the beginning was not as trivial as I thought. Not only do trivial branches have to be removed (i.e. branches with finite height) but there are also branches of $\omega$ height whose intersection is empty and at every level the node (seen as an open set) has uncountable intersection with $U$. To remove such branches we need to assure that all the child nodes closure is contained in it's predecessor. To this for each $I_a^i$ can be restricted such that it's intersection with $U$ is still uncountable. This can easily be done since the real line is separable. This assures that all branches have union that's a point.
Comment: @SamuelM.A.Luque That's only if the continuum hypothesis holds
Comment: The second sentence was presumably intended to say that $U$ has empty interior.
Comment: I know a different proof. $(1).$ Let $Y$ be a subspace of a completely metrizable space $X$. Then $Y$ is completely metrizable iff $Y$ is a $G_{\delta}$ subset of $X.$ $(2).$ If $Y$ is a non-empty completely metrizable space with no isolated points then $Y$ has a subspace that's homeomorphic to the Cantor Set $C$, so $|Y|\ge |C|=2^{\aleph_0}.$ $(3).$  If $S$ is an uncountable subset of $\Bbb R$ then there is  closed subset $T$ (of $\Bbb R$) such that the subspace $T\cap S$ is uncountable  and has no isolated points....Continued in next comment.
Comment: I don't have time to deal with this now, but if no one posts a detailed answer, I'll try to come back to this at some later time and write one, perhaps with some additional historical comments, as I think it would be useful to have a  classically styled proof of it available here (meaning I'm not going to talk about trees and topology and such). I did this as part of some more extensive personal notes I wrote in Fall 1990 on various aspects of the Cantor-Bendixson theorem, but those notes are handwritten, so I'll have to "LaTeX" the portion that deals with this specific result.
Comment: Good point. I'll delete.
Comment: @AndreasBlass yes it does thanks I will fix it
Comment: ... Continued. Now if S is an uncountable $G_{\delta}$ subset of $\Bbb R$ then with $T$ as in $(3)$, the subspace $T\cap S$ is also $G_{\delta}$. Applying $(1)$ and then $(2)$ with $Y=T\cap S,$ we obtain $|S|\ge |T\cap S|\ge 2^{\aleph_0}.$
Comment: FYI, William Henry Young showed this in 1903 by proving the marginally stronger fact that every uncountable $G_{\delta}$ contains a nonempty perfect set. To be more correct historically, Young proved this for any uncountable set that can be written as the intersection of the interiors of countably many intervals, and in 1914 Hausdorff simplified the notion of a $G_{\delta}$ set to be a set that is the intersection of countably many open sets, showing (in his famous 1914 set theory and topology book) that Young's original proof (what I believe you're attempting) requires only minor adjustments.
Answer: $\newcommand{\cl}{\operatorname{cl}}$ The basic idea of getting a subset of $U$ indexed by the branches of the complete binary tree of height $\omega$ can be carried out with a bit less machinery.
Let $\mathscr{B}$ be a countable base for $\Bbb R$, and let $V=\bigcup\{B\in\mathscr{B}:|B\cap U|\le\omega\}$; clearly $V\cap U$ is countable, so $U_0=U\setminus V$ is uncountable. Moreover, $G\cap U_0$ is either empty or uncountable for each open $G$ in $\Bbb R$.
Let $\Sigma$ be the set of finite sequences of $0$'s and $1$'s, and for each $n\in\Bbb N$ let $\Sigma_n=\{\sigma\in\Sigma:|\sigma|=n\}$. If $\sigma\in\Sigma$ and $i\in\{0,1\}$, denote by $\sigma^{\frown}i$ the sequence obtained by appending $i$ to $\sigma$; thus, if $\sigma\in\Sigma_n$, then $\sigma^{\frown}i\in\Sigma_{n+1}$. For $\sigma,\tau\in\Sigma$ write $\sigma\prec\tau$ iff $\sigma$ is a proper initial segment of $\tau$. I'll construct open sets $G_\sigma$ for $\sigma\in\Sigma$ in such a way that:

$G_\sigma\subseteq A_{|\sigma|}$ for each $\sigma\in\Sigma$,
$G_\sigma\cap U_0\ne\varnothing$ for each $\sigma\in\Sigma$,
$\{G_\sigma:\sigma\in\Sigma_n\}$ is pairwise disjoint for each $n\in\Bbb N$,
$\cl G_\tau\subseteq G_\sigma$ whenever $\sigma\prec\tau$, and
$\operatorname{diam}G_\sigma\le 2^{-n}$ whenever $\sigma\in\Sigma_n$.

Suppose that this has been done. Let $\Sigma_\omega$ be the set of infinite sequences of $0$'s and $1$'s, and note that $|\Sigma_\omega|=2^\omega$. For each $\sigma\in\Sigma_\omega$ and $n\in\Bbb N$ let $\sigma^n\in\Sigma_n$ be the initial segment of $\sigma$ of length $n$, and let $$F_\sigma=\bigcap_{n\in\Bbb N}G_{\sigma^n}=\bigcap_{n\in\Bbb N}\cl G_{\sigma^n}\;.$$
Condition (1) ensures that $F_\sigma\subseteq U$, conditions (2), (4), and (5) and the completeness of $\Bbb R$ ensure that $F_\sigma=\{x_\sigma\}$ for some $x_\sigma\in\Bbb R$, and condition (3) ensures that if $\tau\in\Sigma_\omega$ is distinct from $\sigma$, then $F_\tau\cap F_\sigma=\varnothing$ and hence $x_\tau\ne x_\sigma$. Thus, $\{x_\sigma:\sigma\in\Sigma_\omega\}$ is a subset of $U$ of cardinality $2^\omega$.
To construct the sets $G_\sigma$, let $y_{\langle\rangle}\in U_0$ be arbitrary, let $G_{\langle\rangle}=B(y_0,1)\cap A_0$, and note that $G_{\langle\rangle}\cap U_0$ is infinite (and in fact uncountable). (Here ${\langle\rangle}$ is the sequence of length $0$.) Given $G_\sigma$ for some $\sigma\in\Sigma_n$, let $y_{\sigma^{\frown}0}$ and $y_{\sigma^{\frown}1}$ be distinct points of $G_\sigma\cap U_0$. There is a positive $r<\min\left\{2^{-(n+1)},\frac12|y_{\sigma^{\frown}0}-y_{\sigma^{\frown}1}|\right\}$ such that $\cl\big(B(y_{\sigma^{\frown}0},r)\cup B(y_{\sigma^{\frown}1},r)\big)\subseteq G_\sigma$, and we set $G_{\sigma^{\frown}i}=B(y_{\sigma^{\frown}i},r)\cap A_{n+1}$ for $i\in\{0,1\}$.
Clearly $G_{\sigma^{\frown}0}\cap G_{\sigma^{\frown}1}=\varnothing$, and for $i\in\{0,1\}$ we have $G_{\sigma^{\frown}i}\subseteq A_{|\sigma^{\frown}i|}$, $G_{\sigma^{\frown}i}\cap U_0\ne\varnothing$, $\cl G_{\sigma^{\frown}i}\subseteq G_\sigma$, and $\operatorname{diam}G_{\sigma^{\frown}i}\le 2^{-(n+1)}$, so the recursive construction goes through as desired.
Of course any complete metric space can be substituted for $\Bbb R$.