Bailey–Borwein–Plouffe formula

Question:
$\displaystyle \pi = \sum_{k = 0}^{\infty}\left[ \frac{1}{16^k} \left( \frac{4}{8k + 1} - \frac{2}{8k + 4} - \frac{1}{8k + 5} - \frac{1}{8k + 6} \right) \right]$

How does the BBP formula for digits of $\pi$ works exactly? Why does it use "interbase" math (hexadecimal and binary)? They don't seem to be related to $\pi$ in any way, which is just the ratio of the circumference and the diameter of a circle.
Answer: In the stand-alone version of the programming language Lua, a function that calculates Pi using the plain BBP formula to the desired precision is below. If you do not know the programming language Lua, then there's a good chance you can understand it by ignoring the first and last lines ( the first and last lines are there for programming aesthetics ), thinking of the return as, "the end result is," and knowing that the for is the generic for loop ( i.e. very close to sigma symbol: for variable=initial, final, increment do body with variable set to the current iteration end ).
function( percision )
    pi = 0
    for k = 0, percision, 1 do
        pi = pi + ((16^-k) * ( 4/(8 * k + 1) - 2/(8* k+4) - 1/(8 * k+5) - 1/(8 * k+6) ) )
    end
    return pi
end

But, there's a great limiting factor with this function: It can only calculate pi to a messily 10 digits ( because stand-alone lua uses Double-precision floating-point format ). So, the real thing this post is about is a Lua function that uses a slightly modified version of the BBP formula. This Modification to the BBP formula by essentially shifting down up the decimal place (please note that in Lua, the range of both functions presented in this post are the same, but this post does show an example of a way to work around difficulties in using the BBP formula and also please note that the, " 1 * shift " in the equation is there to show the modifications in the equation that were made ).
function(percision)
    pi = 0
    shift = percision ^ 10
    for k = 0, percision, 1 do
        pi = pi + ((16^-k) * ( (4 * shift )/(8 * k + 1) - ( 2 * shift )/(8* k+4) - ( 1 * shift )/(8 * k+5) - (1 * shift )/(8 * k+6) ) )
    end
    return pi
end

This basic principle can be applied to calculating Pi for real by making it so that far less decimal digits have to be computed while yielding better precision. However, if you were going to make this for real and you do understand this about hardware then you could save a HUGE amount of computing effort if you programmed it in a low level programming language like c++, and you changed the precision to an exponent of 2 (which could be 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 65536, 131072, 262144, ... ) so that you could then only have to count the number of bits, and multiply that number by the exponent to get the resulting number of bits.
Interbase math is exactly like regular math, it has all of the same properties, except it has a different radix or base, so it displays differently. Basically a core fundamental principle is that whenever the last digit on the number goes past the base number, it overflows into the next slot. For example, in base 8, octal, when you add 1 to 7, it becomes 8 which you carry onto the next slot to get 10 which is in octal, but if you converted it back to base 10 then it would be 8. The reason the BBP formula is so convenient is because when you calculate it in base 10 with a calculator, you get would-be hex gibberish so you have to convert it back to base 10 again. Whereas internal in computer hardware everything is computed in base 2, so the BBP formula actually saves the extra effort of converting PI to base 10 because the BBP formula would produce it pre-made ready to go in base 10 for us all to read.
On a person note, these are my favorite bases because of their algebraic symmetry. The more algebraically symmetrical a base it, the more easier it is to do more complex things because the simplicity of the base allows for easier conversions, more intuitive conventions, and an easier ability to manipulate data (the reason for this is rather complex because it can't really be spoken from fact, rather it can be spoken from experience).

Base $4$
Because $4 = 2^2$ and the expression $2^2$ is perfectly symmetrical because
it consists of 2 terms, each of which are 2.
Base $65536$
I don't like this as much as the other 2 because its not perfectly symmetrical. However, it does have the advantage (unlike the next) of us being able to comprehend it. It can be represented as $65536=2^{2^{2^2}}$ which means it is still very symmetrical because the number of 2 exponents is $4=2^2$, however it is still not pinpoint perfect.
Base $2^{13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096}\approx$$10^{16144609452111090514334441274226029970131082121399509384912393635887695069756771104231368302164231425136015724934359162600354003567428775844746162570046507.91002177536}$
Even thou this base is currently incomprehensible even if you use all the computers in all the world, and probably never will be comprehensible, it is still nevertheless my favorite base. It can be represented by $4^{4^{4^4}}$
which gives it perfect geometric symmetry because it is 4 exponents of 4 plus the added benefit of $4=2^2$. I mean, I just love this base because you just can't get that kind of flawlessness until you get up into numbers that can't even be expressed by any means other than Knuth mans wonderful arrows.
Answer: Here is a short implementation in Python:
from decimal import Decimal, getcontext

def pi(precision):
    getcontext().prec=precision
    return sum(1/Decimal(16)**k *
        (Decimal(4)/(8*k+1) -
         Decimal(2)/(8*k+4) -
         Decimal(1)/(8*k+5) -
         Decimal(1)/(8*k+6)) for k in xrange(precision))

print pi(1000)

Comment: As nobody has commented on this so far, let me add a warning that this is not how the formula is supposed to be used.  If you run this program, then the last digit(s) will usually be wrong.
Answer: First note that the BPP formula does not compute the digits of $\pi$ in base 10, but rather base 16 (hexadecimal). Roughly, the factor
$$ \left( \frac{4}{8k + 1} - \frac{2}{8k + 4} - \frac{1}{8k + 5} - \frac{1}{8k + 6} \right) $$
corresponds to the $k$th hexadecimal digit after the decimal place, which is clear enough given that it is sitting next to the factor $1/16^k$.
For everything else, including a rigorous derivation of this formula there is the charming article "The Quest for Pi" by Bailey, Borwein, Borwein and Plouffe.
Comment: This factor does *not* correspond to any particular digit on any particular decimal or hexadecimal place, which is clear enough given that it is much smaller than $1$ for large $k$.
Comment: Agree with @janek37. This answer should not be checkmarked.
Comment: I also noted that your name is in binary :) Thanks for the help 'D'

Bailey–Borwein–Plouffe formula


path from theme css

Question: I'm trying to include my own font to my drupal website. I've got a custom.css file in my theme inside 'sites/all/themes/mytheme/css' folder. My fonts are in my  'sites/all/themes/mytheme/fonts' folder. The css is called from the template.php in my theme folder.
This is my css code right now:
@font-face {
    font-family: 'slashbadass_black';
    src: url('../fonts/Myfont.eot');
    src: url('../fonts/Myfont.eot?#iefix') format('embedded-opentype'),
         url('../fonts/Myfont.woff2') format('woff2'),
         url('../fonts/Myfont.woff') format('woff'),
         url('../fonts/Myfont.ttf') format('truetype'),
         url('../fonts/Myfont.svg#slashbadass_black') format('svg');
    font-weight: normal;
    font-style: normal;
}

