Name for scale contain the notes C, D, E, F G#, A, A#

Question: Is this an actual scale mode, like Phrygian, Locrian, etc, or is it just a constructed scale?

C, D, E, F G#, A, A# (C)

So, root, major second, major third, perfect forth, augmented fifth, major sixth and minor seventh.
Comment: @Dom's answer is more complete than what is available on this website, but it's nonetheless a good starting place if you're trying to identify a scale: http://www.scales-chords.com/scalefinder.php
Answer: Yes this scale actually exits and it's a mode of A Neapolitan Minor which contains the notes:

A  Bb  C  D  E  F  G# A

This scale starting on C in particular would be called Mixolydian Augmented due to it resembling the Mixolydian scale, but one where you would create an augmented chord off the tonic chord.

C  D  E  F  G#  A  Bb  C

You can also think of this scale as a mix of major and minor where you would just not use the 5th and both types of 6ths and strictly use the minor's 7th as such.

C  D  E  F  Ab A Bb

Comment: Augmented tonic... why do Augmented / Diminished modes exist when their tonic triads can't work as "tonic" in standard usage?
Comment: @RailroadHill I'm not sure what you are trying to say. If you are using one of these scale you are probably already a few steps away from traditional harmony so talking about standard usage isn't very useful.


How to I trigger Xdebug 3.x with Drush in PHPStorm

Question: Has anyone has success with getting CLI debugging (drush) working with Xdebug 3.x?
There are several obsolete posts here... but all obsolete with the new version of Xdebug.
Expected behavior
After setting a breakpoint in a PHP class or module, that I know is executed when a specific Drush command is run, I would like PHPStorm to stop at the breakpoint.
Debugging when initiated from the browser works beautifully.
Drush - nothing.
Though it used to before I;

upgraded to Catalina
upgraded Xdebug from 2.x to 3.x

Environment:
Local MAMP Drupal 8 / Drush 9.7.2
PHP
PHP 7.4.13 (cli) (built: Nov 30 2020 14:46:04) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Zend OPcache v7.4.13, Copyright (c), by Zend Technologies
Answer: I am guessing that you have changed your xdebug.ini according to the new standards. (Port changed from 9000 to 9003 etc...)
If not you should do that first.
Check this link for additional information on the matter.
Besides that considering that you are using phpstorm, you should simply run
<code>export XDEBUG_SESSION=PHPSTORM
</code>
before running the drush command. This must be done once every time you open a new terminal session. (Not sure if there is a way to have it permanently and if there is i am not sure you want it.) Nevertheless, if your configurations are ok, this should work.
Best Regards.
Comment: Thank you. Just a comment or two. First, I don't think there is an xdebug.ini.
According to the docs, the config will more likely be in `php.ini`

Also, in my case there was/is some configuration in `.bash_profile`.

Once I got the debugger to trigger, I saw another error referencing an old virtual host that I'm not using.  Fixed it with `export PHP_IDE_CONFIG="serverName=myhost-www.localhost"`
Comment: @sea26.2 – Can you maybe add another answer as well, with all the steps you did to fix it in the end?
Comment: Hey again, there is no xdebug.ini indeed, but any *.ini file you create will add up to your php configurations and it is advised to use separate files (At least I prefer it that way) to declutter the main php.ini file a bit.


Make a gzip-compressed tar archive of files and directories that have a specific letter

Question: I want ONLY directories and files that contain the letter.
I've been able to recreate it from a previous question. But the tar is not a gzip.
And when trying to make it a gzip it...doesn't remove leading ´/' from hard link targets? which ruins it.
Here's the modified code (not gzip)
find /path/to/dir/ -type d -name "*x*" -o -type f -name "*x*" -exec tar rvf x.tar.gz {} \;

Gzip:
find /path/to/dir/ -type d -name "*x*" -o -type f -name "*x*" -exec tar cvzf x.tar.gz {} \;

The same amount of files appear during the process, but when checking the tar (tf) only a single file that starts with x appears...
Is it not possible to do with gzip, or am I missing an easier solution...
Answer: To removing the leading slash you can change your command like:
cd /
find path/to/dir/ -type ....

This will make find to display relative paths
Answer: You have two issues here. First: the command behind the -exec switch is executed once for every occurrence. While appending to an existing uncompressed tar archive works like a charm, it does not for a compressed archive.
So you have two options here:

create the tar archive uncompressed, and compress it in a second step (as easy as gzip archive.tar)
or you have to build your command line. That is what the tool xargs was made for... it reads lines from standard input and appends them to your initial command line. (for example: cd /path/to/dir; find . -type f -name "*x*" | xargs tar -czf /path/archive.tar.gz)

The second issue with the removal of the trailing / is not a gzip issue, that is a tar issue. Basically, you NEVER want an absolute path to be inside an archive, since the guy extracting your archive wants to have a choice where to put the files - and this means a relative path to the location the extracting guy selects.
If you really know what you are doing, you could use tar's switch --absolute-names, which allows absolute paths to be inside the archive, but I really would not recommend that...
Comment: Other unrelated problem is the precedence of find boolean clauses: `x -o y -exec z` should be `\( x -o y \) -exec z` to execute z in both cases. And, as suggested in @Martin's answer, every launch of `tar czvf tar-file.tgz file-with-x` on every file or directory found will create a new tar-file.tgz, and not append to it if exists.


MapReduce on EMR does not contact RMProxy and gets stuck waiting for resourcemanager?

Question: I'm running mapreduce/hadoop on EMR using hadoop 2.7.3.  Stock install off of AWS, and the jar was built with maven shade plugin.  It gets infinitely stuck waiting for the ResourceManager, but I've found absolutely nothing in the logfiles or on line.
In job.waitForCompletion, it comes to a line of the following:
020-01-25 05:52:41,346 INFO org.apache.hadoop.yarn.client.api.impl.TimelineClientImpl (main): Timeline service address: http://ip-172-31-13-41.us-west-2.compute.internal:8188/ws/v1/timeline/
2020-01-25 05:52:41,356 INFO org.apache.hadoop.yarn.client.RMProxy (main): Connecting to ResourceManager at ip-172-31-13-41.us-west-2.compute.internal/172.31.13.41:8032

Then it just sits there... never makes progress, and the cluster has to be shut down or the task manually killed.
Interestingly, by running hadoop jar <arguments>, I can reproduce this step locally, but I have no idea what is causing it.
After 25 minutes or so, it fails while unpacking the jar:
After 25 minutes or so, the job produces output of the form:

AM Container for appattempt_1580058321574_0005_000001 exited with exitCode: -1000
For more detailed output, check application tracking page:http://192.168.2.21:8088/cluster/app/application_1580058321574_0005Then, click on links to logs of each attempt.
Diagnostics: /Users/gbronner/hadoopdata/yarn/local/usercache/gbronner/appcache/application_1580058321574_0005/filecache/11_tmp/tmp_job.jar (Is a directory)
java.io.FileNotFoundException: /Users/gbronner/hadoopdata/yarn/local/usercache/gbronner/appcache/application_1580058321574_0005/filecache/11_tmp/tmp_job.jar (Is a directory)
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.<init>(ZipFile.java:225)
at java.util.zip.ZipFile.<init>(ZipFile.java:155)
at java.util.jar.JarFile.<init>(JarFile.java:166)
at java.util.jar.JarFile.<init>(JarFile.java:130)
at org.apache.hadoop.util.RunJar.unJar(RunJar.java:94)
at org.apache.hadoop.yarn.util.FSDownload.unpack(FSDownload.java:297)
at org.apache.hadoop.yarn.util.FSDownload.call(FSDownload.java:364)
at org.apache.hadoop.yarn.util.FSDownload.call(FSDownload.java:62)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Failing this attempt

This happens both on AWS EMR and locally.  Never seen this error, and using EMR straight out of the box.
Any ideas as to why this would happen? Bad Jar?  Potentially related to another unanswered question here
Comment: exit -1000   -- not a common error.
Answer: After exhaustively trying hundreds of experiments, it appears that the offending line was
job.setJar().
Why, I do not know.  It works fine under intellij, but reliably crashes using the hadoop command both locally and under intellij.


jQuery flot associate text with plot points

Question: I'm using Flot and would like to associate text with each individual plot point so that when I hover over the plot point the relevant data is displayed.
I have used the following example
http://people.iola.dk/olau/flot/examples/interacting.html
which allows me to display a tooltip but I need to associate text with each plot point.
Answer: I am probably answering this too late. As I understand the question, you are trying to display some text about the point other than just the x,y coordinates at that point. I was able to solve it for myself and found the clue in the link you gave http://people.iola.dk/olau/flot/examples/interacting.html. If you look at the code, in the function bound to plotclick event, there is this variable item.dataIndex:
$("#clickdata").text("You clicked point " + item.dataIndex + " in " + item.series.label + ".");

This variable is a sort of id for the point in the plot. Hence if I make an array with three params, the x coordinate, y coordinate and info, and pass the first two coordinates to the plot function in the following way:
var data = [];
for(i=0;i<len;i++)
  data.push([obj[i][1], obj[i][0]]);
//plotting the new array "data"
var plot = $.plot($("#placeholder"), [data], options);

where the obj array is:
{{12, 20, "info about point 1"},{26, 30, "info about point 2"}}

then the following statement inside the function for plothover event will do the job for us
showTooltip(item.pageX, item.pageY,obj[item.dataIndex][2]);

It worked me for me. Hope it helps. :)
Note:
You may also find it handy to reference the text directly rather than having to keep a reference to obj array:
var myLabel = this.plot.getData()[item.seriesIndex].data[item.dataIndex][2]
showTooltip(item.pageX, item.pageY, myLabel;

Comment: Thanks. Sorry for taking so long to mark this as the correct answer I'm going through my old questions and tidying up.
Answer: This particular code is showing the count for each point, plus the label, along with the x and y values (which happen to be year and salary amount, obviously change that to be whatever makes sense for your graph to be displaying).
        var previousPoint = null;
    jQuery("#placeholder").bind("plotclick", function (event, pos, item) {
            jQuery("#x").text(pos.x.toFixed(0));
                 jQuery("#y").text(pos.y.toFixed(0));

                 if (item) {
                     if (previousPoint != item.datapoint) {
                         previousPoint = item.datapoint;
                                   jQuery("#tooltip").remove();
                                   var x = item.datapoint[0].toFixed(0), y = item.datapoint[1].toFixed(0);
                                   var count = findCount(item.series.label,x);
                                   showTooltip(item.pageX, item.pageY, count + " " + item.series.label + " " + x + " = $" + y);
                          }
                 }
                 else {
                     jQuery("#tooltip").remove();
                     previousPoint = null;
                 }
    });

...that gives you the position of the point and passes it to the function which shows the tooltip, which you can define like this:
        function showTooltip(x, y, contents) {
        jQuery('
' + contents + '
').css( {
                position: 'absolute',
                display: 'none',
                top: y - 35,
                left: x + 5,
                border: '1px solid #fdd',
                padding: '2px',
                'background-color': '#fee'
        }).appendTo("body").fadeIn(200);
    }

