"Parity Initialization Status: In Progress" for long time

Question: Two weeks ago I installed 6 new hard disks (HP 500GB 6G 7.2K SFF 2.5-inch 2-ports SAS DualPort Midline, 507610-B21)
in a "HP DL 380 G5" with a "Smart Array P400" (RAM Firmware Revision 2.08, ROM Firmware Revision 2.08).
I created a new logical disk with 5 physical disk in RAID 5 and a spare drive (array B):
[...]
=> ctrl all show config
Smart Array P400 in Slot 1                (sn: P61620D9SUKHBP)
array A (SAS, Unused Space: 0 MB)
  logicaldrive 1 (136.7 GB, RAID 1, OK)

  physicaldrive 2I:1:1 (port 2I:box 1:bay 1, SAS, 146 GB, OK)
  physicaldrive 2I:1:2 (port 2I:box 1:bay 2, SAS, 146 GB, OK)

array B (SAS, Unused Space: 0 MB)
  logicaldrive 2 (1.8 TB, RAID 5, OK)

  physicaldrive 1I:1:5 (port 1I:box 1:bay 5, SAS, 500 GB, OK)
  physicaldrive 1I:1:6 (port 1I:box 1:bay 6, SAS, 500 GB, OK)
  physicaldrive 1I:1:7 (port 1I:box 1:bay 7, SAS, 500 GB, OK)
  physicaldrive 2I:1:3 (port 2I:box 1:bay 3, SAS, 500 GB, OK)
  physicaldrive 2I:1:4 (port 2I:box 1:bay 4, SAS, 500 GB, OK)
  physicaldrive 1I:1:8 (port 1I:box 1:bay 8, SAS, 500 GB, OK, spare)

[...]
After that I could create the filesystem on It, mount It and use It without any issue.

My problem is that One week later the controller still was initializing parity.

[...]
   Array: B
      Interface Type: SAS
      Unused Space: 0 MB
      Status: OK
  Logical Drive: 2
     Size: 1.8 TB
     Fault Tolerance: RAID 5
     Heads: 255
     Sectors Per Track: 32
     Cylinders: 65535
     Stripe Size: 64 KB
     Status: OK
     Array Accelerator: Enabled
     Parity Initialization Status: In Progress
     Unique Identifier: 600508B10010443953554B484250000C
     Disk Name: /dev/cciss/c0d1
     Mount Points: /buzonesdir 1.8 TB
     OS Status: LOCKED
     Logical Drive Label: A0C36F2EP61620D9SUKHBPA42A

[...]
At that moment, trying to speed up the parity initialization, I increased the rebuild and expand priority from "medium" to "high".

But, one week later (working with high priority) the "Parity Initialization Status" is still "In Progress".

Do you know if this is normal and I should let It continue working?
Do you know any way to check if really "Parity initialization" is being done and how long It will last?

Thank you very much.

Comment: Looks like BBU is absent. When controller hasn't a battery it turn off write-caching that slowdown performance significantly.
Answer: The rebuild/expand priority setting doesn't affect parity initialization.
Be aware that parity initialization only occurs when the controller is not busy.  If you are actively using the controller, it will not be making much progress towards completing initialization.  To make initialization complete as fast as possible, allow the system to sit idle until initialization completes.
You may also have some success by changing the "Surface Scan Analysis Priority" to "High".  If this setting is set to "Delay", then the controller will have to be idle for the specified number of seconds before it resumes a surface scan or parity initialization operation.  Setting this to "High" should force the controller to make some sort of progress even if it is busy.  After initialization completes, though, you'll probably want to reset this back to whatever value it started with.
Comment: +1 for Surface Scan Analysis ... that's what did it for me.
Comment: @NTDLS Depends on your OS, I suppose.  I'll boot to a DOS USB drive or press "Delete" during boot and sit in the BIOS menu if I need to make absolutely sure that no background I/O is happening.  If you set the scan priority to "high", you'll still make progress even if there is background I/O happening.
Comment: What do you mean by "let the system sit idle"? Does this mean booted into the OS - just not using the server much? My array is still at 0.00% after 8 days and the server is unused - just sitting at the Window login screen.
Comment: @NTDLS "Idle" meaning no I/O activity being sent to the controller, by you or by background processes.
Comment: Kind of difficult to do for an OS disk isn't it? Should I find some way to pause the server before the OS loads?
Answer: Firmware first!
The controller you have is older, but there have been a multitude of changes to the controller firmware since the version you're running on. You're at ROM revision 2.08. The current firmware for the Smart Array P400/P400i is version 7.22. Also see this HP advisory indicating the same.
Look through the change log for the controller, there are many issues/bugs addressed in updates.
You could install firmware piecemeal or just run a current HP Firmware DVD to bring the entire system, including disks, up-to-date.
Other notes...

The 500GB nearline SAS disks you're using were released well after this controller was introduced. You may run into interoperability issues until you upgrade the controller firmware.
RAID 5 isn't really recommended anymore. The performance will be poor on the disks you've spec'd, unless it's a pure sequential workload.
Please obtain a battery-backed cache (BBWC) unit for the controller. Performance on HP Smart Array controllers is unacceptable without them.

Also see: Slow parity initialization of RAID-5 array on HP Smart Array P411 controller
Answer: A disk firmware updabe is available. It may resolve your issue "This firmware prevents a rare condition that may occur during a WRITE SAME command sequence that may result in incorrect data being written to the hard drive. The WRITE SAME command may be used during RAID ARRAY parity initialization. "
Comment: If you can post the same answer to two questions it's an indication that the questions **might** be duplicates. So rather than posting an answer you should think about flagging the question.
Comment: There was a already a 10 month old answer that says to update the firmware and is much more detailed. What does this add?


Set text into clipboard from flashVars

Question: What i want to do:
Get Flash Var, Set flashVar Into ClipBoard.
Html:
<embed src="setClip.swf" FlashVars="res=123" quality="high" TYPE="application/x-shockwave-flash">

action script(3):
function loaderComplete(myEvent:Event)
{
   this.flashVars=this.loaderInfo.parameters;
   this.flashVarsLoaded=true;
   this.useFlashVars();
}
function useFlashVars()
{
        aaa.text = myFlashVars.res;
}
var myFlashVars=new Object();
myFlashVars.flashVarsLoaded=false;
myFlashVars.loaderComplete=loaderComplete;
myFlashVars.useFlashVars=useFlashVars;
this.loaderInfo.addEventListener(Event.COMPLETE, myFlashVars.loaderComplete);

When i open the html page there is no text in "aaa" input.
What is the best way to get flash var and then insert him into clipboard(as1,as2,as3)(I Need Good Example)?
Answer: You not need to wait flashvars loading and use Event.COMPLETE. Flashvars lays in main class loaderInfo.parameters just when player starts. Just try trace it trace (this.loaderInfo.parameters["res"]) in main class.
1 create new fla file, save it
2 add to stage textfield (dynamic), set instance name ft1
3 click main stage, in properties panel, Class type main
4 create main.as in dir with fla (step 1)
5 main as:
package  {

    import flash.display.MovieClip;
    public class main extends MovieClip {
        public function main() {
            tf1.text = this.loaderInfo.parameters["foo"];
        }
    }
}

6 File->publish
7 Go dir (step 1), open .html file, add line
<param name="flashvars" value="foo=10" />
in params (twice)
8 open HTML in browser, enjoy
(NB: You cannot test flashvars in Adobe Flash IDE environment, olny in real browser)
About clipboard:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/System.html#setClipboard()
This method works from any security context when called as a result of a user event (such as a keyboard or input device event handler).
9 add button to stage, name it btn
10 main.as:
package  {
    import flash.display.MovieClip;
    import flash.events.MouseEvent;
    import flash.system.System;

    public class main extends MovieClip {
        public function main() {
            tf1.text = loaderInfo.parameters["foo"];
            btn.addEventListener(MouseEvent.CLICK, onClickHandler);
        }

        private function onClickHandler(e:MouseEvent):void {
            System.setClipboard(loaderInfo.parameters["foo"]);
        }
    }
}

11 Compile .fla, open HTML in browser, click btn, check clipboard
Sorry, no way to fill clipboard "automagically" without user interaction. Remember: reading and writing the clipboard is a huge security hole.

Set text into clipboard from flashVars


How to make a loading mask for a portion of a page in angularjs?

Question: I have a $http request that loads information for a <select> tag.  I want to show some kind of loading mask/image, but I want it to only display over the affected part of the page.
HTML
<select ng-model='widgetType' ng-options="widget.name for widget in allWidgets track by widget.id">
<fieldset id="needs-loading-mask" ng-disabled="widgetType.id">

  <select ng-model='widgetVariant' ng-optoins="variant.name for variant in allVariants track by variant.id>
<fieldset>

JS
    $scope.$watch('widgetType.id', function(newValue, oldValue) {
        if(newValue) {
            $scope.loadingVariants = true;
            console.log("Getting variants from server");
            $timeout(function() { // only here for debug purposes
                $http.get('/api/widget-variants/?widget=' + newValue)
                    .success(function (data) {
                        $scope.allVariants = data;
                        $scope.loadingvariants = false;
                    }).error(function (data) {
                        $scope.loadingvariants = false;
                    });
                }, 1000);
        } else {
            $scope.allVariants = [];
        }
    });

I'm wanting #needs-loading-mask to be occluded by a loading mask while $scope.loadingVariants is true, but I can't figure out how to get it to float OVER the select, filling the parent fieldset using a declarative syntax.
I can't remove the select field because that plays havoc with tab order, but it seems like it should be possible to float something in front of it.
Comment: See the comments in the accepted answer for the bulk of what this question was about.  The answer has sufficient good content that I didn't want to delete the question, but the CSS portion of it is answered http://stackoverflow.com/questions/21027514/how-do-i-mask-a-region-of-the-page-in-a-responsive-design-using-css
Answer: $http is aware of its job
Easy way, with only one boolean management:
Declare a service like this:
angular.module('services.httpRequestTracker', [])
    .factory('httpRequestTracker', ['$http', function ($http) {

        var httpRequestTracker = {};
        httpRequestTracker.hasPendingRequests = function () {
            return $http.pendingRequests.length > 0;
        };

        return httpRequestTracker;
    }]);

In your main controller (usually app controller):
$scope.hasPendingRequests = function () {
   return httpRequestTracker.hasPendingRequests();
};

And wherever you want in your page, something like:

The magic here is thus the http.pendingRequests.length method.
Comment: The service definition is unnecessary. You can just "return $http.pendingRequests.length > 0" in the $scope function.
Comment: That is a much cleaner version than mine, but how do you get the image up and over the fieldset?  JQuery wise you would measure the fieldset and then position the element over the top of it (I think).  Is there some CSS positioning trick I can use to make that happen here?  I could maybe give it a loading background with css, but I'd rather have a loading foreground.
Comment: The answer had to come in two parts.  This is how you do the CSS to get the localized masking (which was the original question).  http://stackoverflow.com/questions/21027514/how-do-i-mask-a-region-of-the-page-in-a-responsive-design-using-css
Answer: Request Tracker in angulajs.
angular.module('services.httpRequestTracker', [])
.service('httpRequestTracker', ['$http', function ($http) {
    var httpRequestTracker = {};
    httpRequestTracker.hasPendingRequests = function () {
        return $http.pendingRequests.length > 0;
    };

    return httpRequestTracker;
}]);


Load a panels display in code