So is this path OK? For what I've seen the font-family is not available right now.
Answer: Define your css in mytheme.info:
stylesheets[all][] = css/style.css
@font-face {
  font-family: "Oswald";
  src: url(../fonts/oswald.eot?#iefix) format("embedded-opentype"),
     url(../fonts/oswald.woff) format("woff"),
     url(../fonts/oswald.ttf) format("truetype"),
     url(../fonts/oswald.svg) format("svg")
}

instead of template.php
Comment: I'm adapting an external theme so I try to follow the same structure. If i call the css file from theme.info the path will be fine as it is?
Comment: I have it so in all my Drupal projects so it will work
Comment: It worked as you said but the real problem was not having the fonts on the server.

path from theme css


Inverted tiff images and photometric interpretation tag in PIL?

Question: I'm creating black and white TIF images from scratch and drawing text on them using Python's Imaging Library.  Using Python 2.7, PIL 1.1.7 on Windows 7.
To create each image, I use this code
<code>def newBinaryImage(w,h):
  return Image.new("1",(w,h),1)
</code>
When I open them in any Windows image viewer, they look fine.  After I upload them into a database and then view them with a custom made GUI, they look fine in the GUI viewer.  However, when I try to print them from the GUI, they become inverted and print out as white text on a black background.  (This does not happen when printing it before loading.)
After contacting the vendor who created the custom software, they told us they think the problem might be with the photometricinterpretation tag and it could be fixed by using Group4 compression.  Is there a way to do this in PIL, or is there anything that could/should be changed when creating the image?
Here's an Image.DEBUG on one of my images:
<code>>>>Image.open("1010.tif").show()
tag: ImageWidth (256) - type: short (3) - value: (1200,)
tag: ImageLength (257) - type: short (3) - value: (1600,)
tag: Compression (259) - type: short (3) - value: (1,)
tag: PhotometricInterpretation (262) type: short (3) - value: (1,)
tag: StripOffsets (273) - type: long (4) - value: (98,)
tag: RowsPerStrip (278) - type: short (3) - value: (1600,)
tag: StripByteCounts (279) - type: long (4) - value: (240000,)
*** Summary ***
- compression: raw
- photometric_interpretation: 1
- planar_configuration: 1
- fill_order: 1
- size: (1200,1600)
format key: ('II', 1, 1, 1, (1,), ())
- raw mode: 1
- pil mode: 1
</code>
Comment: Printers have traditionally ignored the palette on 1-bit images and simply assumed that 0=white and 1=black. You need to change your image to match, but I don't think PIL lets you change the palette on a mode `'1'` image.
Answer: I ended up fixing this problem by using ImageMagick.  All I did was "convert" each file from type "tif" to type "tif", and it solved the problem!  Seems to be a compression issue with PIL.


What is the diagram for the limit that is the Cartesian product?

Question: Every limit starts with a diagram.  It is sometimes given by a little category $J$ and a functor from $J$ into $C$ that picks out the diagram.  For a Cartesian product, say in Set, what is this diagram?  Is it just two objects and no arrows?
Answer: Yes, two objects with no arrows is exactly the diagram that gives you the product as a limit.


Is it true that there is a continuous, onto map from $(0,1]$ to $\mathbb R$?

Question: Is it true that there is a continuous, onto map from $(0,1]$ to $\mathbb R$?
I am trying but could not approach.
Comment: What did you try?
Comment: @mechanodroid Well, your argument just shows that there must be $x\in(0,1)$ with $f(x)=f(1)$.
Comment: I tried using tangent function. but that $1$ is giving some problem
Comment: I'm probably missing something but assume that $f : (0,1] \to \mathbb{R}$ is continuous and surjective. Then $f|_{(0,1)} : (0,1) \to \mathbb{R}\setminus \{f(1)\}$ is also continuous and surjective. But $(0,1) $ is connected which then implies that $\mathbb{R}\setminus \{f(1)\}$ is connected as an image of a connected set via a continuous function. This is a contradiction.
Comment: @MarsPlastic Right, thanks.
Answer: $f(x) = \frac{1}{x}$ maps $(0,1]$ to $[1,+\infty)$. Can you map the latter onto $\Bbb R$ continuously? Then compose.
Comment: Kudos to @HennoBrandsma for not just giving this student the answer to his homework assignment.
Answer: Try $\frac{\sin(\frac{1}{x})}{x}$.
Answer: One example is
$$ f(x) = \frac{\sin(1/x)}{x} $$


Integration by parts problem related to integral form of Euler constant

Question: I am stumped on an integration by parts problem. One of the integrals related to the Euler constant is:
$$\int_0^1 v^{n} log(1-v)dv = [ \frac{v^{n+1}-1}{n+1}log(1-v)]_0^1 -  \int_0^1 \frac{v^{n+1}-1}{n+1}*\frac{1}{v-1}dv =  -\frac{1}{n+1} \int_0^1 \frac{1-V^{n+1}}{1-V}dv$$ When I integrate this integral by parts I get the following instead :$$[{V^{n}}{n+1}log(1-v)]_0^1 - \frac{1}{n+1}\int_0^1\frac{V^{n}}{V-1}dv $$  I would appreciate anyone telling me where I am going wrong with this. Thanks in advance.
Comment: the problem with your approach is that $$\left[\frac{v^n}{n+1} \log(1-v)\right]_0^1=-\infty$$
Answer: With $f(v)=\frac{1}{n+1} (v^{n+1}-1)$ and $g(v)=\log(1-v)$, we have
$$(fg)'(v) = f'(v) g(v) + f(v) g'(v) = v^n \log(1-v) + \frac{1}{n+1} (v^{n+1}-1) \cdot \frac{1}{v-1}.$$
Integrate both sides and rearrange to get the first line in your post.

Your attempt is slightly wrong, but perhaps you meant
$$\left[\frac{v^{n+1}}{n+1} \log(1-v)\right]_0^1 - \frac{1}{n+1} \int_0^1 \frac{v^{n+1}}{v-1} \mathop{dv}$$
Symbolically this is fine, but you get issues with the logarithm term as $v \to 1$.


Rails application deployment, nginx, unicorn, capistrano socket error

Question: I am deploying a rails application to a digital ocean VPS. I have followed https://coderwall.com/p/yz8cha . All things done well, but now the browser shows only a blank  page.
Nginx log contains:
2014/08/04 03:07:20 [crit] 20550#0: *4 connect() to unix:/var/run/unicorn.testvpsdo.sock failed (2: No such file or directory) while connectin$
2014/08/04 03:08:39 [crit] 20550#0: *11 connect() to unix:/var/run/unicorn.testvpsdo.sock failed (2: No such file or directory) while connecti$
2014/08/04 03:08:40 [crit] 20550#0: *11 connect() to unix:/var/run/unicorn.testvpsdo.sock failed (2: No such file or directory) while connecti$
2014/08/04 03:08:41 [crit] 20550#0: *11 connect() to unix:/var/run/unicorn.testvpsdo.sock failed (2: No such file or directory) while connecti$
2014/08/04 03:08:41 [crit] 20550#0: *11 connect() to unix:/var/run/unicorn.testvpsdo.sock failed (2: No such file or directory) while connecti$
2014/08/04 03:08:42 [crit] 20550#0: *11 connect() to unix:/var/run/unicorn.testvpsdo.sock failed (2: No such file or directory) while connecti$
2014/08/04 03:08:42 [crit] 20550#0: *14 connect() to unix:/var/run/unicorn.testvpsdo.sock failed (2: No such file or directory) while connecti$
2014/08/04 03:08:42 [crit] 20550#0: *19 connect() to unix:/var/run/unicorn.testvpsdo.sock failed (2: No such file or directory) while connecti$
2014/08/04 04:15:01 [error] 22883#0: *19 connect() failed (111: Connection refused) while connecting to upstream, client: 184.108.40.206, serv$
2014/08/04 04:40:46 [error] 29378#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 220.127.116.11, serve$
2014/08/04 04:45:22 [error] 29378#0: *10 connect() failed (111: Connection refused) while connecting to upstream, client: 22.214.171.124, serv$
2014/08/04 04:49:48 [crit] 31073#0: *1 connect() to unix:/var/run/unicorn.testvpsdo.sock failed (2: No such file or directory) while connectin$
2014/08/04 04:58:19 [crit] 31073#0: *4 connect() to unix:/var/run/unicorn.testvpsdo.sock failed (2: No such file or directory) while connectin$
2014/08/04 04:58:38 [crit] 31073#0: *7 connect() to unix:/var/run/unicorn.testvpsdo.sock failed (2: No such file or directory) while connectin$
2014/08/04 04:59:45 [crit] 32683#0: *1 connect() to unix:/var/run/unicorn.testvpsdo.sock failed (2: No such file or directory) while connectin$
2014/08/04 05:00:28 [crit] 32683#0: *4 connect() to unix:/var/run/unicorn.testvpsdo.sock failed (2: No such file or directory) while connectin$
2014/08/04 05:00:29 [crit] 32683#0: *4 connect() to unix:/var/run/unicorn.testvpsdo.sock failed (2: No such file or directory) while connectin$
2014/08/04 05:08:15 [crit] 32683#0: *8 connect() to unix:/var/run/unicorn.testvpsdo.sock failed (2: No such file or directory) while connectin$
2014/08/04 05:09:50 [crit] 32683#0: *11 connect() to unix:/var/run/unicorn.testvpsdo.sock failed (2: No such file or directory) while connecti$
2014/08/04 05:30:02 [crit] 32683#0: *14 connect() to unix:/var/run/unicorn.testvpsdo.sock failed (2: No such file or directory) while connecti$

I have changed the directory and now error shows:
2014/08/04 05:34:18 [emerg] 1985#0: invalid host in upstream "/tmp/unicorn.testvpsdo.sock" in /etc/nginx/sites-enabled/testvpsdo:2
2014/08/04 05:36:35 [emerg] 2459#0: invalid host in upstream "/tmp/unicorn.testvpsdo.sock" in /etc/nginx/sites-enabled/testvpsdo:2

Nginx config:
 upstream unicorn {
     server unix:/tmp/unicorn.testvpsdo.sock fail_timeout=0;
 }

 server {
     listen 80 default_server deferred;
     # server_name example.com;
     root /home/navin/apps/testvpsdo/current/public;

     location ^~ /assets/ {
         gzip_static on;
         expires max;
         add_header Cache-Control public;
     }

     try_files $uri/index.html $uri @unicorn;

     location @unicorn {
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         proxy_set_header Host $http_host;
         proxy_redirect off;
         proxy_pass http://unicorn;
     }

     error_page 500 502 503 504 /500.html;
     client_max_body_size 20M;
     keepalive_timeout 10;
}

I don't know how to fix it even though I searched through many websites.
Comment: Is that all the log says? Just one line? Or can you post the log if there is more info in it.
Comment: Btw, can you check what permission is given to the socket file?
Comment: how to check ?...when I tried to open that .sock file by vim it says admission denied...
Comment: please do `stat -c  '%a' sockfile`. And btw what about the log? Does it say anything else?
Comment: %a means I have to give address of the directory ?
Comment: DUDE!! I did not mean SOCKFILE. please replace with your socket name!
Comment: 777 this is the result I got
Comment: And btw, please post last 20 lines from your nginx log.
Comment: Yes, I added in to question
Comment: Can you confirm if Unicorn is up and running?
Comment: How  to?...actually me too think that there was a problem with unicorn running but unicorn is starts via capistrano I am just a beginner dont know how to check unicorn is running via capistrano
Comment: Hey its okay. Just do `ps aux | grep unicorn` and if you see some processes, then its running. Btw I am very suspicious of the configuration file for nginx. Are you sure that you have `unix:/tmp/unicorn.testvpsdo.sock` in it? the `unix:` part is very important.

Double check that. Did you restart `nginx` after updating the configuration.
Comment: Hi I have manually started unicorn from my project folder now its working and still I have to find how to start the unicorn via capistrano , Thank you
Answer: The nginx can not access your socket file due to permissions. Try that:
sudo mkdir /var/sockets
sudo chmod -R 755 /var/sockets
sudo mv /tmp/unicorn.testvpsdo.sock /var/sockets/unicorn.testvpsdo.sock

Then specify the new socket directory in the nginx.conf and in the unicorn.rb file.
Redeploy and see what happens.


Number Theory Problem: Pseudoprimes

Question: I want to prove the following:

If the number $M_p=2^p-1$ is composite, where $p$ is a prime, then $M_p$ is a pseudoprime.

I know the following facts:

A composite integer $n$ is called pseudoprime whenever $n|2^n-2$.
Because $n$ is a composite number, we can write $n=rs$, with $1<r\le s<n$. Then, $2^r-1|2^n-1$.
Comment: ... *if* Mp is composite, that is.
Comment: What is the question?
Comment: Hi! The question is prove that Mp is a pseudoprime. Thank you for your help!
Answer: Let $q$ be a prime dividing $M_p$. Then $2^p-1$ is divisible by $q$, and hence the order of $2$ mod $q$, which is $p$, must divide $q-1$. That is: $p|(q-1)$.
Therefore, we have: $2^p-1|2^{(q-1)}-1$, i.e. $2^q \equiv 2$ (mod $M_p$).
Let $k$ be the highest power of $q$ that divides $M_p$. Repeatedly apply the above congruence $k$ times, then raise both sides to every prime power that divides $M_p$: the R.H.S. is still 2, the L.H.S. is $2^{M_p}$.
Thus, we get $2^{M_p} \equiv 2$ (mod $M_p$).
Comment: Thank you for your help! May you explain more how do you convert 2^q = 2 (mod Mp) to 2^Mp = 2 (mod Mp)?
Comment: May you tell me why in the R.H.S. is still 2, after you raise the power?

Number Theory Problem: Pseudoprimes


Matrix representations of inner products

Question: Let $M_{n\times n}(R)$ be the set of all $n \times n$ square matrices with real entries, and S the set of all symmetric invertible matrices in $M_{n\times n}(R)$.
For every $P$ in $S$, is there a basis $B$ of an n-dimensional inner product space $V$ with an inner product < , > such that $P$ is the matrix representation of the inner product with respect to the basis $B$?
Comment: No. For example, the $1 \times 1$ matrix $M=-1$ is not the matrix representation of any inner product.
Comment: But it is the representation of the bilinear form $-xy$. As i mention in my answer, some authors talk about inner products in a more general sense.
Answer: Yes. However, we need to be careful in what we mean by "inner product". If $P$ is only symmetric, then it represents a bilinear form, which some authors refer to as inner product (e.g. Steven Roman). To get positivity, i.e. $<x,x>$ positive for non-zero $x$, we need $P$ to be additionally positive-definite.


How to optimize RBF parameters $C,\gamma$ with KSVM method?

Question: I want to find the best choice of $C$ and $\gamma$ parameters for Radial Basis Function kernel.
I am using kernlab instead of e1071 library. So how can i optimize RBF parameters $C$ and $\gamma$ with ksvm function?
Comment: This question is just a more specific version of this one. https://stats.stackexchange.com/questions/193306/optimization-when-cost-function-slow-to-evaluate/193310#193310
Answer: You can use Optunity for that purpose. This is a library of optimization algorithms for automated hyperparameter search.
You can find an example of using Optunity to optimize an SVM in e1707 here, mapping this to kernlab should be straightforward. All you need to do is specify box constraints (a lower and upper bound) on $C$ and $\gamma$ and a budget of function evaluation (i.e., how many ($C$, $\gamma$)-pairs can be tested.
Comment: I use R for svm classification, but i can not install Optiunity package. Thankyou Mr. Claesen
Comment: Excuse me Mr. Claesn, I didn't know that you are main contributor of Optunity package.
At last, the command
`install_github("claesenm/optunity/wrappers/R")` worked for me!
Comment: Glad to hear it's working! If you run into any problems, please let us know via Github issues so we can solve them ASAP.


Rails couldn't find a valid model for ActiveStorage::Blob association, while trying to use activeadmin and active storage

Question: I've:

Set up a rails project

Added Active Admin.

Set up Active Storage, updating the configuration to connect locally and doing:
bin/rails active_storage:install
bin/rails db:migrate

Then when trying to set up a very simple model Document with a file attached:
class Document < ApplicationRecord
    has_one_attached :file
end

And the most simple Active Admin page possible for it:
ActiveAdmin.register Document do
  permit_params :name, :type, :file
end

I'm getting the following error when trying to access the page:

Rails couldn't find a valid model for ActiveStorage::Blob association.
Please provide the :class_name option on the association declaration.
If :class_name is already provided, make sure it's an
ActiveRecord::Base subclass.

I'm unsure what is going wrong. It seems from the docs everything should work after the migration and adding that line to the model.
Ruby version: "3.1.1"
Rails version: "7.0.2"
Comment: For me, restarting the server fixed the issue.
Comment: I had a similar error (after upgrading from rails 6 to 7), and [this](https://stackoverflow.com/a/59828575/5783745) solved for me.
Answer: I run into the same issue, and found out that this answer fixed the issue for me:
https://stackoverflow.com/a/72005456/583560

[...]adding an initializer with the following worked (Rails 126.96.36.199):
Rails.application.reloader.to_prepare do
 ActiveStorage::Blob
end


Userform combobox take first value only - Excel VBA

Question: I have a user form set up which contains a ComboBox. The ComboBox is populated with values from a dynamic named range "List1" .. every thing is Fine .. when I choose the first value from the list it works and I could complete my tasks .. but when I choose another value from the list the value disappears and the combobox value become empty ..
here is the code :
Private Sub ComboBox1_Change()
ComboBox1.RowSource = "'[" & ActiveWorkbook.Name & "]DATA'!List1"
ComboBox1.DropDown
Worksheets("TEMP").Range("A3").Value = ComboBox1.Value
End Sub

Could anyone give me a solution please ..
UPDATE:
I follow the instructions in this tutorial .. but I do it in a userform:
http://trumpexcel.com/2013/10/excel-drop-down-list-with-search-suggestions
Comment: Usually you populate the Combobox from the Initialize event. Then perform some action in the change event. You don't repopulate the same combobox with the same list. Every time you change it.
Comment: Could there be something wrong with the formula for your dynamic name?
Comment: The problem is with the dynamic range formula.
Comment: =DATA!$D$4:INDEX(Table1[H3];MAX(Table1[H2]);1)
Comment: this is the formula .. please help me change it ..
Comment: I don't know what you want it to do, so I am unable to further assist.  I would recommend that you revise your question and describe what you expect that formula to return. Also you may want to look at the "Table1" Name object, as that may be contributing the problem.
Answer: I couldn't get it to display blank in cell A3 - it all worked, except I had to type in the combo box to get the values to appear (i.e. get the change event to fire).  Also try changing ActiveWorkbook to ThisWorkbook (the book with the code in).
Try populating your combo box when you first open the form:
Private Sub UserForm_Initialize()
    ComboBox1.RowSource = "'[" & ActiveWorkbook.Name & "]DATA'!List1"
End Sub

Private Sub ComboBox1_Change()
    Worksheets("TEMP").Range("A3").Value = ComboBox1.Value
End Sub

Comment: unfortunately it doesn't work .. still when I choose another value than the first from list the combobox become empty!
Comment: @Abeer I have tested this solution and it works as-expected.
Answer: Main problem: the combobox will change its values by the selected item
select item 5 -> item 5 is selected (also if values change)
If the source is changed (no item 5 exists or has an empty string) the box will be empty. You are NOT selecting a value! Try it like that:
Private Sub UserForm_Initialize()
  Dim ListCB As Variant, TmpText As String
  If Not IsArray(Sheets("Data").Range(Names("List1"))) Then
    temptext = Worksheets("TEMP").Range("A3").Value
    Worksheets("TEMP").Range("A3").Value = ""
  End If
  ListCB = Sheets("Data").Range(Names("List1"))
  If Len(temptext) Then Worksheets("TEMP").Range("A3").Value = temptext
  ComboBox1.List = ListCB
End Sub

ListCB will not change when an item is selected -> your combobox stays as it is.
EDIT:
Try it this way:
Dim ListCB As Variant

Private Sub UserForm_Initialize()
  Dim TmpText As String
  If Not IsArray(Sheets("Data").Range(Names("List1"))) Then
    temptext = Worksheets("TEMP").Range("A3").Value
    Worksheets("TEMP").Range("A3").Value = ""
  End If
  ListCB = Sheets("Data").Range(Names("List1"))
  If Len(temptext) Then Worksheets("TEMP").Range("A3").Value = temptext
  GetCBList
End Sub

Sub GetCBList()
  Dim b As Variant, i As Long
  Dim a() As Variant: ReDim a(UBound(ListCB))
  For Each b In ListCB
    If Len(b) Then
      If InStr(1, b, ComboBox1.Value, vbTextCompare) > 0 Or ComboBox1.Value = "" Then: a(i) = b: i = i + 1
    End If
  Next
  If i > 0 Then ReDim Preserve a(i - 1)
  ComboBox1.List = a
End Sub

Private Sub ComboBox1_Change()
  GetCBList
  ComboBox1.DropDown
  Worksheets("TEMP").Range("A3").Value = ComboBox1.Value
End Sub

Attention: Dim ListCB As Variant needs to be outside of the subs/functions (should be first line at all in this form). Replace Private Sub UserForm_Initialize() and Private Sub ComboBox1_Change() with this code and check if that is what you want.
Comment: I try to run this solution but a message with error 1004 show "Application-defined or object-defined error"
Comment: tried it again -> download from your link -> copy my code -> replace the `Private Sub UserForm_Initialize()`-part of your userform -> works without any errors...
Comment: I want the combobox list values changed as I typed .. as in this tutorial : http://trumpexcel.com/2013/10/excel-drop-down-list-with-search- suggestions .. could you please help to make it work with userform? .. everything is ready in the file attached ..
Comment: you may simply put after `Worksheets("TEMP").Range("A3").Value = ComboBox1.Value` the line `ComboBox1.Value = Worksheets("TEMP").Range("A3").Value`... the combobox itself will not be empty (but the list will be)... however, make sure youre not ending in an endless loop... i'll look into it...
Comment: @Abeer i edited my answer... pls check if that fits your needs (you may replace `ListCB = Sheets("Data").Range(Names("List1"))` with the full range or or even a bigger range... empty cells will be ignored and there is no need for your `List1` to make it work.
Comment: Thank you very much .. it works now .. I very appreciate your help :)


Move docker data (images and containers) to separate drive with different FS

Question: I am planning to move docker data (images and containers) to separate drive as they require many space.
As I know I can move /var/lib/docker to separate drive and create soft link to it.  But I have read that BTRFS is a best file system option for docker.
But I suspect it is not enough to format external drive to BTRFS and move existing folder to it.  As I see the content of this folder depends on the using file system.
How can I move (recreate) docker folder (images and containers) on the external drive with different file system correctly?
Answer: As you stated simply moving or copying the docker images/containers from the default AUFS to BTRFS formatted drive is not going to work. So as a first step, you can commit all your containers as images and use docker save commands to save the images as .tar files and then once you have prepped docker to use btrfs, you run docker load to load the images into the new storage driver.
The steps would be roughly as follows - this is what i did in my Ubuntu 14.10 box -

Save your images
docker save IMAGEID > /tmp/redis.tar
Prep btrfs

 mkfs.btrfs /dev/sdb
 mkdir /var/lib/docker-btrfs
 mount /dev/sdb /var/lib/docker-btrfs/

Stop docker and set docker to utilize btrfs and run it.

service docker stop
docker -d -s btrfs  --graph="/var/lib/docker-btrfs"  -H unix:///var/run/docker.sock

The above step can also be accomplished by modifying /etc/default/docker.

Load the images.

docker load --input /tmp/redis.tar

You should be able to see the images and run containers from here. For containers, you can also try export and import methods, i have never tried that one though.


Convert UTC to local time in date field

Question: I have a content type with a date field, which I convert to a specific date format in a preprocess function:
$variables['date'] =
\Drupal::service('date.formatter')->format($variables['node']->field_datum->date->getTimestamp(), 'long_date_without_time');

But as Germany is one hour ahead, a date like 2015-03-31 23:01:08 UTC converts to 1. April 2015. How can I convert this to our local time?
EDIT: I already set the correct timezone in the UI. And I just saw that the wrong dates are only shown when I set my system time between 11pm and 1 am...
Comment: Just a side note here, but your should really be using the field formatters / render system instead of in a preprocess.  Timezone may not end up in the cache context here, so you may encounter weirdness b/c caching problems.
Comment: I want to display the date before the page title and this is not possible with the normal field display...
Answer: The date formatter service automatically converts it to whatever time zone you selected when you installed the Drupal site, admin/config/regional/settings.
Also, if you allow users to set their own timezone in user/1/edit, it would use that time.
So either you need to change the timezone in admin/config/regional/settings and/or in user/1/edit
Comment: I already had set on both sites the correct timezones. And I just saw that the wrong dates are only shown when I set my system time between 11pm and 1 am - this is really weird...
Comment: If a TZ isn't supplied to DateFormatter, it will pull it from the PHP `date_default_timezone_get()`.  If you use the field formatters, it honors the Drupal settings via `drupal_get_user_timezone()` or the override setting.
Comment: Also, the config whether or not a user can use their own TZ is on admin/config/regional/settings.  If that is set, then they can pick an option on their own user edit page.
Comment: As I already said, the correct timezone is already set in the UI
Comment: Which city or town do u live in and which timezone did u select?
Comment: So you selected [`Europe/Berlin`](https://www.google.ca/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=berlin+time) as your time zone and you live in Berlin?
Comment: Sorry, I didn't see that you answered. I don't live in Berlin, but in the same country and time zone.
Comment: Sorry forgot to use the @0711master so you get notified. What city/town do you live in then?

Convert UTC to local time in date field


What is the opposite class to TcpListener in C# and how to use it to send message to server

Question: I have programmed TCP Server in my application which can handle incoming connections and decode inoming messages.
But now I wanted create a client on Windows Phone which will send short string message: "I am Client" to the server. In server I used the class TcpListener so I was looking for the "opposite" class like TcpSender but I could not find one.
The servers ip is: 192.168.0.13 and port is 13000.
To sum up the question: How to create short client which will send single message to the server?
My server looks like - I post it only to show that I've done it:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace HomeSecurity {
    class TCPEventServer {
        private TcpListener tcpListener;
        private Thread listenThread;

        public TCPEventServer() {
            this.tcpListener = new TcpListener(IPAddress.Any, 13000);
            this.listenThread = new Thread(new ThreadStart(ListenForClients));
            this.listenThread.Start();
        }
        private void ListenForClients() {
            this.tcpListener.Start();
            while (true) {

                TcpClient client = this.tcpListener.AcceptTcpClient();

                Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                clientThread.Start(client);
            }
        }
        private void HandleClientComm(object client) {
            TcpClient tcpClient = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();
            byte[] message = new byte[4096];
            int bytesRead;

            while (true) {
                bytesRead = 0;
                try {

                    bytesRead = clientStream.Read(message, 0, 4096);
                } catch {

                    break;
                }
                if (bytesRead == 0) {

                    break;
                }

                ASCIIEncoding encoder = new ASCIIEncoding();

                string messageDecoded = encoder.GetString(message, 0, bytesRead);
                messageDecoded = messageDecoded.Replace("\r", string.Empty).Replace("\n", string.Empty);
                string ip = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address + "";

                Console.WriteLine("message: " + messageDecoded + " ip: " + ip);

                VideoStream.PassMessage(messageDecoded, ip);
            }

            tcpClient.Close();
        }
    }
}

Comment: There is no `TcpSender`, you have to use [`TcpClient`](http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx) to send data.
Comment: @Sinatr This class seems to be unavailable in Windows Phone.
Comment: Once you know what you need, rest is assured -> google "tcpclient wp8" -> [first result](http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202858.aspx)
Answer: Look at the TcpClient class here. That has functions for establishing a connection to a listener, with example code.
Comment: ah, wasn't aware of that. Look [here](http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202858(v=vs.105).aspx) instead then. :)
Comment: This class seems to be unavailable in Windows Phone.
Comment: Thanks. I tried to use SocketEx but I get: http://stackoverflow.com/questions/21603010/when-i-want-to-use-nuget-library-socketex-tcpclient-dll-cannot-find-or-open-t


ListView ID called on null? (Kotlin)

Question: I'm new to Kotlin and im trying to build a HomePage where there is a BottomNavigation with 3 Fragment pages but in 1 of the pages I set a ListView and whenever I call the ID it gives the following errer(Caused by: java.lang.IllegalStateException: categoryListView must not be null)
Here is how Im calling it in my HomePage which is where the content appears:
class HomePage : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

    lateinit var adapter : CategoryAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home_page)

        adapter = CategoryAdapter(this, DataService.categories)
        categoryListView.adapter = adapter

        navView.setNavigationItemSelectedListener(this)

        bottomNavigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)

        replaceFragment(HomeFragment())
    }

    private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        when(item.itemId) {
            R.id.Bottom_Nav_Home -> {
                println("Home pressed")
                replaceFragment(HomeFragment())
                return@OnNavigationItemSelectedListener true
            }
            R.id.Bottom_Nav_Notifs -> {
                println("Notification pressed")
                replaceFragment(NotifsFragment())
                return@OnNavigationItemSelectedListener true
            }
            R.id.Bottom_Nav_List -> {
                println("List pressed")
                replaceFragment(ListFragment())
                return@OnNavigationItemSelectedListener true
            }
        }
        false
    }

    private fun replaceFragment(fragment: Fragment) {
        val fragmentTransaction = supportFragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.NavPageFragment, fragment)
        fragmentTransaction.commit()
    }
}