I can't really tell you why the background color has to be in quotes, but I can tell you that it does.  Obviously change the colors, padding, fadeIn value, etc. to match how you want things to look.
Answer: function redrawplot() {
   $('.tt1').remove();
   var points = plot.getData();
     var graphx = $('#placeholder').offset().left;
     graphx = graphx + 30; // replace with offset of canvas on graph
     var graphy = $('#placeholder').offset().top;
     graphy = graphy + 10; // how low you want the label to hang underneath the point
     for(var k = 0; k < points.length; k++){
          for(var m = 1; m < points[k].data.length-1; m++){
            if(points[k].data[m][0] != null && points[k].data[m][1] != null){
                  if ((points[k].data[m-1][1] < points[k].data[m][1] && points[k].data[m][1] > points[k].data[m+1][1]) && (points[k].data[m-1][1] - points[k].data[m][1] < -50 || points[k].data[m][1] - points[k].data[m+1][1] > 50)) {
                                 showTooltip1(graphx + points[k].xaxis.p2c(points[k].data[m][0]) - 15, graphy + points[k].yaxis.p2c(points[k].data[m][1]) - 35,points[k].data[m][1], points[k].color);
              }
                              if ((points[k].data[m-1][1] > points[k].data[m][1] && points[k].data[m][1] < points[k].data[m+1][1]) && (points[k].data[m-1][1] - points[k].data[m][1] > 50 || points[k].data[m][1] - points[k].data[m+1][1] < -50)) {
                                 showTooltip1(graphx + points[k].xaxis.p2c(points[k].data[m][0]) - 15, graphy + points[k].yaxis.p2c(points[k].data[m][1]) + 2,points[k].data[m][1], points[k].color);
                              }
                            }
        }
      }

 }

 function showTooltip1(x,y,contents, colour){
      $('
' +  contents + '
').css( {
            position: 'absolute',
            display: 'none',
            top: y,
            left: x,
            'border-style': 'solid',
            'border-width': '2px',
            'border-color': colour,
            'border-radius': '5px',
            'background-color': '#ffffff',
            color: '#262626',
            padding: '0px',
            opacity: '1'
      }).appendTo("body").fadeIn(200);
 }


How to get free API for vegetable and fruit rates?

Question: I want API url for following categories:
Bus route schedule, vegetable rates, fruit rates, gold rates, weather reports.
Answer: This is the free API Url for weather Open Weather
For Gold Gold
Comment: weather report api is good


How add new tab in structure when manage it?

