Programs & Examples On #Gcov

gcov is a code coverage tool for GCC

Increase JVM max heap size for Eclipse

--launcher.XXMaxPermSize

256m

Try to bump that value up!

java.lang.OutOfMemoryError: GC overhead limit exceeded

The parallel collector will throw an OutOfMemoryError if too much time is being spent in garbage collection. In particular, if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.

CFLAGS, CCFLAGS, CXXFLAGS - what exactly do these variables control?

As you noticed, these are Makefile {macros or variables}, not compiler options. They implement a set of conventions. (Macros is an old name for them, still used by some. GNU make doc calls them variables.)

The only reason that the names matter is the default make rules, visible via make -p, which use some of them.

If you write all your own rules, you get to pick all your own macro names.

In a vanilla gnu make, there's no such thing as CCFLAGS. There are CFLAGS, CPPFLAGS, and CXXFLAGS. CFLAGS for the C compiler, CXXFLAGS for C++, and CPPFLAGS for both.

Why is CPPFLAGS in both? Conventionally, it's the home of preprocessor flags (-D, -U) and both c and c++ use them. Now, the assumption that everyone wants the same define environment for c and c++ is perhaps questionable, but traditional.


P.S. As noted by James Moore, some projects use CPPFLAGS for flags to the C++ compiler, not flags to the C preprocessor. The Android NDK, for one huge example.

Rounding numbers to 2 digits after comma

This is not really CPU friendly, but :

Math.round(number*100)/100

works as expected.

What is the best way to compare floats for almost-equality in Python?

For some of the cases where you can affect the source number representation, you can represent them as fractions instead of floats, using integer numerator and denominator. That way you can have exact comparisons.

See Fraction from fractions module for details.

How to call execl() in C with the proper arguments?

If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:

system("The same thing you type into console");

Is there a way to compile node.js source files?

You can use the Closure compiler to compile your javascript.

You can also use CoffeeScript to compile your coffeescript to javascript.

What do you want to achieve with compiling?

The task of compiling arbitrary non-blocking JavaScript down to say, C sounds very daunting.

There really isn't that much speed to be gained by compiling to C or ASM. If you want speed gain offload computation to a C program through a sub process.

member names cannot be the same as their enclosing type C#

Constructors don't return a type , just remove the return type which is void in your case. It would run fine then.

How To Get The Current Year Using Vba

Year(Date)

Year(): Returns the year portion of the date argument.
Date: Current date only.

Explanation of both of these functions from here.

How can I convert a string with dot and comma into a float in Python

s =  "123,456.908"
print float(s.replace(',', ''))

What is the difference between 'classic' and 'integrated' pipeline mode in IIS7?

In classic mode IIS works h ISAPI extensions and ISAPI filters directly. And uses two pipe lines , one for native code and other for managed code. You can simply say that in Classic mode IIS 7.x works just as IIS 6 and you dont get extra benefits out of IIS 7.x features.

In integrated mode IIS and ASP.Net are tightly coupled rather then depending on just two DLLs on Asp.net as in case of classic mode.

jQuery: click function exclude children.

To do this, stop the click on the child using .stopPropagation:

$(".example").click(function(){
  $(this).fadeOut("fast");
}).children().click(function(e) {
  return false;
});

This will stop the child clicks from bubbling up past their level so the parent won't receive the click.

.not() is used a bit differently, it filters elements out of your selector, for example:

<div class="bob" id="myID"></div>
<div class="bob"></div>

$(".bob").not("#myID"); //removes the element with myID

For clicking, your problem is that the click on a child bubbles up to the parent, not that you've inadvertently attached a click handler to the child.

How can I specify the schema to run an sql file against in the Postgresql command line

The PGOPTIONS environment variable may be used to achieve this in a flexible way.

In an Unix shell:

PGOPTIONS="--search_path=my_schema_01" psql -d myDataBase -a -f myInsertFile.sql

If there are several invocations in the script or sub-shells that need the same options, it's simpler to set PGOPTIONS only once and export it.

PGOPTIONS="--search_path=my_schema_01"
export PGOPTIONS

psql -d somebase
psql -d someotherbase
...

or invoke the top-level shell script with PGOPTIONS set from the outside

PGOPTIONS="--search_path=my_schema_01"  ./my-upgrade-script.sh

In Windows CMD environment, set PGOPTIONS=value should work the same.

OSError - Errno 13 Permission denied

Probably you are facing problem when a download request is made by the maybe_download function call in base.py file.

There is a conflict in the permissions of the temporary files and I myself couldn't work out a way to change the permissions, but was able to work around the problem.

Do the following...

  • Download the four .gz files of the MNIST data set from the link ( http://yann.lecun.com/exdb/mnist/ )
  • Then make a folder names MNIST_data (or your choice in your working directory/ site packages folder in the tensorflow\examples folder).
  • Directly copy paste the files into the folder.
  • Copy the address of the folder (it probably will be ( C:\Python\Python35\Lib\site-packages\tensorflow\examples\tutorials\mnist\MNIST_data ))
  • Change the "\" to "/" as "\" is used for escape characters, to access the folder locations.
  • Lastly, if you are following the tutorials, your call function would be ( mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) ) ; change the "MNIST_data/" parameter to your folder location. As in my case would be ( mnist = input_data.read_data_sets("C:/Python/Python35/Lib/site-packages/tensorflow/examples/tutorials/mnist/MNIST_data", one_hot=True) )

Then it's all done. Hope it works for you.

Swift Beta performance: sorting arrays

TL;DR: Yes, the only Swift language implementation is slow, right now. If you need fast, numeric (and other types of code, presumably) code, just go with another one. In the future, you should re-evaluate your choice. It might be good enough for most application code that is written at a higher level, though.

From what I'm seeing in SIL and LLVM IR, it seems like they need a bunch of optimizations for removing retains and releases, which might be implemented in Clang (for Objective-C), but they haven't ported them yet. That's the theory I'm going with (for now… I still need to confirm that Clang does something about it), since a profiler run on the last test-case of this question yields this “pretty” result:

Time profiling on -O3 Time profiling on -Ofast

As was said by many others, -Ofast is totally unsafe and changes language semantics. For me, it's at the “If you're going to use that, just use another language” stage. I'll re-evaluate that choice later, if it changes.

-O3 gets us a bunch of swift_retain and swift_release calls that, honestly, don't look like they should be there for this example. The optimizer should have elided (most of) them AFAICT, since it knows most of the information about the array, and knows that it has (at least) a strong reference to it.

It shouldn't emit more retains when it's not even calling functions which might release the objects. I don't think an array constructor can return an array which is smaller than what was asked for, which means that a lot of checks that were emitted are useless. It also knows that the integer will never be above 10k, so the overflow checks can be optimized (not because of -Ofast weirdness, but because of the semantics of the language (nothing else is changing that var nor can access it, and adding up to 10k is safe for the type Int).

The compiler might not be able to unbox the array or the array elements, though, since they're getting passed to sort(), which is an external function and has to get the arguments it's expecting. This will make us have to use the Int values indirectly, which would make it go a bit slower. This could change if the sort() generic function (not in the multi-method way) was available to the compiler and got inlined.

This is a very new (publicly) language, and it is going through what I assume are lots of changes, since there are people (heavily) involved with the Swift language asking for feedback and they all say the language isn't finished and will change.

Code used:

import Cocoa

let swift_start = NSDate.timeIntervalSinceReferenceDate();
let n: Int = 10000
let x = Int[](count: n, repeatedValue: 1)
for i in 0..n {
    for j in 0..n {
        let tmp: Int = x[j]
        x[i] = tmp
    }
}
let y: Int[] = sort(x)
let swift_stop = NSDate.timeIntervalSinceReferenceDate();

println("\(swift_stop - swift_start)s")

P.S: I'm not an expert on Objective-C nor all the facilities from Cocoa, Objective-C, or the Swift runtimes. I might also be assuming some things that I didn't write.

Does a "Find in project..." feature exist in Eclipse IDE?

yes, but you need to open the global search panel. to do so, press the binoculars icon on the top right corner of the IDE.

you can even filter searches by function identifiers, method scopes an etc...

  • Choose File Search for plain text search in workspace/selected projects
  • For specific expression searches, choose the relevant tab (such as Java Search which allows to search for specific identifiers)

Open link in new tab or window

It shouldn't be your call to decide whether the link should open in a new tab or a new window, since ultimately this choice should be done by the settings of the user's browser. Some people like tabs; some like new windows.

Using _blank will tell the browser to use a new tab/window, depending on the user's browser configuration and how they click on the link (e.g. middle click, Ctrl+click, or normal click).

Best way to access a control on another form in Windows Forms?

I agree with using events for this. Since I suspect that you're building an MDI-application (since you create many child forms) and creates windows dynamically and might not know when to unsubscribe from events, I would recommend that you take a look at Weak Event Patterns. Alas, this is only available for framework 3.0 and 3.5 but something similar can be implemented fairly easy with weak references.

However, if you want to find a control in a form based on the form's reference, it's not enough to simply look at the form's control collection. Since every control have it's own control collection, you will have to recurse through them all to find a specific control. You can do this with these two methods (which can be improved).

public static Control FindControl(Form form, string name)
{
    foreach (Control control in form.Controls)
    {
        Control result = FindControl(form, control, name);

        if (result != null)
            return result;
    }

    return null;
}

private static Control FindControl(Form form, Control control, string name)
{
    if (control.Name == name) {
        return control;
    }

    foreach (Control subControl in control.Controls)
    {
        Control result = FindControl(form, subControl, name);

        if (result != null)
            return result;
    }

    return null;
}

Lambda function in list comprehensions

The first one

f = lambda x: x*x
[f(x) for x in range(10)]

runs f() for each value in the range so it does f(x) for each value

the second one

[lambda x: x*x for x in range(10)]

runs the lambda for each value in the list, so it generates all of those functions.

How to get substring of NSString?

Option 1:

NSString *haystack = @"value:hello World:value";
NSString *haystackPrefix = @"value:";
NSString *haystackSuffix = @":value";
NSRange needleRange = NSMakeRange(haystackPrefix.length,
                                  haystack.length - haystackPrefix.length - haystackSuffix.length);
NSString *needle = [haystack substringWithRange:needleRange];
NSLog(@"needle: %@", needle); // -> "hello World"

Option 2:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^value:(.+?):value$" options:0 error:nil];
NSTextCheckingResult *match = [regex firstMatchInString:haystack options:NSAnchoredSearch range:NSMakeRange(0, haystack.length)];
NSRange needleRange = [match rangeAtIndex: 1];
NSString *needle = [haystack substringWithRange:needleRange];

This one might be a bit over the top for your rather trivial case though.

Option 3:

NSString *needle = [haystack componentsSeparatedByString:@":"][1];

This one creates three temporary strings and an array while splitting.


All snippets assume that what's searched for is actually contained in the string.

How do I create HTML table using jQuery dynamically?

You may use two options:

  1. createElement
  2. InnerHTML

Create Element is the fastest way (check here.):

$(document.createElement('table'));

InnerHTML is another popular approach:

$("#foo").append("<div>hello world</div>"); // Check similar for table too.

Check a real example on How to create a new table with rows using jQuery and wrap it inside div.

There may be other approaches as well. Please use this as a starting point and not as a copy-paste solution.

Edit:

Check Dynamic creation of table with DOM

Edit 2:

IMHO, you are mixing object and inner HTML. Let's try with a pure inner html approach:

function createProviderFormFields(id, labelText, tooltip, regex) {
    var tr = '<tr>' ;
         // create a new textInputBox  
           var textInputBox = '<input type="text" id="' + id + '" name="' + id + '" title="' + tooltip + '" />';  
        // create a new Label Text
            tr += '<td>' + labelText  + '</td>';
            tr += '<td>' + textInputBox + '</td>';  
    tr +='</tr>';
    return tr;
}

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

When I find myself thinking about using Manager or Helper in a class name, I consider it a code smell that means I haven't found the right abstraction yet and/or I'm violating the single responsibility principle, so refactoring and putting more effort into design often makes naming much easier.

But even well-designed classes don't (always) name themselves, and your choices partly depend on whether you're creating business model classes or technical infrastructure classes.

Business model classes can be hard, because they're different for every domain. There are some terms I use a lot, like Policy for strategy classes within a domain (e.g., LateRentalPolicy), but these usually flow from trying to create a "ubiquitous language" that you can share with business users, designing and naming classes so they model real-world ideas, objects, actions, and events.

Technical infrastructure classes are a bit easier, because they describe domains we know really well. I prefer to incorporate design pattern names into the class names, like InsertUserCommand, CustomerRepository, or SapAdapter. I understand the concern about communicating implementation instead of intent, but design patterns marry these two aspects of class design - at least when you're dealing with infrastructure, where you want the implementation design to be transparent even while you're hiding the details.

Maximum value for long integer

Python long can be arbitrarily large. If you need a value that's greater than any other value, you can use float('inf'), since Python has no trouble comparing numeric values of different types. Similarly, for a value lesser than any other value, you can use float('-inf').

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

I would assume that one might want a solution that produces a widely useable base64 URI. Please visit data:text/plain;charset=utf-8;base64,4pi44pi54pi64pi74pi84pi+4pi/ to see a demonstration (copy the data uri, open a new tab, paste the data URI into the address bar, then press enter to go to the page). Despite the fact that this URI is base64-encoded, the browser is still able to recognize the high code points and decode them properly. The minified encoder+decoder is 1058 bytes (+Gzip?589 bytes)

