Javascript Function Encapsulation

Question: i am getting undefined undefined when i defined and call the setTimeout function as follow:
var person = {
    first: 'joe',
    last: 'doe',
    getName: function(){
        console.log(this.first + ' ' + this.last);
    }
}

setTimeout(person.getName(), 2000);

unless if i wrap the person.getName() in a function as follow:
setTimeout(function(){
    person.getName()
}, 2000);

Now i am getting a right output. Why it's so?
Comment: Did you call the settimout function before you initialize person
Comment: Actually your first example works and puts `joe doe`, but doesn't wait for the timeout…
Answer: Assuming you meant:
var person = {
    first: 'joe',
    last: 'doe',
    getName: function(){
        console.log(this.first + ' ' + this.last);
    }
}

setTimeout(person.getName, 2000);

The reason you get undefined is that what you are effectively doing is :
var somefunc = person.getName;
setTimeout(somefunc, 2000);

So somefunc gets called in the context of window. i.e. window.somefunc()
However when you do
setTimeout(function(){
    person.getName()
}, 2000);

The context of getName is preserved as you are Calling (not passing around) person.getName
Comment: What he's effectively doing is `var somefunc = person.getName();`, which sets `somefunc()` to whatever `person.getName()` returns. Context is not the problem, the issue is calling versus referring.
Answer: I have just answerd for something similar here :
How can I pass a parameter to a setTimeout() callback?
The setTimeout function fix the context to the window, so it's not possible to do what you want !
To do it i have wrapped the setTimeout function in another one which can set the context :
myNass_setTimeOut = function (fn , _time , params , ctxt ){
return setTimeout((function(_deepFunction ,_deepData, _deepCtxt){
            var _deepResultFunction = function _deepResultFunction(){
                //_deepFunction(_deepData);
                _deepFunction.apply(  _deepCtxt , _deepData);
            };
        return _deepResultFunction;
    })(fn , params , ctxt)
, _time)
};

// lets try this functions :
for(var i=0; i<10; i++){
   setTimeout(function(){console.log(i)} ,1000 ); // stock setTiemout in closure
}

for(var i=0; i<10; i++){
   setTimeout( console.log(i) ,1000 ); // stock setTiemout direct call
}

for(var i=0; i<10; i++){
   setTimeout(console.log ,1000 , i); // stock setTiemout not compatible IE
}

for(var i=0; i<10; i++){
   myNass_setTimeOut(console.log ,1000 , [i] , console); // wrapped setTimeout
}

So to answer your question :
var person = {
    first: 'joe',
    last: 'doe',
    getName: function(){
        console.log(this.first + ' ' + this.last);
    }
}

setTimeout(person.getName(), 2000);

When you launch : setTimeout(person.getName(), 2000); setTimeout will execute in the future 2s (2000ms) the 1st argument !
But what is the value of your 1st argument ? : the result of your function person.getName( ),
so it's equivalent of :
var _arg1 = person.getName();
setTimeout(_arg1 , 2000);

which is very different of :
var _arg1 = person.getName;
setTimeout(_arg1 , 2000);

The first case you pass the result of a function to setTimeout which wait a reference to a function.
In the second case you pass a reference to a function (good it's what expected), but not in the good context !
So, now you have to fix the context :
whith the core javascript function :apply
Now try this :
var _arg1 = function(){ person.getName.apply(person) };
setTimeout(_arg1 , 2000);
myNass_setTimeOut(person.getName , 2000 , null , person);

So you have two choice :

Fixing the context for every argument you pass to setTimeout.
Use a function which do it for you

the myNass_setTimeOut function will make the trick !
Now, let see something a little bit more deeper :
var person = {
        first: 'joe',
        last: 'doe',
        getName: function(){
            console.log(this.first + ' ' + this.last);
        } ,
        say : function(sentence){
             console.log(this.first + ' ' + this.last + ' say : ' + sentence)
        }
    }

How could pass argument sentence to a setTimeout ?
var heSay = "hello !"; setTimeout(person.say(heSay) , 1000 ); heSay = "goodBye !";
// not good : execute immediatly

var heSay = "hello !";setTimeout(function(){person.say(heSay)} , 1000 ); heSay = "goodBye !";
// not good : hesay googbye

var heSay = "hello !"; setTimeout(person.say , 1000 , heSay); heSay = "goodBye !";
// not good bad context

var heSay = "hello !"; setTimeout(function(whatHeSay){person.say(whatHeSay)} , 1000 , heSay);heSay = "goodBye !";
// GOOD ! ok but not compatible with IE

var heSay = "hello !"; myNass_setTimeOut(person.say , 1000 , [heSay] , person ); heSay = "goodBye !";
// just good !

hope this help you !
edit :
for modern browser suporting bind don't take care about that do what say
here @dandavis
Answer:
you call it too early.
the this gets broken when you save a function ref without the object it's attached to.

solution?
use bind and don't call it early:
var person = {
    first: 'joe',
    last: 'doe',
    getName: function(){
        console.log(this.first + ' ' + this.last);
    }
}

setTimeout(person.getName.bind(person), 2000);

Answer: Your first function works fine for me (tested in Chrome):
http://jsfiddle.net/fzrxK/1/
var person = {
    first: 'joe',
    last: 'doe',
    getName: function(){
        alert(this.first + ' ' + this.last);
    }
}

setTimeout(person.getName(), 2000);

Perhaps there's another issue elsewhere?
Comment: I updated the code for an 'alert' instead of console.log - still seems to work fine for me both ways...
Comment: Ahh - I understand you now.  Seems there was more than one error in the original code.
Answer: Calling person.getName() executes the function and returns undefined (as nothing was declared to return in that function).
What you wanted was:
setTimeout(person.getName, 2000);

Calling setTimeout(person.getName(), 2000); sets a timeout to execute the results returned by person.getName() which is undefined rather than a function.
Calling setTimeout(person.getName, 2000); sets a timeout to execute the function person.getName.
With parenthesis executes the function. Without parenthesis passes the variable (which happens to be defined as a function).
Edit: As @Isaac points out, passing the function person.getName in also changes the behavior of this so that is likely not what you wanted either.
Comment: `setTimeout(person.getName, 2000)` is what he actually did, otherwise he wouldn't have got the `undefined undefined` output in console…
Answer: var person = {
    first: 'joe',
    last: 'doe',
    getName: function(){
        console.log(this);
    }
}
person.getName()
setTimeout(person.getName, 2000);

Outputs:
Object {first: "joe", last: "doe", getName: function}
Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}

My guess is, JavaScript pulls the getName function out of the scope of person
Comment: Also, note that `setTimeout(person.getName, 2000);` is different to `setTimeout(person.getName(), 2000);`
Comment: You are right: http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/
Comment: `person` is not a scope. It's the context of the call `person.getName()`, and also that function never was "in" there to be "pulled out"
Comment: http://en.wikipedia.org/wiki/Scope_(computer_science) Well actually, `scope == context`, so I'd still be correct

Javascript Function Encapsulation


Typescript - Can't find the constructor method inside the module

Question: I have the following issue.
I have created a sample project using angular-cli tool and I have the following code inside the app.component.ts file
import { Component } from '@angular/core';
import * as Stomp from '@stomp/stompjs';
import * as SockJS from 'sockjs-client';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  stompClient: any = null;

  constructor(){
      this.connect();
  }

  connect() {
      let socket: any = new SockJS('http://localhost:8083/gs-guide-websocket');
      this.stompClient = Stomp.over(socket);
      this.stompClient.connect({}, (frame) => {
          ...
      });
  }
}

In package.json file I have this:
"dependencies": {
    "@angular/animations": "^4.2.4",
    "@angular/common": "^4.2.4",
    "@angular/compiler": "^4.2.4",
    "@angular/core": "^4.2.4",
    "@angular/forms": "^4.2.4",
    "@angular/http": "^4.2.4",
    "@angular/platform-browser": "^4.2.4",
    "@angular/platform-browser-dynamic": "^4.2.4",
    "@angular/router": "^4.2.4",
    "@stomp/stompjs": "^3.1.1",
    "core-js": "^2.4.1",
    "rxjs": "^5.4.2",
    "sockjs-client": "^1.1.4",
    "websocket": "^1.0.25",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "1.4.9",
    "@angular/compiler-cli": "^4.2.4",
    "@angular/language-service": "^4.2.4",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.2.0",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "~2.3.3"
  }

This code is working fine. Client communication with the server is establish.
I have added the same app.component.ts file to another project (not created using angular-cli tool) but during the call of the connect() method I get the following error:
    ERROR TypeError: SockJS is not a constructor
    at AppComponent.connect (sam.ts:26)
    at new AppComponent (app.component.ts:22)
    at createClass (provider.ts:359)
    at createDirectiveInstance (provider.ts:181)
    at createViewNodes (view.ts:341)
    at callViewAction (view.ts:782)
    at execComponentViewsAction (view.ts:700)
    at createViewNodes (view.ts:358)
    at createRootView (view.ts:197)
    at Object.createProdRootView [as createRootView] (services.ts:103)
zone.min.js:1 Unhandled Promise rejection: SockJS is not a constructor ; Zone: <root> ; Task: Promise.then ; Value: TypeError: SockJS is not a constructor
    at AppComponent.connect (app.component.ts:26)
    at new AppComponent (app.component.ts:22)
    at createClass (provider.ts:359)
    at createDirectiveInstance (provider.ts:181)
    at createViewNodes (view.ts:341)
    at callViewAction (view.ts:782)
    at execComponentViewsAction (view.ts:700)
    at createViewNodes (view.ts:358)
    at createRootView (view.ts:197)
    at Object.createProdRootView [as createRootView] (services.ts:103) TypeError: SockJS is not a constructor

This project has the following package.json:
"dependencies": {
    "@angular/compiler-cli": "^4.3.1",
    "@angular/platform-server": "^4.3.1",
    "@types/protobufjs": "^6.8.0"
  },
 "devDependencies": {
    "@angular/common": "^4.2.4",
    "@angular/compiler": "^4.3.1",
    "@angular/compiler-cli": "^4.3.1",
    "@angular/core": "^4.3.1",
    "@angular/forms": "^4.2.4",
    "@angular/http": "^4.3.1",
    "@angular/platform-browser": "^4.3.1",
    "@angular/platform-browser-dynamic": "^4.3.1",
    "@angular/platform-server": "^4.3.1",
    "@angular/router": "^4.3.1",
    "@ngtools/webpack": "1.1.2",
    "@stomp/stompjs": "^3.1.1",
    "@types/core-js": "0.9.34",
    "@types/node": "6.0.41",
    "long": "^3.2.0",
    "angular2-template-loader": "0.6.2",
    "awesome-typescript-loader": "^3.2.1",
    "core-js": "2.4.1",
    "protobufjs": "^6.8.0",
    "raw-loader": "0.5.1",
    "rxjs": "^5.4.2",
    "sockjs-client": "^1.1.4",
    "websocket": "^1.0.25",
    "systemjs": "0.19.41",
    "typescript": "^2.4.2",
    "webpack": "3.3.0",
    "zone.js": "0.8.14"
  }

