text:
Q: Lifting nested values from json that might be optional using Serde in Rust I am using this solution:
Is there a way to omit wrapper/root objects when deserializing objects with Serde?
to raise float values out of nested json structures:
Here is the JSON
"activitiesWon": {
    "statId": "activitiesWon",
    "basic": {
        "value": 3.0,
        "displayValue": "3"
    }
},

And here is the data structure and customer deserializer:
#[derive(Serialize, Deserialize, Debug, Default, Clone, Copy)]
pub struct PvpStatsData {
    #[serde(rename = "activitiesWon", deserialize_with="property_to_float")]
    pub activities_won:f32,
}

pub fn property_to_float<'de, D>(deserializer: D) -> Result<f32, D::Error>
    where D: serde::de::Deserializer<'de>,
{
    #[derive(Deserialize)]
    struct Outer {
        pub basic: Inner,
    }

    #[derive(Deserialize)]
    struct Inner {
        pub value: f32,
    }

    let helper = Outer::deserialize(deserializer)?;
    Ok(helper.basic.value)
}

This works great. However, some of the structures / properties might not exist, and thus their field signature looks like this, with the custom deserializer which either returns a Option, or None:
#[derive(Serialize, Deserialize, Debug, Default, Clone, Copy)]
pub struct PvpStatsData {
    #[serde(rename = "bestSingleGameKills", deserialize_with="property_to_option_float")]
    pub best_single_game_kills:Option<f32>,
}

pub fn property_to_option_float<'de, D>(deserializer: D) -> Result<Option<f32>, D::Error>
    where D: serde::de::Deserializer<'de>,
{
    println!("PARSER");
    #[derive(Deserialize, Debug, )]
    struct Outer {
        pub basic: Inner,
    }

    #[derive(Deserialize, Debug, )]
    struct Inner {
        pub value: f32,
    }

    Option::<Outer>::deserialize(deserializer).map(|o:Option<Outer>| match o {
        Some(e) => {
            println!("{:?}", e);
            Some(e.basic.value)
        },
        None => None,
    })
}

However, when parsing, if the property doesn't exist in json, then I get a parse error:
serde_json::Error : Error("missing field `bestSingleGameKills`", line: 1, column: 4358)

and my custom de-serialization method is never called.
Anyone know why the de-serialization method is not called? and / or how I can get it to be called when the property doesn't exist? I have other deserializers that can deal with Optional results, but I suspect this has something to do with the combination of the nested json and option.
Ive posted a playground of the example here:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=022d7ca3513e411644d186518d177645
(just uncomment the second json block to see the issue)

A: The default field attribute should work (I'm assuming you are ok with best_single_game_kills defaulting to None when it is absent in the json).
#[derive(Deserialize, Debug, Default, Clone, Copy)]
pub struct PvpStatsData {
    #[serde(default, rename = "activitiesWon", deserialize_with="property_to_float")]
    pub activities_won:f32,

    #[serde(default, rename = "bestSingleGameKills", deserialize_with="property_to_option_float")]
    pub best_single_game_kills:Option<f32>,
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a50748db2fb585a9430371a6ecd10f82


text:
Q: Dynamically load a JavaScript file How can you reliably and dynamically load a JavaScript file?  This will can be used to implement a module or component that when 'initialized' the component will dynamically load all needed JavaScript library scripts on demand.
The client that uses the component isn't required to load all the library script files (and manually insert <script> tags into their web page) that implement this component - just the 'main' component script file.
How do mainstream JavaScript libraries accomplish this (Prototype, jQuery, etc)?  Do these tools merge multiple JavaScript files into a single redistributable 'build' version of a script file?  Or do they do any dynamic loading of ancillary 'library' scripts?
An addition to this question: is there a way to handle the event after a dynamically included JavaScript file is loaded?  Prototype has document.observe for document-wide events. Example:
document.observe("dom:loaded", function() {
  // initially hide all containers for tab content
  $$('div.tabcontent').invoke('hide');
});

What are the available events for a script element?

A: You may create a script element dynamically, using Prototypes:
new Element("script", {src: "myBigCodeLibrary.js", type: "text/javascript"});

The problem here is that we do not know when the external script file is fully loaded.
We often want our dependant code on the very next line and like to write something like:
if (iNeedSomeMore) {
    Script.load("myBigCodeLibrary.js"); // includes code for myFancyMethod();
    myFancyMethod(); // cool, no need for callbacks!
}

There is a smart way to inject script dependencies without the need of callbacks. You simply have to pull the script via a synchronous AJAX request and eval the script on global level.
If you use Prototype the Script.load method looks like this:
var Script = {
    _loadedScripts: [],
    include: function(script) {
        // include script only once
        if (this._loadedScripts.include(script)) {
            return false;
        }
        // request file synchronous
        var code = new Ajax.Request(script, {
            asynchronous: false,
            method: "GET",
            evalJS: false,
            evalJSON: false
        }).transport.responseText;
        // eval code on global level
        if (Prototype.Browser.IE) {
            window.execScript(code);
        } else if (Prototype.Browser.WebKit) {
            $$("head").first().insert(Object.extend(
                new Element("script", {
                    type: "text/javascript"
                }), {
                    text: code
                }
            ));
        } else {
            window.eval(code);
        }
        // remember included script
        this._loadedScripts.push(script);
    }
};

A: There is no import / include / require in javascript, but there are two main ways to achieve what you want:
1 - You can load it with an AJAX call then use eval.
This is the most straightforward way but it's limited to your domain because of the Javascript safety settings, and using eval is opening the door to bugs and hacks.
2 - Add a script element with the script URL in the HTML.
Definitely the best way to go. You can load the script even from a foreign server, and it's clean as you use the browser parser to evaluate the code. You can put the script element in the head element of the web page, or at the bottom of the body.
Both of these solutions are discussed and illustrated here.
Now, there is a big issue you must know about. Doing that implies that you remotely load the code. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performances.
It means that if you use these tricks directly, you won't be able to use your newly loaded code the next line after you asked it to be loaded, because it will be still loading.
E.G : my_lovely_script.js contains MySuperObject
var js = document.createElement("script");

js.type = "text/javascript";
js.src = jsFilePath;

document.body.appendChild(js);

var s = new MySuperObject();

Error : MySuperObject is undefined

Then you reload the page hitting F5. And it works! Confusing...
So what to do about it ?
Well, you can use the hack the author suggests in the link I gave you. In summary, for people in a hurry, he uses en event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. E.G :
function loadScript(url, callback)
{
    // adding the script element to the head as suggested before
   var head = document.getElementsByTagName('head')[0];
   var script = document.createElement('script');
   script.type = 'text/javascript';
   script.src = url;

   // then bind the event to the callback function
   // there are several events for cross browser compatibility
   script.onreadystatechange = callback;
   script.onload = callback;

   // fire the loading
   head.appendChild(script);
}

Then you write the code you want to use AFTER the script is loaded in a lambda function :
var myPrettyCode = function() {
    // here, do what ever you want
};

Then you run all that :
loadScript("my_lovely_script.js", myPrettyCode);

Ok, I got it. But it's a pain to write all this stuff.
Well, in that case, you can use as always the fantastic free jQuery framework, which let you do the very same thing in one line :
$.getScript("my_lovely_script.js", function() {
    alert("Script loaded and executed.");
    // here you can use anything you defined in the loaded script
});

A: If you have jQuery loaded already, you should use $.getScript.
This has an advantage over the other answers here in that you have a built in callback function (to guarantee the script is loaded before the dependant code runs) and you can control caching.

A: If you want a SYNC script loading, you need to add script text directly to HTML HEAD element. Adding it as  will trigger an ASYNC load. To load script text from external file synchronously, use XHR. Below a quick sample (it is using parts of other answers in this and other posts):
/*sample requires an additional method for array prototype:*/

if (Array.prototype.contains === undefined) {
Array.prototype.contains = function (obj) {
    var i = this.length;
    while (i--) { if (this[i] === obj) return true; }
    return false;
};
};

/*define object that will wrap our logic*/
var ScriptLoader = {
LoadedFiles: [],

LoadFile: function (url) {
    var self = this;
    if (this.LoadedFiles.contains(url)) return;

    var xhr = new XMLHttpRequest();
    xhr.onload = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                self.LoadedFiles.push(url);
                self.AddScript(xhr.responseText);
            } else {
                if (console) console.error(xhr.statusText);
            }
        }
    };
    xhr.open("GET", url, false);/*last parameter defines if call is async or not*/
    xhr.send(null);
},

AddScript: function (code) {
    var oNew = document.createElement("script");
    oNew.type = "text/javascript";
    oNew.textContent = code;
    document.getElementsByTagName("head")[0].appendChild(oNew);
}
};

/*Load script file. ScriptLoader will check if you try to load a file that has already been loaded (this check might be better, but I'm lazy).*/

ScriptLoader.LoadFile("Scripts/jquery-2.0.1.min.js");
ScriptLoader.LoadFile("Scripts/jquery-2.0.1.min.js");
/*this will be executed right after upper lines. It requires jquery to execute. It requires a HTML input with id "tb1"*/
$(function () { alert($('#tb1').val()); });

A: With Promises you can simplify it like this.
Loader function:
  const loadCDN = src =>
    new Promise((resolve, reject) => {
      if (document.querySelector(`head > script[src="${src}"]`) !== null) return resolve()
      const script = document.createElement("script")
      script.src = src
      script.async = true
      document.head.appendChild(script)
      script.onload = resolve
      script.onerror = reject
    })

Usage (async/await):
await loadCDN("https://.../script.js")

Usage (Promise):
loadCDN("https://.../script.js").then(res => {}).catch(err => {})

NOTE: there was one similar solution but it doesn't check if the script is already loaded and loads the script each time. This one checks src property.

A: I used a much less complicated version recently with jQuery:
<script src="scripts/jquery.js"></script>
<script>
  var js = ["scripts/jquery.dimensions.js", "scripts/shadedborder.js", "scripts/jqmodal.js", "scripts/main.js"];
  var $head = $("head");
  for (var i = 0; i < js.length; i++) {
    $head.append("<script src=\"" + js[i] + "\"></scr" + "ipt>");
  }
</script>

It worked great in every browser I tested it in: IE6/7, Firefox, Safari, Opera.
Update: jQuery-less version:
<script>
  var js = ["scripts/jquery.dimensions.js", "scripts/shadedborder.js", "scripts/jqmodal.js", "scripts/main.js"];
  for (var i = 0, l = js.length; i < l; i++) {
    document.getElementsByTagName("head")[0].innerHTML += ("<script src=\"" + js[i] + "\"></scr" + "ipt>");
  }
</script>

A:
does anyone have a better way?

