Error:(25, 94) error: incompatible types: SettingsFragment cannot be converted to Fragment

Question: import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;

import static android.R.attr.fragment;

public class AppPreferences extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_note_detail);

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        SettingsFragment settingsFragment = new SettingsFragment();
       // fragmentTransaction.add(android.R.id.content, settingsFragment, "SETTING_FRAGMENT");

the error starting here is settingsFragment and the error is Error:(25, 94) error: incompatible types: SettingsFragment cannot be converted to Fragment
FragmentTransaction setting_fragment = fragmentTransaction.add(android.R.id.content, settingsFragment, "SETTING_FRAGMENT");
setting_fragment.commit();

and this is my settingsFragment
public  static class SettingsFragment extends PreferenceFragment{

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        addPreferencesFromResource(R.xml.app_preferences);
    }
}

Comment: Try changing android.R.id.content to R.id.content
Answer: You should use (if you want to keep the compatibility)  the PreferenceFragmentCompat included in the support v7 compatibility library.
PreferenceFragment is not included in the compatibility set of fragments, so changing PreferenceFragment to PreferenceFragmentCompat should suffice for your porpuses.
Check this out.
Hope it helps
Comment: Same error? Any difference? @ThetruesAbdallah update the question with your changes
Comment: ` public static class  SettingsFragment extends PreferenceFragmentCompat {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // Load the preferences from an XML resource
            addPreferencesFromResource(R.xml.app_preferences);

        }` the error now is cannot resolve PreferenceFragmentCompat
Answer: hey i got the solution to my problem

public class AppPreferences extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_note_detail);

The problem was with this code here so and this  getSupportFragment();  so i use just  getFragmentManager(); and its works

     // FragmentManager fragmentManager = getSupportFragmentManager();
      //  FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    SettingsFragment settingsFragment = new SettingsFragment();
    FragmentTransaction setting_fragment;
    setting_fragment = getFragmentManager().beginTransaction().add(android.R.id.content, settingsFragment, "SETTING_FRAGMENT");
    setting_fragment.commit();

}

public static class SettingsFragment extends PreferenceFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.app_preferences);
    }
}

}

Comment: I had the same problem. I have tried to use "PreferenceFragmentCompat", as indicated in the accepted answer, but I didn't succeed to configure the theme. Then I have replaced  getSupportFragmentManager() by getFragmentManager() and it worked fine.


Atualizando o tamanho do fancybox dinamicamente

Question: Olá,
Eu preciso redimensionar o tamanho de uma fancy box dinamicamente a partir de um evento onClick que irá mostrar outros componentes na página.
Tentei utilizar o seguinte trecho de código encontrado aqui, e este redimensiona a página mas dá o seguinte erro, além de não centralizar o fancybox na página.

Uncaught TypeError: Object function (){b.open.apply(this,arguments)}
  has no method 'center'

Além disso, utilizando este método, ao redimensionar o navegador, a Fancybox volta ao seu tamanho inicial.
Existe algum modo de contornar estes problemas? Estou utilizando a versão 2.1.5
Answer: Você pode fazer dessa maneira:

$("#seuBotao").click(function () {
        parent.$fancybox.update();
});

Lembrando que para que isso funcione corretamente você precisa que na chamada do FancyBox o atributo autosize seja true
Exemplo:
$("#fancy").fancybox({
        width: 750,
        height: 550,
        autoSize: true
});


Quando a textbox for nula, o botão ficará desligado

Question: Quando escrever na textbox, o botão irá ligar, mas quando não tiver nada na textbox vai desligar. Consegui fazer o método do botão ligar porém não consegui fazer o de desligar se a textbox for nula
private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (txt.Text == null)
    {
        bt.Enabled = false;
    }
    else
    {
        bt.Enabled = true;
    }
}

Answer: Essa lógica não funciona porque quando a TextBox está vazia ela tem a propriedade Text como string vazia ("") e não null.
Logo basta alterar ligeiramente a sua logica:
private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (txt.Text == "") //agora com "" de string vazia
    {
        bt.Enabled = false;
    }
    else
    {
        bt.Enabled = true;
    }
}

Na verdade pode até compactar bastante esta logica fazendo assim:
private void textBox1_TextChanged(object sender, EventArgs e)
{
    bt.Enabled = txt.Text != "";
}

Repare que nesta ultima versão o Enabled recebe o valor da comparação txt.Text != "" e por isso será diretamente o true ou false que pretende.
Answer: Vai depender do comportamento ideal e esperado para isso, um exemplo, se não quiser nem espaço em branco vai ter que usar string.IsNullOrWhiteSpace, exemplo:
private void textBox1_TextChanged(object sender, EventArgs e)
{
    button1.Enabled = !(string.IsNullOrWhiteSpace(textBox1.Text));
}

isso faz com que se colocar espaço sem nenhuma letra, não vai considerar e o botão continua desabilitado, agora se quiser considerar também os espaços para habilitar o botão é só usar propriedade Length da classe String
private void textBox1_TextChanged(object sender, EventArgs e)
{
    button1.Enabled = textBox1.Text.Length > 0;
}

Referencias

Propriedade String.Length
string.IsNullOrWhiteSpace
Classe String
Answer: Apenas complementando a resposta do Isac, talvez seja interessante adicionar o método Trim() ao final, se você não quiser que o botão seja habilitado apenas com a tecla espaço do teclado:
private void textBox1_TextChanged(object sender, EventArgs e)
{
    bt.Enabled = txt.Text.Trim() != "";
}


How to write multiple try statements in one block in python?

Question: I want to do:
try:
    do()
except:
    do2()
except:
    do3()
except:
    do4()

If do() fails, execute do2(), if do2() fails too, exceute do3() and so on.
best Regards
Comment: I have a feeling that describing your specific use case will lead to an answer with a more elegant solution...
Answer: If you really don't care about the exceptions, you could loop over cases until you succeed:
for fn in (do, do2, do3, do4):
    try:
        fn()
        break
    except:
        continue

This at least avoids having to indent once for every case. If the different functions need different arguments you can use functools.partial to 'prime' them before the loop.
Comment: `pass` should be `continue` perhaps?  Works as written but `continue` is semantically clearer.
Comment: @Triptych True, that does signal intent better. Edited answer.
Answer: I'd write a quick wrapper function first() for this.
usage: value = first([f1, f2, f3, ..., fn], default='All failed')
#!/usr/bin/env

def first(flist, default=None):

    """ Try each function in `flist` until one does not throw an exception, and
    return the return value of that function. If all functions throw exceptions,
    return `default`

    Args:
        flist - list of functions to try
        default - value to return if all functions fail

    Returns:
        return value of first function that does not throw exception, or
        `default` if all throw exceptions.

    TODO: Also accept a list of (f, (exceptions)) tuples, where f is the
    function as above and (exceptions) is a tuple of exceptions that f should
    expect. This allows you to still re-raise unexpected exceptions.
    """

    for f in flist:
        try:
            return f()
        except:
            continue
    else:
        return default

# Testing.

def f():
    raise TypeError

def g():
    raise IndexError

def h():
    return 1

# We skip two exception-throwing functions and return value of the last.
assert first([f, g, h]) == 1

assert first([f, g, f], default='monty') == 'monty'

Answer: It seems like a really odd thing to want to do, but I would probably loop over the functions and break out when there were no exception raised:
for func in [do, do2, do3]:
    try:
        func()
    except Exception:
        pass
    else:
        break

Comment: Creat, but what's else here for? it seem redundant here.
Comment: The `else` will only execute when there isn't an exception. If there's an exception the for will continue whereas if there wasn't an exception the `break` will execute. :)

A lot of statements in Python takes an `else` with the intention of "if everything went well, then do this".

See the documentation for the `try` statement: https://docs.python.org/3/reference/compound_stmts.html#try
Answer: Here is the simplest way I found, just embed the try under the previous except.
try:
    do()
except:
    try:
        do2()
    except:
        do3()

Comment: I did the same thing but can't it be made more compact?
Answer: You should specify the type of the exception you are trying to catch each time.
try:
    do()
except TypeError: #for example first one - TypeError
    do_2()
except KeyError: #for example second one - KeyError
    do_3()

and so on.
Comment: @alwbic: If you don't know the type of the exception, you don't know how to handle the exception.
Comment: I don't agree with you. I know that my statement will fail, but i don't know in which order they will fail. But I know what to do if it fails.
Comment: If I don't know the type of the exception?
Comment: @alwbic I am really sure that you must know what type(s) of exception(s) do you expect.
Comment: @alwbic: It is just a bad practice "Do something if something fails", you don't now why it fails.
Comment: @alwbic. I agree with you and you can do `except Exception: pass`. Something I always do when I develop is `except Exception as e: print(str(e))` to know what was the error.
Answer: if you want multiple try statments you can do it like this, including the except statement. Extract (refactor) your statements. And use the magic of and and or to decide when to short-circuit.
def a():
    try: # a code
    except: pass # or raise
    else: return True

def b():
    try: # b code
    except: pass # or raise
    else: return True

def c():
    try: # c code
    except: pass # or raise
    else: return True

def d():
    try: # d code
    except: pass # or raise
    else: return True

def main():
    try:
        a() and b() or c() or d()
    except:
        pass

Answer: import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise

Comment: This doesn't answer the question at all!
Comment: I laughed so hard at this answer, thanks for making my day


Apache As-Is Redirect is Internal... WHY?

Question: So I have a pretty standard Apache 2 setup, with AllowOverride all.
And I have three files in the "testing" folder under my docroot:
.htaccess
AddHandler send-as-is .asis

page.html
this is the page!

wtf.asis
Status: 301 Copy Is Elsewhere
Location: /testing/page.html
Content-Type: text/plain

Redirecting...