!function(e){"use strict";function h(b){var a=b.charCodeAt(0);if(55296<=a&&56319>=a)if(b=b.charCodeAt(1),b===b&&56320<=b&&57343>=b){if(a=1024*(a-55296)+b-56320+65536,65535<a)return d(240|a>>>18,128|a>>>12&63,128|a>>>6&63,128|a&63)}else return d(239,191,189);return 127>=a?inputString:2047>=a?d(192|a>>>6,128|a&63):d(224|a>>>12,128|a>>>6&63,128|a&63)}function k(b){var a=b.charCodeAt(0)<<24,f=l(~a),c=0,e=b.length,g="";if(5>f&&e>=f){a=a<<f>>>24+f;for(c=1;c<f;++c)a=a<<6|b.charCodeAt(c)&63;65535>=a?g+=d(a):1114111>=a?(a-=65536,g+=d((a>>10)+55296,(a&1023)+56320)):c=0}for(;c<e;++c)g+="\ufffd";return g}var m=Math.log,n=Math.LN2,l=Math.clz32||function(b){return 31-m(b>>>0)/n|0},d=String.fromCharCode,p=atob,q=btoa;e.btoaUTF8=function(b,a){return q((a?"\u00ef\u00bb\u00bf":"")+b.replace(/[\x80-\uD7ff\uDC00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g,h))};e.atobUTF8=function(b,a){a||"\u00ef\u00bb\u00bf"!==b.substring(0,3)||(b=b.substring(3));return p(b).replace(/[\xc0-\xff][\x80-\xbf]*/g,k)}}(""+void 0==typeof global?""+void 0==typeof self?this:self:global)

Below is the source code used to generate it.

var fromCharCode = String.fromCharCode;
var btoaUTF8 = (function(btoa, replacer){"use strict";
    return function(inputString, BOMit){
        return btoa((BOMit ? "\xEF\xBB\xBF" : "") + inputString.replace(
            /[\x80-\uD7ff\uDC00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g, replacer
        ));
    }
})(btoa, function(nonAsciiChars){"use strict";
    // make the UTF string into a binary UTF-8 encoded string
    var point = nonAsciiChars.charCodeAt(0);
    if (point >= 0xD800 && point <= 0xDBFF) {
        var nextcode = nonAsciiChars.charCodeAt(1);
        if (nextcode !== nextcode) // NaN because string is 1 code point long
            return fromCharCode(0xef/*11101111*/, 0xbf/*10111111*/, 0xbd/*10111101*/);
        // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
        if (nextcode >= 0xDC00 && nextcode <= 0xDFFF) {
            point = (point - 0xD800) * 0x400 + nextcode - 0xDC00 + 0x10000;
            if (point > 0xffff)
                return fromCharCode(
                    (0x1e/*0b11110*/<<3) | (point>>>18),
                    (0x2/*0b10*/<<6) | ((point>>>12)&0x3f/*0b00111111*/),
                    (0x2/*0b10*/<<6) | ((point>>>6)&0x3f/*0b00111111*/),
                    (0x2/*0b10*/<<6) | (point&0x3f/*0b00111111*/)
                );
        } else return fromCharCode(0xef, 0xbf, 0xbd);
    }
    if (point <= 0x007f) return nonAsciiChars;
    else if (point <= 0x07ff) {
        return fromCharCode((0x6<<5)|(point>>>6), (0x2<<6)|(point&0x3f));
    } else return fromCharCode(
        (0xe/*0b1110*/<<4) | (point>>>12),
        (0x2/*0b10*/<<6) | ((point>>>6)&0x3f/*0b00111111*/),
        (0x2/*0b10*/<<6) | (point&0x3f/*0b00111111*/)
    );
});

Then, to decode the base64 data, either HTTP get the data as a data URI or use the function below.

var clz32 = Math.clz32 || (function(log, LN2){"use strict";
    return function(x) {return 31 - log(x >>> 0) / LN2 | 0};
})(Math.log, Math.LN2);
var fromCharCode = String.fromCharCode;
var atobUTF8 = (function(atob, replacer){"use strict";
    return function(inputString, keepBOM){
        inputString = atob(inputString);
        if (!keepBOM && inputString.substring(0,3) === "\xEF\xBB\xBF")
            inputString = inputString.substring(3); // eradicate UTF-8 BOM
        // 0xc0 => 0b11000000; 0xff => 0b11111111; 0xc0-0xff => 0b11xxxxxx
        // 0x80 => 0b10000000; 0xbf => 0b10111111; 0x80-0xbf => 0b10xxxxxx
        return inputString.replace(/[\xc0-\xff][\x80-\xbf]*/g, replacer);
    }
})(atob, function(encoded){"use strict";
    var codePoint = encoded.charCodeAt(0) << 24;
    var leadingOnes = clz32(~codePoint);
    var endPos = 0, stringLen = encoded.length;
    var result = "";
    if (leadingOnes < 5 && stringLen >= leadingOnes) {
        codePoint = (codePoint<<leadingOnes)>>>(24+leadingOnes);
        for (endPos = 1; endPos < leadingOnes; ++endPos)
            codePoint = (codePoint<<6) | (encoded.charCodeAt(endPos)&0x3f/*0b00111111*/);
        if (codePoint <= 0xFFFF) { // BMP code point
          result += fromCharCode(codePoint);
        } else if (codePoint <= 0x10FFFF) {
          // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
          codePoint -= 0x10000;
          result += fromCharCode(
            (codePoint >> 10) + 0xD800,  // highSurrogate
            (codePoint & 0x3ff) + 0xDC00 // lowSurrogate
          );
        } else endPos = 0; // to fill it in with INVALIDs
    }
    for (; endPos < stringLen; ++endPos) result += "\ufffd"; // replacement character
    return result;
});

The advantage of being more standard is that this encoder and this decoder are more widely applicable because they can be used as a valid URL that displays correctly. Observe.

_x000D_
_x000D_
(function(window){_x000D_
    "use strict";_x000D_
    var sourceEle = document.getElementById("source");_x000D_
    var urlBarEle = document.getElementById("urlBar");_x000D_
    var mainFrameEle = document.getElementById("mainframe");_x000D_
    var gotoButton = document.getElementById("gotoButton");_x000D_
    var parseInt = window.parseInt;_x000D_
    var fromCodePoint = String.fromCodePoint;_x000D_
    var parse = JSON.parse;_x000D_
    _x000D_
    function unescape(str){_x000D_
        return str.replace(/\\u[\da-f]{0,4}|\\x[\da-f]{0,2}|\\u{[^}]*}|\\[bfnrtv"'\\]|\\0[0-7]{1,3}|\\\d{1,3}/g, function(match){_x000D_
          try{_x000D_
            if (match.startsWith("\\u{"))_x000D_
              return fromCodePoint(parseInt(match.slice(2,-1),16));_x000D_
            if (match.startsWith("\\u") || match.startsWith("\\x"))_x000D_
              return fromCodePoint(parseInt(match.substring(2),16));_x000D_
            if (match.startsWith("\\0") && match.length > 2)_x000D_
              return fromCodePoint(parseInt(match.substring(2),8));_x000D_
            if (/^\\\d/.test(match)) return fromCodePoint(+match.slice(1));_x000D_
          }catch(e){return "\ufffd".repeat(match.length)}_x000D_
          return parse('"' + match + '"');_x000D_
        });_x000D_
    }_x000D_
    _x000D_
    function whenChange(){_x000D_
      try{ urlBarEle.value = "data:text/plain;charset=UTF-8;base64," + btoaUTF8(unescape(sourceEle.value), true);_x000D_
      } finally{ gotoURL(); }_x000D_
    }_x000D_
    sourceEle.addEventListener("change",whenChange,{passive:1});_x000D_
    sourceEle.addEventListener("input",whenChange,{passive:1});_x000D_
    _x000D_
    // IFrame Setup:_x000D_
    function gotoURL(){mainFrameEle.src = urlBarEle.value}_x000D_
    gotoButton.addEventListener("click", gotoURL, {passive: 1});_x000D_
    function urlChanged(){urlBarEle.value = mainFrameEle.src}_x000D_
    mainFrameEle.addEventListener("load", urlChanged, {passive: 1});_x000D_
    urlBarEle.addEventListener("keypress", function(evt){_x000D_
      if (evt.key === "enter") evt.preventDefault(), urlChanged();_x000D_
    }, {passive: 1});_x000D_
    _x000D_
        _x000D_
    var fromCharCode = String.fromCharCode;_x000D_
    var btoaUTF8 = (function(btoa, replacer){_x000D_
      "use strict";_x000D_
        return function(inputString, BOMit){_x000D_
         return btoa((BOMit?"\xEF\xBB\xBF":"") + inputString.replace(_x000D_
          /[\x80-\uD7ff\uDC00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g, replacer_x000D_
      ));_x000D_
     }_x000D_
    })(btoa, function(nonAsciiChars){_x000D_
  "use strict";_x000D_
     // make the UTF string into a binary UTF-8 encoded string_x000D_
     var point = nonAsciiChars.charCodeAt(0);_x000D_
     if (point >= 0xD800 && point <= 0xDBFF) {_x000D_
      var nextcode = nonAsciiChars.charCodeAt(1);_x000D_
      if (nextcode !== nextcode) { // NaN because string is 1code point long_x000D_
       return fromCharCode(0xef/*11101111*/, 0xbf/*10111111*/, 0xbd/*10111101*/);_x000D_
      }_x000D_
      // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae_x000D_
      if (nextcode >= 0xDC00 && nextcode <= 0xDFFF) {_x000D_
       point = (point - 0xD800) * 0x400 + nextcode - 0xDC00 + 0x10000;_x000D_
       if (point > 0xffff) {_x000D_
        return fromCharCode(_x000D_
         (0x1e/*0b11110*/<<3) | (point>>>18),_x000D_
         (0x2/*0b10*/<<6) | ((point>>>12)&0x3f/*0b00111111*/),_x000D_
         (0x2/*0b10*/<<6) | ((point>>>6)&0x3f/*0b00111111*/),_x000D_
         (0x2/*0b10*/<<6) | (point&0x3f/*0b00111111*/)_x000D_
        );_x000D_
       }_x000D_
      } else {_x000D_
       return fromCharCode(0xef, 0xbf, 0xbd);_x000D_
      }_x000D_
     }_x000D_
     if (point <= 0x007f) { return inputString; }_x000D_
     else if (point <= 0x07ff) {_x000D_
      return fromCharCode((0x6<<5)|(point>>>6), (0x2<<6)|(point&0x3f/*00111111*/));_x000D_
     } else {_x000D_
      return fromCharCode(_x000D_
       (0xe/*0b1110*/<<4) | (point>>>12),_x000D_
       (0x2/*0b10*/<<6) | ((point>>>6)&0x3f/*0b00111111*/),_x000D_
       (0x2/*0b10*/<<6) | (point&0x3f/*0b00111111*/)_x000D_
      );_x000D_
     }_x000D_
    });_x000D_
    setTimeout(whenChange, 0);_x000D_
})(window);
_x000D_
img:active{opacity:0.8}
_x000D_
<center>_x000D_
<textarea id="source" style="width:66.7vw">Hello \u1234 W\186\0256ld!_x000D_
Enter text into the top box. Then the URL will update automatically._x000D_
</textarea><br />_x000D_
<div style="width:66.7vw;display:inline-block;height:calc(25vw + 1em + 6px);border:2px solid;text-align:left;line-height:1em">_x000D_
<input id="urlBar" style="width:calc(100% - 1em - 13px)" /><img id="gotoButton" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABsAAAAeCAMAAADqx5XUAAAAclBMVEX///9NczZ8e32ko6fDxsU/fBoSQgdFtwA5pAHVxt+7vLzq5ex23y4SXABLiiTm0+/c2N6DhoQ6WSxSyweVlZVvdG/Uz9aF5kYlbwElkwAggACxs7Jl3hX07/cQbQCar5SU9lRntEWGum+C9zIDHwCGnH5IvZAOAAABmUlEQVQoz7WS25acIBBFkRLkIgKKtOCttbv//xdDmTGZzHv2S63ltuBQQP4rdRiRUP8UK4wh6nVddQwj/NtDQTvac8577zTQb72zj65/876qqt7wykU6/1U6vFEgjE1mt/5LRqrpu7oVsn0sjZejMfxR3W/yLikqAFcUx93YxLmZGOtElmEu6Ufd9xV3ZDTGcEvGLbMk0mHHlUSvS5svCwS+hVL8loQQyfpI1Ay8RF/xlNxcsTchGjGDIuBG3Ik7TMyNxn8m0TSnBAK6Z8UZfp3IbAonmJvmsEACum6aNv7B0CnvpezDcNhw9XWsuAr7qnRg6dABmeM4dTgn/DZdXWs3LMspZ1KDMt1kcPJ6S1icWNp2qaEmjq6myx7jbQK3VKItLJaW5FR+cuYlRhYNKzGa9vF4vM5roLW3OSVjkmiGJrPhUq301/16pVKZRGFYWjTP50spTxBN5Z4EKnSonruk+n4tUokv1aJSEl/MLZU90S3L6/U6o0J142iQVp3HcZxKSo8LfkNRCtJaKYFSRX7iaoAAUDty8wvWYR6HJEepdwAAAABJRU5ErkJggg==" style="width:calc(1em + 4px);line-height:1em;vertical-align:-40%;cursor:pointer" />_x000D_
<iframe id="mainframe" style="width:66.7vw;height:25vw" frameBorder="0"></iframe>_x000D_
</div>_x000D_
</center>
_x000D_
_x000D_
_x000D_

In addition to being very standardized, the above code snippets are also very fast. Instead of an indirect chain of succession where the data has to be converted several times between various forms (such as in Riccardo Galli's response), the above code snippet is as direct as performantly possible. It uses only one simple fast String.prototype.replace call to process the data when encoding, and only one to decode the data when decoding. Another plus is that (especially for big strings), String.prototype.replace allows the browser to automatically handle the underlying memory management of resizing the string, leading a significant performance boost especially in evergreen browsers like Chrome and Firefox that heavily optimize String.prototype.replace. Finally, the icing on the cake is that for you latin script exclusivo users, strings which don't contain any code points above 0x7f are extra fast to process because the string remains unmodified by the replacement algorithm.

I have created a github repository for this solution at https://github.com/anonyco/BestBase64EncoderDecoder/

Install a .NET windows service without InstallUtil.exe

Yes, that is fully possible (i.e. I do exactly this); you just need to reference the right dll (System.ServiceProcess.dll) and add an installer class...

Here's an example:

[RunInstaller(true)]
public sealed class MyServiceInstallerProcess : ServiceProcessInstaller
{
    public MyServiceInstallerProcess()
    {
        this.Account = ServiceAccount.NetworkService;
    }
}

[RunInstaller(true)]
public sealed class MyServiceInstaller : ServiceInstaller
{
    public MyServiceInstaller()
    {
        this.Description = "Service Description";
        this.DisplayName = "Service Name";
        this.ServiceName = "ServiceName";
        this.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
    }
}

static void Install(bool undo, string[] args)
{
    try
    {
        Console.WriteLine(undo ? "uninstalling" : "installing");
        using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))
        {
            IDictionary state = new Hashtable();
            inst.UseNewContext = true;
            try
            {
                if (undo)
                {
                    inst.Uninstall(state);
                }
                else
                {
                    inst.Install(state);
                    inst.Commit(state);
                }
            }
            catch
            {
                try
                {
                    inst.Rollback(state);
                }
                catch { }
                throw;
            }
        }
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine(ex.Message);
    }
}

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

I'm sure this is a duplicate, but I can't find a question with the same answer.

Add HorizontalContentAlignment="Stretch" to your ListBox. That should do the trick. Just be careful with auto-complete because it is so easy to get HorizontalAlignment by mistake.

Access elements of parent window from iframe

You can access elements of parent window from within an iframe by using window.parent like this:

// using jquery    
window.parent.$("#element_id");

Which is the same as:

// pure javascript
window.parent.document.getElementById("element_id");

And if you have more than one nested iframes and you want to access the topmost iframe, then you can use window.top like this:

// using jquery
window.top.$("#element_id");

Which is the same as:

// pure javascript
window.top.document.getElementById("element_id");

How to solve "Fatal error: Class 'MySQLi' not found"?

I found a solution for this problem after a long analysing procedure. After properly testing my php installation with the command line features I found out that the php is working well and could work with the mysql database. Btw. you can run code-files with php code with the command php -f filename.php
So I realized, it must something be wrong with the Apache.
I made a file with just the phpinfo() function inside.
Here I saw, that in the line
Loaded Configuration File
my config file was not loaded, instead there was mentioned (none).

Finally I found within the Apache configuration the entry

<IfModule php5_module>
    PHPINIDir "C:/xampp/php"
</IfModule>

But I've installed the PHP 7 and so the Apache could not load the php.ini file because there was no entry for that. I added

<IfModule php7_module>
    PHPINIDir "C:/xampp/php"
</IfModule>

and after restart Apache all works well.

These code blocks above I found in my httpd-xampp.conf file. May it is somewhere else at your configuration.
In the same file I had changed before the settings for the php 7 as replacement for the php 5 version.

#
# PHP-Module setup
#
#LoadFile "C:/xampp/php/php5ts.dll"
#LoadModule php5_module "C:/xampp/php/php5apache2_4.dll"
LoadFile "C:/xampp/php/php7ts.dll"
LoadModule php7_module "C:/xampp/php/php7apache2_4.dll"

As you can see I have the xampp package installed but this problem was just on the Apache side.

Text overflow ellipsis on two lines

Easy CSS properties can do the trick. The following is for a three-line ellipsis.

display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;

Vertically centering a div inside another div

Vertically centering div items inside another div

Just set the container to display:table and then the inner items to display:table-cell. Set a height on the container, and then set vertical-align:middle on the inner items. This has broad compatibility back as far as the days of IE9.

Just note that the vertical alignment will depend on the height of the parent container.

_x000D_
_x000D_
.cn_x000D_
{_x000D_
display:table;_x000D_
height:80px;_x000D_
background-color:#555;_x000D_
}_x000D_
_x000D_
.inner_x000D_
{_x000D_
display:table-cell;_x000D_
vertical-align:middle;_x000D_
color:#FFF;_x000D_
padding-left:10px;_x000D_
padding-right:10px;_x000D_
}
_x000D_
<div class="cn">_x000D_
  <div class="inner">Item 1</div>_x000D_
  <div class="inner">Item 2</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

When to use LinkedList over ArrayList in Java?

One of the tests I saw on here only conducts the test once. But what I have noticed is that you need to run these tests many times and eventually their times will converge. Basically the JVM needs to warm up. For my particular use case I needed to add/remove items to a list that grows to about 500 items. In my tests LinkedList came out faster, with LinkedList coming in around 50,000 NS and ArrayList coming in at around 90,000 NS... give or take. See the code below.

public static void main(String[] args) {
    List<Long> times = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
        times.add(doIt());
    }
    System.out.println("avg = " + (times.stream().mapToLong(x -> x).average()));
}