I think just adding the script to the body would be easier then adding it to the last node on the page.  How about this:
function include(url) {
  var s = document.createElement("script");
  s.setAttribute("type", "text/javascript");
  s.setAttribute("src", url);
  document.body.appendChild(s);
}

A: i've used yet another solution i found on the net ... this one is under creativecommons and it checks if the source was included prior to calling the function ...
you can find the file here: include.js
/** include - including .js files from JS - bfults@gmail.com - 2005-02-09
 ** Code licensed under Creative Commons Attribution-ShareAlike License
 ** http://creativecommons.org/licenses/by-sa/2.0/
 **/
var hIncludes = null;
function include(sURI)
{
  if (document.getElementsByTagName)
  {
    if (!hIncludes)
    {
      hIncludes = {};
      var cScripts = document.getElementsByTagName("script");
      for (var i=0,len=cScripts.length; i < len; i++)
        if (cScripts[i].src) hIncludes[cScripts[i].src] = true;
    }
    if (!hIncludes[sURI])
    {
      var oNew = document.createElement("script");
      oNew.type = "text/javascript";
      oNew.src = sURI;
      hIncludes[sURI]=true;
      document.getElementsByTagName("head")[0].appendChild(oNew);
    }
  }
}

A: Just found out about a great feature in YUI 3 (at the time of writing available in preview release). You can easily insert dependencies to YUI libraries and to "external" modules (what you are looking for) without too much code: YUI Loader.
It also answers your second question regarding the function being called as soon as the external module is loaded.
Example:
YUI({
    modules: {
        'simple': {
            fullpath: "http://example.com/public/js/simple.js"
        },
        'complicated': {
            fullpath: "http://example.com/public/js/complicated.js"
            requires: ['simple']  // <-- dependency to 'simple' module
        }
    },
    timeout: 10000
}).use('complicated', function(Y, result) {
    // called as soon as 'complicated' is loaded
    if (!result.success) {
        // loading failed, or timeout
        handleError(result.msg);
    } else {
        // call a function that needs 'complicated'
        doSomethingComplicated(...);
    }
});

Worked perfectly for me and has the advantage of managing dependencies. Refer to the YUI documentation for an example with YUI 2 calendar.

A: I know my answer is bit late for this question, but, here is a great article in www.html5rocks.com - Deep dive into the murky waters of script loading .
In that article it is concluded that in regards of browser support, the best way to dynamically load JavaScript file without blocking content rendering is the following way:
Considering you've four scripts named script1.js, script2.js, script3.js, script4.js then you can do it with applying async = false:
[
  'script1.js',
  'script2.js',
  'script3.js',
  'script4.js'
].forEach(function(src) {
  var script = document.createElement('script');
  script.src = src;
  script.async = false;
  document.head.appendChild(script);
});

Now, Spec says: Download together, execute in order as soon as all download.
Firefox < 3.6, Opera says: I have no idea what this "async" thing is, but it just so happens I execute scripts added via JS in the order they're added.
Safari 5.0 says: I understand "async", but don't understand setting it to "false" with JS. I'll execute your scripts as soon as they land, in whatever order.
IE < 10 says: No idea about "async", but there is a workaround using "onreadystatechange".
Everything else says: I'm your friend, we're going to do this by the book.
Now, the full code with IE < 10 workaround:
var scripts = [
  'script1.js',
  'script2.js',
  'script3.js',
  'script4.js'
];
var src;
var script;
var pendingScripts = [];
var firstScript = document.scripts[0];

// Watch scripts load in IE
function stateChange() {
  // Execute as many scripts in order as we can
  var pendingScript;
  while (pendingScripts[0] && pendingScripts[0].readyState == 'loaded') {
    pendingScript = pendingScripts.shift();
    // avoid future loading events from this script (eg, if src changes)
    pendingScript.onreadystatechange = null;
    // can't just appendChild, old IE bug if element isn't closed
    firstScript.parentNode.insertBefore(pendingScript, firstScript);
  }
}

// loop through our script urls
while (src = scripts.shift()) {
  if ('async' in firstScript) { // modern browsers
    script = document.createElement('script');
    script.async = false;
    script.src = src;
    document.head.appendChild(script);
  }
  else if (firstScript.readyState) { // IE<10
    // create a script and add it to our todo pile
    script = document.createElement('script');
    pendingScripts.push(script);
    // listen for state changes
    script.onreadystatechange = stateChange;
    // must set src AFTER adding onreadystatechange listener
    // else we'll miss the loaded event for cached scripts
    script.src = src;
  }
  else { // fall back to defer
    document.write('<script src="' + src + '" defer></'+'script>');
  }
}

A few tricks and minification later, it's 362 bytes
!function(e,t,r){function n(){for(;d[0]&&"loaded"==d[0][f];)c=d.shift(),c[o]=!i.parentNode.insertBefore(c,i)}for(var s,a,c,d=[],i=e.scripts[0],o="onreadystatechange",f="readyState";s=r.shift();)a=e.createElement(t),"async"in i?(a.async=!1,e.head.appendChild(a)):i[f]?(d.push(a),a[o]=n):e.write("<"+t+' src="'+s+'" defer></'+t+">"),a.src=s}(document,"script",[
  "//other-domain.com/1.js",
  "2.js"
])

A: There's a new proposed ECMA standard called dynamic import, recently incorporated into Chrome and Safari.
const moduleSpecifier = './dir/someModule.js';

import(moduleSpecifier)
   .then(someModule => someModule.foo()); // executes foo method in someModule

A: I did basically the same thing that you did Adam, but with a slight modification to make sure I was appending to the head element to get the job done.  I simply created an include function (code below) to handle both script and CSS files.
This function also checks to make sure that the script or CSS file hasn't already been loaded dynamically.  It does not check for hand coded values and there may have been a better way to do that, but it served the purpose.
function include( url, type ){
    // First make sure it hasn't been loaded by something else.
    if( Array.contains( includedFile, url ) )
        return;

    // Determine the MIME type.
    var jsExpr = new RegExp( "js$", "i" );
    var cssExpr = new RegExp( "css$", "i" );
    if( type == null )
        if( jsExpr.test( url ) )
            type = 'text/javascript';
        else if( cssExpr.test( url ) )
            type = 'text/css';

    // Create the appropriate element.
    var element = null;
    switch( type ){
        case 'text/javascript' :
            element = document.createElement( 'script' );
            element.type = type;
            element.src = url;
            break;
        case 'text/css' :
            element = document.createElement( 'link' );
            element.rel = 'stylesheet';
            element.type = type;
            element.href = url;
            break;
    }

    // Insert it to the <head> and the array to ensure it is not
    // loaded again.
    document.getElementsByTagName("head")[0].appendChild( element );
    Array.add( includedFile, url );
}

A: The technique we use at work is to request the javascript file using an AJAX request and then eval() the return.  If you're using the prototype library, they support this functionality in their Ajax.Request call.

A: jquery resolved this for me with its .append() function
- used this to load the complete jquery ui package
/*
 * FILENAME : project.library.js
 * USAGE    : loads any javascript library
 */
    var dirPath = "../js/";
    var library = ["functions.js","swfobject.js","jquery.jeditable.mini.js","jquery-ui-1.8.8.custom.min.js","ui/jquery.ui.core.min.js","ui/jquery.ui.widget.min.js","ui/jquery.ui.position.min.js","ui/jquery.ui.button.min.js","ui/jquery.ui.mouse.min.js","ui/jquery.ui.dialog.min.js","ui/jquery.effects.core.min.js","ui/jquery.effects.blind.min.js","ui/jquery.effects.fade.min.js","ui/jquery.effects.slide.min.js","ui/jquery.effects.transfer.min.js"];

    for(var script in library){
        $('head').append('<script type="text/javascript" src="' + dirPath + library[script] + '"></script>');
    }

To Use - in the head of your html/php/etc after you import jquery.js you would just include this one file like so to load in the entirety of your library appending it to the head...
<script type="text/javascript" src="project.library.js"></script>

A: Keep it nice, short, simple, and maintainable! :]
// 3rd party plugins / script (don't forget the full path is necessary)
var FULL_PATH = '', s =
[
    FULL_PATH + 'plugins/script.js'      // Script example
    FULL_PATH + 'plugins/jquery.1.2.js', // jQuery Library
    FULL_PATH + 'plugins/crypto-js/hmac-sha1.js',      // CryptoJS
    FULL_PATH + 'plugins/crypto-js/enc-base64-min.js'  // CryptoJS
];

function load(url)
{
    var ajax = new XMLHttpRequest();
    ajax.open('GET', url, false);
    ajax.onreadystatechange = function ()
    {
        var script = ajax.response || ajax.responseText;
        if (ajax.readyState === 4)
        {
            switch(ajax.status)
            {
                case 200:
                    eval.apply( window, [script] );
                    console.log("library loaded: ", url);
                    break;
                default:
                    console.log("ERROR: library not loaded: ", url);
            }
        }
    };
    ajax.send(null);
}

 // initialize a single load
load('plugins/script.js');

// initialize a full load of scripts
if (s.length > 0)
{
    for (i = 0; i < s.length; i++)
    {
        load(s[i]);
    }
}

This code is simply a short functional example that could require additional feature functionality for full support on any (or given) platform.

A: Something like this...
<script>
     $(document).ready(function() {
          $('body').append('<script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places&callback=getCurrentPickupLocation" async defer><\/script>');
     });
</script>

A: This works:
await new Promise((resolve, reject) => {
  let js = document.createElement("script");
  js.src = "mylibrary.js";
  js.onload = resolve;
  js.onerror = reject;
  document.body.appendChild(js)
});

Obviously if the script you want to import is a module, you can use the import(...) function.

A: another awesome answer
$.getScript("my_lovely_script.js", function(){

   alert("Script loaded and executed.");
  // here you can use anything you defined in the loaded script

 });

https://stackoverflow.com/a/950146/671046

A: Dynamic module import landed in Firefox 67+.
(async () => {
   await import('./synth/BubbleSynth.js')
})()

With error handling:
(async () => {
    await import('./synth/BubbleSynth.js').catch((error) => console.log('Loading failed' + error))
})()

It also works for any kind of non-modules libraries, on this case the lib is available on the window.self object, the old way, but only on demand, which is nice.
Example using suncalc.js, the server must have CORS enabled to works this way!

(async () => {
 await import('https://cdnjs.cloudflare.com/ajax/libs/suncalc/1.8.0/suncalc.min.js')
 .then( () => {
   let times = SunCalc.getTimes(new Date(), 51.5,-0.1);
   console.log("Golden Hour today in London: " + times.goldenHour.getHours() + ':' + times.goldenHour.getMinutes() + ". Take your pics!")
  })
})()

https://caniuse.com/#feat=es6-module-dynamic-import