am I doing it correct? or am I supposed to call the categoryListView elsewhere? because I tried in my ListFragment which is where my activity code is and it gave a context error
here is how the Fragment activity looks:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/Bottom_List"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Fragments.ListFragment">

    <ListView
        android:id="@+id/categoryListView"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Answer: You are trying to get the categoryListView resolved inside the activity but it is (as far as I understand) part of the fragment. This simply does not work.
The CategoryAdapter and the ListView should be used inside your HomeFragment class and this will work then.
So move this code into your fragment:
adapter = CategoryAdapter(this, DataService.categories)
categoryListView.adapter = adapter

Update
I would move it into the onViewCreated() method. There you can simply rely on the fact that there is a view available with a context.
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    adapter = CategoryAdapter(view.context, DataService.categories)
    categoryListView.adapter = adapter // categoryListView will be not null here
}

Comment: The issue in putting the code in the fragment is that it requires me to give context and I tried multiple methods and nothing works, is the way im building the page wrong by any means? can you please explain a little deeper about moving the CategoryAdapter and listView into the HomeFragment
Comment: I updated my answer with a simple way to get the context

ListView ID called on null? (Kotlin)


How do I practice harmonizing in singing?

Question: I'm not good at singing harmonies. In my mind to harmonize, you can just sing an alternate melody and that usually sounds good with the main melody. I don't think to myself that I have to sing a 5th (I can't do that anyway)
When I try to sing harmonies, I can't seem to distance myself from hearing the main melody. I have to sing really loudly so that the main melody does not distract me.
What other tips and tricks should I know in order to harmonize?
Answer: Learning to create your own vocal harmony part along with a melody is often something that musicians learn intuitively, through listening to a lot of music, but also by singing in a band or choir.  Having said this, there is nothing wrong with taking a short cut towards gaining this skill, by using a little musical knowledge.  You can create vocal (or any other, for that matter) harmony parts, using some basic knowledge of harmony (certainly not as advanced as harmonising chorales in the style of Bach, but a good deal above the level of simply trying to find what "sounds good" with a trial-and-error approach).
Below is a very simple melody; following it are a series of steps designed to create a reasonably interesting harmony to go with it. Following these steps will help you to connect more closely with the harmony, and separate yourself from the main melody.

Importantly, the underlying chords (the harmony), are also shown; the melody and any harmony parts need to predominately use notes from these chords, unless you are specifically trying to have your melody or harmony parts reacting "against" the harmony (dissonant), which is quite a bit more advanced.
So, the first chord "C" has the notes C, E and G; the second chord "F" has F, A and C; the third chord "G" has G, B and D. The easiest approach to harmonisation is to simply have the harmony part follow the underlying chords, and the easiest way to do this is to just follow the root notes C, F, G:

Okay, this will work, but it is pretty dull, especially as the harmony and melody parts mostly have the same notes.  Instead of using these root notes, we could use other chord tones:

Right, this is starting to sound far more interesting, now let's make the harmony part match the melody part by using: chord tones when the melody has chord tones; non-chord tones when the melody has non-chord tones:

This results in the classic "harmonisation-in-thirds". What if we want the harmony part to sound a little more distinct from the melody? Well, we could use different chord tones to start with, let's try having the harmony part move in contrary motion (opposite direction) to the melody:

Nice! (Even if I do say so myself…) Now we could finish off by putting non-chord tones into the harmony part:

This is just a very simple example of course, and as I say a lot of this becomes intuitive as you sing, play and listen to more music. I am also aware that you may need to read up on some of the terms here (chord tones, non-chord tones etc.) I'll put some links in...
Comment: Depending on future readers' ultimate goals with this, whether pop music or classical voice leading, note the parallel perfect fifths in the final measure of the last example.
Answer: It sounds like you've got some intuitive knowledge of what a harmony should be, which means you're 90% of the way there. Further practice will let you figure out what sounds good and what doesn't.
The best way to practice harmonizing in singing is to work with another singer. First one of you sing harmony, and the other melody, then switch up.  Find somebody else who wants to learn to harmonize, or who is patient enough to sing very simple stuff and to listen to your mistakes while you learn.
Some tips you can try:

Go slow. Trying to come up with a harmony on the fly is difficult. You need to know what the melody is, where it is going, what would sound good against the melody, and where to find that note relative to the note the melody singer is going to sing next. That's a lot to do all at once.  Sing slowly enough that on each note, you have time to find the harmony note you want. At first, this might be holding each note for a full second or more. It'll get faster with practice.
Sing single notes. One singer sings a note and holds it. The other singer aims for a harmony a third above that, or a fourth above, or a fifth. Or whatever arbitrary interval you decide on. Use a keyboard to check yourself. If neither of you knows enough to use a keyboard, get a really cheap one, put stickers with the note names ( or even 1-2-3-4-5-6-7), and stick to the key of C, which is all white notes. Just google to find out which key is C.
Sing slowly. Yes, I mentioned it before, but it bears repeating.
Look for songs with a very small range, no more than a five note range between the lowest and highest notes is best. This way, you will be less likely to run out of range for your harmony.
Look for songs with a simple chord structure. You want something that sits on the same chord for most of a line, if not the whole things. American gospel songs often do this. If you don't know chords, look up guitar tablature. They have chords written out as letters. When the chord changes, the letter above the music changes.
Don't try to harmonize with a song until you know the melody really well. Christmas songs, nursery rhymes, and patriotic tunes can all be good early choices, if you stick with tunes with limited ranges.
Slow is the way to go. Seriously, this one suggestion will help you hear what you are doing, and give you time to figure out what you should be doing. Ignore the rest if you want, but not this.

If you don't have someone else to sing with, a piano makes a distant second choice for learning to harmonize, but then you really will have to learn enough to find notes and intervals on the keyboard.
Comment: Are there any (free) online resources for this sort of practice? Like simple vocal lines designed for practicing harmony singing on YouTube or some such?
Answer: Learn about chord structure and voicing.When harmonising, the other voice(s) SHOULD be clear to you, otherwise you have nothing to pitch off.A lot of people find they need to hear their own voice above the others, so that's not unusual. What is more important overall is that all the voices blend - if you're using mics, your voice might need to be louder to YOU, but think about the other guy - why would HE want to hear YOUR voice above HIS ?
A basic harmony may be just singing the notes of the main melody, but a third above. This works in many songs, and is not so bad to do - when the other singer goes up, you do too, by the same amount. That's not technically true, but it'll do for now.Listen to stuff like the Everly Brothers for this sort of harmony.
It's also very important that the other voice keeps to the tune. Sounds basic, but it's so easy not to. I used to sing with someone else who was great at harmony, and sometimes we'd both be trying to harmonise with each other, and the main melody was lost. Not so good !
Comment: I learned most of what I know about harmonizing by singing along with the Everly Brothers. Excellent example for beginners.
Answer: Are you an instrumentalist as well? If you play an instrument, such as guitar or piano, it may help you greatly to pick out your original melody line on the instrument, and then pick out the harmony melody.
Practice singing the harmony part alone with the instrument and then try to sing it together with a recording of your original melody. It's easy to fall into singing in unison, but working on the harmony melody alone can help your vocal muscle memory to remember it.
Another good way to practice harmony singing is to listen to and sing along to songs with vocal harmonies. Practice singing the main melody as well as the harmony parts.


Counting while Playing

Question: The most important aspect of maintaining your rhythm is counting. And I can usually understand and/or count the rhythm when I take a look at the score. However, the problem begins when I start playing. If I focus too much on counting and rhythm may fingering get awry sometimes or I don't focus enough on other aspects like reading the notes ahead and dynamics. I know that time and practice are the most important things here but is there any effective practice regimen to get over it quickly? or any specific tips to improve on it?
Also, this might sound stupid, but simply the sound of my instrument makes me unable to hear my counting and therefore lose track of it. I can count by feeling and intuition but to less effect. Is there any suggestions for this aside from time and practice?
Comment: You do need to practice this way, but eventually you don't need to "hear" the counting in your head. Eventually you'll stop doing that and you'll just know which beat you're on at all times.
Answer: Lots.

write the count out in pencil on your score, so you're not trying to remember what comes after "three" when you're trying to play and you aren't decoding what pitch goes on which count in realtime.
practice just the rhythm clapping it, chanting it, playing it on the tonic note.
practice counting aloud with a recording of it to get a feel for it.
count only one: as a practice exercise, practice only saying "one" at the downbeats and no other counting to learn the association of where the measures start with the habit of saying "one!"  This may make it easier when you then bring the rest of the count in.
exaggerate the emphasis: as a practice exercise, play with a really exaggerated marcato rhythm until you're getting everything in the right place in time.  You can be cantabile later.
metronome

Finally, let me say, I think a lot of problems junior musicians have with counting and rhythmic accuracy are at least exacerbated, if not caused, by a bad attitude about rhythm, that playing the "right notes" in the right order is more important than playing them in the right moment.
The most important aspect of maintaining your rhythm is NOT counting.  The most important aspect of maintaining your rhythm is knowing the feeling of your rhythm.  Counting is a tool, a means to that end.  It's the scaffold with which you build the building, but it's not the building.  Or perhaps more accurately, it's the measuring tape that keeps you honest as you put the footings of your pillars down.  If you're having trouble getting your footings to match with the measuring tape, maybe that's because you're placing them based on mistaken estimates of where they go.
The point of counting is to give you the feel for how the piece goes, how its impulses fall, accurately. If the counting is fighting you, maybe the issue is you need to get the feel of the rhythm into your body, understanding it not as a semantic thing ("two half notes followed by 4 eighths and a half note") but a sensation ("DUM! DUM! DADADADA-DUM!")
Rhythm is not an arbitrary series of durations: it is the other main dimension of beauty in music.  If melody is the part of music that sings, rhythm is the part of music that dances.  Those series of durations were chosen for a reason, and have meaning and expressiveness.  The point of counting is to attempt to reveal that to you, so that you can reveal them to the audience.  Get into them, and I think you will begin to find them compelling, to find they take on a life of their own.
Comment: Nicely suggested.
Comment: Well written. I especially find _"You can be cantabile later."_ to be very important, even more when playing pieces for the first time, wheter alone or with an orchestra. Playing it perfectly in time is required first to make it cantabile properly later.
Answer: As with many questions on this site, the meat of the answer is, practice. What seems difficult now, will seem much easier after practice.
However, there are some things you can do:
You may need to explicitly count while learning a piece, but once you know the piece's rhythms, you shouldn't need to. So forget about dynamics until you know how the piece goes. This also goes for reading ahead - if you know the piece, you don't need to read ahead. The sheet music is only there to jog your memory. First learn to play the piece. Then learn to play it with expression.
If you are finding counting so difficult that the sound of your instrument distracts you, perhaps you are attempting pieces with rhythms that are too difficult for your level. Go back to some simpler pieces until you develop your counting skills. Over time, counting will become something you hardly think about.
Make a point of counting when you are listening to music. If you find it difficult to count while listening, then you're going to have even more trouble counting and playing at the same time. So count while listening until you can do that with no effort. When you can do it easily with pieces in 4/4 or 3/4 with drums or strong rhythm, move on to pieces with more unusual time signatures, or pieces in which the rhythm isn't signposted by drums or strong rhythmic parts.
Answer: The existing answers have a lot of good advice, especially as regards transitioning from counting the beat to feeling the beat. As an intermediate step, you might tapping your foot in time instead of counting. As you become more comfortable, you can progress from tapping the entire foot to just tapping a toe -- which no one will even know you're doing if you're wearing shoes. If you watch musicians playing, many of them will move their body in time with the music, whether a gentle head nod, or a slight swaying of the body, or the full-blown head banging of a rock guitarist (sorry... I'm stereotyping). These motions are cues to themselves and their fellow performers of where they feel the beat, and they serve to keep everyone synchronized.
As for practicing, it can be very helpful to pick one small part (perhaps a measure or so) where you are having trouble, and work through how the rhythm should go, and then just repeat that section over and over to internalize the rhythm. If you need to slow it down to get through it, that's fine; at this point you're looking for accuracy. I'll occasionally break things down to the level of individual 16th notes if I have to. Details like dynamics and articulation are extraneous at this point, and only serve as a distraction. Even playing the instrument itself can be a distraction! Just clapping, or singing/speaking some nonsense syllables ("da da da da da") can be helpful. The point is to learn the feel of the passage so that you can perform it instinctively, without needing to count.
Answer: If you're having difficulty counting while playing, the most likely cause is that you're trying to time your counts to your actions, whereas you need to time your actions to your counts.
Counting has specific applied uses: 1) to enable you to anticipate the duration of sounds of varying length (or their printed notes) and 2) to keep track of where you are in the course of a bar or phrase. But the basically required aspect of counting concerns setting the regular pace at which you intend to play - effectively, in the manner of a conductor. The conductor sets the pace (beat-rate), the players time their playing-actions to that pace.
To set a regular pace, the conductor has to mentally anticipate a predetermined number of beats in advance of the current beat - in particular, when the last of those beats will occur. You cannot set a pace just thinking one beat before thinking of the next. So, if you're intending to count 4, you need to anticipate when the fourth beat occurs and then pace the intervening counts regularly towards it. Then, with that forward-moving pace consciously in your mind, you time your playing actions to coincide with particular beats (or where indicated, between particular beats). This procedure is one you can practise straightforwardly until your actions and counts seem thoroughly "as one".