Question:
I try to do own User Graffic Interface. That interface must help to managers do they are own form displays. By drug`n drop elements in space. Then when they push save. I will save coordinats of elements. I need to show my module in other (new one) tab when manage in structure. I have little exp. working with drupal. But deadline is coming close. I sware i will give this module for avryone. So i need help. (pls. didn't write about Display Suit.)
<code><?php
/**
 * Implements hook_form_FORM_ID_alter().
 */
function admt_form_node_type_form_alter(&$form, &$form_state) {
  $default_value =TRUE;// auto_nodetitle_get_setting($form['#node_type']->type);

  $type = $form['#node_type'];
  $form['#theme'] = 'admt_form_theme_function';
  $form['admt'] = array(
    '#type' => 'fieldset',
    '#title' => t('Graffic User Interface'),
    '#weight' => 0,
    '#collapsible' => TRUE,
    '#collapsed' => false,
    '#group' => 'additional_settings',
    //'#theme' => 'admt_form_theme_function',
    '#attached' => array(
      'js' => array(drupal_get_path('module', 'menu') . '/menu.admin.js'),
    ),
  );

    if (isset($type) && $type->has_title) {
    $title = $type->title_label;
    }
    $fields = array();
    $arrFieldsType=array(
    "number"=>"textfield",
    "text_textfield"=>"textfield",
    "options_select"=>"select",
    "taxonomy_autocomplete"=>"textfield",
    "text_textarea_with_summary"=>"textare",
    "image_image"=>"file",
    "checkboxes",
    "radios"
    );
  $instances = field_info_instances('node', $type->type);
  $extra_fields = field_info_extra_fields('node', $type->type, 'form');

  // Fields.
  foreach ($instances as $name => $instance) {
    $form['admt'][$name] = array(
    '#type' => $arrFieldsType[$instance["widget"]["type"]],
    '#title' => t($instance["label"]),
    '#default_value' => array('value' => '...'),
    //'#options' => $type2,
     );
        if($arrFieldsType[$instance["widget"]["type"]]!="select") $form['admt'][$name]['#size']= '20';
  }

  // Non-field elements.
  foreach ($extra_fields as $name => $extra_field) {
    if(!empty($extra_field["type"]))
    $typ=$arrFieldsType[$extra_field["type"]];
    else
    $typ="textfield";
    $form['admt'][$name] = array(
    '#type' => $typ,
    '#size' => '20',
    '#title' => t($extra_field["label"]),
    '#default_value' => array('value' => '...'),
    '#description' =>  t($extra_field["description"]),
    //'#options' => $type2,

     );
  }
  return $form;
}
function admt_theme($existing, $type, $theme, $path,$form)
{
  return array(
    'admt_form_theme_function' => array(
      'render element' => 'form',
      'template' => 'admt',
      'form' => $form,
    ),
  );
}
</code>
Answer: You need to create a menu with type as MENU_LOCAL_TASK. Can refer to menu 'node/%node/edit' in node.module.
Hope it helps


How can I improve my Javascript/jQuery logic? Example included

Question: This isn't a direct question, but more a question on how I can improve my javascript by condensing my code and writing in a more logical way.
Basically I just wrote some javascript, using jQuery, in order to create some portfolio animations on my website. You can view the portfolio and animations here:
http://www.saelstrom.com/portfolio/full-portfolio
Everything I wanted to accomplish seems to work. However I just have this feeling that it could have been written with a lot less code. I could be wrong, but I thought I'd put the question out there just in case there's any experts who'd like to point me in the right direction for the next time I write some javascript.
Here's my scripts:
<code>$(document).ready(function() {

// ------------------------------------------------------
// - Create jQuery Function - Fade Then Slide Toggle
// ------------------------------------------------------
jQuery.fn.fadeThenSlideToggle = function(speed, callback) {
  if (this.is(":visible")) {
    return this.fadeTo(speed, 0).slideUp(speed, callback);
  } else {
    return this.slideDown(speed).fadeTo(speed, 1, callback);
  }
};

// ------------------------------------------------------
// - Portfolio Item Collapse
// ------------------------------------------------------
$('.folio-item').click(function(){
    collapse = $(this).find('.folio-collapse');
    collapse.slideToggle('slow',function(){
        if($(this).is(':visible')){
            $(this).parent().addClass('open');
        }
        else
        {
            $(this).parent().removeClass('open');
        }
    });
});

// ------------------------------------------------------
// - Portfolio Item Hover
// ------------------------------------------------------
$('.folio-item').hover(function(){
    hoveritem = $(this).find('.hover-item');
    hoveritem.fadeIn('fast');
},
function(){
    hoveritem = $(this).find('.hover-item');
    hoveritem.fadeOut('fast');
});

$('.folio-screen').hover(function(){
    hoveritem = $(this).find('.launch');
    hoveritem.fadeIn('fast');
},
function(){
    hoveritem = $(this).find('.launch');
    hoveritem.fadeOut('fast');
});

// ------------------------------------------------------
// - Portfolio Show/Hide Section Wrappers
// ------------------------------------------------------

// - Web Design - Click Function
$('li.port-web').click(function(){

    if($('.web-wrapper').is(':visible')){
        // Do Nothing
    }
    else if($('.marketing-wrapper').is(':visible')){
        // Remove 'active' Class
        $(this).parent().find('li.port-marketing').removeClass('active');
        // Add Class 'active'
        $(this).parent().find('li.port-web').addClass('active');
        // Hide Marketing Wrapper
        $('.marketing-wrapper').fadeThenSlideToggle('slow',function(){
            // Show Web Wrapper
            $('.web-wrapper').fadeThenSlideToggle('slow');
        });
    }
    else if($('.branding-wrapper').is(':visible')){
        // Remove 'active' Class
        $(this).parent().find('li.port-branding').removeClass('active');
        // Add Class 'active'
        $(this).parent().find('li.port-web').addClass('active');
        // Hide Branding Wrapper
        $('.branding-wrapper').fadeThenSlideToggle('slow',function(){
            // Show Web Wrapper
            $('.web-wrapper').fadeThenSlideToggle('slow');
        });
    }
    else if($('.landing-wrapper').is(':visible')){
        // Remove 'active' Class
        $(this).parent().find('li.port-landing').removeClass('active');
        // Add Class 'active'
        $(this).parent().find('li.port-web').addClass('active');
        // Hide Landing Wrapper
        $('.landing-wrapper').fadeThenSlideToggle('slow',function(){
            // Show Web Wrapper
            $('.web-wrapper').fadeThenSlideToggle('slow');
        });
    }

});

// - Internet Marketing - Click Function
$('li.port-marketing').click(function(){

    if($('.marketing-wrapper').is(':visible')){
        // Do Nothing
    }
    else if($('.web-wrapper').is(':visible')){
        // Remove 'active' Class
        $(this).parent().find('li.port-web').removeClass('active');
        // Add Class 'active'
        $(this).parent().find('li.port-marketing').addClass('active');
        // Hide Web Wrapper
        $('.web-wrapper').fadeThenSlideToggle('slow',function(){
            // Show Marketing Wrapper
            $('.marketing-wrapper').fadeThenSlideToggle('slow');
        });
    }
    else if($('.branding-wrapper').is(':visible')){
        // Remove 'active' Class
        $(this).parent().find('li.port-branding').removeClass('active');
        // Add Class 'active'
        $(this).parent().find('li.port-marketing').addClass('active');
        // Hide Branding Wrapper
        $('.branding-wrapper').fadeThenSlideToggle('slow',function(){
            // Show Marketing Wrapper
            $('.marketing-wrapper').fadeThenSlideToggle('slow');
        });
    }
    else if($('.landing-wrapper').is(':visible')){
        // Remove 'active' Class
        $(this).parent().find('li.port-landing').removeClass('active');
        // Add Class 'active'
        $(this).parent().find('li.port-marketing').addClass('active');
        // Hide Landing Wrapper
        $('.landing-wrapper').fadeThenSlideToggle('slow',function(){
            // Show Marketing Wrapper
            $('.marketing-wrapper').fadeThenSlideToggle('slow');
        });
    }

});

// - Branding - Click Function
$('li.port-branding').click(function(){

    if($('.branding-wrapper').is(':visible')){
        // Do Nothing
    }
    else if($('.web-wrapper').is(':visible')){
        // Remove 'active' Class
        $(this).parent().find('li.port-web').removeClass('active');
        // Add Class 'active'
        $(this).parent().find('li.port-branding').addClass('active');
        // Hide Web Wrapper
        $('.web-wrapper').fadeThenSlideToggle('slow',function(){
            // Show Branding Wrapper
            $('.branding-wrapper').fadeThenSlideToggle('slow');
        });
    }
    else if($('.landing-wrapper').is(':visible')){
        // Remove 'active' Class
        $(this).parent().find('li.port-landing').removeClass('active');
        // Add Class 'active'
        $(this).parent().find('li.port-branding').addClass('active');
        // Hide Landing Wrapper
        $('.landing-wrapper').fadeThenSlideToggle('slow',function(){
            // Show Branding Wrapper
            $('.branding-wrapper').fadeThenSlideToggle('slow');
        });
    }
    else if($('.marketing-wrapper').is(':visible')){
        // Remove 'active' Class
        $(this).parent().find('li.port-marketing').removeClass('active');
        // Add Class 'active'
                $(this).parent().find('li.port-branding').addClass('active');
        // Hide Marketing Wrapper
        $('.marketing-wrapper').fadeThenSlideToggle('slow',function(){
            // Show Branding Wrapper
            $('.branding-wrapper').fadeThenSlideToggle('slow');
        });
    }

});

// - Landing Pages - Click Function
$('li.port-landing').click(function(){

    if($('.landing-wrapper').is(':visible')){
        // Do Nothing
    }
    else if($('.web-wrapper').is(':visible')){
        // Remove 'active' Class
        $(this).parent().find('li.port-web').removeClass('active');
        // Add Class 'active'
                $(this).parent().find('li.port-landing').addClass('active');
        // Hide Web Wrapper
        $('.web-wrapper').fadeThenSlideToggle('slow',function(){
            // Show Landing Wrapper
            $('.landing-wrapper').fadeThenSlideToggle('slow');
        });
    }
    else if($('.branding-wrapper').is(':visible')){
        // Remove 'active' Class
        $(this).parent().find('li.port-branding').removeClass('active');
        // Add Class 'active'
                $(this).parent().find('li.port-landing').addClass('active');
        // Hide Branding Wrapper
        $('.branding-wrapper').fadeThenSlideToggle('slow',function(){
            // Show Landing Wrapper
            $('.landing-wrapper').fadeThenSlideToggle('slow');
        });
    }
    else if($('.marketing-wrapper').is(':visible')){
        // Remove 'active' Class
        $(this).parent().find('li.port-marketing').removeClass('active');
        // Add Class 'active'
        $(this).parent().find('li.port-landing').addClass('active');
        // Hide Marketing Wrapper
        $('.marketing-wrapper').fadeThenSlideToggle('slow',function(){
            // Show Landing Wrapper
            $('.landing-wrapper').fadeThenSlideToggle('slow');
        });
    }

});

});
</code>
Answer: For one you could use more chaining:
<code>// ------------------------------------------------------
// - Portfolio Item Collapse
// ------------------------------------------------------
$('.folio-item').click(function(){
    collapse = $(this).find('.folio-collapse').slideToggle('slow',function(){
        if($(this).is(':visible')){
            $(this).parent().addClass('open');
        }
        else
        {
            $(this).parent().removeClass('open');
        }
    });
});

// ------------------------------------------------------
// - Portfolio Item Hover
// ------------------------------------------------------
$('.folio-item').hover(function(){
    hoveritem = $(this).find('.hover-item').fadeIn('fast');
},
function(){
    hoveritem = $(this).find('.hover-item').fadeOut('fast');
});

$('.folio-screen').hover(function(){
    hoveritem = $(this).find('.launch').fadeIn('fast');
},
function(){
    hoveritem = $(this).find('.launch').fadeOut('fast');
});
</code>
You could remove redundant code:
<code>/* ALL THIS CODE CAN GO AWAY */

if($('.marketing-wrapper').is(':visible')){
    // Do Nothing
}

if($('.web-wrapper').is(':visible')){
    // Do Nothing
}

if($('.branding-wrapper').is(':visible')){
    // Do Nothing
}

if($('.landing-wrapper').is(':visible')){
    // Do Nothing
}
</code>
It's not bad. I'd start there. Your comments take up a lot of space which might give the illusion of verbosity :)


What should an almost empty measure look like in 5/2 time?

Question: I am working on an exercise where I am given a few empty bars along with a time signature; and I am to fill it in with rests following the standard rules.
In 5/2 time, I am given 4 measures, each with a single note.  They are, in order:
half note, whole note, dotted whole note, and quarter note.

Since I do not know any way to group the beats, I was left with no choice but to write the first measure as:
half note, half rest, half rest, half rest, half rest,

the second measure as:
whole note, half rest, half rest, half rest,

the third measure as:
dotted whole note, half rest, half rest,

and the fourth measure as:
quarter note, quarter rest, half rest, half rest, half rest, half rest.

But this looks odd to me; and I have never seen anything like it.  Is this the correct way to fill the measures in with rests?
Comment: @Sarkreth the risk of using a whole rest is that it's also used to indicate a rest for an entire measure.    Of course the real answer is that nobody writes 5/2 anyway :-).
Comment: This book, Complete Elementary Music Rudiments by Mark Sarnecki -- 2nd Edition, does seem to take exercises to extremes!   Maybe you could find a better book that draws its examples from real music?
Comment: This sounds like a homework exercise! But anyway, when in doubt assume 3+2 groupings. Also bars 1 & 4 are short one beat each in your solution.
Comment: @DeanRansevycz It's an exercise out of a book I'm working through, called *Complete Elementary Music Rudiments* by Mark Sarnecki -- 2nd Edition.  I suppose it is a homework exercise, assigned to me by myself.  Also, that was a typo in the first two measures (now fixed).  But other than that is this the best I can do?
Comment: @DeanRansevycz Also, forgive my bad wording, but by "I do not know any way to group the beats" I meant I do not know of any way to group the two half-rests together into one rest, like how I would group three eighth-rests into a dotted quarter rest in 6/8 time.
Comment: well, just as there are "half notes" and "whole notes", there are "half rests" and "[whole rests](https://www.google.com/search?q=whole+rest&rlz=1C1CHBF_enUS741US741&oq=whole+rest&aqs=chrome.0.0l6.1280j0j7&sourceid=chrome&ie=UTF-8)"
Comment: See also this discussion:  https://www.ars-nova.com/Theory%20Q&A/Q143.html
Comment: @CarlWitthoft That was exactly my concern about the whole rest.  I was stuck doing nothing but writing a string of half rests.  If nobody writes 5/2, then perhaps that's why it looks so strange to me.
Comment: @CarlWitthoft i agree with the comment in that link on ars-nova.com that the important part is clarity.  The best part about writing to yourself is you can make up your own conventions.
Comment: I have seen music written in 3/2 time, and I remember that a note with duration of the whole measure was written as a dotted whole, but I don't remember example of the measures.
Answer: 5/2 is an odd time signature.  There are two normal ways to group the 5 beats, either as 2+3, or as 3+2.
How will you know which grouping to use? It depends where the accent near the middle of the measures falls — you could tell if there was some actual music, but it doesn't make much sense that one would be preferred in this abstract exercise.

Either way, to complete the measure with rests you should use the same method:

First, complete the beat.

Then, add beats to complete the group — like the midpoint of a measure in an even time signature.
(I've used dashed barlines to show the groupings in the examples below)

Lastly, complete the measure.

Here's how the measures should look:
(I've reordered the examples so that the notes gets bigger each measure)

Using a 2+3 grouping:

Note: The last measure doesn't show the grouping with a dashed barline because the dotted whole note is too large — you could write the dotted whole note as a whole note tied to a half note if you really need to show the grouping.

Using a 3+2 grouping:

The whole note rests won't get mistaken for whole measure rests because in 5/2 a whole measure rest is written with a different symbol:
Comment: The name of the different symbol is "breve rest" or "double whole rest."
Answer: If there's a consistent 2+3 or 3+2 grouping (i.e. if the piece could have been notated as pairs of either 2/2 + 3/2 bars or 3/2 + 2/2 ones)  follow that grouping.
In real life (though maybe not in an examination) and in the special case of a single note at the beginning or end of the bar, I'd be inclined to fill it with the minimum number of rests regardless.
Answer: I have seen examples of dotted measures, but this is often hard to read, as it is not easy to see the dot combined with a measure. The most common is to fill out with rests separately. Since the whole rest is usually used to notate rest for the entire measure, no matter what the time signature is, you are right to fill out with half rests, as these are the largest rest value you have for using in part of a measure where it is not rest for the whole measure.
Since rest is just meaning "do not play", you do not need to combine them in any way, as you would need for notes. If you do the same for notes, you need to tie them together, because otherwise it would be separate notes played each with a new stroke. For rests, this is not necessary because two separate rests sound the same as one combined rest with same total duration (i.e., two separate quarter rests is exactly the same as one half rest). Because of this, there is no concept of tying rests together.
Answer: The convention in 5-time is to group the beats either in a 3-2 or 2-3 pattern, depending on where the musical emphasis goes. When filling out a measure, it is desirable to use the largest notations that express the division. However, in this case, it's a bit visually confusing for a measure to have both half and whole rests. Thus, for the exercises in question:
X: 1
T:
K: none
M: 5/2
L: 1/2
[K: clef=perc stafflines=1] B z2 z2 || B2 z3 || B3 z2 || B/2 z/2 z2 z2 ||

Comment: Personally, I would prioritize clear subdivisions of the measure over avoiding half & whole rests in the same measure.  So I would be disinclined to use your second measure in a measure that was grouped as 3+2, since the dotted whole rest crosses the subdivision between the "3" and the "2".  Similarly, I would be disinclined to use any of the others in a measure that was grouped as 2+3.


How can I prevent my layout from disrupting when a Javascript function runs?

Question: I've just added a Javascript function of changeText to make my site have the accessibility feature of making text larger in order for visually impaired users to be able to use my site with more ease. However upon clicking on the icon for 'larger text' which runs the javascript, it messes up my layout. How can I correct this? Would it be CSS? Here is the website:
[www.me14ch.leedsnewmedia.net/slate][1]
and the enlarge text icons are to the right hand side of the header. Or if this helps, this is the code:

And the Javascript:
function changeText(size) {
var obj = document.getElementsByTagName('html')[0];
obj.style.fontSize = size + '%';

}
Comment: yes but this is for a university brief and so we have to cater for people using screens such as a mobile phone which may not have a zoom function for example. annoying but what we have to do!
Comment: Wouldn't visually impaired persons use the zoom feature of their browser? Zoom avoids most of the layout problems that you noted.
Comment: Then I recommend live editing using the Chrome browser. Via the developer panel, it allows you to emulate various mobile devices and also edit the CSS.  This is a much easier and faster way to see what works and what doesn't.  Then you incorporate those working changes into the actual css.
Answer: Your div#font-size-buttons is inheriting your new font-size:150% rule, which pumps up its height to 48px after click.
To combat this you need to fix it height to let's say 32px, as so:
#font-size-buttons {
  float: right;
  clear: both;
  margin-right: 5px;
  font-size: 32px;
}

Hope this helps
EDIT:
You'll need these too:
.intro {
  clear: both;
  text-align: left;
  padding: 4px;
  line-height: 1.5;
}
.subgroup1 {
  width: 64.54%;
  float: left;
  margin-bottom: 25px;
  margin-top: 5px;
}

(I removed fixed height from .subgroup and decreased margin, to make div more "elastic")
#footer {
  max-width: 1000px;
  width: 100%;
  color: black;
  bottom: 0;
  position: relative;
  font-family: arial, palatino sans-serif;
  font-size: 0.75em;
  text-align: center;
  background: #A3CC39;
  clear: both;
  border-radius: 5px;
}

(Again - removed height:20px from footer to make div adjusts itself)
Comment: fab that helped solve one part of the problem thank you! do you know how I can solve the bottom half of my page layout disrupting?
Comment: Your main problems there are fixed heights on elements - your containers are not flexible enough to accomodate changes to their content. See my edits - give it a go and let me know if it worked for you
Answer: Looking at the website yes you need to add css to it to draw your website and limit part of the website so the js does not affect things you dont want to.
but you would need to provide more code of your website so we can help you
Comment: Would you be able to use inspect element to see my code? Because its very long to paste in! :)
Answer: I looked quickly and changing you whole css would be too long so the workaround I suggest is that your + and - only change your wrapper div as this is your main content. For this change in your js to be

and in the body change

to be

The last thing will be in your css to replace .wrapper by #wrapper to keep the same style you created.
Hope this will help


Archery without a range

Question: I would like to play with a bow, mostly for the discipline and relaxation that is demanded (from what I heard). Problem is there is no range around. I have a 13 x 11 m backyard, and including a corridor I can have about 20 meter of total lenght.
Is that enough for getting some practice? How much distance is needed for hobbish archery?
Comment: I'd be a lot more concerned about making sure you've got a means of controlling overshot and errant arrows, before you make sure you've got enough distance.
Comment: Taking the long dimension and assuming you have a decent pull strength on your bow, if you were standing 13m away from your target, your backstop would not catch any arrows fired more than about 11 degrees too high. It might be okay once you got your eye in, but 10 degrees in archery is not all that much to miss by when you're not familiar with the distance or the bow. I foresee this resulting in an arrow sailing over the fence into someone else's backyard.
Comment: I have 2,5 meter high brick wall around the backyard, I thought that it was enough? Am I mistaken?
Answer: I would advise not using a back garden because it is really easy to miss and it doesn't take much to distract an archer, especially if you have not had practice at a range.
To answer your question, a standard archery range is between 12 and 16m. When I last taught it (this summer) I had kids shooting at targets between 8 and 20, and even the best archers amongst staff and students would not hit it 3 times out of 5 (Its classed as a fluke if any less in my eyes)
When I was learning to shoot I went out to a farmers field near me and asked the owner if I could shoot at his hay bails. Always shooting away from animals and any roads I learnt quickly enough and knew I wanted to stick with it.
If you are in the city, colleges(university's) tend to have archery clubs. You will have to contact them and maybe even get insurance for it, but that is the way I train at the moment.
Whatever you do, just be safe about it. You only need 1 arrow to go wrong.
Answer: You can always shoot from the backyard into the corridor... as long as you don't have anything and anyone in it and you put a good light close to the target.
Just be ready to have some holes on the door at the end of the corridor...

Archery without a range


Probability model vs statistical model vs stochastic model

Question: I understand that a statistical model is a model which accounts for the uncertainty in the model. Eg. Demand price equation: $demand_{i}= a+b price_{i}+ u_{i}$ where $u_{i}$ refers to the residual term.
How to differentiate the other two models from a statistical model?
Answer: Many times there is observable phenomena that is random in nature. We call it a Random Process (Random Experiment). The random process has outcomes, and subsets of these outcomes are called events. We map these events to a numeric form using Random Variables.
We study and capture our knowledge about this random process by creating a Stochastic Model. The stochastic model predicts the output of an event by (1) providing different choices (of values of a random variable) AND (2) the probability of those choices. These two elements are summarized as a Probability Distribution.
This distribution has some parameters (like mean, standard deviation) which were inferred from the observable phenomena using Statistical Inference.
Before inference, the distribution had unknown (not inferred yet) parameters. It was, hence, a family of distributions, since each value of the parameter is a different distribution. This family is called a Statistical Model.
Usually a statistical model is guessed (exponential, binomial, normal, uniform, bernoulli, etc) using Exploratory Data Analysis, then its parameters are inferred (estimated) by applying statistical inference (say, algorithms involving loss function minimization) to arrive at a stochastic model (statistical model with known parameters) (a.k.a. Estimator) that captures our knowledge about the random process.
The term 'Probability Model' (probabilistic model) is usually an alias for stochastic model.
References:
1 Using statistical methods to model the fine-tuning of molecular machines and systems
Steinar Thorvaldsen, Ola Hossjer
[2] Statistics (Point Estimation) - Lecture One Charlotte Wickham - Berkeley


Equal regression coefficients in a mean zero stationary process

Question: Problem
I have a stationary stochastic process $\{Z_t\}$, where $\mathbb{E}(Z_t) = 0$, $\forall t=0,1,2,\cdots$.
Say I would like to perform linear regression on $Z_{t+k}$ by $Z_{t+k-1}, \cdots Z_{t+1}$, for some integer(lag) $k>0$, i.e.
$$
\mathbb{E} (Z_{t+k} | Z_{t+k-1}, \cdots Z_{t+1}) = \xi_1 Z_{t+k-1} + \cdots + \xi_{k-1} Z_{t+1}
$$
And I would also like to perform linear regression on $Z_t$ by $Z_{t+1}, \cdots Z_{t+k-1}$,
$$
\mathbb{E} (Z_t | Z_{t+1}, \cdots Z_{t+k-1}) = \psi_1 Z_{t+1} + \cdots + \psi_{k-1} Z_{t+k-1}
$$
then, I would like to show
$$
\xi_i = \psi_i
$$
for $i=1, \cdots, k-1$.

Try
I have noticed that $(\xi_1, \cdots, \xi_{k-1})$ minimizes the error
$$
\mathbb{E} \left[ (Z_{t+k} -  \xi_1 Z_{t+k-1} - \cdots - \xi_{k-1} Z_{t+1})^2 \right]
$$
and $(\psi_1, \cdots, \psi_{k-1})$ minimizes the error
$$
\mathbb{E} \left[ (Z_t -  \psi_1 Z_{t+1} -\cdots - \psi_{k-1} Z_{t+k-1})^2 \right]
$$
but I'm stuck at how I should proceed.
Answer: Note that
$$
\begin{aligned}
\mathbb{E} \left[ (Z_{t+k} - \xi_1 Z_{t+k-1} - \cdots - \xi_{k-1} Z_{t+1})^2 \right]  &=\mathbb{E} \left[ Z_{t+k}^2 -  \xi_1 Z_{t+k}Z_{t+k-1} - \cdots + \xi_{k-1}^2 Z_{t+1}^2 \right] \\
&= \mathbb{E} \left[ Z_{t+k}^2 \right] - \xi_1 \mathbb{E}\left[  Z_{t+k}Z_{t+k-1}\right] - \cdots + \xi_{k-1}^2\mathbb{E}\left[ Z_{t+1}^2 \right] \\
&= \mathbb{E} \left[ Z_t^2 \right] -\xi_1 \mathbb{E}\left[  Z_tZ_{t+1}\right] - \cdots + \xi_{k-1}^2 \mathbb{E}\left[ Z_{t+k-1}^2 \right] \\
&= \mathbb{E} \left[ (Z_t -  \xi_1 Z_{t+1} -\cdots - \xi_{k-1} Z_{t+k-1})^2 \right]
\end{aligned}
$$
So let us suppose that $\exists! (\xi_1^\ast, \cdots, \xi_{k-1}^\ast)$ that minimizes the the above error.
Then the parameter vector also minimizes
$$
\mathbb{E} \left[ (Z_t -  \psi_1 Z_{t+1} -\cdots - \psi_{k-1} Z_{t+k-1})^2 \right]
$$
thus, if we denote $\exists! (\psi_1^\ast, \cdots, \psi_{k-1}^\ast)$ as the parameter vector that minimizes the above error, we have
$$
(\xi_1^\ast, \cdots, \xi_{k-1}^\ast) = (\psi_1^\ast, \cdots, \psi_{k-1}^\ast)
$$


How to load a textfile on a string

Question: I am not very good at jquery and i am having some trouble to load a text file and show it on a string.
Here is the code:

This is what i try:

As you can see this maybe does not make sense.
Sorry for any english mistakes.
Thank you.
Answer: The $.get is asynchronous. This means that the typed() object is instanciated before the data is retrieved. With any AJAX request, any code that depends on its result must be placed in the callback. Try this:
$.get('file.txt', function(data) {
    alert(data) //just to se that it has loaded.
    $("#typed").typed({
        strings: data,
        typeSpeed: 50,
        backDelay: 500,
        loop: false,
        loopCount: false,
        callback: function() {
            foo();
        },
        resetCallback: function() {
            newTyped();
        }
    });
});

Also note that from the Typed documentation that the strings property needs to be an array of strings, not HTML as your current AJAX request is returning.
Comment: thank you, it worked. Now i see why it did not work. Thank you again.
Comment: No problem, glad to help.

How to load a textfile on a string


Show that $\pi_{n}(B)$ is isomorphic to $\pi_{n}(E)$.

Question: Let $(E, p, B)$ be a covering space with $B$ and $E$ both path-connected. Show that for all $n \geq 2,$ $\pi_{n}(B)$ is isomorphic to $\pi_{n}(E)$. Could anyone give me a hint for the solution please?
Comment: For a covering map $p:E\to B$ where $B$ and $E$ are path-connected, note that $p$ is a fibration with discrete fiber $F$.  (Path-connected of $B$ and $E$ is important; otherwise, $p$ might not be a fibration.)  For a discrete space $F$, $\pi_n(F)$ is trivial for every positive integer $n$.  Then you can use the same argument as in my answer here: https://math.stackexchange.com/questions/3379347.
Comment: @WETutorialSchool could you please look at this question also https://math.stackexchange.com/questions/3379461/calculating-pi-1x/3379839?noredirect=1#comment6954756_3379839
Comment: In regard to your fist comment ..... will I use that theorem that "If $0 \rightarrow A \rightarrow B \rightarrow 0$  is exact with a map$ h: A \rightarrow  B$, then $h$ is an isomorphim "@WETutorialSchool
Comment: Yes, that is exactly why $\pi_n(E)\cong \pi_n(B)$ for $n>1$.
Answer: Hint: Lifting property of covering spaces.
Comment: where can I find a good explanation for it?
Comment: It's usually proved in any introduction to covering spaces. See proposition 1.30 in Hatcher's book.
Comment: And how can we relate it to long exact sequences? Do you have a reference for this?
Comment: You don't need to worry about the long exact sequence. Your statement is literally a consequence of the lifting property. Look it up.
Comment: My professor said that the proof includes using long exact sequences ... but I can not see why?
Comment: You need the homotopy lifting property to use the long exact sequence, so using the sequence feels backwards. Still, if you insist: The long exact sequence involves homotopy groups of three spaces, $B$, $E$ and $F$. Show that most of the groups of $F$ are trivial.
Comment: How do I need the homotopy lifting property to use the long exact sequence?
Comment: Is the question I am asking is proposition 4.1 in Hatcher?


Problem installing WPT manifest using wevtutil

Question: I'm trying to add performance counters and custom events to a piece of software, so that I can view these using Windows Performance Toolkit programs such as XPerf and GPUView.
  I am going to refrain, using all my powers of restraint, from launching into a cathartic rant regarding the state of the documentation for the software and the time I've now wasted trying to tease clues from the web. I'm going to describe how I got to where I am now, just in case this is of use to other lost souls.
So far, I've gathered that I have to write an Event manifest for my performance counters and events. You can do this by hand or by using a tool called 'ecmangen.exe'. The documentation for that program gives a nice step by step guide for event creating manifests but doesn't explain how to integrate these with your code.
The next step, as far as I can work out, is to use two cryptic command line applications 'MC.exe' and 'CTRPP.exe'. These seem to generate C or C# headers, source and resource files for adding event and counter instrumentation to your code, respectively.
  Next, you have to build your code (look at the samples in 'C:\Program Files\Microsoft SDKs\Windows\v7.1\Samples\winbase\Eventing') and then we come to where I'm currently stuck: the correct use of the next cryptic tool 'wevtutil.exe'
This tool needs two things: the binary (exe or DLL) that you've compiled with those resources in it and the manifest file you used to generate those resources. The trouble I'm having is that it's very picky about where the binary file is and I've been unable to determine the form of this pickiness. Incantations and goat sacrifices have yielded no results.
If I have a path defined in the 'resourceFileName' field of the 'provider' tag in the manifest file such as 'c:\MYDIR\TEd.exe' then it is fine. If, however, I put the same exe in a different folder (one that failed was C:\tw\TEd.exe), it complains.
The error message given is 'Warning: Publisher TEd-Event-Provider resources are not accessible.' but no more explanation as to why, or where it tried to look.
So, am I going about adding instrumentation in the wrong way, is there already a guide that explains all the gotchas and what is the nature of 'wevtutil.exe's strange selectivity towards directory names.
Thanks in advance,
Tim.
Answer: I've just had exactly the same message, and struggled for an hour to resolve it, before I had a brainwave and read the error msg ;-).
The solution to my problem was simply to add the ".rc" file to my project, and then re-build.  Looking back it is fairly obvious, but it had me stumped for a while.
Hope this helps.

Edit - 4th Feb
Ok, not too sure if I know what your problem is, but the following batch script is how I did it all.  Good luck.
rem -------------------------------------------------------------------
rem Do all of this from the project directory

rem -------------------------------------------------------------------
rem Generate Header and Resource - remove the ReadOnly attrib to "help" it along
attrib -r MyModuleTracing.h
mc.exe -um MyModuleTracing.xml
rem This generates MyModuleTracing.h and MyModuleTracing.rc, add both to your project

rem -------------------------------------------------------------------
rem ** Now build the project **
rem -------------------------------------------------------------------

rem Register MyModule Tracing with the system
if exist MyModuleTracing.xml (
  wevtutil um MyModuleTracing.xml

  copy MyModuleTracing.xml Release
  cd Release
  copy MyModule.dll %SystemRoot%\System32
  wevtutil im MyModuleTracing.xml
)

rem -------------------------------------------------------------------
rem Do a capture, and also export the results to an XML file.
xperf -start MyModuleSession -on [REPLACE_WITH_YOUR_GUID] -f MyModuleSession.etl
xperf -on base -f Kernel.etl

rem Run the app, wait until exit, and then stop the capture
start /wait MyModule.exe

xperf -stop
xperf -stop MyModuleSession
xperf -merge MyModuleSession.etl Kernel.etl MyModuleSessionMerged.etl

tracerpt MyModuleSessionMerged.etl -o MyModuleSessionMerged.xml -of XML

Comment: What's stumping me is the fact that it works if the output dir is in one place but not in another place.
Comment: Thanks Rich, I'll try that out tomorrow.
Comment: I've got all of mine working now, so if you still can't get yours working, let me know and I'll describe what I've done.
Comment: Ah, still no dice. I was already adding the '.rc' files, at least the two named 'XXXXX_manifest.rc' and 'XXXXX_profile_events.rc'.
Answer: I had the same problem - as best I can tell, there's a directory length limit on wevtutil. When I installed the file from a directory with a shorter path, it worked.
Answer: In case anyone else comes across this, you can actually get things working from an arbitrary directory:
Add USER Read&Execute privs to a directory containing or above your project:

icacls projectdir /grant BUILTIN\Users:(OI)(CI)(RX)

Then installing the manifest should work with no errors:

wevtutil im yourmanifest.man /rf:c:\full\path\to\yourprogram.exe /mf:c:\full\path\to\yourprogram.exe


Making Selenium work with bug reporting software

Question: I've developed an automated test application with Selenium (using Python) and I was wondering if there was a way to automatically generate a bug report in a bug tracker such as Mantis. I have looked on Google but no luck so far.
I want to be able to track the bug (open, resolved, ongoing) once generated and assign it to a person or a team.
Comment: Yep, that's possible. The actual implementation will depend on the bugtracker you're using. Mantis, for example, [exposes a SOAP API](https://www.mantisbt.org/docs/master-1.2.x/en/administration_guide.html#ADMIN.CONFIG.SOAP) for doing things like reporting issues.
Comment: Thank you for your answer and sorry if i'm abusing of your kindness but could you provide me with an example? Or some guidance on how to implement it in python?
Answer: Thanks to Carsten answer i was able to find
http://wiki.opencsw.org/file-bugs-via-a-script
and my implementation is going forward. It seems that mantis is the best tool for my need.


Vertical divider between columns in Shiny

Question: I have a Shiny application in which I would like to have a vertical divider (vertical line) between some UI elements that are all in the same fluidRow().  In the very trivial example (below), I would like to see this:

I've found a few suggestions of how to do it with CSS, but I can't find a way to integrate those into my Shiny app.  (I don't know CSS, obviously.)  The actual app is currently using shiny, shinydashboard, and shinydashboardplus, if that helps.
library(shiny)
library(shinydashboard)

ui <- fluidPage(

    # Application title
    titlePanel("Divider example"),

    mainPanel(
        fluidRow(
            column(12,
                plotOutput("distPlot")
            )
        ),
        fluidRow(
            column(6,
                   sliderInput(inputId = 'sldNumPts', min = 10, max = 1000,
                               value = 50, label = 'Number of Points')
            ),
            column(6,
                   sliderInput(inputId = 'sldBreaks', min = 10, max = 50,
                               value = 10, label = 'Number of Breaks'),
                   radioButtons(inputId = 'rdoColor', label = 'Color',
                                choices = c('red', 'green', 'blue'),
                                inline = TRUE)
            )
        )
    )
)

# Define server logic required to draw a histogram
server <- function(input, output) {

    output$distPlot <- renderPlot({
        hist(rnorm(input$sldNumPts), breaks = input$sldBreaks,
             col = input$rdoColor, border = 'white')
    })
}

# Run the application
shinyApp(ui = ui, server = server)

Answer: You can add CSS through the style argument. In this case, you can add a border in column within your ui:
library(shiny)
library(shinydashboard)

ui <- fluidPage(

  # Application title
  titlePanel("Divider example"),

  mainPanel(
    fluidRow(
      column(12,
             plotOutput("distPlot")
      )
    ),
    fluidRow(
      column(6,
             sliderInput(inputId = 'sldNumPts', min = 10, max = 1000,
                         value = 50, label = 'Number of Points')
      ),
      column(6,
             sliderInput(inputId = 'sldBreaks', min = 10, max = 50,
                         value = 10, label = 'Number of Breaks'),
             radioButtons(inputId = 'rdoColor', label = 'Color',
                          choices = c('red', 'green', 'blue'),
                          inline = TRUE),
             style = 'border-left: 1px solid'
      )
    )
  )
)

For more information on integrating CSS into your shiny app, refer to this resource.


Do random forests work better than multinomial logistic regression for prediction of categorical non-binary variables? Why?

Question: I posted another question that was well received. I am posting this new question because it was suggested by other members of Cross Validated. Here is the link of the original question that I posted: In R Linear Regression , a categorical variable is changed to numeric to build a model. Would that trick work to predict a categorical variable?
Do Random Forests work better than Multinomial Logistic Regression for Prediction of Categorical Non-Binary Variables? Why?
In the previous question was suggested that Multinomial Logistic Regression works better for inference and that Random Forest works better for prediction. One of the goals of this question is to learn more about that answer.
***Also, I would like to learn the R code for Multinomial Logistic Regression. In the other question, I published a R code for Linear Regression that worked well, in the sense that I got no warnings, but the results had no sense according to @RobertLong This question is a follow up of the previous question.
The data is in the following link: Data for this question
I am trying to predict the last column called classe.
***With random forests I get 99% of accuracy. It is difficult to improve that. However, I would like to compare it with multilinear logistic regression. Also, I would love to learn more about strengths and weaknesses of multilinear logistic regression for this kind of problem. ***
Here is my new code with the random forests algorithm. It seems that everything is right because I am getting 99% accuracy.
<code>library(caTools)
library(randomForest)
library(ggplot2)
library(caret)
library(lattice)

dataset <- read.csv("data.csv", header=T)
set.seed(1234)
dataset <- dataset[, -c(1:7)]

#only keep columns with at least 50% non-blanks

dataset <- dataset[, colSums(is.na(dataset)) < nrow(dataset) * 0.5]

# Keep only the complete rows
dataset <- dataset[complete.cases(dataset), ]

#We eliminate zeroVar and nearZeroVar columns

x = nearZeroVar(dataset, saveMetrics = TRUE)
str(x, vec.len=2)
dataset <- dataset[!x$zeroVar]
 x = nearZeroVar(dataset, saveMetrics = TRUE)
str(x, vec.len=2)
dataset <- dataset[!x$nzv]

write.csv(dataset, file="data.csv")
dataset <- read.csv("data.csv", header=T)
dataset <- dataset[, -1]

#classe is opened as chr but it is a categorical variable

dataset$classe<- factor(dataset$classe)

#We divide our data in a training set
#and a testing set

split= sample.split(dataset$classe, SplitRatio = 7/10)
training_set = subset(dataset, split==TRUE)
testing_set = subset(dataset, split==FALSE)

#We train our model with the training set
##At this point we have 53 variables. 52 predictors.
#We need to use a number close to
#sqrt 52
#We are going to use 7

rf_mod <- train(
  classe ~ .,
  data = training_set,
  metric = "Accuracy",
  method = "rf",
  trControl= trainControl(method="none"),
  tuneGrid = expand.grid(.mtry=7)
 )

 #We measure the accuracty of our model
 #with the testing set

 rf_pred <- predict(rf_mod, testing_set)
 confusionMatrix(rf_pred, testing_set$classe)
</code>

@Sycorax wrote that we cannot generalize. I agree and disagree at the same time. I agree with his idea that everything depends on the kind of problem. However, I disagree because my question has some particular features that affect the algorithm performance. I am a beginner, but I am reading the book "Practical machine Learning in R," written by Fred Nwanganga and Mike Chapple. They mention that every algorithm has weaknesses and strengths. As we are predicting a non-binary categorical variable, that affects which one is the best algorithm for that purpose. Additionally, I read that some algorithms do not work well with "a large" number of continuous features. In this question, we are analyzing this particular dataset, and by extension, datasets similar to this one.
@jluchman asked me a great question: what better means? I am just a beginner, but correct me if I am wrong. In my perspective, linear regression gives us ideas that can be explained easier than results that are obtained with other methods. However, I just bought some new books, and I am seeing that many authors are skipping multinomial logistic regression for this type of problems and they are going more with naive Bayes, random forests, etc. However, I still need to check some linear regression books.
Comment: Random forest is better for problems where random forest does better. Multinomial logistic regression is better for problems where multinomial logisitc regression is better. If you've found that one is better/worse on your problem, then perhaps we can conclude certain properties about your problem, the available data, the choice of features, or the choice of hyper-parameters, but any categorical statements about the utility of the methods across all problems would be overstated.
Comment: Multinomial logistic regression is machine learning…
Comment: You might want to review how multinomial logistic regression relates to logistic regression before you dive into more sophisticated machine learning models.
Comment: One thing that could help to answer the question is a sense for what "better" means for the use of the model?  Are you seeking to find an easy to explain model for a specific audience?  Are you seeking to find a predictive function that predicts as well as possible for some production application?  I anticipate the best tool for the job likely depends on what the need for the model is.
Comment: Hi, I don't think the constant small edits to this question are beneficial. It's hard to answer a question that's a moving target, and it diminishes the visibility of other questions. This one is already highly visible because of the bounty.
Comment: *"However, I disagree because my question has some particular features that affect the algorithm performance."* This is what I mean when I say "If you've found that one is better/worse on your problem, then perhaps we can conclude certain properties about your problem, the available data, the choice of features, or the choice of hyper-parameters" -- at most, you've found that one method works better for your problem than an alternative.
Comment: @Sycorax Thank you for your ideas! I added your ideas to my question, and I will write why I disagree and agree at the same time.
Comment: Thank you Sycorax for expanding your comment! Excellent ideas!
Comment: @jluchman Thank you for your ideas! I will answer your question, and I will add some ideas in the main section of the question.
Comment: @AryaMcCarthy Please accept my apologies. I promise to not do it again.
Answer:
Random forest is better for problems where random forest does better. Multinomial logistic regression is better for problems where multinomial logisitc regression is better. -Sycorax (in the comments)

This is really all there is to it, but it might help to unpack this comment.
If you have a relationship that (at least approximately) follows the multinomial logistic model, then that is the (approximately) correct model. It might be that  a random forest can achieve high in-sample performance, but when it comes to making out-of-sample predictions, it will have achieved that awesome performance by fitting to coincidences in the training data rather than the true relationship between the features and the outcome. In such a scenario, the logistic regression outperforms the random forest, even in terms of pure predictive ability, contradicting your source.
To be fair to your source, however, relationships in real life tend to be complicated. Simple models like multinomial logistic regressions are likely to miss important relationships that flexible models like random forests are able to detect. If you control for overfitting concerns, then letting a random forest "go do its thing" might make for a better out-of-sample predictor.
Yes, there are theorems like Stone-Weierstrass saying that (generalized) linear models with polynomial features can be as good at approximating nonlinear relationships as is demanded (under decent conditions), but you have to engineer those polynomial features and know which ones to engineer. For a random forest, all you do is program considerable flexibility and let it take care of the rest (for better or for worse).


If $|X|=n$ then $S_X \cong S_n$

Question: I would appreciate if you could please express your opinion on this proof. The proof appears to be "self-evident", but, as it often happens with one trying to gain more algebraic maturity, it may not be rigorous enough, especially when it comes to apparently the most simple of things.
Proof:
$S_X$ is a group of permutations on the set $X$, thus $|S_X| = |X|! = n!$. This implies that a bijection exists between $S_X$ and $S_n$. Hence, $S_X\cong S_n$.
Comment: What is your definition of $S_n$? What you should be proving is that if $X$ and $Y$ are any two sets with $|X|=|Y|$, then $S_X \cong S_Y$. You cannot sensibly define $S_n$ until you have proved that! But the main problem with your proof is that the existence of a bijection between two groups does not guarantee that they are isomorphic as groups.
Comment: Presumably you mean the group of all permutations of $Y$. But according to your proof, $S_3$ is isomorphic to the cyclic group of order $6$, because they both have order $6$.
Comment: Hint: To solve this problem you have to have a rigorous definition of $S_X$ where $X$ is an arbitrary set. To try and arrive to such a definition. What is a permutation of $Y=\{1,..,n\}$?
Comment: If $Y$ is a set of $n$ integers, defined as $Y = \{1,...,n\}$, then $S_Y = S_n$ is a group of permutations on $Y$. Thus $S_X\cong S_Y=S_n$.
Comment: The idea that if two symmetric groups have the same order, they must be isomorphic. Please correct me if I'm wrong.
Comment: A permutation of $Y$ is an element $\sigma\in S_n$, correct? $S_X$ is a set of all $\sigma\in S_n$ of order $n$.
Comment: Your answer is like answering the question of "What is a bird?" by saying "it is an element of the set of birds".  There should be a definition of a permuation not refering to the set permutations.
Comment: A permutation is a bijective function $\rho: X\to X$.
Answer: Let me try to spell out what has been said in the comments.
Showing that two groups are isomorphic involves exhibiting an isomorphism between them. As noted in the comments, you need to identify the groups involved: Let $X$ be a set. The group $S_X$ is the set of all bijections $X\to X$ with multiplication given by composition of functions.
Now, let $X$ and $Y$ be two sets of order $n$. It is not enough that $|S_X|=|S_Y|$ since an arbitrary bijection between the two need not be a homomorphism. You need to produce a bijection that is.
Try this: Let $\gamma:X\to Y$ be any bijection. Define a map $\Phi_\gamma:S_X\to S_Y$ by
$$\Phi_\gamma(\sigma)=\gamma\circ\sigma\circ\gamma^{-1}$$
You need to show that $\Phi_{\gamma}(\sigma\circ\tau)=\Phi_\gamma(\sigma)\circ\Phi_\gamma(\tau)$ and that $\Phi_\gamma$ is bijective (hint: show that $\Phi_\gamma^{-1}=\Phi_{\gamma^{-1}}$).
Comment: Why does showing that $\Phi_\gamma^{-1}=\Phi_{\gamma^{-1}}$ show that the homomorphism is bijective?

If $|X|=n$ then $S_X \cong S_n$


Drupal 7 MultiStep Form

Question: I am trying to implement the Multistep tutorial (Step 9) from http://drupal.org/node/717750 in Drupal 7, however in the following function
function my_module_my_form_new_name($form, &$form_state) {
  $form_state['storage']['new_name'] = TRUE;
  $form_state['rebuild'] = TRUE; // Will cause the default submit function
                                 // to be skipped.
}

I just cant set the $form_state['storage']['new_name'] = TRUE;
therefore i can't catch it in :
 if (empty($form_state['storage']['new_name'])) {
    $form['new_name'] = array(
      '#type' => 'submit',
      '#value' => 'Add another name',
      '#validate' => array('my_module_my_form_new_name'),
    );
  }

I can however declare it in the beginning of the function, which can be executed fine. So how can I set it in Drupal 7?
Comment: You're probably better off looking at a Drupal 7 example instead of Drupal 6. The [examples module](http://drupal.org/project/examples) has many form examples including multi-step.
Comment: Thanks, will do... however why I cant pass the value of a variable $form_state['storage']['new_name'] to the step 2?
Comment: Hopefully someone can answer that for you. I haven't read the tutorial you linked to, just noticed it was for Drupal 6.
Answer: Helpful links for creating multi steps form are https://drupal.stackexchange.com/questions/135/are-there-any-examples-of-setting-up-multistep-forms http://drupal.org/node/717750, and http://drupal.org/project/examples.
I practiced multi step forms by getting the code of the form tutorial from http://drupal.org/project/examples, and added further steps; it works excellently fine for me.
Comment: Hi, thanks for the answer. Since this is a quite old question  I've already found an answer to it, which is actually similar to yours.
Comment: its good to hear

Drupal 7 MultiStep Form


Drupal 8: Node form submit/update - how to redirect to a custom page with an code-based approach different than hook_form_alter()

Question: I have Drupal 8 installation, with a custom content type.
I would like to redirect to a specific page after node form submission.
What I have tried so far:
Using hook_form_alter() and it works, but that's not the point here.
What I want to achieve:
Delivering the same functionality in a new OOP code based way.
What I have found so far:
https://www.thirdandgrove.com/redirecting-node-pages-drupal-8
This example shows the replacement for the old hook_init().
Update 1:
Rules module can achieve the desired functionality.
Update 2:
Node_save_redirect module can achieve the desired functionality.
Update 3: A possible answer
https://www.foreach.be/blog/how-manipulate-forms-drupal-8
can someone with enough D8 experience actually confirm if that's actually the official way of doing things ?
Regards,
Oleg
Comment: Good question - one of the most frustrating things for me in 8, is the hybrid we have between event subscribers and the old hook based system. It's one I truthfully don't understand.
Comment: I'm not sure to be honest. Here are a list of core Drupal events that you subscribe to: https://api.drupal.org/api/drupal/core!core.api.php/group/events/8.3.x - there are `EntityTypeEvents` to subscribe to (create, edit and delete). Very little documentation however, and I'm not sure if this event is fired with instances of an entity type or the entity type itself - it might be worth investigating.
Comment: Good luck with it all. An article I found which is quite good at explaining hooks versus event listeners is this one https://knpuniversity.com/screencast/drupal8-under-the-hood/events-versus-hooks
Comment: And another good article - https://www.previousnext.com.au/blog/alter-or-dispatch-drupal-8-events-versus-alter-hooks
Comment: yes, this particular question is about form redirect but the topic is way more generic.... OOP altering a form. BrynJ, based on your answer I assume there is no way to do it OOP?
Comment: Oh, thanks...I've missed that link. This is quite enlightening. I am definitely going to investigate these events very soon and maybe even write a blog post about it.
Answer: A route subscriber doesn't work so well because the route 'entity.node.edit_form' uses an entity form.
One approach would be to use hook_entity_type_alter to change the edit form:
function mymodule_entity_type_alter(array &$entity_types) {
  $handlers = $entity_types['node']->get('handlers');
  $handlers['form']['edit'] = 'Drupal\mymodule\Form\CustomNodeEditForm';
  $entity_types['node']->set('handlers', $handlers);
}

Then you could override the save function of the node.
namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeForm;

class CustomNodeEditForm extends NodeForm {

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    parent::save($form, $form_state);

    $node = $this->entity;

    if ($node->id()) {
      if ($node->access('edit')) {
        $form_state->setRedirect(
          'entity.node.edit_form',
          ['node' => $node->id()]
        );
      }
      else {
        $form_state->setRedirect('<front>');
      }
    }
  }

}

This is heavy-handed and risks conflicts with other customizations, but it assures that the redirects are set in the same place they're set as the node edit form, and are therefore fired before other handlers added by other modules.
A simpler approach is to simply to add another submit handler in form alter.
Answer: While the other solution is perfectly valid, I mark this answer as accepted since it comes closer to what I was looking in first place - the new way to alter forms.
Eventually the solution can be found right here:
https://www.foreach.be/blog/how-manipulate-forms-drupal-8
In summary (quoted from the article):
1 ) The first step is to write a service that intercepts the original UserLoginForm and directs to the adapted form
2)  Changed the route to return the adapted NewUserLoginForm instead of the original UserLoginForm
3) The new form extends the old form and inside the buildForm method you add in the beginning
$form = parent::buildForm($form, $form_state);

This step was missing in the example tere
Answer: This functionality can easily be implemented using rules. This will ensure your Drupal installation to be upgrade proof.
Start off with installing this module. Once installed, create a new rule to trigger on Node > After saving new content of type {your custom content type}. Set action to System > Page redirect and supply the url and you're done.
Comment: The trade off to using Rules vs a few lines of form alter code is in no way worth it.
Comment: Thanks,
I didn't think about Rules here.
Thanks !
Comment: The problem in the past I had with rules was during the maintenance of a project,where the Rules module didn't have good backwards compatibility...since  then I am kind of hesitating before using it.
Comment: Before marking this as the accepted answer, I would like to see if there is also some code based solution.


Orthogonal sets of variables in multiple imputation --> separate imputation models?

Question: First, thanks to those who gave me useful input on this project in a previous thread on this site.I've got a new-ish question at this point on the mechanics of MI (using MI via chained equations):
I've got three sets of variables that I can reasonably assume to be unrelated.  Lets call set 1 "conditions", set 2 "additions", and set 3 "management".  I've also got an outcome.
My dataset is all randomized controlled trials, and it is reasonable to assume that conditions, additions, and management are all orthogonal to one another -- if there is any correlation between the three, it is spurious in the sense that it wouldn't predict new data, and is essentially a fluke.  (This would not hold with observational data).
Each of these sets of variables has missing data (except the outcome).  Because the sets of variables are orthogonal to one another, I set up three separate imputation models for the three sets.  After all, how could data on "management" predict "conditions"?  Any extra information here is spurious.
But then I read a few papers that said that I should put the outcome in the imputation model.  Thinking about it, I see why it makes sense.  But now I've got a problem:  "management" predicts outcome, and outcome can predict "conditions."  My orthogonality assumption is trashed, isn't it?
The reason that I specified the three separate models is that observations are clustered by "conditions" and "additions", and these two levels overlap.  It was much more convenient to model them separately than to make some complicated multi-level imputation model.
So, beyond requests for general advice on how to think about this sort of problem, my specific question is the following: if the only way that the three sets of variables are correlated is through the outcome, and I control for the outcome in the imputation models, can I proceed as I have been doing without biasing my imputations away from their true (or optimal in some sense) values?
If not, do existing software packages handle MI with this sort of multilevel data?  I've been writing my own code (I usually refuse to use canned software until I've implemented something myself), but I feel like I get the mechanism enough to jump to something canned if I have to.
Thanks in advance.
Answer: Peoples' height tends to influence their weight. Peoples' eating habits tend to influence their weight. That does not necessarily make height and eating habits correlated. This is just the first example I could come up with, so there are issues, but the idea should be clear.
Apart from the example, you might just still have conditional independence:
$$
P(additions | outcome, management) = P(additions | outcome)
$$
All in all, I would boldly state: "dependency is not transitive", so you are perfectly safe to go ahead (assuming your original assumption of independence is indeed valid).
Comment: Thanks for the reply, this is in line with my prior.  I guess I was just wondering whether there was something un-intuitive that I should be thinking about, that I'm not.  Maybe not!


What is the importance of $\pi$ in mathematics?

Question: In what specific fields is $\pi$ relevant in mathematics and how is its accuracy important?
Is there any field in which its precision leads to some results despite others?
Comment: To add to the comment by @Qiaochu, [here is a visualization of his comment](http://www.smbc-comics.com/?id=1777).
Comment: It has been established that no more than seventeen decimal digits are used by the NASA for their universal positioning system. So more decimal digits mean nothing, it has only recreational characteristics now.
Comment: $\pi$ is extremely important but it's extremely unimportant to determine its digits.
Comment: $\pi$ shows up in math wherever circles are present or hiding. Be it geometry, calculus, Fourier theory, probability, number theory, ...
Comment: There is no value in finding more and more digits. Just bragging rights and possibly accidental mathematical discoveries that allow for faster computation. In particular, base 10 is a completely arbitrary means of representing real numbers.
Comment: While base 10 might be arbitrary, its computation can give hint toward proving certain conjecture, such as whether $\pi$ is a normal number: http://en.wikipedia.org/wiki/Normal_number
Comment: Write on Google videos: the number pi. Several documentary programs
Answer: The Quest for Pi. David H. Bailey, Jonathan M. Borwein, Peter B. Borwein and Simon Plouffe, Mathematical Intelligencer, vol. 19, no. 1 (Jan. 1997), pg. 50–57
In one of the earliest accounts (about 2000 BC) of π, the Babylonians used the approximation
$3 \ 1/8 = 3.125$. At this same time or earlier, according to an account in an ancient
Egyptian document, Egyptians were assuming that a circle with diameter nine has the
same area as a square of side eight, which implies $π = 256/81 = 3.1604\ldots$ In the 1700s the mathematician Euler, arguably the most prolific mathematician in history, discovered a number of new formulas for π. Among these are
$$
\dfrac{\pi^2}{6} = \sum_{n=1}^{\infty}\dfrac{1}{n^2}, \quad \dfrac{\pi^4}{90} = \sum_{n=1}^{\infty}\dfrac{1}{n^4}
$$
These formulas aren't very efficient for computing π, but they have important theoretical
implications and have been the springboard for notable research questions, such as the
Riemann zeta function hypothesis, that continue to be investigated to this day. One motivation for computations of π during this time was to see if the decimal expansion
of π repeats, thus disclosing that π is the ratio of two integers (although hardly anyone
in modern times seriously believed that it was rational). This question was conclusively
settled in the late 1700s, when Lambert and Legendre proved that π is irrational. Some
still wondered whether π might be the root of some algebraic equation with integer coefficients (although as before few really believed that it was). This question was finally settled in 1882 when Lindemann proved that π is transcendental...
Send an e-mail to receive firstname.lastname@example.com the full article.
Answer: $\pi$ itself appears in many equations, from circles to spheres, and even the Euler identity ($e^{i\pi}+1=0$), which has been crowned as the most beautiful equation in math. So, yes, $\pi$ is very important.
The digits? Not as much. Some people are searching for a pattern or a regularity to the numbers, but even from centuries of pondering on $\pi$, we have yet to conclude any patterns from it. Learning more digits is both an exercise in seeing if we can find a pattern, and just a competition to see who can find the most. It isn't as useful as other fields of mathematics, but it still has unsolved mysteries for future Mathematicians to solve.
If you want more examples of formulas using $\pi$, check out this link: Formulas Using $\pi$
Comment: I'd debate that comment regarding the digits a bit. Certainly the digits themselves are not that interesting save in their lack of pattern. But the mathematics required for us to be _able_ to get those digits can be tremendously interesting. (See for instance [Ramanujan-Sato series](http://en.wikipedia.org/wiki/Ramanujan-Sato_series).)
Comment: Lack of *apparent* pattern. :)
Comment: @Semiclassical That's not finding digits, that's finding a new way to compute the digits. It doesn't actually matter if you use the algorithm to actually find them.
Comment: Yeah, I mean, the finding of the digits is interesting, and is not completely mundane, but without a pattern, extra digits mean little  to nothing.


Is the sequence $\frac{\sum_{k=1}^{n} \frac{1}{k}}{\log n}$ convergent or divergent?

Question: How should I decide if the following sequence is convergent or divergent?
$$a_n = \frac{\sum\limits_{k=1}^{n} \frac{1}{k}}{\log n}$$
I would appreciate any approach. Thanks.

I was misunderstood series and sequence so I edited the post accordingly.
Comment: You're asked to decide if a certain *sequence* converges.  The Ratio Test applies to *series.*
Comment: By looking at the graph of $yx=1$, you can check that $$\log n \leqslant \sum_{k=1}^n \frac 1k \leqslant 1+\log n $$
for each $n\geqslant 1$, so that the limit of the sequence $a_n$ is $1$.
Comment: The term test is sufficient...
Comment: Are you really being asked if $\sum a_n$ converges? Or if the sequence $a_n$ converges?
Answer: You can use comparison with integrals.  Since $f(x)=1/x$ is monotone,
$$
\sum_{k=1}^n \frac 1k
\ge \int_1^{n+1} \frac 1x dx
=\log (n+1)
$$
and similarly
$$
\sum_{k=1}^n \frac 1k
\le 1 + \int_1^n \frac 1xdx
=1+\log n
$$
Therefore $a_n$ is between $\log(n+1)/\log n$ and $1+1/\log n$ and must converge to 1.
Actually you can show a stronger result:  the difference between the $\log n$ and the sum converges to a constant, called Euler–Mascheroni constant.
Answer: By the integral test proof, you know that
$$
\int_1^{n+1}\frac{dx}{x}\leq\sum_{k=1}^n\frac{1}{k}\leq 1+\int_1^{n}\frac{dx}{x}
$$
Since $\int\frac{dx}{x}=\ln(x)+C$, you can calculate that the limit converges by the squeeze theorem.


Can I overfit an ARIMA model?

Question: I am using the forecast package and the auto.arima function.
This function tries different arima model with different p and q parameters and selects the best one by AIC.
I tried increasing the default values, so auto.arima searches more possible models and indeed the AIC gets lower. I also did a quick test by splitting the data into a train and test part and the MAPE did also improve slightly.\
However, I am unsure if I could run into overfitting issues when I increase the parameter range further.
Comment: Why couldn't you?
Answer: It is not very surprising that you get lower AIC when increasing the range, overfitting is always an issue when you try multiple models. AIC or measuring MAPE on the test set helps reduce the risk but once you consider too many models they can mislead you as well.
Answer: You have a supervised model, you always have the risk of overfitting or high model variance. You should test for instance, how perturbation affects the model. Does removing one point completely change the model?
If you add more models, there is a higher chance that one of does will do better in that specific training sample, but that does not mean that that model will do better in general. Does removing a point completely change the estimates? Cross validation is a good approach, which is asymptotically related to AIC.

Can I overfit an ARIMA model?


What's the derivative of $f(x) = \cos (x) ^{\ln(3x)}$?

Question: I don't understand where or how many times I need to apply the chain rule.
Comment: The form of this function is a bit tricky.  I would convert/rewrite it to a form $f(x) = e^{g(x)}$ so that it would have a more familiar look.
Answer: Hint:
Let $\cos x^{ \ln (3x) } = y  $. Then
$$ \ln(3x) \ln( \cos x) = \ln y $$
Now, apply implicit differentiation:
$$ \frac{1}{x} \ln( \cos x ) + \ln(3x) \frac{ - \sin x }{\cos x } = \frac{y'}{y}$$
Now, solve for $y'$


What is the difference between multimodal and multivariate?

Question: Can somebody explains me the difference between "multimodal" and "multivariate"?
For example, I have a dataset which contains different information. All information objects are connected together by a timestamp. Is this  dataset multimodal or multivariate? If I create an algorithm for clustering these data, should I call this algorithm multimodal or multivariate?
Answer: Put very simply, "multi-modal" refers to a dataset (variable) in which there is more than one mode, whereas "multi-variate" refers to a dataset in which there is more than one variable.
Here is a simple demonstration, coded with R:
set.seed(5104)
x1mm = c(rnorm(50, mean=-2), rnorm(50, mean=2))
x1um = rnorm(100, mean=0.5, sd=sqrt(3))
plot(density(x1mm), main="multimodal data")
plot(density(x1um), main="unimodal data")

y = .5*x1um + rnorm(100)
plot(x1um, y, xlab="X", ylab="Y", main="bivariate data")

That's the gist of it.  When you have response and regressor variables, and you want to fit a model that maps them, the use of "multivariate" depends on the nature of the mapping.  When there is only one response and one covariate, we say this is simple regression; if there is more than one covariate, we say it is multiple regression; and if there is more than one response variable, we call it multivariate regression.  In your case, I gather you are interested in clustering / unsupervised learning, so these distinctions don't really apply.
However, the clustering aspect makes this a little more interesting.  In order to cluster successfully, you generally want your data to be multimodal in the full data space.  The clusters / latent groupings are found by finding a partition that separates the data into unimodal subsets that are more coherent than the original (unpartitioned) superset.
Comment: Thanks a lot. So I can say a dataset is multivariate, and multi-modal doesn't have meaning while defining a characteristic of a dataset. Am I right ?
Comment: I wouldn't phrase it quite that way, @RezaRawassizadeh. For clustering, you generally want your data to be multimodal.  I added some additional information to my answer.
Answer: Multivariate refers to cases where you have more than one outcome variable (not levels). In cases where you have just one outcome variable, one speaks of an univariate problem. But as @gung already said, in practice and sometimes even in textbooks these terms get a little blurry and often refer to cases where you have more than two input variables, e.g. multiple regression etc.
Where multimodal refers to the experimental design. One says a model is multimodal if you measure one construct with different methods (e.g. questionnaire and observation). But it can also refer to the distribution of your data.
To conclude, the meaning of those terms depends heavily on the context.
Comment: Thanks for the answer. So the dataset that have timestamped sensor data is multivariate or multimodal ?
Comment: Unfortunately, I don't think your question can be answered with the information you provided.


Creating data string for REST request

Question: normally when I do a REST request I do something like this
$data = <<<EOF
            <Staff>
              <Name>John Smith</Name>
            </Staff>
            <Staff>
              <Name>Jane Smith</Name>
            </Staff>
EOF;

And then I pass this data to the request
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

However, this time I need to do this dynamically.  So I am trying to build up the block like the above, but with dynamic data.  At the moment, I have something like this
foreach($users as $staffMember) {
    $data =  "<Staff>
                  <Name>$staffMember</Name>
              </Staff>";
}

But that will only produce the last result.  If I have many staff members, how can I build up the raw body which can be passed in my request?
Thanks
Answer: You need to use the .= operator which appends data to a variable.
$data = "";

foreach($users as $staffMember) {
    $data .=  "<Staff>
                  <Name>$staffMember</Name>
              </Staff>";
}

Creating data string for REST request


Detect image links and embed them

Question: What I am trying to do, it write a javascript function where you give it a load of text, and it will look for URLs which end in .jpg, .jpeg, .gif, .png etc, and then replaces them with the code for an embedded image. So, for example, a text like:

Bacon ipsum dolor sit amet shank pork loin ground round beef meatloaf landjaeger tongue chicken strip steak short loin jowl pork chop meatball. Doner shank sausage, tri-tip jerky frankfurter tongue. Venison meatloaf kielbasa, hamburger ball tip tongue beef boudin shoulder spare ribs landjaeger short loin shank. http://1.bp.blogspot.com/-jzdnfSEhmEQ/UDvjPnb-Z0I/AAAAAAAACN4/jTQMom9Fr1c/s320/improvKitchen_howToCookBacon_00.jpg Ham hock ribeye swine sirloin tri-tip kielbasa turkey. Venison strip steak landjaeger corned beef ribeye, pig t-bone pancetta fatback drumstick short ribs sausage pork swine turkey. Jerky chuck bacon turducken doner salami andouille short ribs pork kielbasa drumstick pork chop.

Would return

Bacon ipsum dolor sit amet shank pork loin ground round beef meatloaf landjaeger tongue chicken strip steak short loin jowl pork chop meatball. Doner shank sausage, tri-tip jerky frankfurter tongue. Venison meatloaf kielbasa, hamburger ball tip tongue beef boudin shoulder spare ribs landjaeger short loin shank.  Ham hock ribeye swine sirloin tri-tip kielbasa turkey. Venison strip steak landjaeger corned beef ribeye, pig t-bone pancetta fatback drumstick short ribs sausage pork swine turkey. Jerky chuck bacon turducken doner salami andouille short ribs pork kielbasa drumstick pork chop.

I already have a function for links which I found in another SO post if that is of any help:
function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,"$1");
}

Comment: So the function you found does not solve your problem, correct?
Comment: Might not be a good idea. A url that ends with any of the image extensions can also be scripts. Just saying.
Comment: The function I found converts URLs to hyperlinks. Is there any way to modify the function so that it looks for image extensions as well?
Answer: Well you just need to change that replace to  tag markup to an . And add a regexp pattern to check for .jpg, .jpeg, .gif, .png.
function replaceURLWithImage(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])+\.(?:jpe?g|gif|png)/ig;
    return text.replace(exp,"");
}

See this jsfiddle demo.
Comment: Problem is that that will find links like http://www.google.com and try to turn them into images. It needs to look at the URL extension and only match image extensions.
Comment: ah yes sorry. I've updated the `regexp` and the jsfiddle demo.

Detect image links and embed them


Pass Interface to another service in Startup.cs ConfigureServices

Question: I need to pass an Interface as a parameter in another service's constructor.
MSAuthService constructor needs 3 parameters:
public MSAuthService(string jwtSecret, int jwtLifespan, IUserService userService)
{
    this._jwtSecret = jwtSecret;
    this._jwtLifespan = jwtLifespan;
    this._userService = userService;
}

Startup.cs:
services.AddScoped<IUserService, UserManager>();
....
services.AddSingleton<IAuthService>(
    new MSAuthService(
        MyConfigurationManager.GetJWTSecretKey(),
        MyConfigurationManager.GetJWTLifespan(),
        // I want to pass IUserService as parameter here
        )
);

I couldn't figure out how to pass the IUserService to MSAuthService's constructor. I don't want to pass UserManager (concrete) class as a parameter.
Answer: AddSingleton has an overload that accepts a Func<IServiceProvider, TImplementation>.
You can use the IServiceProvider to retrieve the registered dependency, using GetRequiredService:
services.AddSingleton<IAuthService>(sp =>
    new MSAuthService(
        MyConfigurationManager.GetJWTSecretKey(),
        MyConfigurationManager.GetJWTLifespan(),
        sp.GetRequiredService<IUserService>()
        )
);

Comment: @emert117 scoped service cant be injected into singleton in that way. You'll need to change the lifetime scope of the one of the services
Comment: I tried your answer. I got this error: 'Cannot resolve scoped service 'ABC.Business.Abstract.IUserService' from root provider.'
Comment: And you have registered an implementation for `IUserService`?
Comment: Yes. I have UserManager.cs class.
Comment: I changed `services.AddSingleton...` to `services.AddScoped` . Thanks
Answer: did you try to use this on Configure method?
var scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope();
scope.ServiceProvider.GetService<IUserService>();

Comment: @AmerllicA...  :)
Comment: Mmm, Nice solution my old friend


Ajax Submit Forgot Password Form Loaded in Front Page

Question: Firstly, I altered the Forgot Password Form in my template.php and added the #ajax property:
// Ajaxifying the form

    $form['actions']['submit']['#ajax'] = array(
      'callback' => 'themename_user_pass_form_ajax_callback',
      'wrapper' => 'user-pass',
      'method' => 'replace',
      'effect' => 'fade',
    );

Then I created the ajax callback function:
function themename_user_pass_form_ajax_callback($form, &$form_state){

  module_load_include('inc', 'user', 'user.pages');
  return $form;

}

The form works fine in /user/password page and the ajax works too.
I want the form to appear in the front page, So in my page--front.tpl.php I added the following:
<?php
      module_load_include('inc', 'user', 'user.pages');
      $user_pass = drupal_get_form('user_pass');
      print drupal_render($user_pass);
 ?>

The form appears and when submitting returns with js alert

An AJAX HTTP error occurred.
  HTTP Result Code: 500
  Debugging information follows.
  Path: /system/ajax
  StatusText: Internal Server Error
  ResponseText:  Memory used at: devel_boot()=3.43 MB, devel_shutdown()=32.2 MB, PHP peak=32.25 MB.

Note: The ResponseText is from devel.
In my php_error log file I found this:

PHP Fatal error:  Call to undefined function user_pass_validate() in
  /www/drupal/includes/form.inc on line 1464

The user_pass_validate() is not declared maybe module_load_include('inc', 'user', 'user.pages'); is not working with the ajax call?
Comment: I am getting the same error for forgot password activity (ajax). My forgot password link in the registration page. I noticed when I try to register with improper values and validation messages show up, then forgot password returns internal server error. This happens only in server not in my local computer.
Answer: module_load_include() works slightly differently from your example. The first argument is the file extension, the second is the module name, and the third is the file name minus the extension.
This should work:
module_load_include('inc', 'user', 'user.pages');

Comment: This is worked at last when I include the line in hook_init.

function MODULE-NAME_init() {
 module_load_include('inc', 'user', 'user.pages');
}
Comment: I Change both page--front.tpl.php and template.php, Cleared all caches and runed cron. Still the same js alert with the same error appears when submitting the form and the same PHP Error.
Comment: Sorry didn't notice that...calling `drupal_get_form()` directly in a template file will always cause unexpected results, try moving that logic into a `MYTHEME_preprocess_page()` function in your template.php file and passing the rendered form through as a variable. I just tried the `module_load_include()` call on a local site and that's definitely correct, so the problem might just be where your code is
Comment: I added the following to MYTHEME_preprocess_page()
module_load_include('inc', 'user', 'user.pages');
  $variables['user_reset_pass'] = drupal_get_form('user_pass');
Then in my page--front.tpl.php I added the following: print drupal_render($user_reset_pass);

Same problem still exist.