A: Here is some example code I've found... does anyone have a better way?
  function include(url)
  {
    var s = document.createElement("script");
    s.setAttribute("type", "text/javascript");
    s.setAttribute("src", url);
    var nodes = document.getElementsByTagName("*");
    var node = nodes[nodes.length -1].parentNode;
    node.appendChild(s);
  }

A: There are scripts that are designed specifically for this purpose.
yepnope.js is built into Modernizr, and lab.js is a more optimized (but less user friendly version.
I wouldn't reccomend doing this through a big library like jquery or prototype - because one of the major benefits of a script loader is the ability to load scripts early - you shouldn't have to wait until jquery & all your dom elements load before running a check to see if you want to dynamically load a script.

A: I wrote a simple module that automatizes the job of importing/including module scripts in JavaScript. Give it a try and please spare some feedback! :) For detailed explanation of the code refer to this blog post: http://stamat.wordpress.com/2013/04/12/javascript-require-import-include-modules/
var _rmod = _rmod || {}; //require module namespace
_rmod.on_ready_fn_stack = [];
_rmod.libpath = '';
_rmod.imported = {};
_rmod.loading = {
    scripts: {},
    length: 0
};

_rmod.findScriptPath = function(script_name) {
    var script_elems = document.getElementsByTagName('script');
    for (var i = 0; i < script_elems.length; i++) {
        if (script_elems[i].src.endsWith(script_name)) {
            var href = window.location.href;
            href = href.substring(0, href.lastIndexOf('/'));
            var url = script_elems[i].src.substring(0, script_elems[i].length - script_name.length);
            return url.substring(href.length+1, url.length);
        }
    }
    return '';
};

_rmod.libpath = _rmod.findScriptPath('script.js'); //Path of your main script used to mark the root directory of your library, any library

_rmod.injectScript = function(script_name, uri, callback, prepare) {

    if(!prepare)
        prepare(script_name, uri);

    var script_elem = document.createElement('script');
    script_elem.type = 'text/javascript';
    script_elem.title = script_name;
    script_elem.src = uri;
    script_elem.async = true;
    script_elem.defer = false;

    if(!callback)
        script_elem.onload = function() {
            callback(script_name, uri);
        };

    document.getElementsByTagName('head')[0].appendChild(script_elem);
};

_rmod.requirePrepare = function(script_name, uri) {
    _rmod.loading.scripts[script_name] = uri;
    _rmod.loading.length++;
};

_rmod.requireCallback = function(script_name, uri) {
    _rmod.loading.length--;
    delete _rmod.loading.scripts[script_name];
    _rmod.imported[script_name] = uri;

    if(_rmod.loading.length == 0)
        _rmod.onReady();
};

_rmod.onReady = function() {
    if (!_rmod.LOADED) {
        for (var i = 0; i < _rmod.on_ready_fn_stack.length; i++){
            _rmod.on_ready_fn_stack[i]();
        });
        _rmod.LOADED = true;
    }
};

//you can rename based on your liking. I chose require, but it can be called include or anything else that is easy for you to remember or write, except import because it is reserved for future use.
var require = function(script_name) {
    var np = script_name.split('.');
    if (np[np.length-1] === '*') {
        np.pop();
        np.push('_all');
    }

    script_name = np.join('.');
    var uri = _rmod.libpath + np.join('/')+'.js';
    if (!_rmod.loading.scripts.hasOwnProperty(script_name)
     && !_rmod.imported.hasOwnProperty(script_name)) {
        _rmod.injectScript(script_name, uri,
            _rmod.requireCallback,
                _rmod.requirePrepare);
    }
};

var ready = function(fn) {
    _rmod.on_ready_fn_stack.push(fn);
};

// ----- USAGE -----

require('ivar.util.array');
require('ivar.util.string');
require('ivar.net.*');

ready(function(){
    //do something when required scripts are loaded
});

A: I am lost in all these samples but today I needed to load an external .js from my main .js and I did this:
document.write("<script src='https://www.google.com/recaptcha/api.js'></script>");