static long doIt() {
    long start = System.nanoTime();
    List<Object> list = new LinkedList<>();
    //uncomment line below to test with ArrayList
    //list = new ArrayList<>();
    for (int i = 0; i < 500; i++) {
        list.add(i);
    }

    Iterator it = list.iterator();
    while (it.hasNext()) {
        it.next();
        it.remove();
    }
    long end = System.nanoTime();
    long diff = end - start;
    //uncomment to see the JVM warmup and get faster for the first few iterations
    //System.out.println(diff)
    return diff;
}

Can I multiply strings in Java to repeat sequences?

The simplest way is:

String someNum = "123000";
System.out.println(someNum);

Remove attribute "checked" of checkbox

using .removeAttr() on a boolean attribute such as checked, selected, or readonly would also set the corresponding named property to false.

Hence removed this checked attribute

$("#IdName option:checked").removeAttr("checked");

MYSQL query between two timestamps

SELECT * FROM `orders` WHERE `order_date_time`  BETWEEN 1534809600 AND 1536718364

DateTime.MinValue and SqlDateTime overflow

If you use DATETIME2 you may find you have to pass the parameter in specifically as DATETIME2, otherwise it may helpfully convert it to DATETIME and have the same issue.

command.Parameters.Add("@FirstRegistration",SqlDbType.DateTime2).Value = installation.FirstRegistration;

Laravel migration table field's type change

Not really an answer, but just a note about ->change():

Only the following column types can be "changed": bigInteger, binary, boolean, date, dateTime, dateTimeTz, decimal, integer, json, longText, mediumText, smallInteger, string, text, time, unsignedBigInteger, unsignedInteger and unsignedSmallInteger.

https://laravel.com/docs/5.8/migrations#modifying-columns

If your column isn't one of these you will need to either drop the column or use the alter statement as mentioned in other answers.

Confused about __str__ on list in Python

print self.id.__str__() would work for you, although not that useful for you.

Your __str__ method will be more useful when you say want to print out a grid or struct representation as your program develops.

print self._grid.__str__()

def __str__(self):
    """
    Return a string representation of the grid for debugging.
    """
    grid_str = ""
    for row in range(self._rows):
        grid_str += str( self._grid[row] )
        grid_str += '\n'
    return grid_str

What's the best way to check if a String represents an integer in Java?