When I point my browser at /testing/wtf.asis, I see the text "this is the page!", but the address bar still says /testing/wtf.asis.  I expected to see /testing/page.html in the address bar instead and to get a 301 redirect!  Instead, I get a 200 response.  What's going on?  Is it doing an internal redirect?  If so, why?
Comment: Found the answer (below), but does anyone know any more details as to why this happens?
Comment: I had a vague idea that `Location` needs a full URL. Looking through the Apache2 source at [`$TOP/modules/generators/mod_asis.c`](http://svn.apache.org/viewvc/httpd/httpd/trunk/modules/generators/mod_asis.c?view=markup) I see no comment there as to why this behaviour.
Answer: I'm not sure, but I suspect that Location needs a full URL. Can you try that?
Comment: This works.  Sigh, Apache, why do you do this?
Comment: I looked a little but further, and it seems there is some CGI specification that tells web servers to make redirects without domain names internal.  Sounds nifty, but relying on it is another matter.
Comment: You inspired me to look at the RFC; section 6.2.2 of http://www.ietf.org/rfc/rfc3875 says your server will do an internal subrequest if you return a bare "Location: /full-path-without-http-host" without other headers. Graham Dumpleton (author of `mod_wsgi`) says Apache will also accept an `Status: 200` header. Perhaps you can try to return a Content-Type (for example) and see if the redirect is still handled as an internal subrequest?


Is it necessary to monitor the PID of proccesses?

Question: In some tutorials I've seen the following snippet for monitoring processes with PID:
check process nodejs with pidfile "/var/run/yourprogram.pid"
   start program = "/sbin/start myapp"
   stop program  = "/sbin/stop myapp"
   if failed port 8000 protocol HTTP
      request /
      with timeout 10 seconds
      then restart

But in some others I saw monitoring a whole host without PID like the following:
check host localhost with address 127.0.0.1
    start "/sbin/start myapp"
    stop "/sbin/stop myapp"
    if failed port 8000 protocol HTTP
       request /
       with timeout 10 seconds
       then restart

Tell me what is the difference in these two approaches? Which is better for monitoring of node js?
Answer: Process Identifier is actually useful when something goes wrong and/or you have more instances of the very same process running on your system. If you then want to to debug or kill, you can immediately track your process by it's ID rather then guessing one of multiple names.
Comment: Hmm. It's very interesting. Is it possible to run several nodejs instances in a single machine and track pid of each one?
Comment: I have really only elementary experience in the programming as a whole, but in my opininon - yes it is possible if you call the system's function to get the current program's PID from inside the program and have it report for example IP address you are starting this for followed by its PID.


How to alter a field within an unlimited field collection?

Question: I am trying to set the #access attribute to FALSE on a field that is within an unlimited field collection - so it is hidden from users. I am relatively new to Drupal so I'm not sure how to handle this. I tried to use hook_form_alter and some basic CSS - but I couldn't get either of the solution to work properly because of the unlimited field cardinality.
Here's what worked for one row in the field collection in a custom module:
$form['field_my_field_collection']['und'][0]['field_myfield']['#access'] = FALSE;

How do you alter a specific field in a field collection with unlimited values? Thanks in advance for any help - the Drupal community is awesome.
Comment: Yes Drupal community is awesome :)
Comment: have you tried using a for loop something like foreach($form['field_my_field_collection']['und'] as $field)
Comment: Did you look at the field permissions module? http://drupal.org/project/field_permissions
Answer: Since Drupal 7.8 you can leverage hook_field_widget_form_alter. You can alter any field widgets provided by field_collection before the form_alter of the main form.
function my_module_field_widget_form_alter(&$element, &$form_state, $context) {
  if ("field_my_field_collection" == $element['#bundle']) {
    if ("field_my_field_collection" == $element['#field_name']) {
      $element['#access'] = FALSE;
    }
  }
// dpm(array($element, $form_state, $context), "field_name: " . $element['#field_name'] );
}

Answer: Thanks for your help Mohammed, but I ended up using the following code in a custom module:
function mymodule_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'myformid') {
$delta = 0;
$max_delta = $form['field_my_field_collection'][LANGUAGE_NONE]['#max_delta'];
while ($delta <= $max_delta) {
$form['field_my_field_collection'][LANGUAGE_NONE][$delta]['field_myfield']
[LANGUAGE_NONE][0]['#access'] = FALSE;
  $delta++;
    }
  }
}


Django returned JSON, how to parse JSON Objects in js

Question: I am returning from my django code JSON and it looks like this:
my django code:
objs = AccessInfo.objects.filter(~Q(weblink=''))
return HttpResponse(serializers.serialize('json', objs), mimetype="application/json")

what I get in frontend is:

I want to be able to iterate over those JSON objects in frontend with javascript and show each fields value in some html.
If I alert(data), I am getting [ Object, Object ].
I tried $.parseJSON(data), but i am getting:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

how can I do it?
UPDATE:
my js is receiving the data like this:
$.ajax({
   url: '/get_book_access_downloads/',
   type: 'get',
   data: {bookid:bookid},
   dataType: 'json'
}).done(function(data){
   // to do
});

Answer: Your data is already parsed. You have a list of JavaScript objects, there is no need to parse it again.
You used jQuery to load the data, and jQuery parses JSON responses for you when you use dataType: 'json' on the $.ajax() call; had you omitted that argument, jQuery would have auto-detected JSON responses by their mime type anyway and decoded for you then too.
See the jQuery.ajax() documentation for the dataType option:

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
[...]
"json": Evaluates the response as JSON and returns a JavaScript object.

You have a list of 2 results; each result is a JavaScript object with the keys pk, model and fields, and the fields value is another object with each of your model fields.
Comment: thanks. I updated my question, showed how js code gets the JSON objects. how can I access JSON Objects in js. like  ``obj.attribute`` ?
Comment: @doniyor: `obj.fields.attribute`, where `obj` is one of the objects in the `data` list.
Comment: but if I do ``console.log(data.pk);`` i am getting ``undefined`` :(
Comment: @doniyor: you have a **list**; Use `data[0].pk` or `data[1].pk`.
Comment: oh now working like in fairy tales :)) thanks man. i need to dedicate one full day to study serializing.


iPhone: Native App with Locally Stored Webapp?

Question: Is it possible to write a webapp, then embed it in a native app so it can be launched without data and sold through the app store?
The Pre makes it easy to reference files in the local file structure, so it's very easy to build a webapp (HTML, CSS and Javascript) and embed it into a native app.
Is it possible to take the same plain HTML, CSS and Javascript (no Mojo/Webos-specific code) and embed it in the same way into a native iPhone app? This would make it seem to the user as if the icon in the home menu launches a webapp, but the app can be accessed without any data and can be sold through the app store.
Thanks,
~J
Answer: Within my application, I have a complete HTML-based manual that I use a UIWebView to display.  The HTML, CSS, and images are all stored locally in a Help directory within my application bundle.  I simply load the first page using code like the following:
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Help"];
NSURL *helpURL = [NSURL fileURLWithPath:[path stringByAppendingPathComponent:@"helpintroduction.html"]];

NSURLRequest *URLReq = [NSURLRequest requestWithURL:helpURL];
[webHelpView loadRequest:URLReq];

and everything loads and displays as if it were on a remote server.
To preserve the full directory structure of your HTML, etc. files, simply add those files to your Xcode project, dragging in directories where you can, and add a new Copy Files build phase.  Make the destination Resources and the path whatever you want to use for the base of your web files (Help in the example above).  Finally, drag all of the HTML, etc. resources you added to your project into this Copy Files build phase so that they end up bundled with your application.
I see no reason why this wouldn't work with more complex web applications, and I've seen no action by Apple against people doing this within their own applications.
Comment: So this would work to extend the method used by: http://bit.ly/4YYzW So that I can have references to images and scripts in a directory structure in my webapp? -- Thanks for this awesome answer, by the way. I'm just new to iphoning and trying to make sure I'm coming at this problem from the right angle. ~J
Comment: Yes, it should.  Their assertion that you can't have subdirectories is wrong.  In the example I give above, I have many subdirectories within the Help directory, and everything loads correctly.  I've never worked with PhoneGap before, but if everything it produces can be read off of a web server, there's no reason it can't be loaded locally from within your application's resources.
Answer: I don't see why not, just give the UIWebView a baseUrl of your local stored bundle.
Answer: Look at PhoneGap (http://phonegap.com/)
I haven't used it but it may be a good solution for what you're trying to do.
Answer: Yes, it is perfectly doable. You just need to build the absolute path to your HTML files within your application bundle, using "file:///" as the protocol, and point the URL of a UIWebView to it. You can do a quick and dirty test using the iPhone OS simulator and writing something like "file:///foo/bar.html" on Safari.app, provided that HTML exists, it will load just fine.
Answer: The problem is packaging it.  From what I can tell (and i could very well be totally wrong), apple just dumps all your files into one resources folder, regardless of directory structure in your project.  So if you create a webpage that references images/logo.png and javascript/script.js, suddenly those files will be located in / instead of their respective folders.  Given that, it might be feasible to create a web app with a completely flat structure from the start.
Comment: That's not correct.  You can maintain your complete directory structure by including the directory itself as a resource in Xcode.  I do this to provide in-application HTML-based help, with subdirectories for chapters and subdirectories within those for images.
Answer: There's no technical reason I know of why this should be problem.
However, there's always the chance that Apple could reject the app for doing something like this — they certainly haven't been shy about rejecting apps for not "behaving properly" before, and web apps have some certain peculiarities which make them not feel like native apps.
Such a rejection could probably be resolved by resubmitting, since there's certainly no standard for this kind of thing, but it's certainly something to be aware of.
Comment: True, there are lots of apps that use embedded WebViews. However, *I* don't know of any that consist **solely** of a WebView. At the very least, most of those apps will use a native control for the top bar or something, with a massive WebView for rendering content.

But like I said, unlikely it would get rejected, but not impossible.
Answer: If you are not a coder and you are interested in iOS only, you can follow these steps:

Download xCode
Download simple web view app from https://github.com/nomtek/iOSWebViewApp
Open simple web view app within xCode
Add your HTMLs to the project file structure
Run your app and voila :)

This approach is good if you don't need access to any phone specific features, just a standard Web View. Loading time will be short as this approach doesn't load any extra libraries.


Is it possible to prevent a View from executing until the user has chosen filters?

Question: I have a rather complicated View (created with the Views module) with about a dozen filters on it, all exposed to the user. The View is very heavy on CPU, and I would like to prevent it from running until the user has applied his filter choices.
One suggestion for dealing with this is to make a filter "Required": then the exposed filter will be empty when the View is first run and as a result will force the user to apply filter values explicitly.
The problem is that the filters are almost all dropdown lists, so they get a value applied automatically and don't therefore stop the View from running. Does anyone know some other way to do this?
Comment: There is solution on that page: https://www.drupal.org/node/358546 Does it solves your problem?
Comment: Trouble is this involves using PHP code and appears to be for Drupal 5 and/or 6. I could try it on D7 but I am hesitant to use code which could prove unstable later
Answer: I'm assuming that for suggesting an answer to your "Does anyone know some other way to do this?", it's OK to also suggest another "module" (instead of just another "way") ...
The Forena module might possibly be a valid alternative for you to consider. For more info about this module, refer to either of these links:

its Community Documentation.
its Demo site, which includes Reporting Samples and Documentation about the module (also included in a site where the module gets installed).

In this specific case, you could consider transforming your "complicated View" into appropriate Forena data blocks (SQL queries) and custom reports (and/or charts ...). And for those reports to be generated (and the SQL queries to be executed), you could consider using the various Forena features related to "Report Parameters". A few more details about these Report Parameters:

refer to this (extremely basic) demo sample that uses such report parameter.
refer to this relevant part of the documentation (related to report parameters).
Comment: Many thanks - I had looked at Forena a while back but then it slipped off the radar screen. Looks like I need to come back to it!
Comment: Thank you for the thank you. Hope this time your "radar" is big enough ... Also, looking at your profile it shows that you never visited the "tour" (within the help pages, upper right). Which is also why you're probably not aware of what's written in drupal.stackexchange.com/help/someone-answers ...
Comment: @MartinK : bonjour! Did you ever look at Forena "again"?


Does "Maximum image resolution" resize before saving on the site?

Question: I am building a site using Drupal 7, in which users can upload content and images.
When I set the "Maximum image resolution" (on the core image field settings) to be, for example -  800x600.
Is that mean that the pictures will first be resized and weight reduced, and only then will be saved on my Drupal site?
I don't want to have many pictures that weight a lot on my server. I prefer to save only the images that has been resized, in order to have more space on my server.
Answer: that setting means that you can't upload an image with max resolution of 800x600. If you upload an images with a size more than that set, it will be not imported and drupal will return an error alter.
Comment: That's what I thought, and that's the reason I asked the question. But, when I defined max resolution of 800x600, and max file upload of 10 MB. then I tried to upload image that weigh 6.9 MB with resolution of 3872x2592 - and it works. In addition I got the following message: "The image was resized to fit within the maximum allowed dimensions of 800x600 pixels." when I check - the size of the image in my drupal /public_html/sites/default/files is 83.86 kb.
Comment: are you using the Media module or the standard upload box?
Comment: No. but it's looks like great module.


Meteor error, Handsontable not defined

Question: I've installed the Handsontable package from atmosphere, and defining tables works fine in my app except for when I try to create a custom cell renderer.
The offending code in defining the table is this column definition:
{
  type: {
    renderer: function(instance, td, row, col, prop, value, cellProperties) {
      Handsontable.TextCell.renderer.apply(this, arguments);
      $(td).css({
        background: 'yellow'
      });
    }},
    //format: '0, 0.00 $',
    readOnly: true
  }

Anytime I try to make a Hansontable call like the Handsontable.Textcell.renderer.apply above, Meteor throws this error:

Exception from Deps afterFlush function: ReferenceError: Handsontable is not defined

I did read that Handsontable uses Jquery 1.9, but Meteor is bundled with 1.8. Could this be an issue?
Every example I see of custom cell renderers in Handsontable is similar to what I have so I'm a pretty lost on what the problem is. I also created a custom package of Handsontable with the latest version and that didn't help either.
Would love any help. Thanks!
Answer: This is likely a bug in the Handsontable package.
This line: https://github.com/olragon/meteor-handsontable/blob/master/lib/jquery.handsontable.full.js#L13
var Handsontable = {

should be
Handsontable = {

In meteor files are variable scoped. If you use the var keyword then other files can't access it. This is part of the reason you get the Handsontable is not defined error
You also have to export it by adding the line below after https://github.com/olragon/meteor-handsontable/blob/master/package.js#L6
api.export("Handsontable");

So that the api is exposed out of the package.
I have made a pull request so the package maintainer needs to accept it and update the package on atmosphere then you can run mrt update and use your code as you are using now.
If you are in a rush you could fork the package with the updates and use that as your Handsontable package
https://github.com/olragon/meteor-handsontable/pull/1

Meteor error, Handsontable not defined


Matrix times its pseudo-inverse equals the identity matrix. How do we determine the rank?

Question: So I have a matrix, $\mathcal A$, and its pseudo inverse, $\mathcal A^\dagger$. If $\mathcal A$ is $\mathcal m \times n$ with rank $\mathcal n$, what would be the rank of this new identity matrix formed by the operator $\mathcal AA^\dagger$? This identity matrix would have to be square, right? Does this mean it's in subspace $\Bbb R^n$?
Comment: what does "this new identity matrix formed by the operator $\mathcal A \mathcal A^\dagger$" mean?
Comment: I thought that a matrix times its inverse equals the identity matrix, right?
Comment: Non-square matrices don't have an inverse. It is called *pseudo* inverse for reason.
Comment: Well shoot. Then what is the significance of $\mathcal A A^\dagger$?
Comment: it depends on which pseudo inverse you consider.
Comment: If you're talking about the Moore-Penrose pseudoinverse here, then $\mathcal A\mathcal A^\dagger$ and $\mathcal A$ have the same image. This is one of the results of [your previous question](http://math.stackexchange.com/q/2134089/265466).
Answer: If $m \ge n$ then the rank of $A$ is less than or equal to $n$. If $m<n$ then the rank of $A$ is less than or equal to $m$. Thus, I assume that
$m\geq n$.
Let $A=USV^t$ be the SVD (singular value decomposition) of the matrix $A$ where $U$ is an $m\times n$ orthogonal matrix (that is $U^tU$ is an $n \times n$ identity matrix) $V$ is an $n \times n$ orthogonal matrix and $S$ is a diagonal matrix with positive diagonal entries ordered in the non-increasing order. These entries have to be positive; otherwise the rank of $A$ would be less than $n$.
The Moore-Penrose pseudo inverse of $A$ is given by $A^{+} = V  S^{-1} U^t$. Thus,  $AA^{+} = USV^t V S^{-1} U^t = U U^t$ which is an $m \times m$. This is an identity matrix if and only if $m=n$ in which case, you can replace the pseudo inverse by the standard inverse. The rank of $AA^{+}$ is given by the rank of $U$, which is $n$.
Note that $AA^{+}A = A$. If $A$ is a non-singular square matrix then $AA^{-1}A = A$. Thus, the pseudo inverse behaves like a normal inverse in this case.


Augmented triad in Pathetique Sonata? How does it function?

Question: I analyzed the harmony of the Pathetique Sonata as you already know, but one thing about the harmony in the first movement made me curious. No, not unconfirmed modulation or anything like that. No, it has to do with a single chord that I found in the third theme of the exposition. Here is an excerpt containing that chord and clarifying the key the passage is in:

You see it? It is this chord here:

An augmented triad. I have seen this triad crop up a few times in my analyses, usually as part of a passing motion in the melody. Here, though, it seems to be playing a more cadential role. Why? Well, look at the chords before and after the augmented triad:
I64 -> Augmented Triad -> IV -> V
I64, IV, and V are all chords very typical to see at a cadence. If you look at just the bass notes, you get something very familiar, a downward minor scale going to scale degree 5. This is often used as the bass line of a common idiom known as the lament bass. But the passage in question is in Eb major, the relative major of C minor, the scale that shows up in the bass notes. Also, usually the lament bass starts on tonic. Here, a supposed lament bass starts on a second inversion subdominant chord. So the bass progression isn't the whole story.
Now, if you expand your view to the Alberti Bass as a whole, you soon realize that there is no lament bass. If anything, the chord progression is closer to the Circle of Fifths progression than anything else. But this still doesn't explain what the augmented triad is doing. Here is my speculation as to what it is doing.
I speculate that because the augmented triad has a B natural, it is bringing back C minor for just a second before the IV chord arrives. Note how the right hand in the next bar after the augmented triad is playing notes of the C minor chord. With the bass being Ab though, it can't be C minor(unless Beethoven wrote this bit to be polytonal(which I seriously doubt)). Also, there being no G really weakens the C minor possibility.
But is that in fact what the augmented triad is doing is bringing back C minor for just a second, thus acting like III+ in C minor and not I+ in Eb major? Or is it acting more like V+, leading into the IV chord with 2 leading tones, the G leading to Ab and the B leading to C? In other words, how is the augmented triad functioning in this passage?
Comment: Some of these 64's should be 6's.
Answer: Bar ten's first half is I6.  Its second half is also I6, but with the B natural acting as a passing tone from Bb to C, or as something like an inverted appoggiatura or cambiata if you consider the melody to be Eb - Bnat - C.  There's no need to invoke obscure harmony; melody explains it enough.
Answer: Augmented triad is symmetric, so it pulls towards C the same much as it does towards Ab or E. I would agree with your interpretation that it is a secondary dominant (Eb+) to the following IV chord (Ab).


Using Drush on a site installed via Composer

Question: I had a Drupal 8 project installed from Drupal 8 sources what had been downloaded from Drupal 8 site. Recently I heard a good thought that it would be more comfortable to have the project originally installed via Composer. I did the migration and now the project has a structure likewise installed via Composer. That is, it has the "web" subdirectory with Drupal 8 files, the "vendor" directory isn't included in Drupal files and so on.
The site worked successfully after migration.
However, I ran into a problem. Namely, after migration, I couldn't use Drush on the project. The following error appeared upon trying to execute drush cr.

Command cache-rebuild needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.
Command cache-rebuild requires Drupal core version 8+ to run.

My colleagues advised me to install Drush-launcher from GitHub as a shell for original Drush. I did it, this problem seemingly disappeared. But I ran into a next one. Namely, Now I can't use Drush for projects made on Drupal 7.
Is it possible to set up Drush for sites installed via Composer and without using the launcher?
Comment: Install Drush 8 **globally**, that'll cover your Drupal 7 projects, and install drush 9 **locally** to drupal 8 sites. The launcher will take care of the rest
Comment: I have Drush 8 installed globally.
And I have the "drush/drush" package version 9 in my Drupal 8 project.
Is it not sufficient?
How and where can I install Drush 9 locally ?
Comment: If you have drush 8 why can't you use drush for projects made on drupal 7? drush 8 supports drupal 7. You shouldn't even need the launcher, drush is smart enough to work it out any time i've installed it
Comment: If I use modified Drush (with drush launcher), upon working with Drupal 7 projects I see this error message.

The Drush launcher could not find a Drupal site to operate on. Please do *one* of the following:
  - Navigate to any where within your Drupal project and try again.
  - Add --root=/path/to/drupal so Drush knows where your site is located.

Otherwise, if I use original Drush 8, I can't work with Drupal 8 projects installed via Composer.

I forgot to notify before that I use Windows 7 + Acquia Dev Desktop.
Comment: Oh it's Windows? Windows is notoriously buggy with both PHP and Drush. If you can convert to a linux VM you'll probably find life a lot easier. I'm on a Mac and I've never run into the problems you're describing
Comment: Unfortunately, I use the PC not only programming and it has a lot of other soft for Windows. Do you know, is it possible to set up original Drush 8 for working with Composer projects? As I understand original Drush can't find settings.php file.
Comment: Yeah, just `composer remove drush/drush` from your project. Then you'll be using the system one (assuming you also remove the launcher)
Comment: I did it, but "drush cr" doesn't work.
It writes: Command cache-rebuild needs a higher bootstrap level to run - you will need to invoke drush from a     [error]

more functional Drupal environment to run this command.
Command cache-rebuild requires Drupal core version 8+ to run
Comment: You'll need to run it in the Drupal docroot, not the project root. That's usually /docroot or /web
Comment: I tried to did it, there were some errors.
PHP Fatal error:  Class 'Drush\Commands\DrushCommands' not found in D:\devdesktop\pal\drush\Commands\PolicyCommands.php on line 11
PHP Stack trace:
PHP   1. {main}() D:\Program Files (x86)\DevDesktop\tools\vendor\drush\drush\drush.php:0
PHP   2. drush_main() D:\Program Files (x86)\DevDesktop\tools\vendor\drush\drush\drush.php:12
..
Comment: I think you should remove everything and start again, sounds like you have conflicts in there somehow
Comment: I have posted an answer, but you should update your question: 1) Add that you use Windows 7 + Acquia Dev Desktop. 2) What was the error when running Drush for the Drupal 7 site? With this info, we/I could have provided a better answer.
Answer: Acquia Dev Desktop comes with Drush included, and I assume that you could just continue to use that for Drupal 7. However, since you installed Drush Launcher and are using it as drush (drush.bat), you are shadowing it. Break the shadowing by renaming one of the two.
Comment: I use two different bat-files for executing two drush versions for work with these sites.