A: Here is a simple one with callback and IE support:
function loadScript(url, callback) {

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState) { //IE
        script.onreadystatechange = function () {
            if (script.readyState == "loaded" || script.readyState == "complete") {
                script.onreadystatechange = null;
                callback();
            }
        };
    } else { //Others
        script.onload = function () {
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

loadScript("https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {

     //jQuery loaded
     console.log('jquery loaded');

});

A: Here a simple example for a function to load JS files. Relevant points:

*

*you don't need jQuery, so you may use this initially to load also the jQuery.js file

*it is async with callback

*it ensures it loads only once, as it keeps an enclosure with the record of loaded urls, thus avoiding usage of network

*contrary to jQuery $.ajax or $.getScript you can use nonces, solving thus issues with CSP unsafe-inline. Just use the property script.nonce
var getScriptOnce = function() {

    var scriptArray = []; //array of urls (closure)

    //function to defer loading of script
    return function (url, callback){
        //the array doesn't have such url
        if (scriptArray.indexOf(url) === -1){

            var script=document.createElement('script');
            script.src=url;
            var head=document.getElementsByTagName('head')[0],
                done=false;

            script.onload=script.onreadystatechange = function(){
                if ( !done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ) {
                    done=true;
                    if (typeof callback === 'function') {
                        callback();
                    }
                    script.onload = script.onreadystatechange = null;
                    head.removeChild(script);

                    scriptArray.push(url);
                }
            };

            head.appendChild(script);
        }
    };
}();

Now you use it simply by
getScriptOnce("url_of_your_JS_file.js");

A: For those of you, who love one-liners:
import('./myscript.js');

Chances are you might get an error, like:

Access to script at 'http://..../myscript.js' from origin
  'http://127.0.0.1' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

In which case, you can fallback to:
fetch('myscript.js').then(r => r.text()).then(t => new Function(t)());

A: In as much as I love how handy the JQuery approach is, the JavaScript approach isn't that complicated but just require little tweaking to what you already use...
Here is how I load JS dynamically(Only when needed), and wait for them to load before executing the script that depends on them.
JavaScript Approach
//Create a script element that will load
let dynamicScript = document.createElement('script');

//Set source to the script we need to load
dynamicScript.src = 'linkToNeededJsFile.js';

//Set onload to callback function that depends on this script or do inline as shown below
dynamicScript.onload = () => {

    //Code that depends on the loaded script should be here

};

//append the created script element to body element
document.body.append(dynamicScript);

There are other ways approach one could accomplish this with JS but, I prefer this as it's require the basic JS knowledge every dev can relate.
Not part of the answer but here is the JQuery version I prefer with projects that already include JQuery:
$.getScript('linkToNeededJsFile.js', () => {

    //Code that depends on the loaded script should be here

});

More on the JQuery option here

A: This function uses memorization. And could be called many times with no conflicts of loading and running the same script twice. Also it's not resolving sooner than the script is actually loaded (like in @radulle answer).
const loadScript = function () {
    let cache = {};
    return function (src) {
        return cache[src] || (cache[src] = new Promise((resolve, reject) => {
            let s = document.createElement('script');
            s.defer = true;
            s.src = src;
            s.onload = resolve;
            s.onerror = reject;
            document.head.append(s);
        }));
    }
}();

Please notice the parentheses () after the function expression.
Parallel loading of scripts:
Promise.all([
    loadScript('/script1.js'),
    loadScript('/script2.js'),
    // ...
]).then(() => {
    // do something
})

You can use the same method for dynamic loading stylesheets.

A: all the major javascript libraries like jscript, prototype, YUI have support for loading script files. For example, in YUI, after loading the core you can do the following to load the calendar control
var loader = new YAHOO.util.YUILoader({

    require: ['calendar'], // what components?

    base: '../../build/',//where do they live?

    //filter: "DEBUG",  //use debug versions (or apply some
                        //some other filter?

    //loadOptional: true, //load all optional dependencies?

    //onSuccess is the function that YUI Loader
    //should call when all components are successfully loaded.
    onSuccess: function() {
        //Once the YUI Calendar Control and dependencies are on
        //the page, we'll verify that our target container is
        //available in the DOM and then instantiate a default
        //calendar into it:
        YAHOO.util.Event.onAvailable("calendar_container", function() {
            var myCal = new YAHOO.widget.Calendar("mycal_id", "calendar_container");
            myCal.render();
        })
     },

    // should a failure occur, the onFailure function will be executed
    onFailure: function(o) {
        alert("error: " + YAHOO.lang.dump(o));
    }

 });

// Calculate the dependency and insert the required scripts and css resources
// into the document
loader.insert();

A: I have tweaked some of the above post with working example.
Here we can give css and js in same array also.
$(document).ready(function(){

if (Array.prototype.contains === undefined) {
Array.prototype.contains = function (obj) {
    var i = this.length;
    while (i--) { if (this[i] === obj) return true; }
    return false;
};
};

/* define object that will wrap our logic */
var jsScriptCssLoader = {

jsExpr : new RegExp( "js$", "i" ),
cssExpr : new RegExp( "css$", "i" ),
loadedFiles: [],

loadFile: function (cssJsFileArray) {
    var self = this;
    // remove duplicates with in array
    cssJsFileArray.filter((item,index)=>cssJsFileArray.indexOf(item)==index)
    var loadedFileArray = this.loadedFiles;
    $.each(cssJsFileArray, function( index, url ) {
            // if multiple arrays are loaded the check the uniqueness
            if (loadedFileArray.contains(url)) return;
            if( self.jsExpr.test( url ) ){
                $.get(url, function(data) {
                    self.addScript(data);
                });

            }else if( self.cssExpr.test( url ) ){
                $.get(url, function(data) {
                    self.addCss(data);
                });
            }

            self.loadedFiles.push(url);
    });

    // don't load twice accross different arrays

},
addScript: function (code) {
    var oNew = document.createElement("script");
    oNew.type = "text/javascript";
    oNew.textContent = code;
    document.getElementsByTagName("head")[0].appendChild(oNew);
},
addCss: function (code) {
    var oNew = document.createElement("style");
    oNew.textContent = code;
    document.getElementsByTagName("head")[0].appendChild(oNew);
}

};

//jsScriptCssLoader.loadFile(["css/1.css","css/2.css","css/3.css"]);
jsScriptCssLoader.loadFile(["js/common/1.js","js/2.js","js/common/file/fileReader.js"]);
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Online algorithm for calculating standard deviation Normally, I have a more technical problem but I will simplify it for you with an example of counting balls.
Assume I have balls of different colors and one index of an array (initialized to all 0's) reserved for each color. Every time I pick a ball, I increment the corresponding index by 1.
Balls are picked randomly and I can only pick one ball at a time. My sole purpose is to count number of balls for every color, until I run out of balls.
I would like to calculate standard deviation of the number of balls of different colors, while I am counting them. I do not want to calculate it by having to iterate through the array once more after I am done with counting all the balls.
To visualize:
Balls in random order: BBGRRYYBBGGGGGGB (each letter represents first letter of a color)
Array indices from 0 to 3 correspond to colors B, G, R and Y respectively.
When I am done picking the balls, my array looks like [5,7,2,2].
It is very simple to calculate standard deviation after having the final array but I want to do it while I am filling this array.
I want to do it in Java and I have approximately 1000 colors.
What is the most efficient way to implement that? Or is there even a way to do it before having the final array in hand?

A: You don't need an array to calculate standard deviation.
Simply keep track of the number of points, total sum, and total sum of squares.  You can calculate the mean and standard deviation at any time, without having to keep an array.
If I understand your requirements, you'll need a Map where the color is the key and an instance of Statistics is the value.
Here's a class that does it for you.
package statistics;

/**
 * Statistics
 * @author Michael
 * @link http://stackoverflow.com/questions/11978667/online-algorithm-for-calculating-standrd-deviation/11978689#11978689
 * @since 8/15/12 7:34 PM
 */
public class Statistics {

    private int n;
    private double sum;
    private double sumsq;

    public void reset() {
        this.n = 0;
        this.sum = 0.0;
        this.sumsq = 0.0;
    }

    public synchronized void addValue(double x) {
        ++this.n;
        this.sum += x;
        this.sumsq += x*x;
    }

    public synchronized double calculateMean() {
        double mean = 0.0;
        if (this.n > 0) {
            mean = this.sum/this.n;
        }
        return mean;
    }

    public synchronized double calculateVariance() {
       double deviation = calculateStandardDeviation();
        return deviation*deviation;
    }

    public synchronized double calculateStandardDeviation() {
        double deviation = 0.0;
        if (this.n > 1) {
            deviation = Math.sqrt((this.sumsq - this.sum*this.sum/this.n)/(this.n-1));
        }
        return deviation;
    }
}

Here is its unit test:
package statistics;

import org.junit.Assert;
import org.junit.Test;

/**
 * StatisticsTest
 * @author Michael
 * @link http://www.wolframalpha.com/input/?i=variance%281%2C+2%2C+3%2C+4%2C+5%2C+6%29&a=*C.variance-_*Variance-
 * @since 8/15/12 7:42 PM
 */
public class StatisticsTest {

    private static final double TOLERANCE = 1.0E-9;

    @Test
    public void testCalculateMean() {
        double [] values = new double[] {
            1.0, 2.0, 3.0, 4.0, 5.0, 6.0
        };
        Statistics stats = new Statistics();
        for (double value : values) {
            stats.addValue(value);
        }
        double expected = 3.5;
        Assert.assertEquals(expected, stats.calculateMean(), TOLERANCE);
    }

    @Test
    public void testCalculateVariance() {
        double [] values = new double[] {
                1.0, 2.0, 3.0, 4.0, 5.0, 6.0
        };
        Statistics stats = new Statistics();
        for (double value : values) {
            stats.addValue(value);
        }
        double expected = 3.5;
        Assert.assertEquals(expected, stats.calculateVariance(), TOLERANCE);
    }

    @Test
    public void testCalculateStandardDeviation() {
        double [] values = new double[] {
                1.0, 2.0, 3.0, 4.0, 5.0, 6.0
        };
        Statistics stats = new Statistics();
        for (double value : values) {
            stats.addValue(value);
        }
        double expected = Math.sqrt(3.5);
        Assert.assertEquals(expected, stats.calculateStandardDeviation(), TOLERANCE);
    }

}

A: Since average and standard deviation are calculated using sums, you can easily implement appropriate accumulators for these. Then when you want the actual values, finish the rest of the calculation (particularly, the divisions).
The sum of squares is the tricky part since you increment one of the frequencies for each input. One way to deal with this is to maintain a count of each color seen so far (using an appropriate data structure). Then when you see a color in the input, you can subtract out its previous square and add the new square back in (or equivalently add the difference of the two squares to your accumulator).
I'll leave it to the reader to implement the algorithm described here.


text:
Q: Pandas reading file with inconsistent tabs in header I'm reading a data set where columns we're added to the historical files and I want to read the files consistently. The problem is the older files is missing a column don't have the correct number of tabs in the header which leads the first column being read as the index.
The bad.csv
Col1    Col2    Col3    Col4    Col5
6   2   3
5   2   4

A good.csv that loads correctly
Col1    Col2    Col3    Col4    Col5    Col6
6   2   3
5   2   4

I'm reading the csvs file df = pd.read_csv('bad.csv', sep='\t')
I can detect if a file is bad by looking at the index, how can i correct the bad files so that it loads without Col1 being part of the index? I tried df.shift(1, axis=1) but this doesn't include the index, which I can set after shifting but I'm worried this might create more issues. ex:
df = df.shift(1,axis=1)
df.Col1 = df.index

Is there a better way?

A: According to the docs:

Note: index_col=False can be used to force pandas to not use the first
column as the index, e.g. when you have a malformed file with
delimiters at the end of each line.

So I make sure that every line is ended with \t
bad.csv:
col1    col2    col3    col4    col5
2   4   6   8   10
3   5   8   10  13
4   8   12  16  20  24
15  13  11  9   7   5
1   1   2   3   5   8

Then:
df = pd.read_csv('bad.csv', sep='\t', index_col=False)

outcome
   col1  col2  col3  col4  col5  Unnamed: 5
0     2     4     6     8    10         NaN
1     3     5     8    10    13         NaN
2     4     8    12    16    20        24.0
3    15    13    11     9     7         5.0
4     1     1     2     3     5         8.0


text:
Q: Передача функции с аргументами в качестве функции Как передать функцию с аргументами в качестве аргумента (см. переменную result), причем так, чтобы сначала вызвалась функция query, затем функция filterIn, а затем select и в итоге результат вернулся в виде массива объектов (коллекции)?
Ведь если сейчас просто запустить, то вызовется сначала select, потом filterIn и уже потом query
var lib = {
    query: query,
    select: select,
    filterIn: filterIn
};

function query(collection) {
    //Сюда получаем
}

function select() {
    //Код для выборки только нужных ключей коллекции
}

function filterIn(property, values) {
    //Код для фильтрации коллекции
}

var people = [
    {
        name: 'Андрей',
        gender: 'Мужской',
        email: 'andrey@site.ru',
    },
    {
        name: 'Николай',
        gender: 'Мужской',
        email: 'halo@site.ru',
    }
]

var result = lib.query(
    people,
    lib.select('name', 'gender'),
    lib.filterIn('name', ['Андрей', 'Николай'])
);

Причем реализацию переменной result и коллекции редактировать нельзя, все остальное можно.

A: Возвращаемые данные из одной функции надо передавать в другую, и так по цепочке.
select(filter(query(queryArgs), filterArgs), selectArgs);

A: Речь не о запуске функци (его изменить невозможно), а о порядке применения операций к массиву. Функции select и filterIn должны возвращать другие функции, которые и будут в нужном порядке вызываться в query:

var lib = {
    query: query,
    select: select,
    filterIn: filterIn
};

function query(arr, ...fs) {
    console.log('query');

    for (var q=fs.length; q--; ) {
      arr = fs[q](arr)
    }

    return arr;
}

function select(...fields) {
    return function (arr) {
        console.log('select');

        return arr.map(x => {
          var res = {};
          for (var f of fields) res[f] = x[f];
          return res;
        });
    }
}

function filterIn(property, values) {
    return function (arr) {
        console.log('filterIn');

        return arr.filter(x => ~values.indexOf(x[property]));
    }
}

var people = [
    {
        name: 'Андрей',
        gender: 'Мужской',
        email: 'andrey@site.ru',
    },
    {
        name: 'Николай',
        gender: 'Мужской',
        email: 'halo@site.ru',
    }
]

var result = lib.query(
    people,
    lib.select('name', 'gender'),
    lib.filterIn('name', ['Андрей', 'Николай'])
);

console.log(result);
.as-console-wrapper.as-console-wrapper { max-height: 100vh }


text:
Q: Eclipse not starting in Windows 10 (Issues with workspace) So when I start Eclipse, it says that it cannot be started and that I should check my log files in the work space file, any solution on how to fix this?
The eclipse files are stored on my D drive while the workspace is on my C drive if that makes any difference.
If i check the plugin file with workspaceNew there are only 3 files:
org.eclipse.core.resources
org.eclipse.core.runtime
org.eclipse.m2e.logback.configuration

Below is the contents of the most recent log:
!ENTRY org.eclipse.osgi 4 0 2017-10-09 17:08:26.253
!MESSAGE Application error
!STACK 1
java.lang.NoClassDefFoundError: org/w3c/dom/stylesheets/StyleSheet
    at org.eclipse.e4.ui.css.swt.internal.theme.ThemeEngineManager.getCSSSWTEngine(ThemeEngineManager.java:41)
    at org.eclipse.e4.ui.css.swt.internal.theme.ThemeEngineManager.getEngineForDisplay(ThemeEngineManager.java:30)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.createThemeEngine(PartRenderingEngine.java:1428)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.initializeStyling(PartRenderingEngine.java:1281)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:1036)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1032)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:148)
    at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:636)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:579)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:135)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:382)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:236)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.base/java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:648)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:603)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1465)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1438)
Caused by: java.lang.ClassNotFoundException: org.w3c.dom.stylesheets.StyleSheet cannot be found by org.eclipse.e4.ui.css.core_0.10.100.v20140424-2042
    at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:423)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:336)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:328)
    at org.eclipse.osgi.internal.loader.ModuleClassLoader.loadClass(ModuleClassLoader.java:160)
    at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
    ... 26 more

A: Make sure that version of the eclipse and jdk are same as your system i.e. If you are running 32 bit system then make sure eclipse and jdk is also 32 bit
edit eclipse luna requires jdk 7 or up


text:
Q: Compiling without (necessary?) #include Consider the following code:
#include <iostream>

using namespace std;

int main () {

srand(time(0));
double dd [10];
for(int i=0;i!=10; ++i) dd[i]= rand()%5+0;

for(auto i:dd)
cout<<i<<' ';

cout<<endl;

exit(100);

}

Why is it compiling without the #include<ctime> and #include<cstdlib> for the calls to time(0) and exit(100)(which is absolutely useless there, I know)? Are they already included in iostream?

A: The C++ standard, section 17.6.5.2 [res.on.headers], says:

A C++ header may include other C++ headers.