I copied the code from rally25rs answer and added some tests for non-integer data. The results are undeniably in favor of the method posted by Jonas Klemming. The results for the Exception method that I originally posted are pretty good when you have integer data, but they're the worst when you don't, while the results for the RegEx solution (that I'll bet a lot of people use) were consistently bad. See Felipe's answer for a compiled regex example, which is much faster.

public void runTests()
{
    String big_int = "1234567890";
    String non_int = "1234XY7890";

    long startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
        IsInt_ByException(big_int);
    long endTime = System.currentTimeMillis();
    System.out.print("ByException - integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
        IsInt_ByException(non_int);
    endTime = System.currentTimeMillis();
    System.out.print("ByException - non-integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
        IsInt_ByRegex(big_int);
    endTime = System.currentTimeMillis();
    System.out.print("\nByRegex - integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
        IsInt_ByRegex(non_int);
    endTime = System.currentTimeMillis();
    System.out.print("ByRegex - non-integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
        IsInt_ByJonas(big_int);
    endTime = System.currentTimeMillis();
    System.out.print("\nByJonas - integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
        IsInt_ByJonas(non_int);
    endTime = System.currentTimeMillis();
    System.out.print("ByJonas - non-integer data: ");
    System.out.println(endTime - startTime);
}

private boolean IsInt_ByException(String str)
{
    try
    {
        Integer.parseInt(str);
        return true;
    }
    catch(NumberFormatException nfe)
    {
        return false;
    }
}

private boolean IsInt_ByRegex(String str)
{
    return str.matches("^-?\\d+$");
}

public boolean IsInt_ByJonas(String str)
{
    if (str == null) {
            return false;
    }
    int length = str.length();
    if (length == 0) {
            return false;
    }
    int i = 0;
    if (str.charAt(0) == '-') {
            if (length == 1) {
                    return false;
            }
            i = 1;
    }
    for (; i < length; i++) {
            char c = str.charAt(i);
            if (c <= '/' || c >= ':') {
                    return false;
            }
    }
    return true;
}

Results:

ByException - integer data: 47
ByException - non-integer data: 547

ByRegex - integer data: 390
ByRegex - non-integer data: 313

ByJonas - integer data: 0
ByJonas - non-integer data: 16

ASP.NET document.getElementById('<%=Control.ClientID%>'); returns null

Gotcha!

You have to use RegisterStartupScript instead of RegisterClientScriptBlock

Here My Example.

MasterPage:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs"
    Inherits="prueba.MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript">

        function confirmCallBack() {
            var a = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("Button1").ClientID %>');

            alert(a.value);

        }

    </script>

    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

WebForm1.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"
    CodeBehind="WebForm1.aspx.cs" Inherits="prueba.WebForm1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Content>

WebForm1.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace prueba
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "js", "confirmCallBack();", true);

        }
    }
}

List directory in Go

Even simpler, use path/filepath:

package main    

import (
    "fmt"
    "log"
    "path/filepath"
)

func main() {
    files, err := filepath.Glob("*")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(files) // contains a list of all files in the current directory
}

Pipe to/from the clipboard in Bash script

xsel on Debian/Ubuntu/Mint

# append to clipboard:
cat 'the file with content' | xsel -ib

# or type in the happy face :) and ...
echo 'the happy face :) and content' | xsel -ib

# show clipboard
xsel -b

# Get more info:
man xsel

Install

sudo apt-get install xsel

"CASE" statement within "WHERE" clause in SQL Server 2008

CASE LEN('TestPerson')
    WHEN 0 THEN co.personentered  = co.personentered ELSE co.personentered LIKE '%TestPerson'

Try the following:

... and ( 
    (LEN('TestPerson') = 0 and co.personentered  = co.personentered) or
    (LEN('TestPerson') <> 0 and co.personentered LIKE '%TestPerson') ) and ...

Waiting on a list of Future

Use a CompletableFuture in Java 8

    // Kick of multiple, asynchronous lookups
    CompletableFuture<User> page1 = gitHubLookupService.findUser("Test1");
    CompletableFuture<User> page2 = gitHubLookupService.findUser("Test2");
    CompletableFuture<User> page3 = gitHubLookupService.findUser("Test3");

    // Wait until they are all done
    CompletableFuture.allOf(page1,page2,page3).join();

    logger.info("--> " + page1.get());

How to efficiently use try...catch blocks in PHP

There is no any problem to write multiple lines of execution withing a single try catch block like below

try{
install_engine();
install_break();
}
catch(Exception $e){
show_exception($e->getMessage());
}

The moment any execption occure either in install_engine or install_break function the control will be passed to catch function. One more recommendation is to eat your exception properly. Which means instead of writing die('Message') it is always advisable to have exception process properly. You may think of using die() function in error handling but not in exception handling.

When you should use multiple try catch block You can think about multiple try catch block if you want the different code block exception to display different type of exception or you are trying to throw any exception from your catch block like below:

try{
    install_engine();
    install_break();
    }
    catch(Exception $e){
    show_exception($e->getMessage());
    }
try{
install_body();
paint_body();
install_interiour();
}
catch(Exception $e){
throw new exception('Body Makeover faield')
}

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

your 8080 port is already used by another application 1/ you can try to find out which app is using it, using "netstat -aon" and stop the process; 2/ you can go to server.xml and change from port 8080 to another one (ex: 8081)

Remove all files except some from a directory

find . | grep -v "excluded files criteria" | xargs rm

This will list all files in current directory, then list all those that don't match your criteria (beware of it matching directory names) and then remove them.

Update: based on your edit, if you really want to delete everything from current directory except files you listed, this can be used:

mkdir /tmp_backup && mv textfile.txt backup.tar.gz script.php database.sql info.txt /tmp_backup/ && rm -r && mv /tmp_backup/* . && rmdir /tmp_backup

It will create a backup directory /tmp_backup (you've got root privileges, right?), move files you listed to that directory, delete recursively everything in current directory (you know that you're in the right directory, do you?), move back to current directory everything from /tmp_backup and finally, delete /tmp_backup.

I choose the backup directory to be in root, because if you're trying to delete everything recursively from root, your system will have big problems.

Surely there are more elegant ways to do this, but this one is pretty straightforward.

Checking session if empty or not

if (HttpContext.Current.Session["emp_num"] != null)
{
     // code if session is not null
}
  • if at all above fails.

vba error handling in loop

As a general way to handle error in a loop like your sample code, I would rather use:

on error resume next
for each...
    'do something that might raise an error, then
    if err.number <> 0 then
         ...
    end if
 next ....

Bridged networking not working in Virtualbox under Windows 10

Virtual Box gives a lot of issues when it comes to bridge adaptor. I had the same issue with Virtual Box for windows 10. I decided to create VirtualBox Host-Only Ethernet adapter. But I again got issues while creating the host-only ethernet adaptor. I decided to switch to vmware. Vmware did not give me any issues. After installing vmware (and after changing few settings in the BIOS) and installing ubuntu on it, it automatically connected to my host machine's internet. It was able to generate it's own IP address as well and could also ping the host machine (windows machine). Hence, for me virtual box created a lot of issues whereas, vmware worked smoothly for me.

VSCode Change Default Terminal

I just type following keywords in the opened terminal;

  1. powershell
  2. bash
  3. cmd
  4. node
  5. python (or python3)

See details in the below image. (VSCode version 1.19.1 - windows 10 OS) enter image description here

It works on VS Code Mac as well. I tried it with VSCode (Version 1.20.1)

2D character array initialization in C

char **options[2][100];

declares a size-2 array of size-100 arrays of pointers to pointers to char. You'll want to remove one *. You'll also want to put your string literals in double quotes.

The imported project "C:\Microsoft.CSharp.targets" was not found

In my case, I opened my .csproj file in notepad and removed the following three lines. Worked like a charm:

<Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />
<Import Project="..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" />
<Import Project="..\packages\Microsoft.Net.Compilers.1.3.2\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.1.3.2\build\Microsoft.Net.Compilers.props')" />

Determining if a number is prime

I Have Use This Idea For Finding If The No. Is Prime or Not:

#include <conio.h> 
#include <iostream>
using namespace std;
int main() {
  int x, a;
  cout << "Enter The No. :";
  cin >> x;
  int prime(unsigned int);
  a = prime(x);
  if (a == 1)
    cout << "It Is A Prime No." << endl;
  else
  if (a == 0)
    cout << "It Is Composite No." << endl;
  getch();
}

int prime(unsigned int x) {
  if (x == 1) {
    cout << "It Is Neither Prime Nor Composite";
    return 2;
  }
  if (x == 2 || x == 3 || x == 5 || x == 7)
    return 1;
  if (x % 2 != 0 && x % 3 != 0 && x % 5 != 0 && x % 7 != 0)
    return 1;
  else
    return 0;
}

Where to find Java JDK Source Code?

Chances that you already got the source code with the JDK, it is matter of finding where it is. In case, JDK folder doesn't contain the source code:

sudo apt-get install openjdk-7-source

OSX Folks, search in homebrew formulas.

In ubuntu, the command above would put your souce file under: /usr/lib/jvm/openjdk-7/

Good news is that Eclipse will take you there already (How to bind Eclipse to the Java source code):

Follow the orange buttons

enter image description here enter image description here enter image description here

html5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

Here's a solution for AngularJS using an IIFE and leveraging the fact that services are singletons.

This results in isLocalStorageAvailable being set immediately when the service is first injected and avoids needlessly running the check every time local storage needs to be accessed.

angular.module('app.auth.services', []).service('Session', ['$log', '$window',
  function Session($log, $window) {
    var isLocalStorageAvailable = (function() {
      try {
        $window.localStorage.world = 'hello';
        delete $window.localStorage.world;
        return true;
      } catch (ex) {
        return false;
      }
    })();

    this.store = function(key, value) {
      if (isLocalStorageAvailable) {
        $window.localStorage[key] = value;
      } else {
        $log.warn('Local Storage is not available');
      }
    };
  }
]);

How to dynamically add a style for text-align using jQuery

 $(this).css({'text-align':'center'}); 

You can use class name and id in place of this

$('.classname').css({'text-align':'center'});

or

$('#id').css({'text-align':'center'});

Set HTML element's style property in javascript

Don't set the style object itself, set the background color property of the style object that is a property of the element.

And yes, even though you said no, jquery and tablesorter with its zebra stripe plugin can do this all for you in 3 lines of code.

And just setting the class attribute would be better since then you have non-hard-coded control over the styling which is more organized

Error: Unexpected value 'undefined' imported by the module

I had the same issue, I added the component in the index.ts of a=of the folder and did a export. Still the undefined error was popping. But the IDE pop our any red squiggly lines

Then as suggested changed from

import { SearchComponent } from './';

to

import { SearchComponent } from './search/search.component';

'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)

Because the server don't have CORS header, so you are not allowed to get the response.

This is header from API that I captured from Chrome brower:

Age:28
Cache-Control:max-age=3600, public
Connection:keep-alive
Date:Fri, 06 Jan 2017 02:05:33 GMT
ETag:"18303ae5d3714f8f1fbcb2c8e6499190"
Server:Cowboy
Status:200 OK
Via:1.1 vegur, 1.1 e01a35c1b8f382e5c0a399f1741255fd.cloudfront.net (CloudFront)
X-Amz-Cf-Id:GH6w6y_P5ht7AqAD3SnlK39EJ0PpnignqSI3o5Fsbi9PKHEFNMA0yw==
X-Cache:Hit from cloudfront
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
X-Request-Id:b971e55f-b43d-43ce-8d4f-aa9d39830629
X-Runtime:0.014042
X-Ua-Compatible:chrome=1
X-Xss-Protection:1; mode=block

No CORS header in response headers.

Handling exceptions from Java ExecutorService tasks

This is similar to mmm's solution, but a bit more understandable. Have your tasks extend an abstract class that wraps the run() method.

public abstract Task implements Runnable {

    public abstract void execute();

    public void run() {
      try {
        execute();
      } catch (Throwable t) {
        // handle it  
      }
    }
}


public MySampleTask extends Task {
    public void execute() {
        // heavy, error-prone code here
    }
}

What is a None value?

None is a singleton object (meaning there is only one None), used in many places in the language and library to represent the absence of some other value.


For example:
if d is a dictionary, d.get(k) will return d[k] if it exists, but None if d has no key k.

Read this info from a great blog: http://python-history.blogspot.in/

How to Git stash pop specific stash in 1.8.3?

git stash apply n

works as of git version 2.11

Original answer, possibly helping to debug issues with the older syntax involving shell escapes:

As pointed out previously, the curly braces may require escaping or quoting depending on your OS, shell, etc.

See "stash@{1} is ambiguous?" for some detailed hints of what may be going wrong, and how to work around it in various shells and platforms.

git stash list
git stash apply stash@{n}

git stash apply version

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

I had this issue while testing software. Drivers were not signed.

Tip for me was: in cmd line: (administrator) bcdedit /set TESTSIGNING ON and reboot the machine (shutdown -r -t 5)

Programmatically switching between tabs within Swift

In a typical application there is a UITabBarController and it embeds 3 or more UIViewController as its tabs. In such a case if you subclassed a UITabBarController as YourTabBarController then you can set the selected index simply by:

selectedIndex = 1 // Displays 2nd tab. The index starts from 0.

In case you are navigating to YourTabBarController from any other view, then in that view controller's prepare(for segue:) method you can do:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
        if segue.identifier == "SegueToYourTabBarController" {
            if let destVC = segue.destination as? YourTabBarController {
                destVC.selectedIndex = 0
            }
        }

I am using this way of setting tab with Xcode 10 and Swift 4.2.

What is the difference between re.search and re.match?

re.search searches for the pattern throughout the string, whereas re.match does not search the pattern; if it does not, it has no other choice than to match it at start of the string.

jQuery: outer html()

Just use standard DOM functionality:

$('#xxx')[0].outerHTML

outerHTML is well supported - verify at Mozilla or caniuse.

Command to get latest Git commit hash from a branch

Use git ls-remote git://github.com/<user>/<project>.git. For example, my trac-backlog project gives:

:: git ls-remote git://github.com/jszakmeister/trac-backlog.git
5d6a3c973c254378738bdbc85d72f14aefa316a0    HEAD
4652257768acef90b9af560295b02d0ac6e7702c    refs/heads/0.1.x
35af07bc99c7527b84e11a8632bfb396823326f3    refs/heads/0.2.x
5d6a3c973c254378738bdbc85d72f14aefa316a0    refs/heads/master
520dcebff52506682d6822ade0188d4622eb41d1    refs/pull/11/head
6b2c1ed650a7ff693ecd8ab1cb5c124ba32866a2    refs/pull/11/merge
51088b60d66b68a565080eb56dbbc5f8c97c1400    refs/pull/12/head
127c468826c0c77e26a5da4d40ae3a61e00c0726    refs/pull/12/merge
2401b5537224fe4176f2a134ee93005a6263cf24    refs/pull/15/head
8aa9aedc0e3a0d43ddfeaf0b971d0ae3a23d57b3    refs/pull/15/merge
d96aed93c94f97d328fc57588e61a7ec52a05c69    refs/pull/7/head
f7c1e8dabdbeca9f9060de24da4560abc76e77cd    refs/pull/7/merge
aa8a935f084a6e1c66aa939b47b9a5567c4e25f5    refs/pull/8/head
cd258b82cc499d84165ea8d7a23faa46f0f2f125    refs/pull/8/merge
c10a73a8b0c1809fcb3a1f49bdc1a6487927483d    refs/tags/0.1.0
a39dad9a1268f7df256ba78f1166308563544af1    refs/tags/0.2.0
2d559cf785816afd69c3cb768413c4f6ca574708    refs/tags/0.2.1
434170523d5f8aad05dc5cf86c2a326908cf3f57    refs/tags/0.2.2
d2dfe40cb78ddc66e6865dcd2e76d6bc2291d44c    refs/tags/0.3.0
9db35263a15dcdfbc19ed0a1f7a9e29a40507070    refs/tags/0.3.0^{}

Just grep for the one you need and cut it out:

:: git ls-remote git://github.com/jszakmeister/trac-backlog.git | \
   grep refs/heads/master | cut -f 1
5d6a3c973c254378738bdbc85d72f14aefa316a0

Or, you can specify which refs you want on the command line and avoid the grep with:

:: git ls-remote git://github.com/jszakmeister/trac-backlog.git refs/heads/master | \
   cut -f 1
5d6a3c973c254378738bdbc85d72f14aefa316a0

Note: it doesn't have to be the git:// URL. It could be https:// or [email protected]: too.

Originally, this was geared towards finding out the latest commit of a remote branch (not just from your last fetch, but the actual latest commit in the branch on the remote repository). If you need the commit hash for something locally, the best answer is:

git rev-parse branch-name

It's fast, easy, and a single command. If you want the commit hash for the current branch, you can look at HEAD:

git rev-parse HEAD

Simulate Keypress With jQuery

Another option:

$(el).trigger({type: 'keypress', which: 13, keyCode: 13});

http://api.jquery.com/trigger/

Difference between IsNullOrEmpty and IsNullOrWhiteSpace in C#

If your string (In your case the variable text) could be null this would make a big Difference:

1-string.IsNullOrEmpty(text.Trim()) --> EXCEPTION since your calling a mthode of a null object

2-string.IsNullOrWhiteSpace(text) This would work fine since the null issue is beeing checked internally

To provide the same behaviour using the 1st Option you would have to check somehow if its not null first then use the trim() method

if ((text != null) && string.IsNullOrEmpty(text.Trim())) { ... }

Session unset, or session_destroy?

Something to be aware of, the $_SESSION variables are still set in the same page after calling session_destroy() where as this is not the case when using unset($_SESSION) or $_SESSION = array(). Also, unset($_SESSION) blows away the $_SESSION superglobal so only do this when you're destroying a session.

With all that said, it's best to do like the PHP docs has it in the first example for session_destroy().

Find integer index of rows with NaN in pandas dataframe

For DataFrame df:

import numpy as np
index = df['b'].index[df['b'].apply(np.isnan)]

will give you back the MultiIndex that you can use to index back into df, e.g.:

df['a'].ix[index[0]]
>>> 1.452354

For the integer index:

df_index = df.index.values.tolist()
[df_index.index(i) for i in index]
>>> [3, 6]

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

GET parameters in the URL with CodeIgniter

Now it works ok from CodeIgniter 2.1.0

    //By default CodeIgniter enables access to the $_GET array.  If for some
    //reason you would like to disable it, set 'allow_get_array' to FALSE.

$config['allow_get_array']      = TRUE; 

How do I check if file exists in Makefile so I can delete it?

The problem is when you split your command over multiple lines. So, you can either use the \ at the end of lines for continuation as above or you can get everything on one line with the && operator in bash.

Then you can use a test command to test if the file does exist, e.g.:

test -f myApp && echo File does exist

-f file True if file exists and is a regular file.

-s file True if file exists and has a size greater than zero.

or does not:

test -f myApp || echo File does not exist
test ! -f myApp && echo File does not exist

The test is equivalent to [ command.

[ -f myApp ] && rm myApp   # remove myApp if it exists

and it would work as in your original example.

See: help [ or help test for further syntax.

How to stop flask application without using ctrl-c

I did it slightly different using threads

from werkzeug.serving import make_server

class ServerThread(threading.Thread):

    def __init__(self, app):
        threading.Thread.__init__(self)
        self.srv = make_server('127.0.0.1', 5000, app)
        self.ctx = app.app_context()
        self.ctx.push()

    def run(self):
        log.info('starting server')
        self.srv.serve_forever()

    def shutdown(self):
        self.srv.shutdown()

def start_server():
    global server
    app = flask.Flask('myapp')
    ...
    server = ServerThread(app)
    server.start()
    log.info('server started')

def stop_server():
    global server
    server.shutdown()

I use it to do end to end tests for restful api, where I can send requests using the python requests library.

LIKE vs CONTAINS on SQL Server

Also try changing from this:

    SELECT * FROM table WHERE Contains(Column, "test") > 0;

To this:

    SELECT * FROM table WHERE Contains(Column, '"*test*"') > 0;

The former will find records with values like "this is a test" and "a test-case is the plan".

The latter will also find records with values like "i am testing this" and "this is the greatest".

Get current time in milliseconds using C++ and Boost

// Get current date/time in milliseconds.
#include "boost/date_time/posix_time/posix_time.hpp"
namespace pt = boost::posix_time;

int main()
{
     pt::ptime current_date_microseconds = pt::microsec_clock::local_time();

    long milliseconds = current_date_microseconds.time_of_day().total_milliseconds();

    pt::time_duration current_time_milliseconds = pt::milliseconds(milliseconds);

    pt::ptime current_date_milliseconds(current_date_microseconds.date(), 
                                        current_time_milliseconds);

    std::cout << "Microseconds: " << current_date_microseconds 
              << " Milliseconds: " << current_date_milliseconds << std::endl;

    // Microseconds: 2013-Jul-12 13:37:51.699548 Milliseconds: 2013-Jul-12 13:37:51.699000
}

Get current date, given a timezone in PHP?

The other answers set the timezone for all dates in your system. This doesn't always work well if you want to support multiple timezones for your users.

Here's the short version:

<?php
$date = new DateTime("now", new DateTimeZone('America/New_York') );
echo $date->format('Y-m-d H:i:s');

Works in PHP >= 5.2.0

List of supported timezones: php.net/manual/en/timezones.php


Here's a version with an existing time and setting timezone by a user setting

<?php

$usersTimezone = 'America/New_York';
$date = new DateTime( 'Thu, 31 Mar 2011 02:05:59 GMT', new DateTimeZone($usersTimezone) );
echo $date->format('Y-m-d H:i:s');

Here is a more verbose version to show the process a little more clearly

<?php

// Date for a specific date/time:
$date = new DateTime('Thu, 31 Mar 2011 02:05:59 GMT');

// Output date (as-is)
echo $date->format('l, F j Y g:i:s A');     

// Output line break (for testing)
echo "\n<br />\n";

// Example user timezone (to show it can be used dynamically)
$usersTimezone = 'America/New_York';

// Convert timezone
$tz = new DateTimeZone($usersTimezone);
$date->setTimeZone($tz);

// Output date after 
echo $date->format('l, F j Y g:i:s A');

Libraries

  • Carbon — A very popular date library.
  • Chronos — A drop-in replacement for Carbon focused on immutability. See below on why that's important.
  • jenssegers/date — An extension of Carbon that adds multi-language support.

I'm sure there are a number of other libraries available, but these are a few I'm familiar with.


Bonus Lesson: Immutable Date Objects

While you're here, let me save you some future headache. Let's say you want to calculate 1 week from today and 2 weeks from today. You might write some code like:

<?php

// Create a datetime (now, in this case 2017-Feb-11)
$today = new DateTime();

echo $today->format('Y-m-d') . "\n<br>";
echo "---\n<br>";

$oneWeekFromToday = $today->add(DateInterval::createFromDateString('7 days'));
$twoWeeksFromToday = $today->add(DateInterval::createFromDateString('14 days'));

echo $today->format('Y-m-d') . "\n<br>";
echo $oneWeekFromToday->format('Y-m-d') . "\n<br>";
echo $twoWeeksFromToday->format('Y-m-d') . "\n<br>";
echo "\n<br>";

The output:

2017-02-11 
--- 
2017-03-04 
2017-03-04 
2017-03-04

Hmmmm... That's not quite what we wanted. Modifying a traditional DateTime object in PHP not only returns the updated date but modifies the original object as well.

This is where DateTimeImmutable comes in.

$today = new DateTimeImmutable();

echo $today->format('Y-m-d') . "\n<br>";
echo "---\n<br>";

$oneWeekFromToday = $today->add(DateInterval::createFromDateString('7 days'));
$twoWeeksFromToday = $today->add(DateInterval::createFromDateString('14 days'));

echo $today->format('Y-m-d') . "\n<br>";
echo $oneWeekFromToday->format('Y-m-d') . "\n<br>";
echo $twoWeeksFromToday->format('Y-m-d') . "\n<br>";

The output:

2017-02-11 
--- 
2017-02-11 
2017-02-18 
2017-02-25 

In this second example, we get the dates we expected back. By using DateTimeImmutable instead of DateTime, we prevent accidental state mutations and prevent potential bugs.

How to connect to MongoDB in Windows?

you can use below command,

mongod --dbpath=D:\home\mongodata

where D:\home\mongodata is the data storage path

Eclipse does not highlight matching variables

Try:

window > preferences > java > editor > mark occurrences 

Select all options available there.

Also go to:

Preferences > General > Editors > Text Editors > Annotations

Compare the settings for 'Occurrences' and 'Write Occurrences'

Make sure that you don't have the 'Text as higlighted' option checked for one of them.

This should fix it.

Deep copy an array in Angular 2 + TypeScript

Simple:

let objCopy  = JSON.parse(JSON.stringify(obj));

This Also Works (Only for Arrays)

let objCopy2 = obj.slice()

How to run a Python script in the background even after I logout SSH?

Run nohup python bgservice.py & to get the script to ignore the hangup signal and keep running. Output will be put in nohup.out.

Ideally, you'd run your script with something like supervise so that it can be restarted if (when) it dies.

How do I decode a URL parameter using C#?

Server.UrlDecode(xxxxxxxx)

Programmatically Add CenterX/CenterY Constraints

Center in container

enter image description here

The code below does the same thing as centering in the Interface Builder.

override func viewDidLoad() {
    super.viewDidLoad()

    // set up the view
    let myView = UIView()
    myView.backgroundColor = UIColor.blue
    myView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(myView)

    // Add code for one of the constraint methods below
    // ...
}

Method 1: Anchor Style

myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

Method 2: NSLayoutConstraint Style

NSLayoutConstraint(item: myView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0).isActive = true

Notes

  • Anchor style is the preferred method over NSLayoutConstraint Style, however it is only available from iOS 9, so if you are supporting iOS 8 then you should still use NSLayoutConstraint Style.
  • You will also need to add length and width constraints.
  • My full answer is here.

What is PAGEIOLATCH_SH wait type in SQL Server?

From Microsoft documentation:

PAGEIOLATCH_SH

Occurs when a task is waiting on a latch for a buffer that is in an I/O request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.

In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.

If your query is like this:

Select * from <table> where <col1> = <value> order by <PrimaryKey>

, check that you have a composite index on (col1, col_primary_key).

If you don't have one, then you'll need either a full INDEX SCAN if the PRIMARY KEY is chosen, or a SORT if an index on col1 is chosen.

Both of them are very disk I/O consuming operations on large tables.

How to delete the first row of a dataframe in R?

dat <- dat[-1, ] worked but it killed my dataframe, changing it into another type. Had to instead use dat <- data.frame(dat[-1, ]) but this is possibly a special case as this dataframe initially had only one column.

Difference between thread's context class loader and normal classloader

Each class will use its own classloader to load other classes. So if ClassA.class references ClassB.class then ClassB needs to be on the classpath of the classloader of ClassA, or its parents.

The thread context classloader is the current classloader for the current thread. An object can be created from a class in ClassLoaderC and then passed to a thread owned by ClassLoaderD. In this case the object needs to use Thread.currentThread().getContextClassLoader() directly if it wants to load resources that are not available on its own classloader.

Split page vertically using CSS

Just add overflow:auto; to parent div

<div style="width: 100%;overflow:auto;">
    <div style="float:left; width: 80%">
    </div>
    <div style="float:right;">
    </div>
</div>

Working Demo

How do I use arrays in C++?

Assignment

For no particular reason, arrays cannot be assigned to one another. Use std::copy instead:

#include <algorithm>

// ...

int a[8] = {2, 3, 5, 7, 11, 13, 17, 19};
int b[8];
std::copy(a + 0, a + 8, b);

This is more flexible than what true array assignment could provide because it is possible to copy slices of larger arrays into smaller arrays. std::copy is usually specialized for primitive types to give maximum performance. It is unlikely that std::memcpy performs better. If in doubt, measure.

Although you cannot assign arrays directly, you can assign structs and classes which contain array members. That is because array members are copied memberwise by the assignment operator which is provided as a default by the compiler. If you define the assignment operator manually for your own struct or class types, you must fall back to manual copying for the array members.

Parameter passing

Arrays cannot be passed by value. You can either pass them by pointer or by reference.

Pass by pointer

Since arrays themselves cannot be passed by value, usually a pointer to their first element is passed by value instead. This is often called "pass by pointer". Since the size of the array is not retrievable via that pointer, you have to pass a second parameter indicating the size of the array (the classic C solution) or a second pointer pointing after the last element of the array (the C++ iterator solution):

#include <numeric>
#include <cstddef>

int sum(const int* p, std::size_t n)
{
    return std::accumulate(p, p + n, 0);
}

int sum(const int* p, const int* q)
{
    return std::accumulate(p, q, 0);
}

As a syntactic alternative, you can also declare parameters as T p[], and it means the exact same thing as T* p in the context of parameter lists only:

int sum(const int p[], std::size_t n)
{
    return std::accumulate(p, p + n, 0);
}

You can think of the compiler as rewriting T p[] to T *p in the context of parameter lists only. This special rule is partly responsible for the whole confusion about arrays and pointers. In every other context, declaring something as an array or as a pointer makes a huge difference.

Unfortunately, you can also provide a size in an array parameter which is silently ignored by the compiler. That is, the following three signatures are exactly equivalent, as indicated by the compiler errors:

int sum(const int* p, std::size_t n)

// error: redefinition of 'int sum(const int*, size_t)'
int sum(const int p[], std::size_t n)

// error: redefinition of 'int sum(const int*, size_t)'
int sum(const int p[8], std::size_t n)   // the 8 has no meaning here

Pass by reference

Arrays can also be passed by reference:

int sum(const int (&a)[8])
{
    return std::accumulate(a + 0, a + 8, 0);
}

In this case, the array size is significant. Since writing a function that only accepts arrays of exactly 8 elements is of little use, programmers usually write such functions as templates:

template <std::size_t n>
int sum(const int (&a)[n])
{
    return std::accumulate(a + 0, a + n, 0);
}

Note that you can only call such a function template with an actual array of integers, not with a pointer to an integer. The size of the array is automatically inferred, and for every size n, a different function is instantiated from the template. You can also write quite useful function templates that abstract from both the element type and from the size.

Set SSH connection timeout

The ConnectTimeout option allows you to tell your ssh client how long you're willing to wait for a connection before returning an error. By setting ConnectTimeout to 1, you're effectively saying "try for at most 1 second and then fail if you haven't connected yet".

The problem is that when you connect by name, the DNS lookup can take several seconds. Connecting by IP address is much faster, and may actually work in one second or less. What sinelaw is experiencing is that every attempt to connect by DNS name is failing to occur within one second. The default setting of ConnectTimeout defers to the linux kernel connect timeout, which is usually pretty long.

Change WPF controls from a non-main thread using Dispatcher.Invoke

The first thing is to understand that, the Dispatcher is not designed to run long blocking operation (such as retrieving data from a WebServer...). You can use the Dispatcher when you want to run an operation that will be executed on the UI thread (such as updating the value of a progress bar).

What you can do is to retrieve your data in a background worker and use the ReportProgress method to propagate changes in the UI thread.

If you really need to use the Dispatcher directly, it's pretty simple:

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => this.progressBar.Value = 50));

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

You just need to enter this command:

sudo apt-get install gcc

What is the difference between "SMS Push" and "WAP Push"?

An SMS Push is a message to tell the terminal to initiate the session. This happens because you can't initiate an IP session simply because you don't know the IP Adress of the mobile terminal. Mostly used to send a few lines of data to end recipient, to the effect of sending information, or reminding of events.

WAP Push is an SMS within the header of which is included a link to a WAP address. On receiving a WAP Push, the compatible mobile handset automatically gives the user the option to access the WAP content on his handset. The WAP Push directs the end-user to a WAP address where content is stored ready for viewing or downloading onto the handset. This wap address may be a page or a WAP site.

The user may “take action” by using a developer-defined soft-key to immediately activate an application to accomplish a specific task, such as downloading a picture, making a purchase, or responding to a marketing offer.

How to split CSV files as per number of rows specified?

This should work !!!

file_name = Name of the file you want to split.
10000 = Number of rows each split file would contain
file_part_ = Prefix of split file name (file_part_0,file_part_1,file_part_2..etc goes on)

split -d -l 10000 file_name.csv file_part_

How to retrieve absolute path given relative

The best solution, imho, is the one posted here: https://stackoverflow.com/a/3373298/9724628.

It does require python to work, but it seems to cover all or most of the edge cases and be very portable solution.

  1. With resolving symlinks:
python -c "import os,sys; print(os.path.realpath(sys.argv[1]))" path/to/file
  1. or without it:
python -c "import os,sys; print(os.path.abspath(sys.argv[1]))" path/to/file

Visual Studio 2015 is very slow

Update PC Drivers

In my case, and I had bad lag doing the simplest of things, it helped to update my pc drivers. The system drivers are the foundation for everything.

I was fortunate that I have Dell and they have awesome website support to do this. I googled

dell <my model name> update drivers

or go to the drivers home page

I let it update all the drivers it wanted to (Dell driver update is pretty much automatic).

Much of the lag seems to have gone away.

How do I tell if .NET 3.5 SP1 is installed?

Take a look at this article which shows the registry keys you need to look for and provides a .NET library that will do this for you.

First, you should to determine if .NET 3.5 is installed by looking at HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Install, which is a DWORD value. If that value is present and set to 1, then that version of the Framework is installed.

Look at HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\SP, which is a DWORD value which indicates the Service Pack level (where 0 is no service pack).

To be correct about things, you really need to ensure that .NET Fx 2.0 and .NET Fx 3.0 are installed first and then check to see if .NET 3.5 is installed. If all three are true, then you can check for the service pack level.

Mercurial — revert back to old version and continue from there

The answers above were most useful and I learned a lot. However, for my needs the succinct answer is:

hg revert --all --rev ${1}

hg commit -m "Restoring branch ${1} as default"

where ${1} is the number of the revision or the name of the branch. These two lines are actually part of a bash script, but they work fine on their own if you want to do it manually.

This is useful if you need to add a hot fix to a release branch, but need to build from default (until we get our CI tools right and able to build from branches and later do away with release branches as well).

Setting CSS pseudo-class rules from JavaScript

As already stated this is not something that browsers support.

If you aren't coming up with the styles dynamically (i.e. pulling them out of a database or something) you should be able to work around this by adding a class to the body of the page.

The css would look something like:

a:hover { background: red; }
.theme1 a:hover { background: blue; }

And the javascript to change this would be something like:

// Look up some good add/remove className code if you want to do this
// This is really simplified

document.body.className += " theme1";  

Archive the artifacts in Jenkins

An artifact can be any result of your build process. The important thing is that it doesn't matter on which client it was built it will be tranfered from the workspace back to the master (server) and stored there with a link to the build. The advantage is that it is versionized this way, you only have to setup backup on your master and that all artifacts are accesible via the web interface even if all build clients are offline.

It is possible to define a regular expression as the artifact name. In my case I zipped all the files I wanted to store in one file with a constant name during the build.

SQL Server: combining multiple rows into one row

You can achieve this is to combine For XML Path and STUFF as follows:

SELECT (STUFF((
        SELECT ', ' + StringValue
        FROM Jira.customfieldvalue
        WHERE CUSTOMFIELD = 12534
        AND ISSUE = 19602
        FOR XML PATH('')
        ), 1, 2, '')
    ) AS StringValue

Selenium WebDriver.get(url) does not open the URL

Check your browser version and do the following.

1. Download the Firefox/Chrome webdriver from Google

2. Put the webdriver in Chrome's directory.

Ruby: Easiest Way to Filter Hash Keys?

I had a similar problem, in my case the solution was a one liner which works even if the keys aren't symbols, but you need to have the criteria keys in an array

criteria_array = [:choice1, :choice2]

params.select { |k,v| criteria_array.include?(k) } #=> { :choice1 => "Oh look another one",
                                                         :choice2 => "Even more strings" }

Another example

criteria_array = [1, 2, 3]

params = { 1 => "A String",
           17 => "Oh look, another one",
           25 => "Even more strings",
           49 => "But wait",
           105 => "The last string" }

params.select { |k,v| criteria_array.include?(k) } #=> { 1 => "A String"}

What in the world are Spring beans?

First let us understand Spring:

Spring is a lightweight and flexible framework.

Analogy:
enter image description here

Bean: is an object, which is created, managed and destroyed in Spring Container. We can inject an object into the Spring Container through the metadata(either xml or annotation), which is called inversion of control.

Analogy: Let us assume farmer is having a farmland cultivating by seeds(or beans). Here, Farmer is Spring Framework, Farmland land is Spring Container, Beans are Spring Beans, Cultivating is Spring Processors.

enter image description here

Like bean life-cycle, spring beans too having it's own life-cycle.

enter image description here

enter image description here

img source

Following is sequence of a bean lifecycle in Spring:

  • Instantiate: First the spring container finds the bean’s definition from the XML file and instantiates the bean.

  • Populate properties: Using the dependency injection, spring populates all of the properties as specified in the bean definition.

  • Set Bean Name: If the bean implements BeanNameAware interface, spring passes the bean’s id to setBeanName() method.

  • Set Bean factory: If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.

  • Pre-Initialization: Also called post process of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.

  • Initialize beans: If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called.

  • Post-Initialization: – If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.

  • Ready to use: Now the bean is ready to use by the application

  • Destroy: If the bean implements DisposableBean, it will call the destroy() method

Add multiple items to already initialized arraylist in java

What is the "source" of those integer? If it is something that you need to hard code in your source code, you may do

arList.addAll(Arrays.asList(1,1,2,3,5,8,13,21));

Differences in boolean operators: & vs && and | vs ||

I know there's a lot of answers here, but they all seem a bit confusing. So after doing some research from the Java oracle study guide, I've come up with three different scenarios of when to use && or &. The three scenarios are logical AND, bitwise AND, and boolean AND.

Logical AND: Logical AND (aka Conditional AND) uses the && operator. It's short-circuited meaning: if the left operand is false, then the right operand will not be evaluated.
Example:

int x = 0;
if (false && (1 == ++x) {
    System.out.println("Inside of if");
}
System.out.println(x); // "0"

In the above example the value printed to the console of x will be 0, because the first operand in the if statement is false, hence java has no need to compute (1 == ++x) therefore x will not be computed.

Bitwise AND: Bitwise AND uses the & operator. It's used to preform a bitwise operation on the value. It's much easier to see what's going on by looking at operation on binary numbers ex:

int a = 5;     //                    5 in binary is 0101
int b = 12;    //                   12 in binary is 1100
int c = a & b; // bitwise & preformed on a and b is 0100 which is 4

As you can see in the example, when the binary representations of the numbers 5 and 12 are lined up, then a bitwise AND preformed will only produce a binary number where the same digit in both numbers have a 1. Hence 0101 & 1100 == 0100. Which in decimal is 5 & 12 == 4.

Boolean AND: Now the boolean AND operator behaves similarly and differently to both the bitwise AND and logical AND. I like to think of it as preforming a bitwise AND between two boolean values (or bits), therefore it uses & operator. The boolean values can be the result of a logical expression too.

It returns either a true or false value, much like the logical AND, but unlike the logical AND it is not short-circuited. The reason being, is that for it to preform that bitwise AND, it must know the value of both left and right operands. Here's an ex:

int x = 0;
if (false & (1 == ++x) {
    System.out.println("Inside of if");
}
System.out.println(x); //"1"

Now when that if statement is ran, the expression (1 == ++x) will be executed, even though the left operand is false. Hence the value printed out for x will be 1 because it got incremented.

This also applies to Logical OR (||), bitwise OR (|), and boolean OR (|) Hope this clears up some confusion.

How do I display local image in markdown?

if image has bracket it won't display

![alt text](Isolated(1).png)

rename the image and remove brackets

![alt text](Isolated-1.png)

Update: if you have spaces in the file path, you should consider renaming it too or if you use JavaScript you can encode it using

encodeURIComponent(imagePath)

How to analyze a JMeter summary report?

Sample: Number of requests sent.

The Throughput: is the number of requests per unit of time (seconds, minutes, hours) that are sent to your server during the test.

The Response time: is the elapsed time from the moment when a given request is sent to the server until the moment when the last bit of information has returned to the client.

The throughput is the real load processed by your server during a run but it does not tell you anything about the performance of your server during this same run. This is the reason why you need both measures in order to get a real idea about your server’s performance during a run. The response time tells you how fast your server is handling a given load.

Average: This is the Average (Arithmetic mean µ = 1/n * Si=1…n xi) Response time of your total samples.

Min and Max are the minimum and maximum response time.

An important thing to understand is that the mean value can be very misleading as it does not show you how close (or far) your values are from the average.For this purpose, we need the Deviation value since Average value can be the Same for different response time of the samples!!

Deviation: The standard deviation (s) measures the mean distance of the values to their average (µ).It gives you a good idea of the dispersion or variability of the measures to their mean value.

The following equation show how the standard deviation (s) is calculated:

s = 1/n * v Si=1…n (xi-µ)2

For Details, see here!!

So, if the deviation value is low compared to the mean value, it will indicate you that your measures are not dispersed (or mostly close to the mean value) and that the mean value is significant.

Kb/sec: The throughput measured in Kilobytes per second.

Error % : Percent of requests with errors.

An example is always better to understand!!! I think, this article will help you.

Python Pandas : group by in group by and average?

I would simply do this, which literally follows what your desired logic was:

df.groupby(['org']).mean().groupby(['cluster']).mean()

Are querystring parameters secure in HTTPS (HTTP + SSL)?

The entire transmission, including the query string, the whole URL, and even the type of request (GET, POST, etc.) is encrypted when using HTTPS.

Bootstrap 3 truncate long text inside rows of a table in a responsive way

I did it this way (you need to add a class text to <td> and put the text between a <span>:

HTML

<td class="text"><span>looooooong teeeeeeeeext</span></td>

SASS

.table td.text {
    max-width: 177px;
    span {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        display: inline-block;
        max-width: 100%;
    }
}

CSS equivalent

.table td.text {
    max-width: 177px;
}
.table td.text span {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: inline-block;
    max-width: 100%;
}

And it will still be mobile responsive (forget it with layout=fixed) and will keep the original behaviour.

PS: Of course 177px is a custom size (put whatever you need).

Editing the git commit message in GitHub

No, this is not directly possible. The hash for every Git commit is also calculated based on the commit message. When you change the commit message, you change the commit hash. If you want to push that commit, you have to force that push (git push -f). But if already someone pulled your old commit and started a work based on that commit, he would have to rebase his work onto your new commit.

Angular2 get clicked element id

If you want to have access to the id attribute of the button you can leverage the srcElement property of the event:

import {Component} from 'angular2/core';

@Component({
  selector: 'my-app',
  template: `
    <button (click)="onClick($event)" id="test">Click</button>
  `
})
export class AppComponent {
  onClick(event) {
    var target = event.target || event.srcElement || event.currentTarget;
    var idAttr = target.attributes.id;
    var value = idAttr.nodeValue;
  }
}

See this plunkr: https://plnkr.co/edit/QGdou4?p=preview.

See this question:

Set selected item of spinner programmatically

Use the following: spinnerObject.setSelection(INDEX_OF_CATEGORY2).

How can I resolve the error: "The command [...] exited with code 1"?

I know this is too late for sure, but, this could help someone as well.

In my case, i found that the source file is being used by another process which was restricting from copying to the destination. I found that by using command prompt ( just copy paste the post build command to the command prompt and executed gave me the error info).

Make sure that you can copy from the command prompt,

how to change directory using Windows command line

Just type your desired drive initial in the command line and press enter

Like if you want to go L:\\ drive, Just type L: or l:

How to parse a CSV file in Bash?

We can parse csv files with quoted strings and delimited by say | with following code

while read -r line
do
    field1=$(echo "$line" | awk -F'|' '{printf "%s", $1}' | tr -d '"')
    field2=$(echo "$line" | awk -F'|' '{printf "%s", $2}' | tr -d '"')

    echo "$field1 $field2"
done < "$csvFile"

awk parses the string fields to variables and tr removes the quote.

Slightly slower as awk is executed for each field.

You don't have write permissions for the /var/lib/gems/2.3.0 directory

Reinstalling Compass worked for me.. It's a magic!

sudo gem install -n /usr/local/bin compass

How can I check if a string is a number?

int num;
bool isNumeric = int.TryParse("123", out num);

Can someone provide an example of a $destroy event for scopes in AngularJS?

Demo: http://jsfiddle.net/sunnycpp/u4vjR/2/

Here I have created handle-destroy directive.

ctrl.directive('handleDestroy', function() {
    return function(scope, tElement, attributes) {        
        scope.$on('$destroy', function() {
            alert("In destroy of:" + scope.todo.text);
        });
    };
});

Specifying Style and Weight for Google Fonts

They use regular CSS.

Just use your regular font family like this:

font-family: 'Open Sans', sans-serif;

Now you decide what "weight" the font should have by adding

for semi-bold

font-weight:600;

for bold (700)

font-weight:bold;

for extra bold (800)

font-weight:800;

Like this its fallback proof, so if the google font should "fail" your backup font Arial/Helvetica(Sans-serif) use the same weight as the google font.

Pretty smart :-)

Note that the different font weights have to be specifically imported via the link tag url (family query param of the google font url) in the header.

For example the following link will include both weights 400 and 700:

<link href='fonts.googleapis.com/css?family=Comfortaa:400,700'; rel='stylesheet' type='text/css'>

JavaScript override methods

modify() in your example is a private function, that won't be accessible from anywhere but within your A, B or C definition. You would need to declare it as

this.modify = function(){}

C has no reference to its parents, unless you pass it to C. If C is set up to inherit from A or B, it will inherit its public methods (not its private functions like you have modify() defined). Once C inherits methods from its parent, you can override the inherited methods.

Counter exit code 139 when running, but gdb make it through

this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.

to check either a pointer is initialized or not you can try something like

Class *pointer = new Class();
if(pointer!=nullptr){
    pointer->myFunction();
}

Set style for TextView programmatically

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
    textView.setTextAppearance(R.style.yourStyle)

Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

Having the same issue here. As pointed out by @Izabela Orlowska, this problem is most likely caused by special characters in path (android grandle files, resources etc..).

For me: having in folder name caused all the problems. Make sure you do not have any special characters in paths. Disabling AAPT2 is only a temporary "solution". Your project path contains non-ASCII characters android studio

C# Error: Parent does not contain a constructor that takes 0 arguments

The compiler cannot guess what should be passed for the base constructor argument. You have to do it explicitly:

public class child : parent {
    public child(int i) : base(i) {
        Console.WriteLine("child");
    }
}

Checking host availability by using ping in bash scripts

This seems to work moderately well in a terminal emulator window. It loops until there's a connection then stops.

#!/bin/bash

# ping in a loop until the net is up

declare -i s=0
declare -i m=0
while ! ping -c1 -w2 8.8.8.8 &> /dev/null ;
do
  echo "down" $m:$s
  sleep 10
  s=s+10
  if test $s -ge 60; then
    s=0
    m=m+1;
  fi
done
echo -e "--------->>  UP! (connect a speaker) <<--------" \\a

The \a at the end is trying to get a bel char on connect. I've been trying to do this in LXDE/lxpanel but everything halts until I have a network connection again. Having a time started out as a progress indicator because if you look at a window with just "down" on every line you can't even tell it's moving.

Convert iterator to pointer?

Vector is a template class and it is not safe to convert the contents of a class to a pointer : You cannot inherit the vector class to add this new functionality. and changing the function parameter is actually a better idea. Jst create another vector of int vector temp_foo (foo.begin[X],foo.end()); and pass this vector to you functions

Returning IEnumerable<T> vs. IQueryable<T>

Both will give you deferred execution, yes.

As for which is preferred over the other, it depends on what your underlying datasource is.

Returning an IEnumerable will automatically force the runtime to use LINQ to Objects to query your collection.

Returning an IQueryable (which implements IEnumerable, by the way) provides the extra functionality to translate your query into something that might perform better on the underlying source (LINQ to SQL, LINQ to XML, etc.).

In MS DOS copying several files to one file

for %f in (filenamewildcard0, filenamewildcard1, ...) do echo %f >> newtargetfilename_with_path

Same idea as Mike T; might work better under MessyDog's 127 character command line limit

Counting the number of non-NaN elements in a numpy ndarray in Python

Quick-to-write alterantive

Even though is not the fastest choice, if performance is not an issue you can use:

sum(~np.isnan(data)).

Performance:

In [7]: %timeit data.size - np.count_nonzero(np.isnan(data))
10 loops, best of 3: 67.5 ms per loop

In [8]: %timeit sum(~np.isnan(data))
10 loops, best of 3: 154 ms per loop

In [9]: %timeit np.sum(~np.isnan(data))
10 loops, best of 3: 140 ms per loop

Center HTML Input Text Field Placeholder

The HTML5 placeholder element can be styled for those browsers that accept the element, but in diferent ways, as you can see here: http://davidwalsh.name/html5-placeholder-css.

But I don't believe that text-align will be interpreted by the browsers. At least on Chrome, this attribute is ignored. But you can always change other things, like color, font-size, font-family etc. I suggest you rethinking your design whether possible to remove this center behavior.

EDIT

If you really want this text centered, you can always use some jQuery code or plugin to simulate the placeholder behavior. Here is a sample of it: http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html.

This way the style will work:

input.placeholder {
    text-align: center;
}

How to show a running progress bar while page is loading

I have copied the relevant code below from This page. Hope this might help you.

$.ajax({
  xhr: function() {
    var xhr = new window.XMLHttpRequest();
    //Upload progress
    xhr.upload.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with upload progress
        console.log(percentComplete);
      }
    }, false);
    //Download progress
    xhr.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with download progress
        console.log(percentComplete);
      }
    }, false);
    return xhr;
  },
  type: 'POST',
  url: "/",
  data: {},
  success: function(data) {
    //Do something success-ish
  }
});

How to change a css class style through Javascript?

I'd highly recommend jQuery. It then becomes as simple as:

$('#mydiv').addClass('newclass');

You don't have to worry about removing the old class then as addClass() will only append to it. You also have removeClass();

The other advantage over the getElementById() method is you can apply it to multiple elements at the same time with a single line of code.

$('div').addClass('newclass');
$('.oldclass').addClass('newclass');

The first example will add the class to all DIV elements on the page. The second example will add the new class to all elements that currently have the old class.

ArrayList of String Arrays

List<String[]> addresses = new ArrayList<String[]>();
String[] addressesArr  = new String[3];

addressesArr[0] = "zero";
addressesArr[1] = "one";
addressesArr[2] = "two";

addresses.add(addressesArr);

How to get ID of button user just clicked?

You can also try this simple one-liner code. Just call the alert method on onclick attribute.

<button id="some_id1" onclick="alert(this.id)"></button>

How to locate the git config file in Mac

The global Git configuration file is stored at $HOME/.gitconfig on all platforms.

However, you can simply open a terminal and execute git config, which will write the appropriate changes to this file. You shouldn't need to manually tweak .gitconfig, unless you particularly want to.

Is floating point math broken?

Floating point rounding errors. 0.1 cannot be represented as accurately in base-2 as in base-10 due to the missing prime factor of 5. Just as 1/3 takes an infinite number of digits to represent in decimal, but is "0.1" in base-3, 0.1 takes an infinite number of digits in base-2 where it does not in base-10. And computers don't have an infinite amount of memory.

How to compare times in Python?

Surprised I haven't seen this one liner here:

datetime.datetime.now().hour == 8

How can I show an element that has display: none in a CSS rule?

document.getElementById('mybox').style.display = "block";

Splitting String with delimiter

You can also do:

Integer a = '1182-2'.split('-')[0] as Integer
Integer b = '1182-2'.split('-')[1] as Integer

//a=1182 b=2

How to convert DataTable to class Object?

You may want to have a look at the code here. Although it doesn't answer your question directly you could adapt the generic class types that are used to map between data classes and business objects.

Also by using generic you run the conversion process as quickly as possible.

How to create permanent PowerShell Aliases

2018, Windows 10

You can link to any file or directory with the help of a simple PowerShell script.

Writing a file shortcut script

Open Windows PowerShell ISE. In the script pane write:

New-Alias ${shortcutName} ${fullFileLocation}

Then head to the command-line pane. Find your PowerShell user profile address with echo $profile. Save the script in this address.

enter image description here

The script in PowerShell's profile address will run each time you open powershell. The shortcut should work with every new PowerShell window.

Writing a directory shortcut script

It requires another line in our script.

function ${nameOfFunction} {set-location ${directory_location}}
New-Alias ${shortcut} ${nameOfFunction} 

The rest is exactly the same.

enter image description here

Enable PowerShell Scripts

By default PowerShell scripts are blocked. To enable them, open settings -> Update & Security -> For developers. Select Developer Mode (might require restart). Selecting Developer Mode Windows 10.

Scroll down to the PowerShell section, tick the "Change execution policy ..." option, and apply.

Enabling PowerShell scripts

Pandas read_sql with parameters

The read_sql docs say this params argument can be a list, tuple or dict (see docs).

To pass the values in the sql query, there are different syntaxes possible: ?, :1, :name, %s, %(name)s (see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2 in your case I suppose).

In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2 documentation, they support the %(name)s style (and so not the :name I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:

df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
                     'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
                   db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
                   index_col=['Timestamp'])

RESTful web service - how to authenticate requests from other services?

As far as the client certificate approach goes, it would not be terribly difficult to implement while still allowing the users without client certificates in.

If you did in fact create your own self-signed Certification Authority, and issued client certs to each client service, you would have an easy way of authenticating those services.

Depending on the web server you are using, there should be a method to specify client authentication that will accept a client cert, but does not require one. For example, in Tomcat when specifying your https connector, you can set 'clientAuth=want', instead of 'true' or 'false'. You would then make sure to add your self signed CA certificate to your truststore (by default the cacerts file in the JRE you are using, unless you specified another file in your webserver configuration), so the only trusted certificates would be those issued off of your self signed CA.

On the server side, you would only allow access to the services you wish to protect if you are able to retrieve a client certificate from the request (not null), and passes any DN checks if you prefer any extra security. For the users without client certs, they would still be able to access your services, but will simply have no certificates present in the request.

In my opinion this is the most 'secure' way, but it certainly has its learning curve and overhead, so may not necessarily be the best solution for your needs.

How to drop rows from pandas data frame that contains a particular string in a particular column?

If your string constraint is not just one string you can drop those corresponding rows with:

df = df[~df['your column'].isin(['list of strings'])]

The above will drop all rows containing elements of your list

Difference in make_shared and normal shared_ptr in C++

The shared pointer manages both the object itself, and a small object containing the reference count and other housekeeping data. make_shared can allocate a single block of memory to hold both of these; constructing a shared pointer from a pointer to an already-allocated object will need to allocate a second block to store the reference count.

As well as this efficiency, using make_shared means that you don't need to deal with new and raw pointers at all, giving better exception safety - there is no possibility of throwing an exception after allocating the object but before assigning it to the smart pointer.

git status (nothing to commit, working directory clean), however with changes commited

Delete your .git folder, and reinitialize the git with git init, in my case that's work , because git add command staging the folder and the files in .git folder, if you close CLI after the commit , there will be double folder in staging area that make git system throw this issue.

How to access html form input from asp.net code behind

Since you're using asp.net code-behind, add an id to the element and runat=server.

You can then reference the objects in the code behind.

How to create a table from select query result in SQL Server 2008

Please try:

SELECT * INTO NewTable FROM OldTable

Getting file size in Python?

You may use os.stat() function, which is a wrapper of system call stat():

import os

def getSize(filename):
    st = os.stat(filename)
    return st.st_size

show icon in actionbar/toolbar with AppCompat-v7 21

For Actionbar:

getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeAsUpIndicator(R.drawable.ic_action_back);

For Toolbar:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_action_back);

How to get the selected value from RadioButtonList?

The ASPX code will look something like this:

 <asp:RadioButtonList ID="rblist1" runat="server">

    <asp:ListItem Text ="Item1" Value="1" />
    <asp:ListItem Text ="Item2" Value="2" />
    <asp:ListItem Text ="Item3" Value="3" />
    <asp:ListItem Text ="Item4" Value="4" />

    </asp:RadioButtonList>

    <asp:Button ID="btn1" runat="server" OnClick="Button1_Click" Text="select value" />

And the code behind:

protected void Button1_Click(object sender, EventArgs e)
        {
            string selectedValue = rblist1.SelectedValue;
            Response.Write(selectedValue);
        }

Uncaught TypeError: Cannot read property 'split' of undefined

ogdate is itself a string, why are you trying to access it's value property that it doesn't have ?

console.log(og_date.split('-'));

JSFiddle

Sql Server return the value of identity column after insert statement

Insert into TBL (Name, UserName, Password) Output Inserted.IdentityColumnName
 Values ('example', 'example', 'example')

Switch statement fallthrough in C#?

You forgot to add the "break;" statement into case 3. In case 2 you wrote it into the if block. Therefore try this:

case 3:            
{
    ans += string.Format("{0} hundred and ", numbers[number / 100]);
    break;
}


case 2:            
{
    int t = (number / 10) % 10;            
    if (t == 1)            
    {                
        ans += teens[number % 10];                
    }            
    else if (t > 1)                
    {
        ans += string.Format("{0}-", tens[t]);        
    }
    break;
}

case 1:            
{
    int o = number % 10;            
    ans += numbers[o];            
    break;        
}

default:            
{
    throw new ArgumentException("number");
}

Why does this code using random strings print "hello world"?

From the Java docs, this is an intentional feature when specifying a seed value for the Random class.

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random. Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code.

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Random.html

Odd though, you would think there are implicit security issues in having predictable 'random' numbers.

Angularjs simple file download causes router to redirect

We also had to develop a solution which would even work with APIs requiring authentication (see this article)

Using AngularJS in a nutshell here is how we did it:

Step 1: Create a dedicated directive

// jQuery needed, uses Bootstrap classes, adjust the path of templateUrl
app.directive('pdfDownload', function() {
return {
    restrict: 'E',
    templateUrl: '/path/to/pdfDownload.tpl.html',
    scope: true,
    link: function(scope, element, attr) {
        var anchor = element.children()[0];

        // When the download starts, disable the link
        scope.$on('download-start', function() {
            $(anchor).attr('disabled', 'disabled');
        });

        // When the download finishes, attach the data to the link. Enable the link and change its appearance.
        scope.$on('downloaded', function(event, data) {
            $(anchor).attr({
                href: 'data:application/pdf;base64,' + data,
                download: attr.filename
            })
                .removeAttr('disabled')
                .text('Save')
                .removeClass('btn-primary')
                .addClass('btn-success');

            // Also overwrite the download pdf function to do nothing.
            scope.downloadPdf = function() {
            };
        });
    },
    controller: ['$scope', '$attrs', '$http', function($scope, $attrs, $http) {
        $scope.downloadPdf = function() {
            $scope.$emit('download-start');
            $http.get($attrs.url).then(function(response) {
                $scope.$emit('downloaded', response.data);
            });
        };
    }] 
});

Step 2: Create a template

<a href="" class="btn btn-primary" ng-click="downloadPdf()">Download</a>

Step 3: Use it

<pdf-download url="/some/path/to/a.pdf" filename="my-awesome-pdf"></pdf-download>

This will render a blue button. When clicked, a PDF will be downloaded (Caution: the backend has to deliver the PDF in Base64 encoding!) and put into the href. The button turns green and switches the text to Save. The user can click again and will be presented with a standard download file dialog for the file my-awesome.pdf.

Our example uses PDF files, but apparently you could provide any binary format given it's properly encoded.

How do I compare two Integers?

if (x.equals(y))

This looks like an expensive operation. Are there any hash codes calculated this way?

It is not an expensive operation and no hash codes are calculated. Java does not magically calculate hash codes, equals(...) is just a method call, not different from any other method call.

The JVM will most likely even optimize the method call away (inlining the comparison that takes place inside the method), so this call is not much more expensive than using == on two primitive int values.

Note: Don't prematurely apply micro-optimizations; your assumptions like "this must be slow" are most likely wrong or don't matter, because the code isn't a performance bottleneck.

how to read System environment variable in Spring applicationContext

Thanks to @Yiling. That was a hint.

<bean id="propertyConfigurer"
        class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">

    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="searchSystemEnvironment" value="true" />
    <property name="locations">
        <list>
            <value>file:#{systemEnvironment['FILE_PATH']}/first.properties</value>
            <value>file:#{systemEnvironment['FILE_PATH']}/second.properties</value>
            <value>file:#{systemEnvironment['FILE_PATH']}/third.properties</value>
        </list>
    </property>
</bean>

After this, you should have one environment variable named 'FILE_PATH'. Make sure you restart your terminal/IDE after creating that environment variable.

Drag and drop a DLL to the GAC ("assembly") in windows server 2008 .net 4.0

if you have neccessary .net framework installed. Ex ; .Net 4.0 or .Net 3.5, then you can just copy Gacutil.exe from any of the machine and to the new machine.

1) Open CMD as adminstrator in new server.
2) Traverse to the folder where you copied the Gacutil.exe. For eg - C:\program files.(in my case).
3) Type the below in the cmd prompt and install.

C:\Program Files\gacutil.exe /I dllname

Use HTML5 to resize an image before upload

if any interested I've made a typescript version:

interface IResizeImageOptions {
  maxSize: number;
  file: File;
}
const resizeImage = (settings: IResizeImageOptions) => {
  const file = settings.file;
  const maxSize = settings.maxSize;
  const reader = new FileReader();
  const image = new Image();
  const canvas = document.createElement('canvas');
  const dataURItoBlob = (dataURI: string) => {
    const bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
        atob(dataURI.split(',')[1]) :
        unescape(dataURI.split(',')[1]);
    const mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
    const max = bytes.length;
    const ia = new Uint8Array(max);
    for (var i = 0; i < max; i++) ia[i] = bytes.charCodeAt(i);
    return new Blob([ia], {type:mime});
  };
  const resize = () => {
    let width = image.width;
    let height = image.height;

    if (width > height) {
        if (width > maxSize) {
            height *= maxSize / width;
            width = maxSize;
        }
    } else {
        if (height > maxSize) {
            width *= maxSize / height;
            height = maxSize;
        }
    }

    canvas.width = width;
    canvas.height = height;
    canvas.getContext('2d').drawImage(image, 0, 0, width, height);
    let dataUrl = canvas.toDataURL('image/jpeg');
    return dataURItoBlob(dataUrl);
  };

  return new Promise((ok, no) => {
      if (!file.type.match(/image.*/)) {
        no(new Error("Not an image"));
        return;
      }

      reader.onload = (readerEvent: any) => {
        image.onload = () => ok(resize());
        image.src = readerEvent.target.result;
      };
      reader.readAsDataURL(file);
  })    
};

