How can I use port tunneling to connect to a private database instance through a network bastion?

Question: I have a network bastion which is publicly accessible at example.compute-1.amazonaws.com and a private postgres database instance at postgres.example.us-east-1.rds.amazonaws.com:5432
I can ssh into the bastion using
$ ssh -i key.pem firstname.lastname@example.com

Then once I'm in the bastion I create a ssh tunnel with:
$ ssh -i key.pem -L 5432:postgres.example.us-east-1.rds.amazonaws.com:5432 email@example.com

I can then verify that the tunnel works by connecting to the database from the bastion using localhost:
$ psql -p 5432 -h localhost -U postgres

However, I am unable to connect to the database remotely (without being in the bastion).
$ psql -p 5432 -h example.compute-1.amazonaws.com -U postgres
psql: could not connect to server: Connection refused
Is the server running on host "example.compute-1.amazonaws.com" () and accepting
TCP/IP connections on port 5432?

I've configured the security group of the bastion to accept inbound traffic on port 5432.
Am I using ssh -L correctly? Should I be using it outside the bastion? Any advice would be much appreciated.
Answer: When you create an SSH tunnel, it does not expose the opened port to the outside world. The opened port, is only available as localhost. So effectively what you've done is to create a tunnel from your bastion, to your bastion.
Instead, what you want to do is create a tunnel from your local computer through your bastion.
So, you create your tunnel as part of your connection from your local computer to your bastion. You do not need to create another SSH connection.
So, locally, you would execute:
$ ssh -i key.pem -L 5432:postgres.example.us-east-1.rds.amazonaws.com:5432 email@example.com

Assuming postgres.example.us-east-1.rds.amazonaws.com resolves to the private IP address.
Then to connect to your server, still locally, connect as if the server was local:
$ psql -p 5432 -h localhost -U postgres

Doing this, there's no need to use a prompt on your bastion.
Comment: This worked for me, thanks!
The one thing I did forget for anyone who's psql command just hangs there: Make sure that your db security group allows access from the bastion.
Answer: This worked for me. Make sure you have psql client installed locally.
psql --host=myAwsDbEndpointUrl.ciqykqusf0nv.us-west-1.rds.amazonaws.com --port=5432 --username=myUserName --password --dbname=myDbName

When creating your db instance on aws, make sure to define the following:

username
password
database name
port number

I also had to create a security group for the VPC that the database was located in. After creating it make sure your db instance uses this for its security group. The security group has the following rules:
inbound--> type:PostgreSQL, protocol:TCP port range:5432, source:0.0.0.0/0

outbound--> type:All Traffic, protocol:All, port range:all, destination:0.0.0.0/0

Comment: That is not going via a bastion though, right? You are just connecting directly to RDS
Comment: It goes through a vpc that the rds instance is exposed through. You attach the vpc to the rds instance upon creation.
Comment: Yeah i think the original question was with regard to going via a bastion server in the VPC so the RDS instance is not publicly exposed (well thats how i read it)
Comment: That was not the question and your answer doesn't help solving the problem at all.


Symfony - Add class to form tag

Question: I know I can add classes to <input> fields in a form like this:
->add('foo', 'text', array('attr' => array('class' => 'foo-class'));

but how could I add a class to a <form> tag?
Answer: For this, there's 2 solutions, either you do it in your controller or your view.
1) In your controller :
$form = $this->createForm(new FormType(), $data, ['attr' => ['class' => 'myClass']]);

2) In your view (Twig) :
{{ form_start(form, { 'attr' : { 'class': 'myClass' } }) }}

Comment: *The function "form_start" does not exist* when using the second option. Maybe due to I am using Symfony-2.1
Comment: Indeed, it seems like 'form_start' doesn't exists in SF 2.1.
http://symfony.com/doc/2.1/reference/forms/twig_reference.html

If you can't upgrade your Symfony distribution, try to use to first solution, or just write your  tag manually.
Comment: Tried your first option with `createFormBuilder`, but doesn't seem to work. Solved writing the `` tag manually. +1 anyway for your answer because probably there are not other ways to achieve it.
Comment: In fact, i made a mistake in solution 1, the third parameter was incorrect, and i've updated it. My bad
Answer: In a form type class (working in Symfony 4+, not sure if in earlier), in setDefaultOptions():
class FooType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('bar')
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'App\Entity\Foo',
            'attr' => ['class' => 'custom-css-class']
        ]);
    }
}

Symfony - Add class to form tag


Are these two subsets of matrices rank-$1$ connected?

Question: While solving a problem in calculus of variations, I have reached the following question:
Let $s>0$ be a positive number (in my  application $s>\frac{1}{2}$, but I am not sure if it matters here). Let $M_2$ be the set of all real $2 \times 2$ matrices, and define the following sets:
$$X=\{ A \in M_2 \, |\, \det A=s^2 \,\text{and }\,\sigma_1(A)=\sigma_2(A)=s \}, \, \,\,\,\,Y=\{ A \in M_2 \, |\, \sigma_1(A)=0, \sigma_2(A)=1 \},$$
where $\sigma_1(A) \le \sigma_2(A)$ are the singular values of $A$.
(The point of the condition $\det A=s^2$ in the definition of $X$ is to make $\det A$ positive, i.e. to exclude $\det A=-s^2$).

Question: Do there exist $A \in X, B \in Y$ such that $A-B$ has rank $1$?
Answer: $A$ and $B$ exist iff $s\le1$. We have $X=\{sQ:Q\in SO_2\}$ and $Y=\{uv^T:\|u\|_2=\|v\|_2=1\}$. Hence
$$
\det(sQ-uv^T)
=\det(sQ)-v^T\operatorname{adj}(sQ)u
=s^2-sv^TQ^Tu
\ge s^2-s.\tag{1}
$$
Therefore $sQ-uv^T$ is nonsingular when $s>1$.
When $0<s\le1$, pick any two unit vectors such that $v^Tu=s$. Let $A=sI$ and $B=uv^T$. Then $A-B$ is singular by $(1)$ but it is nonzero because $A$ has rank $2$ but $B$ has rank $1$. Hence $A-B$ is necessarily rank-one. Indeed, as $\operatorname{tr}(B)=v^Tu=s$, the eigenvalues of $B$ are $s$ and $0$. Therefore the eigenvalues of $A-B$ are $0$ and $s$.
Comment: Thanks! That is a great answer; However, I don't understand your last comment: why does $\text{tr}(B)=s$ imply that its eigenvalues are $0$ and $s$? (and how do you deduce the same thing for $A-B$?).  BTW, did you really meant eigenvalues or singular values? Anyway, I understand your argument apart from that. Last question: your characterization of $Y$ follows from considering singular vectors right?
Comment: @AsafShachar (1) The trace of a rank-one matrix is equal to the matrix's only nonzero eigenvalue. (2) Since $A=sI$, each eigenvalue $\lambda$ of $B$ contributes to an eigenvalue $s-\lambda$ of $A-B$. (3) Yes. If $A=USV^T$ is a SVD, since the two singular values of $A$ are equal to $s$, we have $S=sI$ and hence $A=sUV^T$. As $\det(A)=s^2$, we have $\det(UV^T)=1$ and hence $Q=UV^T\in SO_2(\mathbb R)$. Similarly, if $Y=U\operatorname{diag}(1,0)V^T$ is a SVD, we have $Y=uv^T$ where $u$ is the first column of $U$ and $v^T$ is the first row of $V^T$.


How to target labels with specific values and change their background color in WPF?

Question: I am trying to set up data triggers to change the background color of specific labels when they contain "Failed". I have done similar things with datagrids but for some reason I can't get the triggers to work and show any changes. When I use the resource dictionary below it changes all labels in the window to the trigger color instead of just the label that contains "Failed". It might be worth noting that the datagrids I worked with before were in user controls and not plain windows. How can I just get the labels with "Failed" to have a different background color and not all labels on the page?
EDIT: I solved this using Tretoms solutions by using a converter and using textblocks instead of labels and binding my text and converter by doing the following. Text="{Binding Path=SecurityAuditOverallResult}" Background="{Binding RelativeSource={RelativeSource Self}, Path=Text, Converter={StaticResource ResourceKey=ContentToColorConverter}}" Foreground="Black"/> <Label
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    </Style>
</ResourceDictionary>

Here is the window I am using the resource dictionary in.
<Window
    x:Class="Domain_Audit_V2.ComputerInfoWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Domain_Audit_V2"
    mc:Ignorable="d"
    Title="{Binding Path=ComputerName}"
    Style="{StaticResource RedWindowStyle}"
    MinHeight="300" MinWidth="350"
    MaxHeight="1020" MaxWidth="850">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Assets/ComputerInfoDictionary.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <ScrollViewer VerticalScrollBarVisibility="Auto">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
                <RowDefinition Height="32" />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="300" />
                <ColumnDefinition Width="800" />
            </Grid.ColumnDefinitions>

            <ProgressBar
            Grid.Row="7" Grid.Column="1"
            HorizontalAlignment="Left"
            Value="{Binding Path=HarddriveFreespace}"
            Minimum="0"
            Maximum="{Binding Path=HarddriveSize}"
            Width="450"/>

        </Grid>
    </ScrollViewer>
</Window>

This is what it looks like when it is ran.
Only the Status and the column next to fileandprintersharing audit result should be highlighted because they contain "Failed".
Comment: You could bind the Label's Background to its own Content with a Binding Converter that checks if the Content string contains the word "Failed". You might also want to use TextBlocks instead of Labels.
Answer: Not with DataTrigger, but with IValueConverter - if it's OK for you:
Quick & Dirty:
XAML:
<Window x:Class="LabelBack.MainWindow"
    ...
    xmlns:local="clr-namespace:LabelBack"
    ...>
<Window.Resources>
    <local:ContentToColorConverter x:Key="ContentToColorConverter"/>
</Window.Resources>
<StackPanel>

</StackPanel>

ContentToColorConverter:
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;

namespace LabelBack
{
    public class ContentToColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value.ToString() == "Failed") return Brushes.LightCoral;
            return Brushes.LightGreen;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

EDIT:
I think all you need to do is, to change the xaml of this pop-up window with all the labels. There you have row content like:

Change it to:

And of course, you must have the reference to the converter class in the Window.Resources section of the same xaml
Comment: Where exactly would I want to make this class in? I'm still learning the project organization part of WPF MVVM, and to me it seems like this would be part of the xaml.cs for this window. However, it doesn't look like i'd want to do that because of the IValueConverter inheritance i'd need. Is this what you would call a helper class?
Comment: I don't really get what you mean. This converter thing doesn't have much to do with MVVM. Or better said, it belongs to the "V" part of it, because it's all about the view. In my opinion the project structure is more flexible than that, to have a one for all definition of it. The XYConverter class can be anywhere in your project. I mostly put them into a Converters, or Helpers folder.  But there's no inheritance here. IValueConverter is an interface.
Comment: I've been trying to get the converter code to work, but for some reason I'm getting a NullReferenceException when I trigger the window and the Converter's Covert function tries the check if the value is "failed". For context this window is triggered when I click on a row in a datagrid that contains a specific computer, then this window with all the labels pops up and shows a detailed view of the computer.
Comment: I think my problem might be the reference to the class in the resources.  `xmlns:local="clr-namespace:Domain_Audit_V2"
    mc:Ignorable="d"
    Title="{Binding Path=ComputerName}"
    Style="{StaticResource RedWindowStyle}"
    MinHeight="300" MinWidth="350"
    MaxHeight="1020" MaxWidth="850">

` I keep cross checking and can't find a difference between yours. My visual studio shows 0 references on my Convert method inside of the class though.
Comment: if there is something wrong with the namespace reference in the xaml (it's not found) then it's marked with blue squiggle lines. If the line is not marked you should be good to go. And if you are using visual studio (e.g. 2022 community) and type "xmlns:something="clr-namespace:" it should show you the possible namespaces. And as you continue, you should come to the required classname. But the fact that the reference count is 0 means nothing. VS does not check the xaml references.
Put a breakpoint into the converter class to see if it's hit.
Comment: I pushed a small project to github. I hope it helps: https://github.com/tretom2121/LabelBack
Comment: Thanks for that github project, after tinkering I've found out that it does not like my data binding `Content="{Binding Path=SecurityAuditOverallResult}"`  I'm using to connect to my model and change the label dynamically. If I change the label content to a static string like Content="Failed" just like your first two examples, it works exactly like  it does in your example. Any ideas on what could be causing this? I have checked if my binding is producing an actual value of "failed", but if I use my binded content it always returns null when it triggers the converter method.
Comment: I found a solution that does the trick in the meantime. See edit.
Comment: The same solution must work for Label as well as for Textbox. I think your problem was just that you didn't set the UpdateSourceTrigger value to PropertyChanged, or you are not binding to a dependency property, and it's either not updating your initial null value or your binding is not working. I'll update the repo to show a possible way with mvvm
Comment: I have updated the repo. Click the button to set the label content. The background color changes as expected.


Where can I find in database that page (panel) is disabled?

Question: I am using Panels module. If I go to structure -> pages menu link, I will see my pages list.
I can disable/enable those pages. But how does this work under the hood? Where is it marked in the database that some specific page is disabled?
Answer: Panel pages requires Page Manager module which comes with Ctools Module.... Below function in page_manager/page_manager.admin.inc is responsible for enable / disable action...
function page_manager_enable_page($disable, $js, $page) {
  if (!isset($_GET['token']) || !drupal_valid_token($_GET['token'], $page->task_name)) {
    return MENU_ACCESS_DENIED;
  }
  if ($page->locked) {
    if ($disable) {
      drupal_set_message(t('Unable to disable due to lock.'));
    }
    else {
      drupal_set_message(t('Unable to enable due to lock.'));
    }
  }
  else {
    if ($function = ctools_plugin_get_function($page->subtask, 'enable callback')) {
      dpm($function);
      $result = $function($page, $disable);
      menu_rebuild();

      // We want to re-cache this if it's changed so that status is properly
      // updated on the changed form.
      if (!empty($page->changed)) {
        page_manager_set_page_cache($page);
      }
    }
  }

  // For now $js is not actually in use on this.
  drupal_goto('admin/structure/pages');
}

When a panel page (Custom Created , Not default pages that comes with module) is enabled or disabled below function is called in ctools/page_manager/plugins/tasks/page.inc...
/**
 * Callback to enable/disable the page from the UI.
 */
function page_manager_page_enable(&$cache, $status) {
  $page = &$cache->subtask['subtask'];
  ctools_include('export');
  ctools_export_set_object_status($page, $status);

  $page->disabled = FALSE;
}

You can find panel pages details inside variable table under the variable

default_page_manager_pages

When Disabled
a:1:{s:15:"test_panel_page";b:1;}

When Enabled
a:0:{}

Default pages that comes with module enable / disable status also stored in variables table...


Gmail marking self-signed certs as unencrypted

Question: Just a quick question/answer pair to share what I've learned this morning.
Gmail marks self-signed certs for TLS as unencrypted in their interface now. This is obviously wrong. How has anyone else got around this?
Comment: It's not obviously wrong. Without pinning, self-signed certs might as well be unencrypted because they're not providing any protection from active MITM attacks.
Comment: Are you sure this changed? It still shows self signed as encrypted for me.
Answer: Turns out there's a quick fix if you run your own mail server, and possibly web server alongside - use your letsencrypt certs. In /etc/postfix/main.cf:
smtpd_tls_cert_file = /etc/letsencrypt/live/domain.com/fullchain.pem
smtpd_tls_key_file = /etc/letsencrypt/live/domain.com/privkey.pem
smtp_tls_cert_file = /etc/letsencrypt/live/domain.com/fullchain.pem
smtp_tls_key_file = /etc/letsencrypt/live/domain.com/privkey.pem

Not sure of the difference between enabling it for smtpd only (does that cover send/receive? A topic for another question...) but both are there to be sure, anyway.
I also updated the LE script to reload postfix when certs were renewed:
web_service2='postfix'
/usr/sbin/service $web_service2 reload

Added those lines to /usr/local/sbin/le-renew-webroot-SITE which runs on a cron job.
Comment: PS - you can add them to `/etc/dovecot/conf.d/10-ssl.conf` as well, but you don't need to to get rid of the red padlock in Gmail.
Comment: PPS - finally I also added the mail subdomain to the domains list in the config at `/usr/local/etc/le-renew-webroot-SITE.ini`, so that the hostname matches. Then renewed the cert. Again, not essential, but good for completeness. Tested with [SSL Tools](https://ssl-tools.net/mailservers).


How can I cache headers with varnish 4?

Question: I am not able to find a way to do it. Can you help me with some code. I searched a lot on internet but wasn't able to find something.
Comment: Varnish caches both HTML and HTTP headers of a page. Thus your question makes little sense. Can you clarify?
Comment: I thought I had this problem but my problem is even bigger. I get Err_Connection_Refused after modifying the varnish default file. I have installed it properly. Varnish is on port 80 and apache on port 8080.
Answer: double check you have changed the backend port to 8080 also in default.vcl file.
Restart apache and varnish.
You can follow this blog post to ensure varnish is properly installed: https://info.varnish-software.com/blog/install-and-test-varnish-in-5-steps

How can I cache headers with varnish 4?


Simple regular expression in gsub

Question: I have a little problem. I have "some text 23%", but I need "some text ; 23%", so I tried replacing " " for " ; ".
I tried something like this:
<code>"some text 23%".gsub /(\d+)%/, "; \0"
</code>
Problem is in response, in console it is ok, but when I use it in script I have:
<code>"some text ; ^@"
</code>
And I don't know what do with ^@ for have good value.
Thanks for help!
Comment: What version of ruby are you using?
Answer: The following should work:
<code>"some text 23%".gsub(/(\d+)%/, "; \\1%")
</code>
You can find more information about making back references to the captures in the ruby documentation: http://ruby-doc.org/core-1.9.3/String.html#method-i-gsub
Comment: Thanks Luke, but $1 is empty ; /
Comment: Hi vayneyks, I've updated the answer and checked it on ruby-1.9.3 (from a script)
Comment: I have one more question

In my project I need put regexp and value to change in file. I try get in from .txt file, but it don't work - it is string, and when I convert it to regexp I have problem with polish words, and see '\u0142' instead 'ł'. This is realy important for me ; / Can anybody help me?

Simple regular expression in gsub


How to work with zero dates ("0000-00-00") in Hibernate?

Question: I have MySql table that has a date field with zeroes ("0000-00-00") as its default value (field cannot be null, I can't change table structure). Hibernate doesn't like zero dates and throws exception during read or save.
I managed to make it read records by setting MySql connection setting "zeroDateTimeBehavior=convertToNull" that converts zero dates to nulls while retrieving records. It is all working fine until I try to save the record that has null date - it throws exception that date cannot be null.
So the question is - how to save record through Hibernate so date will appear as zeroes in a table?
Thanks.
Comment: Why do you want to handle them, anyway?  Zero date--get out there and celebrate Jesus' birthday!  Why are you in front of your computer on such a momentous occasion!
Comment: Year zero is nonexistent in the Julian and Gregorian calendar -- it jumps straight from 1 BC to 1 AD.  I can't really blame Hibernate for this one.
Comment: And a zero month and day number is not allowed anyway, even if the year was valid.
Answer: I'd try to add an Hibernate Interceptor (API, Doc) and try to implement something in the onSave() method.
The following code may work:
<code>static final Date ZERO_DATE = //0000-00-00

public boolean onSave(Object entity,
                  Serializable id,
                  Object[] state,
                  String[] propertyNames,
                  Type[] types)
           throws CallbackException {
    for(int i = 0; i< propertyNames.length; i++) {
        if(propertyNames[i].equals("dateFieldName") && state[i]==null) {
            state[i] = ZERO_DATE;
            return; //or may continue, if there are several such fields.
        }
    }
}
</code>
Comment: But what exactly is ZERO_DATE?
Comment: The java represntation of a date field with just zeroes.
Comment: Can you give an example how it looks? There is no such thing in java as date with all zeroes, that's why there is a problem with zero dates.
Comment: There is no such thing *anywhere* as a date with all zeroes. That thing in MySQL is not a date value.
Answer: Ready and working solution for DATE '0000-00-00' and TIME '00:00:00': How to map MySQL DATE '0000-00-00' & TIME '00:00:00' with Hibernate
Thanks Preston for the code and ChssPly76 for useful comments.


How to practice guitar improvisation?

Question: How to practice improvisation on guitar? How did you learn improvisation?
What should I practice, how should I practice? I want to lift my guitar playing to a new level, because I'm little bored of learning songs.
I've tried to play to backing tracks or did something like this, but the results were worse than horrible.
Comment: Join a band where everybody is a better player than you. That's 'think on your feet 101'.
Comment: I'm curious to know what was horrible about playing to the backing tracks, since that would be my strong suggestion.
Comment: It's actually how I learned as a kid, two bands in a row where I was actually the worst player - by just enough to keep up, but learn a lot in a short time. I then supplemented that with a studio session as a hired vocalist [with no real clue] on an actual record! which pretty much taught me 'how to sing' in a *mere* 12 hour session.  [I never claimed it was easy, but by hell you learn fast or you leave, pick a window ;)
Comment: @TheChaz2.0 - Boredom, no challenge, the luxury of being able to stop [or play badly with no fear of reprisal] whenever you like, repetitive structures, same each time... no audience applause at the end, or bottles if you were lousy...
Comment: @Tetsujin - easily said, hardly done! Can't think why a band might want someone who is a lesser player to join. Unless it massaged someone's ego!
Comment: Sparingly.  There's an audience for well-known songs, well played.  Even a bit of a one for new, original songs.  But the world is not terribly interested in hearing guitarists play scales over chord changes.
Answer: Learn which notes go best with which other notes. The best way is to understand and learn scales. They are the starting point of most tunes. Not just played as notes up and down as in actual scales, but to be able to mix and match.
A safe place to start is pentatonic. With five notes, and the other two iffy ones removed, just about everything played will start to sound reasonable. Get used to the major and minor pents.
Bear in mind that the two factors in improv. are the right notes and the right timing. But there is also a third: dynamics. Playing all notes at the same volume gets very boring very quickly. Imagine someone talking. Interest is kept partly by dynamics.
Talking about talking - a lot of music can be explained in conversation form. Question and answer if you like. A way in to this would be to actually have a conversation with someone, and, keeping the sentences each of you use short, straight after each, play what was said on your guitar. The rhythm is already there, just provide some notes! It's not easy initially, but anything worth while is like that.
Be very aware of what key you're in, and what chords and harmony are likely to occur in that key. For example, in key C, playing the notes D E F in a bar will fit far better over a Dm or G7 chord than over C or Am. But only by experimenting will you make sense of this side of improve. It can be done theoretically, but is much more effectively done practically. And, yes, there will be times when you can fit D E F over a C chord. I say to students: for now, only those 5 pent notes will work, but eventually, any note, any time, anywhere - you'll play and it'll sound good.
Work through different scales, modes, and eventually you'll arrive at the ultimate - all 12 notes of the chromatic scale, which can all be used in any key - once you know how!
Answer: Instead of learning songs, learn styles. Pay attention to what rhythmic patterns, scales and tonalities, inflections, and timbres/effects work in each of a number of styles that you like, paying attention to what things 'just work' in general, and what things only work in certain styles.
Listen carefully to masters of these genres (or if they are too intimidating, just to people who are quite good). Imitate what they do. If you get it right, great. If not, hey - you're just 'making your own style'.
Know the layout of your instrument so well that you can play a tune on it as easily as singing it.
If you have time, make your own backing tracks - it will force you to understand the genres you're interested in even better, and how all the instrumental parts work together, which will help your improvisation a lot.
Answer: If you are not ready to practice to a backing track, then I recommend practicing scales first. Practice to a metronome - start at a slow speed that you are comfortable with and work your way up. It is customary to learn the pentatonic scale first. If you play blues or rock music, you'll most likely spend most of your days improvising there. Once you become comfortable with the first position, start practicing the others.
A word of caution: many guitar players find themselves confined to the Pentatonic scale later if they cannot play they the others. On that note, although it may be overwhelming, I recommend that you practice the modes of the major scale, i.e. Ionian, Dorian, Phrygian, Lydian, etc. This is not vital, especially if your are a beginner, however, improvising in them will make your solos sound more interesting later on.
Once you become somewhat comfortable with the Pentatonic scale, as others have suggested, practice to backing tracks online. If you think it sounds bad, don't worry, you will get better with time. Learning guitar can be frustrating, so if you get discouraged, take a break for awhile and return to your practice with a clear mind.
As a last suggestion, listen to other guitar players. If it helps, learn some solos note for note so that you can glean licks to incorporate into your own playing. When I started doing this, I was listening to very fast and difficult solos; I got the false impression that speed is everything and that playing solos is all about skill. But, just remember that a few tasteful notes can sound better than a blur of scales. Pay attention to what the instruments around you are playing and keep in mind that using every tool in your arsenal right out of the gate is a waste, and leaves you nowhere to go. Your solo should build on itself; this is what intrigues your audience.
After awhile, you will begin to develop your own style and improvising will be no sweat :)
Best of luck!
Answer: You'll never be happy with your soloing if you just place notes over chords.  Music is a cultural art form.  You need to immerse yourself in a culture.
Learning to solo well, take your playing to "the next level" requires learning to speak the language of music.  Theory, while awesome, is the grammar of music but knowing the rules of grammar will not help you write a novel (it will help you write a novel with good grammar).
Transcribe!
You didn't state how you learn songs, sheet music, by ear, etc.  If by ear then the following exercise might work well.
Start listening to improvisational musicians.  Don't just learn your favorite some from a band as most bands play it the same way every time.  Zep is a good example of a band that pushed the limit of improv in rock.  Don't just listen to recorded versions of songs, listen to all the live versions, bootlegs if you can get a copy.  In Jazz this is easy because the name of the game is change.  For example, want to learn Groovin' High by Dizzy Gillespie don't just get the lead sheet and put chord tones over the chords (you will hate playing).  Get your hands on a dozen recorded live versions of the tune with great players and start transcribing their solos.  This will introduce you to musical vocabulary.
Each song has mood or feel, not just a lost of chords and notes.  It is always a good idea to learn about the song, what was the composer's intent.
At the end of the day there are simple rules to music like this or that mode fits over this or that chord but music is an expressive art form and all the rules won't make you creative.
Playing with others is very important since part of improve is communicating with others, being a good listener while you're playing (not a natural thing at first).  But it would be nice to have some vocabulary before jumping into an open stage night.
Take a different tack to learning and keep up with the backing tracks.
Answer: So the easiest would just be to look up "backing track" on youtube. Because it tells you what scale they're playing in. Not sure why you said it was a disaster. All you do is either play the notes of the scale (ie lead guitar) or the chords of the scale (ie rythm guitar). but you do both of these from the scale. that's why if you don't know how to play scales and find diatonic chords from scales then you need to practice.
The next step up would be to try to jam with any song you hear on youtube. The way to go about this is to first figure out the scale. Here's a method I've found useful: as the song plays, just randomly pick notes on the guitar, the ones that don't sound good are not in the key. the notes that you have left are in the key. next figure out if this is a major or minor key, and what the tonic is. if you have no idea what I'm talking about or how to do what I'm saying then you need to practice a bit more theory.
Third, try to find someone to jam with you. You can take turns where one of you picks a chord progression, then the other solos on top of it. Both would be in the same scale.
Which leads me to say that the basis of most improvisation is just picking a chord progression and soloing on top of it. Soloing in its basic form just means you're randomly picking notes from the scale. Now making this sound good just takes practice. Also look on google for "chord progression generator" here's one: http://chordchord.com/ ... the I is your key and scale. just jam on top of that.
p.s One last thing is try to find songs by ear. ie look up "how to play by ear" on guitar. It'll make you better at finding the tone that's in your head. It's hard to improvise if you can't play what's in your mind out your fingers.
Answer: There is something called melodic patterns that a person can study after they've got a good handle on the basic scales. My own experience had me practicing these patterns for a while and then I noticed when I'd listen to music I could hear in my mind the places where I could insert a particular pattern to compliment what was already happening musically. There are a ton of these melodic patterns already worked out, so all you need to do is look for them and work on them. After a while you may even start building your own patterns. At that point you'll truly be improvising.
Answer: you should develop a dictionary of phrases through your music life, every style has its conventional and novel musical phrases and some patterns are taken from old music of violin and flute (ostinanto with open strings, for example, thirds and octaves are played on anything for centures), some from old rocknroll or the vocal lines... musical education including knowledge of scales, chords, sequences, memorization techniques and analysis, ear training including perfect pitch, ability to write music in conventional music terms,  harmony, picking, tapping on guitar, harmonics, legato techniques, various articulation, precise intonation, bends...  When you have these in your mind and hands you can absorb music a proper effective way and develop and grow as a good player. Play what you think sounds good enough to be replayed, most pop music is primitive to learn on it, JS Bach and sons wrote a better musical entertainment and tutorials for us, in my opinion. I like how Gary Moore and SRV played Jimmy Hendrix songs and added their own style, energy and phrases, for example...Lenny Tristano was a good jazz pianist, John Coltrane was one to play sax a strange novel way...to name a few good names..
Comment: "Ear training including perfect pitch..." -- you aren't going to learn perfect pitch (unless you are still very young), but you can learn _relative pitch_ at any age, which is more useful anyway.
Comment: I have seen people who have learned it training, that ability does not guarantee that you`ll be a star and a good player, world-class level concert violinists and pro singers have these almost all (in the range of their instrument) and however many do mistakes on Auralia testing software, and perfect pitch is not always perfect to recognize 100% of sound coming  to your ears, if you can score 50% with software testing your are not pitch deaf, and there are no published studies of the perfect pitch testing of rich musicians...
Comment: That is completely wrong. Most musicians, world-class or otherwise, do _not_ have perfect pitch. Most good musicians have good _relative_ pitch. Perfect pitch is extremely rare, and those with perfect pitch don't really make mistakes in identifying pitches. How often to you make a mistake when you look at something red, thinking that it is blue instead?
Comment: all people do mistakes, Mozart was a human, not an angel. His dad Leopold taught him all knowledge including ear training, we all able to do what we have learned. Once I showed at the local music store how I can tune a guitar exactly in pitch without a tuner and a reference tone, then we have checked with a tuner. I never brag with skills I have learned. I can hear tones of a range I play, not all orchestral instruments including bubens and koyotes howls in nature. You can call me tone deaf, it is OK. I am not a  pro musician. Оne having a good memory learns a perfect sound pitch in any tuning
Comment: @DavidBowling, pitch memory can be acquired later in life. Studies show that environmental factors contribute to perfect pitch, which might suggest that perfect pitch is acquired at a young age. For example, in countries with tonal languages (like China), perfect pitch is much more common.
Comment: @jdjazz -- to the question of "how to practice guitar improvisation" this answer suggests, among other things: "musical education... including perfect pitch." This is utter nonsense. Yes, there are suggestions that the _propensity_ to develop perfect pitch can be fostered at around the same time that children are able to acquire languages with ease, but nobody _learns_ perfect pitch (which is not the same thing as the ability to remember a few pitches) later in life.
Comment: @DavidBowling, possibly relevant: http://news.uchicago.edu/story/acquiring-perfect-pitch-may-be-possible-some-adults
Comment: @jdjazz -- "However, the current set of studies cannot directly address whether this adult-acquired absolute pitch ability is comparable to the performance of "true" perfect pitch."
Comment: @DavidBowling, that statement is simply saying that they don't know whether the underlying mechanisms are the same (e.g., in the brain). The musical skill (the ability to identify absolute pitch) is the same.
Comment: @jdjazz -- I disagree. [The ability to identify a few absolute pitches is not the same thing as perfect pitch](https://www.youtube.com/watch?v=TgFdics3uKo).
Comment: Does the study mention identifying "a few" absolute pitches? "For the training portion of the experiment, participants listened to and classified 180 piano notes—in three, 60-note blocks—and then received immediate feedback on whether they had selected the correct label for the note. They then heard the note again. Participants showed significant improvements in note identification after the training." The point is that the skill of identifying absolute pitches was learned in a short time by people who didn't previously have that skill, not that they achieved 100% accuracy.
Comment: The video is 100% anecdotal, and the scientific claims have no citations. His formal education is in music, but in the video he makes incredibly broad scientific and neurological claims without offering any justification. Also, parts of the video emphasize that absolute pitch relies on acquired knowledge (music theory): "[Father:] When you hear these really complex chords... you recognize them because you know some of the theory behind it, right? [Son:] Yep."
Comment: @jdjazz -- I have never met anyone who actually _learned_ perfect pitch. The description of the training you mention in the experiment doesn't sound like perfect pitch to me. I have met plenty of people who can identify some pitches absolutely, on the instrument that they play all the time, and I can do this too, but I don't have perfect pitch. Yet we have gone far from the point of my original comment, which was that this answer suggests to a learner that they should _learn perfect pitch_ as part of their musical training in learning how to improvise.
Comment: @jdjazz -- This is an irresponsible statement. The learner is not going to learn to have perfect pitch, and there is no point anyway. While more professional musicians have perfect pitch than members of the general public, it is not true, as OP claimed in a comment, that all "world-class level concert violinists and pro singers" have perfect pitch. Good relative pitch is much more important. It is irresponsible, and wrong, to feed the public fascination with perfect pitch by suggesting that serious musicians should _learn perfect pitch._
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/78694/discussion-between-jdjazz-and-david-bowling).
Answer: Chordbot is an android app that helps you build chord progressions. It will then play the progressions. You control the tempo and they supply a number of strumming or picking styles to choose from. You could then jam to a chord progression of your choice at whatever speed is comfortable. Or, you could get yourself a looper and play the chord progression yourself and then improvise over it.
Answer: me I found some guitar riff on guitar pro software, I made it play in loop, and I improvised guitar solos on it, trying to use key tones or modes. The application chord tracker work well too, it play songs indicate the chord which is playing and you can make a part of the song play in loop and improvise with your guitar. If you don't know how to improvise I suggest you to use either key tones or modes, it can make good solos, take a course with a guitar teacher for that.
Answer: In addition to skinny peacock's answer I think the actual answer is theft. Every other answer here would force you to someone invent great solos out of thin air. Absurd. Steal them ... exactly as every great musician has.
You learn the solos you like, you analyze them a bit, you pick out little phrases and 'melodic patterns' and you create a palette of your own patterns.
Do you want to play melodic solos?
Steal Elliot Easton, Gilmore, Ian Bairnson (Alan Parsons, Pilot), Joe Walsh, Knopfler, Brad Delp, Larry Carlton ... Brian May, Steely Dan solos like on Kid Charlamane... etc.

How to practice guitar improvisation?


Trying to update taxonomy menu item with hook_taxonomy_menu_update

Question: I'm having issues getting this to function to work, if I understand correctly this hook fires after saving or creating a taxonomy term.
I am also unable to use dpm($item) as nothing is rendered
<code>function form_alter_taxonomy_menu_update(&$item) {
    $item['options']['attributes']['class'] = 'myClass';
    return $item;
}
</code>
Can anyone spot what I have done wrong
Answer: If you're just adding a class, I wouldn't rely on a hook from the taxonomy menu contributed module at all. Do it at the theme level like this.
Comment: Thanks.I need to make the class the value of a field from my term, is this still possible with the method you are suggesting?
Comment: You could use Views to generate the menu instead of taxonomy menu, then use replacement patterns to put the value of a field within the class.
Comment: Yeh I've wondered this, just I have never built a hierarchical structure before, I guess now is the time to learn!
Comment: You might be interested in this too: https://www.drupal.org/node/988694


Looking for correct distribution for modelling foosball scoring

Question: I'm trying to adapt something like this association football prediction approach to 2v2 foosball games at our office.
For football, they basically have an offense score and a defense score for each time. The game is a fixed length of time. They then use Poisson regression based on the scoring history to try to find out each team's offensive/defensive values.
The problem is different for foosball, and I think Poisson may not be the correct distribution to use. For the following reasons:

We play first to 10 points, not for a fixed length of time
Players switch positions after their team scores 5 points

Can anyone recommend a better distribution or a way of approaching the problem? We don't need a 100% optimal solution, but we are aiming for something that is reasonably ok.
Bonus points for ideas on how to split the offense/defense ratings among the players.
Comment: [Here](http://stats.stackexchange.com/questions/15776/measuring-individual-player-effectiveness-in-2-player-per-team-sports/) is a *very* similar recent question.
Comment: When thinking about the other question, I sketched out a scheme for a model of playing to a set number of points, but I never posted it to that question. I ended up with a *curved* exponential family, which had some similarities to a generalized linear model. If you would like to see that, I can try to dig out those notes and post it.
Comment: What do you mean by "switch positions"?
Comment: On trying to find a distribution - if all games are complete, obviously the winning score is 10; the distribution is on the losing score (and you'd also need to model the probability of winning of course). For that it seems to me a quasi-binomial GLM would be an obvious first choice, though perhaps something like a beta-binomial model might do if you have the resources to pursue it.
Answer: Here is an explanation of how Elo rankings are used in an actual foosball league. It goes into quite a lot of depth.
Comment: The Elo rating system is named after Arpad Elo, and therefore isn't capitalized all the way through.


SQL Injection ou Script injection - MVC-5 - É uma preocupação?

Question: Estou desenvolvendo um aplicativo em MVC-5 e li várias matérias sobre SQL Injection.
Gostaria de saber se tenho que tomar qualquer medida de segurança ou modificar meus comandos selects, ou se na verdade o MVC-5 já dispões de blindagem contra esta situação.
Em todo o meu projeto estou utilizando o formato abaixo para selecionar dados das minhas tabelas:
string query = "SELECT * FROM TABELA WHERE CHAVE = '"+CH+"'";
            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
            using (var command = new SqlCommand(query, connection))
            {
                connection.Open();
                using (var reader = command.ExecuteReader())

Comment: Esse código não tem nada de ASP.Net MVC. Mas ele está totalmente suscetível a injeção de qualquer coisa. Acho que a pergunta é bem ampla e precisaria de mais foco. Se usar o MVC corretamente, se usar o ADO.Net ou EF ou outro mecanismo de acesso de forma correta, aí não terá problemas de SQL Injection. Script injection depende de outros fatores. Veja se acha alguma coisa útil. http://pt.stackoverflow.com/search?q=sql+injection Mas aconselho fazer um estudo mais estruturado sobre desenvolvimento de software como um todo.
Comment: StoredProcedure?? O Ado.net tem a feature há anos de AddParameter que já resolve esse problema de sql injection.
Comment: Acredito que um meio de prevenir é usando stored procedures ou ORMs (com baixa performance em comparação a stored procedure).
Answer: Acho que está acontecendo uma confusão entre as tecnologias.
ASP.NET MVC é um framework para WEB, como tal ele é capaz de proteger contra:

HTML Injection, quando alguém coloca tags HTML em um campo de texto por exemplo.
Script Injection, quando alguém coloca um tag script em um campo de texto por exemplo.

Para esses dois, a validação é dupla, ele não deixa entrar esse tipo de string, mas se você forçar ele a permitir ele fará HTML Encoding quando for mostrar na tela para garantir que esses tags apareçam em texto plano e não HTML, tornando-os inofencivos.
Ele ainda tem proteção contra cross-scripting, usando um ValidationToken.
Tudo isso tem a ver com uma interface WEB, que é o que o MVC é.
Já SQL Injection, quem pode te prover uma segurança já pronta é o Entity Framework. É muito recomendável usá-lo. Ele vai sanitarizar qualquer valor antes de colocar numa query. Inclusive você não precisa mais fazer querys, apenas usar lambda expressions.
Seu exemplo ficaria: var dado = db.Tabela.Where(x=> x.Chave == CH).SingleOrDefault();
Ele vai limpar o valor de CH para evitar caracteres considerados perigosos como comentários SQL, aspas simples e etc...
Mas existem muitas formas de se proteger, no entanto, a maioria não é "pré-pronta".
Espero que ajude...
Answer: Ao invés de concatenar strings para formar sua query.
utilize Parameters.Add do SqlCommand para previnir Sql Injection.
Segue exemplo abaixo aplicado ao seu código:
string query = "SELECT * FROM TABELA WHERE CHAVE = @CH";

using (var command = new SqlCommand(query, connection))
{
    SqlParameter param  = new SqlParameter();
    param.ParameterName = "@CH";
    param.Value         = CH;

    command.Parameters.Add(param);

    connection.Open();

    using (var reader = command.ExecuteReader())


How to convert UTC+0 Date to PST Date?

Question: I have this UTC+0 Date :
2011-11-28T07:21:41.000Z

and I'd like, on C#, convert it to a PST Date. How can I do it? Tried with :
object.Data.ToLocalTime()

but I can't get the correct value (which should be 2011-11-27)
EDIT
Also tried (after suggesion on another topic) this :
DateTime convertedDate = DateTime.SpecifyKind(
    DateTime.Parse(object.Data.ToShortDateString()),
    DateTimeKind.Utc);

DateTime dt = convertedDate.ToLocalTime();
string dataVideo = dt.ToShortDateString();

but the date still 28/11/2011, not 27/11/2011
Comment: Check this question: http://stackoverflow.com/questions/179940/c-sharp-convert-utc-gmt-time-to-local-time
Comment: Tried some strategies, such as `DateTime.Parse(object.Data.ToShortDateString()).ToLocalTime()` but nothing happens...
Comment: I don't see a failure mode but one: check that your machine is actually in the PST timezone.  Document the time you get, not just the date.
Comment: So, what Time Zone is set on your computer? The suggested by @Stijn solution should work.
Answer: I've changed my clock to use UTC-08:00 Pacific Time.
DateTime timestamp = DateTime.Parse("2011-11-28T07:21:41.000Z");
Console.WriteLine("UTC: " + timestamp.ToUniversalTime());
Console.WriteLine("PST: " + timestamp.ToLocalTime());

Output:
UTC: 28/11/2011 7:21:41
PST: 27/11/2011 23:21:41

Example with TimeZoneInfo
DateTime timestamp = DateTime.Parse("2011-11-28T07:21:41.000Z");
Console.WriteLine("UTC: " + timestamp.ToUniversalTime());
Console.WriteLine("GMT+1: " + timestamp.ToLocalTime());
Console.WriteLine("PST: " + TimeZoneInfo.ConvertTimeBySystemTimeZoneId(timestamp, "Pacific Standard Time"));

Output:
UTC: 28/11/2011 7:21:41
GMT+1: 28/11/2011 8:21:41
PST: 27/11/2011 23:21:41

Comment: @markzzz yes, you need to use TimeZoneInfo class, but it's only available int .NET 3.5+.
Comment: Nevermind dropping the Z. I've updated the answer. PST is UTC-08:00 as far as I can see, not UTC-12:00 ?
Comment: First, I can't drop the Z (I won't to get a string replace on a Date, that's horrible). Second, no it doesnt do the trick : the date still 28/11/2011, which, on PST, is 27/11/2011 (12 hour before).
Comment: :O! But I need to print that value without change clock of my computer :) Is there a method to convert a certain date in UTC (my date) to PST date?. Yeah, sorry, is UTC-08:00, UTC-12:00 should be PDT...
Comment: Yes, I have .NET 3.5. How can I do it with TimeZoneInfo? Can you give to me an example?
Comment: More info can be found in the link below. Using local time won't work well if the application is hosted on a server outside of the intended time zone. https://learn.microsoft.com/en-us/dotnet/standard/datetime/converting-between-time-zones
Answer: For a little more color
2011-11-28T07:21:41.000Z
This is a ISO8601 Timestamp, the Z at the end means UTC time.  This represents a specific instant in time.
DateTime.Parse will return to you a local date time structure, there are three types of datetime kinds, UTC, Local, and Unspecified.
If you try displaying this, it will show you this instant in your computers current timezone (I'm eastern time so when I print it I get 11/28/2011 2:21:41 AM).
If I want to switch this DateTime Kind to UTC, I could do something like
DateTime.Parse("2011-11-28T07:21:41.000Z").ToUniversalTime()
Printing this now (since it's kind is now UTC) I get 11/28/2011 7:21:41 AM.
Note that although the time is printed differently both these date times are referring to the same instant in time.
To display this instant in a different timezone, the easiest way imo is the TimeZoneInfo class (though I'm not sure it's 100% accurate).
TimeZoneInfo.ConverTimeBySystemTimeZoneId(dateTime, "Pacific Standard Time").
Printing it now will yield your desired result 11/27/2011 11:21:41 PM
Note that this return DateTime's Kind property is now Unspecified, meaning you won't be able to transfer it back to UTC without more information.  You no longer have a specific instant in time, rather you have a unspecified time..we know it's the same instant as the ones previously just in pacific time, but the computer no longer knows that.  Keep that in mind if you want to store this time.

How to convert UTC+0 Date to PST Date?


Rendering Transparent Blocks in OpenGL

Question: I'm rendering 3D terrain with cubes and I need to render water transparently.
My solution for this, after some research, was to separate the water cubes into one buffer and the solid blocks into the other buffer, then in my fragment shader, I'm using:
uniform float transparency;

in my rendering code:
shader.setFloat("transparency", 1.0f);
glBindVertexArray(solidVAO);
glDrawArrays(GL_TRIANGLES, 0, solidPoints.size());

shader.setFloat("transparency", 0.3f);
glBindVertexArray(transparentVAO);
glDrawArrays(GL_TRIANGLES, 0, transparentPoints.size());

and then in my Fragment Shader
out vec4 FragColor;

in vec2 TexCoord;

// texture sampler
uniform sampler2D atlas;
uniform float transparency;

void main()
{
    FragColor = texture(atlas, TexCoord);
    FragColor.w = transparency;
}

However, the water is still solid, is there a better approach to drawing transparent shapes in front of solids? Or, what is going wrong here?
Answer: You need to set blending mode for the transparent shape as well:
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

Rendering Transparent Blocks in OpenGL


Why does playing the piano give me a pain in the neck?

Question: I have a keyboard set up with a proper stool so my arms are held straight out, with music at eye level - almost identical to how I set up my PC for good posture.
But while I can use the PC all day with no issues, within 5 minutes of playing the keyboard - I'm just starting - I get stiffness pain at the bottom of my neck, probably one vertebra above the shoulders.
Can anyone advise what is causing this and how to adjust? I think my main posture can't be too bad - I'm not hunching or craning my neck - but wondered if perhaps I am 'clenching' somehow?
Answer: I'm a violinist, not a pianist, but it's very common for beginning violin players to have severe pain because they are too tense, especially when they are self taught.  I'm going to suggest a few generic techniques to start minimizing tension.

When you sit down at the piano, think about how you are sitting.
Look for any tension, especially in your neck and shoulders. Close
your eyes, and take a few deep, slow breaths to help you relax.
Play a note. Not a piece, or even a scale, just a single note.
Think about how relaxed you feel playing that note. Think about
tension in your back and shoulders. If you find any, slow down again
and relax. Now try two notes, or maybe even three or four. But still
think about relaxing, not about music. This is what your body should
feel like all the time when you play.
Now you've got a baseline for how you should feel while playing.
So play something simple. Either a short tune you know well, or a
scale, or whatever you find easy. Halfway through, stop and think
about tension. Did you tense up again? If you did, sit back, relax,
and start over, slower. Slowing down makes it easier to play, and
easier to think about not getting tense.
Another exercise is to practice breathing while playing. A lot of
beginners tend to hold their breathe, which just adds stress and
tension. So play a scale. Depending on your speed, you may want to
breathe in going up, and out going down, or breathe in for 4 notes,
out for 4 notes. Just practice breathing in rhythm, and being aware
of your breathe. When you are playing music, start thinking about
when you breathe in general. Breathing exercises aren't just for
singers.

In summary: Consciously relax before playing, and check for tension as you play. If you get tense, back off, relax, and slow down. Make sure you breathe.
If the tension is caused more by your posture, you may need to find a teacher to help you out, since we can't see how you hold yourself over the net. A teacher could also help with the sort of tension issues I'm talking about here, so if lessons are an option, it would probably be worthwhile, even if only for a short time.
Comment: Thanks. I have a teacher and she hasn't complained about posture so I figure tensing up is most likely, particularly the stress of trying to get a phrase right after the Nth attempt :)
Comment: +1 for 'teacher' - every time. We all (well, most of us...) tense up when doing something new/stressful/tricky, and a good teacher should spot this pretty quickly, and offer an antidote or two.


All DFT of binary numbers subsets of prime length are nonzero

Question: Let $p$ be a prime. Consider a sequence $S$ of $p$ binary numbers $x_n \in \{ 0, 1 \}$, i.e. $S = \{x_1, x_2, \cdots, x_p\}$, where the number of zeroes in $S$ is neither $0$ nor $p$.  Then the conjecture is: for all such sequences, all discrete fourier transformation (DFT) components $\hat S_k$ of $S$ are nonzero. That is, show that,  $\forall k = 1\cdots p$, one obtains $\hat S_k = \sum_{n=1}^p x_n \exp (2 \pi i \frac{ n k }{p}) \ne 0$.
A way to the solution might be the visualization that a vectorial sum of $p$ evenly distributed spokes in a wheel (the unit circle) is performed, where only those spokes with $x_n = 1$ are existent, and where every $k$th spoke (modulo $p)$ is counted, and the vector sum will not disappear.
It is  clear that the conjecture only holds if $p$ is prime. Since if it weren't, write $p= q \cdot r$, and consider a sequence $S^q$ where every $q$th entry is $x_n = 1$ and all others are $0$. The DFT components $\hat S^q_k$ of  $S^q$  will then be  $$\hat S^q_k = \sum_{n=1}^p x_n \exp (2 \pi i\frac{ n k }{q r}) =  \sum_{n=1}^r \exp (2 \pi i \frac{ n q k }{q r})  =  \sum_{n=1}^r \exp (2 \pi i \frac{ n  k }{r})  =  0.$$
Comment: This may be using a *sledgehammer to crack a nut*, but "On Vanishing sums of roots of unity" by Lam and Leung gives your desired result as a special case of their main result.
Answer: This DFT $\hat S_k$ equals $f(\zeta_k)$, where $f(t) = x_p + \sum_{n=1}^{p-1} x_n t^n$ is a polynomial with integer coefficients and $\zeta_k = \exp(2\pi i k/p)$ is a primitive $p$th root of unity (since $p$ is prime). The only way $f(\zeta_k)$ could equal $0$ is if $f(t)$ is a multiple of the minimal polynomial of $\zeta_k$, which is $1+t+t^2+\cdots+t^{p-1}$. There are only two cases where this happens, namely $x_1=\cdots=x_p=0$ and  $x_1=\cdots=x_p=1$; this finishes the proof.
(Proof that $\zeta_k$ is a primitive $p$th root of unity: it is a $p$th root of unity since $\zeta_k^p = \exp(2\pi i k/p)^p = \exp(2\pi i k p/p) = \exp(2\pi i k) = 1$, but for any $1\le m\le p-1$ we have $\zeta_k^m = \exp(2\pi i k/p)^m = \exp(2\pi i k m/p) \ne 1$ since $km$ is not a multiple of $p$.)
Comment: Thanks Greg. I was just wondering whether this needs another step. You write: "$\zeta_k = \exp(2\pi i k/p)$ is a primitive $p$th root of unity". For this to hold for *all* $k$, one needs to show that $p$ must be prime (or is that obvious by other means?). For if $p$ were not prime, then for some $k$, a minimal polynomial of $\zeta_k$ with smaller degree than $p-1$ could be constructed, and then the rest of the proof would not hold.
Comment: don't you yourself say $p$ is prime in your question?
Comment: @kodlu Yes the question states that $p$ is prime. The statement which needs to be proven is: "For $p$ prime, and for all $k$, $\zeta_k = \exp(2\pi i k/p)$ is a primitive $p$th root of unity." It is already clear that this does not hold if $p$ is not prime. However, that doesn't prove the positive statement that it holds if $p$ is prime.
Comment: Dear Greg, to complete the question: Do you have a proof for the statement: " For $p$ prime, and for all $k$,  $\zeta_k = \exp(2\pi i k/p)$ is a primitive $p$th root of unity."  ?
Comment: I encourage you to review the definition of "primitive $p$th root of unity" and verify it directly by calculating the powers of $\zeta_k$.
Comment: There is a little bit more to do than just calculating the powers. I found a proof here: https://math.stackexchange.com/a/101123/317854


Why does intrinsic euler angle rotation not equal extrinsic rotation?

Question: I am trying to implement a Rotation matrix showing that intrinsic rotations equal extrinsic rotations, with a simple reordering of matrix arguments and angles.
From wikipedia, "Any extrinsic rotation is equivalent to an intrinsic rotation by the same angles but with inverted order of elemental rotations, and vice versa."
Let $Rx$,$Ry$,$Rz$ be the common Rotation matrices given in the literature and wiki link.
Let $\alpha$, $\beta$,$\gamma$ be the angles by which the Rotations are rotated about the axes.
Suppose I use a Z-X-Z extrinsic convention.
Then I have $R$ = $Rz(\gamma$)$Rx(\beta$)$Rz(\alpha$). Physically, this means I Rotate an object in the order,starting from the rightmost angle to the left and get a resulting Rotation matrix, $R$.
If I then use a z-x'-z'' intrinsic convention, I would swap angles and get $R$ =$Rz(\alpha$)$Rx(\beta$)$Rz(\gamma$). Meaning, on the intrinsic (movable) axis, I start rotating by the $\gamma$ angle about the $Zaxis$ and continue to the left.
My understanding is both Rotations should be mathematically equivalent.
Yet when I try to use concrete values like ($\alpha$,$\beta$,$\gamma$) = (45,30,15) degrees, respectively, I get two different answers depending on the method.
Running the models in R I get for
Extrinsic:
<code>> round(Rz(D2R(angles[3]))%*%Rx(D2R(angles[2]))%*%Rz(D2R(angles[1])),4)
>       [,1]    [,2]    [,3]
> [1,] 0.5245 -0.8415  0.1294
> [2,] 0.7745  0.4085 -0.4830
> [3,] 0.3536  0.3536  0.8660
</code>
Intrinsic:
<code>> round(Rz(D2R(angles[1]))%*%Rx(D2R(angles[2]))%*%Rz(D2R(angles[3])),4)
>       [,1]    [,2]    [,3]
> [1,] 0.5245 -0.7745  0.3536
> [2,] 0.8415  0.4085 -0.3536
> [3,] 0.1294  0.4830  0.8660
</code>
Note that the Rotations are not equivalent, but similar. If I transpose the Intrinsic result, they are even closer -- the absolute values are exact.
<code>> round(t(Rz(D2R(angles[1]))%*%Rx(D2R(angles[2]))%*%Rz(D2R(angles[3]))),4)
         [,1]    [,2]   [,3]
  [1,]  0.5245  0.8415 0.1294
  [2,] -0.7745  0.4085 0.4830
  [3,]  0.3536 -0.3536 0.8660
</code>
Even though the values are correct, now the signs are wrong.
If I lastly convert the angles to negative values, the answers line up perfectly.
<code>> round(t(Rz(D2R(-angles[1]))%*%Rx(D2R(-angles[2]))%*%Rz(D2R(-angles[3]))),4)
        [,1]    [,2]    [,3]
 [1,] 0.5245 -0.8415  0.1294
 [2,] 0.7745  0.4085 -0.4830
 [3,] 0.3536  0.3536  0.8660
</code>
So, concretely, the Rotation matrices will be equal if I equate
$Rz(\gamma$)$Rx(\beta$)$Rz(\alpha$) = ($Rz(-\alpha$)$Rx(-\beta$)$Rz(-\gamma$))$^T$
Extrinsic being the left side, and intrinsic being the right.
I've looked high and low in the literature and questions here, but i still don't understand why this is the case, and have not found any concrete examples that show this.
I have seen some examples showing to invert or transpose one frame to get the other, but nothing about negative angles.
Can someone explain why this is true?
*D2R in my code is just a function to convert degrees to radians.
edit. I should also add that I"m aware the negative angles alone imply clockwise (lefthand) rotation. I still don't get the equivalence of intrinsic to extrinsic though.
Answer: I think the reason you are having difficulty is because you do not know how to represent the $x'$ or $z''$ rotations in matrix notation.
A single rotation matrix takes a set of $(x,y,z)$ coordinates for one point $P$ in a particular fixed coordinate system and gives you a set of $(x,y,z)$ coordinates for a (usually different) point $P'$ in the same fixed coordinate system, namely the point $P'$ to which the rotation would move an object at point $P$.
In some applications the fixed coordinate system is called the "world" coordinates.
The rotation matrices you can obtain by plugging in various angles $\theta$ and $\phi$ in $R_x(\theta)$ and $R_z(\phi)$ will always represent rotations around the "world" $x$ and $z$ axes, never around the "body" axes $x'$ or $z''$ except in the cases where those axes happen to coincide with the world axes
(which happens when the previous intrinsic rotation angles are zero).
In order to perform a rotation around the $x'$ axis in general you need a way to perform a rotation around an arbitrary axis in the $x,y$ plane.
One way to do this is to rotate the arbitrary axis back onto the world $x$ axis (which you can do via an $R_z$ matrix), rotate things around the world $x$ axis (via an $R_x$ matrix), and then undo the first rotation (via another $R_z$ matrix).
You can multiply these matrices together to get a single matrix that represents the rotation around the desired axis, although the form of that matrix is (typically) not equal to any $R_x,$ $R_y,$ or $R_z$ matrix.
Likewise to rotate around the $z''$ axis, you can rotate the $z''$ axis back to the $z$ axis, perform your rotation there, and then undo the first rotation.
A more detailed explanation of this, showing how the complete matrix multiplication for the intrinsic rotations produces the same composed rotation matrix as the matrix multiplication for the extrinsic rotations, is given in this answer.

By the way, while you can get the inverse of a world-axis rotation by changing the sign of the angle (for example, from $R_z(\alpha)$ to $R_z(-\alpha)$),
you can also get an inverse of a rotation by transposing the rotation matrix.
That is,
$$ R_z(-\alpha) = R_z(\alpha)^T. $$
Now observe that
\begin{align}
(R_z(-\alpha)R_x(-\beta)R_z(-\gamma))^T
&= (R_z(-\gamma))^T (R_x(-\beta))^T (R_z(-\alpha))^T \\
&= R_z(\gamma)R_x(\beta)R_z(\alpha),
\end{align}
which is the identity formula you confirmed at the end of your question.


How do I change Jboss' logging directory

Question: I'm running jboss-as 7.2. I'm trying to configure all log files to go to /var/log/jboss-as but only the console log is going there. I'm using the init.d script provided with the package and it calls standalone.sh. I'm trying to avoid having to modify startup scripts.
I've tried adding JAVA_OPTS="-Djboss.server.log.dir=/var/log/jboss-as" to my /etc/jboss-as/jboss-as.conf file but the init.d script doesn't pass JAVA_OPTS to standalone.sh when it calls it.
The documentation also says I should be able to specify the path via XML with the following line in standalone.xml:
<path name="jboss.server.log.dir" path="/var/log/jboss-as"/>

However, it doesn't say where in the file to put that. Every place I try to put it causes JBoss to crash on startup saying that it can't parse the standalone.xml file correctly.
Answer: You can specify the path of your log files via the standalone.sh file. If you look at the org.jboss.as.logging subsystem, you will see the configuration there.


Creating 8-bit images

Question: I'm trying to create an 8-bit image with a solid background color. It seems like it should be pretty straight forward but the details on the file list it as 32-bit color depth. What am I missing?
    public void CreateImage()
    {
        var bmpOut = new Bitmap(300, 300);
        var g = Graphics.FromImage(bmpOut);
        g.FillRectangle(new SolidBrush(Color.Gray), 0, 0, 300, 300);

        var stream = new MemoryStream();
        bmpOut.Save(stream, GetPngCodecInfo(), GetEncoderParameters());

        bmpOut.Save(@"C:\image.png", GetPngCodecInfo(), GetEncoderParameters());
    }

    public EncoderParameters GetEncoderParameters()
    {
        var parameters = new EncoderParameters();
        parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 8);

        return parameters;
    }

    public ImageCodecInfo GetPngCodecInfo()
    {
        var encoders = ImageCodecInfo.GetImageEncoders();

        ImageCodecInfo codecInfo = null;

        foreach (var imageCodecInfo in encoders)
        {
            if (imageCodecInfo.FormatID != ImageFormat.Png.Guid)
                continue;

            codecInfo = imageCodecInfo;
            break;
        }

        return codecInfo;
    }

Comment: `"C:\image.png"` is potentially invalid path... assuming you have `@` in front of it (or just random string for sake of sample).
Comment: From what I can see, the thing you're missing is a color palette...
Answer: Use this constructor to specify a pixel format : http://msdn.microsoft.com/en-us/library/3z132tat.aspx
Since you cannot create a Graphics from an indexed pixel format, you can only write raw pixels  to a 8-bit image.
Bitmap bitmap = new Bitmap(32, 32, PixelFormat.Format8bppIndexed);
var bitmapData = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), ImageLockMode.ReadWrite, bitmap.PixelFormat);
Random random=new Random();
byte[] buffer=new byte[bitmap.Width*bitmap.Height];
random.NextBytes(buffer);
Marshal.Copy(buffer,0,bitmapData.Scan0,buffer.Length);
bitmap.UnlockBits(bitmapData);
bitmap.Save("test.bmp",ImageFormat.Bmp);

You can either use such code on WinForms : http://www.codeproject.com/Articles/17162/Fast-Color-Depth-Change-for-Bitmaps
Or if you can reference this class from WPF it will be much easier :
http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.formatconvertedbitmap(v=vs.85).aspx
Comment: Be careful, though. Specifying the pixel format alone will not be enough as creating an 8-bit indexed image will fail on the next line—creating a `Graphics` from the image.
Comment: What on earth is that `Random` doing there?
Comment: Creating a Graphics from an indexed format will raise an exception : A Graphics object cannot be created from an image that has an indexed pixel format.
Comment: @Nyerguds being used to create a random image, I supposed? As a matter of fact, I bumped into this answer looking for a way to visualize my random data
Comment: This answer doesn't actually answer the question, by the way. This does not in any way allow a user to determine how to select and paint a specific color. To do that, you need to edit the _color palette_. As far as I can see, the resulting random image from this just uses the colors of the default palette created with an 8-bit image.
Comment: @Aybe So at the end, how can we get the 8bit bitmap after creating a graphics?
Answer: You could also create the image at a higher bit rate and then convert it to 8 bits just before saving. This would allow you to use a Graphics context when creating the image. See this question for suggestions on how to convert to 8 bits:C# - How to convert an Image into an 8-bit color Image?
Answer:
ImageExtensions.cs
using System.Runtime.InteropServices;
using System.Linq;

using System.Drawing.Imaging;
using System.Drawing;
using System;

public static partial class ImageExtensions {
    public static ColorPalette ToGrayScale(this ColorPalette palette) {
        var entries=palette.Entries;

        for(var i=entries.Length; i-->0; entries[i]=entries[i].ToGrayScale())
            ;

        return palette;
    }

    public static Color ToGrayScale(this Color color, double[] luminance=null) {
        var list=(luminance??new[] { 0.2989, 0.5870, 0.1140 }).ToList();
        var channel=new[] { color.R, color.G, color.B };
        var c=(byte)Math.Round(list.Sum(x => x*channel[list.IndexOf(x)]));
        return Color.FromArgb(c, c, c);
    }

    public static Bitmap To8bppIndexed(this Bitmap original) {
        var rect=new Rectangle(Point.Empty, original.Size);
        var pixelFormat=PixelFormat.Format8bppIndexed;
        var destination=new Bitmap(rect.Width, rect.Height, pixelFormat);

        using(var source=original.Clone(rect, PixelFormat.Format32bppArgb)) {
            var destinationData=destination.LockBits(rect, ImageLockMode.WriteOnly, pixelFormat);
            var sourceData=source.LockBits(rect, ImageLockMode.ReadOnly, source.PixelFormat);

            var destinationSize=destinationData.Stride*destinationData.Height;
            var destinationBuffer=new byte[destinationSize];

            var sourceSize=sourceData.Stride*sourceData.Height;
            var sourceBuffer=new byte[sourceSize];

            Marshal.Copy(sourceData.Scan0, sourceBuffer, 0, sourceSize);
            source.UnlockBits(sourceData);

            destination.Palette=destination.Palette.ToGrayScale();
            var list=destination.Palette.Entries.ToList();

            for(var y=destination.Height; y-->0; ) {
                for(var x=destination.Width; x-->0; ) {
                    var pixelIndex=y*destination.Width+x;
                    var sourceIndex=4*pixelIndex;

                    var color=
                        Color.FromArgb(
                            sourceBuffer[0+sourceIndex],
                            sourceBuffer[1+sourceIndex],
                            sourceBuffer[2+sourceIndex],
                            sourceBuffer[3+sourceIndex]
                            ).ToGrayScale();

                    destinationBuffer[pixelIndex]=(byte)list.IndexOf(color);
                }
            }

            Marshal.Copy(destinationBuffer, 0, destinationData.Scan0, destinationSize);
            destination.UnlockBits(destinationData);
        }

        return destination;
    }
}

Call bmpOut=bmpOut.To8bppIndexed(); before you it save to file.
Comment: There is _no sense_ in converting a palette to grayscale for a new image. Just fill the palette with color values from 00,00,00 to FF,FF,FF. With a palette like that, you are 100% sure to have all gray values, and the 8-bit value to put on the final pixel is simply equal to any of the three color components of the actual grayscaled pixel colour. No more lookups needed.

Creating 8-bit images


Best Way to Capture/Log Transactions between MySQL and PHP on Ubuntu Server?

Question: Am running Ubuntu Server 12.04 on a VPS and supporting multiple websites running LAMP. One of the sites is configured for SSL and is running an application built using the Cake PHP framework. The administrative interface for the application interacts with the MySQL server (installed on the same server) and since we introduced SSL (https) into the mix, some forms aren't able to retrieve data from the MySQL database when users access them using https (these are drop downs the are pulling their lists from a table in the database). If one forgoes SSL and comes to the same URLs via http only, no issues. Nothing specific is showing up in the Apache or PHP logs.
My developers are suggesting that this is a server configuration issue. I'm not so sure.
I'm green regarding what's possible from a sniffing standpoint, but since I can easily replicate the use cases where we are not able to retrieve data, I would love to find a way to sniff the traffic to uncover why we can't retrieve the data from those forms.
What would be a way of getting the type of verbose logging that would show the request from the app and it's interaction with MySQL?
Answer: You can use the general query log in MySQL.
Answer: I'd take a guess and say that what you're either experiencing a Cross-Origin Request or a Mixed Content (secure/unsecure) problem.
Again, this is a guess because you haven't given enough detail, but if your forms dynamically load the dropdown information through AJAX, and if they have http:// hard coded in the AJAX URL (i.e. you loaded the page through https://yourdomain.com but the ajax is trying to load from http://yourdomain.com) then it's not going to work due to one of the problems I mentioned above.
The solution is to ensure that the AJAX calls use the same protocol as the original page load.  The easiest way to do that is to omit the protocol altogether (e.g. //yourdomain.com) when making the request.
Comment: Oz, this look promising and have passed your suggestion to our developers.


ReportViewer with DataTable don't applies DataView

Question: This is my first post here so please excuse me if I do something wrong.
My question is really simple but it's like I stand in front of a wall...i just try to filter the data of my DataTable that I have created in my DataSet. I use the DataSet to fill my .rdlc report, this works good.
But now I want to filter the data in the DataTable by the Date Column (in my SQL Express it is named Datum and a nchar(10) column, it's not the best idea and I should change it i know ;) ).
I found this thread and this very usefull site and created my samplecode in base of this two sites but the data isn't filtered. I think i could have forgot something...
Here is my code:
    private void Form1_Load(object sender, EventArgs e)
    {
        DataView dvDay = new DataView(this.dsStempelJoinsTests.dtJOIN);
        dvDay.RowFilter = "Datum = '12.03.2014'";
        this.dtJOINTableAdapter.Fill(this.dsStempelJoinsTests.dtJOIN);

        this.rvData.RefreshReport();
    }

The Data in my SQL Express is stored like this 31.02.2014. But my .rdlc report shows data from other dates.
Comment: I haven't used ADO.Net for a while but I guess you need to Fill the adapter view the view: this.dtJOINTableAdapter.Fill(dvDay);
Answer: You can use Sort in your SQL Query here is an example how you can do this.  e.g
SELECT * FROM Customers
ORDER BY Country ASC;


Where is the `Drush` command specific documentation?

Question: To be more specific than the title, I want to know what drush cim exactly does, like:

where is the drush cim command specific documentation?
Does cim command remove the files after they are imported, or not?
where are the setting files imported from, can you provide me with a path relative to the root (I mean, relative to where the main index.php file of drupal is)?
can we change the import path?
can we tell drush to just delete any (previously exported) setting files ?
Comment: We don't locate documentation here (it's something that many years have taught us that Q+A is not a good format for). But that said, it seems you've already found the documentation, you just don't personally find it useful - that doesn't automatically mean that more detailed documentation exists somewhere else. In this case I doubt it does. So that probably leaves you with 2 options: 1. raise a feature request to drush for more detailed documentation, or 2. ask a detailed question here about the specific, practical problem you're trying to solve by using `cim`, and how far you've got with it
Comment: Look at step 4 of method 3 in this post - it may answer some questions: https://www.morpht.com/blog/drupal-and-composer-part-3-converting-management-existing-drupal-8-site-composer
Comment: The gripe doesn't need to be in the question as it offers nothing.
Comment: Look at https://github.com/drush-ops/drush/blob/9.7.1/src/Drupal/Commands/config/ConfigImportCommands.php#L150-L264 to find the exact code that's being executed.
Comment: Please don't change questions once they've been answered, as existing submissions will be invalidated by this. If you have a new question, please ask separately. Thanks!
Comment: Mitigating personal feelings is not the purpose of an Q&A site nor is it helpful.
Comment: @Kevin Just leave the useful performance compare alone (which's the question's background too).
Comment: Hey Top-Master, precision is always appreciated among developers but could you please stop editing your question into something completely new? If you found out you needed something different than what's asked originally, simply ask a new question. You can then even add and accept your own answer to it.
Answer:
where is the drush cim command specific documentation?

https://drushcommands.com/drush-9x/config/config:import/

Does cim command remove the files after they are imported

No.

where are the setting files imported from, can you provide me with a
  path relative to the root (I mean, relative to where the main
  index.php file of drupal is)?

The path to the configuration folder is set in settings.php file. It will look like $configuration_directories = "path/to/config/folder". This is relative to the Drupal root directory.

can we change the import path?

Yes, you can change the path in the settings.php file.

can we tell drush to just delete any (previously exported) setting files ?

Anytime you export configuration, all the old configuration files will be wiped out, and new ones created from the current active configuration in the database.
Comment: Also note that 'cdel' deletes configuration from the active configuration in the database, not the exported .yml files.
Comment: does running `drush cdel` delete all (previously exported) configurations?
Comment: No. That function requires an argument - the configuration object to be deleted. I don't believe all config can be deleted with that function.
Comment: I would like to delete my quesion, but to be able to do that, you need to delete your answer first. Thanks in advance. (I am sure with 14K points you don't mind losing few here)


tensorflow resize image by random factor

Question: I am trying to resize an image by a factor during graph construction when the image size is unknown:
H, W, _ = img.get_shape()
scale = tf.random_uniform([1], minval=1, maxval=1.5, dtype=tf.float32, seed=None, name=None)

Out of these I need to magically compute a size which would translate to the following:
tf.image.resize_images(tf.expand_dims(img, 0), [H*scale, W*scale])

Which returns:
ValueError: 'size' must be a 1-D int32 Tensor

Any help is greatly appreciated. Thank you.
Answer: Your scale has shape (1,), so [H*scale, W*scale] has shape (1, 2). To fix it, just generate a scalar random instead of a 1-element vector:
scale = tf.random_uniform([], minval=1, maxval=1.5, dtype=tf.float32, seed=None, name=None)

Note the shape is an empty list, meaning you want a scalar.
In addition to that, you have to fix the data type of the size parameter, like this:
tf.image.resize_images(tf.expand_dims(img, 0), tf.cast([H*scale, W*scale], tf.int32))

Comment: Ah, great solution, for the life of me I couldn't figure out how to get a scalar out of `tf.random_uniform`. :)
Comment: Nice way of obtaining the random scalar. Thank you.
Answer: Your problem is that you're mixing the python list [H*scale, W*scale] with tensors. By default, tensorflow will convert lists like this to tensorflow constants as appropriate. But in this case, your list contains tensors and you're ending up with a nested set of tensors that aren't 1D.
To avoid confusion in cases like this stop using python constructs such as the list and convert your height and width into tensorflow constructs explicitly and check their shape before proceeding.
x = tf.concat((scale*W, scale*H), axis=0)
print(x)
Tensor("concat_3:0", shape=(2,), dtype=float32)

Doing so shows us that we now have a 1D tensor as required. But it's float32 (at least it was in the simple test case I set up), so let's cast that to an int:
x = tf.cast(x, tf.int32)

Now you're ready to go
tf.image.resize_images(tf.expand_dims(img, 0), size=x)

No error should occur there.
Comment: This solved my problem, thank you. I had to add another thing though, so in case anyone else has the same problem, my way of obtaining H and W didn't work. Instead use: H = tf.shape(img)[0]
        W = tf.shape(img)[1]


Notating a sus chord with thirteenth

Question: How do you notate a chord like G F A C E without using slash notation? G13sus? G13sus4?
If it's along the lines of a G13, this leads to me to wonder why the chord G F A C is usually notated as G9sus4 and not G11sus or G11sus4. After all, the only difference between that and the G11 is the omitted third.
Comment: Why _would_ you notate it without slash notation? F△/G seems very much the clearest way of expressing it.
Comment: This may be helpful: [what is the method behind naming jazz chords?](https://music.stackexchange.com/a/110876/70803)
Comment: @leftaroundabout F/g would imply some sort of supension of a subdominant, resolving into the dominant. Naming the chord G something instead implies a dominant function, resolving into the tonic. The chord here would be seen as a G dominant 7 9 11 13 chord without the third. I would not actually name this a Gsus4, as the 11 does not really serve as a suspension. So I'd suggest to notate this as G13(no 3,5).
Comment: @leftaroundabout The main reason is that I use a roman numeral notation and already reserve the slash to indicate a new or temporary tonic. Combining this with the bass slash notation would be too cumbersome. But you're right that, otherwise, it would be the clearest notation.
Comment: Some say that jazz chord symbols are *not* analysis and should simply be the clearest indication of *what to play*, Leftaroundabout's `F△/G` seems clearer and more direct for what to play than the cumbersome and redundant `G13sus4`.
Answer:
How do you notate a chord like G F A C E without using slash notation? G13sus? G13sus4?

Either would work. "sus" is typically interpreted as sus4.
Someone could interpret it as sus2. Someone else could add the fifth: D. But that's the fun with interpreting the chord symbols.

G11sus or G11sus4

These two symbols don't make sense to me. "11" means: add 11 (and b7, and perhaps even 9), while "sus4" means: replace 3 with 4 – that's contradictory.

After all, the only difference between that [G13sus4] and the G11 is the omitted third.

But that's a huge difference! So large, that – as Richard points out – many musicians wouldn't even consider to play a chord with both major third and 11 and play sus4 if they see 11 symbol. I'd like to add that some other musicians see sus4 as a coexistence of third and fourth. But it's a clearly very distinct sound.
In a major and dominant chords the perfect fourth is often called an avoid note, i.e. a note that even if it's present in the scale, shouldn't be emphasized. Playing a note as a part of the chord does emphasize it.

Why would you notate it without slash notation? F△/G seems very much the clearest way of expressing it.

I agree it's a very clear way to notate the chord, I would argue, even more clear than G13sus4:

it strongly suggests to play notes G F A C E
it strongly suggests to play G in the bass (which is not suggested by G13sus4)

The only issue that I may have with F△/G is that it suggests that the root of the chord is F, which means it's a fourth inversion of a ninth chord... which doesn't really exist, see e.g.:
How do you write a dominant ninth in fourth inversion?
What I mean by this is that in most cases we wouldn't hear this chord as rooted in F.
So the symbol F△/G isn't so helpful in understanding the harmony. But for writing a readable score for the performers it seems fine to me.
Comment: I'm just not quite sure if it's a contradiction or simply overlap/redundancy. G11 says "add 11"; G11sus4 says "add 11 *and* omit third". The thing that bugs me most though, is that if you go from `G F A C` to `G F A C E`, you go from G9sus4 to G13sus4. That's not... totally intuitive. But since 9sus4 is used so frequently, I'll probably stick to that.
Comment: Good point about 'making it simple to read' and/or 'explaining what's going on'. I think most of us reading it to play for the first time would prefer the former. We really don't use the latter until doing the post mortem, we just need something unequivocal to play. So the 'make it simple' wins - for most of us.
Comment: "I'd like to add that some other musicians see sus4 as a coexistence of third and fourth." I haven't encountered this. If the 3rd and 4th are both present, then in what sense is a suspension occurring? Are we delaying resolution to the 5th? That seems wrong, but maybe this is an aspect of suspensions I'm not aware of. +1 for the point about F∆/G. That might be an accurate description of the notes, but it doesn't describe the harmonic function. I hadn't previously thought about the redundancy of G11sus4. That's an interesting point--I'm convinced. Having 11 and 4 in the same symbol is redundant
Comment: When I see G13, I play the 3rd and 4th together (eg G-B-C-F in the left hand in a solo piano context). I personally don't think G11sus is redundant, and I think I've seen it in lead sheets. Like Daan points out, the sus really means 'don't play the 3rd' in that context. But here's my two cents: the best way to notate this is Dmin9/G or G13sus. If it's a jazz setting, both will make very clear that you want all the upper extensions. When I see G13sus, I'm more likely to omit the 5th than include it. They also both convey the correct function.
Answer: I would argue that calling it G13 is sufficient, and that it's not necessary to specify the sus aspect of this chord.
This is because eleventh and thirteenth chords often automatically omit the chordal (major) third so that it doesn't clash with the eleventh. This is one reason why ♯11 chords are so much more common than "regular" 11 chords: the ♯11 creates a whole step (or major ninth) with the third, as opposed to the half step created between the third and eleventh.
To quote a great comment by Max to Dom's terrific answer here:

it's puristic to insist that G11 contains both a B and a C. In older
pop charts G11 is a common shorthand for G7sus4 or G9sus4, as becomes
clear from looking at the voicings in the piano part. If you want an
accompanist to play both the B and C, G11 alone probably isn't enough
to override the instinct against playing that chord. I have seen
G7add11 used in this (uncommon) situation, and there was a suggested
voicing written in as well. (And the suggested voicing was stacked
fourths, so it actually put the 11th below the 3rd.)

Following this same logic, I would simply call your G F A C E a G13 chord. You could specify the omissions of the third and fifth if you really want, but in my experience that would be unnecessary and may honestly just trip up a sight reader.
Comment: I think for G13 it would be a lot more common to omit the 11th rather than the 3rd, no?
Comment: Perhaps there's a stylistic difference I'm not aware of, then. I'm glad I answered so I can get this figured out!
Comment: This is a very interesting answer, but I strongly disagree with the first sentence. However, I found myself arguing about that several times and I wonder if this disagreement may come from differences between jazz and classical notation? In classical music 6/7 chord, a.k.a. Chopin chord is what in jazz would be called 13 chord. Could it be that in classical notation 13 (which is perhaps never used) would indeed mean a chord with all components, including 3 and 11, i.e. something different than in jazz nomenclature?
Comment: In a modern jazz piano context (post Bill Evans), G13 is typically voiced F-A-B-E, the "type B rootless voicing" that many books teach. G13 does contain a 3rd in a jazz setting.

Notating a sus chord with thirteenth