Which means an implementation is free to include other headers when you include one of them. From an implementor's point of view, that's just quite practical, of course.
There are even headers which are guaranteed to include others. For example, <string> implies <initializer_list>.
As for <iostream>, it implies <ios> (which itself implies <iosfwd>), <streambuf>,  <istream> and <ostream>. So there is no guarantee for <ctime> and <cstdlib>, and you should include them explicitly for better portability.
To find out which headers are guaranteed to include others, you can either have a look yourself in the standard or in a draft (see all the synopses starting in section 18), or just go to cppreference.com, for example http://en.cppreference.com/w/cpp/header/iostream for <iostream>. It's quite a reliable online C++ reference.
Or you just explicitly include every header you need. Which may be the best choice in the end.

A: Yes, iostream includes cstdlib (at least in your case; you should not rely on that dependency chain).
Your compiler might have an option to list the dependencies, e.g. for the GNU C compiler, you can use the -M flag to list all includes.


text:
Q: Jquery collapse and expand server side control i am using asp.net 3.5 and c#.
I have a server-side div (runat="server") and , what I want is this that when I click on the link, div1 will collapse. I have to do this in JQuery.
I already achieve the target to use the following example. It collapse and expand the client side div.. now i want to do the same thing to the server-side div control
http://www.dynamicdrive.com/dynamicindex17/animatedcollapse.htm

A: What the problem? The only difference is that you need to use control's ClientID value. In your case if div with jason id has runat="server" attribute you may use: animatedcollapse.addDiv('<%= jason.ClientID %>', 'fade=1,height=80px')

A: By 'do the same on the serverside', do you mean you want state to persist when you click on other elements that cause postback?
I did a blog post on doing this with a Panel control and remembering its state on the server side so if you click on other elements the state persists through postbacks.   It should equally apply to a DIV:
Persisting Collapse state on postback


text:
Q: Complete database reset for MySQL dump? This may seem like a very dumb question but I didn't learn it in any other way and I just want to have some clarification.
I started to use MySQL a while ago and in order to test various scenarios, I back up my databases. I used MySQL dump for that:
Export:

mysqldump -hSERVER -uUSER -pPASSWORD --all-databases > filename.sql

Import:

mysql -hSERVER -uUSER -pPASSWORD < filename.sql

Easy enough and it worked quite well up until now, when I noticed a little problem with this "setup": It does not fully "reset" the databases and tables. If, for example, there is an additional table added AFTER a dump file has been created, that additional table will not disappear if you import the same dump file. It essentially only "corrects" tables already there and recreates any databaes or tables missing, but does not remove any additional tables, which happen to have names that are not in the dump file.
What I want to do is to completely reset all the databases on a server when I import such a dump file. What would be the best solution? Is there a special import function reserved for that purpose or do I have to delete the databases myself first? Or is that a bad idea?

A: You can use the parameter --add-drop-database to add a "drop database" statement to the dump before each "create database" statement.
e.g.

mysqldump -hSERVER -uUSER -pPASSWORD --all-databases --add-drop-database >filename.sql

see here for details.

A: There's nothing magic about the dump and restore processes you describe.  mysqldump writes out SQL statements that describe the current state of the database or databases you are dumping. It has to fetch a list of tables in each database you're dumping, then it has to read the tables one by one and write them out as SQL. On databases of any size, this takes time.
So, if you create a new table while mysqldump is running, it may not pick up that new table. Similarly, if your application software changes contents of tables while mysqldump is running, those changes may or may not show up in the backup.
You can look at the .sql files mysqldump writes out to see what they have picked up.  If you want to be sure that your dumped .sql files are perfect, you need to run mysqldump on a quiet server -- one where nobody is running data definition language.
MySQL hot backup solutions are available. You may need to look into that.

A: The OP may want look into
mysql_install_db

if they want a fresh start with the post-install default
settings before restoring one or more dumped DBs.  For
production servers, another useful script is:
mysql_secure_installation

Also, they may prefer to dump the DB(s) they created separately:
mysqldump -hSERVER -uUSER -pPASSWORD --database foo > foo.sql

to avoid inadvertently changing the internal DBs:
mysql, information_schema, performance_schema.


text:
Q: I have AMD gpu, should I move to Ubuntu? I'm using windows currently but because of programming, aesthetics, financial and other reasons I have decided to move to Ubuntu.
Problem is my device is a laptop with Intel CPU and AMD R7 M360 GPU and I have read online (like here) that AMD graphics are a mess in Ubuntu 16.04.
I'm not very familiar with how Ubuntu work or what some of these technical words used in the link above, Until now I have just simply wrote C++ codes in Ubuntu or any Linux environment.
Should I avoid moving to Ubuntu or is there a solution to this driver issue?
Thanks.

A: First of all, the article linked to is fairly old in Linux terms and AMD regards.
Ubuntu works very well with AMD hardware, but your use should determine which Ubuntu version you need.
Ubuntu 16.04 LTS (Long Term Support) is primarily for you if you are going to use professional software such as CAD, OpenCL and similar software. AMD provides their own closes-source proprietary graphics driver on their website http://support.amd.com/en-us/kb-articles/Pages/AMDGPU-PRO-Driver-for-Linux-Release-Notes.aspx
However, if you don't know what any of this is, you might as well go with 17.04, since it has a newer kernel and therefore better hardware support - again, however, AMD's own closed source driver doesn't support this newer kernel, so you won't be able to install it on Ubuntu 17.04
Instead, you will be using the Open Source radeonsi driver part of a project called MESA. radeonsi is actually developed by AMD developers, and this is the driver you will be getting the best overall experience with.
The Open Source driver radeonsi is the AMD driver with the best gaming support on Linux and also has no screen tearing. This is the recommended driver for most users.
The only downside of the radeonsi driver, is that it is packaged alongside every major Ubuntu release (every six months). Therefore, you will not be getting the latest enhancements right away.
However, to that, there is a solution. If you want the latest drivers automatically, you can add something called a repository. There is a repository that will automatically update your open source radeonsi driver everytime a new update arrives.
You can do that by opening a terminal ctrl+alt+t (after installing Ubuntu), and enter:
sudo add-apt-repository ppa:paulo-miguel-dias/pkppa
sudo add-apt-repository ppa:kisak/kisak-mesa

press yes to add it and then:
sudo apt update && sudo apt upgrade -y

Lastly, reboot your computer and you will have the latest stable graphics driver installed.
There is only one caveat with adding this repository, which might be that you need to remove it before upgrading Ubuntu to let's say Ubuntu 17.10 when that arrives.
You can remove the repository by writing this in the terminal:
sudo apt install ppa-purge

    sudo ppa-purge ppa:paulo-miguel-dias/pkppa

sudo ppa-purge ppa:ppa:kisak/kisak-mesa
sudo apt update && sudo apt upgrade

s
When the new Ubuntu has been installed, simply add the repository again to automatically get the newest updates again. BTW, this repository also works on Ubuntu 16.04 LTS
*radeonsi is also referred to as AMDGPU
** The closed source driver is referred to as AMDGPU-PRO
You can download Ubuntu and try it out on your computer without installing it. You only need a USB Dongle and put a Ubuntu Live-Preview on it.
You can get this here:
https://www.ubuntu.com/download/desktop


text:
Q: Although I have pip installed and import kivy in cmd, I still get an error and the code is not executed from kivy.app import App
from kivy.uix.button import Button

class TestApp(App):
    def build(self):
        return Button(text='Hello World')

TestApp().run()

Traceback:
Traceback (most recent call last):
  File "c:\Users\HYPER\Desktop\training.py\from kivy.app import App.py", line 1, in <module>
    from kivy.app import App
  File "c:\Users\HYPER\Desktop\training.py\kivy.py", line 2, in <module>
    kivy.require('1.9.0')`enter code here`
AttributeError: module 'kivy' has no attribute 'require'

[Done] exited with code=1 in 4.102 seconds


text:
Q: Using sed to write xml tag in Rakefile I have trying to pre-process a xml-like file by using Rakefile, what I am trying to do is adding a group of xml tags.
The following sed is the short version of what I have done
sed -ig '/TARGET_STRING/{N;G;s/$/<key>KEY_NAME<\/key>/g;}' whateverfile.xml

and this piece of code is worked beautifully and successes while using terminal.
And I put them into the Rakefile I made, like this:
desc 'setup pods archs'
task :setup_podsarchs => :setup_submodules do
    puts 'Altering xml...'.cyan
    `sed -ig '/TARGET_STRING/{N;G;s/$/<key>KEY_NAME<\/key>/g;}' whateverfile.xml`
end

After executing rake, it prompt an error and terminate the task
sed: 1: "/TARGET_STRING/{N;G;s/$/ ...": bad flag in substitute command: 'k'

I had searching around for a long time, cannot find any information about escaping the < and > characters in Ruby.

My platform

*

*OS: Mac OS X 10.9

*Ruby: 2.0.0p247

*rake: 0.9.6

*sed: 7

Update
Hi, thank you guys for the extremely fast reply.
and @the Tin Man,
for the comment,
What I am trying to do is pre-process the Xcode project file (.pbxproj), which is structured as a xml,
For simplicity, I just show the example of xml structure here:
<dict>
    <key>Key_ONE</key>
    <string>1</string>
</dict>

What I am trying to do is finding the KEY_ONE and adding another key after that:
<dict>
    <key>Key_ONE</key>
    <string>1</string>
    <key>Key_TWO</key>
    <string>2</string>
</dict>

A: Using regular expressions for anything beyond the most trivial and controlled parsing leads to madness. Use Nokogiri, an excellent Ruby XML/HTML parser. For instance:
require 'nokogiri'

xml = <<EOT
<xml>
  <foo>foo</foo>
  <bar>bar</bar>
</xml>
EOT

doc = Nokogiri::XML(xml)

doc.at('foo').content = 'bar'
doc.at('bar')['class'] = 'cyan'

puts doc.to_xml

Which outputs:
<?xml version="1.0"?>
<xml>
  <foo>bar</foo>
  <bar class="cyan">bar</bar>
</xml>

Notice the content inside the <foo> tag changed, along with <bar> gaining an attribute.
What's important about using a parser is that the content can change, tag parameters can change, their order can move around inside the tag, tags can be split across multiple lines, and a parser will not care, whereas a regular expression will spout flames and stop working.

A: parser is better solution.
for sed point  of view try with
`sed -ig '/TARGET_STRING/{
    N
    s/$/\
<key>KEY_NAME<\/key>/
    }' whateverfile.xml`

G is normaly not needed because nothing is loaded into
g is also not needed, there is onle 1 replacement possible


text: Q: What is the difference between Hamming Code and Two-Dimentional Parity? Hamming Code is able to correct one bit error(but detect multiple error),and Two-Dimentional Parity can also make this. I think the latter is easier, but the former is used in most conditions. These two is similar. What is the difference between Hamming Code and Two-Dimentional Parity?