and here's the javascript result:

var resizeImage = function (settings) {
    var file = settings.file;
    var maxSize = settings.maxSize;
    var reader = new FileReader();
    var image = new Image();
    var canvas = document.createElement('canvas');
    var dataURItoBlob = function (dataURI) {
        var bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
            atob(dataURI.split(',')[1]) :
            unescape(dataURI.split(',')[1]);
        var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
        var max = bytes.length;
        var ia = new Uint8Array(max);
        for (var i = 0; i < max; i++)
            ia[i] = bytes.charCodeAt(i);
        return new Blob([ia], { type: mime });
    };
    var resize = function () {
        var width = image.width;
        var height = image.height;
        if (width > height) {
            if (width > maxSize) {
                height *= maxSize / width;
                width = maxSize;
            }
        } else {
            if (height > maxSize) {
                width *= maxSize / height;
                height = maxSize;
            }
        }
        canvas.width = width;
        canvas.height = height;
        canvas.getContext('2d').drawImage(image, 0, 0, width, height);
        var dataUrl = canvas.toDataURL('image/jpeg');
        return dataURItoBlob(dataUrl);
    };
    return new Promise(function (ok, no) {
        if (!file.type.match(/image.*/)) {
            no(new Error("Not an image"));
            return;
        }
        reader.onload = function (readerEvent) {
            image.onload = function () { return ok(resize()); };
            image.src = readerEvent.target.result;
        };
        reader.readAsDataURL(file);
    });
};