Matplotlib - Setting up rcParams for moving xlabel to the top?

Question: I need all of my figures to have xlabel, xticks and xticklabels on the top.
Since of that, I wrote a function to adjust plt.rcParams which serves for initializing purpose.
However, it seems there is no such parameter to setup xlabel to the top in advance. Here is a simplified showcase:
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['xtick.bottom'] = False
plt.rcParams['xtick.labelbottom'] = False
plt.rcParams['xtick.top'] = True
plt.rcParams['xtick.labeltop'] = True

data = np.arange(9).reshape((3,3))

f,ax = plt.subplots()
ax.imshow(data)
ax.set_xlabel('x label')
ax.set_ylabel('y label')

Output:

Currently the way I found to adjust it is putting ax.xaxis.set_label_position('top') after calling ax.set_xlabel('x label').
I'm looking for a solution with two goals:

It change the default x-label position so that every time ax.set_xlabel() is called, it shows up at the top.
This step could be executed before calling ax.set_xlabel()

So I don't have to use ax.xaxis.set_label_position() individually every time.
Extra:
As @r-beginners mentioned, the official reference did provide a example. But in the script they called is ax.set_title('xlabel top'), which is different from ax.set_xlabel('x label'). Note that a title is always on the top by default, regardless setting up plt.rcParams or not. I assume they missed this issue by mistake.
Answer: As far as I can tell, the position of the label of the x axis is hard-coded.
Let's look at the definition of the XAxis class, the relevant file is .../matplotlib/axis.py
class XAxis(Axis):
    ...
    def _get_label(self):
        # x in axes coords, y in display coords (to be updated at draw
        # time by _update_label_positions)
        label = mtext.Text(x=0.5, y=0,
                           fontproperties=font_manager.FontProperties(
                               size=rcParams['axes.labelsize'],
                               weight=rcParams['axes.labelweight']),
                           color=rcParams['axes.labelcolor'],
                           verticalalignment='top',
                           horizontalalignment='center')

        label.set_transform(mtransforms.blended_transform_factory(
            self.axes.transAxes, mtransforms.IdentityTransform()))

        self._set_artist_props(label)
        self.label_position = 'bottom'
        return label
    ...

As you can see, the vertical position of the label is hard-coded in the call to Text, y=0 in display coordinates, to be updated at display time by _update_label_positions and the label_position is hard-coded to 'bottom'.
Comment: I see... So there's no way to change default position of xlabel for now :(  Anyway, much appreciate for you bringing up the information about `XAxis`, I've learned something.
Comment: @Pakox.Wang Well, sometimes one has to _accept_ also unpleasant facts… and yes, me too I've learned something new about Matplotlib thanks to your question.
Answer: There is an explanation in the official reference. This will help you deal with it.
import matplotlib.pyplot as plt
import numpy as np

# plt.rcParams['xtick.bottom'] = plt.rcParams['xtick.labelbottom'] = False
# plt.rcParams['xtick.top'] = plt.rcParams['xtick.labeltop'] = True

x = np.arange(10)

fig, ax = plt.subplots()

ax.plot(x)
ax.set_xlabel('xlabel top')  # Note title moves to make room for ticks

secax = ax.secondary_xaxis('top')
secax.set_xlabel('new label top')

plt.show()

Comment: Actually I've tried this and didn't work. Let me check it again later to see if I'm getting anything wrong.
Comment: note that in that example they use `ax.set_title` to set the xlabel, instead of `ax.set_xlabel`. If you set an xlabel as normal, it will still be on the bottom.
Comment: After seeing @tmdavision comment, I ran the official reference code in my environment and it is correctly placed at the top. Have you checked the reference?
Comment: yes I have and my comment still stands. The "xlabel top" you see at the top is set by `ax.set_title()`. If you use `ax.set_xlabel()`, it is still placed at the bottom of the Axes
Comment: right... But that is not a solution to how to get the xlabel on the top of the axes, since a title is different to an xlabel. That is how to put a different text object in that position, which is not what the question asked... Your solution works for the `xticks` and `xticklabels`, but not the `xlabel`
Comment: I finally understand the purpose of your comment. I guess I don't understand it. How would you answer this question? I would be interested in it.
Comment: I edited my question. I'm really sorry for not being explicit enough and cost your time for that.
Comment: I'm not sure if this is the best way to do it, but I used `ax.secondary_xaxis()` to set the label. Please note that this is not an example of the graph you presented.
Comment: I'm actually looking for a solution with two goals: 1. It change the default x-label position so that every time I call `ax.set_xlabel()`, it shows up at the top. 2. This step can be executed before I call `ax.set_xlabel()`. ...Do you think if I should report this on github, since they use the wrong example and didn't really solve the problem?


specific Regular expression search python

Question: This is my first post.
I always come to this forum looking for an answer when it comes to code.
I have been fighting with understanding regular expressions in Python, but it is kind of hard.
I have text that looks like this:
Name:   Clash1
Distance:   -1.341m
Image Location: Test 1_navis_files\cd000001.jpg
HardStatus: New
Clash Point:    3.884m, -2.474m, 2.659m
Date Created:   2016/6/2422:45:09

Item 1
GUID:   6efaec51-b699-4d5a-b947-505a69c31d52
Path:   File ->Colisiones_v2015.dwfx ->Segment ->Pipes (1) ->Pipe Types (1) ->Default (1) ->Pipe Types [2463] ->Shell
Item Name:  Pipe Types [2463]
Item Type:  Shell

Item 2
GUID:   6efaec51-b699-4d5a-b947-505a69c31dea
Path:   File ->Colisiones_v2015.dwfx ->Segment ->Walls (4) ->Basic Wall (4) ->Wall 1 (4) ->Basic Wall [2343] ->Shell
Item Name:  Basic Wall [2343]
Item Type:  Shell

------------------

Name:   Clash2
Distance:   -1.341m
Image Location: Test 1_navis_files\cd000002.jpg
HardStatus: New
Clash Point:    3.884m, 3.533m, 2.659m
Date Created:   2016/6/2422:45:09

Item 1
GUID:   6efaec51-b699-4d5a-b947-505a69c31d52
Path:   File ->Colisiones_v2015.dwfx ->Segment ->Pipes (1) ->Pipe Types (1) ->Default (1) ->Pipe Types [2463] ->Shell
Item Name:  Pipe Types [2463]
Item Type:  Shell

Item 2
GUID:   6efaec51-b699-4d5a-b947-505a69c31de8
Path:   File ->Colisiones_v2015.dwfx ->Segment ->Walls (4) ->Basic Wall (4) ->Wall 1 (4) ->Basic Wall [2341] ->Shell
Item Name:  Basic Wall [2341]
Item Type:  Shell

------------------

What I need to do is to create a list that extracts for every chunk of text (separated by the -------------------------------) the following things as a string: the clash name and the clash point.
For example: Clash 1 3.884, 3.533, 2.659
I am really new to Python, and really do not have much understanding about regular expressions.
Can anyone give me some clues about using regex to extract this values from the text?
I did something like this:
exp = r'(?<=Clash Point\s)(?<=Point\s)([0-9]*)'
match = re.findall(exp, html)

if match:
    OUT.append(match)
else:
    OUT = 'fail'

but I know I am far from my goal.
Answer: If you're looking for a regex solution, you could come up with:
^Name:\s*         # look for Name:, followed by whitespaces
                  # at the beginning of a line
(?P<name>.+)      # capture the rest of the line
                  # in a group called "name"
[\s\S]+?          # anything afterwards lazily
^Clash\ Point:\s* # same construct as above
(?P<point>.+)     # same as the other group

See a demo on regex101.com.

Translated into Python code, this would be:
import re
rx = re.compile(r"""
                ^Name:\s*
                (?P<name>.+)
                [\s\S]+?
                ^Clash\ Point:\s*
                (?P<point>.+)""", re.VERBOSE|re.MULTILINE)

for match in rx.finditer(your_string_here):
    print match.group('name')
    print match.group('point')

This will output:
Clash1
3.884m, -2.474m, 2.659m
Clash2
3.884m, 3.533m, 2.659m

See a working demo on ideone.com.
Answer: import re

lines = s.split('\n')

names = []
points = []

for line in lines:
    result = re.search('^Name:\s*(\w+)', line)
    if result:
        names.append(result.group(1))

    result = re.search('^Clash Point:\s*([-0-9m., ]+)',line)
    if result:
        points.append(result.group(1))

print(names)
print(points)

# if you need more nice output, you can use zip() function
for name, point in zip(names, points):
    print(name, point)

You can find useful information about regular expressions at regexr.com. Also, i use it for quick tests and reference.


Model selection aimed at making "misfit" statistically insignificant