and also has a systemjs.config.js file that has the following:
map:
   {
      ...
      'sockjs-client': 'node_modules/sockjs-client',
      '@stomp/stompjs': 'node_modules/@stomp/stompjs'
   },
   packages:
   {
      ...
      'node_modules/sockjs-client': { main: './dist/sockjs.js' },
      'node_modules/@stomp/stompjs': { main: './lib/stomp.js' }
   }

I can't figure it out why it can't find the constructor method.
Any help to understand and fix this error?
Answer: Install typings for this lib https://www.npmjs.com/package/@types/sockjs-client and you'll see how to use it properly.


How to save web page locally in android?

Question: I want to save simple text web page as html file in android and then show in webview.
The web page load first time from xml. then i want to download it and save it as html file.
But I want it at runtime to write data in a file and then show it in the app.
 it is possible.
thanks
Answer: To save a webpage :
saveWebArchive()
To load a webView already stored in assets
<code>        WebView wv;
        wv = (WebView) findViewById(R.id.webView1);
        wv.loadUrl("file:///android_asset/youwebview.html");
</code>


Retrieving data from DB in C# to Angular

Question: I need to Retrieving out for example all the volunteers from the DB
I wrote the service that gets all the volunteers
this is the service:
GetAllVolunteers():Observable<Volunteer>{
    return this.http.get<Volunteer>(environment.url+"ward/GetAllVolunteers")
  }

here I'm trying to retrieve out the data:
import { Component, OnInit } from '@angular/core';
import { Volunteer } from 'src/app/shared/models/volunteers.models';
import { VolunteerService } from 'src/app/shared/services/volunteer.service';

@Component({
  selector: 'app-all-volunteers',
  templateUrl: './all-volunteers.component.html',
  styleUrls: ['./all-volunteers.component.css']
})
export class AllVolunteersComponent implements OnInit {
  allVolunteers: Array<Volunteer> = [];
  constructor(public volunteerService: VolunteerService) { }

  ngOnInit(): void {
    this.volunteerService.GetAllVolunteers().subscribe(
      res => {
        this.allVolunteers=res
      }
    )
  }
}

this is the function in c# that retrieve all the volunteer:
[Route("GetAllVolunteers")]
        public List<volunteerDTO> GetAllVolunteers()
        {
         return volunteerBL.getAllVolunteers().Select(v => BL.converts.volunteersConvert.convertVolunteerToDTO(v)).ToList(); ;
        }

How do I place the result in the array allVolunteers[]?
Thanks in advance
Comment: What part doesn't work? It seems fine except a missing semicolon after `this.allVolunteers=res`
Comment: I put a semicolon and it's still wrong
Comment: this is the error:
Type 'Volunteer' is missing the following properties from type 'Volunteer[]': length, pop,push, concat, and 28 more.ts(2740)
Comment: You should use the get function using Volunteer[] instead of Volunteer as a generic type.
Comment: What a get function?
Answer: Your C# api controller action is returning a List of objects :
[Route("GetAllVolunteers")]
public List<volunteerDTO> GetAllVolunteers()
{
    return volunteerBL.getAllVolunteers().Select(v => BL.converts.volunteersConvert.convertVolunteerToDTO(v)).ToList(); ;
}

But your service function is expecting a single object :
GetAllVolunteers():Observable<Volunteer>{
    return this.http.get<Volunteer>(environment.url+"ward/GetAllVolunteers")
}

It should expect an array instead :
GetAllVolunteers():Observable<Volunteer[]>{
    return this.http.get<Volunteer[]>(environment.url+"ward/GetAllVolunteers")
}


Table tests for multi-return value function

Question: I'm cutting my teeth on Go and after digging into table driven tests I ran into the following problem:
I have a function that returns multiple values
// Halves an integer and and returns true if it was even or false if it was odd.
func half(n int) (int, bool) {
    h := n / 2
    e := n%2 == 0
    return h, e
}

I know that for half(1) the return value should be 0, false and for half(2) it should match 1, true, but I can't seem to figure out how to put this on a table.
How would one go to have something that resembles the following?
var halfTests = []struct {
    in  int
    out string
}{
    {1, <0, false>},
    {3, <1, true>},
}

Is there any other, more idiomatic way of doing this?
For reference, here's a test for something that resembles a FizzBuzz function, using tables:
var fizzbuzzTests = []struct {
    in  int
    out string
}{
    {1, "1"},
    {3, "Fizz"},
    {5, "Buzz"},
    {75, "FizzBuzz"},
}

func TestFizzBuzz(t *testing.T) {
    for _, tt := range fizzbuzzTests {
        s := FizzBuzz(tt.in)
        if s != tt.out {
            t.Errorf("Fizzbuzz(%d) => %s, want %s", tt.in, s, tt.out)
        }
    }
}

Answer: Just add another field to your struct that holds the second return value. Example:
var halfTests = []struct {
    in   int
    out1 int
    out2 bool
}{
    {1, 0, false},
    {3, 1, true},
}

Your testing function would look like the following:
func TestHalf(t *testing.T) {
    for _, tt := range halfTests {
        s, t := half(tt.in)
        if s != tt.out1 || t != tt.out2 {
            t.Errorf("half(%d) => %d, %v, want %d, %v", tt.in, s, t, tt.out1, tt.out2)
        }
    }
}

Comment: Edited the question with proper formatted suggestion.


Android R new Api isAutoRevokeWhitelisted() always give false even if manually permisssion reset is turned on /off

Question: So on Android R , user can now choose to allow the OSs to revoke given permission if the app isn't using them. This new settings will be available in the permission section of the app setting(check screenshot for reference), by default its turned off as per current beta behaviour
https://developer.android.com/preview/privacy/permissions#auto-reset

There is an api added to track if currently your app is in the given whitelist or not
https://developer.android.com/reference/android/content/pm/PackageManager#isAutoRevokeWhitelisted(). I tried testing this but even when i turn the on or off the settings the api always returns false. Wondering if anyone else has faced this issue yet.
I checked the logs and i can see a few logs which makes me feels that even after turning the option on its doesnt actually get added to the whitelist
<code>2020-08-14 03:04:26.002 7005-7047/? I/AppPermissionGroupsViewModel: sessionId 5928824040472035289 setting auto revoke enabled to true forcom.abc.xyz UserHandle{0}
2020-08-14 03:04:26.007 864-3020/? D/audio_hw_primary: enable_snd_device: snd_device(2: speaker)
2020-08-14 03:04:26.007 7005-7283/? W/AutoRevokePermissions: Error carrier privileged status for com.abc.xyz: -1
2020-08-14 03:04:26.007 864-3020/? D/audio_route: Apply path: speaker
2020-08-14 03:04:26.007 7005-7283/? I/AutoRevokePermissions: Parsed teamfood setting value: null
2020-08-14 03:04:26.007 7005-7283/? I/chatty: uid=10187(com.google.android.permissioncontroller) pool-2-thread-7 identical 1 line
2020-08-14 03:04:26.007 7005-7283/? I/AutoRevokePermissions: Parsed teamfood setting value: null
</code>
Comment: filed a bug with google too https://issuetracker.google.com/issues/164188698
Comment: I am not seeing this problem, testing on a Pixel 2 running Beta 3. `isAutoRevokeWhitelisted()` is returning the expected value if `android:autoRevokePermissions` is skipped or set to `discouraged`. If it is set to `disallowed`, `isAutoRevokeWhitelisted()` returns `true` regardless of the switch's setting. My sample app for this should be published on Monday. Note that if you want Google to pay attention to your issue, most likely you are going to need to provide a sample app and instructions for reproducing the problem.
Answer: You probably have targetSDK set to 29, I also experienced incorrect API work on it. But if I set targetSDK to 30 it gets back to normal.
Comment: yes that's correct it is only happening only. target sdk 29, still strange perhaps i will file this with google again.


Remove menu item from display

Question: How can I programatically remove/hide a menu item when the menu is displayed?
Comment: I just went through that problem, and i ended abandoning taxonomy menu to make a custom menu based on the current language. It will probably be faster than trying to make the module work for you.
Answer: If I understand well your question, you can use theme_menu_item_link() function to your template.php of your theme.
This is an example that I have tested (in this example Garland is the theme used, so you must replace the name of the function with the respective name):
Here is the example menu:

This is the function to remove the items:
function garland_menu_item_link($link) {
  if (empty($link['localized_options'])) {
    $link['localized_options'] = array();
  }
  if ($link['title'] != 'item 1') {
    $link['localized_options'] += array('html' => TRUE);
    return l('' . $link['title'] . '', $link['href'], $link['localized_options']);
  }
  else {
    unset($link);
  }
}

Please note that I have added if($link['title'] != 'item 1'){.. to detect the menu item, and remove it (with unset($link)).
This is the code for changing the text:
function garland_menu_item_link($link) {
  if (empty($link['localized_options'])) {
    $link['localized_options'] = array();
  }
  if ($link['title'] == 'item 1') {
    $link['title'] = 'new text';
  }

  $link['localized_options'] += array('html' => TRUE);
  return l('' . $link['title'] . '', $link['href'], $link['localized_options']);
}

Remember to clear the cache to see the changes.
I found these other resources related with theme_menu_item_link(): http://drupal.org/node/245156, http://drupal.org/node/249864, http://drupal.org/node/417482.
Comment: Thanks, I just want to add that for filtering links by language just use: $link['options']['langcode'] == $language->language
Answer: Here you have my implementation. I added the return line into the last else, and check for a specific role.
function batuka_menu_item_link($link) {
  global $user;
  if (in_array("club member", $user->roles)) {
    if (empty($link['localized_options'])) {
      $link['localized_options'] = array();
    }
    if ($link['title'] != 'Instructor Profile') {
      $link['localized_options'] += array('html'=>true);
      return l(''.$link['title'].'', $link['href'], $link['localized_options']);
    }
    else {
      unset($link);
      return;
    }
  }
}

Remove menu item from display


NodeJS code executes differently when run via browser and when run via curl in terminal

Question: I have the following simple NodeJS code:
var http = require("http");

http.createServer( function(request, response){
    response.writeHead(200);
    setTimeout(function(){
        response.write("This printed 3 secs later, ait?");
        response.end();
    }, 3000);

    response.write("This will be printed before.\n");
}).listen(8080);

If I run the script with node scriptname.js and then access it via curl in terminal like this:
curl http://localhost:8080

I get an output as expected, first it prints This will be printed before., then after 3 seconds it prints This printed 3 secs later, ait?.
However, when I open http://localhost:8080 in my browser (newest versions of Chrome, Firefox) page loads for 3 seconds and it prints the text This will be printed before.
This printed 3 secs later, ait? all at once. Why does this happen and how could I make the same behavior in the browser?
edit: So, as Ken stated in his answer

...this is simply due to the behavior of the browser rendering engine to render the contents. The rendering engine cashes the contents until  response.end();

and advised to go and check out Socket.IO, I came up with this working example which uses express and Socket.IO:
//timeoutTest.js
var express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server);