usage is like:

resizeImage({
    file: $image.files[0],
    maxSize: 500
}).then(function (resizedImage) {
    console.log("upload resized image")
}).catch(function (err) {
    console.error(err);
});

or (async/await):

const config = {
    file: $image.files[0],
    maxSize: 500
};
const resizedImage = await resizeImage(config)
console.log("upload resized image")

How to retrieve unique count of a field using Kibana + Elastic Search

Now Kibana 4 allows you to use aggregations. Apart from building a panel like the one that was explained in this answer for Kibana 3, now we can see the number of unique IPs in different periods, that was (IMO) what the OP wanted at the first place.

To build a dashboard like this you should go to Visualize -> Select your Index -> Select a Vertical Bar chart and then in the visualize panel:

  • In the Y axis we want the unique count of IPs (select the field where you stored the IP) and in the X axis we want a date histogram with our timefield.

Building a visualization

  • After pressing the Apply button, we should have a graph that shows the unique count of IP distributed on time. We can change the time interval on the X axis to see the unique IPs hourly/daily...

Final plot

Just take into account that the unique counts are approximate. For more information check also this answer.

How do I make background-size work in IE?

I created jquery.backgroundSize.js: a 1.5K jquery plugin that can be used as a IE8 fallback for "cover" and "contain" values. Have a look at the demo.