text:
Q: R Generate non repeating pairs in data frame, avoiding same group members So the purpose is to compare each ID with each other ID by taking distances. Also some IDs may be related by belonging to the same group, this means it is not necessary to compare them if they are related.
Consider the following dataframe Df
ID AN     AW      Group
a  white  green   1
b  black  yellow  1
c  purple gray    2
d  white  gray    2

The following code helps in achieving this result (from question: R Generate non repeating pairs in dataframe):
ids <- combn(unique(df$ID), 2)
data.frame(df[match(ids[1,], df$ID), ], df[match(ids[2,], df$ID), ])

#ID   AN     AW    ID2   AN2    AW2
a   white  green   b   black  yellow
a   white  green   c   purple gray
a   white  green   d   white  gray
b   black  yellow  c   purple gray
b   black  yellow  d   white  gray
c   purple gray    d   white  gray

I want to know if it is possible to not compute certain computations in order to have this answer:
#ID   AN     AW    Group   ID2   AN2    AW2   Group2
a   white  green     1      c   purple gray    2
a   white  green     1      d   white  gray    2
b   black  yellow    1      c   purple gray    2
b   black  yellow    1      d   white  gray    2

Meaning I can avoid this computations:
#ID   AN     AW    Group   ID2   AN2    AW2    Group2
a   white  green     1      b   black  yellow    1
c   purple gray      2      d   white  gray      2

I am able to subset if I compare groups, but that means more computing time since the data frame is big, and the combinations follow n*(n-1)/2
Is this possible? Or do I have to make all combinations and then subset the comparisons between the same group out?

A: Here is a fairly lengthy base R solution that assumes that there may be more than two groups.
# create test data.frame
df <- data.frame(ID=letters[1:4], AN=c("white", "black", "purple", "white"),
                 AW=c("green", "yellow", "gray", "gray"),
                 Group=rep(c(1,2),each=2), stringsAsFactors=FALSE)

# split data.frame by group, subset df to needed variables
dfList <- split(df[, c("ID", "Group")], df$Group)
# use combn to get all group-pair combinations
groupPairs <- combn(unique(df$Group), 2)

Next, we loop through (via sapply) all pairwise combinations of groups. For each combination, we build a data.frame that is the pairwise combination of IDs between each group via expand.grid. The IDs are extracted (with the [[]] operator) from the named list, dfList using their names from groupPairs[1,i] and groupPairs[2,i].
# get a list of all ID combinations by group combination
myComparisonList <- sapply(1:ncol(groupPairs), function(i) {
                           expand.grid(dfList[[groupPairs[1,i]]]$ID,
                                       dfList[[groupPairs[2,i]]]$ID,
                                       stringsAsFactors=F)
                           })
# extract list of combinations to matrix
idsMat <- sapply(myComparisonList, rbind)

# bind comparison pairs together by column
dfDone <- cbind(df[match(idsMat[,1], df$ID), ], df[match(idsMat[,2], df$ID), ])
# differentiate names
names(dfDone) <- paste0(names(dfDone), rep(c(".1", ".2"),
                        each=length(names(df))))

A: if you can use sql to do this then where g is for the group.
sqldf("select * from f t1 inner join f t2 on t1.g!=t2.g")


text:
Q: Show Youtube like preview on the listImageview in android recyclerview Currently what I am doing:

*

*I am having a list of items that I show in a recycler view

*Each item has an image and a title (Basically its the list of videos)

*On click of each item, I show video in a detail screen

What I want to achieve:

*

*How to show a preview in Imageview as youtube does on focusing on one
of an item of listview

*Is there any existing library that handles this


text:
Q: Can I make a #define and use it in a throw? Can I make something like this?
#define N_VALID "is not a valid ID"
...
throw N_valid;
...
catch(char *message){
fprintf(stderr,"%s",message);}

A: Yes, except that you are throwing a const char *, not a char *: https://ideone.com/UsnitG
#include <iostream>
using std::cout; using std::endl;

#define N_VALID "is not a valid ID"

void function_throws()
{
  throw N_VALID;
}

int main()
{
    try
    {
        function_throws();
    }
    catch(const char *message) // <= Note the const here!
    {
        cout << message << endl;
    }
}

However, Joel is correct that you should avoid doing this.  If you really want to use a macro here, try using it as an argument to a std::exception object: https://ideone.com/Dsx1RF
void function_throws()
{
  throw invalid_argument(N_VALID);
}

int main()
{
    try
    {
        function_throws();
    }
    catch(const invalid_argument& ex)
    {
        cout << "invalid_argument: " << ex.what() << endl;
    }
}

A: Yes.
#define N_VALID "is not a valid ID"

throw N_VALID;
throw "is not a valid ID";

The bottom two lines above are literally identical in the eyes of the compiler, once pre-processing has completed.

A: This is legal but immoral.  You should ALWAYS throw an object so that your clients can handle your errors individually, rather than having a giant if statement in one catch.

A: The #define directive works by replacing a tag with another tag in your code before the application is compiled. Thus, if you can do this:
throw "is not a valid ID";

you can do this:
throw N_VALID;

A: It should work.  Remember, the pre-processsor runs before the compiler and will replace the N_VALID with "is not a valid ID"


text:
Q: ElasticSearch Index a Document fails on existing index I am using ES php library. Here is what i have tried...
$params = [
    'index' => 'tasks',
    'body' => [
        'settings' => [
            'number_of_shards' => 3,
            'number_of_replicas' => 2
        ],
        'mappings' => [
            'all' => [
                '_source' => [
                    'enabled' => true
                ],
                'properties' => [
                    'task' => [
                        'type' => 'string',
                        'analyzer' => 'standard'
                    ],
                    'to' => [
                        'type' => 'string',
                        'analyzer' => 'standard'
                    ],
                    'category' => [
                        'type' => 'integer',
                        'analyzer' => 'keyword'
                    ]
                ]
            ]
        ]
    ]
];

// Create the index with mappings and settings now
$response = $client->indices()->create($params);

It returns success.
Now when i try to index a document...
$params = [
    'index' => 'tasks',
    'type' => 'all',
    'id' => 'some_id',
    'body' => [ 'task' => 'some test', 'to' => 'name', 'category' => 1]
];

$response = $client->index($params);

This throws error and does not work, however it works If i try this without creating index and mapping first.
Please suggest. Thanks

A: It's wrong to define analyzer in a field of type 'integer'.
Trying to create this mapping through Elasticsearch-PHP gives me a bad request:
... "reason":"Mapping definition for [category] has unsupported parameters:  [analyzer : keyword]"}},"status":400}

Trying to create this mapping directly via PUT to ES gives me same error
I'm using ES version 2.2.0 and Elasticsearch-PHP 2.0


text:
Q: Inconsistent outcome when trying to fetch all items from a paginated url I am having the issue of fetching all forms currently hosted in hubspot.
I tried with a simple for loop where I made one request at the time, and fetched one form at a time, which worked, but was very slow.
I then thought it might work better if I created a seperate task for each request, and then made the task create each request, and store them in one common list.
Problem is that I expect the list to have 2000 items, but I never seem to get that, it seem pretty inconsistent the number of items I get?
But how come?
This is how I have setup my for fetching scheme.
private static async Task<IEnumerable<HubspotModel>> GetForms(
    string hubspotPath, int pageSize)
{
    int totalResults;
    int offset = 0;
    List<HubspotModel> output = new();
    List<Task> tasks = new();
    using var client = new HttpClient();
    {
        System.Net.Http.Headers.HttpResponseHeaders requestHeader = client
            .GetAsync($"https://api.hubapi.com{hubspotPath}?" +
                $"hapikey={HubspotConfiguration.ApiKey}&limit={1}&offset={0}")
            .Result.Headers;
        totalResults = int.Parse(requestHeader.GetValues("x-total-count").First());
        do
        {
            tasks.Add(Task.Run(() =>
            {
                int scopedOffset = offset;
                IEnumerable<HubspotModel> forms = GetFormsFromHubspot(hubspotPath,
                    pageSize, offset, client);
                output.AddRange(forms);

            }).ContinueWith(requestReponse =>
            {
                if (requestReponse.IsFaulted)
                {
                    Console.WriteLine("it failed");
                }
            }));
            offset += pageSize;
        }
        while (totalResults > offset);

        await Task.WhenAll(tasks);
    }

    return output;
}

private static IEnumerable<HubspotModel> GetFormsFromHubspot(string hubspotPath,
    int pageSize, int offset, HttpClient client)
{
    HttpResponseMessage request = client
        .GetAsync($"https://api.hubapi.com{hubspotPath}?" +
            $"hapikey={HubspotConfiguration.ApiKey}&limit={pageSize}&offset={offset}")
        .Result;
    request.EnsureSuccessStatusCode();
    string content = request.Content.ReadAsStringAsync().Result;
    IEnumerable<Dictionary<string, object>> jsonResponse = JsonSerializer
        .Deserialize<IEnumerable<Dictionary<string, object>>>(content,
        new JsonSerializerOptions() { });
    var guid = Guid.Parse(jsonResponse.First()["guid"].ToString());
    var forms = jsonResponse.Select(x => new HubspotModel()
    {
        id = Guid.Parse(x["guid"].ToString()),
        FormName = x["name"].ToString(),
        Form = x
    });
    return forms;
}

A: First of all, I'd suggest to make GetFormsFromHotspot an async as well and use await client.GetAsync( ...) and await request.Content.ReadAsStringAsync() instead of client.GetAsync(...).Result and ReadAsStringAsync().Result respectively, because using .Result will block the current thread and thus, you will throw away the advantages of async Tasks.
But the main cause of the problem should be the following
GetFormsFromHubspot(hubspotPath, pageSize, offset, client);

Here you are calling the GetFormsFromHubspot with an offset parameter from an outer scope (and that value keeps changing), thus it will not use the value it had when you created that task but it uses the value it actually has, when that particular part of the code is really executed. So the value that is used as an offset is quite random. You already tried to create a
int scopedOffset = offset;