server.listen(8080);

app.use(express.static(__dirname + '/'));

app.get('/', function (req, res) {
   res.sendfile(__dirname + '/timeoutTest.html');
});

io.sockets.on('connection', function (client) {
   client.emit('msg', "This prints right now on connection.");

   setTimeout(function(){
      client.emit('msg', "This prints out after 3 secs.");
   }, 3000);
});

//timeoutTest.html
<!DOCTYPE html>

Comment: PS. I have recommended to you `Socket.IO` for the starter of server-browser interaction issue. This technology is generally called `RPC(remote procedure cal)` . `Socket.IO` is familiar to many people and you can find abundant resource on the web, so good thing to start. Just for future references, I personally do not use it anymore since it's a huge library just to do RPC between node and browser. The more concise and sophisticated (I think) and seamless way to do RPC here is to use `https://github.com/substack/dnode or https://github.com/dominictarr/rpc-stream with 'Browserify'.
Comment: Please refer my answer to a related question here. http://stackoverflow.com/questions/12832402/is-socket-io-a-must-in-developing-client-apps-for-nodejs-servers
Comment: Thanks for additional comments!
Answer: I think this is simply due to the behavior of the browser rendering engine to render the contents.
The rendering engine cashes the contents until
response.end(); arrives, then renders whole.
Basically, HTML contents in the browser are never updated automatically by incremental server push such as response.write.
You must pull data from the server to the browser client by Ajax and DHTML/js technique.
curl in terminal is completely different story in terms of the mere output of the node server.
If you seek more interactive behavior between node server and browser client, if you want server push feature, websocket is the way to go, and also investigate node  stream stuff.
Socket.IO is famous, and for node stream
https://github.com/substack/stream-handbook should be interesting to you.
I personally do this on my own project:
http://kenokabe.github.io/MarkdownLive/
I write stuff using Markdown and needed a streaming preview, so I created by myself. The preview screen is a Browser HTML page, and the HTML contents rendered and updated incrementally in streaming manner.
Comment: Thanks Ken, your answer made me go and explore this further. You can check out what I came up with in my edit. Thx!
Comment: It's my pleasure, Nikola. Glad to hear that my little comment help you.


Windows Server 2008 R2 C Drive losing space by the hour