Counting while Playing


How to have different input types for the same function?

Question: The basic idea of what I want to do is:
def aFunction(string='', dicti={}):
    if len(str) > 0:
         print('you gave string as input')
    if len(dicti) > 0:
         print('you gave a dict as input')

aFunction(string='test')
dict['test'] = test
aFunction(dicti=dict)

I know this kind of idea is possible in more OO type of languages, but is this also possible in Python?
Right now I'm doing
def aFunction(input):
    if type(input) == str:
         print('you gave string as input')
    if type(input) == dict:
         print('you gave a dict as input')

aFunction('test')

But I want the difference to be clear when the function is called.
Answer: The idea of having the same method support different argument types is known as multiple dispatch or multimethods.
To get a good introduction to it, you can read this Guido Van Rossum article and have a look at PyPi since there are a few multimethod packages available.
Comment: Thanks, I didn't know the name (was looking at polymorphism) that should help
Comment: Nitpick: _multiple dispatch_ is when there are multiple arguments. This is [_single dispatch_](https://docs.python.org/3/glossary.html#term-single-dispatch).
Answer: Type checks should be avoided in Python (search about "duck typing" on that). When they are necessary, it should usually be done with isinstance rather than an equality check on the type like the question shows. This has the advantage of being more flexible for inheritance situations.
Since Python 3.4, the string-like branch and the dict-like branch can be written in separate functions using stdlib functools.singledispatch.
So instead of:
def aFunction(input_):
    if isinstance(input_, str):
        print('you gave a string-like input')
        ...
    elif isinstance(input_, dict):
        print('you gave a dict-like input')
        ...

You can now have:
from functools import singledispatch

@singledispatch
def aFunction(input_):
    pass

@aFunction.register(str)
def _(input_):
    print("you gave a string-like input")

@aFunction.register(dict)
def _(input_):
    print("you gave a dict-like input")

In Python 3.5+ you have another option of using type hinting function annotations. Read PEP 484 - Type Hints for more details about that feature. It means the single dispatch generic function above can be written as:
from functools import singledispatch

@singledispatch
def aFunction(input_):
    pass

@aFunction.register
def _(input_: str):
    print("you gave a string-like input")

@aFunction.register
def _(input_: dict):
    print("you gave a dict-like input")

Comment: +1 Good point about language philosophy. Plus I believe you should change the name of the `input` argument (now it overwrites a built-in function).
Answer: What you have basically works, there's just some trouble with the variable declarations.  Here is a working vesrion:
def aFunction(str = '', dicti = {}):
    if len(str) > 0:
         print 'you gave string as input'
    if len(dicti) > 0:
         print 'you gave a dict as input'

str = 'test'
dicti = dict([('test', 'test')])
aFunction(str = str)
aFunction(dicti = dicti)
aFunction(str = str, dicti = dicti)
aFunction(dicti = dicti, str = str)

puts:
you gave string as input
you gave a dict as input
you gave string as input
you gave a dict as input
you gave string as input
you gave a dict as input

You can also have non-specific arguments that are sent to the function as both a list and a dictionary (see What is a clean, pythonic way to have multiple constructors in Python? for example).
Comment: Your answer is wrong. You can still call `aFunction` with: `aFunction([1,2,3])` and it will be assuming that you gave it a string (which clearly isn't the case) as well as `aFunction(dicti="this is not a dict")` and it would assume you inputed a dict. @wim got the correct answer, using duck typing. Assigning a default argument to a given type, won't give you guarantees, since Python is a weakly typed language and it may change at runtime.
Comment: Python is *strongly* typed; you generally cannot substitute a value of one type when a different type is expected. (If Python were weakly typed, then something like `1 + "1"` would equal either `2` or `"11"`, depending on how `+` was defined.) The fact that you can *assign* a value of any type to any name makes it *dynamically* (as opposed to statically) typed.


How do I parse this piece of XML?

Question: I have the following piece of XML in my SQL:
DECLARE @xml XML
SET @xml = '<?xml version="1.0" encoding="UTF-8"?>
<BillingAddresses>
  <BillingAddress Winner="W1">
    <Losers>
      <Loser Id="L1" />
      <Loser Id="L2" />
      <Loser Id="L3" />
    </Losers>
  </BillingAddress>
  <BillingAddress Winner="W10">
    <Losers>
      <Loser Id="L65" />
    </Losers>
  </BillingAddress>
</BillingAddresses>'

I'd like to fetch data in the following manner.
Winner | LoserID
W1       L1
W1       L2
W1       L3
W10      L65

I can get to the Winner attribute of BillingAddress:
SELECT Col.value('(@Winner)[1]', 'varchar(30)')
FROM @xml.nodes('/BillingAddresses/BillingAddress') Rev(Col)

but I am at a loss how to get to the Id attribute of the Loser nodes
Answer: I actually got it...
    SELECT
         Col.value('(../../@Winner)[1]', 'varchar(30)') AS WinnerId
        ,Col.value('(@Id)[1]', 'varchar(18)') AS LoserId
    FROM @xml.nodes('/BillingAddresses/BillingAddress/Losers/Loser') Rev(Col)

The trick is to go as deep into the XML hierarchy, then use the relative operator (../) to make your way out to fetch whatever parent piece you need.

How do I parse this piece of XML?


How can one efficiently group the nodes of a directed acyclic graph to make collective nodes?

Question: The adjacency matrix $A$ of the transitive closure of a directed acyclic graph can have a `checkerboard' pattern  like
\begin{equation}
A = \begin{pmatrix}
0 & ? & ? & ? & {\bf a}    &  {\bf a}   & b  &  b  &  b    &   {\bf c} \\
? & 0 & ? & ? & {\bf a}   &   {\bf a}  &  b &   b &   b   &   {\bf c} \\
? & ? & 0 & ? &  {\bf a}  &   {\bf a}  &  b &   b &   b   &   {\bf c}\\
? & ? & ? & 0 &  {\bf a}  &   {\bf a}  &  b &   b &   b  &    {\bf c}\\
 {\bf a}'  &{\bf a}'   &  {\bf a}' &  {\bf a}'  &  0 &  ? &   {\bf d} &  {\bf d}  &  {\bf d}   &  e  \\
{\bf a}'  &  {\bf a}' & {\bf a}'  &  {\bf a}'  &  ? & 0 &   {\bf d} &  {\bf d}  &  {\bf d}   & e   \\
 b'  &  b' &  b' &   b' &  {\bf d}'  &  {\bf d}'   &  0 & ? & ?  &  {\bf f} \\
 b'  &   b'&   b'&   b' & {\bf d}'   & {\bf d}'    &  ? & 0 & ?  &  {\bf f} \\
 b'  &   b'& b'  &   b' &  {\bf d}'  &  {\bf d}'  &  ? & ? & 0  &  {\bf f} \\
{\bf c}' &   {\bf c}' & {\bf c}'  &   {\bf c}' &  e'  & e'    &  {\bf f}'  & {\bf f}'  &  {\bf f}'   & 0\end{pmatrix}\ .
\end{equation}
The alternate light and heavy fonts are here just to make the `checkerboard'
pattern of the lettered constants apparent to the eye.
Each of the square blocks along the diagonal can be viewed as representing a set of nodes
that forms in a sense its own collective node; in my work it has been profitable to study
the related four-node graph whose adjacency matrix is
$$\begin{pmatrix}
 0 &{\bf a} & b & {\bf c}\\
{\bf a}' & 0 & {\bf d} & e\\
 b' & {\bf d}' & 0 & {\bf f}\\
 {\bf c}' & e' & {\bf f}' & 0\\
\end{pmatrix}\ .$$
Question: given any adjacency matrix where the nodes have not already been assigned to sets that make the checkerboard pattern plain, how can this sort be efficiently done?
Answer: This problem may belong just to the general mathematics of matrices and not require special knowledge of adjacency matrices at all, just knowledge of their basic properties:
The elements of an adjacency matrix are all $0$'s and $1$'s, and any above-diagonal element $A_{ij}$ and its below-diagonal
counterpart $A_{ji}$ must form one of the pairs $(1,0)$, $(0,1)$, and $(0,0)$.  The diagonal elements are $0$.
If an adjacency matrix represents a transitive closure,
then if $A_{ij}=1$ and $A_{jk}=1$, then $A_{ik}=1$.  The $4\times 4$, $2\times 2$, $3\times 3$, and $1\times 1$
blocks along the diagonal of the example above are otherwise arbitrary.
Some problems cannot be reduced to fewer nodes than in the original problem.
One can split the nodes into a set $I$ and a set $J$ and see if the set $I$ forms a collective node by checking if for each $j\in J$ all the values $A_{ij}$ for $i\in I$ match,
and all the values $A_{ji}$ also match.  If one finds a collective node, finding the next reduces to another solving the same general problem but with an adjacency matrix with fewer nodes, which is helpful; still, running through all the sets is slow and I am looking for a better approach.


SQL command to INSERT a row - but when current_timestamp() exists, update it

Question: I have SQL table like this
| id (int) | price (float) | date (current_timestamp)|
|----------|---------------|-------------------------|
| 1        | 5.50          | 2021-09-04              |
| 2        | 20.49         | 2021-09-05              |

I need help with SQL command for update row  WHERE date = CURDATE() but only if row with today timestamp exists. If not then insert. How?
Comment: Research: INSERT ON DUPLICATE UPDATE. You may need to make sure that `date` is defined as unique
Answer: You can use on duplicate key update . . . assuming you have a unique index or constraint on id.
insert into t (id, price, date)
    values (?, ?, ?)
    on duplicate key update date = values(date);

If id is not the primary key or declared unique, you can add the constraint:
alter table t add constraint unq_t_id unique (id);

Comment: I added unique index on date and that works. Thanks.


What does expectation of an indicator random variable signify?

Question: This was a question in my probability theory class recently:

There are $5$ balls, numbered $1-5$, in a bag. We take $3$ of those
balls at random. What is the expected value of the sum of the $3$
balls taken out of the bag?

Here's one approach that my instructor suggeseted:
Let $I_i$ be the Indicator random variable for ball with the number $i$, which is 1 if the ball is selected and $0$ otherwise.
We then calculate the the required expected value of the sum as :
$$
\sum_{i=1}^{5} iE[I_i]=\frac{3}{5}(1 + 2 + 3 + 4 + 5)\boxed{=9}
$$
I don't understand why this approach works. Why would the summation of the multiplication of the expectation of the indicator random variable with the number that it is associated with giving me the correct answer?
Answer: The expectation of an indicator variable is just the probability of the event it indicates,
and by linearity of expectation,
Expectation of sum = Sum of expectation
Answer: The indicator $I_i$ is a Bernoulli random variable that takes the value $1$ if ball $i$ was one of the 3 balls you chose and $0$ otherwise. Recall the expected value of a Bernoulli random variable is the probability of success, which in this case is $3/5$.
Notice the sum of the values of the 3 balls you chose can be expressed as
$$S=\sum_{i=1}^5 iI_i.$$
Use linearity of expectation to compute $E[S]$ and you are done.


Organizando ordem do Mês em um array php

Question: Usei a função abaixo para organizar as ordens dos meses em ordem crescente, funciona perfeitamente, porém ela perde as chaves, quando cria o novo array organizado, as chaves iniciam do 0 (zero) novamente
Array desordenado:

Array ( [39] => agosto [40] => agosto [41] => agosto [42] => agosto [43] => agosto [44] => agosto [45] => agosto [46] => agosto [48] => agosto [71] => novembro [69] => novembro [70] => novembro [64] => outubro [65] => outubro [66] => outubro [68] => outubro [49] => setembro [51] => setembro [52] => setembro [53] => setembro [54] => setembro [55] => setembro [56] => setembro [57] => setembro [59] => setembro [60] => setembro [62] => setembro )

Array ordenado, após passar pela função abaixo, porém perdendo as chaves:

Array ( [0] => agosto [1] => agosto [2] => agosto [3] => agosto [4] => agosto [5] => agosto [6] => agosto [7] => agosto [8] => agosto [9] => setembro [10] => setembro [11] => setembro [12] => setembro [13] => setembro [14] => setembro [15] => setembro [16] => setembro [17] => setembro [18] => setembro [19] => setembro [20] => outubro [21] => outubro [22] => outubro [23] => outubro [24] => novembro [25] => novembro [26] => novembro )

e abaixo a função utilizada:
$sort = array('Janeiro', 'janeiro','Fevereiro',
              'fevereiro','Março', 'março','Abril',
              'abril','Maio', 'maio','Junho', 'junho',
              'Julho', 'julho','Agosto', 'Agosto',
              'Setembro', 'setembro','Outubro', 'outubro',
              'Novembro', 'novembro','Dezembro', 'dezembro');

usort($teste,
       function($value1, $value2) use ($sort) {
           return array_search($value1,$sort) > array_search($value2,$sort);
       }
);

Minha pergunta é, como eu faço essa ordenação em ordem crescente dos meses sem perder as chaves?
Answer: Consegui resolver apenas trocando o 'usort', pelo 'uasort', classifica com base no meu array base ($sort), porém mantendo as chaves.
$sort = array('Janeiro', 'janeiro','Fevereiro',
              'fevereiro','Março', 'março','Abril',
              'abril','Maio', 'maio','Junho', 'junho',
              'Julho', 'julho','Agosto', 'Agosto',
              'Setembro', 'setembro','Outubro', 'outubro',
              'Novembro', 'novembro','Dezembro', 'dezembro');

uasort($teste,
       function($value1, $value2) use ($sort) {
           return array_search($value1,$sort) > array_search($value2,$sort);
       }
);


SwiftUI voice over keyboard navigation for macOS

Question: Is there a way to change the default key combination voice over uses to move the focus of the reader between elements on macOS? On iOS it's just various forms of multi-gesture inputs that are already pretty intuitive, but on macOS it seems to be ctrl+option+arrow_key or ctrl+option+shift+arrow_key and this is by far NOT as intuitive as something like being able to use the Tab key to navigate between elements.
Answer: You can't change the VO key (ctrl+opt) but you can assign other keys to do the same action.
Assign VoiceOver commands to keyboard or keypad keys on Mac
VoiceOver is quite different than PC based screen readers (JAWS, NVDA, Narrator). It does have a learning curve and might not seem intuitive, but visually impaired users have been using it for a long time.
If you have a trackpad, you can turn on the Commander and do the same gestures (such as swipe right) on the trackpad like you can on the iphone.


Show that $y(t) = t$ and $g(t) = t \ln(t)$ are linearly independent

Question: I need to show that $y(t) = t$ and $g(t) = t \ln(t)$ are linearly independent.  I thought I could use the Wronskian as follows:
$y'(t) = 1$
$g'(t) = 1 + \ln(t)$
So $W(y, g) = (t)(1 + \ln(t)) - t \ln(t)$, so $W(y, g)(0) = 0$, which means they're not linearly independent.  Am I doing something wrong, or is the problem statement written incorrectly?
Comment: Are the functions defined (esp $g$) at $t=0$? Also, I get $W=t$, which is only 0 when $t=0$.
Comment: Try it this way.  If there were numbers $a$ and $b$ such that $ay(t)+bg(t)$ were everywhere zero, and $a$ and $b$ were not both zero (which is the definition of linear dependence), then what could you say about $\ln t$ as a function?  Is this a contradiction?
Comment: They certainly are linearly independent. This can be done in several easy ways.
Answer: The point is that

two functions whose Wronskian is nonzero somewhere in an interval where the functions are differentiable are linearly independent on that interval.
two functions that are analytic on an open interval $(a,b)$ and whose Wronskian is $0$  everywhere on that interval are linearly dependent on that interval.

It is quite possible to have two analytic functions whose Wronskian is $0$ at some points of the interval but not at others, and then the functions are linearly independent.
Consider for example $t$ and $t^2$, whose Wronskian is $0$ at $t=0$.
In your example, the Wronskian of $t$ and $t \ln t$ is in fact nonzero everywhere on the interval $(0,\infty)$ where they are both analytic.
Answer: A related problem. Just apply the idea from linear algebra, two vectors $u_1$ and $u_2$ are linearly independent, if
$$c_1 u_1 + c_2 u_2 = 0 \Rightarrow c_1=c_2=0\,. $$
Apply this to your functions
$$ c_1 y(t) + c_2 g(t) = 0 $$
Now we need another equation in $c_1$ and $c_2$. We can get it by differentiating the equation with respect to $t$
$$ c_1 y'(t) + c_2 g'(t) = 0 \,.  $$
The two homogeneous equations will have a solution $c_1=c_2=0$ if the determinant $D\neq 0$. That is
$$ y(t)g'(t)-g(t)y'(t)=0 \,. $$
Applying this to your problem,
$$ t(\ln(t) + 1 ) - t\ln(t) = t \neq 0 \,. $$
So, the two functions are linearly independent.
Comment: Does this allow me to write a general solution for $t^2y'' - ty' + y = 0$?
Comment: @BobJohn:Yes, because you have two linearly independent solutions. You can write the general solution as $y_G(t)=c_1y(t)+c_2g(t)$.


Using Array Walk Within A Class

Question: I am having a small programming issue.  I am trying to execute a function within a class and I have an array that I am using array_walk to execute a function on each variable within that array.  The issue is that the function I am executing is a method within the same class.  I have looked over my code however cannot find what the issue is.  Please let me know what a possible solution to this error is or if you see something I am not seeing.
Currently it is not even executing the function escape().  I purposely added a ' in the status variable as I want it to be escaped, but it is done not.
A little background: This is a database class I am building and the prepare() method will help escape variables in the query before it is executed.  I removed some code that is not relevant to this issue.
This is the result it is giving me: UPDATE table_name SET status='I'm doing good!' WHERE username='someone'
<?php
class Database {
    var $weak_escape = false;

    function escape($str) {
    if ($this->weak_escape) return $this->weak_escape($str);
    else return $this->sql_escape($str);
    }

    function weak_escape($str) {
    return addslashes($str);
    }

    function sql_escape($str) {
    return mysql_real_escape_string($str);
    }

    function prepare($query) {
    $args = func_get_args();
    array_shift($args);
    array_walk($args, array(&$this, 'escape'));
    return vsprintf($query, $args);
    }
}

$db = new Database();
$username = "someone";
$status = "I'm doing good!";
echo $db->prepare("UPDATE table_name SET status='%s' WHERE username='%s'", $status, $username);
?>

Comment: I think should be like this $db = new Database(); And I am pretty sure if not already, real soon passing by reference is depreciated.
Comment: Yeah that is just my bad habit, in the final code it has variables there, when typing it in to this website I forgot that part.  Thanks though, I fixed the example above.  Obviously that doesn't fix the issue though.
Comment: where is the escape function being performed? Edit:Never mind, i see it. though I don't think you need to ue an & there. $this should already refer to the class no?
Comment: I tried it with an without, and unforuntely it did not make a difference.
Comment: your escape function is firing and working. got something to do with other parts of your code.
Comment: Dr.Molle's method ended up working.  But only returning without declaring a variable it didn't modify the inputted data.
Answer: I'de make my escape function static, cause it's the same for every instance:
class Database {
    static function escape($str) {
       return addslashes($str);
    }

    function prepare($query) {
      $args = func_get_args();
      array_shift($args);
      array_walk($args, array('Database', 'escape'));  //Look here
      return vsprintf($query, $args);
    }
}

Hope this helps. Cheers
Comment: I have a feeling that will work with the example I gave however my actual code it doesn't work because within `function escape($str)` it makes a $this reference to another method within the class.  Let me try to update my example above to show what I mean.
Answer: You'll need to modify the argument(reference of array-item), this isn't done if you return it:
function escape(&$str)
{
  $str=addslashes($str);
}

Comment: That ended up doing the trick.  Thank you, normally I do that but I figured I would try to reduce the amount of code, however less code ended up hurting me.  Normally I don't use the & but it obviously makes a difference.
Answer: Hope this is what you are looking for.
I did this:
class Database {
    function escape($str) {
       return addslashes($str);
    }

    function prepare($query) {
    $args = func_get_args();
    $args[1] = $this->escape($args[1]);
    array_shift($args);
    array_walk($args, array($this, 'escape'));
    return vsprintf($query, $args);
    }
}

$db = new Database();
$username = "someone";
$status = "I'm doing good!";
print $db->prepare("UPDATE table_name SET status='%s' WHERE username='%s'", $status, $username);

got result:
UPDATE table_name SET status='I\'m doing good!' WHERE username='someone'

Using Array Walk Within A Class


What step am I missing installing drush with Composer?

Question: From my project root, where composer.json and composer.lock are, I tell composer to require drush/drush. It seems to do what it should, but upon completion it seems drush is not installed.
$ composer require drush/drush
Using version ^8.1 for drush/drush
./composer.json has been updated
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing webmozart/path-util (2.3.0)
    Downloading: 100%

  - Installing symfony/var-dumper (v2.8.13)
    Downloading: 100%

  - Installing jakub-onderka/php-console-color (0.1)
    Downloading: 100%

  - Installing jakub-onderka/php-console-highlighter (v0.3.2)
    Downloading: 100%

  - Installing dnoegel/php-xdg-base-dir (0.1)
    Downloading: 100%

  - Installing nikic/php-parser (v2.1.1)
    Downloading: 100%

  - Installing psy/psysh (v0.7.2)
    Downloading: 100%

  - Installing pear/console_table (v1.3.0)
    Downloading: 100%

  - Installing consolidation/output-formatters (1.1.0)
    Downloading: 100%

  - Installing consolidation/annotated-command (1.4.1)
    Downloading: 100%

  - Installing drush/drush (8.1.5)
    Downloading: 100%

Writing lock file
Generating autoload files
> DrupalProject\composer\ScriptHandler::createRequiredFiles

$ drush
The program 'drush' is currently not installed. You can install it by typing:
sudo apt install drush

Comment: try this http://drupal.stackexchange.com/questions/219209/what-step-am-i-missing-installing-drush-with-composer/219219
Answer: Well, actually you installed it locally. You can find it in your project's directory under vendor/drush/drush place (maybe, it depends where the composer put it). You can call only from that place because it's not in your global path. If you want to use this method, you need to call it with an absolute or relative route. Like if your composer installed to here:
On Windows:
D:/phptest/my_project/vendor/drush/drush
On Linux:
~/my_project/vendor/drush/drush
and you are in the D:/phptest/my_project (Windows) or ~/my_project (Linux) dir, in that case, you need to call it like:
On Windows:
vendor/drush/drush --version   OR  D:/phptest/my_project/vendor/drush/drush --version
On Linux:
vendor/drush/drush --version   OR  ~/my_project/vendor/drush/drush --version
and you will get something like:
Drush Version   :  8.1.3
Of course for this, you need a PHP in the global path. (so you need to be able to call PHP from anywhere.)
If you installed it globally with composer (I think you just installed it locally), in that case maybe you need to create a (soft) symlink one place which is globally available for you (listed in the %PATH% variable on windows or in the $PATH variable on Linux), or you need to add the drush's dir to your global path variable.
I suggest you, install it globally, like here is written: https://docs.drush.org/en/8.x/install/
# Browse to https://github.com/drush-ops/drush/releases and download the drush.phar attached to the latest 8.x release.

# Test your install.
php drush.phar core-status

# Rename to `drush` instead of `php drush.phar`. Destination can be anywhere on $PATH.
chmod +x drush.phar
sudo mv drush.phar /usr/local/bin/drush

# Optional. Enrich the bash startup file with completion and aliases.
drush init

Then you can use it in any site's dir.
TIPP: if you're installing drush launcher (https://github.com/drush-ops/drush-launcher) globally, then you can have per-site base different drush installed. In this case, you don't need to have global drush installed.
Comment: I know this is an old comment, but I came to it looking for some Drush help.  The above link to /en/master/install is no longer active. Anyone new to this and looking for the current link for installation instructions, its found here: https://docs.drush.org/en/8.x/install/.

Enjoy.  :-)
Comment: @Drew Thanks, I've updated my answer and also I've extended it.
Answer: Since you didn't use the --global option, Composer installed Drush in the vendor directory. More precisely, the Drush executable is on vendor/bin. If I run vendor/bin/drush status, I get the following output.

Drupal version                  :  8.2.1
   Site URI                        :  http://default
   Database driver                 :  sqlite
   Database name                   :  sites/default/files/.ht.sqlite
   Drupal bootstrap                :  Successful
   Drupal user                     :
   Default theme                   :  bartik
   Administration theme            :  seven
   PHP executable                  :  /usr/local/bin/php
   PHP configuration               :  /usr/local/etc/php/7.0/php.ini
   PHP OS                          :  Darwin
   Drush script                    :  /Library/Server/Web/Data/Sites/Default/vendor/drush/drush/drush.php
   Drush version                   :  8.1.5
   Drush temp directory            :  /tmp
   Drush configuration             :
   Drush alias files               :
   Install profile                 :  standard
   Drupal root                     :  /Library/Server/Web/Data/Sites/Default
   Drupal Settings File            :  sites/default/settings.php
   Site path                       :  sites/default
   File directory path             :  sites/default/files
   Temporary file directory path   :  /tmp
   Sync config path                :  sites/default/files/config_Dy0z5R0mB3fLiKC_f8qR1UcV4HkXFeohO3KKXBcYUTWrsxunPXpZbezfqd39
                                      mz4u0G7LVAYSmg/sync

I normally read they suggest installing Drush as you did, but you can also install it globally, with composer --global require drush/drush. On macOS Sierra, using that command installs Drush in ~/.composer/vendor/bin, which I then need to add to the Bash PATH with the following command.
if [ -d $HOME/.composer/vendor/bin ]; then
    export PATH=$PATH:$HOME/.composer/vendor/bin
fi

I didn't install Drush globally, but I added those lines in ~/.bash_profile, in the case I globally install other commands with Composer.


Three separate tables that sit left to right next to each other centered

Question: I am attempting to have a series of tables sit next to each other from left to right while being centered.

Status:

Now Playing:

Album Art goes here

Player goes here

Stuff

stuff 2

stuff 3

By using float:left in my tables I have been able to get them to sit next to each other, but I have not been able to center the tables. I tried wrapping everything in a div and telling to to center everything, but that does not seem to work.  Any help is appreciated!
Answer: Try changing the first div to:

As long as the margin-left is - half the width, this should work.
Answer: Use display:inline-block instead of float:left.
Then use the div style text-align=center on the enclosing div.
Will also need to add vertical-align=top to each table style.
See here:
http://jsfiddle.net/KJhhc/
Comment: Stan, Please see if you can upvote the answers that worked for you. We value the votes a lot within the stackoverflow community. Also please "mark as answer" the solution that you chose.
Answer: Concept is to set the width for
 and specify margin-left and margin-right to auto.
<!DOCTYPE html>

Status:

Now Playing:

Album Art goes here

Player goes here

Stuff

stuff 2

stuff 3

Comment: This worked for me thank you! This was my first time reaching out to the internet for help with code and I am not disappointed. Thanks again!


Integrating $\int{\frac{x}{x+1}}\,dx$

Question: None of the methods I know can solve this easily. I tried integrating by parts, but it essentially leads you to the equation $\int{\frac{x}{x+1}}\,dx=\int{\frac{x}{x+1}}\,dx$, which isn't very helpful.
Using Wolfram Alpha, it seems like you need to rewrite the integrand:
$$\frac{x}{x+1}=1-\frac{1}{x+1}$$
That makes it easy to integrate. Is this some method that others know about? I never came across a problem like this before, so it's interesting for me. In what cases should one rewrite the integrand like this in order to make integration easier? I'm asking this so that I can be prepared for the next time a question like this stumps me.
Comment: Two words: long division.
Comment: It seems you are happy with your answer. The general way to do this would be to use https://en.wikipedia.org/wiki/Polynomial_long_division Can be good to remember when your polynomials are a bit larger.
Comment: Thank you. So in which cases should I use long division? When I have a fraction that I can't seem to integrate using traditional methods?
Comment: Just substitute $x = y-1$ ($dx=dy$)?
Comment: Long division isn't a method of integration - it's a way to rewrite the integrand. Notice that we can't use a logarithm nor a substitution outright, and parts doesn't help at all. Use long division when the degree of the numerator is at least that of the denominator.
Comment: @SeanRoberson I just realized that the substitution suggested by kennytm allows you to rewrite as $$\frac{y-1}{y}=1-\frac1y=1-\frac{1}{x+1}$$ so it does help in this case! (And it's the same thing as suggested by WA)
Comment: I'll also keep your suggestion in mind. Thank you!
Answer: This is a standard technique: $$\frac{x}{x+1} = \frac{x+(1-1)}{x+1}=\frac{x+1}{x+1}-\frac{1}{x+1}$$
Notice all I did was to add $0$.
Comment: Two standard techniques that students often underestimate the power of: adding $0$ and multiplying by $1$.
Comment: I've never thought of it like that before, so it seems quite ingenious!
Answer: Just another take, in case Bye_Worlds ingenuity escapes you.
Suppose you need to address $\int\frac{x}{x+1} \,dx$, as given.
One option is to use "u-substitution": Let $u = x+1 \implies du=dx.$ But also $u = x+1 \implies x = u-1$
That gives us $$\int \frac {u-1}{u}\,du = \int \left (1 - \frac 1u\right) \,du$$
$$ = u - \ln(u) + c$$
Back substitution gives us $$ (x+1) - \ln(x+1) + c$$
Now notice, we can absorb the $1$ from $x + 1$ to get $$x - \ln (x+1) + \underbrace{(c +1)}_C$$
Comment: Oh my, I didn't read the helpful comments below your question. At any rate, you are most welcome!
Comment: Hey, thanks a lot for the answer! I feel really bad saying this though (and really mean, given the fact that you spent some time writing this out), but I essentially *did* figure this out if you look at my comment on the question, thanks to kennytm's suggestion. That being said, I want to thank you wholeheartedly for answering my question – it does quite well to elucidate this particular method :)

Integrating $\int{\frac{x}{x+1}}\,dx$


How to get @UseAdviceWith working in Camel 3

Question: I am about writing some unit tests for production Camel routes in a Spring Boot application. To do so I use adviceWith technique and do not want the CamelContext to start before the advising is done. With Camel 2.24.2 my test class looks like a snippet below, I have ommited the details like autowiring and test expectations for brevity.
@RunWith(CamelSpringBootRunner.class)
@SpringBootTest
@UseAdviceWith
public class CamelApplicationTests {
    ...
    context.getRouteDefinition("test.simple").adviceWith(context, new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {
            interceptSendToEndpoint("file:/home/outfolder")
                .skipSendToOriginalEndpoint()
                .to("mock:outFolder");
            }
        });
    context.start();
    ...
}

Running this test I get logs as expected
INFO  melSpringBootExecutionListener - @RunWith(CamelSpringBootRunner.class) before: class org.sample.CamelApplicationTests.testSimple
INFO  melSpringBootExecutionListener - Initialized CamelSpringBootRunner now ready to start CamelContext
INFO  spring.CamelAnnotationsHandler - Skipping starting CamelContext(s) as UseAdviceWith annotation was found and isUseAdviceWith is set to true.

Now, it's time for a migration towards Camel 3 and the advising part have to be rewritten as follows and it works just fine
@RunWith(CamelSpringBootRunner.class)
@SpringBootTest
@UseAdviceWith
public class CamelApplicationTests {
    ...
    AdviceWithRouteBuilder.adviceWith(context, "test.simple", route ->
        route.interceptSendToEndpoint("file:/home/outfolder")
            .skipSendToOriginalEndpoint()
            .to("mock:outFolder"));
    context.start();
    ...
}

Except that CamelContext is getting start automatically, so we have the advised route restarted
INFO  o.a.c.i.e.InternalRouteStartupManager    : Route: test.simple started and consuming from: file:///home/infolder
INFO  o.a.c.impl.engine.AbstractCamelContext   : Total 1 routes, of which 1 are started
INFO  o.a.c.impl.engine.AbstractCamelContext   : Apache Camel 3.4.3 (camel) started in 0.923 seconds
INFO  org.sample.CamelApplicationTests         : Started  in 11.544 seconds (JVM running for 13.935)
INFO  o.a.c.i.engine.DefaultShutdownStrategy   : Starting to graceful shutdown 1 routes (timeout 45 seconds)
...
INFO  o.a.c.impl.engine.AbstractCamelContext   : Route: test.simple is stopped, was consuming from: file:///home/infolder
INFO  o.a.c.impl.engine.AbstractCamelContext   : Route: test.simple is shutdown and removed, was consuming from file:///home/infolder
INFO  org.apache.camel.reifier.RouteReifier    : AdviceWith route after: ...
...
INFO  o.a.c.i.e.InternalRouteStartupManager    : Route: test.simple started and consuming from: file:///home/infolder

It seems to be a bug, or am I missing something?
P.S.
After some researching I found an issue have been fixed in Camel 2.21 version, so I have checked the CamelSpringBootExecutionListener.java file from 3.4.x branch and it looks OK, but after taking a closer look at my logfile I noticed there was no @RunWith(CamelSpringBootRunner.class) preparing log, which means the prepareTestInstance method was never invoked, but I guess it should
Answer: Solved this by migrating to Junit 5, now I have my test classes annotated like
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.apache.camel.test.spring.junit5.UseAdviceWith;
import org.springframework.boot.test.context.SpringBootTest;

@CamelSpringBootTest
@SpringBootTest
@UseAdviceWith
public class CamelApplicationTests {
    ...
}


SOM based on a not euclidean distance

Question: Suppose one has trained a SOM on a certain number of data. Without explaining all the procedure, one can say that the SOM algorithm produces a certain number of prototypes and the new elements coming in input are clustered based on the distance from the prototypes.
Two possible packages are:

kohonen::som (R)
somclu (Python)

Here it is explained the fact that in a high dimensional context the euclidean distance is not the best to capture the difference among vectors.
Nevertheless, relying on the two previous algorithms it seems (coincidence?) that there's not the possibility to choose a distance different from the euclidean one in order to train the models.
There exists a reason for which the euclidean distance could be the best (or only possible) one on the training process of a self organizing map?
Answer: This problem is not only related to the SOM, it's a general problem. In big dimensions small changes in parameters can cause big differences in distances. This problem appears when you try to measure euclidean distance in high dimensional space. Let say you have two vectors. Each of them has dimension size equal to 1000. In the first vector all elements equal to 1, and in the second one all elements equal to 0.99. Basically, all elements in the second vector reduced by 1% compare to the first one. These vectors should be pretty close to each other when you try to learn algorithm to capture some relations in the data. But here what happens when you try to compute euclidian distance.
<code>>>> import numpy as np
>>> x = np.ones(1000)
>>> y = np.ones(1000) * 0.99
>>> x[:10]
array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])
>>> y[:10]
array([ 0.99,  0.99,  0.99,  0.99,  0.99,  0.99,  0.99,  0.99,  0.99,  0.99])
>>>
>>> from sklearn import metrics
>>> metrics.euclidean_distances(x,y)
array([[ 0.31622777]])
>>>
>>> metrics.pairwise.cosine_distances(x,y)
array([[ -3.55271368e-15]])
</code>
As you can see euclidean distance shows that vectors are not very close to each other. For comparison I've also added the cosine distance metric. Cosine distance is equal to zero (in the example above I got $-3 \cdot 10 ^ {-15}$, because of computational error), because two vectors have the same direction and angle between them is equal to zero
Comment: In the literature related to the SOM I've came across just euclidean disntance and cosine similarities. Here you can find an implementation of SOM that supports both of these measurments - https://github.com/itdxer/neupy/blob/master/neupy/algorithms/competitive/sofm.py
Comment: I agree. Nevertheless, what I have seen in the SOM context is that it seems like no one has thought to something different to the euclidean distance. What you've answered strenghtens the concept: there exists some implementation of the SOMs with a not-euclidean distance?
Answer: Upon reading about Kohonen Self Organising Maps, my initial thoughts were the same. It seems there has been some research on it, but I don't know enough about the area to comment more. There is a paper called Extending the SOM Algorithm to Non Euclidean Distances via the Kernel Trick, but it is behind a paywall so I can't comment on the content. I've requested the paper on Research gate so we'll see how that goes.
With regards to the code: could you inherit from existing solutions and implement a different distance metric? Alternatively, could you transform the data set via feature scaling, say, and see how your results differ?
Comment: The algorithm is written in C: I think that maybe it could be easier to implement it from the beginning than inheriting. About the scaling it's an interesting idea, but it would be the transformation of a transformation (maybe too many passsages?). I've seen the paper: probably it's a well-known topic outside stack! :)

SOM based on a not euclidean distance