but you don't use it. And also you create it at the wrong position. Create that scopedOffset outside  of the task, but inside  the loop's body. So it will be created at the creationtime of the task. And because it's inside the loop's body, a new value will be created for each task.
The following should do the trick (after you refactor GetFormsFromHubspot to be async.
do {
  int scopedOffset = offset
  tasks.Add(Task.Run(async () => {
      IEnumerable<HubspotModel> forms = await GetFormsFromHubspot(hubspotPath, pageSize, scopedOffset, client);
      output.AddRange(forms);
    })
    .ContinueWith(...);
  );
  offset += pageSize;
} while (totalResults > offset);

A: The main problem with your code is that the List<T> is not thread-safe. When multiple threads are Adding to a list concurrently without synchronization, its behavior becomes undefined (throws exceptions, becomes corrupted etc). There are many ways to solve this problem:

*

*Synchronize the access to the list with the lock statement: lock (output) output.AddRange(forms);.

*Use a concurrent collection instead of the List<T>, for example a ConcurrentQueue<T>.

*Avoid collecting manually the output altogether. Instead of storing your tasks in a List<Task>, you can store them in a List<Task<HubspotModel[]>>, meaning that each task will be a generic Task<TResult>, with the TResult being an array of HubspotModel instances. Finally you will get all the output at once, when you await the Task.WhenAll.

Below is an implementation of the third idea. Notice that I have avoided creating a HttpClient instance, because the recommendation is to instantiated this class only once, and reuse it throughout the life of the application.
private static async Task<HubspotModel[]> GetFormsAsync(HttpClient client,
    string hubspotPath, int pageSize)
{
    string url = $"https://api.hubapi.com{hubspotPath}?hapikey=" +
        $"{HubspotConfiguration.ApiKey}&limit={1}&offset={0}";
    HttpResponseMessage response = await client.GetAsync(url)
        .ConfigureAwait(false);
    response.EnsureSuccessStatusCode();
    int totalCount = Int32.Parse(response.Headers
        .GetValues("x-total-count").First());

    List<int> offsets = new();
    for (int offset = 0; offset < totalCount; offset += pageSize)
        offsets.Add(offset);

    Task<HubspotModel[]>[] tasks = offsets.Select(offset => Task.Run(async () =>
    {
        HubspotModel[] forms = await GetFormsAsync(client,
            hubspotPath, pageSize, offset).ConfigureAwait(false);
        return forms;
    })).ToArray();

    HubspotModel[][] results = await Task.WhenAll(tasks).ConfigureAwait(false);

    return results.SelectMany(x => x).ToArray();
}

private async static Task<HubspotModel[]> GetFormsAsync(HttpClient client,
    string hubspotPath, int pageSize, int offset)
{
    string url = $"https://api.hubapi.com{hubspotPath}?hapikey=" +
        $"{HubspotConfiguration.ApiKey}&limit={pageSize}&offset={offset}";
    HttpResponseMessage response = await client.GetAsync(url)
        .ConfigureAwait(false);
    response.EnsureSuccessStatusCode();

    string content = await response.Content.ReadAsStringAsync()
        .ConfigureAwait(false);
    IEnumerable<Dictionary<string, object>> jsonResponse = JsonSerializer
        .Deserialize<IEnumerable<Dictionary<string, object>>>(content,
        new JsonSerializerOptions() { });

    Guid guid = Guid.Parse(jsonResponse.First()["guid"].ToString());
    HubspotModel[] forms = jsonResponse.Select(x => new HubspotModel()
    {
        Id = Guid.Parse(x["guid"].ToString()),
        FormName = x["name"].ToString(),
        Form = x
    }).ToArray();
    return forms;
}

One more improvement that you could consider doing is to switch from the Task.WhenAll to the new (.NET 6) API Parallel.ForEachAsync. The advantage is that you'll get control over the degree of parallelism, and so you'll be able to reduce the parallelization in case the remote server can't keep up with the pressure. Unfortunatelly the Parallel.ForEachAsync method does not return the results like the Task.WhenAll, so you'll be back to your original problem. You can find a solution about this here: ForEachAsync with Result.


text:
Q: Calculating previous Sunday Javascript Im trying to calculated the date for the previous sunday via the .setdate .getdate - 7 days method but it seem to work perfectly for calculating yesturday last week but not for sunday. Any ideas?

var today = new Date();
var yesterday = new Date();
var LWyesterday = new Date();
var LWSunday = new Date();

// Set yesturday date
yesterday.setDate(today.getDate() - 1);
console.log('yesterday = ' + yesterday);

// Calculated and set Sunday
var Sunday = new Date(today.getTime() - today.getDay() * 24 * 3600 * 1000);
console.log('recent sunday = ' + Sunday);

// Set yesturday last week
LWyesterday.setDate(yesterday.getDate() - 7);
console.log('last week yesterday = ' + LWyesterday);

// Set sunday last week
LWSunday.setDate(Sunday.getDate() - 7);
console.log('last week sunday = ' + LWSunday);
// returns Tue May 23 2017 14:08:24 GMT+0100 (GMT Summer Time)
// Should have been  Tue >**April**< 23 2017 14:08:24 GMT+0100 (GMT Summer Time)

https://jsfiddle.net/afmc9yon/

A: You don't have to set the month, since the setDate function takes care of automatically:

https://www.w3schools.com/jsref/jsref_setdate.asp
Date.setDate(day) - day an integer representing the day of a month.
Expected values are 1-31, but other values are allowed:

*

*0 will result in the last day of the previous month

*-1 will result in the day before the last day of the previous month

  If the month has 31 days:

*

*32 will result in the first day of the next month

  If the month has 30 days:

*

*32 will result in the second day of the next month

What you need is:

*

*
getDay() gives you back the day of the week (where Sunday is 0, Monday is 1, ... Saturday is 6)

*

*you have to convert it to Monay is 1, ... Saturday is 6, Sunday is 7

*you can do the conversion by today.getDay() || 7 (borrowing it from Damian)

*otherwise when today is Sunday the code will give you this Sunday as last week's Sunday

*
you have to decrease the day of the month (getDate()) by the day of the week (getDay()||7)

So in your case use: LWSunday.setDate(today.getDate() - (today.getDay()||7));
Similarly if you want to get current week's Sunday, then you have to add 7 days: Sunday.setDate(today.getDate() - (today.getDay()||7) + 7);

var today = new Date();
var Sunday = new Date();
var LWSunday = new Date();

// Calculated and set Sunday
Sunday.setDate(today.getDate() - (today.getDay()||7) + 7);
console.log('recent sunday = ' + Sunday);

// Set sunday last week
LWSunday.setDate(today.getDate() - (today.getDay()||7));
console.log('last week sunday = ' + LWSunday);

You can also make a function out of it:

if (!Date.prototype.getSunday)
  Date.prototype.getSunday = function() {
    var dat = new Date(this.valueOf());
    dat.setDate(dat.getDate() - (dat.getDay()||7) + 7);
    return dat;
  }

if (!Date.prototype.getLastSunday)
  Date.prototype.getLastSunday = function() {
    var dat = new Date(this.valueOf());
    dat.setDate(dat.getDate() - (dat.getDay()||7) );
    return dat;
  }

var date = new Date('2017-01-02');
console.log(date);
console.log('this Sunday',date.getSunday());
console.log('last sunday',date.getLastSunday());

var date = new Date('2017-01-01');
console.log(date);
console.log('this Sunday',date.getSunday());
console.log('last sunday',date.getLastSunday());

date = new Date('2017-05-02');
console.log(date);
console.log('this Sunday',date.getSunday());
console.log('last sunday',date.getLastSunday());

date = new Date('2017-05-07');
console.log(date);
console.log('this Sunday',date.getSunday());
console.log('last sunday',date.getLastSunday());

A: var now = new Date();
var daysBack = -7 + (7 - now.getDay());

console.log(
    new Date(now.getTime()  + ((daysBack || -7)*1000*60*60*24))
)

We use daysBack variable so that we can get previous Sunday regardless what day of week is today. As getDay() returns 0 for Sunday, 1 for Monday etc., we use a formula as the above. For example, if today is Saturday and getDay() gives us 6, we have here -7 + (7 - 6), then -7 + 1 and we get -6 what means closest Sunday was 6 days ago.
daysBack || -7 is used to get previous Sunday in the case today is Sunday too.

A: I just noticed your real problem:
Sunday might be in the last month.
Therefore the Sunday.getDate()-7 is positive, not changing the LWSunday Month property...
So you also need to change the month ( in some cases) :
LWSunday.setDate(Sunday.getDate() - 7);
if(Sunday.getMonth()!==today.getMonth()){
   LWSunday.setMonth(LWSunday.getMonth()-1);
}
//same for year...
   console.log('last week sunday = ' + LWSunday);

OR you take the whole date:
var LWSunday = new Date(Sunday.getTime() - 7*24*3600*1000);

http://jsbin.com/yevutabuxe/edit?console

A: SetDate() finds the day of month for the time value input.  But you're trying to find the whole date value by the looks.  If I understand what you're trying to do, what you really want is:
    LWSunday.setTime(Sunday.getTime() - 7*24*60*60*1000);


text:
Q: Complex heatmap barplot ordering I have generated a fairly simple oncoprint using Complexheatmaps. Is anyone able to tell me the way the default top annotation barplot is ordered. My rows are ordered specifically to group shared genes but this is not followed in the stacked barplot. I was hoping the barplot ordering would follow the row orders so that these would match. I can't seem to find an answer to this in the vignette. Do I have to write a separate heatmap annotation to solve this (being a novice I am afraid to admit this may take me a little while!!)
Many thanks,
. Oncoprint image


text:
Q: How to perform different logic based on checkbox being true or false? I have two sections(primary and secondary) in a form with several textboxes which display information. On the secondary section I've added a checkbox (which when checked) I want to copy the information from the fields on the primary section into the fields on the secondary side. If its unchecked I want it to leave the field as blank.
Here is some sample code to help see what I am trying to do:
The CheckChanged event calls four different methods (each method contains logic for a specific checkbox):
    private void CheckBoxCheckedChanged(
    {
        Method1();
        Method2();
        Method3();
        Method4();
    }

When Method4 is called I'd like to process the logic mentioned above if its checked, and leave blank if its not.
    private void Method4()
    {
        if (checkBox4.Checked = true)
        {
            secondaryTextbox.Text = primaryTextbox.Text;
        }
        else if (checkBox4.Checked = false)
        {
            secondaryTextbox.Text = "";
        }

    }

The issue I'm having is that when I do this once the checkbox is checked, I can no longer 'uncheck' to change the field back to being blank.
What am I doing wrong, or is there a better way to go about this?
I apologize ahead of time if I posted this wrong, this is my first time using SO.

A: The code you wrote makes an assignment (=) inside the if statement's expression, but this is not what you mean. You should use == if you want to make a comparison. Or even better, just do this instead:
    if (checkBox4.Checked)
    {
        secondaryTextbox.Text = primaryTextbox.Text;
    }
    else
    {
        secondaryTextbox.Text = "";
    }

As Paolo pointed out the code you tried gives a compiler warning. If you try to never write code that produces  warnings you can catch simple errors like this more quickly. There's even an option to treat warnings as errors which you can use.

A: You need
if (checkBox4.Checked == true)

to check if true, the way you were doing it was always assigning it the value "true"

A: You are doing assignment when you mean to be testing
use this
if (checkBox4.Checked == false)

or better this
if (false == checkBox4.Checked)

or even better this
if ( ! checkBox4.Checked)

instead of this
if (checkBox4.Checked = false)

A: You have a very small problem in your code:
you are using = instead of ==
also it is better to define an array of check-box and text-box instead of func1,func2,func3,func4

A: You are using a single "="  to test of the checkbox is checked.
THis has the effect of setting the checkbox state.
Use "==", as in
if (checkBox4.Checked == true)

or in fact, much better:
if (checkBox4.Checked)


text:
Q: C# display value in textboxes when checkboxes are checked in DataGridView and clear when unchecked I have a checkbox column in datagridview, where if I check the checkbox, the cell values will be parse in to textboxes & combobox and unchecked will clear the all the textboxes & combobox.
I have achieved the above description, the problem is when i checked it from bottom to top order, the textboxes value won't change. It will remain the same to the first checked.
As my snippet below, textbox should display 'AZI' since i checked it after 'FRAN', but it still show 'FRAN'. But if the checked order is 'AZI' then 'FRAN', it will behave correctly.

I have referred this post How to clear textbox when all checkboxes are unchecked in DataGridView C#
And below is my codes so far,
private void datagridview1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            bool unSel = true;
            foreach (DataGridViewRow row in datagridview1.Rows)
            {
                DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells["ckbox"];
                bool isSel = (bool)chk.EditedFormattedValue;
                object cell = row.Cells["ckbox"].EditedFormattedValue;
                unSel &= !Convert.ToBoolean(cell);

                if (isSel)
                {
                    combobox1.Text = row.Cells["combobox1"].Value.ToString();
                    textbox1.Text = row.Cells["textbox1"].Value.ToString();
                    textbox2.Text = row.Cells["textbox2"].Value.ToString();
                    textbox3.Text = row.Cells["textbox3"].Value.ToString();
                }
            }
            if (unSel)
            {
                textbox1.Clear();
                cbDoctorList.Text = "";
                textbox2.Clear();
                textbox3.Clear();
            }
        }

Appreciate your helps on this!

A: When you toggle a checkbox in a DataGridViewCheckBoxCell it normally puts the CurrentCell into edit mode. The new value isn't committed to the cell until the DataGridView leaves edit mode one way or another.
You could try ending the edit immediately when a checkbox toggles. See if it helps to add this code first in your click handler method.
void datagridview1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (dataGridView.CurrentCell is DataGridViewCheckBoxCell)
    {
        dataGridView.EndEdit();
    }
    .
    .
    .
}