Question: To load a Panel display from the database we can use panels_load_display($did)
However, the $did value is an autoincrement value from the database. It is not present in exported Panel page displays (e.g features export).
I thought perhaps we could use ctools_export_object_load to load the exported panels display.
However, I found that it only returns a result if the display is in the panels_display table in the database, and returns empty empty for exported code storage displays.
e.g:
// Attempt to load Panels display
ctools_include('export');
$uuid = '49c15c71-d5d1-d574-b539-0149f912f925';
$display  = ctools_export_load_object('panels_display', 'conditions', array('uuid' => $uuid ));
var_export($display); // empty array if not in DB.

How can we load a Panel display in code when that display is exported in features and using code-based storage?
Comment: What hook is used in your feature to declare the displays?
Comment: @ciss the hook used by features is `hook_default_page_manager_pages` I wonder if will need to load the panel page itself, then get the display from that. There doesn't appear to be a simple equivalent function to load exported panel displays.
Answer: The relationship between tables and their exported datasets is declared via the export key in a table's schema definition. We can see that key both for page_manager_pages and panels_display.
ctools also allows the definition of a default hook. If non was provided it will fall back to default_{table}.
When loading a ctools exportable via ctools_export_load_object() ctools will first query the table for objects, then invoke the default hook to retrieve any objects stored in code.
When page manager pages are exported, panels_display objects are not declared separately under their own hook, but are wrapped in hook_default_page_manager_pages().
In order to retrieve them by their UUID they would have to be declared within hook_default_panels_display().
Comment: Thanks @ciss, nice answer, but not quite the solution I was looking for, upvoted anyway, with my other solution coming.
Answer: After trying various approaches such as:
$page = ctools_export_load_object('page_manager_pages', 'names', array('app'));
var_export($page);
// And also
$handler = ctools_export_load_object('page_manager_handlers', 'names', array('page_app__panel_context_7d7ea5ec-d257-43aa-bfe6-a0c25623111d'));
var_export($handler);

I found I couldn't reliably load the panel display when it was in both code and stored in the db.
Maybe there's another way but in the maze of ctools, panels and page manager, I ended up with a simpler solution.
Minipanels!
Compared to page displays, it's much easier to load and render minipanels programmatically:
$minipanel_name = 'minipanel_machine_name';
// This loads the minipanel, both from DB or from code export.
$minipanel = panels_mini_load($minipanel_name);
// Render the minipanel display
if (empty($minipanel) || empty($minipanel->display)) {
  watchdog('module', 'Unable to load minipanel: !name', array('!name' => $minipanel_name));
}else if (!empty($minipanel->display)) {
  $display = $minipanel->display;
  // Pass data as dynamic args to panel display
  // This is optional, but used for this case.
  $display->args = array('data' => $data);
  $output = panels_render_display($display);
}

Load a panels display in code


Is there a way to get the value inside the table by clicking an HREF Link?

Question: I am reading a JSON file, accessed via Python. The values from JSON file will be then displayed on a table. Per row, I have a button. What I want is to see the value when I click the button.
What algorithm I could use in such a way that i could store the ALL values so when I click the button, I can get its corresponding ROW value.
Iteration of my JSON file below:

    {{ entryIteration.sha1 }}
    {{ entryIteration.requestedStatus }}
    {{ entryIteration.detectionName }}
    {{ entryIteration.userRemarks }}

        Approve
        Reject
        View

{% endfor %}

Answer: $('.btn btn-default').click(function(){
    var tdtext1 = $(this).closest('tr').find('.tdclass1')
     var tdtext2 = $(this).closest('tr').find('.tdclass2')
})

Use .closest() to get the value of data in the row where the button is

Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.


Issues with jQuery .before

Question: So I'm building a very simple carousel with 4 divs. It uses 2 jQuery functions to set a div to either first or last position. There is only alpha transitions as I don't need movement.
For some reason, though I can access my divs with .eg(n) etc, but the first, last and other various numbers aren't working in this function.
Code:
$('#prev').click(function() {

    $('.container .divname').animate({opacity: 0}, 1000,function(){

     $('.container .divname:first').before($('.container .divname:last'));

     $('.container .divname').animate({opacity: 1}, 1000);

    });

    return false;

});

So that function isn't working.
$('#prev').click(function() {

        $('.container .divname').animate({opacity: 0}, 1000,function(){

         $('.container .divname:eq(0)').before($('.container .divname:eq(3)'));

         $('.container .divname').animate({opacity: 1}, 1000);

        });

        return false;

    });

This also doesn't work, but if I change the eq(3) to eq(2) it does, but obviously misses one of my divs. I can still access the eq(3) because I tested it, and made it's background red.
$('.container .divname:eq(3)').css({'background-color' : '#ff0000'});

This works...
Can anyone please tell me why this maybe happening?
Html example is as below

some content

some content

some content

some content

EDIT:
I have changed all the id to class now for the w3c kids in the audience. Issue still resides.
http://jsfiddle.net/3P8t5/1/
Comment: Ids should really be unique.
Comment: Yeah I realize my coding is a bit rough, but this won't solve the issue will it?
Comment: As ids are unique so it must not assign to second element in the page due to this it makes a invalid html as w3c recommends.
Comment: Ok, i'll change the id to a class edit if the issue still occurs. Still makes no sense how I can access them individually but not in the function itself. Still, I'll make the changes so we can get that issue out the way.
Answer: The root of your problem is that you have put your .before() function to shift the divs in a callback function attached to your four divs - thus it is called four times meaning everything is shifted four times bringing you back to square one ...and becuase it's such a simple little loop, it's fast and it appears nothing has happened.
Solution - attach the animate function to just the container;
$('#prev').click(function() {

// Fade just the container - not each placeholder meaning the callback function is only called once, not four times
$('.container').animate({
    opacity: 0
}, 1000, function() {

    $('.container .divname:eq(0)').before($('.container .divname:eq(3)'));

    // Fade back in just the container - not each placeholder
    $('.container').animate({
        opacity: 1
    }, 1000);
});
return false;
});

http://jsfiddle.net/cywjs/1/
Comment: Barry Mcgee, you are a genius! Thank you sir!
Answer: other than friends suggested (Ids should really be unique) i saw misspell in your code.change "divnaname" to "divname" in the div tags.e.g:
 ...

Edit:
check this demo demo
is this what you are trying to do?
Comment: That's actually just a temp name for the sake of this post but thanks, i'll tweak it.
Comment: it is not important how you are naming tags but they must be same in the murkup and jquery selector.
Comment: Not exactly but close. I want previous to send 4 to the front of the queue, like 1,2,3,4, then press prev and achieve 4,1,2,3. Obviously with a next button it would go from 1,2,3,4 to 2,3,4,1.

Issues with jQuery .before


Fabric js load image from data uri coming from another url

Question: I know how to load image from data uri into fabric js. But i am not able to figure out how to load image if the data uri is coming from another url. I have a PHP script which accepts the image URL and returns the base64 image data.
<?php
    $path = $_REQUEST['url'];
    $type = pathinfo($path, PATHINFO_EXTENSION);
    $data = file_get_contents($path);
    $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
    echo $base64;
?>