Is there a command for formatting HTML in the Atom editor?

  1. Go to "Packages" in atom editor.
  2. Then in "Packages" view choose "Settings View".
  3. Choose "Install Packages/Themes".
  4. Search for "Atom Beautify" and install it.

NVIDIA NVML Driver/library version mismatch

sudo reboot

Rebooting solved it for me.

R - Concatenate two dataframes?

you can use the function

bind_rows(a,b)

from the dplyr library

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

Some of the data processing requirements doesn't need sort at all. Syncsort had made the sorting in Hadoop pluggable. Here is a nice blog from them on sorting. The process of moving the data from the mappers to the reducers is called shuffling, check this article for more information on the same.

Differences between strong and weak in Objective-C

strong and weak, these keywords revolves around Object Ownership in Objective-C

What is object ownership ?

Pointer variables imply ownership of the objects that they point to.

  • When a method (or function) has a local variable that points to an object, that variable is said to own the object being pointed to.
  • When an object has an instance variable that points to another object, the object with the pointer is said to own the object being pointed to.

Anytime a pointer variable points to an object, that object has an owner and will stay alive. This is known as a strong reference.

A variable can optionally not take ownership of an object that it points to. A variable that does not take ownership of an object is known as a weak reference.

Have a look for a detailed explanation here Demystifying @property and attributes

List<T> OrderBy Alphabetical Order

This is a generic sorter. Called with the switch below.

dvm.PagePermissions is a property on my ViewModel of type List T in this case T is a EF6 model class called page_permission.

dvm.UserNameSortDir is a string property on the viewmodel that holds the next sort direction. The one that is actaully used in the view.

switch (sortColumn)
{
    case "user_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.user_name, ref sortDir);
        dvm.UserNameSortDir = sortDir;
        break;
    case "role_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.role_name, ref sortDir);
        dvm.RoleNameSortDir = sortDir;
        break;
    case "page_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.page_name, ref sortDir);
        dvm.PageNameSortDir = sortDir;
        break;
}                 


public List<T> Sort<T,TKey>(List<T> list, Func<T, TKey> sorter, ref string direction)
    {
        if (direction == "asc")
        {
            list = list.OrderBy(sorter).ToList();
            direction = "desc";
        }
        else
        {
            list = list.OrderByDescending(sorter).ToList();
            direction = "asc";
        }
        return list;
    }

How can I use a search engine to search for special characters?

This search engine was made to solve exactly the kind of problem you're having: http://symbolhound.com/

I am the developer of SymbolHound.

How can I plot with 2 different y-axes?

As its name suggests, twoord.plot() in the plotrix package plots with two ordinate axes.

library(plotrix)
example(twoord.plot)

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

forward declaration of a struct in C?

A struct (without a typedef) often needs to (or should) be with the keyword struct when used.

struct A;                      // forward declaration
void function( struct A *a );  // using the 'incomplete' type only as pointer

If you typedef your struct you can leave out the struct keyword.

typedef struct A A;          // forward declaration *and* typedef
void function( A *a );

Note that it is legal to reuse the struct name

Try changing the forward declaration to this in your code:

typedef struct context context;

It might be more readable to do add a suffix to indicate struct name and type name:

typedef struct context_s context_t;

Different between parseInt() and valueOf() in java?

The parse* variations return primitive types and the valueOf versions return Objects. I believe the valueOf versions will also use an internal reference pool to return the SAME object for a given value, not just another instance with the same internal value.

Find all elements on a page whose element ID contains a certain text using jQuery