I tested this answer using your test case where the checked order is "FRAN" then "AZI" and it works as expected with the minimal sample shown below.

public partial class MainForm : Form
{
    public MainForm() => InitializeComponent();

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        dataGridView.AllowUserToAddRows= false;
        dataGridView.DataSource = Items;
        Items.Add(new Item { Name = "AZI" });
        Items.Add(new Item { Name = "FRAN" });
        dataGridView.Columns[nameof(Item.Selected)].AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader;
        dataGridView.Columns[nameof(Item.Name)].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

        dataGridView.CellContentClick += onCellContentClick;
    }

    private void onCellContentClick(object? sender, DataGridViewCellEventArgs e)
    {
        if (dataGridView.CurrentCell is DataGridViewCheckBoxCell)
        {
            dataGridView.EndEdit();

            Item item = Items[e.RowIndex];
            textBoxLast.Text = item.Selected ? item.Name : string.Empty;
            textBoxAll.Text =
                string.Join(
                    ",",
                    Items.Where(_=>_.Selected).Select(_ => _.Name));
        }
    }
    BindingList<Item> Items = new BindingList<Item>();
}
class Item
{
    public bool Selected { get; set; }
    public string Name { get; set; } = string.Empty;
}


text:
Q: Finding date before given number of months from a given date I have a date say for e.g. current date which is 19/04/2013
And I have number of months given say for e.g. 10
I want to find out the date falling before 10 months from 19/04/2013.
How to achieve it in Java?
For example, if I want to find out date before a week, I can achieve as below:
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.DAY_OF_YEAR, -7);
Date newDate = calendar.getTime();

But how to find the same for months ?

A: Well, you could do something similar to your example:
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.MONTH, -10);
Date newDate = calendar.getTime();

It'll set newDate to a date 10 months before myDate.

A: Using jodatime this is so much easier and verbose:
 LocalDate date = LocalDate.parse("19/04/2013", DateTimeFormat.forPattern("dd/MM/yyyy"));
 LocalDate result = date.minus(Months.TEN);
 System.out.println(result.toString("dd/MM/yyyy"));


text:
Q: Parsing a csv file to populate database Given I have a csv file such as this
str_name,int_points,int_bonus
joe,2,5
Moe,10,15
Carlos,25,60

I can have csv file with x number of columns and y number of rows so i am trying to develop a generic method to parse it and populate data in to dynamodb table.
In order to populate the dynamodb table i would do something like this
String line = "";
    String cvsSplitBy = ",";

    try (BufferedReader br = new BufferedReader(
                                new InputStreamReader(objectData, "UTF-8"));

        while ((line = br.readLine()) != null) {

            // use comma as separator
            String[] elements = line.split(cvsSplitBy);

            try {
                table.putItem(new Item()
                    .withPrimaryKey("name", elements[0])
                    .withInt("points", elements[1])
                    .withInt("bonus", elements[2])
                    .....);

                System.out.println("PutItem succeeded: " + elements[0]);

            } catch (Exception e) {
                System.err.println("Unable to add user: " + elements);
                System.err.println(e.getMessage());
                break;
            }

        }

    } catch (IOException e) {
        e.printStackTrace();
    }

However i would not always know wether i am inserting a int or a string, it is depenedent on the csv file so i was kinda lost on how to create a generic function which would read the first line of my csv file and take advantage of prefix which indicates if the particular column is a int or a string.

A: Just store labels (first row) and then while iterating over row values, decide based on label what method to call. If you are not against bringing some external dependencies I advise you to use some external csv reader , e.g.
SuperCsv
Using this library you can for example read each row as a Map(label->val) then iterate over entries and based on labels prefix update your db with correct method. Or just read header and then do the same reading each row as a list.
Example :
This is of course very crude and I would probably refactor it somehow (e.g. have a list of processors for each column instead of ugly switch)
but it shows you the idea
        List<String> labels = new ArrayList<>();//store first row here
        List<String> elements = new ArrayList<>();//currently processed line here
        Item item = new Item();
        for (int i = 0; i < elements.size(); i++) {
            String label = labels.get(i);
            switch (getTypePrefix(label)){
                case "int":
                    item = item.withInt(getName(label),elements.get(i));
                    break;
                case "str":
                    item = item.withString(getName(label),elements.get(i));
                    break;
                default:
                    //sth
                    break;
            }
        }
        table.putItem(item);

A: OK, I can't post this as a comment so I wrote  a simple example. Note that I'm not familiar with that Amazon API you're using but you should get the idea how I'd go about it (I've basically rewritten your code)
        String line = "";
        String cvsSplitBy = ",";

        try (BufferedReader br = new BufferedReader(
                            new InputStreamReader(objectData, "UTF-8"));

     String[]  colNames = br.readLine().split(cvsSplitBy);      //first line just to get the column names
     while ((line = br.readLine()) != null) {
        String currColumnName = colNames.get(i);
        // use comma as separator
        String[] elements = line.split(cvsSplitBy);
        boolean isInt ;
        for (int i = 0; i < elements.length;i++){

        try {
            try{
            int iVal = new Integer(elements[i]);
            isInt = true;
            }catch(NumberFormatException e){
            //process exception
            isInt = false;
            }
            if(isInt){
            table.putItem.(new Item().withInt(currColumnName,iVal));
            }else{
            table.putItem.(new Item().withString(currColumnName),elements[i])); //don't even know whether there is a withString method
            }

            System.out.println("PutItem succeeded: " + elements[i]);

        } catch (Exception e) {
            System.err.println("Unable to add user: " + elements);
            System.err.println(e.getMessage());
            break;
        }
        }

    }

} catch (IOException e) {
    e.printStackTrace();
}

This example assumes that your first row contains the column names as stored in the DB. You don't have to write anywhere whether they an int or a String because there is a check in the program (granted this is not the most efficient way to do this and you may write something better, perhaps what Molok has suggested)


text:
Q: could not resolve module This is a generic Eclipse RCP application error and difficult to find root cause through searching.
Could not resolve module: pica.test.visit.rcp.todo [101]
  Unresolved requirement: Require-Bundle: org.eclipse.eavp.viz; bundle-version="0.1.1"
I'm following this tutorial with success:
http://www.vogella.com/tutorials/EclipseRCP/article.html#introduction-to-eclipse-rcp-applications
Running Eclipse ICE.
https://www.eclipse.org/ice/
ICE has the VisIT plugins installed for visualization calls under org.eclipse.eavp plugin
At 13.4.1. Add the plug-in dependencies: I add the org.eclipse.eavp.viz and org.eclipse.eavp.viz.service which causes above error.
What is the proper way to add such dependencies?

A: As updated by OP in an edit to the question:

At Step 13.4.1, do not add your plug-in dependencies. Instead create a target definition with the path to your plugin.
Right click your project > New > Other > Plug-in Development > Target Definition > Add > Path to Plugin > Save > Run
No errors, UI is shown.


text:
Q: If $ a(12a + 5b +2c) > 0 $ , then prove that the real roots of equation $ ax^2+ bx +c =0$ are less than 2 I know that to prove both roots less than 2 ,i have to prove $ 4a+ 2b +c > 0$ and $ -b/2a < 2 $ . Here i have no idea how to proceed.

A: The original statement is not true. Take $\mathbb p(x)=2x^2-5x+1$. Clearly $a(12a+5b+2c)=2>0$ but one of the roots ($\approx 2.281$) is greater than $2$.
The following proves the converse:
Note that if both roots are less than $2$, then:
$(1)$ Both roots must be on the same side of $2$ on the x- axis.
$(2)$ $2$ must be greater than the mid-point of the two roots.
Both the above conditions ensure that both roots are less than $2$. Draw possible graphs of $\mathbb p(x)=ax^2+bx+c$ to get a feel of this.
$(1)$ is ensured by $a\times \mathbb p(2)>0$.
$(2)$ is ensured by $2 > \dfrac 12\left (\dfrac{-b+ \sqrt{b^2-4ac}}{2a}+\dfrac{-b- \sqrt{b^2-4ac}}{2a}\right )$.
We therefore get $$a(4a+2b+c)>0\iff a(8a+4b+2c)>0$$ and the second condition gives us $$4>-\dfrac ba\iff 4a^2>-ab\iff a(4a+b)>0$$ Adding the two conditions obtained, we get $$a(12a+5b+2c)>0$$