Question: I have a server that has been behaving as normal for years now. In the last few days, something has happened. (I can't document exactly when, as I only know theres an issue with this box when someone tells me..)
The Box serves websites.
All Sites, IIS, Logs Database and DB logs / files are on a D Partition.
Now I can see that I am losing approx 1/2 a GB per hour on the C Drive.
I am not a sys admin, and we don't have one available here, so I am struggling to pin down where this is going wrong, and how / why.
So, are there any built in tools I can use to identify what is happening here, or at least help me see which folder is growing, so I can start to track down what is going on?
Comment: Download a program such as windirstat, treesize and run it (As Administrator) this will give you a graphical layout of the drive, This should help you identify where the space is being used
Answer: Not sure about built in tools but they will all require some upfront configuration, however Treesize Free will show you whats in use where quickly and easily.
Remember to run it as administrator.
Comment: I'll run Disk Cleanup as Admin, to buy me some time, then base line TreeSize, and see whats happened an hour later. Thanks
Update: Disk Cleanup as Admin hasn't touched the WinSXS folder.
Comment: That shows that Windows is using 28.2GB at present.
17.5GB of that is in winsxs.
I ran DiskCleanup, and that claimed it would recover 5 - 6 GB of space. In the end it recovered about 400mb. So to the uneducated it would seem that the winsxs folder is the issue.
Comment: WinSXS is a bit of a nightmare, it effectively holds a load of different versions of similar DLL/runtime files. When you install a new program or Windows updates you may see expansion in the WinSXS folder, but you wouldn't expect to see continuous expansion of that folder without explicitly making changes. You say you see continuous expansion. If you save the treesize out put and then run it again which folders have changed in size?
Comment: Disk Cleanup needs to run as administrator too, or it won't be able to access loads of hte locations it looks at for clean up.
Comment: Windows Update has been failing since the 14th. It triggers at 03.00 am here. So Is it feasible that the updates are failing because they need more space than is available to install. But then the system can't tidy them up as they haven't succeeded? 9If so, I'm caught in a catch 22 situation
Comment: Its a possibility. how much space do you have free, what % is that of total?
Comment: 1.19 GB free of a 32.4 GB drive. so about 3.5%. Something else that has struck me is that theres lots of web apps on the D drive. (Unaffected.) But is it possible the 8 GB of ram is insufficient, and the reducing space on the C drive is because disk space is being used as temporary memory in a swap file (Apologies if that went out with the arc :D)
Comment: Your swap file is probably of fixed size (equal to or 1.5x the physical ram). Did you compare the first treesize with a new one. Once we know the folder we know whats happening.
Comment: Its the Windows and Users Folders that are increasing. I didn't have the users folder expanded. The Windows Folder, it was Microsoft.NET and System32 folders. Its hard to be too precise, as my maths was off a bit earlier (to0 many zeros). We have lost 600 mb in the last 3.5 hours. (Queue you telling me thats normal during daily operation!)
Comment: Don't mess with the WinSxS folder, unless you are using tools designed to do so, like Disk Cleanup.  Many (but not all) files in the WinSxS folder are hard links which basically means there are multiple directory entries for the same file, but the file only takes up the space once.  Deleting hard linked files does not free up disk space unless it is the last link to a file.  Disk Cleanup is smart enough to know which WinSxS files are the last remaining link _and_ are not needed and it leaves the rest alone.
Comment: @Matt No one else brought that up, so I'll ask - can you expand drive C (it might require some server down-time)? 30GB is not nearly enough if you update Windows regularly (or automatically), you need to at least double it.
Comment: I can try to do that this evening. Though as I am not trained in this, it could be interesting! Assume it is done via Computer Manager -> Disk Management ? How risky is this, do I need to wait until all the backups have run on the D Drive?
Comment: I do this all the time in VMWare and not lost a machine once. At the same time you run the risk of corrupting the OS disk and losing the server entirely. If you are running on hardware you might struggle as the free space you can free up to expand into will be stuck at 'the other end' of the D drive so your OS disk can't expand into it. If you don't know what you are doing and this is runinng anything even slightly important be very very careful (don't do it!).
Comment: Any further details on the user folders that are expanding? Again, wouldn't expect them to just get bigger without any specific actions to cause it. Additionally I won't expect an OS disk to loose 600MB in 3 hours unless I was doing something to cause that.
Comment: I'll look some more tomorrow. I've kept it running all today so that they can run reports, get their backups done and so on. This box is running fairly critical stuff, so I am guessing that this falls into the 'dont resize the disks' category for now.
Comment: Fustrratingly, the issue has gone away. I managed to make enough space last night for teh windows updates to run. They ran, tidied up after themselves leaving me with 9gb of space, and nothing is eating it up today. Guess I'll have to put it down to an unknown Ms Update issue. Thanks for all the suggestions, and also for pointing me towards Treezize free


How to reverse an extend migration

Question: I recently ran this migration while installing the fuzzily gem:
class AddTrigramsModel < ActiveRecord::Migration
  extend Fuzzily::Migration
end

From looking at my schema.rb file, it looks like the effect of this migration was:
  create_table "trigrams", :force => true do |t|
    t.string  "trigram",     :limit => 3
    t.integer "score",       :limit => 2
    t.integer "owner_id"
    t.string  "owner_type"
    t.string  "fuzzy_field"
  end

  add_index "trigrams", ["owner_id", "owner_type", "fuzzy_field", "trigram", "score"], :name => "index_for_match"
  add_index "trigrams", ["owner_id", "owner_type"], :name => "index_by_owner"

Not sure if the easiest way is just to drop the table trigrams, or if there is a more appropriate method?  I am assuming the indexes will be deleted on dropping the table?
Answer: Just run rake db:rollback. Fuzzily has support for rollbacks. Although everything it does is dropping the trigrams table :)
# lib/fuzzily/migration.rb:33
def down
  drop_table trigrams_table_name
end

How to reverse an extend migration


Is there a maximum amount of payment that can be collected through mobile via each payment method (check, credit, ACH, cash)?

Question: When using ST Payments and Payment Collections to collect a deposit on an estimate in the mobile app, is there a maximum amount that can be collected? Customer said they tried to enter a $54,000 check but received an error that it exceeded the limit.
Answer: Check processing limits are account-specific.  These would be set upon the initial onboarding of the Check/ACH processing account based upon the business financials provided.
Whenever a check returns due to a "Velocity" limit, Fintech Support receives a notification automatically and we work with the Processor to try to increase the limits for the account moving forward.


MuPDF mutools question: can't get extract to work

Question: Where does MuPDF's mutools put the image files it extracts? The official documentation says "The image and font files will be saved out to the same folder which the file originates from." However, I've run several successful extractions with no such result.
By the way, pardon if this fits the definition of "non-programming question", but the official web site for MuPDF support (https://artifex.com/support/open-source/) says, "If you are using an AGPL licensed version of MuPDF, we recommend exploring . . . Stack Overflow: This website has a small but active community involved with MuPDF, as well as PDF. Questions raised here will often get a good response." And their link is to the main Stack Overflow site, right here, not a subsidiary site like SuperUsers. So I'm going to assume that I'm in the right place. If not, please blame MuPDF for sending me here.
My command line looks like this...
mutools extract -r PATHtoPDF
...with the intent of extracting all images. On some PDFs it errors out with messages about garbage, but on others it will give me a long list of short lines, e.g.
extracting image img-150.png
extracting image img-151.png
extracting image img-152.png
...etc., and then a list of fonts it also seems to be extracting. Then mutools stops--and though there is no error message, I see nothing. No files in the directory the PDF is in (which is where the documentation said they'd be), no files in the MuPDF directory where mutools is, no files in my Windows Documents directory, and I can't think of anywhere else they'd logically be (except maybe Windows Downloads, but no luck there either). The -help only gives -r and -p as options; there's no mention of a path for output. I did type an output path right after PATHtoPDF once, but mutools errored out without doing anything, so clearly that's not the way to go and I assumed that files would be placed in the MuPDF directory where mutools is. By now I've done several tests, so somewhere--if mutools output wasn't lying to me--I've got a whole bunch of image files floating around. My system is logically arranged but complex and large with five different big fixed disks full of data; a search of the whole thing would take hours.
By the way, I'm a noob Windows MuPDF user, not a programmer and have no idea how to compile windows binaries. Therefore the only useable MuPDF I found was here (https://mupdf.en.lo4d.com/download) which is 1.19, a bit old now, but I'm assuming it should still be serviceable. If it makes a difference, the system I'm doing this on is also old but still serviceable: Win7.
Answer: OK, this is very strange. After reading K J's responses (thanks, K J), I did a few additional experiments based on K J's testing recommendations. I found that under some circumstances MuPDF Mutool will do what it's supposed to, and under others it will not. viz:
Here is the actual command line that produces a list of results in the command-prompt window but doesn't actually extract any images:
H:\_WorkingProjects\ebooks\_XtractImgs\mupdf-1.9a-windows\mutool extract -r H:\_WorkingProjects\ebooks\_XtractImgs\AnimeRootsEarlyJapMonstrArt2010Papp.pdf

In this case, the command-line window I'm working with is the one from the Windows Start Menu--go to the start menu, drill down to Windows Accessories, find "Command Prompt" and click it. Then paste in my command prompt and press Enter. The command-prompt window will seem like it's working, but as I said before, no images are actually extracted.
HOWEVER, guess what? Start a command prompt from inside the window that contains the PDF (highlight folder, Shift-right click), which is H:\_WorkingProjects\ebooks\_XtractImgs, Then paste the EXACT SAME COMMAND LINE onto the prompt -- and it works. Images and fonts are extracted.
Downright weird.


Tutorials that explain boosting

Question: I'm a newbie trying to learn Boosting. The examples I found online are quite confusing. Is there a simple tutorial somewhere that explains Boosting with an example?
Comment: A short note on boosting in the context of decision trees is provided in James et al. ["An Introduction to Statistical Learning"](http://www-bcf.usc.edu/~gareth/ISL/ISLR%20Fourth%20Printing.pdf) p. 321-324. More detailed treatment is in Hastie et al. ["The Elements of Statistical Learning"](http://www-stat.stanford.edu/~tibs/ElemStatLearn/download.html) Chapter 10.
Comment: A working guide to boosted regression trees. *Journal of Animal Ecology* often used in introductory courses
Answer: Recommended in comments:
A short note on boosting in the context of decision trees is provided in James et al. "An Introduction to Statistical Learning" p. 321-324. More detailed treatment is in Hastie et al. "The Elements of Statistical Learning" Chapter 10. – Richard Hardy
A working guide to boosted regression trees. Journal of Animal Ecology often used in introductory courses – charles
Comment: h/t @RichardHardy
Comment: hat tip to @charles
Answer: Machine Learning: Classification
This MOOC on Coursera by University of Washington has a very good and comprehensive explanation of boosting models in Week 5. They have specifically focused on Adaboost and have given a very good and easy to understand explanation of the model and the mathematics behind it. To get a glimpse of how the video is you can look at this pdf
I also found this article to be a very good intuitive explanation of XGBoost.
Comment: I really wish we'd stop focusing on AdaBoost.
Comment: @MatthewDrury: What would you propose to get the basics of a reference implementation based on your experience? AnyBoost (Mason et al.), LogitBoost (Friedman), something else?
Comment: Regression boosting to minimize least squares, here's an exposition I put together for a job interview: https://github.com/madrury/boosting-presentation/blob/master/latex/presentation.pdf
Answer: Chris' Bishop Pattern Recognition and Machine Learning has a full chapter ( Chapter 14) which addresses Bagging, boosting etc, def. worth a look, hope this helps!

Tutorials that explain boosting


How to prevent CKEditor from removing content and tags written in source?

Question: I'd like to be able to use things such as the  tag for purposes of using font awesome icons, but CKEditor strips tags like this. If I place
 when in 'source' mode in ckeditor it gets removed as soon as I return to the standard mode. Is there a way to ensure that ckeditor allows these tags?
I saw that someone provided a solution here How to stop CKEditor 126.96.36.19974 from stripping


How to copy all items from one array into another?

Question: How can I copy every element of an array (where the elements are objects), into another array, so that they are totally independent?
I don't want changing an element in one array to affect the other.
Comment: The array part is covered by the answers to [this question](https://stackoverflow.com/questions/7486085/copy-array-by-value), and the object part is covered by the answers to [this question](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript). I've also fixed my answer below. *(You probably don't remember, but did you edit your question within the first five minutes to add the note about objects? Because several people, including me, answered it without seeming to have read that part.)*
Comment: At least based on the title, the linked questions are about cloning, not copying values. `a = [1, 2, 3], b = [4, 5, 6]`. If you do `a = b.slice()` you have copied b. You have not copied the values of b into a. a's array may be referenced multiple places.
Answer: The key things here are

The entries in the array are objects, and
You don't want modifications to an object in one array to show up in the other array.

That means we need to not just copy the objects to a new array (or a target array), but also create copies of the objects.
If the destination array doesn't exist yet...
...use map to create a new array, and copy the objects as you go:
const newArray = sourceArray.map(obj => /*...create and return copy of `obj`...*/);

...where the copy operation is whatever way you prefer to copy objects, which varies tremendously project to project based on use case. That topic is covered in depth in the answers to this question. But for instance, if you only want to copy the objects but not any objects their properties refer to, you could use spread notation (ES2015+):
const newArray = sourceArray.map(obj => ({...obj}));

That does a shallow copy of each object (and of the array). Again, for deep copies, see the answers to the question linked above.
Here's an example using a naive form of deep copy that doesn't try to handle edge cases, see that linked question for edge cases:

function naiveDeepCopy(obj) {
    const newObj = {};
    for (const key of Object.getOwnPropertyNames(obj)) {
        const value = obj[key];
        if (value && typeof value === "object") {
            newObj[key] = {...value};
        } else {
            newObj[key] = value;
        }
    }
    return newObj;
}
const sourceArray = [
    {
        name: "joe",
        address: {
            line1: "1 Manor Road",
            line2: "Somewhere",
            city: "St Louis",
            state: "Missouri",
            country: "USA",
        },
    },
    {
        name: "mohammed",
        address: {
            line1: "1 Kings Road",
            city: "London",
            country: "UK",
        },
    },
    {
        name: "shu-yo",
    },
];
const newArray = sourceArray.map(naiveDeepCopy);
// Modify the first one and its sub-object
newArray[0].name = newArray[0].name.toLocaleUpperCase();
newArray[0].address.country = "United States of America";
console.log("Original:", sourceArray);
console.log("Copy:", newArray);
.as-console-wrapper {
    max-height: 100% !important;
}

If the destination array exists...
...and you want to append the contents of the source array to it, you can use push and a loop:
for (const obj of sourceArray) {
    destinationArray.push(copy(obj));
}

Sometimes people really want a "one liner," even if there's no particular reason for it. If you refer that, you could create a new array and then use spread notation to expand it into a single push call:
destinationArray.push(...sourceArray.map(obj => copy(obj)));

Comment: @user1720860: The above definitely clones array entries, which is what the question asked. If you have a more complex thing than is addressed by the above, I suggest posting a new question including the code / array structure you're dealing with so that people can help you with it.
Comment: `destinationArray.push(...sourceArray);` worked for me perfectly.
Comment: Well this doesn't actually work on an example I am dealing with :(
Comment: This didnt work for me either. http://stackoverflow.com/questions/28482593/copying-an-array-of-objects-into-another-array-in-javascript-deep-copy
Comment: if sourceArray is null, "apply" fails in IE8
Comment: @v-tec: I'm mildly surprised if it doesn't in other browsers as well.
Comment: Cleaner way to ```push```: ```Array.prototype.push.apply(destinationArray, sourceArray);```
Comment: @vepasto: I don't see that as cleaner at all. There *is* a cleaner option, in ES2015, but it's not that.
Comment: With me the objects in the arrays are still linked
Comment: @ErikvandenHoorn - Indeed! It's weird, the history of the question shows that even the first version of it talks about objects, but I'm normally pretty tuned into those things. It's *possible* the question was edited within the first five minutes, but... As you say, the original answer didn't copy the objects, it just created a new array with the same objects in it. I've fixed it, thanks for pointing it out.
Answer: Easy way to get this working is using:
var cloneArray = JSON.parse(JSON.stringify(originalArray));

I have issues with getting arr.concat() or arr.splice(0) to give a deep copy. Above snippet works perfectly.
Comment: [As mentioned in another comment](https://stackoverflow.com/questions/3978492/fastest-way-to-duplicate-an-array-in-javascript-slice-vs-for-loop#comment41154579_23481165), worth noting that both `undefined` and any function inside your array will get converted to `null` during the `JSON.stringify` process, though this is the simplest way to clone both the array itself and all its children so that any further changes don't affect the original, so is still very useful if the above caveats don't cause any issues for your use case.
Comment: This way can be like the last chance, because this function has a high impact on productivity
Answer: A great way for cloning an array is with an array literal and the spread syntax. This is made possible by ES2015.
const objArray = [{name:'first'}, {name:'second'}, {name:'third'}, {name:'fourth'}];

const clonedArr = [...objArray];

console.log(clonedArr) // [Object, Object, Object, Object]

You can find this copy option in MDN's documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator#Copy_an_array
It is also an Airbnb's best practice. https://github.com/airbnb/javascript#es6-array-spreads
Note: The spread syntax in ES2015 goes one level deep while copying an array. Therefore, they are unsuitable for copying multidimensional arrays.
Comment: Yeah, MDN is community-edited and early on people not closely involved with it thought it was an operator. (In fact, I was the one who fixed MDN. ;-) )
Comment: Note that the question is about an array of *objects* and talks about not wanting modifying an object in the new array to modify it in the old. This doesn't copy the objects, just the array, so doesn't do what the OP asked. (Neither did my answer originally. **Years** later [today] someone pointed out that part of the question. I can't imagine how I missed it, but lots of people did. Weird. (Side note: `...` isn't an operator.)
Comment: Very interesting, the MDN docs used to call it spread operator.  The URL that I shared still has it like that:  `https://developer.mozilla.org/.../Operators/Spread_operator#Copy_an_array`.
Anyhow, I updated the answer to say spread syntax.
Answer: var clonedArray = array.concat();

Comment: Note that the question is about an array of *objects* and talks about not wanting modifying an object in the new array to modify it in the old. This doesn't copy the objects, just the array, so doesn't do what the OP asked. (Neither did my answer originally. **Years** later [today] someone pointed out that part of the question. I can't imagine how I missed it, but lots of people did. Weird.
Answer: If you want to keep reference:
Array.prototype.push.apply(destinationArray, sourceArray);
Comment: Does not work for arrays with a length beyond 65536 because that is the maximum hardcoded argument limit in the Chrome browser.
Comment: Note that the question is about an array of *objects* and talks about not wanting modifying an object in the new array to modify it in the old. This doesn't copy the objects, just the array, so doesn't do what the OP asked. (Neither did my answer originally. **Years** later [today] someone pointed out that part of the question. I can't imagine how I missed it, but lots of people did. Weird.
Answer: There are two important notes.

Using array.concat() does not work using Angular 1.4.4 and jQuery 3.2.1 (this is my environment).
The array.slice(0) is an object. So if you do something like newArray1 = oldArray.slice(0); newArray2 = oldArray.slice(0), the two new arrays will reference to just 1 array and changing one will affect the other.

Alternatively, using newArray1 = JSON.parse(JSON.stringify(old array)) will only copy the value, thus it creates a new array each time.
Comment: That's not true. JavaScript `array.slice(0)` returns new object each time it's called and changing one returned instance doesn't change others. If you are using "frameworks" that change this behavior, it's just a bug / bad design.
Comment: Not sure if I agree with @wonder.mice. If I run the following in my browser console then it does change the object in the original array: const first = [{test: 'test'}]; const second = first.slice(); second.map(x=>x.test='test2'); When I then check first the value of test will have changed to "test2".
Comment: @ErikvandenHoorn Well, yes, array is copied, but it's a "shallow" copy, not "deep" copy - elements still reference same values. Add new item to `second`, `first ` will not have it.
Answer: I suggest using concat() if you are using nodeJS. In all other cases, I have found that slice(0) works fine.
Comment: Note that the question is about an array of *objects* and talks about not wanting modifying an object in the new array to modify it in the old. This doesn't copy the objects, just the array, so doesn't do what the OP asked. (Neither did my answer originally. **Years** later [today] someone pointed out that part of the question. I can't imagine how I missed it, but lots of people did. Weird.
Answer: structuredClone represents a novel approach to perform deep cloning.

const objArray = [{name:'first'}, {name:'second'}, {name:'third'}, {name:'fourth'}];

// Clone it
const clonedArr = structuredClone(objArray);
console.log(clonedArr)


how to enable monitoring in google cloud for kubernetes through rest api

Question: Anyone can help me how to enable monitoring in google cloud through restapi.?
just like in gcloud sdk
<code>gcloud services enable monitoring
</code>
while creating a dashboard, able to see some metrics through rest api but not enable monitoring
Answer: Certain Google APIs are not publically accessible. As per the docs, Enabling the Monitoring API can be done only via Cloud Console or Cloud SDK. Only after enabling it, you can interact with it either directly or using client libraries. But it's not possible to enable this API via direct call to Google API.
Comment: Hello @sumitmadan and welcome to ServerFault! Please remember to [react to answers for your questions](https://stackoverflow.com/help/someone-answers).
That way we know if the answers were helpful and other community members could also benefit from them. Try to [accept answer](https://stackoverflow.com/help/accepted-answer) that is the final solution for your issue, upvote answers that are helpful and comment on those which could be improved or require additional attention. Enjoy your stay!


How to analyze introduction of Rachmaninoff's Paganini variation?

Question: I'm trying to analyze the introduction of Rachmaninoff's Paganini variations (picture below). I'm thinking the whole thing is a sequence and I only have to analyze the first two measures. The F# makes me think that the first chord of the second measure (F#-A-C-E) is an applied dominant and I think it's a vii7 of G. However, what's the second chord of the second measure (G-A-C#-F)? I can't make sense of it, although I hear it as a dominant of the A to follow.
I would appreciate the help!
Answer: I would argue that chord labels and Roman numerals are less helpful for a passage like this one.
Instead, I'd spot a larger pattern: that of the bass pitches for the first eight measures. F♯, G, A, B♭, C, C♯, D♯, and E create an octatonic scale (an alternation of half and whole steps) that culminates on the E on the downbeat of m. 9, helping solidify the V7 of the global A minor.
We could connect this to Roman numerals in a meaningful way, though, if we want to push this a bit farther. The downbeats in the bass emphasize every other note of the octatonic collection (F♯, G, A, B♭, C, C♯, D♯, E) and in doing so spell out the viio7/V in A minor. This being the opening of the piece, it's a common compositional tactic to prepare V (which therefore prepares the arrival of tonic) to lead in to the work at large.


Music with 3 Staves

Question: I am new and have a question. The sheet music with the staves are shown below. I want to play the piano only part. Could someone tell me what chords (keys) to play for the attached piano part only?
Comment: Usually 3 staves like this indicate (sung) melody+accompaniment, c.f. https://music.stackexchange.com/q/11463/2639  -- are there lyrics associated with the upper staff in other parts of the music?
Answer: All 3 staves are the score, with the top staff (a solo) being assigned to a single instrument/voice, and the bottom 2 staves (accompaniment) being assigned to a keyboard.
The chord symbols written above the top staff describe the harmony occurring from the point where a chord symbol is written until the next chord symbol. The chord symbols are, apparently, for a guitar to play an accompaniment, either along with the keyboardist or as the only accompanying instrument.
The chord symbols could also assist the keyboardist in improvising additional notes in the accompaniment, if the keyboardist wanted to fill out the texture.
Alternatively, a keyboardist could ignore the bottom two staves and improvise an accompaniment based solely on the chord symbols, as a jazz pianist might in a jazz ensemble. By approaching the accompaniment in this way, you could play notes within the chord that are higher or lower than those written in the keyboard part. You could add more notes per beat (see how the first keyboard chord in the second measure is a half note; that could be two quarter notes or four eighth notes). If you are going to try improvising, I recommend you keep the bass notes as written, as they are the most important voice after the solo voice. The bass line and the solo are a duet. Improvise only the right hand based on the chord symbols.
The chord symbols are accurate for the two measures you show here, but do not take into account rhythms that appear in the keyboard part.
Gsus/B is a perfectly legitimate guitar chord and jazz chart or lead sheet chord. If you break down Gsus/B, reading from left to right, it means: [G] a G major chord, [sus] a 4th above the root (G) instead of a 3rd, so a C instead of a B; [/] over; [B] a B in the bass; the 5th above the root (G) is implied and is a D.
If you look at the keyboard part that's exactly what you have: a B in the left hand or the bass, and G-C-D in the right hand.
The [sus] literally means a suspended note from a previous chord, in this case the C which was in the previous C Major chord, and [sus] almost always means a 4th instead of 3rd in the chord. The C should resolve to a B in the next measure, which we do not see in your example.
Answer: The chords are written above the music: Am7 F | C Gsus/B
Gsus/B is a very strange chord, so it should sound a little weird compared to the others.  The notes for these chords are spelled out in the bottom two clefs.
Comment: @Fugu - Your comments make sense.  I'd also be skeptical of such a chord and listen to the actual song to confirm that the transcription is accurate.
Comment: Don't play Gsus/B. I'm not sure there's any context in which that would be a nice-sounding thing.
Comment: @Fugu What? The written notes are a perfectly "nice-sounding thing". I suspect the problem is that Gsus/B is a silly name for the chord, though without seeing the *next* bar that is just a guess. C9/B might be a more sensible name for it - or even C11/B if the F in the vocal part is considered as belonging to the chord. The voice leading between the voice part and the bass (three consecutive 5ths A-E, F-C, C-G followed by a diminished 5th B-F) isn't "nice" though!
Comment: The way it's written there's a minor ninth between the B and the C, which will always exist in a chord spelled Gsus/B.  This minor ninth, particularly in the key of C, is a combination of extremely dissonant and function-muddling since you are simultaneously playing the suspension from the dominant chord and the note that the suspension resolves to.  Ultimately these things are subjective, but "very strange" is an accurate way to characterize this chord, without question.
Comment: Ultimately I was telling them what to play based on what is written in the music.  Of course Gsus/B will be dissonant, particularly because of the minor 9, but that is what's written.  With the notes written, I couldn't think of this as a C chord, since there is no 3, unless it were a Cmaj7sus4/B (add9), which seems to have the same strangeness about it.  I say play what's on the page.
Comment: I don't think "play what's on the page" is bad advice; I was just following up on you calling the chord "very strange". It is so strange that I, personally, wouldn't play it, and would consult the source material myself to make sure what's actually being played there because it's exceedingly unlikely that it's a suspension with the resolve for the suspension in the bass, since this is very strange.
Comment: @Fugu Of course "these things are subjective", but you can find minor 9ths between the bass and treble everywhere in music for the last 400 years at least. The *name* of the chord might be "strange" I really can't see why you think it *sounds* strange. If the next chord is Am or Am7, the bass and treble progression C-C, B-D, A-E is just a musical cliché! On the very first page of a well known harmony textbook the author shows a chord (from a piece by Gounod, in 1859) voiced Eb C Db Eb F - and the fistful of notes C Db Eb F doesn't sound strange or even dissonant, *in its musical context.*
Comment: There's no minor ninth in that chord. The minor ninth is a particularly dissonant interval and should be employed with care, especially if the chord isn't dominant functioning. Your cliche progression also doesn't include a C natural in the dominant part of the progression, because including both a B and a C (with a B in the bass and in the key of C) is very dissonant, and is therefore not analogous. This is a very strange chord.
Comment: @alephzero - While I agree that a minor ninth can be used, I would argue that it has not been very present throughout the past 400 years, particularly in a harmonic context, ie, the minor 9 is a part of the chord.  I'm sure it has appeared much more between the melody and the harmony, particularly in harmonic minor or playing the 4 against the I chord in major.  Even in Jazz, where dissonance is much more acceptable, the minor 9 is really only to be used harmonically on a dominant functioning chord.  In all my formal studies, particularly classical, the minor 9 is to be strongly avoided.
Comment: Much of this seems to be based on one incorrect idea, which is that every note played must be "part of a chord." That leads both to over-complicated naming of chords and convoluted attempts to "analyse the harmony" accounting for every note. Non-chord tones have been used for a long as music has existed, I suspect.  IMO the second half of bar 7 is just a C chord, with a non-chord B that happens to be in the bass. I would hesitate even to call it a C9 chord because of the D a the top of the voicing, *without knowing what happens in bar 8*.
Comment: Cmaj/B isn't that uncommon. The B resolves up to the root (C), which gives a really nice sound. I feel like I've heard this from Keith Jarrett, but I can't pinpoint which track. In this case, though, I doubt the mystery chord is Cmaj/B because I don't think it's resolving up to Cmaj given that it's already coming *from* Cmaj. My guess is that Amin is coming next, to complete the parallel 10th movement. I see the motivation for calling it Gsus/B (the mystery chord is replacing G/B). **But I would label the harmony as Gmaj11/B, because I hear the same sound when I double the B an octave up.**
Comment: @alephzero - it can't be C9/B, as C9 will have Bb in it, as well. Cmaj9 may work.
Comment: That Gsus/C is iffy at best anyway. A guitarist would be expected to play it - after all, that's why the chord symbol's there. But - sus needs qualifying. Sus 2 or sus 4? Obvious from the dots, sus4, but really that should be written in the chord on top. With B,G,C,D it's going to be more Gadd11/B.
Comment: @jdjazz - Maybe not Gmaj11, as that implies F# and A as well. Gadd11 isn't bad as the basic name.
Comment: @Tim, yes I was thinking Gmaj11 with no 7 but I see the issue you mention.
Comment: @alephzero - I won't disagree that there is a tendency to overanalyze every note on a page, however, in this particular instance, it is written on the music.  Without knowing where the transcription comes from, I assume that it is the composer's intent, so it's not really us placing the label on the chord.  We could seek an alternate analysis and say the whole measure is some sort of C chord.  I'd also note that it's not incorrect to analyze in any manner, as long as the analysis has meaning.  This analysis could easily express the notes that are taking place for a player to replicate.
Answer: Play the bottom two lines, which are the left and right hand piano parts. Above the whole lot, the chord symbols are written. So you have everything you need. Plus the top line, which is the lead vocal, usually.
Play the written parts, and they are exactly what's needed. They mirror the chord symbols above.
Comment: What does it means they mirror the chords, Do I for instance on the  F (top line) play the F chord per the 3 stave or just the F alone.
Comment: The symbols are always supposed to tell exactly what chord will be needed in each bar. So, if the letter 'F' appears above the top staff, it means the *chord* of F.
Comment: last question: Does it make sense to play the chords and the second line?
Comment: Yes, chords and middle line is what I often do, when I've got fed up with playing what's actually written. Or even bass line and other inversions of the middle line chords. Or even top line with some vocalists, (if it's a vocal line) and make do with comping chords underneath. It gives some variety, but will depend on how you play those chords. There are so many different ways...
Answer: Your question is a bit difficult to understand, but I think you're asking whether or not to play the chords written in above. Short answer: no. Just play the bottom two staves, the piano part. The chords above are mostly for guitar. Although if you want to, you can add some of the chord tones to the piano part.

Music with 3 Staves


Improve mapping performance

Question: I'm mapping values that I receive from an ajax call. It works pretty well, but it is still not fast enough in ie7 (I'm getting a slow script warning).
I can't figure out any way to make this faster. I've tried using native javascript functions as well, but the speed improvement was negligible. Do you guys have any ideas?
var $audit = $('#audit');

$.each(data, function (i, val) {

    if (val != null && val !== '0') {

        $audit.find('input[type="checkbox"].' + i).attr('checked', val == 1);
        $audit.find('input[type="text"].' + i).val(val);
        $audit.find('select.' + i).val(val);
    }

});

Some psuedo-html:

    <input type="text" class="foo1" />
    <input type="checkbox" class="foo2" />
    <select class="foo3">
        <option value="1">1</option>
    </select>

Comment: What is in data? Have you done any profiling to see where the browser spend it's time?
Comment: How much is `data.length`? Can you provide an example of your markup (e.g. the `.1` and `.2` element blocks)?
Comment: @alexn `data` is JSON, parsed to a javascript object. And ive used console.time to narrow my problem down to this loop.
Comment: Do you mean `` instead of ``? And how many records r u expecting?
Comment: What is the structure of the `data` object? Why don't you use a detailed profiler like http://www.compuware.com/application-performance-management/dynatrace-ajax-download.html
Answer: I dont know if it will help that much but you could cache your inputs + select and just filter that instead of finding the "same" element over and over again and just filter the specific element in a much smaller collection:
var $audit = $('#audit'),
    $inputs = $audit.find('input, select');

$.each(data, function (i, val) {
    if (val != null && val !== '0') {
        var current = $inputs.filter('.' + i);
        if(current.is(":checkbox") {
            current.attr('checked', val === 1);
        } else {
            current.val(val);
        }
    }
});

Comment: This is a good idea, but its actually slower. Probably due to the `is()` check on each iteration
Answer: You can try to use knockout.js for your purposes. It may be faster.
This is an example of data binding:  http://knockoutjs.com/examples/controlTypes.html
Answer: Per iteration, it's not too surprising that its slow when the scope chain keeps entering and leaving the DOM. However that the loop is taking a long time begs the question: how many of these divs are on the page? If it's more than around 50, then you've got a UI design issue.
To get this to go significantly faster really equires a radical redisgn of the code. If it were me, I'd build up an HTML framgent containing the repeating divs as a javascript string then splice it into the page using a single createElement/setting the innerHTML
Comment: So youre saying that `createElement` for each input would be faster than just mapping the values?
Comment: No - that would be about as slow - create a string contianing multiple divs, then use createElement to contain a single div and set it's innerHTML to the string containing multiple entries.

Improve mapping performance


Generalised Logistic Regression with mixed effects - Binomial model creation / selection

Question: I have a dataset with 72 individuals from 5 separate groups, with repeated measures - each individual was sampled 4 times. All data is binomial, and in most cases there are more 0s than 1s.
I have a lot of potential predictor variables BacteriaA,BacteriaB etc, (9+ depending on how I group the data), and a number of outcome variables I want to test DiseaseA, Disease B, etc.
data <- read.csv("https://pastebin.com/raw/gwEFqh79 ")
cols <-   colnames(data)
data[cols] <- lapply(data[cols], factor)
str(data)

'data.frame':   500 obs. of  18 variables:
 $ Group    : Factor w/ 5 levels "A","B","C","D",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ ID       : Factor w/ 73 levels "E1","E10","E11",..: 1 1 1 1 2 2 2 2 2 2 ...
 $ Time     : Factor w/ 4 levels "1","2","3","4": 2 4 2 4 1 2 3 1 2 3 ...
 $ DiseaseA : Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...
 $ DiseaseB : Factor w/ 2 levels "0","1": 2 1 2 1 1 1 1 1 1 1 ...
 $ DiseaseC : Factor w/ 2 levels "0","1": 1 2 1 2 1 1 1 1 1 1 ...
 $ DiseaseD : Factor w/ 2 levels "0","1": 2 2 2 2 1 1 1 1 1 1 ...
 $ DiseaseE : Factor w/ 2 levels "0","1": 2 2 2 2 1 1 1 1 1 1 ...
 $ DiseaseF : Factor w/ 2 levels "0","1": 2 2 2 2 1 1 1 1 1 1 ...
 $ BacteriaA: Factor w/ 2 levels "0","1": 2 1 1 1 1 2 1 2 1 1 ...
 $ BacteriaB: Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...
 $ BacteriaC: Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 2 1 1 ...
 $ BacteriaD: Factor w/ 2 levels "0","1": 2 1 2 1 2 2 1 1 2 1 ...
 $ BacteriaE: Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...
 $ BacteriaF: Factor w/ 2 levels "0","1": 1 1 1 2 1 1 1 1 1 1 ...
 $ BacteriaG: Factor w/ 2 levels "0","1": 1 2 2 2 1 2 2 1 2 2 ...
 $ BacteriaH: Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...
 $ BacteriaI: Factor w/ 2 levels "0","1": 2 1 1 1 1 1 1 1 1 1 ...

I have run a model using glmer because I believe I need a mixed effects model, and I have binomial data.
model1 <- glmer(DiseaseA ~ (1|Group) + (1|ID) + Time + BacteriaA + BacteriaB + BacteriaC + BacteriaD + BacteriaE + BacteriaF + BacteriaG + BacteriaH + BacteriaI, data = data, family = 'binomial'(link = "logit"))

summary(model1)

Model failed to converge with max|grad| = 0.0337228 (tol = 0.001, component 1)Model failed to converge with max|grad| = 0.0337228 (tol = 0.001, component 1)Generalized linear mixed model fit by maximum likelihood (Laplace Approximation) ['glmerMod']
 Family: binomial  ( logit )
Formula: DiseaseA ~ (1 | Group) + (1 | ID) + Time + BacteriaA + BacteriaB +
    BacteriaC + BacteriaD + BacteriaE + BacteriaF + BacteriaG +      BacteriaH + BacteriaI
   Data: data

     AIC      BIC   logLik deviance df.resid
   426.2    489.4   -198.1    396.2      485

Scaled residuals:
    Min      1Q  Median      3Q     Max
-1.2452 -0.3965 -0.2829 -0.1610  4.8949

Random effects:
 Groups Name        Variance  Std.Dev.
 ID     (Intercept) 1.298e+00 1.139325
 Group  (Intercept) 3.841e-05 0.006198
Number of obs: 500, groups:  ID, 73; Group, 5

Fixed effects:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)  -1.5414     0.4423  -3.485 0.000493 ***
Time2         0.6009     0.4518   1.330 0.183535
Time3         0.4617     0.4782   0.966 0.334287
Time4         0.4136     0.4577   0.904 0.366223
BacteriaA1   -0.5733     0.4593  -1.248 0.211939
BacteriaB1   -0.6688     0.5057  -1.323 0.185963
BacteriaC1   -0.6867     0.4371  -1.571 0.116228
BacteriaD1   -0.7494     0.3458  -2.167 0.030236 *
BacteriaE1   -0.1796     0.7715  -0.233 0.815964
BacteriaF1   -1.3041     0.6412  -2.034 0.041972 *
BacteriaG1   -0.7576     0.3260  -2.324 0.020133 *
BacteriaH1  -10.1035   124.1785  -0.081 0.935154
BacteriaI1   -0.1340     0.7987  -0.168 0.866712
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation matrix not shown by default, as p = 13 > 12.
Use print(x, correlation=TRUE)  or
    vcov(x)        if you need it

convergence code: 0
Model failed to converge with max|grad| = 0.0337228 (tol = 0.001, component 1)

I am super new to modelling, never mind mixed models, and I'm just really stuck on what I should do next.
Is this the right model? How do I work out the odds ratios from this? What does Model failed to converge with max|grad| mean?
And most of all, how do I choose a model from this? Is there a stepwise way of dealing with so many variables?
Comment: It's worth pausing to see if the sample size is adequate.  The simplest thing you can do with binary outcome data is to estimate the probability that Y=1.  This takes a sample size of n=96 independent subjects, to get a margin of error of +/- 0.1 in estimating the unknown probability.  You are trying to do something that will require a much larger sample size than that, although having repeated measures does boost the effective sample size a bit.
Answer: I think your questions are a little too broad, and it's likely you should consider other approaches before jumping into a generalized linear mixed-effects model (GLMM), especially if you're super new to modelling.
To briefly answer your questions:

There is no "right model" -- remember, "all models are wrong, but
some are
useful". To determine if yours is even useful, you need to perform model validation (look at residuals, homoskedasticity, etc.) and consider what standard you'd want to hold your model to.
Because you're fitting a model with the logit link, your regression parameters are already transformed into log-odds space (NOTE: if you have many more zeroes than ones, you may wan to consider the cloglog link instead). Assume you were to fit a null model (no predictors, only an intercept term) through model2 <- glm(DiseaseA ~ 1, data = data, family = 'binomial'(link = "logit")), and let's say the intercept parameter was estimated to be -2. Your model would be written as follows:
$\log(\frac{p}{1-p}) = \beta_0 = -2$

This means the log odds are -2 -- you would exponentiate to get the odds ($\frac{p}{1-p} = e^{\beta_0} = e^{-2} = 0.1353$) and back-transform to get the probability ($p = \frac{0.1353}{0.1353+1} = 0.1192$). Your log-odds will follow this process, although you have many more regression parameters.
See this post.
To your final question -- again, it is a bit too broad to really answer. There are many ways to perform model selection, and stepwise selection as you suggest is typically frowned upon. If you are new to modelling, how did you know to fit this model in the first place? Mixed-effects GLMMs are not easy and you should not just jump into one without a lot of appreciation for the statistics behind them. I suggest you read Ben Bolker's FAQ on GLMMs as a helpful resource to start (here).
Comment: I wouldn't choose a link function based on the distribution of the outcome.


Como analisar a demora do start de uma aplicação React Native?

Question: Tenho notado que está demorando muito tempo para meu APP inicializar (9 segundos) até cair na pagina inicial, isso em release mode (em debug também leva bastante tempo). Durante esse tempo fica uma tela branca.
Tentei usar o profile do flipper mas só consigo fazer análises após o APP estar iniciado então gostaria de saber se existe uma forma de verificar o que pode estar impactando no startup do APP e causando essa tela branca, existe algum recurso ou ferramenta pra isso?
Comment: Difícil saber ao certo, parece ser um problema de ambiente, se não for, vai ser específico ao seu código. É difícil entender por que isso tá acontecendo, pode ser até mesmo o celular que está testando. Seria interessante testar em outros dispositivos com sistemas diferentes para ver se existe algum padrão no que está acontecendo.
Comment: Já foi testado, só tenho interesse em saber mesmo se existe uma forma de analisar isso
Comment: o app faz alguma chamada de api no começo?
Comment: Sim, temos os providers do Keycloack sendo inicializados, tbm do Redux, NativeBase e o React Navigation, fazendo um teste bobo agora, notei que o React Navigation atrasa bastante no start
Comment: Mas pra mim, o React Navigation apenas empilha as rotas declaradas no começo, não deveria fazer "calculos" etc..
Comment: Creio que achei o possível problema, ta num renderItem de uma VirtualizedList. No entanto o mesmo não está na rota inicial e sim em uma das rotas mapeadas no Router, isso que parece estranho
Answer: Fiz uma análise "hard coded" e percebi que o motivo da lentidão é por algumas telas que são inicializadas nas rotas utilizarem o faker para alguns mocks:
<code>import faker from '@faker-js/faker';
</code>
Retirando a implementação o tempo de carregamento inicial também diminui.


Program hangs when implementing linked list

Question: The goal of this program is to gain  a better understanding of linked lists. I am supposed to create the function PromoteTarget that does the following:

Goes through a list of numbers and if the number specified isn't found (target) then it is appended to the end of the list. If the list is empty, then target becomes the head.
If target is found in the list one or more times, then the target numbers are to be brought to the front of the list. I should be able to do this without changing or deleting any nodes.

Here is my code:
      void PromoteTarget(Node*& headPtr, int target)
    {

    Node *current = headPtr;
    Node *prevnode = headPtr;
    int count = 0;
    while (current != 0) {
        if (current->data == target) {
            count++;
        }
        current = current->link;
    }
    if (count == 0) {

        Node *newNodePtr = new Node;
        newNodePtr->data = target;
        newNodePtr->link = 0;
        if (headPtr == 0)
            headPtr = newNodePtr;
        else
        {
            Node *cursor = headPtr;

            while (cursor->link != 0)
                cursor = cursor->link;
            cursor->link = newNodePtr;
        }
    }

    if (count > 0) {
        current = headPtr;
        while (current != 0) {
            if (current->data == target) {
                prevnode->link = current->link;
                current->link = headPtr;
                headPtr = current;
            }
            prevnode = current;
            current = current->link;
        }
    }
    }

This is an example of what I should receive as output:
================================
passed test on empty list
================================
initial: 4  5
(target: 3)
ought2b: 4  5  3
outcome: 4  5  3
================================
initial: 3  4  5  7  4  5
(target: 5)
ought2b: 5  5  3  4  7  4
outcome: 5  5  3  4  7  4
================================
initial: 7  6  4  3  4  5
(target: 4)
ought2b: 4  4  7  6  3  5
outcome: 4  4  7  6  3  5
================================
initial: 6  5  7  5  3  5  6  5  3
(target: 7)
ought2b: 7  6  5  5  3  5  6  5  3
outcome: 7  6  5  5  3  5  6  5  3
================================
initial: 5
(target: 6)
ought2b: 5  6
outcome: 5  6
================================
initial: 5  6  4  4  5  7
(target: 6)
ought2b: 6  5  4  4  5  7
outcome: 6  5  4  4  5  7
================================

This is what I am actually getting:
================================
passed test on empty list
================================
initial: 4  5
(target: 3)
ought2b: 4  5  3
outcome: 4  5  3

The program hangs and never gives me the full output. Based on the output I am getting though, I have a pretty good feeling about the first half of my program working as intended. Although I could totally be wrong.
If I had to guess, my problem occurs whenever I try to move the elements to the front of the linked list. Does my logic look ok? Am I forgetting or missing something or did I just make a dumb mistake?
Comment: The code as presented creates no output, making it rather difficult for us to debug based on your stated symptom. I'd advise you to [debug your small program](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/), narrow down where the problem occurs, and create a [mcve] based upon what you learned from debugging.
Comment: When your program hangs, break it with a debugger. What line does it say it's on?
Comment: One possibility would be that you have an infinite loop (circular list) but we cannot know since we have no idea how you build the list. Either by using a debugger or add some output in the above function should works.
Comment: @JosephSible If I am using the debugger correctly, then I believe it is hanging at the last line of the function.
Comment: @JosephSible "Program received signal SIGINT, Interrupt.
0x0000000000401d3e in PromoteTarget (headPtr=@0x7fffffffebc8: 0x615c80,
    target=5) at llcpImp.cpp:284
                 current = current->link;"
Comment: Now that you've paused the program step it  until you see what the loop it's caught in. Once you know the loop, you probably have a good idea what variables have the wrong values and you can use the debugger to help find out where and how things really went wrong. Warning: The crash site is often nowhere near where the actual bug is.
Answer: You can do both operations in a single traversal of the Linked List. During the traversal itself, every time a Node with data equal to target is encountered, shift this Node to the beginning of the Linked List and set the boolean variable exists to true. At the end of traversal, if exists == false then add a new Node to the end of the Linked List.
Node* createNode(int target)
{
    Node *newNodePtr = new Node;
    newNodePtr->data = target;
    newNodePtr->link = nullptr;
    return newNodePtr;
}

void PromoteTarget(Node*& headPtr, int target)
{
    if (headPtr == nullptr)
        headPtr = createNode(target);
    else
    {
        Node *prev, *curr;
        prev = headPtr;
        curr = headPtr->link;
        bool exists = false;
        while (curr != nullptr)
        {
            if (curr->data == target)
            {
                exists = true;
                prev->link = curr->link;
                curr->link = headPtr;
                headPtr = curr;
                curr = prev->link;
            }
            else
            {
                prev = curr;
                curr = curr->link;
            }
        }

        if (exists == false)
            prev->link = createNode(target);
    }
}


Correlation and Hotelling test

Question: To find a Hotelling $T^2$ score it is necessary to calculate the covariance matrix and then invert it.
Now, when the test is a two-sample $T^2$ test, the covariance matrix is a pooled matrix. When there is a high degree of correlation / collinearity in the variables the covariance could be close to a singularity (the determinant near zero). So it is recommended in statistics books to remove those highly correlated variables from the data matrix and to calculate the covariance matrix again until having a viable matrix that can be inverted.
This is my question: how do you determine the correlation in the variables when you have two groups? My intuition tells me that you find the correlation matrix directly from your data matrix and you use this correlation matrix to determine which variables to eliminate.
On the other hand, in a two-sample test you have a covariance matrix that is pooled: a weighted sum of two matrices. Should you find then the highly correlated variables from the covariance matrix of each one of the two groups and then eliminate them all from the data matrix?
Which option is correct?
Comment: As stated the question doesn't make sense. "So it is recommended in statistics books" can you give an example? I suspect a misunderstanding.
Answer: The pooled matrix is the one that you need to invert, so that is the one that you should examine for high correlations.
However, what if you have 2 variables that are highly correlated with each other and several other variables that are fairly independent of those 2 and each other.  And what if the two groups are identical on all of the variables other than the 1st 2, but different on the 1st 2 in the direction perpendicular to their covariance?  this means that you have a meaningful and significant difference, but removing the correlated variables (or even just one of them) would remove the difference.

Correlation and Hotelling test


Put Dynamically Generated GridView to Specific  in ASP.Net C#

Question: I have created gridview in code behind file of C#.
I want to place that gridview into a specific
 of source file.
My code to generate the grid is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class gv1 : System.Web.UI.Page
{
    SqlConnection cn;
    SqlCommand cmd;
    DataSet ds;
    SqlDataAdapter da;

    protected void Page_Load(object sender, EventArgs e)
   {
        cn = new SqlConnection("Data Source=AMIR-PC\\MOHEMMAD;Initial Catalog=CRM_InvestPlus;Integrated Security=True");

   }
   protected void Button1_Click(object sender, EventArgs e)
   {
       cn.Open();
       string query = "select V.Version_Name,S.Software_Name,C.Capacity,V.Price from " +
        "Software_Master S inner join Version_Master V inner join Dealer_License_Capacity C " +
        "on V.Version_ID=C.Version_ID and V.Software_ID=C.Software_ID on " +
        "S.Software_ID=C.Software_ID where C.ID='D00001' and C.Software_ID='001' and C.Version_ID='1'";

    cmd = new SqlCommand(query, cn);
    da = new SqlDataAdapter(cmd);
    ds = new DataSet();
    da.Fill(ds);
    cn.Close();

    GridView gr1 = new GridView();
    Table t = new Table();
    gr1.Controls.Add(t);

    int count = Convert.ToInt32(ds.Tables[0].Rows[0]["Capacity"].ToString());

    for (int i = 0; i < count; i++)
    {

        GridViewRow row = new GridViewRow(i, i, DataControlRowType.DataRow, DataControlRowState.Normal);
        TableCell cell1 = new TableCell();
        TableCell cell2 = new TableCell();
        TableCell cell3 = new TableCell();
        TableCell cell4 = new TableCell();

        TextBox txtPrice = new TextBox();

        FileUpload fl = new FileUpload();
        fl.ID = "fl" + i;

        if (i == 0)
        {
            cell1.Text = ds.Tables[0].Rows[0]["Software_Name"].ToString();
            cell2.Text = ds.Tables[0].Rows[0]["Version_Name"].ToString();
            //cell3.Text = ds.Tables[0].Rows[0]["Price"].ToString();
            cell3.Controls.Add(txtPrice);
        }
        else
        {
            cell1.Text = "";
            cell2.Text = "";
            cell3.Text = "";
        }

        cell4.Controls.Add(fl);

        row.Cells.Add(cell1);
        row.Cells.Add(cell2);
        row.Cells.Add(cell3);
        row.Cells.Add(cell4);

        gr1.Controls[0].Controls.AddAt(i, row);

    }
    form1.Controls.Add(gr1);
   }
}

Grid is generated successfully...
Now I want to place the grid gr1 to
 tag that is:

How is it possible to place gr1 in last most
..???
Please help
thanks in advance.
Answer: you need to add runat="server" and an id to your div tag and you can do it like this

block.Controls.Add(gr1);

Comment: sorry block is accessible but only `class="block-border"`  should be given the id or all s should be placed id..?? @COLD TOLD


How to run "git clone ssh" with ansible and pass a password after the command is ran?

Question: Friends,
I need to write an ansible task, which clones a git repository on a remote machine. I tryed like this:
- name: CLONING EMPTY REPOSITORY
  ansible.builtin.shell:
    chdir: /home/marcio/devdir
    cmd: git clone ssh://firstname.lastname@example.com/home/marcio/devdir/fresco.git fresco.local

Ansible is configured to become sudo when necessary and this is working fine, the above task, however, never finishes executing because the password of the user "marcio" must be provided after the git clone command is ran.
Since the original repository is located on the same machine where it will be cloned, I tryed generating a public key and storing it on the authorized_keys file of the server, but it didn't work as well.
Does anybody know a way to pass this password as a variable or another way to work around this problem?
Answer: Use expect:
- name: CLONING EMPTY REPOSITORY
  ansible.builtin.expect:
    chdir: /home/marcio/devdir
    command: git clone ssh://email@example.com/home/marcio/devdir/fresco.git fresco.local
    responses:
      "YOUR ACTUAL LOGIN PROMPT": username
      "YOUR ACTUAL PASSWORD PROMPT": password


how to change address bar by its content-type/title of node

Question: I have a content type where user allowed to add the content, which create a node of that particular content, when i click to that content for detail page it re-direct to the node page created by authenticated user, but the address bar is something like

www.myexample.com/node/23 23

or some no.
Now i want the address should be

www.myexample.com/(content-type)/(node-title)

please help me.
Thanks
Answer:
Install Pathauto
Visit the URL Alias Patterns page at /admin/config/search/path/patterns
Choose an appropriate token-based pattern for your content type in the relevant text field, before saving. (e.g. <code>[node:content-type]/[node:title]</code>)
Visit the "Bulk Update" tab and generate all Content aliases.

From now on any time you (or anyone else) creates a node of that type, the URL alias will be automatically set.


For loop counter in MIPS

Question: so I'm currently trying to go through a for loop in MIPS and trying to multiply with it. I did the same thing with addition and it worked. Below, $t0 is the lower integer the user has entered, $t6 is the upper integer + 1, and $t4 is the register that stores the result. Here it is:
        beq $t0, $t6, resultFunction
        add $t4, $t4, $t0
        addi $t0, $t0, 1
        j addForLoop

What this does is store the lowest integer value a user has entered and then increments it to an upper integer value they have entered + 1 so that it increments correctly. It then adds appropriately and then increments the counter by 1, repeating if they are not the same. When the values are the same, it exits out of the loop. For example, if the values are 2 and 4, the answer would be 2 + 3 = 5, then 5 + 4 = 9. The loop would output with the answer 9 as it should. I tried to do this same thing but multiplying instead, and this is where my problem is. When trying to replace add with mul (like this),:
        beq $t0, $t6, resultFunction
        mul $t4, $t4, $t0
        addi $t0, $t0, 1
        j multForLoop

it is not working correctly and I'm getting 0 as the output instead. If the two integers are 2 and 4 again, it should output 24 (2 * 3 = 6, 6 * 4 = 24). I'm not quite sure why this isn't working and any help would be appreciated.
Answer: You haven't shown us all your code, but presumably $t4 is 0 when the loop starts, and anything multiplied by 0 equals 0.
Set $t4 to 1 before the loop.
Comment: Thank you. I actually had just figured it out, it was 0 and I had to implement two different for loops. The first added the lowest integer value plus 0 and stored it into $t4, and once that loop was finished, I had the for loop for multiply work correctly since $t4 was now no longer 0.

For loop counter in MIPS


Algebraic and topological complements in a Hilbert space

Question: Every closed subspace of a Hilbert space has a topological complement, namely its orthogonal complement.  I'm wondering if every algebraic complement of a closed subspace of a Hilbert space is automatically a topological complement.
In other words, if $C$ is closed, $V$ and $C$ have trivial intersection, and $V+C$ is the whole space, then is $V$ automatically closed?
Thank you for your help!
Answer: Not in infinite dimension. Yes, of course, in finite dimension since every subspace is closed.
Take a nonzero, unbounded linear functional $\phi$ on your infinite-dimensional Hilbert space $H$. Take $x_0\in H$ such that $\phi(x_0)=1$. Then
$$
H=\ker \phi \oplus \mathbb{C}x_0\qquad x=(x-\phi(x)x_0)+\phi(x)x_0.
$$
Since $\mathbb{C}x_0$ is finite-dimensional, it is closed. And since $\phi$ is unbounded, $\ker \phi$ is not closed.
Notes:

To "construct" such a $\phi$, take $\{e_n\}$ an infinite orthonormal set in $H$ and set $\phi(e_n):=n$. Extend by linearity to $\mbox{span}\{e_n\}$. Then extend to any algebraic complement of $\mbox{span}\{e_n\}$ by $0$.
If $H=F\oplus G$ is an orthogonal direct sum of any two subspaces of $H$, though, then both $F$ and $G$ must be closed and we have $F=G^\perp$ and $G=F^\perp$.
Comment: That's a great example.  Thank you!


Como evitar erro de cálculo no SQL Server?

Question: Tenho uma consulta que faz um calculo, mais o campo "a.totalcustoprodutos" aparece com valor zero em alguns momentos, então gera um erro de divisão por zero, é possível passar algum valor padrão? Tipo 1 caso tenha o valor zero?
select a.totalcustoprodutos, a.datanota, a.numeronota, a.cfop,
((a.totalnota / a.totalcustoprodutos) - 1.000) * 100 as TotalMargem
from TB_C_VENDAS a
where a.numeronota > 0 and a.tipooperacao = 'V'

Comment: E o correto assumir o valor de `a.totalnota` cheio se não tiver valor algum (0) em `a.totalcustoprodutos`? A lógica é esta que você quer, ou está só tentando resolver um problema causando outro?
Comment: Eu preciso do total totalcustoprodutos custo produto para encontra a média, não posso usar o totalnota. Agradeço!
Comment: Então as repostas dadas não faz o que você deseja, certo? O que deve ser feito então quando encontra um zero no `a.totalcustoprodutos`? Nada. não calcula? Gera erro? Pega outro valor? Usa uma fórmula completamente diferente?
Comment: Já postaram uma resposta que resolveu o problema. agradeço!
Comment: Se o que você comentou acima está certo esta resposta só resolve algumas situações. Mas não sou eu que terei prejuízo. Se realmente responde, o que você comentou está errado. Sem conhecer o real problema, eu duvido que isto solucione corretamente. E o problema pode estar em outro lugar. Talvez nem deveria ter o 0 lá. Mas aí já é especulação.
Comment: Você esta certo, não resolve em tudo, é preciso analisar o relatório depois mais é a única forma de não ter a mensagem de erro. Eu já identifiquei o porquê do total custo produtos = 0 mais eu preciso trazer todos os registros, então seria um jeito de evitar o erro inicial, depois do relatório então é possível analisar o porquê do custo zero. Agradeço
Answer: Tu pode fazer um "CASE". Veja:
select a.totalcustoprodutos, a.datanota, a.numeronota,a.cfop, ((a.totalnota / (CASE WHEN a.totalcustoprodutos > 0 THEN a.totalcustoprodutos ELSE 1 END)) - 1.000) * 100 as TotalMargem
from TB_C_VENDAS a
where a.numeronota > 0 and a.tipooperacao = 'V'

Comment: Agradeço a ajuda!
Answer: SELECT a.totalcustoprodutos,
       a.datanota,
       a.numeronota,
       a.cfop,
       ((a.totalnota / NULLIF(isnull(a.totalcustoprodutos,0))) - 1.000) * 100 AS TotalMargem,
FROM TB_C_VENDAS a
WHERE a.numeronota > 0
  AND a.tipooperacao = 'V'
assim fica bem mais simples
a funcao NULLIF retona null caso o a.totalcustoprodutos seja 0
como a.totalcustoprodutos tambem pode ser null, forcamos o 0 com a isnull
um valor dividido por null retorna null e nao da erro.
um valor dividido por 0 da erro.
Answer: Você pode usar o "Case" e substituir o "zero" por outro número:
Ex:
SELECT a.totalcustoprodutos,
       a.datanota,
       a.numeronota,
       a.cfop,
       ((a.totalnota / (CASE a.totalcustoprodutos WHEN 0 THEN 1
                        ELSE a.totalcustoprodutos END)) - 1.000) * 100 AS TotalMargem,
FROM TB_C_VENDAS a
WHERE a.numeronota > 0
  AND a.tipooperacao = 'V'

Porém, será que apenas substituir 0 por 1 seria uma solução ou apenas um "jeitinho"?
Talvez seria legal identificar o porquê esse campo está igual a 0 e talvez adicionar um filtro no seu select para não trazer os registros que possuem na coluna totalcustoprodutos iguais a 0.
Comment: eu já identifiquei o porque do total custo produtos = 0 mais eu preciso trazer todos os registros, então seria um jeito de evitar o erro inicial, depois do relatório então é possível analisar o porque do custo zero. agradeço


Swift 4 Get preferredUnit from HealthKit

Question: I´m a beginner in Swift and I tried to get the User preferred Unit from HealthKit.
Apple offers this function for it
func preferredUnits(for quantityTypes: Set<HKQuantityType>,
     completion: @escaping ([HKQuantityType : HKUnit], Error?) -> Void)

Source
But I really have no idea how to implement it correctly. Atm the function do nothing in my App.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.

    let bloodGlucose = HKObjectType.quantityType(forIdentifier: .bloodGlucose)
    let HKQuantitySet: Set<HKSampleType> = [bloodGlucose!]

    self.preferredUnits(for: HKQuantitySet as! Set<HKQuantityType>, completion: { (preferedUnit, error) in
            print(preferedUnit)
        })

    return true
}

func preferredUnits(for quantityTypes: Set<HKQuantityType>,
                completion: @escaping ([HKQuantityType : HKUnit], Error?) -> Void){

}

I´m pretty sure I am totally wrong about this.
Does someone know how to implement the function correctly? Not only for bloodglucose, in general, would be nice.
Comment: You implementation looks ok so far.  What do you want to do with the value?  You would probably store it in a property.
Comment: You need to show more code in context. How is this code supposed to be called?
Comment: There must be more code. You can just type this code in the middle of your AppDelegate. It must be enclosed in some function. Which function?  How is that function called
Comment: Don't post additional information as an answer; [edit](https://stackoverflow.com/posts/50936871/edit) your question.
Comment: I would store it into the userdefaults. That's not the problem. The problem is that I do not getting any value or error. The app just do not execute the function. I implemented it into the app delegate file after I get the state of permission.
Comment: There is no more code. I have no idea how to implement it. But I would like to implement it like the following.
Executed on Startup, the App detects the user preferred Unit and stores it to the "userdefaults"
Comment: I posted the Code as Answer @Paulw11
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/173430/discussion-between-paulw11-and-exitare).
Answer: You need to call the preferredUnits function an instance of HKHealthStore.  Your code is just calling a function that you have declared with the same signature that does nothing.