If you're finding by Contains then it'll be like this

    $("input[id*='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you're finding by Starts With then it'll be like this

    $("input[id^='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you're finding by Ends With then it'll be like this

     $("input[id$='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which id is not a given string

    $("input[id!='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which name contains a given word, delimited by spaces

     $("input[name~='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which id is equal to a given string or starting with that string followed by a hyphen

     $("input[id|='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

How to detect DIV's dimension changed?

ResizeSensor.js is part of a huge library, but I reduced its functionality to THIS:

function ResizeSensor(element, callback)
{
    let zIndex = parseInt(getComputedStyle(element));
    if(isNaN(zIndex)) { zIndex = 0; };
    zIndex--;

    let expand = document.createElement('div');
    expand.style.position = "absolute";
    expand.style.left = "0px";
    expand.style.top = "0px";
    expand.style.right = "0px";
    expand.style.bottom = "0px";
    expand.style.overflow = "hidden";
    expand.style.zIndex = zIndex;
    expand.style.visibility = "hidden";

    let expandChild = document.createElement('div');
    expandChild.style.position = "absolute";
    expandChild.style.left = "0px";
    expandChild.style.top = "0px";
    expandChild.style.width = "10000000px";
    expandChild.style.height = "10000000px";
    expand.appendChild(expandChild);

    let shrink = document.createElement('div');
    shrink.style.position = "absolute";
    shrink.style.left = "0px";
    shrink.style.top = "0px";
    shrink.style.right = "0px";
    shrink.style.bottom = "0px";
    shrink.style.overflow = "hidden";
    shrink.style.zIndex = zIndex;
    shrink.style.visibility = "hidden";

    let shrinkChild = document.createElement('div');
    shrinkChild.style.position = "absolute";
    shrinkChild.style.left = "0px";
    shrinkChild.style.top = "0px";
    shrinkChild.style.width = "200%";
    shrinkChild.style.height = "200%";
    shrink.appendChild(shrinkChild);

    element.appendChild(expand);
    element.appendChild(shrink);

    function setScroll()
    {
        expand.scrollLeft = 10000000;
        expand.scrollTop = 10000000;

        shrink.scrollLeft = 10000000;
        shrink.scrollTop = 10000000;
    };
    setScroll();

    let size = element.getBoundingClientRect();

    let currentWidth = size.width;
    let currentHeight = size.height;

    let onScroll = function()
    {
        let size = element.getBoundingClientRect();

        let newWidth = size.width;
        let newHeight = size.height;

        if(newWidth != currentWidth || newHeight != currentHeight)
        {
            currentWidth = newWidth;
            currentHeight = newHeight;

            callback();
        }

        setScroll();
    };

    expand.addEventListener('scroll', onScroll);
    shrink.addEventListener('scroll', onScroll);
};

How to use it:

let container = document.querySelector(".container");
new ResizeSensor(container, function()
{
    console.log("dimension changed:", container.clientWidth, container.clientHeight);
});

"Could not find a valid gem in any repository" (rubygame and others)

I tried to install a gem which is for JRuby only, running into the same error. Using jruby's command worked then:

jruby -S gem install some_jruby_gem

Set auto height and width in CSS/HTML for different screen sizes

This is what do you want? DEMO. Try to shrink the browser's window and you'll see that the elements will be ordered.

What I used? Flexible Box Model or Flexbox.

Just add the follow CSS classes to your container element (in this case div#container):

flex-init-setup and flex-ppal-setup.

Where:

  1. flex-init-setup means flexbox init setup; and
  2. flex-ppal-setup means flexbox principal setup

Here are the CSS rules:

 .flex-init-setup {
     display: -webkit-box;
     display: -moz-box;
     display: -webkit-flex;
     display: -ms-flexbox;
     display: flex;
 }
 .flex-ppal-setup {
     -webkit-flex-flow: column wrap;
     -moz-flex-flow: column wrap;
     flex-flow: column wrap;
     -webkit-justify-content: center;
     -moz-justify-content: center;
     justify-content: center;
 }

Be good, Leonardo

How can I convince IE to simply display application/json rather than offer to download it?

Above solution was missing thing, and below code should work in every situation:

Windows Registry Editor Version 5.00
;
; Tell IE to open JSON documents in the browser.  
; 25336920-03F9-11cf-8FD0-00AA00686F13 is the CLSID for the "Browse in place" .
;  

[HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00

[HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/x-json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00

[HKEY_CLASSES_ROOT\MIME\Database\Content Type\text/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00

Just save it file json.reg, and run to modify your registry.

Dynamically create an array of strings with malloc

You should assign an array of char pointers, and then, for each pointer assign enough memory for the string:

char **orderedIds;

orderedIds = malloc(variableNumberOfElements * sizeof(char*));
for (int i = 0; i < variableNumberOfElements; i++)
    orderedIds[i] = malloc((ID_LEN+1) * sizeof(char)); // yeah, I know sizeof(char) is 1, but to make it clear...

Seems like a good way to me. Although you perform many mallocs, you clearly assign memory for a specific string, and you can free one block of memory without freeing the whole "string array"

Using a .php file to generate a MySQL dump

_x000D_
_x000D_
global $wpdb;_x000D_
$export_posts = $wpdb->prefix . 'export_posts';_x000D_
$backupFile = $_GET['targetDir'].'export-gallery.sql';_x000D_
$dbhost=DB_HOST;_x000D_
$dbuser=DB_USER;_x000D_
$dbpass=DB_PASSWORD;_x000D_
$db=DB_NAME;_x000D_
$path_to_mysqldump = "D:\xampp_5.6\mysql\bin";_x000D_
$query= "D:\\xampp_5.6\mysql\bin\mysqldump.exe -u$dbuser -p$dbpass $db $export_posts> $backupFile";_x000D_
exec($query);_x000D_
echo $query;
_x000D_
_x000D_
_x000D_

Object comparison in JavaScript

If you work without the JSON library, maybe this will help you out:

Object.prototype.equals = function(b) {
    var a = this;
    for(i in a) {
        if(typeof b[i] == 'undefined') {
            return false;
        }
        if(typeof b[i] == 'object') {
            if(!b[i].equals(a[i])) {
                return false;
            }
        }
        if(b[i] != a[i]) {
            return false;
        }
    }
    for(i in b) {
        if(typeof a[i] == 'undefined') {
            return false;
        }
        if(typeof a[i] == 'object') {
            if(!a[i].equals(b[i])) {
                return false;
            }
        }
        if(a[i] != b[i]) {
            return false;
        }
    }
    return true;
}

var a = {foo:'bar', bar: {blub:'bla'}};
var b = {foo:'bar', bar: {blub:'blob'}};
alert(a.equals(b)); // alert's a false

How to create a simple checkbox in iOS?

On iOS there is the switch UI component instead of a checkbox, look into the UISwitch class. The property on (boolean) can be used to determine the state of the slider and about the saving of its state: That depends on how you save your other stuff already, its just saving a boolean value.

Switching users inside Docker image to a non-root user

You should also be able to do:

apt install sudo

sudo -i -u tomcat

Then you should be the tomcat user. It's not clear which Linux distribution you're using, but this works with Ubuntu 18.04 LTS, for example.

How to run java application by .bat file

If You have jar file then create bat file with:

java -jar NameOfJar.jar

How to set 24-hours format for date on java?

for 12-hours format:

SimpleDateFormat simpleDateFormatArrivals = new SimpleDateFormat("hh:mm", Locale.UK);

for 24-hours format:

SimpleDateFormat simpleDateFormatArrivals = new SimpleDateFormat("HH:mm", Locale.UK);

Hibernate Union alternatives

I have to agree with Vladimir. I too looked into using UNION in HQL and couldn't find a way around it. The odd thing was that I could find (in the Hibernate FAQ) that UNION is unsupported, bug reports pertaining to UNION marked 'fixed', newsgroups of people saying that the statements would be truncated at UNION, and other newsgroups of people reporting it works fine... After a day of mucking with it, I ended up porting my HQL back to plain SQL, but doing it in a View in the database would be a good option. In my case, parts of the query were dynamically generated, so I had to build the SQL in the code instead.

Pandas: drop a level from a multi-level column index?

Another way to drop the index is to use a list comprehension:

df.columns = [col[1] for col in df.columns]

   b  c
0  1  2
1  3  4

This strategy is also useful if you want to combine the names from both levels like in the example below where the bottom level contains two 'y's:

cols = pd.MultiIndex.from_tuples([("A", "x"), ("A", "y"), ("B", "y")])
df = pd.DataFrame([[1,2, 8 ], [3,4, 9]], columns=cols)

   A     B
   x  y  y
0  1  2  8
1  3  4  9

Dropping the top level would leave two columns with the index 'y'. That can be avoided by joining the names with the list comprehension.

df.columns = ['_'.join(col) for col in df.columns]

    A_x A_y B_y
0   1   2   8
1   3   4   9

That's a problem I had after doing a groupby and it took a while to find this other question that solved it. I adapted that solution to the specific case here.

How to write PNG image to string with the PIL?

When you say "I'd like to have number of such images stored in dictionary", it's not clear if this is an in-memory structure or not.

You don't need to do any of this to meek an image in memory. Just keep the image object in your dictionary.

If you're going to write your dictionary to a file, you might want to look at im.tostring() method and the Image.fromstring() function

http://effbot.org/imagingbook/image.htm

im.tostring() => string

Returns a string containing pixel data, using the standard "raw" encoder.

Image.fromstring(mode, size, data) => image

Creates an image memory from pixel data in a string, using the standard "raw" decoder.

The "format" (.jpeg, .png, etc.) only matters on disk when you are exchanging the files. If you're not exchanging files, format doesn't matter.

nvm is not compatible with the npm config "prefix" option:

This error can occur when your NVM installation folder path has a Symbolic Link.

Explanation

The default installation path of NVM is: $HOME/.nvm but your home folder could be a symbolic link for another drive, like my case.

Example, my home folder is a Symbolic Link to aother drive:

/home/myuser -> /bigdrive/myuser

This cause the prefix problem.

Solution

On your startup script (.bashrc or .zshrc or other), change the NVM folder to the direct path.

Ex: NVM_DIR="/bigdrive/myuser/.nvm".

.bashrc

export NVM_DIR="/bigdrive/myuser/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

Get the time difference between two datetimes

The following approach is valid for all cases (difference between dates less than 24 hours and difference greater than 24 hours):

// Defining start and end variables
let start = moment('04/09/2013 15:00:00', 'DD/MM/YYYY hh:mm:ss');
let end   = moment('04/09/2013 14:20:30', 'DD/MM/YYYY hh:mm:ss');

// Getting the difference: hours (h), minutes (m) and seconds (s)
let h  = end.diff(start, 'hours');
let m  = end.diff(start, 'minutes') - (60 * h);
let s  = end.diff(start, 'seconds') - (60 * 60 * h) - (60 * m);

// Formating in hh:mm:ss (appends a left zero when num < 10)
let hh = ('0' + h).slice(-2);
let mm = ('0' + m).slice(-2);
let ss = ('0' + s).slice(-2);

console.log(`${hh}:${mm}:${ss}`); // 00:39:30

How to disable margin-collapsing?

I had similar problem with margin collapse because of parent having position set to relative. Here are list of commands you can use to disable margin collapsing.

HERE IS PLAYGROUND TO TEST

Just try to assign any parent-fix* class to div.container element, or any class children-fix* to div.margin. Pick the one that fits your needs best.

When

  • margin collapsing is disabled, div.absolute with red background will be positioned at the very top of the page.
  • margin is collapsing div.absolute will be positioned at the same Y coordinate as div.margin

_x000D_
_x000D_
html, body { margin: 0; padding: 0; }_x000D_
_x000D_
.container {_x000D_
  width: 100%;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.absolute {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 50px;_x000D_
  right: 50px;_x000D_
  height: 100px;_x000D_
  border: 5px solid #F00;_x000D_
  background-color: rgba(255, 0, 0, 0.5);_x000D_
}_x000D_
_x000D_
.margin {_x000D_
  width: 100%;_x000D_
  height: 20px;_x000D_
  background-color: #444;_x000D_
  margin-top: 50px;_x000D_
  color: #FFF;_x000D_
}_x000D_
_x000D_
/* Here are some examples on how to disable margin _x000D_
   collapsing from within parent (.container) */_x000D_
.parent-fix1 { padding-top: 1px; }_x000D_
.parent-fix2 { border: 1px solid rgba(0,0,0, 0);}_x000D_
.parent-fix3 { overflow: auto;}_x000D_
.parent-fix4 { float: left;}_x000D_
.parent-fix5 { display: inline-block; }_x000D_
.parent-fix6 { position: absolute; }_x000D_
.parent-fix7 { display: flex; }_x000D_
.parent-fix8 { -webkit-margin-collapse: separate; }_x000D_
.parent-fix9:before {  content: ' '; display: table; }_x000D_
_x000D_
/* Here are some examples on how to disable margin _x000D_
   collapsing from within children (.margin) */_x000D_
.children-fix1 { float: left; }_x000D_
.children-fix2 { display: inline-block; }
_x000D_
<div class="container parent-fix1">_x000D_
  <div class="margin children-fix">margin</div>_x000D_
  <div class="absolute"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here is jsFiddle with example you can edit

Webpack not excluding node_modules

If you ran into this issue when using TypeScript, you may need to add skipLibCheck: true in your tsconfig.json file.

Set variable in jinja

Nice shorthand for Multiple variable assignments

{% set label_cls, field_cls = "col-md-7", "col-md-3" %}

How to find the parent element using javascript

Use the change event of the select:

$('#my_select').change(function()
{
   $(this).parents('td').css('background', '#000000');
});

How to calculate Date difference in Hive

datediff(to_date(String timestamp), to_date(String timestamp))

For example:

SELECT datediff(to_date('2019-08-03'), to_date('2019-08-01')) <= 2;

Number prime test in JavaScript

A small suggestion here, why do you want to run the loop for whole n numbers?

If a number is prime it will have 2 factors (1 and number itself). If it's not a prime they will have 1, number itself and more, you need not run the loop till the number, may be you can consider running it till the square root of the number.

You can either do it by euler's prime logic. Check following snippet:

function isPrime(num) {
  var sqrtnum=Math.floor(Math.sqrt(num));
    var prime = num != 1;
    for(var i=2; i<sqrtnum+1; i++) { // sqrtnum+1
        if(num % i == 0) {
            prime = false;
            break;
        }
    }
    return prime;
}

Now the complexity is O(sqrt(n))

For more information Why do we check up to the square root of a prime number to determine if it is prime?

Hope it helps

Access to build environment variables from a groovy script in a Jenkins build step (Windows)

On jenkins 2.x, with groovy plugin 2.0, running SystemGroovyScript I managed to get to build variables, as below:

def build = this.getProperty('binding').getVariable('build')
def listener = this.getProperty('binding').getVariable('listener')
def env = build.getEnvironment(listener)
println env.MY_VARIABLE

If you are using goovy from file, simple System.getenv('MY_VARIABLE') is sufficient

Checking if a collection is null or empty in Groovy

There is indeed a Groovier Way.

if(members){
    //Some work
}

does everything if members is a collection. Null check as well as empty check (Empty collections are coerced to false). Hail Groovy Truth. :)

Angular2 *ngFor in select list, set active based on string from object

Check it out in this demo fiddle, go ahead and change the dropdown or default values in the code.

Setting the passenger.Title with a value that equals to a title.Value should work.

View:

<select [(ngModel)]="passenger.Title">
    <option *ngFor="let title of titleArray" [value]="title.Value">
      {{title.Text}}
    </option>
</select>

TypeScript used:

class Passenger {
  constructor(public Title: string) { };
}
class ValueAndText {
  constructor(public Value: string, public Text: string) { }
}

...
export class AppComponent {
    passenger: Passenger = new Passenger("Lord");

    titleArray: ValueAndText[] = [new ValueAndText("Mister", "Mister-Text"),
                                  new ValueAndText("Lord", "Lord-Text")];

}