Lets assume the url is http://example.com/encodeImage.php?url=http://example.com/image.png. I am trying to use this URL into this function
fabric.Image.fromURL('http://example.com/encodeImage.php?url=http://example.com/image.png', function(img) {

But it is not able to load the image. In the console it says unable to load the image
Is it something even possible to do with fabric js?
Answer: Add image in this way:
var img = new Image();
    img.onload = function () {
        var imgbase64 = new fabric.Image(img, {
            scaleX: 0.2,
            scaleY: 0.2
        })
        canvas.add(imgbase64);
        canvas.deactivateAll().renderAll();
    }

$.ajax({url: "http://example.com/encodeImage.php?url=http://example.com/image.png", success: function(result){
        img.src = result;
    }});

Answer: fabric.Image.fromURL(url, function (img, callback) {
    img.id = imageId;
    img.filters = [new fabric.Image.filters.HueRotation()];
    img.applyFilters()
    var cor = img.set(
        {
            left: left,
            top: top,
            selectable: false,
        }
    )

    canvas.add(img);
});

Comment: Can you explain what this code is doing? Also it looks like it might be incomplete, as it is missing the closing brace at the end


Recarregar página com MVC

Question: Fiz uma função na model e a chamada na controller. Aí, passo para o jquery e o comando de gravar no BD é excutado com êxito. Acontece, que quando eu termino de gravar, a tela continua com as informações anteriores, ou seja, os textbox preenchidos, os checkbox's checados. Como eu faço para após a gravação no BD(sucesso do ajax) eu recarregar a página ou os campos alterados somente? Abaixo minha chamada jquery. O alerta com a mensagem pode ser desconsiderado, se necessário.
var checkedItemsUn = {}, checkedItemsMot = {}, checkedItemsPdv = {}, counter = 0;

function Gravar() {

    $("#check-list-box li.active").each(function (idx, li) {
        checkedItemsUn[counter] = $(li).text();
        counter++;
    });

    counter = 0

    $("#check-list-box-mot li.active").each(function (idx, li) {
        checkedItemsMot[counter] = $(li).text();
        counter++;
    });

    counter = 0

    $("#check-list-tipo li.active").each(function (idx, li) {
        checkedItemsPdv[counter] = $(li).text();
        counter++;
    });

    counter = 0
    str = "";

    $.ajax({
        url: '/CadastroCargo/GravaResponsavel',
        datatype: 'json',
        contentType: 'application/json;charset=utf-8',
        type: 'POST',
        data: JSON.stringify({ _responsavel: $('#txtResponsavel').val(), _ativo: $('#ckbAtivo').prop("checked"), _Un: checkedItemsUn,
            _motivo: checkedItemsMot, _pdv: checkedItemsPdv, _nivel: $('#cbxNivelResp').val()
        }),
        success: function (data) {

            str += '
';
            str += '<button type="button" class="close" data-dismiss="alert"></button>';
            str += '
Operação realizada com sucesso!
';
            str += 'Registro gravado no banco de dados com sucesso.';
            str += '
';

            $('#alerta').html(str);

            str = "";
        },
        error: function (error) {
        }
    })
}

Comment: Se fizeres `window.location.href = "/oTeuController/aTuaFuncao"` e carregares os dados no controller e enviar para a view deve resolver...
Comment: No fim de gravares os dados, no success fazes um `windows.location.href` para um função que irá carregar os dados para um view. Os parâmetros a pores é o teu controller primeiro e depois a tua função...
Comment: Fiz:  window.location.href = '/CadastroCargo/CadastroCargo'; Onde CadastroCargo é meu controller e minha Action e aí funcionou.
Comment: Devo colocar a minha função ou a Action? Coloquei a action e não funcionou. Qual função? Pois todas têm parâmeros e são para a funcionalidade da página, não entendi.
Answer: Se queres carregar novamente um view, podes usar o window.location.href no success do teu pedido Ajax.
Como tal, ficará algo do tipo:
$.ajax({
        url: '/CadastroCargo/GravaResponsavel',
        datatype: 'json',
        contentType: 'application/json;charset=utf-8',
        type: 'POST',
        data: JSON.stringify({ _responsavel: $('#txtResponsavel').val(), _ativo: $('#ckbAtivo').prop("checked"), _Un: checkedItemsUn,
            _motivo: checkedItemsMot, _pdv: checkedItemsPdv, _nivel: $('#cbxNivelResp').val()
        }),
        success: function (data) {

            str += '
';
            str += '<button type="button" class="close" data-dismiss="alert"></button>';
            str += '
Operação realizada com sucesso!
';
            str += 'Registro gravado no banco de dados com sucesso.';
            str += '
';

            $('#alerta').html(str);

            str = "";

            window.location.href = '/CadastroCargo/CadastroCargo' //AQUI
        },
        error: function (error) {
        }

Onde na função CadastroCargo carregas os dados para carregar na view que pretendes.

Recarregar página com MVC


Apache logging issues

Question: I'm trying to parse apache log files, but I'm finding some strange results and I'm not sure what they mean.  Hopefully someone can provide some insight.  (all of the IP addresses were altered.  none actually start with 192, I didn't figure the search engines mattered though.)
In the first example, multiple ip addresses are showing up in the host field:
188.8.131.52 - - [04/Aug/2009:04:21:44 -0500] "GET /publications/example.pdf HTTP/1.1" 200 2738
184.108.40.206, 22.214.171.124 - - [04/Aug/2009:04:21:22 -0500] "GET /docs/another.pdf HTTP/1.0" 206 371469

What causes this?  Does it have to do with proxy servers?  Is there a way to have Apache only log one?
Edit:
Here it is:
LogFormat "%h %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-agent}i\" %I %O" common

In the second example, a bunch of information is just completely missing!  What would cause this?
msnbot-65-55-207-50.search.msn.com - - [29/Dec/2009:15:45:16 -0600] "GET /publications/example.pdf HTTP/1.1" 200 3470073 "-" "msnbot/2.0b (+http://search.msn.com/msnbot.htm)" 266 3476792
- - - - "-" - - "-" "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; InfoPath.1)" 285 594
- - - - "-" - - "-" "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; InfoPath.1)" 285 4195
- - - - "-" - - "-" "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; InfoPath.1)" 299 109218
crawl-17c.cuil.com - - [29/Dec/2009:15:45:46 -0600] "GET /publications/another.pdf HTTP/1.0" 200 101481 "-" "Mozilla/5.0 (Twiceler-0.9 http://www.cuil.com/twiceler/robot.html)" 253 101704

My CustomLog configuration says:
LogFormat "%h %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-agent}i\" %I %O" common

Comment: We need your `CustomLog` directive to determine what you've done.
Comment: +1 to womble's comment ... you've posted a LogFormat definition but we need your CustomLog line in order to determine what logging format has been applied to your config.
Answer: Can you post the output of httpd -l and httpd -M, please?
That comma separated %h line looks suspiciously like something is jamming in an X_FORWARDED_FOR value. The fact that you don't have a date on the subsequent lines seems odd, so my assumption is that there is a module loaded that's registered a logging hook and it's munching up your output.
I've never seen that happen and I run some pretty large Apache installations. It has got to be some screwy module causing problems (or, perhaps the lack of a required module).
The other possibility might be that Apache doesn't know how to satisfy your format directive. The '-' simply means that a requested data point wasn't available. Those format specifiers are built in to mod_log_config, which ought (needs?) to be present by default.
Edit... I know Ubuntu & Red Hat define a 'combined' as well as a 'common.' Could you try using that format instead? I think someone already mentioned that, though.
Answer: It looks to me like you are behind a proxy/cache and you are using mod_rpaf which replaces the IP address that apache sees in %h with the contents of X-Forwarded-For.  Some proxy servers include their IP and the forwarded IP (giving you the 188.8.131.52,22.214.171.124 IP addresses.  The reason you are getting some blank results is that some proxy servers use headers other than X-Forwarded-For and rpaf replaces a null value with -.
Answer: It looks like you are reusing the common logging definition. This probably isn't supported. Try defining your own logger
LogFormat "%h %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-agent}i\" %I %O" mylogformat

Apache logging issues


Hide comma between anchor tags in a div with CSS

Question: I have this kind of HTML:

    link,
    link,
    link

How could I hide the commas with css?
I've tried:
.meta{
    display: none;
}
meta a{
    display: inline;
}

but this has no effect as it affects the parent. Also I tried:
.meta *:not(a){
    display: none;
}

...but this removes everything, so no luck!
Comment: Do you need the , in the html?
Comment: No, I just need to remove the "," (it's output by php but I have a slightly difficult access to it).
Answer: I finally resorted to jquery with this:
jQuery('.meta').each(function() {
    var text = jQuery(this).text();
    jQuery(this).text(text.replace(',', ' '));
});

...but if anyone finds a CSS solution I will give them the answer.
Comment: no need JS, check the duplicate question for some ideas


If $m^3 = n^2$ and $n$ is even, then n is divisible by $4$.

Question: Conjecture: If $m^3 = n^2$ and $n$ is even, then n is divisible by $4$.
The proof falls apart from the beginning.
$n$ is even therefore there is a number $k$ such that $n=2k$
$m^3 = n^2$
$m^3 = (2k)^2$
$m^3 = 4k^2$
$4|4k^2$ therefore $4|n^2$

However, I can't think of an example where a cubic is equal to a square.  I also ask with hesitation because we have been studying prime numbers and the Euclidean Key theorem as well as other proofs using the Fundamental Theorem of Arithmetic.  So, this approach seems out of place for the section of homework that I'm doing.
Comment: A cube us equal to a square precisely when it's a sixth power.  For example $2^6=64$, so $64=8^2 =4^3$.
Comment: Try $m = a^2, n = a^3$ for some $a$.
Comment: Try: $n$ even $\Rightarrow$ $m$ even $\Rightarrow$ $m^3$ divisible by 8 $\Rightarrow$ $n^2$ divisible by 8 $\ldots$
Comment: Assuming only integers allowed how about $4^3=8^2$...
Comment: Apparently I didn't spend enough time on this one.  I'll be stepping back for a bit to think more about it.  Thanks for the input.
Comment: If I take n as 2 though, then isn't this not necessarily true?  Or is it due in the part that I am constrained by $m^3=n^2$ that I cannot use this as a counterexample?
Comment: @Joel: yes, of course, my apologies.
Answer: Since $n^2 = m^3$ (i.e. $n^2$ is both a perfect square and a perfect cube), the number of factors of 2 in its prime factorization must be a common multiple of 2 and 3.
The smallest such multiple would be zero, but we can discard that possibility on the grounds that $n$ is even.
So, $n^2$ has at least six factors of 2 in its prime factorization. This means that $n$ has at least three factors of 2 in its prime factorization, and so $n$ is divisible by 4 (indeed, it is divisible by 8).
Comment: How should I go about showing "So, $n^2$ has at least six factors of 2 in its prime factorization."  Is this drawn from the fact that $n^2=m^3$?
Comment: @arete It's the next smallest number (after 0) that it is a common multiple of 2 and 3.
Answer: There are multiple problems here:
(1) If $n$ is even then $4|n^2$, but not necessarily $n$.
(2) Your "proof" doesn't really use the fact that $m^3 = n^2$.
Also, there are numbers that satisfy $m^3 = n^2$.  For instance, $2^6 = 4^3 = 8^2$.
Comment: Well then, that's a start.
Comment: Yes, I suppose I should take the whole "proof" into account.  Otherwise, I'm missing important tools.  @JyrkiLahtonen's advice was helpful.
Answer: Here is one way to proceed:
Suppose $m^3=n^2$, and $n$ is even. As you say, $n$ must be $2k$ for some integer $k$. Then $m^3=4k^2$, which means in particular that $2\mid m^3$. Now, either by a quick contradiction, or by using Euclid's lemma, it follows that $2\mid m$. (The point here is that $2$ is prime, so if $2\mid m^3=m\cdot m\cdot m$, then it must divide $m$ or $m$ or $m$. The argument by contradiction is that if $m$ is odd, then $m^3$ is also odd by a direct computation, so $2\mathrel{\not|} m^3$.)
If $2\mid m$ then there is an integer (say, $\ell$) such that $m=2\ell$. Then $m^3=8\ell^3$. Then $8\ell^3=4k^2$, so $2\ell^3=k^2$, so $2\mid k$. Then $k=2a$ for some integer $a$, and $n=2k=4a$ is indeed a multiple of $4$.

But it may be worth thinking about this in slightly more general terms. The equation $m^3=n^2$ tells us that the prime factorizations of the two numbers $m^3$ and $n^2$ must coincide. Start with the prime factorization of $m$ and cube it to find the prime factorization of $m^3$. Similarly, start with the prime factorization of $n$ and square it to find the prime factorization of $n^2$. This tells you that there are primes $p_1<p_2<\dots<p_a$ and $q_1<q_2<\dots<q_b$ and exponents $\alpha_1,\dots,\alpha_a$ and $\beta_1,\dots,\beta_b$ such that $$ p_1^{3\alpha_1}\dots p_a^{3\alpha_a}=q_1^{2\beta_1}\dots q_b^{2\beta_b}. $$
(Here, of course, $m=p_1^{\alpha_1}\dots p_a^{\alpha_a}$ and $n=q_1^{\beta_1}\dots q_b^{\beta_b}$.)
The uniqueness of the prime factorization tells us that $a=b$, $p_1=q_1$, $p_2=q_2$, etc, and $3\alpha_1=2\beta_1$, $3\alpha_2=2\beta_2$, etc.
Now: If $3\alpha_i=2\beta_i$, then $2\mid\alpha_i$ (so $m$ is a square) and $3\mid\beta_i$ (so $n$ is a cube), so $n$, being even, must in fact be a multiple of $2^3=8$.
The advantage of this approach, which perhaps looks a bit more complicated than the first one, is that it generalizes to other situations. So one can now quickly conclude by the same argument that if, say, $m^6=n^{17}$, then $n$ is a sixth power (so if $n$ is even, then it is a multiple of $64$, for example). Or, if $m^6=n^{15}$, then $n$ is a square. Etc.
Answer: First try to prove that every number that is both a square and a cube is a sixth power.  (It is easier to prove that every sixth power is both a square and a cube.)  Then you have $m^3=n^2=\ell^6$.  If $4\mid \ell^6$ then $2\mid \ell^3$.  Then you can show that $2\mid\ell^3$ only if $2\mid\ell$.  That implies that $8\mid\ell^3=n$, so of course $4\mid n$.
Comment: I'm not quite understanding the approach to show that $m^3=n^2=l^6$ .  Is there an abstract example that could be shown?  This is the part of the proof that I'm not quite understanding.
Comment: Let $m=\ell^2$, $n=\ell^3$.  Thus, $m^3=n^2=\ell^6$.


Dúvida sobre each() no Jquery

Question: Porque o código abaixo só me retorna o primeiro "104 104" e não "104 106"

$(function(){
  $('#sortable li').each(function(){
    console.log($('#sortable li').attr('id'));
  });
});

Comment: Podes juntar o HTML? assim podemos responder mais pedagogicamente. De modo breve estás sempre a usar o mesmo elemento... deves usar `console.log(this.id);`. Mas se juntares o HTML é mais fácil perceber o problema e responder.
Answer: Quando usas $('#sortable li').attr('id') o jQuery vai retornar somente o id do primeiro elemento que esse seletor encontrar.
Quando usas essa linha de código dentro de um .each() não estás na verdade a mudar nada, e daí ele dar a mesma resposta nas duas vezes.
Contudo o seletor $('#sortable li') retorna todos os elementos que queres e faz sentido usar o .each() para os iterar. Sendo que o jQuery atribui o elemento iterado ao this dentro dessa função passada ao .each() então para saberes o id basta usares this.id, como referi no meu comentário antes.
Assim basta usares:
$('#sortable li').each(function(){
    console.log(this.id);
});

NOTA: repara que te falta });  no final do teu código, antes do </script>.
Answer: Porque a cada giro do loop você está fazendo uma nova consulta ao DOM.
A estrutura do $.each(); permite que você acesse o index do elemento e o próprio elemento, sem refazer a consulta ao DOM:
$('#sortable li').each(function(i, o){
   console.log(o.id);
});

Comment: o `this` retorna o elemento atual do for tb dentro do bloco. Ex: `$(this).attr("id")`
Comment: kkk eu sei Bruno, é pq escrevi rapido aqui e nem reparei. O html ta em cima Sergio. Marcelo, entendi. Mas como faço para obter os ids das duas li. To apanhando aqui, pra essa porcaria. :)
Comment: acumula eles em um array ou em uma string, não sei se entendi ao certo sua duvida... cada volta do loop ele vai te expor o id do atual e então vc vai acumulando em alguma variável que foi declarada fora do loop (each)
Comment: Acabei de descubrir...rss Vlw galera...
Answer: é isso?
$("#sortable li").each(function(){
    console.log($(this).attr("id"));
});

https://jsfiddle.net/Lqmf8g20/
Answer: Olá segue um exemplo onde exibirá os atributos "id" em um 'alert' do Javascript:
 $("#sortable li").each(function(ui, e){
     alert($(this).attr("id"));
 });

Comment: Seria útil se acrescentasse  à sua resposta uma pequena explicação.

Dúvida sobre each() no Jquery


Finding the radius of cylindrical shells when rotating two functions that make a shape about an axis of rotation (the shell method)

Question: I have been constantly writing and re-writing the procedure to find the radius in my notes. I know it is a simple concept but everywhere I look doesn't go over that concept- maybe I should know it already but I must have forgot. I know what the radius is by definition but I am still having trouble.
At first I took the line perpendicular to height and usually came up with the function that the line touched.
Then after getting it wrong I would subtract/add the difference of the axis of rotation and the start of the function except the radius always wanted to be $x$ or $y$.
Then I came up with the idea that radius was the difference between $f(y)$, $f(x)$ and the axis of revolution. So the radius would be $x$ or $y$ plus/minus the difference from the axis of revolution.
The problem is that there is not enough examples or questions with answers in my book to know if I understand it correctly.
Comment: Your question is quite vague. Can you give an example problem to clarify what type of problems you are trying to solve?
Answer: The key idea is that the radius $r$ is a variable which we create to integrate over. Let's look at an example: finding the volume of the region between the curves $f(x)=-(x-3)^2+5$ and $g(x)=x$ when it is rotated around the $y$-axis, using the method of cylindrical shells. Note that the two curves intersect at $x=1$ and at $x=4$.
Here is the figure:

Now, to get an idea of how the cylindrical shells work, imagine cutting a thin vertical sliver out of our picture and rotating just that around the $y$ axis - getting something that looks like a cylindrical shell.

Now we want to compute the volume of this shell: The volume of the shell is approximately area of the sliver multiplied by $2\pi r$ where $r$ is the distance from the axis of rotation. Why? Because for every point on the line of our sliver we are making a circle or radius $r$. We can compute the area of the sliver by approximating it as a rectangle with some very small base $dr$ and height $f(r)-g(r)$. Hence the volume of the shell is approximately
$$2\pi r(f(r)-g(r))dr$$

Now imagine dividing our figure entirely into thin slivers and rotating them. By taking an integral over all possible $r$, we can essentially sum up all of the volumes of these cylindrical shells and get the final volume.
$$V=\int\limits_a^b2\pi r(f(r)-g(r))\,dr$$
For the sake of completing our example, notice that in our case $a=1$, $b=4$, $f(r)=-(r-3)^2+5$, and $g(r)=r$. Hence for our example we have
$$\begin{align}
V&=\int\limits_1^42\pi r(-(r-3)^2+5-r)\,dr
\\&=2\pi\int\limits_1^4 r(-r^2+5r-4)\,dr
\\&=2\pi\int\limits_1^4 -r^3+5r^2-4r\,dr
\\&=2\pi\left(-\frac{1}{4}r^4+\frac{5}{3}r^3-2r^2\right)\bigg|_{r=1}^{r=4}
\\&=2\pi\left(-64+\frac{5}{3}\times 64-32+\frac{1}{4}-\frac{5}{3}+2\right)
\\&=2\pi\left(\frac{32}{3}+\frac{7}{12}\right)
\\&=2\pi\left(\frac{135}{12}\right)
\\&=\frac{45\pi}{2}
\end{align}$$
Comment: Nice (-_^) Peter


Underlying assumption in a Primal/Dual table

Question: I just read in one of the questions answered by @MikeSpivey that the following table is provided in Sierksma's Linear and Integer Programming: Theory and Practice, Volume 1, page 144.
<code>Primal Optimal Solution                     Dual Optimal Solution
(a) Multiple                     implies    Degenerate
(b) Unique and nondegenerate     implies    Unique and nondegenerate
(c) Multiple and nondegenerate   implies    Unique and degenerate
(d) Unique and degenerate        implies    Multiple
</code>
I wonder if the information provided in this table is provided based on the assumption that matrix A has full rank.
Answer: An LP is degenerate if in a basic feasible solution, one of the basic variables takes on a zero value. Degeneracy is caused by redundant constraint(s) and could cost simplex method extra iterations, as demonstrated in the following example.
$max \space z=x_{1}+x_{2}+x_{3}$
$x_{1}+x_{2} \leq 1$
$-x_{2}+x_{3} \leq 0$
$x_{1},x_{2},x_{3} \geq 0$
Note that constraints $x_{2} \geq 0$ follows from constraints $-x_{2}+x_{3} \leq 0$ and $x_{3} \geq 0$, and is thus redundant. You can check that after iteration 2, the value of the objective function remains the same $z = 1$. Due to degeneracy, basis change does not cause the iteration to follow an edge; we are still in the
same vertex.
The example was taken from here An Example of Degeneracy in Linear Programming
This example shows that redundancy may occur even if matrix $A$ has full rank.
Comment: Thank you for your reply. In the example you provided matrix A=[1 1;-1 1] has full rank, and yet we have degeneracy. Is there anything I am missing?
Comment: @Quick: thanks, you are right, I fixed the answer, so looks like we cannot make connection between redundancy and matrix $A$ with no full rank, and A = [1 1 0; 0 -1 1]


Why is entropy sometimes written as a function with a random variable as its argument?

Question: Why do people sometimes write the entropy as a function on a random variable?
For example, in some class notes I am seeing:
$$ \sum_X Q(X) \log Q(X) = - H_Q(X) $$
I realize this is not to be taken as super formal since there is abuse of notation mixing the random variable and its value, but even after taking that into account this doesn't seem to make a lot of sense because the entropy is a function of the distribution $Q$ alone. Why not simply write $H_Q$ or even $H(Q)$? Why keep the $X$ around?
Comment: Interesting question. Same applies to E[X] and Var[X] too.
Comment: Good point! And very interesting too, because I find E[X] and Var[X] very natural and intuitive while finding H_Q(X) not so intuitive. I guess when talking about expectation and variance, we are often focused on the random variable and there is a single distribution on that support, whereas entropy is often discussed in the context of more than one distribution over the same support.
Answer: This is notation that bypasses the distribution (similar to moments)
As can be seen from the formula, the entropy is fully determined by the probability distribution of the random variable, not the random variable itself.  In the formula you give in your question the object $X$ is used as an index of summation, so the summation does not depend on $X$ (it is "summed out" of the equation).  (Note that it is bad practice to use the same notation for the random variable and the index of summation.)  The notation you are referring to is similar to the notation for the moments of random variables, which are also fully determined by the distribution of those random variables.  I will try to explain the alternative notational methods here.

Two possible notations: If you take $Q$ to denote the mass function of the random variable (and let $\mathscr{X}$ denote its support) then a natural notation for the entropy would be:
$$H(Q) \equiv - \sum_{x \in \mathscr{X}} Q(x) \log Q(x).$$
However, if you accept the notation for moments, you could also reasonably denote the entropy as:
$$H(X) \equiv \mathbb{E}(-\log(X)) = - \sum_{x \in \mathscr{X}} Q(x) \log Q(x).$$
These two alternatives frame the notation either as a function of the distribution, or a function of the random variable.  In the latter case we use the same notational convention used for moments of random variables, which are also functions of the underlying distribution of the random variable.

Technical issues with moment notation: From a technical perspective, a random variable is a mapping on the sample space.  If we are working in the probability space $(\Omega, \mathscr{G}, \mathbb{P})$ then a random variable is a measureable function $X: \Omega \rightarrow \mathbb{R}$ from the sample space to the real numbers.  Importantly, the random variable does not contain the information on its own distribution, so it is impossible to define the entropy of the distribution ---or any moments of the distribution--- purely as a function of the random variable.  It is possible to obtain the probability distribution from the random variable $X$ and the probability measure $\mathbb{P}$, so such a function can have both arguments, but it cannot be a function only of the random variable.
This means that whenever we use moment notation (where we express moments as a function of the random variable rather than the distribution), the functions must be implicitly conditional on the underlying probability measure $\mathbb{P}$ or the specific distribution of the random variable in question.  Sometimes we have a function where one or more arguments are only implicit, and do not appear in the function notation, and so it is certainly possible to write moments (and the entropy function) in this way.  It is in common usage in statistical problems.
This notation is a convenience because it allows you to relate the moments/entropy directly to random variables rather than their distributions.
Comment: If you used $\Omega$ as a set of all possible outcomes why you also used $\mathscr{X}$ Aren't these the same support of $X$
Comment: Also isn't it better to use $H[X]$ instead $H(Q)$?
Comment: Thanks for the clarification on $\mathscr{X}$, although it is very [common](https://en.wikipedia.org/wiki/Entropy_(information_theory)) to write $H[X]$ we need to change.
Comment: Update: I have re-thought this answer and made a major change.  Apologies to anyone who upvoted prior to my change of views.
Comment: You may consider using $H[X]$ to further distinguish the two for the second case.
Comment: @EasyPoints: No, the set $\Omega$ is the sample space and the set $\mathscr{X} \subset \mathbb{R}$ is the support of $X$ (which is the subset of its range that has positive density.
Answer: It makes sense if you remember that X is a statistical ensemble, which has associated with it some probability distribution. For instance, the Wikipedia article for information-theoretic entropy consistently uses the notation $H(X)$. In that sense, it's actually the Q that's extraneous.
I can speculate two reasons your instructor includes the Q there.
The Q could be there to remind you what the associated probability distribution is. It could also be a preface to introducing concepts like cross-entropy, where you may take your average over a different distribution P. (The cross-entropy Wikipedia article exclusively uses distributions over the same support as arguments to the cross-entropy function.)
Answer: $H$ is just a letter some smart guy use for Entropy. It is possible to use even $E$ for entropy but then there will be confusion with the expected value.
In here $X \sim \mathcal D$, means $\mathcal D$ is probability distribution of discrete random variable $X$.
$$
H[X] = - \sum_{x \sim \mathcal D,  \\ x \in R_X} P(x) \log_2 P(x)
$$
where:

$P(x)$ is probability that $X=x$
$x \sim \mathcal D$ ($x$ is also drawn from $\mathcal D$)
$R_X$ is the support of $X$ (the set of all possible values $X$ can take)
Comment: Your summation notation is nonstandard and potentially confusing.  Because you are using a sum, you must be assuming $X$ is discrete.  Thus, the sum is a sum over all real numbers; but since its terms are zero except for the values of $X$ with positive probability, you may also write it as a sum over the support of $X.$  As usual, we are conventionally supposing "$P(x)\log_2 P(x)$" means $0$ when $P(x)=0.$
Comment: The notations here are ambiguous/confusing. $H[X]$ suggests that $X$ is the object whose entropy you're measuring. But then you also use $X$ as an index in the sum; it can't be both simultaneously. Also, some of the options here use generic symbols like $Pr$ to denote probability, without specifying the distribution
Comment: @user20160 is it bad still?
Comment: Yes, $X$ is discrete RV, this is what I assumed since OP used the $\sum$ as well. How I can denote that $x$ is a sampled from $X$, usually there is an index $i$ from 1 to $N$ means $N$ samples. I will check what is support. Good hints.
Comment: @whuber, I took your additional inputs and applied to the entropy formula for DRV.
Comment: For a discrete variable, the support is the set of values at which it has positive probability.  You can more simply write $-\sum_{x\in\mathbb{R}}P(x)\log_2 P(x)$ because (by definition) such a sum extends only over the terms that are nonzero, of which at most a countable number exist when $X$ is discrete. If you want to be specific you could write  $-\sum_{x\mid P(x)\gt 0}P(x)\log_2 P(x).$ The expression "$x\sim \mathcal{D}$" makes no sense, because you intend $x$ to be a *number.*
Comment: But probability cannot be negative unless quasi probability distribution, why we need to state this obvious facts, and also although $\mathbb R$  is a good option $R_X$ is more precise. I think you have a strong bias :) from the literature you take as a reference.
Answer: A possible perspective is that it better accommodates the notation for conditional entropy (or mutual information): consider the common notation $H_P(X|Y)$, where $P_{XY}$ is understood to refer to the joint distribution on $XY$, versus alternatives one might consider such as e.g. $H(P_X|P_Y)$, which might mislead one into thinking it is a function of the marginal distributions $P_X$ and $P_Y$ alone.
(Of course, $H(P_X|P_Y)$ is not the only way one could try to denote this, but it seems very likely that any notation for conditional entropy will need to refer to $X$, $Y$ and the joint distribution $P_{XY}$ in some form - so you might as well put it together as $H_P(X|Y)$.)
Though in any case, you're not alone in suggesting the notation $H(P)$ when there is only one random variable - it's used in some places, but mostly when there is no danger of confusion along the lines of what's mentioned above.


HTTP Persistent connection

Question: Trying to implement a simple HTTP server in C using Linux socket interface I have encountered some difficulties with a certain feature I'd like it to have, namely persistent connections. It is relatively easy to send one file at a time with separate TCP connections, but it doesn't seem to be very efficient solution (considering multiple handshakes for instance). Anyway, the server should handle several requests (HTML, CSS, images) during one TCP connection. Could you give me some clues how to approach the problem?
Comment: Did you consider using, or at least studying the source code of, some HTTP server free library in C like e.g. D.Moreno's [libonion](http://www.coralbits.com/libonion/)? Implementing an full HTTP server stack is a *lot* of work.
Answer: It is pretty easy - just don't close the TCP connection after you write the reply.
There are two ways to do this, pipelined, and non pipelined.
In a non-pipelined implementation you read one http request on the socket, process it, write it back out of the socket, and then try to read another one. Keep doing that until the remote party closes the socket, or close it yourself after you stop getting requests on the socket after about 10 seconds.
In a pipelined implementation, read as many requests as are on the socket, process them all in parallel, and then write them all back out on the socket, in the same order as your received them. You have one thread reading requests in all the time, and another one writing them out again.
You don't have to do it, but you can advertize that you support persistent connections and pipelining, by adding the following header in your replies:
<code>Connection: Keep-Alive
</code>
Read this:
http://en.wikipedia.org/wiki/HTTP_persistent_connection
By the way, in practice there aren't huge advantages to persistent connections. The overhead of managing the handshake is very small compared to the time taken to read and write data to network sockets. There is some debate about the performance advantages of persistent connections. On the one hand under heavy load, keeping connections open means many fewer sockets on your system in TIME_WAIT. On the other hand, because you keep the socket open for 10 seconds, you'll have many more sockets open at any given time than you would in non-persistent mode.
If you're interested in improving performance of a self written server - the best thing you can do to improve performance of the network "front-end" of your server is to implement an event based socket management system. Look into libev and eventlib.
Comment: Another huge advantage of using persistent connection (based on what I read from books) is to jump through the "slow-start" phase, make more usage of bandwidth.

HTTP Persistent connection


Is this undefined?

Question: My compiler warns: operation on j may be undefined
Here's the C code:
for(int j = 1; pattern[j] != '\0' && string[i] != '\0';){
    if(string[i+j] != pattern[j++]){//this is on the warning
        found = 0;
        break;
    }
}

Is that undefined?
Comment: Where is 'i' declared/initialized?
Comment: @MartinJames That's irrelevant.
Comment: You might find [this question](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points?rq=1) an interesting read.
Comment: I think problem is related to [Sequence points](http://www.geeksforgeeks.org/sequence-points-in-c-set-1/)
Comment: @2013Asker Which compiler did you use ?
Comment: @Saradhi I'm using gcc
Comment: Usually when someone asks whether something is UB in C, it is.
Comment: possible duplicate of [Why are these constructs undefined behavior?](http://stackoverflow.com/questions/949433/why-are-these-constructs-undefined-behavior)
Answer: YES. string[i+j] != pattern[j++] is having two different execution based on variable j without any sequence point in between. So it is example of undefined behaviour.
Comment: The [page](http://www.geeksforgeeks.org/sequence-points-in-c-set-1/) you requested is _now available_ :-)
Answer: Yes. The C11 standard says in §6.5:
If a side effect on a scalar object is unsequenced relative to either a different
side effect on the same scalar object or a value computation using the value of the
same scalar object, the behavior is undefined. If there are multiple allowable
orderings of the subexpressions of an expression, the behavior is undefined if such
an unsequenced side effect occurs in any of the orderings.

Here, in the comparison
if(string[i+j] != pattern[j++])

you are both incrementing the value of j with pattern [j++], and using the value of j in string [i + j]. The side effect of j++ is not sequenced relative to the value computation i + j. So this is classic undefined behavior.

Is this undefined?


nth prime divided by n

Question: So I was playing around in MATLAB and I plotted the following function;
$$f(n) = \frac{p_n}{n},  $$
where $p_n$ denotes the $n^{th}$ prime number (i.e. 5 is the $4^{th}$ prime number). The following plot emerged. The result looks a lot like a natural log. Indeed, plotting $e^{f(n)}$ as a function of $n$ reveals a straight(ish) line. From where does this regularity arise? Can this result be extrapolated to find other primes?
Comment: By the Prime Number Theorem we have $\pi(n)\sim\frac{n}{\log n}$ and $p_n\sim n\log n$, so, nothing unexpected.
Comment: Congrats on noticing!  Let $p_n =M$.  The prime number theorem says the number of primes equal or less than $M$ is roughly $\frac M{\ln M}$.  But we know this exactly $n$ by definition so $n \approx \frac {p_n}{\ln p_n}$ and $\ln p_n \approx \frac {p_n}{n}$ which is *exactly* your result.
Comment: " Can this result be extrapolated to find other primes?" Unfortunately not.  It can tells us approximately how many primes we can find in an interval but it can not tell us anything about which of those numbers are prime.
Answer: You are correct, the function is indeed in first approximation a natural log. The result you stumbled upon is the prime counting function $\pi(n)$, that counts how many primes there are smaller than $n$, for which one finds:
$$
\pi(n) \approx \frac{n}{\log n}
$$
and this is the same equivalent to saying that the $n$th prime would be expected to be close to $n \log n$.
Unfortunately this result can not be used to predict primes, but is important in number theory.

nth prime divided by n


How to use procedure within package in PL/SQL

Question: How to create a Package with Procedure in it?  Procedure will take designation and incentive as input and update the employee salary by adding the incentive for the given designation. Display the number of employee records that have got updated, e.g. '3 employee record(s) are updated'.
I have a table EMPLOYEE, with EMP_ID, EMP_NAME, SALARY and DESIGNATION.
The given Functional Requirements are:
Package name as  EMP_DESIGNATION, and
Procedure signature:
EMP_DETAILS(design employee.designation%TYPE, incentive number);

The code which I tried is -
set serveroutput on;
CREATE OR REPLACE PACKAGE EMP_DESIGNATION AS
 PROCEDURE EMP_DETAILS(
design employee.designation%TYPE,
incentive NUMBER) IS
BEGIN
UPDATE employee SET employee.salary = employee.salary + incentive
WHERE employee.designation = design;
dbms_output.put_line(SQL%ROWCOUNT || ' employee record(s) are updated');
END EMP_DESIGNATION;
END;
/

The output is-
Warning: Package Body created with compilation errors.
BEGIN
*
ERROR at line 1:
ORA-04063: package body "P10017.EMP_DESIGNATION" has errors
ORA-06508: PL/SQL: could not find program unit being called:
"P10017.EMP_DESIGNATION"
ORA-06512: at line 2

How to solve this error? Please help. Thank you in advance.
PL/SQL: Statement ignored
Comment: To find out how many rows are affected by DML statements, you check the value of SQL%ROWCOUNT
Answer: You have to create a package specification first, then its body. Something like this:
SQL> CREATE OR REPLACE PACKAGE emp_designation
  2  AS
  3     PROCEDURE emp_details (design employee.designation%TYPE, incentive NUMBER);
  4  END emp_designation;
  5  /

Package created.

SQL>
SQL> CREATE OR REPLACE PACKAGE BODY emp_designation
  2  AS
  3     PROCEDURE emp_details (design employee.designation%TYPE, incentive NUMBER)
  4     IS
  5     BEGIN
  6        UPDATE employee
  7           SET employee.salary = employee.salary + incentive
  8         WHERE employee.designation = design;
  9
 10        DBMS_OUTPUT.put_line (
 11           SQL%ROWCOUNT || ' employee record(s) are updated');
 12     END emp_details;
 13  END emp_designation;
 14  /

Package body created.

SQL>

Comment: You **MUST** end everything that began, but you must pay attention to what you're ending.
Comment: After making the changes still the code raised error, which I have mentioned, by editing it in the question above.
Comment: Changes you did were incorrect. Look again at my code. You can't END the package body first, and then END the procedure.
Comment: Oh so I should not end the begin, as we are ending both the procedure and package?


Como funciona o minificador de codigo?

Question: Estou perguntando isso porque eu fui minificar um JS e ele me deu um código que não entendi muito bem...
Meu código original:
$('input').each(function(a,b){if(b.value == "U"){$('.variacao-sku').remove()}});

O que ele me deu:
$("input").each(function(a,e){"U"==e.value&&$(".variacao-sku").remove()});

O código funcionou até, mas não entendi, ele não usou o if, verificou se a string "U" é igual a e.value e usou o operador && e removeu o item com o remove. Qual o sentido daquele && ali?
Answer: Essa técnica é chamada de curto circuito em expressões lógicas.
Quando você tem uma expressão lógica A && B, o resultado será verdadeiro se, e somente se, ambos operando forem verdadeiros, ou falso caso contrário. Assim, o interpretador irá primeiro avaliar o valor de A, se for considerado um valor falso, ele não precisará avaliar B, retornando A; se A for avaliado como verdadeiro, será retornado o valor de B, pois se B for falso, o resultado deverá ser falso e se verdadeiro deverá ser verdadeiro.
Portanto, na expressão:
"U" == e.value && $(".variacao-sku").remove()

O interpretador primeiro irá avaliar "U" == e.value, se for verdadeiro, irá avaliar (executar) $(".variacao-sku").remove(), produzindo o mesmo resultado que o código original:
if (b.value == "U") {
    $('.variacao-sku').remove()
}

Que é executar o remove() somente quando b.value for "U".
Comment: Caramba, isso é muito, muito interessante. Obrigado por isso. (sem ironia)
Answer: O seu código inicial já está mais ou menos minimizado, então o minify não alterou muito (formatação e nomes).
Agora para a validação:
O && interrompe a validação assim que encontrar algo em desacordo e não continua verificando o resto.
Exemplo:
Se (1 == 2 && a == b) {}

Nesse caso, em tempo de execução, a instrução a == b nunca será executada, porque assim que o compilador ver que 1 não é igual a 2, ele vai sair do if e nem vai se preocupar com o que tem para frente.
Agora se você fizer:
Se (1 == 2 & a == b) {}

Nesse caso, em tempo de execução, as duas instruções serão verificadas e só depois o computador vai decidir o que deve ser feito.
É até recomendável usar sempre && (ou ||) para evitar processamento desnecessário.

Como funciona o minificador de codigo?


Intersection multiplicity for two curves defined by $f=0,g=0$

Question: I want to understand how I can find the intersection multiplicity $I_p$ at a point $p$ for two curves $f,g$.

I have the example where
  $$ f(x,y) = y^2-x^3, \,\,\,\, g(x,y)=y^2-x^2(x+1) $$
  Then I am looking for the intersection multiplicity of the ideal $(f,g)$ at $p=(0,0)$.

My first attempt is to notice that $g(x,y)=y^2-x^3-x$ and the ideal $(f,g)$ can be written as $(f,g-f)=(y^2-x^3,x^2)$. But now I am stuck since I cannot find a way to possibly simplify this ideal as to conclude about the intersection form. Only step I can go further is to note that
$$ I_{(0,0)}(y^2-x^3,x^2) = 2I_{(0,0)}(y^2-x^3,x) $$
What would the next step be in order to determine $I_p$? In a previous example I was able to reduce the original ideal to an ideal involving only degree 1 curves concluding easily about what the multiplicity is. Now?
Comment: $(y^2-x^3,x^2)=(y^2,x^2)$ and the intersection multiplicity is 4.
Comment: @HuFei That I understand why the 2 goes outside. What I do not see is how you reduce $y^2-x^3$ to $y^2$.
Comment: @GaussTheBauss I do not understand your comment. The zeroes of a polynomial in two variable is usually called a curve
Comment: $Marion "Two surfaces" might be a better expression here.
Comment: I will change it.
Comment: How do you get the right hand side?
Comment: Follow your writing, $\cdots=2I_{(0,0)}(y^2-x^3,x)=2I_{(0,0)}(y^2,x)=4I_{(0,0)}(y,x)=4$.
Comment: @HuFei I mean why $(y^2-x^3,x^2)=(y^2,x^2)$. I do not see how you subtract this $x^3$.
Comment: @Marion You already have $(y^2-x^3,x^2)=2(y^2-x^3,x)$ when calculate the multiplicities, while the latter is equal to $2(y^2,x)$.
Answer: It doesn't look like anyone ever responded to your question, so here's an answer many days late (and many dollars short).
As Mohan said, $(y^2 - x^3, x^2) = (y^2, x^2)$.  Note that since $x^2 \in (y^2 - x^3, x^2)$, then $x^3 = x \cdot x^2 \in (y^2 - x^3, x^2)$.  Then $y^2 = y^2 - x^3 + x^3 \in (y^2 - x^3, x^2)$ as it a sum of elements of $(y^2 - x^3, x^2)$.  This shows $(y^2 - x^3, x^2) \supseteq (y^2, x^2)$, but in fact the reverse inclusion holds as well since $y^2 - x^3 = y^2 - x \cdot x^2 \in (y^2, x^2)$.
Fulton lists 7 axioms that you can use in computing intersection multiplicity in section 3.3 (pp. 36-37) of his book Algebraic Curves.  (The one I used above is axiom 7.)
Now we have to find the dimension over $k$ of the local ring $\left(\frac{k[x,y]}{(y^2,x^2)}\right)_{(x,y)}$.  One can show that you don't actually need to localize, and $1, x, y, xy$ forms a basis for the quotient ring, so the answer is 4, as stated in the comments.  (This also follows from axiom 6 of Fulton's book.)


Javascript drag div inside viewport container

Question: I am trying to achieve a drag and drop feature for mobile devices... there is a container div with a fixed width/height and inside it another div with contents but it's size is way bigger than the parent.
My issue is that once I click on the draggable div I am able to move it around but I don't really find any solution to keep the draggable element position the same every time I start touchmove on the screen..
I try to keep this as minimal as possible
Also I dont want to use jQueryUI
P.S. Dragging the element will only work on desktop by using touch emulation
Here is an example
JSFiddle
Here is my code

Comment: Your fiddle is empty.
Comment: You need the container div to 'mask' the draggable element? I got this right? What I know didn't get is: what is the draggable element supposed to do? You can drag it around. And then? Where it should be dropped (since its drag & drop) JSfiddle doesn't emulate mobile events, so I can't really test it.
Comment: That's the problem I encountered...I do not want to drag the element inside container from top left of it, I want to drag it from the position I touched the element .So basicly the element inside it should work same as in this fiddle http://jsfiddle.net/WBv9r/1/light/
Answer: You need to get the change in position not, the current position. So what this means is you'll need to get the pageX and pageY on touchstart save those in some variable you can access later, perhaps like this:
var touch_x= 0;
var touch_y= 0;

On touchstart you can set touch_x and touch_y to the current pageX and pageY.
Then on touchmove you can reference that and find the difference. So you dont move by pageX you move by touch_x - pageX. This will cause you to move in both positive and negative directions. Your current code will always have positive number and thus, only move in positive directions.
Comment: finally seems to work as expected, thanks alot for your help.. I got confused by solving this one since I never did anything like this :)
Comment: wait till you try adding in pinch and zoom ;)


Find a vector satisfying $\|x\|_2=1$ such that $\|Ax\|_2=\|A\|_2$

Question: Find a vector satisfying $\|x\|_2=1$ such that $\|Ax\|_2=\|A\|_2$
where $A=\begin{bmatrix}
-1 & 1\\
 2& 2
\end{bmatrix}$
I know that $\|A\|_2=\sqrt{\lambda_{\max}AA^T}$. But I'm not sure how to use this concept here.
Can some helps me here?
Comment: Well, the definition I'm used to is $$\|A\|_2=\sup_{\|x\|_2=1}\|Ax\|_2$$So, you just need to find the $x$ with norm $1$ which maximizes $\|Ax\|_2$.
Comment: A unit vector in $\mathbb{R}^2$ can be written $x = (\cos(t),\sin(t))$. You can use that to evaluate $\|Ax\|_2$ ass function of $t$ and then maximize it.
Comment: Are you sure about that definition? That gives a matrix when the matrix norm is a number.
Comment: @NinadMunshi:  Perhaps the OP means the largest eigenvalue $\lambda_{max}$ of the semi-definite matrix $AA^T$, so one takes the square root of a scalar.
Comment: @hardmath yeah, that's it. It is equivalent to the usual definition of norm 2, but he have written with a weird notation.
Answer: Hint: let $x = (\cos t, \sin t)$, then $\lVert Ax \rVert_2^2 = 5 + 3\sin(2t)$.
Remember that the operator norm is defined by $\lVert A \rVert = \sup_{\lVert x \rVert = 1} \lVert Ax \rVert$.


Docker-desktop for MacOs can't add /usr/local folder in Preferences/File-Sharing

Question: I'm using Docker Desktop vrs 18.104.22.168 (edge channel) on Mac Os Mojave. I need to include a file from /usr/local folder, as shared file in Docker's preferences, but the /usr folder is not displayed while browsing the folders. The option to write the folder/file name manually is also not available. See the print screens.
Does anyone have a clue how to add those folders in preferences?
File sharing paths are not manually editable
Folders like /usr or /Volumes don't appear in folder browsing
Update
I need to share this actual folder: /usr/local/share/dotnet/sdk/NuGetFallbackFolde and not entirely the /usr/local as I wrote above. But as I'm not able to select at least the /usr folder, this is why I've mentioned only the /usr/local folder.
Update
I've downgraded progressively up to Docker Community Edition 184.108.40.206 2019-02-15. That seems to be the last version with the old user interface. With this version the folder browser dialog from file sharing displays all the folders and also manual editing of the file paths works.
On versions Docker Desktop Community 18.104.22.168 and Docker Desktop Community 188.8.131.52, which have the new UI, it doesn't work.
Comment: The same thing happens also with version 184.108.40.206 (stable channel)
Comment: so the way to fix the manual entry is to use `Docker Community Edition 220.127.116.11 2019-02-15`, right?
Answer: I have faced the same problem and could sort it out using the latest docker version.
You can edit ~/Library/Group\ Containers/group.com.docker/settings.json.
Then add whatever path you need, in my case was a synthetic link (created through synthetic.conf), this way by manual editing the file the UI does not auto resolve the link so it works well.
{
  "filesharingDirectories" : [
    "\/Users",
    "\/Volumes",
    "\/datadrive",
    "\/private",
    "\/tmp"
  ],

Comment: For anyone having a hard time finding this file, ensure you escape the space between 'Group' and 'Containers'  with a backslash  e.g `vim ~/Library/Group\ Containers/group.com.docker/settings.json`
Comment: Also need to restart docker afterwards in order for it to appear - thanks for the tips ^
Comment: I faced this on docker desktop v4.15.0 ( latest today ) and solved using this, Thanks @Federico
Comment: Still works for osx V4.22.1 (118664)
Answer: In the File Sharing tab of Docker's Preferences, click the Add Directory button (+) and browse to the root directory of your Mac drive. Now press Command+Shift+Dot to show hidden directories. This will make the usr directory visible.
You will now be able to browse to the /usr/local/share/dotnet/sdk/NuGetFallbackFolder directory.
Answer: I think you have to add application to the list of trusted apps. Take a look here:
http://www.owsiak.org/macos-mojave-and-accessing-timemachine-data/
Unless you add Full Disk access, applications are not able to browse certain areas of your volume.
Update
Unfortunately, it looks like giving access to whole drive is not a solution in this case.
It looks like Docker Desktop is not quite happy with sharing /usr/local directory.
Comment: Unfortunately it didn't help. I've added Docker, restarted it, restarted even the OS and it's still the same issue. Anyway, other apps are displaying all folders and are not granted full access in security & privacy mac os settings.
Comment: You are right. It's a different issue. According to Docker Desktop, `/usr`, `/usr/local` are reserved and it's not possible to add them inside `File Sharing`.
Comment: Can you please point me to where you've seen this documentation, that it's impossible? I'm building a simple sample from .net core documentation, and it's the .net core that needs access to these paths. Moreover Docker Desktop is showing only 4 folders, so much more folders are missing, not only the /usr. All the folders that are by default shared /Users /Volumes /private and /tmp are not visible when browsing. So for instance if I remove one of these folders from File Sharing, I can not add it back.
Comment: In my case, this is a message I am getting when I try to add `/usr`. I will add it to answer.
Comment: I see. I need actually to add this specific subdirectory `/usr/local/share/dotnet/sdk/NuGetFallbackFolder`, but I didn't mentioned all subfolders, as I don't see the option to add any subfolder under `/usr`. Are you using Docker on Linux or how were you able to at least try to add the `/usr/local ` folder?
Comment: I am using it on macOS. If I double click path, I am able to edit it. No issues here.
Comment: I see. So on my mac OS this doesn't work with Docker Desktop version 126.96.36.199. When I'm double clicking an existing path, there's no option to edit it. Check out this video here: https://youtu.be/_z5mZC0aMII


Reference for generalized linear mixed models using Laplace approximation

Question: I'm fitting a generalized linear mixed model in R using the Laplace approximation. I'm looking for a reference for the Laplace approximation used for that, or a reference regarding the comparison between the PQL and Laplace methods for fitting generalized linear mixed models.
Answer: Here are some papers:
Breslow and Clayton, 1993:  Approximate Inference in Generalized Linear Mixed Models.
Tierney and Kadane, 1986: Accurate Approximations for Posterior Moments and Marginal Densities.
Breslow, 2003: Whither PQL?.
Tuerlinckx, et al. 2006: Statistical Inference in generalized linear mixed models: A review.
Wolfinger, 1993: Laplace's approximation for nonlinear mixed models.
Vonesh, 1996: A Note on the Use of Laplace's Approximation for Nonlinear Mixed-Effects Models.
Comment: See also the `INLA` package and papers by Havard Rue.
Comment: Is there any literature on Laplace approximation for discrete distribution?


How to batch convert sentence lengths to masks in PyTorch?

Question: For example, from
lens = [3, 5, 4]

we want to get
mask = [[1, 1, 1, 0, 0],
        [1, 1, 1, 1, 1],
        [1, 1, 1, 1, 0]]

Both of which are torch.LongTensors.
Answer: One way that I found is:
torch.arange(max_len).expand(len(lens), max_len) < lens.unsqueeze(1)

Please share if there are better ways!
Answer: Just to provide a bit of explanation to the answer of @ypc (cannot comment due to lack of reputation):

torch.arange(max_len)[None, :] < lens[:, None]

In a word, the answer uses broadcasting mechanism to implicitly expand the tensor, as done in the accepted answer. Step-by-step:

torch.arange(max_len) gives you [0, 1, 2, 3, 4];

adding [None, :] appends 0th dimension to the tensor, making its shape (1, 5), which gives you [[0, 1, 2, 3, 4]];

similarly, lens[:, None] appends 1st dimension to the tensor lens, making its shape (3, 1), that is [[3], [5], [4]];

By comparing (or doing anything like +,-,*,/, etc) a tensor of (1, 5) and (3, 1), following the rule of broadcasting, the resulting tensor will be of shape (3, 5), and the result values will be result[i, j] = (j < lens[i]).
Answer: torch.arange(max_len)[None, :] < lens[:, None]
Comment: Try to give a description about your answer. It will help others to easily catch your code.Refer https://stackoverflow.com/help/how-to-answer


Stuck on Inverse Laplace transform, trying to convert convolution to ODE

Question: I want to express a convolution of a known signal $b(t)=c(t)\ast h(t)$ as an ODE $b'(t)$ instead.
The kernel $h(t)$ takes a double exponential form $Au(t)(1-e^{-T_{on} t})e^{-T_{off} t}$.
After rearranging and doing Laplace transforms, I get a lone $s$ term, the inverse of which I understand would be $\delta'(t)+\delta(0)$.
This ends up on the right hand side of $\beta'=b''$:
$$\beta' = \dots - b(0)(\delta'(t)+\delta(0))$$
Is my cause hopeless at this point?
Here is my work in detail:

EDIT:
DinosaurEgg solved it! Looks like I was close, but missing two pieces:

I got $H(S)$ wrong, by forgetting the minus sign, I got $2s+\lambda+\kappa$ on top instead of $\lambda-\kappa$.
It didn't occur to me to simply assume $b(0)=b'(0)=0$. This works just fine. In the screenshot below, you can see the ODE solution is a little bit off at the beginning when that assumption is violated (look at $b_\text{conv}/b_\text{ode}$), but quickly corrects itself.
Comment: It is also helpful if you show some work as it shows you have put some effort, and also helps others identify any mistakes along the way.
Comment: Is $u(t)$ the unit step function?
Comment: Yes, $u(t)$ is the unit step function. I'll attach screenshots with my work--it was a lot to try to format right with MathJax, after having struggled to get it right with KaTeX
Answer: The result is actually quite a bit simpler. To declutter the notation a bit I will set $\kappa=\tau_{\text{off}}^{-1}, \lambda=\tau_{\text{off}}^{-1}+\tau_{\text{on}}^{-1}$
and then one calculate the Laplace transform of the kernel $h(t)$, which is
$$H(s)=\frac{\lambda-\kappa}{(s+\kappa)(s+\lambda)}$$
which after clearing denominators, gives the following relation for $B(s)$
$$(s^2+(\kappa+\lambda)s+\kappa\lambda)B(s)=(\lambda-\kappa)C(s)$$
The reason why we wrote the relation this way is because Laplace transforms multiplied by integer powers of $s$ can be rewritten as Laplace transforms of derivatives of the function. In your case, noting that $b(0)=b'(0)=0$, we find that from standard properties of the Laplace transform that
$$\mathcal{L[b'(t)](s)}=s\mathcal{\mathcal{L}[b(t)](s)}~~,~~\mathcal{L[b''(t)](s)}=s^2\mathcal{\mathcal{L}[b(t)](s)}$$
which allows us to write the relation after undoing the Laplace transform as
$$b''(t)+(\kappa+\lambda)b'(t)+\kappa\lambda b(t)=(\lambda-\kappa)c(t)$$


What better for memory usage: define constants in subs or in module

Question: I understand that is some of VB basics, but can't figure out how to ask google:
How VBA manage constants? In some languages compiler replace them by values. But how that works in VBA? Will it matter if i declare them in sub/function, not in global space. Especially, if a sub/function is called many times in runtime.
I'm often declare function name and some other strings as constants in sub/function space - it's easier for me to read my code.
For example: SUB_NAME in Get_AppExcel_Ref() in code below, to use it for logging error events.
If the Get_AppExcel_Ref() will be called couple times while programm running -  SUB_NAME will be allocated in memory once, on first run, or on every call? Or maybe there is some kind perfomance issue and better declare SUB_NAME as global.
Private Sub Get_AppExcel_Ref(ByRef appObject As Object)
  Const SUB_NAME As String = "Get_AppExcel_Ref"

  On Error GoTo ERR_NOT_OPENNED
  Set appObject = GetObject(, "Excel.Application")
  Exit Sub

ERR_NOT_OPENNED:
  If Err.Number = 429 Then
    Err.Clear
    Set appObject = CreateObject("Excel.Application")
  Else
    Call LOG.printLog("open Excel", Err, SUB_NAME)
  End If
End Sub

'LOG - user class type variable, printLog params: Description, Error, Source Name

Comment: A `Const` declared local has local scope so it will not be known outside that scope.
Comment: A `Const` such as your string, will be stored somewhere in memory (otherwise its value will not be known). So for memory usage it doesn't matter if you declare it local or global.
Comment: A `Const` in VB is probably implemented as a read-only variable. It will exist only once in memory, independent of how often you call the fuction where it is declared. The compiler/interpreter may fold multiple identical Const values onto a single value, thus saving memory. But I wouldn't worry about these things for VB.
Comment: I can't imagine why this code is actually necessary. If nothing else it won't work with a `Private Sub` followed by `End Function`
Comment: CallumDA, this my mistake, sorry for misslead. Changed "function" to "sub" in my code, but forgot to do full replace in this example. Of course there - 'private sub: exit sub: end sub'.
Answer: Declaring your Const as global will make no sense, as it would display the same string, no matter where you would use it.
You could declare it as a global variable (for example to save the extra parameter to you logging routine) and assign the name of the routine, but you would have the name of you routine as a (constant) string in your code also (so same amount of memory used). And at the end, it will completely mess up your logic, because when calling a subroutine, the content will be overwritten and when after that call an error occurs, your log will show the wrong routine name. So don't go that path.
As Paul Ogilivie writes in his comments, think about a constant as a read-only variable - and don't waste any thoughts about the exaxt implementation (but I think it is save to assume that the string is put only once in memory). You have more than enough memory available for your VBA code, and string handling is so fast that you will never experience any runtime issues.
My credo: Use everyhing as it fits your needs as programmer best - and readability is an important aspect to this. Don't care too much about memory consumption or runtime speed - except if you really hit problems. And if you do, these are most likely caused by other things.
Answer: Firs of all, welcome to SO.
I think the VBA compiler does also replace constants with their values, as with other languages. So they are not the same as variables.
I don't think a constant is necessary here. I only tend to use them for parameters, not just to replace any string.
Your code would be just fine like this:
LOG.printLog "open Excel", Err, "GetAppExcelRef"

Comment: Thank you for answer. This is not best example, that i choose to show. And it's realy looks questionable to use const here vs put exact string in calling method. But there is some ground for that decision. It's like the scheme that i use to create methods. Copy/paste some abstract constructions (predefined const with method name and log calling) + some troubles with adequate naming at first approach led me to this solution. With my modest experience in programming that approach produce less mistakes. ;) Like using obsolete "Call" for better code reading in VBA IDE.


Find dimension of $V$ and $W$

Question: Let $V$ denote vector space $C^{5} [a,b]$ over $\Bbb R$ and
$$W=\left \{f\in V: \frac{\mathrm d^{4}f}{\mathrm dt^{4}}+2\frac{\mathrm d^{2}f}{\mathrm dt^{2}} - f =0\right \}$$
What are the dimensions of $V$ and $W$?
Comment: The first one is very easy, for the second try to make the ansatz $f(t)=ae^{\lambda t}$, which values for $\lambda$ are possible?
Comment: Thnx all of u 4 ur valuable time and support. @Fakesupport ur explanation is too good.
Answer: We have
$$ \dim V= \infty$$
and
$$ \dim W= 4.$$
Comment: Let's hope he understands it
Answer: $V$ is infinite dimensional, you can easily see that every polynomial, or exponential function, sine function, etc. are elements of $V$. $W$ however, is a smaller space. The elements can be found by simply solving the ODE. Since no boundary/intial values are given, these will be the valid solutions up to some constants, the ODE should tell you how many.

Find dimension of $V$ and $W$


Disable msgbox for Command Button that increments offset cell up 1 each time but shows error msgbox if above row 1

Question: I have a command button that moves the activecell.offset up one cell each time the button is pressed.
<code>    ActiveCell.Offset(-1, 0).Select
</code>
However, whenever the cell reaches the first row the next time it is pressed the following error appears:
"Run-Time error '1004':
Application-defined or object defined error."
Should I implement code to look and see if it row is > 1 or if column is > 1 ??
I don't mind if the function does nothing, I just don't want the msgbox to show up. Is there an easier way that I am unaware of?
Comment: How can you go up one row from the first row??! Add an If clause.
Comment: A simple : If ActiveCell.Row > 1 then ActiveCell.Offset(-1, 0).Select
Comment: Sorceri, your comment got me to get it to work. Thank you very much!
Answer: Sorceri answered this question.
his code:
<code>    If ActiveCell.Row > 1 then ActiveCell.Offset(-1, 0).Select
</code>
Thank you sir!


Finding correlation between two data sets in R

Question: UPDATED DATA SET 2 and 1 STRUCTURE: Sorry for this sudden update. I have two data sets. The structure of my first data set is (when using print(matr1) in R):
        month_year  income
 [1,]  "Jan 2000"  "30000"
 [2,]  "Feb 2000"  "12364"
 [3,]  "Mar 2000"  "37485"
 [4,]  "Apr 2000"  "2000"
 [5,]  "Jun 2000"  "7573"
          .     .      .
          .     .      .

Thus the first data set has one income value for each month of each year.
The structure of my second data set is (when using print(matr2) in R):
     month_year     value
 [1,] "Jan 2000" "84737476"
 [2,] "Jan 2000" "39450334"
 [3,] "Jan 2000" "48384943"
 [4,] "Feb 2000" "12345678"
 [5,] "Feb 2000" "49595340"

          .     .      .
          .     .      .

So in this second data set I have n(say 100 but not constant all the time) number of values for each month of each year.
Both the data sets have values month wise for many subsequent years(like for all the months for year 2000, 2001 and so on). Now I want to find the correlation between these two data sets but month-wise and not as whole. When I use the R command cor(as.numeric(matr1[,"income"]),as.numeric(matr2[,"value"])) then I get the overall correlation but I want the correlation per month rather than as a whole. I want the correlation something like this:
                  Jan | Feb | Mar | Apr | May | .....
Correlation        x  |  y  |  z  |  p  |  q  | .....

The issue that I have is:

How do I get the correlation value per month instead of the overall correlation?

NOTE: I am not sure whether I should have posted this question here or on Cross Validated. I had posted a question for this data set only regarding an error in getting correlation and it was migrated from there to here. So please forgive if I am posting this on wrong place.
UPDATE1: After some suggestion I have modified this post to point in the correct dimension. First of all, the data sets as of now are in matrix format and hence the quotes. I can convert it to data.frame as suggested by some comments but right now I have been calculating the correlation by converting the columns using as.numeric.
Comment: Does each of your data sets have one income/value for each month/year? Then how do you expect to compute a correlation? Apart from that statistical query, your question needs a lot of other help, such as why is everything in quotes (A: you haven't read your data in properly) and how do I convert things to dates (A: see about a hundred other SO questions and/or install the "lubridate" package).
Comment: @Spacedman, everything in quotes because he has a matrix, and matrix can't have both character and numeric classes at the same time, so the coercion hierarchy was implemented here by default I guess.
Comment: I see you're using a matrix. `data.frame` or `ts` object would be more appropriate for these sort of matters.
Comment: @Spacedman I have done some modification to above post. I understand that by having only one value of month in each data set we cannot get the correlation. I have values for month for each year in both data sets(for April in 2000 as well as 2001 and so on in each data set and for each month in that way)
Answer: May be you can try:
dat1 <- structure(list(year = c(2000L, 2000L, 2000L, 2000L, 2000L, 2001L,
2001L, 2001L, 2001L, 2001L), month = c(1L, 2L, 3L, 4L, 5L, 1L,
2L, 3L, 4L, 5L), income = c(30000L, 12364L, 37485L, 2000L, 7573L,
25000L, 14364L, 38485L, 4000L, 7873L)), .Names = c("year", "month",
"income"), class = "data.frame", row.names = c(NA, -10L))

dat2 <- structure(list(month_year = c("Jan 2000", "Feb 2000", "Mar 2000",
"Apr 2000", "May 2000", "Jan 2001", "Feb 2001", "Mar 2001", "Apr 2001",
"May 2001"), value = c(84737476L, 39450334L, 48384943L, 12345678L,
49595340L, 84337476L, 34450334L, 48984943L, 124545678L, 49525340L
)), .Names = c("month_year", "value"), class = "data.frame", row.names = c(NA,
-10L))

 dat1$month_year <- paste(month.abb[dat1$month], dat1$year)
 dat1$month <- gsub(" \\d+","", dat1$month_year)
 dat2$month <- gsub(" \\d+","", dat2$month_year)
 dat1$indx <- with(dat1, ave(month, month, FUN=seq_along))
 dat2$indx <- with(dat2, ave(month, month, FUN=seq_along))
 dat1 <- dat1[,c(2,3,5)]
 dat2 <- dat2[,c(3,2,4)]
 colnames(dat2)[2] <- "income"

 library(reshape2)

 dat2C <- dcast(dat2, indx~month, value.var="income")
 dat1C <- dcast(dat1, indx~month, value.var="income")
 m1 <- as.matrix(dat1C[,-1])
 m2 <- as.matrix(dat2C[,-1])
 cor(m1,m2)
  diag(cor(m1,m2))
 # Apr Feb Jan Mar May
  #1   -1   1   1  -1

Also, if you can merge the two datasets together, this could be done using data.table. Using the dput() data above
 library(data.table)
 dat1$month_year <- paste(month.abb[dat1$month], dat1$year)
 dat1 <- dat1[,c(4,3)]
 setDT(dat1)
 setDT(dat2)
 setkey(dat2, month_year)

 dat2[dat1, income := i.income]
 dat2[,month:= gsub(" \\d+", "", month_year)][,cor(value, income), by=month]
 #    month V1
 #1:   Apr  1
 #2:   Feb -1
 #3:   Jan  1
 #4:   Mar  1
 #5:   May -1

Update
dat1 <- structure(list(month_year = structure(c(5L, 3L, 8L, 1L, 7L, 6L,
4L, 9L, 2L), .Label = c("Apr 2000", "Apr 2001", "Feb 2000", "Feb 2001",
"Jan 2000", "Jan 2001", "Jun 2000", "Mar 2000", "Mar 2001"), class = "factor"),
income = c(30000, 12364, 37485, 2000, 7573, 42000, 15764,
38465, 5000)), .Names = c("month_year", "income"), row.names = c(NA,
-9L), class = "data.frame")

 dat2 <-  structure(list(month_year = structure(c(5L, 5L, 5L, 3L, 3L, 7L,
 7L, 7L, 1L, 1L, 6L, 6L, 4L, 4L, 8L, 8L, 2L, 2L, 2L, 2L), .Label = c("Apr 2000",
 "Apr 2001", "Feb 2000", "Feb 2001", "Jan 2000", "Jan 2001", "Mar 2000",
 "Mar 2001"), class = "factor"), value = c(84737476, 39450334,
 48384973, 12345678, 49595340, 4534353, 43353325, 84333535, 35343232,
 4334353, 3434353, 5355322, 5223345, 4523535, 345353, 32235, 423553,
 233553, 423535, 884455)), .Names = c("month_year", "value"), row.names = c(NA,
 -20L), class = "data.frame")

 datN <- merge(dat1, dat2, all=T)
 library(data.table)
 DT <- data.table(datN)
 DT[, month:= gsub(" \\d+", "", month_year)][,cor(value, income),by=month]
 #   month         V1
 #1:   Apr -0.7136049
 #2:   Feb -0.7037676
 #3:   Jan -0.8637808
 #4:   Jun         NA
 #5:   Mar -0.6484684

Comment: Thanks for your answer but there is some update in my data set 2 structure. Now in data set 2 I have multiple values for each month but data set 1 still has one value for each month. I have modified my post above. How will the approach get modify now for this situation? Also, I have transformed the `year` and `month` structure of data set 1(and joined these two columns) to match with `month_year` structure of data set 2.
Comment: I am having a bit difficulty in understanding with what exactly are you doing in forming `dat1` and `dat2`? The data set that I have shown is a sample data set to show the structure and the values in those data sets are getting generated automatically, like from a database or a csv file. The values are not entered manually.Though the structure of data set is as I have shown. I apologize for a bit confusion that I am having
Comment: @Jason Donnald.  Your dataset is difficult to reproduce.  But, if you copy the one I showed, it would be easier to get the result.  I used `dput`.  For example, after you read the dataset i.e. `dat <- read.table("file.txt" , sep=""); `dput(head(dat, 20))` would give the structure.
Comment: that's the issue that the values are not fixed that I can manually enter like the way you have shown.And neither its specific that how many values will be there.Hence I am having difficulty in understanding how to form a generic structure with the kind of data set that I have?
Comment: @Jason Donnald.  The use of `dput` is for portability.  If you show your dataset like the way you showed and some columns are `character` columns, the reader may not be able to judge whether that column is `factor` or `character`.  Using `dput`, it gives the structure, and thus easier to understand the problem. Did you tried reading the data and `dput(head(dat,20))`
Comment: I tried using `dput(head(dat1,20))` and `dput(head(dat2,20))` and then do the steps as shown above but all I get a correlation result is `NA`. The issue is that in my data set 1 I have one value for each month of each year but in my data set 2 I have multiple values for each month of each year. So this difference in number of overall rows (either month wise or as a whole) is creating issues.
Comment: @Jason Donnald, I tried to replicate the issue in the updated dataset (which you can check).  Regarding the NAs, the correlation calculation depends upon standard deviation, which will be the one creating the problem.
Comment: Yes the standard deviation is coming zero and the reason for that I think is because of difference in size of data set(both month wise and overall). How can it be resolved?
Comment: @Jason Donnald. If standard deviation is the issue, you need more data to solve it.
Comment: but more data in which data set? My second data set has around 1000+ rows while first data set has around 100 rows. could this be issue?
Comment: @Jason Donnald, As you mentioned earlier, one of the dataset have only single rows for each month.  When this dataset gets merged to second dataset, it creates only duplicated rows.  If there is no variability for that month, this will affect the SD.
Answer: Get your data into a data frame with month, value, and income columns. EG:
d = data.frame(month=rep(1:12,5),value=runif(60,10000000,60000000), income=runif(60,5000,40000))

> head(d)
  month    value   income
1     1 58348424 34478.63
2     2 59512513 16179.46
3     3 21844994 20961.56
4     4 25843593 38502.16
5     5 24805863 12397.32
6     6 24200966 24110.27

Then its as simple as using dplyr to group by month and summarize:
> require(dplyr)
> d %.% group_by(month) %.% summarize(cor = cor(value, income))
Source: local data frame [12 x 2]

   month         cor
1      1  0.17774478
2      2 -0.61693145
3      3 -0.05692027
4      4 -0.44966542
5      5 -0.30049386
6      6  0.09447414
7      7  0.67567298
8      8  0.14363810
9      9 -0.71899361
10    10  0.20807679
11    11 -0.42560100
12    12  0.23584150

Getting the month number from a date string is covered in many other places... but here I'd use the lubridate package. For the month/year strings in your second data set, for example:
require(lubridate)
month(dmy(paste("01",dat2$month_year)))

returns the month number. Note the trick of sticking a "01" on the start to make it a valid date.
Comment: Thanks for your answer but there is some update in my data set 2 structure. Now in data set 2 I have multiple values for each month but data set 1 still has one value for each month. I have modified my post above. How will the approach  get modify now for this situation?
Comment: Also, I have transformed the `year` and `month` structure of data set 1(and joined these two columns) to match with `month_year` structure of data set 2.


Strong mints make my voice sound way better. Is there any way to keep this effect?

Question: I've recently noticed that having a strong mint before I sing makes it a lot easier to hit notes (and to hold them with less wavering), it increases my vocal range, and altogether just makes my voice sound a whole lot better even while just talking. Unfortunately this only lasts for around 10-15 minutes after the mint is gone.
I don't know much about this (so please correct me if I'm mistaken) but I'm assuming the mint opens my airways more or relaxes some muscle in my throat which causes these positive effects on my voice.
My question is: Is there a way that I can retain these effects for longer periods of time, or even permanently? Perhaps there are some vocal training exercises I could do?
Answer: You are correct that menthol can act as a muscle relaxant, and that relaxed muscles in the throat will help with your singing.
There are numerous exercises for singers designed to work on throat relaxation. A google search with "vocal exercises relax throat" or "how to relax throat muscles for singing" will give you plenty of material to check out.
You can also look into the bel canto technique, which includes relaxation work as part of it.