Question: I am working with a model that can be described roughly as
$$
\left\{ \begin{array}{ll} y^* & = & \beta_0 + x'\beta + \epsilon_{\{x,v\} }
\\ w^* & = & \gamma_0 + v'\gamma + \delta_{\{x,v\} }
\\ y & = & 1[y^* >0 ]
\\ w & = & 1[w^* >0 ]
\end{array} \right.
$$
although one or the other of $y$ or $w$ can be ordinal. (I am fitting this in generic terms with Stata cmp package by Roodman (2011).)
When the sets of regressors $x$ and $v$ are empty, $y^*$ and $w^*$ are strongly correlated. (and thus are their discrete versions $y$ and $w$). It is this correlation that I am aiming my model selection at: I need to make it small, which I know I can make happen as there are common influences on $y$ and $w$ from the explanatory variables $x$ and $v$ (which I kept distinct in my notation, but they will likely have a lot of common variables in practice).
My questions are:

What are the ways to conduct model selection here? So far, I am using a greedy search algorithm that adds one variable at a time to $x$ and/or $v$, check how the magnitude (or, better, significance) of the $\epsilon$-$\delta$ correction is affected, and chooses the variable that provides the best improvement.
Do I need to worry about the excluded variables needed for identification? (A somewhat longer, and a more accurate, story is that the $y$ equation is a selection equation, and $w$ equation is the response equation that only applies to cases with $y=1$, in a variation of the Heckman model. Whether the selection actually depends on $w$, as is implied in the labor supply model used by Heckman, is anybody's telling, but it does not need to be, in the context of my application).
What other questions should I be asking?

A somewhat similar problem of modifying your model until a certain test statistic becomes insignificant is faced in structural equation modeling, and I don't think they have an answer that I would find satisfactory.
Comment: I don't see any other answers here, which is a pity, since the question is interesting. I will like to take another thinking on the matter. Can you please clarify/verify the data series which comprise your sample?
Comment: I was hoping Frank Harrell would take it up, but he hasn't yet. The data, as I said, are of selection + outcome format. A similar structure can be found say in [Peress 2010](http://www.citeulike.org/user/ctacmo/article/10615475), although his selection variable $y$ is ordinal rather than binary.
Answer: I will propose a method, based on the assumption that the regressors matrix will be identical for both equations, call it $Z$.
Then : what do you seek? To "remove the correlation" between $y$ and $w$ because you believe it comes from the regressors. How will you know? As far as I can tell, you will have to consider "what is left unexplained" from the two dependent variables after regressing them on $Z$, and check whether these two "unexplained"s have become uncorrelated.
These two "unexplained"s are the residuals from the two regressions. Ideally, you would want them to be totally uncorrelated, i.e to obtain
$$\text{Corr}(\hat \epsilon, \hat \delta) = 0 \Rightarrow \text{Cov}(\hat \epsilon, \hat \delta) = 0 \Rightarrow E (\hat \epsilon \hat \delta) - E (\hat \epsilon )E (\hat \delta) = 0$$
As residuals, they will have by construction zero mean. So you are left with the ideal target of
$$E (\hat \epsilon \hat \delta) = 0$$
i.e. that the two residual series are orthogonal.
This is a moment condition, and you can minimize its sample analogue, namely
$$\min \frac 1n |\sum_i\hat \epsilon_i \hat \delta_i| = min \frac 1n |\mathbf {\hat
\epsilon'}\mathbf {\hat \delta}|$$
where the prime denots a row vector.
Now denote $M_z = I-Z(Z'Z)^{-1}Z'$ the "annihilator" or "residual maker" $n\times n$ matrix. It second name comes from the fact $M_z\mathbf y = \mathbf {\hat
\epsilon}$. This matrix is symmetric and idempotent, $M_z' = M_z,\; M_zM_z = M_z$.
Then you can write your objective function as
$$\min \frac 1n |(M_z\mathbf y)' (M_z\mathbf w)| =\min \frac 1n |\mathbf y' M_z'M_z\mathbf w| =\min \frac 1n|\mathbf y' M_z\mathbf w| $$
Minimize over the set of regressors of course. So you set up a routine to evaluate this product over various combinations of regressors. The combination that gives you the lower value of your objective function is the one that will make your two dependent variables as uncorrelated as possible, after removing the effect of the said regressors.
For your routine, note that the objective function is equivalent to the inner product of the residual from one regresion times the other dependent variable
$$\mathbf y' M_z\mathbf w = \mathbf y'\mathbf {\hat \delta} = \mathbf {\hat
\epsilon'}\mathbf w$$
ADDITION:
If you want to minimize directly the (absolute value of) the correlation coefficient between the two residual series, you will have to take into account their estimated standard deviations also. In such a case your objective function becomes
$$\min |\mathbf y' M_z\mathbf w|\left(\mathbf y' M_z\mathbf y\mathbf w' M_z\mathbf w\right)^{-\frac 12}$$
Comment: Alecos, that's a reasonable answer, but it does not help my particular problem -- as I said in my point 1, I know how to devise a greedy search (and that's what I am doing now), but that's a mechanical solution, not a statistical one. Besides, the residuals are not really observed, as these are limited dependent variable models, as I explained in the update. I also want to keep the regressors separate, as that's what the existing evidence points for the fit of the separate equations.
Comment: I don't see how an objective function that is the feasible implementation of a moment condition, is _not_ a statistical solution. The point is not the search, it is how one evaluates the search. UPDATE: and I answered before seeing the update.


1 dummy coded variable and 4 continuous variables in standard regression

Question: I will try to be as specific as possible and I do hope that someone can steer me on the right track.
I have 1 categorical variable for grade consisting of grade 1, 2, 3 and 4 which will be dummy coded. I also have 4 continuous predictor variables. Now, the perplexing part is I would like to know if it is possible to see the changes in strength of predictive power of the continuous variables on the DV between grades? I am told that I can do this in MR. Basically, besides looking at whether these variables predict the DV, my research is also looking at the whether different continuous variables predict or do not predict (or difference in predictive power for) the DV when participants are in grade 1, 2, 3 or 4.
If you need more info, I will be glad to furnish you with more details.
Answer: The way to do this is with interactions. This consists (in your case) of multiplying the continuous variables by the categorical variable and adding them as moer independent variables. How to do this exactly depends on your software, but it is pretty simple in any software.
Interpretation of the results can be a little tricky; I recommend looking at lots of graphs; one good set here would be the DV vs. each of the continuous IVs (one plot for each) with one line for each grade.


'include'-ing a module, but still can't call the method

Question: Why does the following code give the error below?
require 'open3'

module Hosts
  def read
    include Open3
    popen3("cat /etc/hosts") do |i,o,e,w|
      puts o.read
    end
  end
end

Hosts.read
#=> undefined method `popen3' for Hosts:Class (NoMethodError)

It works if I call popen3 using full path ie Open3::popen3.  But I've include-ed it, so thought I wouldn't need the Open3:: bit?
Thanks
Answer: You have defined an instance method, but are trying to use it as singleton method. To make what you want possible, you also have to extend the Open3, not include:
module Hosts
  extend Open3

  def read
    popen3("cat /etc/hosts") do |i,o,e,w|
      puts o.read
    end
  end
  module_function :read # makes it available for Hosts
end

Now:
Hosts.read
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1             localhost
=> nil

Reading about the following concepts in Ruby will make things much clearer for you:

context
self
include vs extend

Instead of module_fuction you could also achieve the same result with either of below:
module Hosts
  extend Open3
  extend self

  def read
    popen3("cat /etc/hosts") do |i,o,e,w|
      puts o.read
    end
  end
end

And
module Hosts
  extend Open3

  def self.read
    popen3("cat /etc/hosts") do |i,o,e,w|
      puts o.read
    end
  end
end

Comment: ah, i was thinking along those lines but coming up short. I shall read up on 'extend'. And 'module_function'! Thanks very much.
Comment: @spoovy N/p :) You could also achieve the same effect with few more options. Will edit in a moment (just in case you're interested :))


What's "species counterpoint"? Are there any other types of counterpoint?

Question: I believe the title says it all. On Wikipedia it shows the five species but I have the idea that there is another type of counterpoint not based on those species. Is that vague idea of mine correct?
I believe I got that idea reading this sentence:

Species counterpoint can at first seem very limiting, but through its practice, it can be used to create very exciting melodies and counter-melodies.

From this answer.
Answer: The linked answer almost answers this question as well, I think.  "Species counterpoint" is the name given to counterpoint composed in the styles described by Fux in Gradus ad Parnassum (though the idea is apparently older).  The species were intended to be a didactic tool to teach the student how to write counterpoint.  The approach is sufficiently effective that modern university students of eighteenth-century counterpoint frequently still use the species to understand how to write and understand that style of counterpoint.
Real eighteenth-century composers may or may not have used the ideas of Fux when learning to write counterpoint.  It is probably not accurate to say that an accomplished composer wrote a piece with a particular "species" in mind, though it is possible that a species could describe part or all of a contrapuntal work.  For the fifth species ("free" counterpoint, following the stylistic guidelines of the time) to describe such a work is a tautology, of course, but the other species could be used to describe parts of certain works.
Answer: I like the other answers here, but I want to stress that species counterpoint developed out of analysis of existing music.  Palestrina had never heard of species counterpoint.  He just wrote music.  Fux and others like him then looked at Palestrina's music and said, hmm, well, he does this and this in these circumstances, so we'll call that the first species.  And he does this other thing and this other thing in these other circumstances, so we'll call that the second species.  Then we'll use these species to teach counterpoint.  Palestrina himself breaks the "rules" of species counterpoint all over the place.
To my mind species counterpoint gets (some of) the form of Renaissance music without the soul.  Sort of like reading a basic book about massage and going into business as a masseur without ever having read more advanced work, gotten any hands-on training, or even had a massage.  It's a helpful tool but far less useful than experience of singing the actual thing.
Answer: Are there any other types of counterpoint?
Yes! Outside of the Palestrina-style counterpoint described by Fux's "species" -- which is to say, Modal, and eventually Tonal, counterpoint -- there are a variety of approaches. Here are a few.
Serial counterpoint
These two videos give brief introductions to serialism and to serial counterpoint, repsectively.

Melharmony
Melharmony is a system of developing polyphonic or contrapuntal music based in music systems that are fundamentally melodic; for example, Indian Classical music.
In this answer to the question Can modal counterpoint be studied without studying harmony? Where to start? there are a number of resources listed.
Microtonal counterpoint
Many composers have explored counterpoint in microtonal compositions, though to date, I'm unaware of a unified approach. The book Steps to the Sea: Ear Training and Composing in a Minute Equal Temperament by Julia Werntz (2014, Frog Peak Music) lays out microtonal composition exercises in a form analogous to "species" exercises.
Rhythmic counterpoint
(See also: What is rhythmic counterpoint?)
Phasing
Phasing is a technique primarily associated with composer Steve Reich. The basic concept is to create a musical line as a series of pulses, initial played in unison, but then slowly going out of phase with each other through progressive delays of each part.
A straightforward example is his Clapping Music (1972).

His piece Electric Counterpoint is a more elaborate example.
Rhythmic canons
Termed by Olivier Messaiaen, a rhythmic canon is one such that "each instrument should play the same rhythm but start at a different time."1 Further, "if the rhythmic canon is such that at every time interval exactly one instrument can be heard, then the canon is said to be tiled."2
An example of a rhythmic cannon can be heard in Messaiaen's Harawi (1945) midway though "Part VII: Adieu".
Tom Johnson works especially with tiling rhythmic canons. For example, his piece Tilework for Trombone.
Much of the writing on (tiling) rhythmic canons is highly mathematical. The seminal paper by Daniel Vuza, "Supplementary sets and regular complementary unending canons", can be found in Perspectives of New Music.3 Moreno Andreatta has written extensively on the subject. For more musically oriented papers, Tom Johnson has published several articles. Google Scholar is a good source for papers by both Andreatta and Johnson, as well as others.

1 http://archive.bridgesmathart.org/2009/bridges2009-265.pdf, accessed 2020 Sept 19.
2 Ibid.
3 D.T. Vuza, "Supplementary sets and regular complementary unending canons", Perspectives of New Music, Nos. 29(2) pp. 22-49; 30(1) pp.184-207; 30(2) pp.102-125; 31(1), pp. 270-305, (1991).
Comment: There's also older counterpoint than that described by Fux or practiced by Palestrina.
Comment: @phoog Organum?
Comment: And everything between organum and Palestrina.  Dunstaple, Ockeghem, Josquin, Mouton, Taverner, Tallis, Byrd, etc.  Imagining that Palestrina's style represents the Renaissance is rather like imagining that Bach's represents the Baroque: it's good, and it is arguably the pinnacle of the period's development, but the music of the century or two leading up to it was not exactly operating with the same set of rules.
Answer: Heh. I just linked to this elsewhere; a marvelous book for learning species counterpoint is the Aldwell-Schachter "Harmony & Voice Leading" text. We used at the UW-Madison School of Music and it's amazing.
http://books.google.com/books/about/Harmony_Voice_Leading.html?id=-Hp1g3DWNMgC
To build on the accepted answer, the various species progress like so:
First: note on note
Second: two notes on one note
Third: usually regarded as four notes on one note, but there are differences of opinion here
Fourth: suspensions
Fifth: basically "anything goes"
Compositionally speaking, these are all techniques used to put pieces together, but are never a piece in and of themselves, except, of course, when used pedagogically. For example, fourth species is often used to give a "soaring" sort of feeling due to the rhythmic offsets and harmonic blurring it employs. One good example is the second movement of Mozart's Clarinet Concerto in A, K622; that intro employ fourth species counterpoint.
Answer: Species Counterpoint is the tools by which counterpoint is composed. The five species of counterpoint make up all the pedagogical lessons needed to explain the counterpoint of composers like Palestrina.
Comment: Well, it's a method used by modern composers of counterpoint and taught in universities.  Do we know that anybody used these methods in the renaissance/baroque periods?
Comment: Let me see if I get it. Species counterpoint it's not a "kind" of counterpoint, but what's used to compose it?
Comment: Yes, I'd say that's a good way to put it. The five species of counterpoint are the building blocks composers use to compose counterpoint in general.
Comment: @MonicaCellio Yes. See "The Study of Counterpoint" by Joseph Fux, born 1660. In it, he describes all species of counterpoint.
Comment: @MonicaCellio Fux was born 135 years later than Palestrina.  I'm not aware of evidence that Palestrina or other Renaissance composers used methods similar to Fux's.  Lots of late Baroque and classical-period composers did, however.
Answer: In my experience, the term "species counterpoint" refers to only the pedagogical method by which it can be learned.  Fux's Gradus was the first to break it into "species," and that's where the name came from.  Other approaches exist and are often called the direct approach.  This boasts being able to bring you to writing more exciting music faster by dispensing with the progression from whole notes to half notes, etc.  Here is one such example:
https://www.amazon.com/Direct-Approach-Counterpoint-Century-Style/dp/B000EBPC12


Como setar e acessar sessão depois de usar session_name

Question: Eu tenho uma $_SESSION["id"]="123";
e acesso ela direto assim:
echo $_SESSION["id"];

Se eu usar o
session_name(md5("seg".$_SERVER["REMODE_ADDR"].$_SERVER["HTTP_USER_AGENT"]));

como vou acessar ou setar a sessão?
Answer: Se você utilizar apenas o session_name() ele retornará o nome da sessão atual. Quando você cria um name para a session_name($name) ele irá sobrescrever o nome da sessão atual e retornará o antigo nome.
Então quando você dá um nome para a sessão:
session_name(md5("seg".$_SERVER["REMODE_ADDR"].$_SERVER["HTTP_USER_AGENT"]));

E quer resgata-la. Basta fazer isso:
$nomeDaSessao = session_name();

Dá uma olhada no "manuel"

O nome da sessão refere-se ao nome da sessão, que é usado em cookies e
URLs (por exemplo, PHPSESSID). Ele deve conter apenas caracteres
alfanuméricos; ele deve ser curto e descritivo (para usuários com
avisos de cookie habilitados). Se name é informado, o nome da sessão
atual é modificado para o novo valor.

EDIT
pagina1.php
// a variável ficará com o nome da antiga sessao PHPSESSID
$sessao_antiga = session_name("teste"); // alterei o PHPSESSID para teste

session_start(); // inicio a sessao

$session_name_new = session_name(); // recupero o nome da atual

echo "O nome da sessão é ".$session_name_new."
"; // mostro o nome da atual
echo "Mas o nome da sessão antes era ".$sessao_antiga."
"; // mostro o nome da antiga

$_SESSION['id'] = "123"; // abro uma sessão com o nome id

if(isset($_SESSION['id'])){ // verifico se existe a sessao
    echo "A sessão com a chave 'id' existe! O valor dela é ".$_SESSION['id']; // mostro uma msg
}

O exemplo acima vai retornar:
O nome da sessão é teste
Mas o nome da sessão antes era PHPSESSID
A sessão com a chave 'id' existe! O valor dela é 123

Repare que quando você altera o nome da sessão, você altera o cookie PHPSESSID, e vincula as outras sessões a este nome. É importante destacar que essa alteração tem que ser feita ANTES do session_start().
Porém, para você recuperar essas chaves em cada script, você precisará alterar o nome da sessão também nas outras páginas. Assim:
pagina2.php
session_name("teste");

session_start();

if(isset($_SESSION['id'])){
    echo "A sessão 'id' Existe!";
}

O exemplo acima vai retornar:
A sessão 'id' Existe!
Comment: Obrigado Andrei
Comment: @RodrigoMarques não esquece de aprovar... =) Abraço!
Comment: Dúvida, ao usar md5 para setar uma nome para a sessão, pode haver algum problema se dois usuários tiverem o mesmo nome de sessão?
Comment: @GuilhermeCostamilam neste caso, ACHO que não, pois ele está pegando o `$_SERVER["REMODE_ADDR"]`. Mas seria bom ele inserir um date também. E tem um salt ali com o "seg"
Comment: @GuilhermeCostamilam se dois usuários tiverem o mesmo nome da sessão, não será problema se ele não estiver gerenciando isso. Geralmente esse name é alterado para que você possa gerenciar isso por ter muitos usuários usando a MESMA aplicação por exemplo. Ai você pode derrubar as sessões dinamicamente.
Comment: @GuilhermeCostamilam no caso dele é apenas para "segurança". Eu nem sei se isso amplia a segurança. Mas... Se não ampliar, não modifica nada. Apenas deixará um pouco mais lento.
Comment: então eu setaria assim $nomeDaSessao['id']='blablabla'; e acessaria assim echo $nomeDaSessao['id']; porque o nome da seção padrao é PHPSESSID e eu acesso com $_SESSION
Comment: @RodrigoMarques vou colocar um exemplo para vc entender.
Comment: @RodrigoMarques ficou mais claro? Qualquer coisa chama aqui...
Comment: pelo que entendi, indiferente do nome da seção vou sempre usar o $_SESSION['*'] para chamar ela, a unica diferença é que vou ter que setar o nome da sessão antes do session_start(); de todas as minhas paginas que usarem a sessão. isso?
Comment: existe algum pv aqui?
Comment: @RodrigoMarques exato. Se você não setar o nome, ele não irá encontrar a `SESSION['*']`.
Comment: @RodrigoMarques como assim.. pv???


Java program. How do I loop my "isLucky method through the array? and how do I print the result in the main method?

Question: How do I print the result in the main method? And how do I loop the "isLucky" method to the array?  I posted a little bit ago and was told I should post again with less questions.
import java.util.Scanner;

public class FunArrays {

public static void main(String[] args) {

    luckyNumber1 = 7;
    luckyNumber2 = 13;
    luckyNumber3 = 18;

    int[] a=new int[10];
    Scanner sc=new Scanner(System.in);
        System.out.println("Please enter numbers...");
        for(int j = 0; j < a.length; j++)
        a[j] = sc.nextInt();

    boolean b = isLucky(a);

        int result;

        if(b){
            result = sum(a);
        }

        else{
            result = sumOfEvens(a);
        }

}

public static int sum(int [ ] value)
{
      int i, total = 0;
      for(i=0; i<10; i++)
      {
          total = total + value[ i ];
      }

      return (total);
}
static int sumOfEvens(int array[])
{
int sum = 0;
for(int i = 0; i < array.length; i++) {
    if(array[i] % 2 == 0)
        sum += array[i];
}
return sum;
}
public static boolean isLucky (int[] array)
{

    if ( array[i] == 7 || array[i] == 13 || array[i] == 18 )
        return true;

    else
        return false;
}

// write the static methods isLucky, sum, and sumOfEvens

}
Answer: Try this,
public static boolean isLucky(int[] array)
    {
        for (int i = 0; i < array.length; i++)
        {
            if (array[i] == 7 || array[i] == 13 || array[i] == 18)
            {
                System.out.println("Going to return true");
                return true;
            }
        }
        return false;
    }

printing the result by using System.out.println("Result : "+result); in your main method
Comment: wow thank you! very helpful! Does the System.out.println("Result : "+result); print the result for whichever is true?
Comment: Make two sout like System.out.println("Sum Result : "+result); and System.out.println("sumOfEvens Result : "+result); with in the condition check. It will print the result from which one.
Comment: So would I post System.out.println("Sum Result : "+result); below the actual result? Or would I just put both outside of that in the main method?
Comment: Like this,if (b)
        {
            result = sum(a);
            System.out.println("Sum Result : "+result);
        }

        else
        {
            result = sumOfEvens(a);
            System.out.println("sumOfEvens Result : "+result);
        }
Comment: My "isLucky" method.  it pops up a "else" without "if" statement
Comment: Like where did I compile or where did I put the system.out.println 's?
Comment: Already you did that code in you main method replace the code by what i gave you
Comment: I'm receiving multiple errors.  They are "cannot find symbol" errors.  The "LuckyNumber" numbers in the main method, and the "i" in the "isLuckyNumner" method.
Comment: replace main, public static void main(String[] args)
    {
        int[] a = new int[10];
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter numbers...");
        for (int j = 0; j < a.length; j++)
        {
            a[j] = sc.nextInt();
        }

        boolean b = isLucky(a);

        int result;
        if (b)
        {
            result = sum(a);
            System.out.println("Sum Result : "+result);
        }
        else
        {
            result = sumOfEvens(a);
            System.out.println("sumOfEvens Result : "+result);
        }
    }
Comment: replace sum and sumofEvens, public static int sum(int[] value)
    {
        int i, total = 0;
        for (i = 0; i < 10; i++)
        {
            total = total + value[ i];
        }

        return (total);
    }

    static int sumOfEvens(int array[])
    {
        int sum = 0;
        for (int i = 0; i < array.length; i++)
        {
            if (array[i] % 2 == 0)
            {
                sum += array[i];
            }
        }
        return sum;
    }
Comment: replace isLucky method,  public static boolean isLucky(int[] array)
    {
        for (int i = 0; i < array.length; i++)
        {
            if (array[i] == 7 || array[i] == 13 || array[i] == 18)
            {
                System.out.println("Going to return true");
                return true;
            }
        }
        return false;
    }
Comment: What about "i" in the "isLucky" method?
Comment: What i its used in the for loop so there is no problem


Error is raised when I try to redirect webform submission to external webpage with query string

Question: Dear Drupal community,
I created a webform using the webforms module in Drupal 8 in order to add information to a webpage. Since I don't want to update the webpage manually I'd like to automatize this process by redirecting the information entered in the webform to a cgi script which then takes care of the rest (The target webpage is not based on drupal). So I used the [webform_submission:values:<>] tokens and added them in the query string of the external url. In principle it works, but I noticed that for some fields in the webform entries spaces and special characters like " and ' are possible. In these cases I get an error message that the confirmation URL is not valid. I attached a .png. At the blue line you see a space, this seems to be what causes the problem. But if I enter the url manually in the browser my cgi script works as expected. So I only need to prevent drupal from stopping the redirect.
I appreciate any help.
best regards
ps. I created the same post over at the drupal.org forum. Strangely though, I don't see my post appearing at the forum.
pps. While the approach with the query string is probably an unsafe approach it's alright for my purpose since everything happens in an password protected internal area.
Answer: I think there's an easier way to achieve what you want.
In you webform go to "Settings > Form" then you'll see near the bottom "Custom settings" with a dropdown for "method". There you can change it to "GET (Custom)" then enter the url for your third party site.
If you needed the get variable names to be something specific you might need to remake your fields with the right key to match your get variable names you need.
But that should do the trick and it will take care or encoding any special characters for you
Comment: Thanks, this exactly does the trick. I should have thought there was an easier solution than my cumbersome approach. This helps me a lot. Best regards.


The role of bias terms in binary recommender systems

Question: I realize that a recommender system applied to, for example, the Movielens dataset needs to account for bias. That is, one needs to adjust for the varying popularity of movies, and that users have different baselines for their ratings. If one users tends to rates movies high and another users rates movies low, a rating of 4 out of 5 implies different level of appreciation.
However, I struggle to understand the meaning of bias terms in a recommenders systems that uses binary data as its input. For example, when we instead of movie ratings have yes/no information on if a user purchased or viewed an item in an online store.
This implementation introduces scalar bias terms for both products and users. The method is a hybrid in the sense that it takes into account both user behaviour and metadata. The paper also describes how it is used on binary data in an online store. How should the bias terms be interpreted in this case?
Comment: Bias is a catch all parameters that accounts for the shift in the unit of measure. Think of measuring the temperature in Fahrenheit vs Celsius, your model shouldn't depend on unit of measure. So the bias would account for different zero points in the scales in this case
Comment: You are right, but there is something about the binary case that throws me off. That is, for example, in a case were an item is either bought or not in an online store. Here, there is no rating, just a yes or no on which to base future recommendations.
Answer: Look once more at the model definition, in the simplest case, it predicts the rating for $u$-th user and $i$-th item $\hat r_{ui}$ using
$$
\hat r_{ui} = f(\boldsymbol{q}_u \cdot \boldsymbol{p}_i + b_u + b_i)
$$
where $\boldsymbol{q}_u$ and $\boldsymbol{p}_i$ are latent representations per user and item, while $b_u$ and $b_i$ are bias terms. Bias term for user $b_u$ is the "default" or "average" rating the user gives, bias term for the item is the "default" rating for the item. Notice that the part $\boldsymbol{q}_u \cdot \boldsymbol{p}_i$ depends on the interaction of a particular user with a particular item, it tells you how well does the item matches the person. On another hand, $b_u$ is the base rating by the user regardless of everything else, and $b_i$ is the base rating for the item regardless of everything else. If the latent representations for user and item are orthogonal, $\boldsymbol{q}_u \cdot \boldsymbol{p}_i$ would be equal to zero, so the rating would reduce to $f(b_u + b_i)$.
To give an example, say that you are Netflix and your user Bob likes watching sci-fi movies, so a romantic comedy probably would not be a great fit for him. On another hand, if it is a multi-category Oscar winner, so it may make sense to "bump" the predicted rating by the fact that the movie has a very high average rating $b_i$. Another user, Anna is very critical and rarely gives thumbs-up to the movies, so $b_u$ would be negative for her, always decreasing the predicted ratings by a constant.
Additionally, same as in linear regression, intercepts improve the numerical stability of the algorithm and are beneficial when training the model.
Including additional features, such as metadata, does not change the interpretation.
Comment: Excellent answer. If the recommendations are applied to a binary dataset, would the b_i bias term represent how popular an item? What would b_u represent, how many items a user has bought? Also, when you mention Anna, our critical reviewer, wouldn't b_u be the term that is negative?
Comment: @Figaro remember that $f(\cdot)$ translates to the predicted rating. So $b_i$ is a number that translates to the rating of the item, if other things were zeros $f(b_i)$ would be the rating predicted only on the base of it. Depending on what your data is, it might be popular. Same with $b_u$, it's the "average rating" user gives--it could be something $f(b_u)$ could be something like the probability that user gives thumbs up, or that they click the item.
Comment: Good catch with Anna, it should be $b_u$, corrected.
Comment: Even in the binary case? As in the online store example where an item has either been bought by the user, or not. Here, there are no ratings.
Comment: @Figaro in such case you have so-called implicit feedback http://yifanhu.net/PUB/cf.pdf
Answer: Even if the system uses binary data as input (0/1), it can still have some "bias" (average, offset) of these zeros and ones. You can look at matrix factorization implementation here (for netflix competition data, which is very similar to movielens dataset):
https://github.com/pepe78/netflix_matrix_factorization


PDE subscript notation

Question: What does this notation mean in a PDE: $(u_xu_t)_{xx}$?
For example, I have checked that  $(u_xu_t)_x=u_{xx}u_{xt}$ so the product rule does not apply. However, it applies in the former case. What's the general rule?
Comment: Actually, $(u_xu_t)_x=u_{xx}u_t+u_xu_{tx}$.
Comment: Subzero-273K : You claim to have checked that  $(u_xu_t)_x=u_{xx}u_{xt}$. Please, show your calculus for this supposed check.
Comment: Where does the author of the linked paper use the result in your original post?
Comment: @Bran In the linked paper, the expression $u_{xt}=u_{yy}+(uu_x)_{x}$ is a PDE. It is not obtained as a particular case of any general differentiation rule for products. It probably results from the modeling of some physical phenomenon. I suspect that the same is true for the equality in the post.
Comment: @Bran: Don't confuse an equation with an identity. $(u_tu_x)_x=u_{tx}u_x+u_tu_{xx}$ is an identity which means that is is true any function $u(x,t)$. On the other hand $(u_tu_x)_x=u_{xx}u_{xt}$ which is an equation  is not true for any $u(x,t)$, but it is true for some particular functions solutions of the equation. So, the relationship  $(u_tu_x)_x=u_{xx}u_{xt}$ mut not be used everywhere for differents problems than the specific problem to which it is coming from.
Comment: The author uses it as above!
Comment: @JJacquelin In the paper context
Comment: @Subzero-273K What is $u$ in the context? Is it solution of any equation?
Comment: Yes, a solution to a PDE. Used for different PDEs
Comment: @Subzero-273K Could you give the reference?
Comment: E.g. https://arxiv.org/pdf/1003.0287.pdf
Comment: @Kevin Compare the dKP equation elsewhere
Comment: Ok, could you, in your original post verify for us that $(u_t u_x)_x=u_{xx} u_{tx}$?
Answer: It means that, for a function $u=u(x,t)$, you are computing the following quantity
\begin{align*} \frac{\partial^2}{\partial x \partial x} \left( \frac{\partial u}{\partial x} \cdot \frac{\partial u}{\partial t} \right) = \frac{\partial}{\partial x} \left( \frac{\partial^2 u}{\partial x \partial x}\cdot \frac{\partial u}{\partial t} + \frac{\partial u}{\partial x} \frac{\partial^2 u}{\partial x \partial t} \right) \\
= \frac{\partial^3 u}{\partial x \partial x \partial x} \cdot \frac{\partial u}{\partial t} + 2\frac{\partial^2 u}{\partial x \partial x} \cdot \frac{\partial^2 u}{\partial x \partial t} + \frac{\partial u}{\partial x} \cdot \frac{\partial^3 u}{\partial x \partial x \partial t}
\end{align*}

PDE subscript notation


Why doesn't baseball severely punish pitchers who seemingly hit batters intentionally?

Question: Time and time again, pitchers intentionally hit batters who show them up (or for whatever reason), yet they (the pitchers) hardly ever get seriously penalized. Further, when they are penalized, it's usually only a 4-6 game suspension (of a 100+ game season). So my question is, given how incredibly dangerous a pitcher's fastball is, why doesn't MLB punish pitchers harder for hitting the batter?
I'm aware that there are "unwritten rules of the game", but honestly I think that's just an incredibly terrible excuse for bad behavior. The batter is completely defenseless, and the argument can even be made that the batter can't even properly do his job as an offensive player, due to the psychological effect of thinking that he's gonna get dinged. Parallels can be drawn between this and the NBA's rule of "allowing shooters to come down in their space". In the NBA, you can no longer contest a shot and move into the shooter's space, because doing this prevents them from coming down safely, and also prevents them from developing a psychological block (thinking that they're going to come down on someone's foot and twist their ankle when they go up to shoot). This leads to better shooting, better offense, and more entertainment for fans.
Though we can't always determine a pitcher's intention, shouldn't a reasonably hard suspension be enough to deter throwing at batters no matter what? If a pitcher knows he's gonna get a hefty suspension regardless of his intent, I feel like he'd be much more careful in his pitch placement.
I personally just feel like it would just be better for the game of baseball to leave out the intentional hitting of batters. So why hasn't baseball worked to change this yet? Does MLB feel like this isn't an issue? Is it just too deeply rooted in the culture for this ever to change?
Answer: The main problem with handing out huge suspensions is that you cannot prove intent. When the batter goes up, he assumes some risk of being hit with a ball. The NBA rule punishes blocking the landing zone of a shooter. That rule is enforceable because blocking a landing zone is always intentional. There's no other reason to do that than to interfere with the shooter. In baseball, the psychological block you mentioned for the shooter is already present. There is a good chance a batter will be hit with a ball, whether the pitcher has intent behind it or not.
If the MLB were to punish pitchers no matter intent, well, they already do that! The batter gets a free base. If the MLB increases the punishment too much, the batters will become incentivized to get hit. They would crowd the plate, allow themselves to be hit, etc. Some players already do this, notably Chase Utley, because they feel that getting hit by a pitch is worth the reward of a free base.
Getting hit by a pitch is already part of the game, and it is impossible to prove intent, because it happens accidentally as well as on purpose.
Comment: I couldn't disagree more. Any potential professional hockey player who never hits anyone isn't going anywhere in the game.
Comment: From [ESPN's coverage](http://www.espn.com/mlb/story/_/id/19506109/bryce-harper-washington-nationals-suspension-reduced-three-games): "MLB chief baseball officer Joe Torre's explanation of the disciplinary decisions said Strickland **intentionally** hit "Harper with a pitch" (my emphasis). Seems like MLB are happy enough to state that it was intentional.
Comment: The NHL can't *prove* intent for e.g. hits to the head, but that doesn't stop them handing out large bans.
Comment: @PhilipKendall If a NHL player is worried about accidentally hitting someone in the head, then they won't hit anyone. You **don't** have to hit to play hockey. You **do** have to throw the ball within feet or inches of a batter to play baseball.
Comment: My point being that the game of baseball cannot be played without the ball going through the strike zone, very close to the batter. Pitchers aren't perfect, they will occasionally hit a player.


cannot load new scene

Question: I'm loading the default scene perfect "MainScene". but when y load a scene created by mi
the application crash
THIS WOKS OK
  - (CCScene*) startScene
  {
       return [CCBReader loadAsScene:@"MainScene"];
  }

THIS MAKES THE APP CRASH
  - (CCScene*) startScene
  {
       return [CCBReader loadAsScene:@"miNewScene"];
  }

   miNewScene : CCScene

EXCEPTION @"Argument must be non-nil"
does anyone knows what might be happening here?
Thanks in advance
Best regards!
Answer: It sounds like you do not have a CCB document in SpriteBuilder named miNewScene.ccb.
It does not suffice to just have a CCScene subclass by that name. CCBReader loads a CCB document, and if necessary it will instantiate the custom class associated with the document. It does not instantiate classes.
If you want to launch with a non-SpriteBuilder scene, do this:
- (CCScene*) startScene
{
    return [miNewScene node];
}

Note that it is customary in Objective-C to start class names with uppercase letters so as to not confuse them with variables/properties which are supposed to begin with a lowercase letter.
Comment: ok thanks for your answer, I thought that only creating the new scene through Xcode and calling this funcion That would be enough
Thanks very much
Answer: If you use SpriteBuilder, the Best way to load a custom CCScene:
MainScene *mainScene = (MainScene *)[CCBReader load:@"MainScene"];
/** Reset contentSize : SpriteBuilder changes this **/
mainScene.contentSizeType = CCSizeTypePoints;
mainScene.contentSize = [CCDirector sharedDirector].designSize;

No children of another container and less memory footprint

cannot load new scene


Browse files inside a Hyper-V snapshot

Question: If it possible to browse the inside of a snapshot file for a specific file? It is not possible for us to merge this particular snapshot file so we are looking for an alternative to recover a specific file inside it.
How can one open a snapshot file and navigate inside it?
Answer: Is the snapshot corrupt? If not, why not just take a snapshot of your current environment, and apply the one you want to look at, then re-apply your current one?
Answer: Make copies of all the .AVHD and .VHD files associated with your VM in some other location.  Then use Disk Manager to mount the (copy of the) .AVHD file associated with your snapshot.  This requires Server 2008 R2.  The .AVHD files won't show up by default in the user interface, but it can still mount them.
Then browse the file system looking for whatever you like.
Don't try to mount them without copying them, though, or you'll (at best) corrupt your snapshot chain.  Even mounting an NTFS volume changes it.
Comment: Will check that tomorrow once I'm back at work.

Browse files inside a Hyper-V snapshot


How to convert an object to iterable (list)?

Question: I want to convert an object to an iterable.
I have the output of the format
>>>result[0]
<Particle [0.015270307267929021, -0.0009933688866323714, -0.004208897534490854, -0.011275132115610775, 0.0029132053067140572, 0.005608170262839968, 0.0005401367846572976, -0.013393458586919493, 0.0003998091070805884, 0.0002900137732599478]>

The full code of the problem is
from fstpso import FuzzyPSO

def example_fitness( particle ):
    return sum(map(lambda x: x**2, particle))

if __name__ == '__main__':

    dims = 10
    FP = FuzzyPSO()
    FP.set_search_space( [[-10, 10]]*dims )
    FP.set_fitness(example_fitness)
    result =  FP.solve_with_fstpso()
    print "Best solution:", result[0]
    print "Whose fitness is:", result[1]

I want to use result[0] as the list.
Source
Comment: Your `result[0]` seem to be just one element `Particle` which looks to me contains a list inside. May I ask what is the data type of the `result[0]`? You could try `list(result[0])`. This should work most of the case, but this one may not since I see it as single element.
Comment: it is an object `fstpso.pso.Particle`
Comment: `list(result[0])` returns `TypeError: 'Particle' object is not iterable
`
Answer: According to your comment which states it's fstpso.pso.Particle, if you just call the following, you'll be able to use it as iterator without changing the original source code.
variable = result[0].X
for i in variable:
    print(i)

The original source code indicates the __repr__() function is just printing the self.X value, which is a list.
def __repr__(self):
return "<Particle %s>" % str(self.X)

Answer: The fstpso.pso.Particle object is as follows:
class Particle(object):

    def __init__(self):
        self.X = []
        self.V = []
        self.B = []
        self.MarkedForRestart = False
        self.CalculatedFitness = sys.float_info.max
        self.FitnessDevStandard = sys.float_info.max
        self.CalculatedBestFitness = sys.float_info.max
        self.SinceLastLocalUpdate = 0

        self.DerivativeFitness = 0
        self.MagnitudeMovement = 0
        self.DistanceFromBest = sys.float_info.max
        self.CognitiveFactor = 2.
        self.SocialFactor = 2.
        self.Inertia = 0.5

        # support for PPSO
        self.MaxSpeedMultiplier = .25
        self.MinSpeedMultiplier = 0

    def __repr__(self):
        return "<Particle %s>" % str(self.X)

    def __str__(self):
        return "\t".join(map(str, self.X))

From https://github.com/aresio/fst-pso/blob/master/fstpso/pso.py
What you want can be got with:
result[0].X


Playing a chord then a note

Question: If I played a chord (c major for example) then a note (B for example), will I hear the note B relative to C as major seventh or relative to E as perfect fifth or relative to G as major third or relative to the chord itself?
Comment: If you had taken the trouble to try this out, then you'd know what you hear.
Comment: I do a similar, but slightly different thing. To get a C note, I imagine it's the M3 of key Ab.
Answer:
...will I hear the note B relative to C as major seventh or relative
to E as perfect fifth or relative to G as major third or...

Yes, one of those. Or something else.  A C chord can be followed by any other chord, including many that include the note B.  Or by no chord at all - just a note!
Play your C chord.  Then play a G chord with B in the melody.  Then try an E chord instead.  A Cmaj7 chord.  How about D6? Or B?  Or G♯dim7?
Music is all about possibilities.   There's no 'correct' chord containing B that follows a C chord.  But there's lots of choices!
Anyway, we don't know what YOU will hear.   Try!
Answer: I think the specifics of chord voicing and inversion along with which octave you play the single B could effect the perception.
If the chord were root position, close voicing, C4 E4 G4 C5 and you then played B4 a half step under C5 it probably has a chance of sounding like the M7 above root C4.
Compare that with playing the single tone as B3 below the C4 which might not be convincing as a major seventh chord in third inversion. It might sound more like C4 descending to the leading tone and a possible implied dominant harmony.
Alternately consider the chord in second inversion, open voicing, G3 E4 C5, and the single tone is B4 dropped down from C5. That could imply a first inversion Em chord G3 E4 B4.
You will notice I'm using words like - if, could, might, imply - because only one chord and only one subsequent tone is a very limited context. My gut feeling is whatever style music you spend a lot of time playing and listening to will have a stronger effect than anything else. If that style is "classical", you're likely to hear the B as a leading tone or passing tone implied. If that style is modern/jazz/pop, it's more likely to sound as a M7 over C.
From the traditional, classical harmonic perspective I think you want to keep in mind that major seventh chords are far less common that dominant, diminished, and minor seventh chords, and especially a M7 above the tonic chord is just contrary to the style. Relative to a C major triad, the B is the leading tone. The leading tone's role is about making dominant harmony.
That B is made clear as a dominant in combination with G (the dominant scale degree) or F (the subdominant scale degree). Playing the B in literal isolation makes it a bit ambiguous, but part of that ambiguity is that in classical style it certainly would not sound like the M7 of a Cmaj7 chord, a tonic chord contrary to the style. You might say the ambiguity comes from make a muddle of the role of B relative to identities of tonic and dominant chords.
Try your experiment not with B♮ but with B♭. With the C major triad in just about any inversion or voicing that B♭ will most certainly sound as the minor seventh relative to root C. Part of the reason for this strong identity is there is only one diatonic dominant seventh in each key, and stylistically it is a very common chord. There will be no ambiguous muddle when you hit that lone B♭. It will clearly sound like a dominant chord.
From the traditional, classical harmonic perspective your experiment zeroed in on an important idea: the tonic chord is the one chord of a key that does not support a seventh or any other extension.
Comment: "You will notice I'm using words like - if, could, might, imply - because only one chord and only one subsequent tone is a very limited context": this seems the most important point. One can establish contexts to suggest any of the possibilities. The notes D-C-B-C with the words "God save the king" ("of thee I sing" in the US), only having chords with the D and two Cs, most would probably hear the unaccompanied B as a leading tone implying a G chord. But if you've got a jazzy piece full of major 7th chords, it will probably sound like a major seventh. Out of context, it's just subjective.
Answer: If your ear hears chords as single entities then you will hear it as a maj7 to the C chord. However  it is possible for someone to hear those other relationships you mentioned. Everyone has their own unique way of hearing things.
Comment: We hope an individual isn't locked into perceiving chords and notes in just ONE way!  They should be open to many possibilities and contexts for that B after a C chord.
Answer: Once you have the notes of a chord in your head, it's easier to reference other diatonic notes from this chord. It is possible to do the other options as you say, but why would you, after hearing three main notes of the chord from a particular key?
Even if the original chord is in 1st or 2nd inversion, your ears should (with some experience), be able to add B to the C E G you hear, producing the major 7th chord. Mainly as those 3 notes should be unmistakable as C major - there's really nothing else that blend can be, making the C (wherever it is) the root. It should also work with any other notes - even, eventually with non-diatonic notes, say making C+, or C7, for example.
Working as you say, you're introducing an extra stage in the proceedings, for no good purpose. Although it's quite clever if you can.

Playing a chord then a note