Programs & Examples On #Itemscollection

How to use glob() to find files recursively?

Simplified version of Johan Dahlin's answer, without fnmatch.

import os

matches = []
for root, dirnames, filenames in os.walk('src'):
  matches += [os.path.join(root, f) for f in filenames if f[-2:] == '.c']

JavaScript object: access variable property by name as string

You don't need a function for it - simply use the bracket notation:

var side = columns['right'];

This is equal to dot notation, var side = columns.right;, except the fact that right could also come from a variable, function return value, etc., when using bracket notation.

If you NEED a function for it, here it is:

function read_prop(obj, prop) {
    return obj[prop];
}

To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:

var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};

you can access property x of c as follows:

var cx = foo['c']['x']

If a property is undefined, an attempt to reference it will return undefined (not null or false):

foo['c']['q'] === null
// returns false

foo['c']['q'] === false
// returns false

foo['c']['q'] === undefined
// returns true

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

It might be old but in my case, it was because of docker. Hope it will help others.

How do I change an HTML selected option using JavaScript?

You could also change select.options.selectedIndex DOM attribute like this:

_x000D_
_x000D_
function selectOption(index){ _x000D_
  document.getElementById("select_id").options.selectedIndex = index;_x000D_
}
_x000D_
<p>_x000D_
<select id="select_id">_x000D_
  <option selected>first option</option>_x000D_
  <option>second option</option>_x000D_
  <option>third option</option>_x000D_
</select>_x000D_
</p>_x000D_
<p>_x000D_
  <button onclick="selectOption(0);">Select first option</button>_x000D_
  <button onclick="selectOption(1);">Select second option</button>_x000D_
  <button onclick="selectOption(2);">Select third option</button>_x000D_
</p>
_x000D_
_x000D_
_x000D_

How can I save a screenshot directly to a file in Windows?

Of course you could write a program that monitors the clipboard and displays an annoying SaveAs-dialog for every image in the clipboard ;-). I guess you can even find out if the last key pressed was PrintScreen to limit the number of false positives.

While I'm thinking about it.. you could also google for someone who already did exactly that.


EDIT: .. or just wait for someone to post the source here - as just happend :-)

How to use double or single brackets, parentheses, curly braces

  1. A single bracket ([) usually actually calls a program named [; man test or man [ for more info. Example:

    $ VARIABLE=abcdef
    $ if [ $VARIABLE == abcdef ] ; then echo yes ; else echo no ; fi
    yes
    
  2. The double bracket ([[) does the same thing (basically) as a single bracket, but is a bash builtin.

    $ VARIABLE=abcdef
    $ if [[ $VARIABLE == 123456 ]] ; then echo yes ; else echo no ; fi
    no
    
  3. Parentheses (()) are used to create a subshell. For example:

    $ pwd
    /home/user 
    $ (cd /tmp; pwd)
    /tmp
    $ pwd
    /home/user
    

    As you can see, the subshell allowed you to perform operations without affecting the environment of the current shell.

  4. (a) Braces ({}) are used to unambiguously identify variables. Example:

    $ VARIABLE=abcdef
    $ echo Variable: $VARIABLE
    Variable: abcdef
    $ echo Variable: $VARIABLE123456
    Variable:
    $ echo Variable: ${VARIABLE}123456
    Variable: abcdef123456
    

    (b) Braces are also used to execute a sequence of commands in the current shell context, e.g.

    $ { date; top -b -n1 | head ; } >logfile 
    # 'date' and 'top' output are concatenated, 
    # could be useful sometimes to hunt for a top loader )
    
    $ { date; make 2>&1; date; } | tee logfile
    # now we can calculate the duration of a build from the logfile
    

There is a subtle syntactic difference with ( ), though (see bash reference) ; essentially, a semicolon ; after the last command within braces is a must, and the braces {, } must be surrounded by spaces.

split string only on first instance - java

String[] func(String apple){
String[] tmp = new String[2];
for(int i=0;i<apple.length;i++){
   if(apple.charAt(i)=='='){
      tmp[0]=apple.substring(0,i);
      tmp[1]=apple.substring(i+1,apple.length);
      break;
   }
}
return tmp;
}
//returns string_ARRAY_!

i like writing own methods :)

Truncate with condition

As a response to your question: "i want to reset all the data and keep last 30 days inside the table."

you can create an event. Check https://dev.mysql.com/doc/refman/5.7/en/event-scheduler.html

For example:

CREATE EVENT DeleteExpiredLog
ON SCHEDULE EVERY 1 DAY
DO
DELETE FROM log WHERE date < DATE_SUB(NOW(), INTERVAL 30 DAY);

Will run a daily cleanup in your table, keeping the last 30 days data available

http://localhost/ not working on Windows 7. What's the problem?

See the above solutions are very good.But whenever you get this 404 eroor,first see this.I am sure the problem will be solved...

Just go to httpd.conf file by clicking wamp server symbol in bottom right taskbar-Apache->httpd.conf... or c:\\wampt\\bin\\apache\\apache2.2.1\\conf\\httpd.conf and approximate on line no 46 you will find "Listen 80"...just make sure it is written "80" after Listen...if it not then change it to 80...And your problem will be solved...

.append(), prepend(), .after() and .before()

To try and answer your main question:

why would you use .append() rather then .after() or vice verses?

When you are manipulating the DOM with jquery the methods you use depend on the result you want and a frequent use is to replace content.

In replacing content you want to .remove() the content and replace it with new content. If you .remove() the existing tag and then try to use .append() it won't work because the tag itself has been removed, whereas if you use .after(), the new content is added 'outside' the (now removed) tag and isn't affected by the previous .remove().

Select2() is not a function

The issue is quite old, but I'll put some small note as I spent couple of hours today investigating pretty same issue. After I loaded a part of code dynamically select2 couldn't work out on a new selectboxes with an error "$(...).select2 is not a function".

I found that in non-packed select2.js there is a line preventing it to reprocess the main function (in my 3.5.4 version it is in line 45):

if (window.Select2 !== undefined) {
    return;
}

So I just commented it out there and started to use select2.js (instead of minified version).

//if (window.Select2 !== undefined) {
//    return;
//}

And it started to work just fine, of course it now can do the processing several times loosing the performance, but I need it anyhow.

Hope this helps, Vladimir

npm command to uninstall or prune unused packages in Node.js

Note: Recent npm versions do this automatically when package-locks are enabled, so this is not necessary except for removing development packages with the --production flag.


Run npm prune to remove modules not listed in package.json.

From npm help prune:

This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.

Extraneous packages are packages that are not listed on the parent package's dependencies list.

If the --production flag is specified, this command will remove the packages specified in your devDependencies.

How do I tokenize a string sentence in NLTK?

This is actually on the main page of nltk.org:

>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']

git push: permission denied (public key)

This error happened while using Ubuntu Bash on Windows.

I switched to standard windows cmd prompt, and it worked no error.

This is a workaround as it means you probably need to load the ssh private key in ubuntu environment if you want to use ubuntu.

CAST DECIMAL to INT

There's also ROUND() if your numbers don't necessarily always end with .00. ROUND(20.6) will give 21, and ROUND(20.4) will give 20.

Javascript array declaration: new Array(), new Array(3), ['a', 'b', 'c'] create arrays that behave differently

Arrays in JS have two types of properties:

Regular elements and associative properties (which are nothing but objects)

When you define a = new Array(), you are defining an empty array. Note that there are no associative objects yet

When you define b = new Array(2), you are defining an array with two undefined locations.

In both your examples of 'a' and 'b', you are adding associative properties i.e. objects to these arrays.

console.log (a) or console.log(b) prints the array elements i.e. [] and [undefined, undefined] respectively. But since a1/a2 and b1/b2 are associative objects inside their arrays, they can be logged only by console.log(a.a1, a.a2) kind of syntax

Retrieve version from maven pom.xml in code

When using spring boot, this link might be useful: https://docs.spring.io/spring-boot/docs/2.3.x/reference/html/howto.html#howto-properties-and-configuration

With spring-boot-starter-parent you just need to add the following to your application config file:

# get values from pom.xml
[email protected]@

After that the value is available like this:

@Value("${pom.version}")
private String pomVersion;

How can I pass POST parameters in a URL?

This could work if the PHP script generates a form for each entry with hidden fields and the href uses JavaScript to post the form.

How to enable core dump in my Linux C++ program

You need to set ulimit -c. If you have 0 for this parameter a coredump file is not created. So do this: ulimit -c unlimited and check if everything is correct ulimit -a. The coredump file is created when an application has done for example something inappropriate. The name of the file on my system is core.<process-pid-here>.

How to refresh an IFrame using Javascript?

This should help:

document.getElementById('FrameID').contentWindow.location.reload(true);

EDIT: Fixed the object name as per @Joro's comment.

How to save picture to iPhone photo library?

One thing to remember: If you use a callback, make sure that your selector conforms to the following form:

- (void) image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo;

Otherwise, you'll crash with an error such as the following:

[NSInvocation setArgument:atIndex:]: index (2) out of bounds [-1, 1]

Real differences between "java -server" and "java -client"?

IIRC the server VM does more hotspot optimizations at startup so it runs faster but takes a little longer to start and uses more memory. The client VM defers most of the optimization to allow faster startup.

Edit to add: Here's some info from Sun, it's not very specific but will give you some ideas.

How does MySQL CASE work?

CASE is more like a switch statement. It has two syntaxes you can use. The first lets you use any compare statements you want:

CASE 
    WHEN user_role = 'Manager' then 4
    WHEN user_name = 'Tom' then 27
    WHEN columnA <> columnB then 99
    ELSE -1 --unknown
END

The second style is for when you are only examining one value, and is a little more succinct:

CASE user_role
    WHEN 'Manager' then 4
    WHEN 'Part Time' then 7
    ELSE -1 --unknown
END

iptables block access to port 8000 except from IP address

You can always use iptables to delete the rules. If you have a lot of rules, just output them using the following command.

iptables-save > myfile

vi to edit them from the commend line. Just use the "dd" to delete the lines you no longer want.

iptables-restore < myfile and you're good to go.  

REMEMBER THAT IF YOU DON'T CONFIGURE YOUR OS TO SAVE THE RULES TO A FILE AND THEN LOAD THE FILE DURING THE BOOT THAT YOUR RULES WILL BE LOST.

Unable to preventDefault inside passive event listener

In plain JS add { passive: false } as third argument

document.addEventListener('wheel', function(e) {
    e.preventDefault();
    doStuff(e);
}, { passive: false });

Converting map to struct

Hashicorp's https://github.com/mitchellh/mapstructure library does this out of the box:

import "github.com/mitchellh/mapstructure"

mapstructure.Decode(myData, &result)

The second result parameter has to be an address of the struct.

clearInterval() not working

The setInterval method returns an interval ID that you need to pass to clearInterval in order to clear the interval. You're passing a function, which won't work. Here's an example of a working setInterval/clearInterval

var interval_id = setInterval(myMethod,500);
clearInterval(interval_id);

Removing rounded corners from a <select> element in Chrome/Webkit

firefox: 18

.squaredcorners {
    -moz-appearance: none;
}

How to open an existing project in Eclipse?

This is How I do it.

File -> Open Project from File System -> Existing Project in WorkSpace

Can I have multiple background images using CSS?

CSS3 allows this sort of thing and it looks like this:

body {
    background-image: url(images/bgtop.png), url(images/bg.png);
    background-repeat: repeat-x, repeat;
}

The current versions of all the major browsers now support it, however if you need to support IE8 or below, then the best way you can work around it is to have extra divs:

<body>
    <div id="bgTopDiv">
        content here
    </div>
</body>
body{
    background-image: url(images/bg.png);
}
#bgTopDiv{
    background-image: url(images/bgTop.png);
    background-repeat: repeat-x;
}

setting min date in jquery datepicker

$(function () {
    $('#datepicker').datepicker({
        dateFormat: 'yy-mm-dd',
        showButtonPanel: true,
        changeMonth: true,
        changeYear: true,
yearRange: '1999:2012',
        showOn: "button",
        buttonImage: "images/calendar.gif",
        buttonImageOnly: true,
        minDate: new Date(1999, 10 - 1, 25),
        maxDate: '+30Y',
        inline: true
    });
});

Just added year range option. It should solve the problem

Bootstrap 3 Slide in Menu / Navbar on Mobile

Without Plugin, we can do this; bootstrap multi-level responsive menu for mobile phone with slide toggle for mobile:

_x000D_
_x000D_
$('[data-toggle="slide-collapse"]').on('click', function() {_x000D_
  $navMenuCont = $($(this).data('target'));_x000D_
  $navMenuCont.animate({_x000D_
    'width': 'toggle'_x000D_
  }, 350);_x000D_
  $(".menu-overlay").fadeIn(500);_x000D_
});_x000D_
_x000D_
$(".menu-overlay").click(function(event) {_x000D_
  $(".navbar-toggle").trigger("click");_x000D_
  $(".menu-overlay").fadeOut(500);_x000D_
});_x000D_
_x000D_
// if ($(window).width() >= 767) {_x000D_
//     $('ul.nav li.dropdown').hover(function() {_x000D_
//         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
//     }, function() {_x000D_
//         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
//     });_x000D_
_x000D_
//     $('ul.nav li.dropdown-submenu').hover(function() {_x000D_
//         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
//     }, function() {_x000D_
//         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
//     });_x000D_
_x000D_
_x000D_
//     $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
//         event.preventDefault();_x000D_
//         event.stopPropagation();_x000D_
//         $(this).parent().siblings().removeClass('open');_x000D_
//         $(this).parent().toggleClass('open');_x000D_
//         $('b', this).toggleClass("caret caret-up");_x000D_
//     });_x000D_
// }_x000D_
_x000D_
// $(window).resize(function() {_x000D_
//     if( $(this).width() >= 767) {_x000D_
//         $('ul.nav li.dropdown').hover(function() {_x000D_
//             $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
//         }, function() {_x000D_
//             $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
//         });_x000D_
//     }_x000D_
// });_x000D_
_x000D_
var windowWidth = $(window).width();_x000D_
if (windowWidth > 767) {_x000D_
  // $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
  //     event.preventDefault();_x000D_
  //     event.stopPropagation();_x000D_
  //     $(this).parent().siblings().removeClass('open');_x000D_
  //     $(this).parent().toggleClass('open');_x000D_
  //     $('b', this).toggleClass("caret caret-up");_x000D_
  // });_x000D_
_x000D_
  $('ul.nav li.dropdown').hover(function() {_x000D_
    $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
  }, function() {_x000D_
    $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
  });_x000D_
_x000D_
  $('ul.nav li.dropdown-submenu').hover(function() {_x000D_
    $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
  }, function() {_x000D_
    $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
  });_x000D_
_x000D_
_x000D_
  $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
    event.preventDefault();_x000D_
    event.stopPropagation();_x000D_
    $(this).parent().siblings().removeClass('open');_x000D_
    $(this).parent().toggleClass('open');_x000D_
    // $('b', this).toggleClass("caret caret-up");_x000D_
  });_x000D_
}_x000D_
if (windowWidth < 767) {_x000D_
  $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
    event.preventDefault();_x000D_
    event.stopPropagation();_x000D_
    $(this).parent().siblings().removeClass('open');_x000D_
    $(this).parent().toggleClass('open');_x000D_
    // $('b', this).toggleClass("caret caret-up");_x000D_
  });_x000D_
}_x000D_
_x000D_
// $('.dropdown a').append('Some text');
_x000D_
@media only screen and (max-width: 767px) {_x000D_
  #slide-navbar-collapse {_x000D_
    position: fixed;_x000D_
    top: 0;_x000D_
    left: 15px;_x000D_
    z-index: 999999;_x000D_
    width: 280px;_x000D_
    height: 100%;_x000D_
    background-color: #f9f9f9;_x000D_
    overflow: auto;_x000D_
    bottom: 0;_x000D_
    max-height: inherit;_x000D_
  }_x000D_
  .menu-overlay {_x000D_
    display: none;_x000D_
    background-color: #000;_x000D_
    bottom: 0;_x000D_
    left: 0;_x000D_
    opacity: 0.5;_x000D_
    filter: alpha(opacity=50);_x000D_
    /* IE7 & 8 */_x000D_
    position: fixed;_x000D_
    right: 0;_x000D_
    top: 0;_x000D_
    z-index: 49;_x000D_
  }_x000D_
  .navbar-fixed-top {_x000D_
    position: initial !important;_x000D_
  }_x000D_
  .navbar-nav .open .dropdown-menu {_x000D_
    background-color: #ffffff;_x000D_
  }_x000D_
  ul.nav.navbar-nav li {_x000D_
    border-bottom: 1px solid #eee;_x000D_
  }_x000D_
  .navbar-nav .open .dropdown-menu .dropdown-header,_x000D_
  .navbar-nav .open .dropdown-menu>li>a {_x000D_
    padding: 10px 20px 10px 15px;_x000D_
  }_x000D_
}_x000D_
_x000D_
.dropdown-submenu {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.dropdown-submenu .dropdown-menu {_x000D_
  top: 0;_x000D_
  left: 100%;_x000D_
  margin-top: -1px;_x000D_
}_x000D_
_x000D_
li.dropdown a {_x000D_
  display: block;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
li.dropdown>a:before {_x000D_
  content: "\f107";_x000D_
  font-family: FontAwesome;_x000D_
  position: absolute;_x000D_
  right: 6px;_x000D_
  top: 5px;_x000D_
  font-size: 15px;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu>a:before {_x000D_
  content: "\f107";_x000D_
  font-family: FontAwesome;_x000D_
  position: absolute;_x000D_
  right: 6px;_x000D_
  top: 10px;_x000D_
  font-size: 15px;_x000D_
}_x000D_
_x000D_
ul.dropdown-menu li {_x000D_
  border-bottom: 1px solid #eee;_x000D_
}_x000D_
_x000D_
.dropdown-menu {_x000D_
  padding: 0px;_x000D_
  margin: 0px;_x000D_
  border: none !important;_x000D_
}_x000D_
_x000D_
li.dropdown.open {_x000D_
  border-bottom: 0px !important;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu.open {_x000D_
  border-bottom: 0px !important;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu>a {_x000D_
  font-weight: bold !important;_x000D_
}_x000D_
_x000D_
li.dropdown>a {_x000D_
  font-weight: bold !important;_x000D_
}_x000D_
_x000D_
.navbar-default .navbar-nav>li>a {_x000D_
  font-weight: bold !important;_x000D_
  padding: 10px 20px 10px 15px;_x000D_
}_x000D_
_x000D_
li.dropdown>a:before {_x000D_
  content: "\f107";_x000D_
  font-family: FontAwesome;_x000D_
  position: absolute;_x000D_
  right: 6px;_x000D_
  top: 9px;_x000D_
  font-size: 15px;_x000D_
}_x000D_
_x000D_
@media (min-width: 767px) {_x000D_
  li.dropdown-submenu>a {_x000D_
    padding: 10px 20px 10px 15px;_x000D_
  }_x000D_
  li.dropdown>a:before {_x000D_
    content: "\f107";_x000D_
    font-family: FontAwesome;_x000D_
    position: absolute;_x000D_
    right: 3px;_x000D_
    top: 12px;_x000D_
    font-size: 15px;_x000D_
  }_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
  <head>_x000D_
    <title>Bootstrap Example</title>_x000D_
    <meta charset="utf-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <nav class="navbar navbar-default navbar-fixed-top">_x000D_
      <div class="container-fluid">_x000D_
        <!-- Brand and toggle get grouped for better mobile display -->_x000D_
        <div class="navbar-header">_x000D_
          <button type="button" class="navbar-toggle collapsed" data-toggle="slide-collapse" data-target="#slide-navbar-collapse" aria-expanded="false">_x000D_
                    <span class="sr-only">Toggle navigation</span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                </button>_x000D_
          <a class="navbar-brand" href="#">Brand</a>_x000D_
        </div>_x000D_
        <!-- Collect the nav links, forms, and other content for toggling -->_x000D_
        <div class="collapse navbar-collapse" id="slide-navbar-collapse">_x000D_
          <ul class="nav navbar-nav">_x000D_
            <li><a href="#">Link <span class="sr-only">(current)</span></a></li>_x000D_
            <li><a href="#">Link</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</span></a>_x000D_
              <ul class="dropdown-menu">_x000D_
                <li><a href="#">Action</a></li>_x000D_
                <li><a href="#">Another action</a></li>_x000D_
                <li><a href="#">Something else here</a></li>_x000D_
                <li><a href="#">Separated link</a></li>_x000D_
                <li><a href="#">One more separated link</a></li>_x000D_
                <li class="dropdown-submenu">_x000D_
                  <a href="#" data-toggle="dropdown">SubMenu 1</span></a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li class="dropdown-submenu">_x000D_
                      <a href="#" data-toggle="dropdown">SubMenu 2</span></a>_x000D_
                      <ul class="dropdown-menu">_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                      </ul>_x000D_
                    </li>_x000D_
                  </ul>_x000D_
                </li>_x000D_
              </ul>_x000D_
            </li>_x000D_
            <li><a href="#">Link</a></li>_x000D_
          </ul>_x000D_
          <ul class="nav navbar-nav navbar-right">_x000D_
            <li><a href="#">Link</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</span></a>_x000D_
              <ul class="dropdown-menu">_x000D_
                <li><a href="#">Action</a></li>_x000D_
                <li><a href="#">Another action</a></li>_x000D_
                <li><a href="#">Something else here</a></li>_x000D_
                <li><a href="#">Separated link</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <!-- /.navbar-collapse -->_x000D_
      </div>_x000D_
      <!-- /.container-fluid -->_x000D_
    </nav>_x000D_
    <div class="menu-overlay"></div>_x000D_
    <div class="col-md-12">_x000D_
      <h1>Resize the window to see the result</h1>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
    </div>_x000D_
_x000D_
  </body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Reference JS fiddle

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?

LINQ-to-SQL is a remarkable piece of technology that is very simple to use, and by and large generates very good queries to the back end. LINQ-to-EF was slated to supplant it, but historically has been extremely clunky to use and generated far inferior SQL. I don't know the current state of affairs, but Microsoft promised to migrate all the goodness of L2S into L2EF, so maybe it's all better now.

Personally, I have a passionate dislike of ORM tools (see my diatribe here for the details), and so I see no reason to favour L2EF, since L2S gives me all I ever expect to need from a data access layer. In fact, I even think that L2S features such as hand-crafted mappings and inheritance modeling add completely unnecessary complexity. But that's just me. ;-)

Getting parts of a URL (Regex)

I tried a few of these that didn't cover my needs, especially the highest voted which didn't catch a url without a path (http://example.com/)

also lack of group names made it unusable in ansible (or perhaps my jinja2 skills are lacking).

so this is my version slightly modified with the source being the highest voted version here:

^((?P<protocol>http[s]?|ftp):\/)?\/?(?P<host>[^:\/\s]+)(?P<path>((\/\w+)*\/)([\w\-\.]+[^#?\s]+))*(.*)?(#[\w\-]+)?$

Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

gcc actually can do this optimization, even for floating-point numbers. For example,

double foo(double a) {
  return a*a*a*a*a*a;
}

becomes

foo(double):
    mulsd   %xmm0, %xmm0
    movapd  %xmm0, %xmm1
    mulsd   %xmm0, %xmm1
    mulsd   %xmm1, %xmm0
    ret

with -O -funsafe-math-optimizations. This reordering violates IEEE-754, though, so it requires the flag.

Signed integers, as Peter Cordes pointed out in a comment, can do this optimization without -funsafe-math-optimizations since it holds exactly when there is no overflow and if there is overflow you get undefined behavior. So you get

foo(long):
    movq    %rdi, %rax
    imulq   %rdi, %rax
    imulq   %rdi, %rax
    imulq   %rax, %rax
    ret

with just -O. For unsigned integers, it's even easier since they work mod powers of 2 and so can be reordered freely even in the face of overflow.

How to pass arguments to entrypoint in docker-compose.yml

The command clause does work as @Karthik says above.

As a simple example, the following service will have a -inMemory added to its ENTRYPOINT when docker-compose up is run.

version: '2'
services:
  local-dynamo:
    build: local-dynamo
    image: spud/dynamo
    command: -inMemory

Difference between float and decimal data type

float (and double) represents binary fractions

decimal represents decimal fractions

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

As of October 3, 2012, a new "Elastic Beanstalk for Java with Apache Tomcat 7" Linux x64 AMI deployed with the Sample Application has the install here:

/etc/tomcat7/

The /etc/tomcat7/tomcat7.conf file has the following settings:

# Where your java installation lives
JAVA_HOME="/usr/lib/jvm/jre"

# Where your tomcat installation lives
CATALINA_BASE="/usr/share/tomcat7"
CATALINA_HOME="/usr/share/tomcat7"
JASPER_HOME="/usr/share/tomcat7"
CATALINA_TMPDIR="/var/cache/tomcat7/temp"

How to quickly check if folder is empty (.NET)?

I'm not aware of a method that will succinctly tell you if a given folder contains any other folders or files, however, using:

Directory.GetFiles(path);
&
Directory.GetDirectories(path);

should help performance since both of these methods will only return an array of strings with the names of the files/directories rather than entire FileSystemInfo objects.

How to extract or unpack an .ab file (Android Backup file)

I have had to unpack a .ab-file, too and found this post while looking for an answer. My suggested solution is Android Backup Extractor, a free Java tool for Windows, Linux and Mac OS.

Make sure to take a look at the README, if you encounter a problem. You might have to download further files, if your .ab-file is password-protected.

Usage:
java -jar abe.jar [-debug] [-useenv=yourenv] unpack <backup.ab> <backup.tar> [password]

Example:

Let's say, you've got a file test.ab, which is not password-protected, you're using Windows and want the resulting .tar-Archive to be called test.tar. Then your command should be:

java.exe -jar abe.jar unpack test.ab test.tar ""

Rounding numbers to 2 digits after comma

Previous answers forgot to type the output as an Number again. There is several ways to do this, depending on your tastes.

+my_float.toFixed(2)

Number(my_float.toFixed(2))

parseFloat(my_float.toFixed(2))

How to use vim in the terminal?

Run vim from the terminal. For the basics, you're advised to run the command vimtutor.

# On your terminal command line:
$ vim

If you have a specific file to edit, pass it as an argument.

$ vim yourfile.cpp

Likewise, launch the tutorial

$ vimtutor

How do you replace double quotes with a blank space in Java?

Strings are immutable, so you need to say

sInputString = sInputString("\"","");

not just the right side of the =

"android.view.WindowManager$BadTokenException: Unable to add window" on buider.show()

I am creating Dialog in onCreate and using it with show and hide. For me the root cause was not dismissing onBackPressed, which was finishing the Home activity.

@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
                .setTitle("Really Exit?")
                .setMessage("Are you sure you want to exit?")
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                Home.this.finish();
                                return;
                            }
                        }).create().show();

I was finishing the Home Activity onBackPressed without closing / dismissing my dialogs.

When I dismissed my dialogs the crash disappeared.

new AlertDialog.Builder(this)
                .setTitle("Really Exit?")
                .setMessage("Are you sure you want to exit?")
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                networkErrorDialog.dismiss() ;
                                homeLocationErrorDialog.dismiss() ;
                                currentLocationErrorDialog.dismiss() ;
                                Home.this.finish();
                                return;
                            }
                        }).create().show();

How do I copy a range of formula values and paste them to a specific range in another sheet?

You can change

Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)

to

Range("B3:B65536").Copy 
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues

BTW, if you have xls file (excel 2003), you would get an error if your lastrow would be greater 3.

Try to use this code instead:

Sub Get_Data()
    Dim lastrowDB As Long, lastrow As Long
    Dim arr1, arr2, i As Integer

    With Sheets("DB")
        lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
    End With

    arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
    arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")

    For i = LBound(arr1) To UBound(arr1)
        With Sheets("Sheet1")
             lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
             .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
             Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
        End With
    Next
    Application.CutCopyMode = False
End Sub

Note, above code determines last non empty row on DB sheet in column A (variable lastrowDB). If you need to find lastrow for each destination column in DB sheet, use next modification:

For i = LBound(arr1) To UBound(arr1)
   With Sheets("DB")
       lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
   End With

   ' NEXT CODE

Next

You could also use next approach instead Copy/PasteSpecial. Replace

.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues

with

Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
      .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value

Trim Whitespaces (New Line and Tab space) in a String in Oracle

If at all anyone is looking to convert data in 1 variable that lies in 2 or 3 different lines like below

'Data1

Data2'

And you want to display data as 'Data1 Data2' then use below

select TRANSLATE ('Data1

Data2', ''||CHR(10), ' ') from dual;

it took me hrs to get the right output. Thanks to me I just saved you 1 or 2 hrs :)

How to connect to SQL Server from another computer?

If you want to connect to SQL server remotly you need to use a software - like Sql Server Management studio.

The computers doesn't need to be on the same network - but they must be able to connect each other using a communication protocol like tcp/ip, and the server must be set up to support incoming connection of the type you choose.

if you want to connect to another computer (to browse files ?) you use other tools, and not sql server (you can map a drive and access it through there ect...)

To Enable SQL connection using tcp/ip read this article:

For Sql Express: express For Sql 2008: 2008

Make sure you enable access through the machine firewall as well.

You might need to install either SSMS or Toad on the machine your using to connect to the server. both you can download from their's company web site.

Re-ordering columns in pandas dataframe based on column name

Don't forget to add "inplace=True" to Wes' answer or set the result to a new DataFrame.

df.sort_index(axis=1, inplace=True)

How to match a line not containing a word

This should work:

/^((?!PART).)*$/

If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:

/^(?!PART)/

Edit (by request): Why this pattern works

The (?!...) syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /PART/." The site I've linked explains this far better than I can, but I'll try to break this down:

^         #Start matching from the beginning of the string.    
(?!PART)  #This position must not be followed by the string "PART".
.         #Matches any character except line breaks (it will include those in single-line mode).
$         #Match all the way until the end of the string.

The ((?!xxx).)* idiom is probably hardest to understand. As we saw, (?!PART) looks at the string ahead and says that whatever comes next can't match the subpattern /PART/. So what we're doing with ((?!xxx).)* is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.

The ^ and $ anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.

Since we do have ^ and $, if PART were anywhere in the string, one of the characters would match (?=PART). and the overall match would fail. Hope that's clear enough to be helpful.

How to comment multiple lines with space or indent

I was able to achieve the desired result by using Alt + Shift + up/down and then typing the desired comment characters and additional character.

Modifying a file inside a jar

You can use the u option for jar

From the Java Tutorials:

jar uf jar-file input-file(s)

"Any files already in the archive having the same pathname as a file being added will be overwritten."

See Updating a JAR File.

Much better than making the whole jar all over again. Invoking this from within your program sounds possible too. Try Running Command Line in Java

Detecting Windows or Linux?

You can use "system.properties.os", for example:

public class GetOs {

  public static void main (String[] args) {
    String s = 
      "name: " + System.getProperty ("os.name");
    s += ", version: " + System.getProperty ("os.version");
    s += ", arch: " + System.getProperty ("os.arch");
    System.out.println ("OS=" + s);
  }
}

// EXAMPLE OUTPUT: OS=name: Windows 7, version: 6.1, arch: amd64

Here are more details:

HashSet vs. List performance

The answer, as always, is "It depends". I assume from the tags you're talking about C#.

Your best bet is to determine

  1. A Set of data
  2. Usage requirements

and write some test cases.

It also depends on how you sort the list (if it's sorted at all), what kind of comparisons need to be made, how long the "Compare" operation takes for the particular object in the list, or even how you intend to use the collection.

Generally, the best one to choose isn't so much based on the size of data you're working with, but rather how you intend to access it. Do you have each piece of data associated with a particular string, or other data? A hash based collection would probably be best. Is the order of the data you're storing important, or are you going to need to access all of the data at the same time? A regular list may be better then.

Additional:

Of course, my above comments assume 'performance' means data access. Something else to consider: what are you looking for when you say "performance"? Is performance individual value look up? Is it management of large (10000, 100000 or more) value sets? Is it the performance of filling the data structure with data? Removing data? Accessing individual bits of data? Replacing values? Iterating over the values? Memory usage? Data copying speed? For example, If you access data by a string value, but your main performance requirement is minimal memory usage, you might have conflicting design issues.

How do I create a unique constraint that also allows nulls?

When I applied the unique index below:

CREATE UNIQUE NONCLUSTERED INDEX idx_badgeid_notnull
ON employee(badgeid)
WHERE badgeid IS NOT NULL;

every non null update and insert failed with the error below:

UPDATE failed because the following SET options have incorrect settings: 'ARITHABORT'.

I found this on MSDN

SET ARITHABORT must be ON when you are creating or changing indexes on computed columns or indexed views. If SET ARITHABORT is OFF, CREATE, UPDATE, INSERT, and DELETE statements on tables with indexes on computed columns or indexed views will fail.

So to get this to work correctly I did this

Right click [Database]-->Properties-->Options-->Other Options-->Misscellaneous-->Arithmetic Abort Enabled -->true

I believe it is possible to set this option in code using

ALTER DATABASE "DBNAME" SET ARITHABORT ON

but i have not tested this

twitter-bootstrap: how to get rid of underlined button text when hovering over a btn-group within an <a>-tag?

Try putting anchor tag inside and adding a{display:block;}....it will work fine

A JOIN With Additional Conditions Using Query Builder or Eloquent

I am using laravel5.2 and we can add joins with different options, you can modify as per your requirement.

Option 1:    
    DB::table('users')
            ->join('contacts', function ($join) {
                $join->on('users.id', '=', 'contacts.user_id')->orOn(...);//you add more joins here
            })// and you add more joins here
        ->get();

Option 2:
    $users = DB::table('users')
        ->join('contacts', 'users.id', '=', 'contacts.user_id')
        ->join('orders', 'users.id', '=', 'orders.user_id')// you may add more joins
        ->select('users.*', 'contacts.phone', 'orders.price')
        ->get();

option 3:
    $users = DB::table('users')
        ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
        ->leftJoin('...', '...', '...', '...')// you may add more joins
        ->get();

Maven Java EE Configuration Marker with Java Server Faces 1.2

Eclipse is buggy on factes screen and at times doesn't update the config files in workspace. There are two options one can try :

  1. Go to org.eclipse.wst.common.project.facet.core.xml file located inside .settings folder of eclipse project. Go and manually delete the JSF facet entry. you can also update other facets as well.

  2. Right click project and go to properties->Maven-->Java EE Integeration. choose options : enable project specific settings, Enable Java EE configuration, Maven archiver generates files under the build directory

How to call a VbScript from a Batch File without opening an additional command prompt

If you want to fix vbs associations type

regsvr32 vbscript.dll
regsvr32 jscript.dll
regsvr32 wshext.dll
regsvr32 wshom.ocx
regsvr32 wshcon.dll
regsvr32 scrrun.dll

Also if you can't use vbs due to management then convert your script to a vb.net program which is designed to be easy, is easy, and takes 5 minutes.

Big difference is functions and subs are both called using brackets rather than just functions.

So the compilers are installed on all computers with .NET installed.

See this article here on how to make a .NET exe. Note the sample is for a scripting host. You can't use this, you have to put your vbs code in as .NET code.

How can I convert a VBScript to an executable (EXE) file?

AngularJS sorting by property

The following allows for the ordering of objects by key OR by a key within an object.

In template you can do something like:

    <li ng-repeat="(k,i) in objectList | orderObjectsBy: 'someKey'">

Or even:

    <li ng-repeat="(k,i) in objectList | orderObjectsBy: 'someObj.someKey'">

The filter:

app.filter('orderObjectsBy', function(){
 return function(input, attribute) {
    if (!angular.isObject(input)) return input;

    // Filter out angular objects.
    var array = [];
    for(var objectKey in input) {
      if (typeof(input[objectKey])  === "object" && objectKey.charAt(0) !== "$")
        array.push(input[objectKey]);
    }

    var attributeChain = attribute.split(".");

    array.sort(function(a, b){

      for (var i=0; i < attributeChain.length; i++) {
        a = (typeof(a) === "object") && a.hasOwnProperty( attributeChain[i]) ? a[attributeChain[i]] : 0;
        b = (typeof(b) === "object") && b.hasOwnProperty( attributeChain[i]) ? b[attributeChain[i]] : 0;
      }

      return parseInt(a) - parseInt(b);
    });

    return array;
 }
})

Convert UTC/GMT time to local time

Don't forget if you already have a DateTime object and are not sure if it's UTC or Local, it's easy enough to use the methods on the object directly:

DateTime convertedDate = DateTime.Parse(date);
DateTime localDate = convertedDate.ToLocalTime();

How do we adjust for the extra hour?

Unless specified .net will use the local pc settings. I'd have a read of: http://msdn.microsoft.com/en-us/library/system.globalization.daylighttime.aspx

By the looks the code might look something like:

DaylightTime daylight = TimeZone.CurrentTimeZone.GetDaylightChanges( year );

And as mentioned above double check what timezone setting your server is on. There are articles on the net for how to safely affect the changes in IIS.

Change image source in code behind - Wpf

You are all wrong! Why? Because all you need is this code to work:

(image View) / C# Img is : your Image box

Keep this as is, without change ("ms-appx:///) this is code not your app name Images is your folder in your project you can change it. dog.png is your file in your folder, as well as i do my folder 'Images' and file 'dog.png' So the uri is :"ms-appx:///Images/dog.png" and my code :


private void Button_Click(object sender, RoutedEventArgs e)
    {
         img.Source = new BitmapImage(new Uri("ms-appx:///Images/dog.png"));
    }

Any way (or shortcut) to auto import the classes in IntelliJ IDEA like in Eclipse?

Seems like IntelliJ IDEA will import missed class automatically, and you can import them by hit Alt + Enter manually.

How to create file object from URL object (image)

In order to create a File from a HTTP URL you need to download the contents from that URL:

URL url = new URL("http://www.google.ro/logos/2011/twain11-hp-bg.jpg");
URLConnection connection = url.openConnection();
InputStream in = connection.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("downloaded.jpg"));
byte[] buf = new byte[512];
while (true) {
    int len = in.read(buf);
    if (len == -1) {
        break;
    }
    fos.write(buf, 0, len);
}
in.close();
fos.flush();
fos.close();

The downloaded file will be found at the root of your project: {project}/downloaded.jpg

Finding all possible combinations of numbers to reach a given sum

Perl version (of the leading answer):

use strict;

sub subset_sum {
  my ($numbers, $target, $result, $sum) = @_;

  print 'sum('.join(',', @$result).") = $target\n" if $sum == $target;
  return if $sum >= $target;

  subset_sum([@$numbers[$_ + 1 .. $#$numbers]], $target, 
             [@{$result||[]}, $numbers->[$_]], $sum + $numbers->[$_])
    for (0 .. $#$numbers);
}

subset_sum([3,9,8,4,5,7,10,6], 15);

Result:

sum(3,8,4) = 15
sum(3,5,7) = 15
sum(9,6) = 15
sum(8,7) = 15
sum(4,5,6) = 15
sum(5,10) = 15

Javascript version:

_x000D_
_x000D_
const subsetSum = (numbers, target, partial = [], sum = 0) => {_x000D_
  if (sum < target)_x000D_
    numbers.forEach((num, i) =>_x000D_
      subsetSum(numbers.slice(i + 1), target, partial.concat([num]), sum + num));_x000D_
  else if (sum == target)_x000D_
    console.log('sum(%s) = %s', partial.join(), target);_x000D_
}_x000D_
_x000D_
subsetSum([3,9,8,4,5,7,10,6], 15);
_x000D_
_x000D_
_x000D_

Javascript one-liner that actually returns results (instead of printing it):

_x000D_
_x000D_
const subsetSum=(n,t,p=[],s=0,r=[])=>(s<t?n.forEach((l,i)=>subsetSum(n.slice(i+1),t,[...p,l],s+l,r)):s==t?r.push(p):0,r);_x000D_
_x000D_
console.log(subsetSum([3,9,8,4,5,7,10,6], 15));
_x000D_
_x000D_
_x000D_

And my favorite, one-liner with callback:

_x000D_
_x000D_
const subsetSum=(n,t,cb,p=[],s=0)=>s<t?n.forEach((l,i)=>subsetSum(n.slice(i+1),t,cb,[...p,l],s+l)):s==t?cb(p):0;_x000D_
_x000D_
subsetSum([3,9,8,4,5,7,10,6], 15, console.log);
_x000D_
_x000D_
_x000D_

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

I actually ended up with something like this to allow for the navbar collapse.

@media (min-width: 768px) { //set this to wherever the navbar collapse executes
  .navbar-nav > li > a{
    line-height: 7em; //set this height to the height of the logo.
  }
}

Reading tab-delimited file with Pandas - works on Windows, but not on Mac

Another option would be to add engine='python' to the command pandas.read_csv(filename, sep='\t', engine='python')

When do you use map vs flatMap in RxJava?

In some cases you might end up having chain of observables, wherein your observable would return another observable. 'flatmap' kind of unwraps the second observable which is buried in the first one and let you directly access the data second observable is spitting out while subscribing.

How can I change IIS Express port for a site

Another fix for those who have IIS Installed:

Create a path on the IIS Server, and allocate your website/app there.

Go to propieties of the solution of the explorer, then in front of using the iisexpress from visual studio, make that vs uses your personal own IIS.

Solution Proprieties

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

Complementing @Bob Jarvis and @dmikam answer, Postgres don't perform a good plan when you don't use LATERAL, below a simulation, in both cases the query data results are the same, but the cost are very different

Table structure

CREATE TABLE ITEMS (
    N INTEGER NOT NULL,
    S TEXT NOT NULL
);

INSERT INTO ITEMS
  SELECT
    (random()*1000000)::integer AS n,
    md5(random()::text) AS s
  FROM
    generate_series(1,1000000);

CREATE INDEX N_INDEX ON ITEMS(N);

Performing JOIN with GROUP BY in subquery without LATERAL

EXPLAIN 
SELECT 
    I.*
FROM ITEMS I
INNER JOIN (
    SELECT 
        COUNT(1), n
    FROM ITEMS
    GROUP BY N
) I2 ON I2.N = I.N
WHERE I.N IN (243477, 997947);

The results

Merge Join  (cost=0.87..637500.40 rows=23 width=37)
  Merge Cond: (i.n = items.n)
  ->  Index Scan using n_index on items i  (cost=0.43..101.28 rows=23 width=37)
        Index Cond: (n = ANY ('{243477,997947}'::integer[]))
  ->  GroupAggregate  (cost=0.43..626631.11 rows=861418 width=12)
        Group Key: items.n
        ->  Index Only Scan using n_index on items  (cost=0.43..593016.93 rows=10000000 width=4)

Using LATERAL

EXPLAIN 
SELECT 
    I.*
FROM ITEMS I
INNER JOIN LATERAL (
    SELECT 
        COUNT(1), n
    FROM ITEMS
    WHERE N = I.N
    GROUP BY N
) I2 ON 1=1 --I2.N = I.N
WHERE I.N IN (243477, 997947);

Results

Nested Loop  (cost=9.49..1319.97 rows=276 width=37)
  ->  Bitmap Heap Scan on items i  (cost=9.06..100.20 rows=23 width=37)
        Recheck Cond: (n = ANY ('{243477,997947}'::integer[]))
        ->  Bitmap Index Scan on n_index  (cost=0.00..9.05 rows=23 width=0)
              Index Cond: (n = ANY ('{243477,997947}'::integer[]))
  ->  GroupAggregate  (cost=0.43..52.79 rows=12 width=12)
        Group Key: items.n
        ->  Index Only Scan using n_index on items  (cost=0.43..52.64 rows=12 width=4)
              Index Cond: (n = i.n)

My Postgres version is PostgreSQL 10.3 (Debian 10.3-1.pgdg90+1)

What is the best regular expression to check if a string is a valid URL?

This will match all URLs

  • with or without http/https
  • with or without www

...including sub-domains and those new top-level domain name extensions such as .museum, .academy, .foundation etc. which can have up to 63 characters (not just .com, .net, .info etc.)

(([\w]+:)?//)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,63}(:[\d]+)?(/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?

Because today maximum length of the available top-level domain name extension is 13 characters such as .international, you can change the number 63 in expression to 13 to prevent someone misusing it.

as javascript

_x000D_
_x000D_
var urlreg=/(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,63}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?/;_x000D_
_x000D_
$('textarea').on('input',function(){_x000D_
  var url = $(this).val();_x000D_
  $(this).toggleClass('invalid', urlreg.test(url) == false)_x000D_
});_x000D_
_x000D_
$('textarea').trigger('input');
_x000D_
textarea{color:green;}_x000D_
.invalid{color:red;}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea>http://www.google.com</textarea>_x000D_
<textarea>http//www.google.com</textarea>_x000D_
<textarea>googlecom</textarea>_x000D_
<textarea>https://www.google.com</textarea>
_x000D_
_x000D_
_x000D_

Wikipedia Article: List of all internet top-level domains

MySQL Orderby a number, Nulls last

For a DATE column you can use:


NULLS last:

ORDER BY IFNULL(`myDate`, '9999-12-31') ASC

Blanks last:

ORDER BY IF(`myDate` = '', '9999-12-31', `myDate`) ASC

Generate fixed length Strings filled with whitespaces

This code will have exactly the given amount of characters; filled with spaces or truncated on the right side:

private String leftpad(String text, int length) {
    return String.format("%" + length + "." + length + "s", text);
}

private String rightpad(String text, int length) {
    return String.format("%-" + length + "." + length + "s", text);
}

Passing multiple values to a single PowerShell script parameter

One way to do it would be like this:

 param(
       [Parameter(Position=0)][String]$Vlan,
       [Parameter(ValueFromRemainingArguments=$true)][String[]]$Hosts
    ) ...

This would allow multiple hosts to be entered with spaces.

Prevent textbox autofill with previously entered values

For firefox

Either:

<asp:TextBox id="Textbox1" runat="server" autocomplete="off"></asp:TextBox>

Or from the CodeBehind:

Textbox1.Attributes.Add("autocomplete", "off");

Ruby class instance variable vs. class variable

Instance variable on a class:

class Parent
  @things = []
  def self.things
    @things
  end
  def things
    self.class.things
  end
end

class Child < Parent
  @things = []
end

Parent.things << :car
Child.things  << :doll
mom = Parent.new
dad = Parent.new

p Parent.things #=> [:car]
p Child.things  #=> [:doll]
p mom.things    #=> [:car]
p dad.things    #=> [:car]

Class variable:

class Parent
  @@things = []
  def self.things
    @@things
  end
  def things
    @@things
  end
end

class Child < Parent
end

Parent.things << :car
Child.things  << :doll

p Parent.things #=> [:car,:doll]
p Child.things  #=> [:car,:doll]

mom = Parent.new
dad = Parent.new
son1 = Child.new
son2 = Child.new
daughter = Child.new

[ mom, dad, son1, son2, daughter ].each{ |person| p person.things }
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]

With an instance variable on a class (not on an instance of that class) you can store something common to that class without having sub-classes automatically also get them (and vice-versa). With class variables, you have the convenience of not having to write self.class from an instance object, and (when desirable) you also get automatic sharing throughout the class hierarchy.


Merging these together into a single example that also covers instance variables on instances:

class Parent
  @@family_things = []    # Shared between class and subclasses
  @shared_things  = []    # Specific to this class

  def self.family_things
    @@family_things
  end
  def self.shared_things
    @shared_things
  end

  attr_accessor :my_things
  def initialize
    @my_things = []       # Just for me
  end
  def family_things
    self.class.family_things
  end
  def shared_things
    self.class.shared_things
  end
end

class Child < Parent
  @shared_things = []
end

And then in action:

mama = Parent.new
papa = Parent.new
joey = Child.new
suzy = Child.new

Parent.family_things << :house
papa.family_things   << :vacuum
mama.shared_things   << :car
papa.shared_things   << :blender
papa.my_things       << :quadcopter
joey.my_things       << :bike
suzy.my_things       << :doll
joey.shared_things   << :puzzle
suzy.shared_things   << :blocks

p Parent.family_things #=> [:house, :vacuum]
p Child.family_things  #=> [:house, :vacuum]
p papa.family_things   #=> [:house, :vacuum]
p mama.family_things   #=> [:house, :vacuum]
p joey.family_things   #=> [:house, :vacuum]
p suzy.family_things   #=> [:house, :vacuum]

p Parent.shared_things #=> [:car, :blender]
p papa.shared_things   #=> [:car, :blender]
p mama.shared_things   #=> [:car, :blender]
p Child.shared_things  #=> [:puzzle, :blocks]  
p joey.shared_things   #=> [:puzzle, :blocks]
p suzy.shared_things   #=> [:puzzle, :blocks]

p papa.my_things       #=> [:quadcopter]
p mama.my_things       #=> []
p joey.my_things       #=> [:bike]
p suzy.my_things       #=> [:doll] 

The executable gets signed with invalid entitlements in Xcode

It seems to be a little bug inside Xcode. Try to archive it anyway, even there is a problem with entitlements. If your entitlements are fine, it will be uploaded without any problem. Apple accept it, and your app will be published to the AppStore.

I did it, and it worked:)

Jackson JSON custom serialization for certain fields

In case you don't want to pollute your model with annotations and want to perform some custom operations, you could use mixins.

ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.setMixInAnnotation(Person.class, PersonMixin.class);
mapper.registerModule(simpleModule);

Override age:

public abstract class PersonMixin {
    @JsonSerialize(using = PersonAgeSerializer.class)
    public String age;
}

Do whatever you need with the age:

public class PersonAgeSerializer extends JsonSerializer<Integer> {
    @Override
    public void serialize(Integer integer, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(String.valueOf(integer * 52) + " months");
    }
}

The service cannot be started, either because it is disabled or because it has no enabled devices associated with it

Try to open Services Window, by writing services.msc into Start->Run and hit Enter.

When window appears, then find SQL Browser service, right click and choose Properties, and then in dropdown list choose Automatic, or Manual, whatever you want, and click OK. Eventually, if not started immediately, you can again press right click on this service and click Start.

Temporary table in SQL server causing ' There is already an object named' error

I usually put these lines at the beginning of my stored procedure, and then at the end.

It is an "exists" check for #temp tables.

IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
begin
        drop table #MyCoolTempTable
end

Full Example:

CREATE PROCEDURE [dbo].[uspTempTableSuperSafeExample]
AS
BEGIN
    SET NOCOUNT ON;


    IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
    BEGIN
            DROP TABLE #MyCoolTempTable
    END


    CREATE TABLE #MyCoolTempTable (
        MyCoolTempTableKey INT IDENTITY(1,1),
        MyValue VARCHAR(128)
    )  

    INSERT INTO #MyCoolTempTable (MyValue)
        SELECT LEFT(@@VERSION, 128)
        UNION ALL SELECT TOP 10 LEFT(name, 128) from sysobjects

    SELECT MyCoolTempTableKey, MyValue FROM #MyCoolTempTable


    IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
    BEGIN
            DROP TABLE #MyCoolTempTable
    END


    SET NOCOUNT OFF;
END
GO

How to find integer array size in java

There is no method call size() with array. you can use array.length

Can I do a max(count(*)) in SQL?

create view sal as
select yr,count(*) as ct from
(select title,yr from movie m, actor a, casting c
where a.name='JOHN'
and a.id=c.actorid
and c.movieid=m.id)group by yr

-----VIEW CREATED-----

select yr from sal
where ct =(select max(ct) from sal)

YR 2013

How to convert comma-separated String to List?

In Kotlin if your String list like this and you can use for convert string to ArrayList use this line of code

var str= "item1, item2, item3, item4"
var itemsList = str.split(", ")

Reset select2 value and show placeholder

I do this for this case:

  $('#select').val('');
  $('.select2.select2-container').remove();
  $('.select2').select2();
  1. I change the select value into empty
  2. I remove container for select2
  3. Re-call select2

Difference between a Structure and a Union

With a union, you're only supposed to use one of the elements, because they're all stored at the same spot. This makes it useful when you want to store something that could be one of several types. A struct, on the other hand, has a separate memory location for each of its elements and they all can be used at once.

To give a concrete example of their use, I was working on a Scheme interpreter a little while ago and I was essentially overlaying the Scheme data types onto the C data types. This involved storing in a struct an enum indicating the type of value and a union to store that value.

union foo {
  int a;   // can't use both a and b at once
  char b;
} foo;

struct bar {
  int a;   // can use both a and b simultaneously
  char b;
} bar;

union foo x;
x.a = 3; // OK
x.b = 'c'; // NO! this affects the value of x.a!

struct bar y;
y.a = 3; // OK
y.b = 'c'; // OK

edit: If you're wondering what setting x.b to 'c' changes the value of x.a to, technically speaking it's undefined. On most modern machines a char is 1 byte and an int is 4 bytes, so giving x.b the value 'c' also gives the first byte of x.a that same value:

union foo x;
x.a = 3;
x.b = 'c';
printf("%i, %i\n", x.a, x.b);

prints

99, 99

Why are the two values the same? Because the last 3 bytes of the int 3 are all zero, so it's also read as 99. If we put in a larger number for x.a, you'll see that this is not always the case:

union foo x;
x.a = 387439;
x.b = 'c';
printf("%i, %i\n", x.a, x.b);

prints

387427, 99

To get a closer look at the actual memory values, let's set and print out the values in hex:

union foo x;
x.a = 0xDEADBEEF;
x.b = 0x22;
printf("%x, %x\n", x.a, x.b);

prints

deadbe22, 22

You can clearly see where the 0x22 overwrote the 0xEF.

BUT

In C, the order of bytes in an int are not defined. This program overwrote the 0xEF with 0x22 on my Mac, but there are other platforms where it would overwrite the 0xDE instead because the order of the bytes that make up the int were reversed. Therefore, when writing a program, you should never rely on the behavior of overwriting specific data in a union because it's not portable.

For more reading on the ordering of bytes, check out endianness.

Check if a String contains a special character

First you have to exhaustively identify the special characters that you want to check.

Then you can write a regular expression and use

public boolean matches(String regex)

How does data binding work in AngularJS?

I wondered this myself for a while. Without setters how does AngularJS notice changes to the $scope object? Does it poll them?

What it actually does is this: Any "normal" place you modify the model was already called from the guts of AngularJS, so it automatically calls $apply for you after your code runs. Say your controller has a method that's hooked up to ng-click on some element. Because AngularJS wires the calling of that method together for you, it has a chance to do an $apply in the appropriate place. Likewise, for expressions that appear right in the views, those are executed by AngularJS so it does the $apply.

When the documentation talks about having to call $apply manually for code outside of AngularJS, it's talking about code which, when run, doesn't stem from AngularJS itself in the call stack.

Moment JS - check if a date is today or in the future

Use the simplest one to check for future date

if(moment().diff(yourDate) >=  0)
     alert ("Past or current date");
else
     alert("It is a future date");

In Ruby on Rails, what's the difference between DateTime, Timestamp, Time and Date?

Here is an awesome and precise explanation I found.

TIMESTAMP used to track changes of records, and update every time when the record is changed. DATETIME used to store specific and static value which is not affected by any changes in records.

TIMESTAMP also affected by different TIME ZONE related setting. DATETIME is constant.

TIMESTAMP internally converted a current time zone to UTC for storage, and during retrieval convert the back to the current time zone. DATETIME can not do this.

TIMESTAMP is 4 bytes and DATETIME is 8 bytes.

TIMESTAMP supported range: ‘1970-01-01 00:00:01' UTC to ‘2038-01-19 03:14:07' UTC DATETIME supported range: ‘1000-01-01 00:00:00' to ‘9999-12-31 23:59:59'

source: https://www.dbrnd.com/2015/09/difference-between-datetime-and-timestamp-in-mysql/#:~:text=DATETIME%20vs%20TIMESTAMP%3A,DATETIME%20is%20constant.

Also...

table with different column "date" types and corresponding rails migration types depending on the database

Using jQuery to programmatically click an <a> link

<a href="#" id="myAnchor">Click me</a>

<script type="text/javascript">
$(document).ready(function(){
    $('#myAnchor').click(function(){
       window.location.href = 'index.php';
    });
})
</script>

What is "X-Content-Type-Options=nosniff"?

A really simple explanation that I found useful: the nosniff response header is a way to keep a website more secure.

From Security Researcher, Scott Helme, here:

It prevents Google Chrome and Internet Explorer from trying to mime-sniff the content-type of a response away from the one being declared by the server.

Fastest way to determine if record exists

SELECT TOP 1 products.id FROM products WHERE products.id = ?; will outperform all of your suggestions as it will terminate execution after it finds the first record.

What does iterator->second mean?

The type of the elements of an std::map (which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K and value is V is std::pair<const K, V> - the key is const to prevent you from interfering with the internal sorting of map values.

std::pair<> has two members named first and second (see here), with quite an intuitive meaning. Thus, given an iterator i to a certain map, the expression:

i->first

Which is equivalent to:

(*i).first

Refers to the first (const) element of the pair object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:

i->second

Which is equivalent to:

(*i).second

Refers to the second element of the pair - i.e. to the corresponding value in the map.

How can I zoom an HTML element in Firefox and Opera?

Use scale instead! After many researches and tests I have made this plugin to achieve it cross browser:

$.fn.scale = function(x) {
    if(!$(this).filter(':visible').length && x!=1)return $(this);
    if(!$(this).parent().hasClass('scaleContainer')){
        $(this).wrap($('<div class="scaleContainer">').css('position','relative'));
        $(this).data({
            'originalWidth':$(this).width(),
            'originalHeight':$(this).height()});
    }
    $(this).css({
        'transform': 'scale('+x+')',
        '-ms-transform': 'scale('+x+')',
        '-moz-transform': 'scale('+x+')',
        '-webkit-transform': 'scale('+x+')',
        'transform-origin': 'right bottom',
        '-ms-transform-origin': 'right bottom',
        '-moz-transform-origin': 'right bottom',
        '-webkit-transform-origin': 'right bottom',
        'position': 'absolute',
        'bottom': '0',
        'right': '0',
    });
    if(x==1)
        $(this).unwrap().css('position','static');else
            $(this).parent()
                .width($(this).data('originalWidth')*x)
                .height($(this).data('originalHeight')*x);
    return $(this);
};

usege:

$(selector).scale(0.5);

note:

It will create a wrapper with a class scaleContainer. Take care of that while styling content.

Multiple Indexes vs Multi-Column Indexes

Yes. I recommend you check out Kimberly Tripp's articles on indexing.

If an index is "covering", then there is no need to use anything but the index. In SQL Server 2005, you can also add additional columns to the index that are not part of the key which can eliminate trips to the rest of the row.

Having multiple indexes, each on a single column may mean that only one index gets used at all - you will have to refer to the execution plan to see what effects different indexing schemes offer.

You can also use the tuning wizard to help determine what indexes would make a given query or workload perform the best.

Java better way to delete file if exists

Starting from Java 7 you can use deleteIfExists that returns a boolean (or throw an Exception) depending on whether a file was deleted or not. This method may not be atomic with respect to other file system operations. Moreover if a file is in use by JVM/other program then on some operating system it will not be able to remove it. Every file can be converted to path via toPath method . E.g.

File file = ...;
boolean result = Files.deleteIfExists(file.toPath()); //surround it in try catch block

How do you uninstall all dependencies listed in package.json (NPM)?

Piggy-backing off of VIKAS KOHLI and jedmao, you can do this

single line version:

npm uninstall `ls -1 node_modules | grep -v ^@ | tr '/\n' ' '` `find node_modules/@* -type d -depth 1 2>/dev/null | cut -d/ -f2-3 | tr '\n' ' '`

multi-lined version:

npm uninstall \
`ls -1 node_modules | grep -v ^@ | tr '/\n' ' '` \
`find node_modules/@* -type d -depth 1 2>/dev/null | cut -d/ -f2-3 | tr '\n' ' '`

jquery stop child triggering parent event

Do this:

$(document).ready(function(){
    $(".header").click(function(){
        $(this).children(".children").toggle();
    });
   $(".header a").click(function(e) {
        e.stopPropagation();
   });
});

If you want to read more on .stopPropagation(), look here.

Finding duplicate values in MySQL

As a variation on Levik's answer that allows you to find also the ids of the duplicate results, I used the following:

SELECT * FROM table1 WHERE column1 IN (SELECT column1 AS duplicate_value FROM table1 GROUP BY column1 HAVING COUNT(*) > 1)

Convert a double to a QString

Building on @Kristian's answer, I had a desire to display a fixed number of decimal places. That can be accomplished with other arguments in the QString::number(...) function. For instance, I wanted 3 decimal places:

double value = 34.0495834;
QString strValue = QString::number(value, 'f', 3);
// strValue == "34.050"

The 'f' specifies decimal format notation (more info here, you can also specify scientific notation) and the 3 specifies the precision (number of decimal places). Probably already linked in other answers, but more info about the QString::number function can be found here in the QString documentation

How to play an android notification sound

You can use Notification and NotificationManager to display the notification you want. You can then customize the sound you want to play with your notification.

What does "connection reset by peer" mean?

This means that a TCP RST was received and the connection is now closed. This occurs when a packet is sent from your end of the connection but the other end does not recognize the connection; it will send back a packet with the RST bit set in order to forcibly close the connection.

This can happen if the other side crashes and then comes back up or if it calls close() on the socket while there is data from you in transit, and is an indication to you that some of the data that you previously sent may not have been received.

It is up to you whether that is an error; if the information you were sending was only for the benefit of the remote client then it may not matter that any final data may have been lost. However you should close the socket and free up any other resources associated with the connection.

How do I hide certain files from the sidebar in Visual Studio Code?

If your working on a Angular 2+ application, and like me you like a clean working environment, follow @omt66 answer and paste the below in your settings.json file. I recommend you do this once all the initial setup has been completed.

Note: This will actually hide the .vscode folder (with settings.json) in as well. (Open in your native file explorer / text editor if you need to make changes afterwards)

https://pastebin.com/X2NL6Vxb

{
    "files.exclude": {
        ".vscode":true,
        "node_modules/":true,
        "dist/":true,
        "e2e/":true,
        "*.json": true,
        "**/*.md": true,
        ".gitignore": true,
        "**/.gitkeep":true,
        ".editorconfig": true,
        "**/polyfills.ts": true,
        "**/main.ts": true,
        "**/tsconfig.app.json": true,
        "**/tsconfig.spec.json": true,
        "**/tslint.json": true,
        "**/karma.conf.js": true,
        "**/favicon.ico": true,
        "**/browserslist": true,
        "**/test.ts": true
    }
}

List of ANSI color escape sequences

How about:

ECMA-48 - Control Functions for Coded Character Sets, 5th edition (June 1991) - A standard defining the color control codes, that is apparently supported also by xterm.

SGR 38 and 48 were originally reserved by ECMA-48, but were fleshed out a few years later in a joint ITU, IEC, and ISO standard, which comes in several parts and which (amongst a whole lot of other things) documents the SGR 38/48 control sequences for direct colour and indexed colour:

There's a column for xterm in this table on the Wikipedia page for ANSI escape codes

Text in a flex container doesn't wrap in IE11

I had the same issue and the point is that the element was not adapting its width to the container.

Instead of using width:100%, be consistent (don't mix the floating model and the flex model) and use flex by adding this:

.child { align-self: stretch; }

Or:

.parent { align-items: stretch; }

This worked for me.

Carousel with Thumbnails in Bootstrap 3.0

Just found out a great plugin for this:

http://flexslider.woothemes.com/

Regards

Failed to install Python Cryptography package with PIP and setup.py

I am having same problem:

pip install cryptography

.
.
.
Installing collected packages: cffi, cryptography
     Running setup.py install for cffi ... error

Then I install libffi-devel and problem is solved

yum install libffi-devel

Share variables between files in Node.js?

With a different opinion, I think the global variables might be the best choice if you are going to publish your code to npm, cuz you cannot be sure that all packages are using the same release of your code. So if you use a file for exporting a singleton object, it will cause issues here.

You can choose global, require.main or any other objects which are shared across files.

Otherwise, install your package as an optional dependency package can avoid this problem.

Please tell me if there are some better solutions.

Finding the max value of an attribute in an array of objects

clean and simple ES6 (Babel)

const maxValueOfY = Math.max(...arrayToSearchIn.map(o => o.y), 0);

The second parameter should ensure a default value if arrayToSearchIn is empty.

SQL query for extracting year from a date

SELECT date_column_name FROM table_name WHERE EXTRACT(YEAR FROM date_column_name) = 2020

Where are the recorded macros stored in Notepad++?

On Vista with virtualization on, the file is here. Note that the AppData folder is hidden. Either show hidden folders, or go straight to it by typing %AppData% in the address bar of Windows Explorer.

C:\Users\[user]\AppData\Roaming\Notepad++\shortcuts.xml

The name 'ConfigurationManager' does not exist in the current context

It's not only necessary to use the namespace System.Configuration. You have also to add the reference to the assembly System.Configuration.dll , by

  1. Right-click on the References / Dependencies
  2. Choose Add Reference
  3. Find and add System.Configuration.

This will work for sure. Also for the NameValueCollection you have to write:

using System.Collections.Specialized;

Opening a .ipynb.txt File

What you have on your hands is an IPython Notebook file. (Now renamed to Jupyter Notebook

you can open it using the command ipython notebook filename.ipynb from the directory it is downloaded on to.

If you are on a newer machine, open the file as jupyter notebook filename.ipynb.

do not forget to remove the .txt extension.

the file has a series of python code/statements and markdown text that you can run/inspect/save/share. read more about ipython notebook from the website.

if you do not have IPython installed, you can do

pip install ipython

or check out installation instructions at the ipython website

What is the meaning of @_ in Perl?

You can also use shift for individual variables in most cases:

$var1 = shift;

This is a topic in which you should research further as Perl has a number of interesting ways of accessing outside information inside your sub routine.

How to specify the JDK version in android studio?

For new Android Studio versions, go to C:\Program Files\Android\Android Studio\jre\bin(or to location of Android Studio installed files) and open command window at this location and type in following command in command prompt:-

java -version

How to stop tracking and ignore changes to a file in Git?

To save some time the rules you add to your .gitignore can be used for removing multiple files/folders i.e.

git rm --cached app/**/*.xml

or

git rm --cached -r app/widgets/yourfolder/

e.t.c.

WARNING: Can't verify CSRF token authenticity rails

I struggled with this issue for days. Any GET call was working correctly, but all PUTs would generate a "Can't verify CSRF token authenticity" error. My website was working fine until I had added a SSL cert to nginx.

I finally stumbled on this missing line in my nginx settings:

location @puma { 
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
    proxy_set_header Host $http_host; 
    proxy_redirect off;
    proxy_set_header X-Forwarded-Proto https;   # Needed to avoid 'WARNING: Can't verify CSRF token authenticity'
    proxy_pass http://puma; 
}

After adding the missing line "proxy_set_header X-Forwarded-Proto https;", all my CSRF token errors quit.

Hopefully this helps someone else who also is beating their head against a wall. haha

How do you make sure email you send programmatically is not automatically marked as spam?

I would add :

Provide real unsubscription upon click on "Unsubscribe". I've seen real newsletters providing a dummy unsubscription link that upon click shows " has been unsubscribed successfully" but I will still receive further newsletters.

How to select min and max values of a column in a datatable?

This worked fine for me

int  max = Convert.ToInt32(datatable_name.AsEnumerable()
                        .Max(row => row["column_Name"]));

How to open a web server port on EC2 instance

You need to configure the security group as stated by cyraxjoe. Along with that you also need to open System port. Steps to open port in windows :-

  1. On the Start menu, click Run, type WF.msc, and then click OK.
  2. In the Windows Firewall with Advanced Security, in the left pane, right-click Inbound Rules, and then click New Rule in the action pane.
  3. In the Rule Type dialog box, select Port, and then click Next.
  4. In the Protocol and Ports dialog box, select TCP. Select Specific local ports, and then type the port number , such as 8787 for the default instance. Click Next.
  5. In the Action dialog box, select Allow the connection, and then click Next.
  6. In the Profile dialog box, select any profiles that describe the computer connection environment when you want to connect , and then click Next.
  7. In the Name dialog box, type a name and description for this rule, and then click Finish.

Ref:- Microsoft Docs for port Opening

apache and httpd running but I can't see my website

Did you restart the server after you changed the config file?

Can you telnet to the server from a different machine?

Can you telnet to the server from the server itself?

telnet <ip address> 80

telnet localhost 80

How to get the last element of a slice?

For just reading the last element of a slice:

sl[len(sl)-1]

For removing it:

sl = sl[:len(sl)-1]

See this page about slice tricks

Increasing the Command Timeout for SQL command

Setting CommandTimeout to 120 is not recommended. Try using pagination as mentioned above. Setting CommandTimeout to 30 is considered as normal. Anything more than that is consider bad approach and that usually concludes something wrong with the Implementation. Now the world is running on MiliSeconds Approach.

A general tree implementation?

I've published a Python [3] tree implementation on my site: http://www.quesucede.com/page/show/id/python_3_tree_implementation.

Hope it is of use,

Ok, here's the code:

import uuid

def sanitize_id(id):
    return id.strip().replace(" ", "")

(_ADD, _DELETE, _INSERT) = range(3)
(_ROOT, _DEPTH, _WIDTH) = range(3)

class Node:

    def __init__(self, name, identifier=None, expanded=True):
        self.__identifier = (str(uuid.uuid1()) if identifier is None else
                sanitize_id(str(identifier)))
        self.name = name
        self.expanded = expanded
        self.__bpointer = None
        self.__fpointer = []

    @property
    def identifier(self):
        return self.__identifier

    @property
    def bpointer(self):
        return self.__bpointer

    @bpointer.setter
    def bpointer(self, value):
        if value is not None:
            self.__bpointer = sanitize_id(value)

    @property
    def fpointer(self):
        return self.__fpointer

    def update_fpointer(self, identifier, mode=_ADD):
        if mode is _ADD:
            self.__fpointer.append(sanitize_id(identifier))
        elif mode is _DELETE:
            self.__fpointer.remove(sanitize_id(identifier))
        elif mode is _INSERT:
            self.__fpointer = [sanitize_id(identifier)]

class Tree:

    def __init__(self):
        self.nodes = []

    def get_index(self, position):
        for index, node in enumerate(self.nodes):
            if node.identifier == position:
                break
        return index

    def create_node(self, name, identifier=None, parent=None):

        node = Node(name, identifier)
        self.nodes.append(node)
        self.__update_fpointer(parent, node.identifier, _ADD)
        node.bpointer = parent
        return node

    def show(self, position, level=_ROOT):
        queue = self[position].fpointer
        if level == _ROOT:
            print("{0} [{1}]".format(self[position].name, self[position].identifier))
        else:
            print("\t"*level, "{0} [{1}]".format(self[position].name, self[position].identifier))
        if self[position].expanded:
            level += 1
            for element in queue:
                self.show(element, level)  # recursive call

    def expand_tree(self, position, mode=_DEPTH):
        # Python generator. Loosly based on an algorithm from 'Essential LISP' by
        # John R. Anderson, Albert T. Corbett, and Brian J. Reiser, page 239-241
        yield position
        queue = self[position].fpointer
        while queue:
            yield queue[0]
            expansion = self[queue[0]].fpointer
            if mode is _DEPTH:
                queue = expansion + queue[1:]  # depth-first
            elif mode is _WIDTH:
                queue = queue[1:] + expansion  # width-first

    def is_branch(self, position):
        return self[position].fpointer

    def __update_fpointer(self, position, identifier, mode):
        if position is None:
            return
        else:
            self[position].update_fpointer(identifier, mode)

    def __update_bpointer(self, position, identifier):
        self[position].bpointer = identifier

    def __getitem__(self, key):
        return self.nodes[self.get_index(key)]

    def __setitem__(self, key, item):
        self.nodes[self.get_index(key)] = item

    def __len__(self):
        return len(self.nodes)

    def __contains__(self, identifier):
        return [node.identifier for node in self.nodes if node.identifier is identifier]

if __name__ == "__main__":

    tree = Tree()
    tree.create_node("Harry", "harry")  # root node
    tree.create_node("Jane", "jane", parent = "harry")
    tree.create_node("Bill", "bill", parent = "harry")
    tree.create_node("Joe", "joe", parent = "jane")
    tree.create_node("Diane", "diane", parent = "jane")
    tree.create_node("George", "george", parent = "diane")
    tree.create_node("Mary", "mary", parent = "diane")
    tree.create_node("Jill", "jill", parent = "george")
    tree.create_node("Carol", "carol", parent = "jill")
    tree.create_node("Grace", "grace", parent = "bill")
    tree.create_node("Mark", "mark", parent = "jane")

    print("="*80)
    tree.show("harry")
    print("="*80)
    for node in tree.expand_tree("harry", mode=_WIDTH):
        print(node)
    print("="*80)

Average of multiple columns

This works in MariaDB:

SELECT Req_ID, (R1+R2+R3+R4+R5)/5 AS Average
FROM Request
GROUP BY Req_ID;

Install Application programmatically on Android

In Android Oreo and above version we have to approach different methods to install apk programatically.

 private void installApkProgramatically() {


    try {
        File path = activity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);

        File file = new File(path, filename);

        Uri uri;

        if (file.exists()) {

            Intent unKnownSourceIntent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).setData(Uri.parse(String.format("package:%s", activity.getPackageName())));

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

                if (!activity.getPackageManager().canRequestPackageInstalls()) {
                    startActivityForResult(unKnownSourceIntent, Constant.UNKNOWN_RESOURCE_INTENT_REQUEST_CODE);
                } else {
                    Uri fileUri = FileProvider.getUriForFile(activity.getBaseContext(), activity.getApplicationContext().getPackageName() + ".provider", file);
                    Intent intent = new Intent(Intent.ACTION_VIEW, fileUri);
                    intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
                    intent.setDataAndType(fileUri, "application/vnd.android" + ".package-archive");
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    startActivity(intent);
                    alertDialog.dismiss();
                }

            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

                Intent intent1 = new Intent(Intent.ACTION_INSTALL_PACKAGE);
                uri = FileProvider.getUriForFile(activity.getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", file);
                activity.grantUriPermission("com.abcd.xyz", uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                activity.grantUriPermission("com.abcd.xyz", uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                intent1.setDataAndType(uri,
                        "application/*");
                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent1.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent1.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                startActivity(intent1);

            } else {
                Intent intent = new Intent(Intent.ACTION_VIEW);

                uri = Uri.fromFile(file);

                intent.setDataAndType(uri,
                        "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        } else {

            Log.i(TAG, " file " + file.getPath() + " does not exist");
        }
    } catch (Exception e) {

        Log.i(TAG, "" + e.getMessage());

    }
}

In Oreo and above version we need unknown resource installation permission. so in activity result u have to check the result for the permission

    @Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {

        case Constant.UNKNOWN_RESOURCE_INTENT_REQUEST_CODE:
            switch (resultCode) {
                case Activity.RESULT_OK:
                    installApkProgramatically();

                    break;
                case Activity.RESULT_CANCELED:
                    //unknown resouce installation cancelled

                    break;
            }
            break;
    }
}

Using Docker-Compose, how to execute multiple commands

Use a tool such as wait-for-it or dockerize. These are small wrapper scripts which you can include in your application’s image. Or write your own wrapper script to perform a more application-specific commands. according to: https://docs.docker.com/compose/startup-order/

How to check whether java is installed on the computer

After installing Java, set the path in environmental variables and then open the command prompt and type java -version. If installed properly, it'll list the java version, jre version, etc.

You can additionally check by trying the javac command too. If it displays some data, you've your java installed with the proper path set, else it'll that javac is an invalid command.

How do I remove the old history from a git repository?

If you want to keep the upstream repository with full history, but local smaller checkouts, do a shallow clone with git clone --depth=1 [repo].

After pushing a commit, you can do

  1. git fetch --depth=1 to prune the old commits. This makes the old commits and their objects unreachable.
  2. git reflog expire --expire-unreachable=now --all. To expire all old commits and their objects
  3. git gc --aggressive --prune=all to remove the old objects

See also How to remove local git history after a commit?.

Note that you cannot push this "shallow" repository to somewhere else: "shallow update not allowed". See Remote rejected (shallow update not allowed) after changing Git remote URL. If you want to to that, you have to stick with grafting.

How do I print a datetime in the local timezone?

Think your should look around: datetime.astimezone()

http://docs.python.org/library/datetime.html#datetime.datetime.astimezone

Also see pytz module - it's quite easy to use -- as example:

eastern = timezone('US/Eastern')

http://pytz.sourceforge.net/

Example:

from datetime import datetime
import pytz
from tzlocal import get_localzone # $ pip install tzlocal

utc_dt = datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=pytz.utc)
print(utc_dt.astimezone(get_localzone())) # print local time
# -> 2009-07-10 14:44:59.193982-04:00

Getting a count of objects in a queryset in django

Another way of doing this would be using Aggregation. You should be able to achieve a similar result using a single query. Such as this:

Item.objects.values("contest").annotate(Count("id"))

I did not test this specific query, but this should output a count of the items for each value in contests as a dictionary.

cURL error 60: SSL certificate: unable to get local issuer certificate

when I run 'var_dump(php_ini_loaded_file());' I get this output on my page 'C:\Development\bin\apache\apache2.4.33\bin\php.ini' (length=50)'

and to get php to load my cert file I had to edit the php.ini in this path 'C:\Development\bin\apache\apache2.4.33\bin\php.ini' and add openssl.cafile="C:/Development/bin/php/php7.2.4/extras/ssl/cacert.pem" where I had downloaded and place my cert file from https://curl.haxx.se/docs/caextract.html

am on windows 10, using drupal 8, wamp and php7.2.4

Auto populate columns in one sheet from another sheet

Below code will look for last used row in sheet1 and copy the entire range from A1 upto last used row in column A to Sheet2 at exact same location.

Sub test()

    Dim lastRow As Long
    lastRow = Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
    Sheets("Sheet2").Range("A1:A" & lastRow).Value = Sheets("Sheet1").Range("A1:A" & lastRow).Value

End Sub

Remove empty strings from array while keeping record Without Loop?

var newArray = oldArray.filter(function(v){return v!==''});

Export to csv in jQuery

By using just jQuery, you cannot avoid a server call.

However, to achieve this result, I'm using Downloadify, which lets me save files without having to make another server call. Doing this reduces server load and makes a good user experience.

To get a proper CSV you just have to take out all the unnecessary tags and put a ',' between the data.

Convert String array to ArrayList

String[] words= new String[]{"ace","boom","crew","dog","eon"};
List<String> wordList = Arrays.asList(words);

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

I my case I'd manually moved a .war file to /var/lib/tomcat9/webapps and unzipped it, then did "chown -R tomcat:tomcat *" in that directory and it resolved it.

How can I start an Activity from a non-Activity class?

Your onTap override receives the MapView from which you can obtain the Context:

@Override
public boolean onTap(GeoPoint p, MapView mapView)
{
    // ...

    Intent intent = new Intent();
    intent.setClass(mapView.getContext(), FullscreenView.class);
    startActivity(intent);

    // ...
}

Is there a "do ... until" in Python?

I prefer to use a looping variable, as it tends to read a bit nicer than just "while 1:", and no ugly-looking break statement:

finished = False
while not finished:
    ... do something...
    finished = evaluate_end_condition()

How to make a submit out of a <a href...>...</a> link?

What might be a handy addition to this is the possibility to change the post-url from the extra button so you can post to different urls with different buttons. This can be achieved by setting the form 'action' property. Here's the code for that when using jQuery:

$('#[href button name]').click(function(e) {
    e.preventDefault();
    $('#[form name]').attr('action', 'alternateurl.php');
    $('#[form name]').submit();
});

The action-attribute has some issues with older jQuery versions, but on the latest you'll be good to go.

How to simulate target="_blank" in JavaScript

This is how I do it with jQuery. I have a class for each link that I want to be opened in new window.

$(function(){

    $(".external").click(function(e) {
        e.preventDefault();
        window.open(this.href);
    });
});

What are the differences between type() and isinstance()?

A practical usage difference is how they handle booleans:

True and False are just keywords that mean 1 and 0 in python. Thus,

isinstance(True, int)

and

isinstance(False, int)

both return True. Both booleans are an instance of an integer. type(), however, is more clever:

type(True) == int

returns False.

Override devise registrations controller

Very simple methods Just go to the terminal and the type following

rails g devise:controllers users //This will create devise controllers in controllers/users folder

Next to use custom views

rails g devise:views users //This will create devise views in views/users folder

now in your route.rb file

devise_for :users, controllers: {
           :sessions => "users/sessions",
           :registrations => "users/registrations" }

You can add other controllers too. This will make devise to use controllers in users folder and views in users folder.

Now you can customize your views as your desire and add your logic to controllers in controllers/users folder. Enjoy !

Replace HTML page with contents retrieved via AJAX

Can't you just try to replace the body content with the document.body handler?

if your page is this:

<html>
<body>
blablabla
<script type="text/javascript">
document.body.innerHTML="hi!";
</script>
</body>
</html>

Just use the document.body to replace the body.

This works for me. All the content of the BODY tag is replaced by the innerHTML you specify. If you need to even change the html tag and all childs you should check out which tags of the 'document.' are capable of doing so.

An example with javascript scripting inside it:

<html>
<body>
blablabla
<script type="text/javascript">
var changeme = "<button onClick=\"document.bgColor = \'#000000\'\">click</button>";
document.body.innerHTML=changeme;
</script>
</body>

This way you can do javascript scripting inside the new content. Don't forget to escape all double and single quotes though, or it won't work. escaping in javascript can be done by traversing your code and putting a backslash in front of all singe and double quotes.

Bare in mind that server side scripting like php doesn't work this way. Since PHP is server-side scripting it has to be processed before a page is loaded. Javascript is a language which works on client-side and thus can not activate the re-processing of php code.

Trees in Twitter Bootstrap

If someone wants expandable/collapsible version of the treeview from Vitaliy Bychik's answer, you can save some time :)

http://jsfiddle.net/mehmetatas/fXzHS/2/

$(function () {
    $('.tree li').hide();
    $('.tree li:first').show();
    $('.tree li').on('click', function (e) {
        var children = $(this).find('> ul > li');
        if (children.is(":visible")) children.hide('fast');
        else children.show('fast');
        e.stopPropagation();
    });
});

How To Launch Git Bash from DOS Command Line?

You can add git path to environment variables

  • For x86

%SYSTEMDRIVE%\Program Files (x86)\Git\bin\

  • For x64

%PROGRAMFILES%\Git\bin\

Open cmd and write this command to open git bash

sh --login

OR

bash --login

OR

sh

OR

bash

You can see this GIF image for more details:

https://media1.giphy.com/media/WSxbZkPFY490wk3abN/giphy.gif

How to access the ith column of a NumPy multidimensional array?

>>> test[:,0]
array([1, 3, 5])

this command gives you a row vector, if you just want to loop over it, it's fine, but if you want to hstack with some other array with dimension 3xN, you will have

ValueError: all the input arrays must have same number of dimensions

while

>>> test[:,[0]]
array([[1],
       [3],
       [5]])

gives you a column vector, so that you can do concatenate or hstack operation.

e.g.

>>> np.hstack((test, test[:,[0]]))
array([[1, 2, 1],
       [3, 4, 3],
       [5, 6, 5]])

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

How to trigger click event on href element

Triggering a click via JavaScript will not open a hyperlink. This is a security measure built into the browser.

See this question for some workarounds, though.

In C#, can a class inherit from another class and an interface?

I found the answer to the second part of my questions. Yes, a class can implement an interface that is in a different class as long that the interface is declared as public.

How to list all tags along with the full message in git?

git tag -l --format='%(contents)'

or

git for-each-ref refs/tags/ --format='%(contents)'

will output full annotation message for every tag (including signature if its signed).

  • %(contents:subject) will output only first line
  • %(contents:body) will output annotation without first line and signature (useful text only)
  • %(contents:signature) will output only PGP-signature

See more in man git-for-each-ref “Field names” section.

How to stop the Timer in android?

In java.util.timer one can use .cancel() to stop the timer and clear all pending tasks.

mongodb how to get max value from collections

what about using aggregate framework:

db.collection.aggregate({ $group : { _id: null, max: { $max : "$age" }}});

Make a UIButton programmatically in Swift

UIButton with constraints in iOS 9.1/Xcode 7.1.1/Swift 2.1:

import UIKit
import MapKit

class MapViewController: UIViewController {  

    override func loadView() {
        mapView = MKMapView()  //Create a view...
        view = mapView         //assign it to the ViewController's (inherited) view property.
                               //Equivalent to self.view = mapView

        myButton = UIButton(type: .RoundedRect)  //RoundedRect is an alias for System (tested by printing out their rawValue's)
        //myButton.frame = CGRect(x:50, y:500, width:70, height:50)  //Doesn't seem to be necessary when using constraints.
        myButton.setTitle("Current\nLocation", forState: .Normal)
        myButton.titleLabel?.lineBreakMode = .ByWordWrapping  //If newline in title, split title onto multiple lines
        myButton.titleLabel?.textAlignment = .Center
        myButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        myButton.layer.cornerRadius = 6   //For some reason, a button with type RoundedRect has square corners
        myButton.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.5) //Make the color partially transparent
        //Attempt to add padding around text. Shrunk the frame when I tried it.  Negative values had no effect.
        //myButton.titleEdgeInsets = UIEdgeInsetsMake(-10,-10,-10,-10)
        myButton.contentEdgeInsets = UIEdgeInsetsMake(5,5,5,5)  //Add padding around text.

        myButton.addTarget(self, action: "getCurrentLocation:", forControlEvents: .TouchUpInside)
        mapView.addSubview(myButton)

        //Button Constraints:
        myButton.translatesAutoresizingMaskIntoConstraints = false //***
        //bottomLayoutGuide(for tab bar) and topLayoutGuide(for status bar) are properties of the ViewController
        //To anchor above the tab bar on the bottom of the screen:
        let bottomButtonConstraint = myButton.bottomAnchor.constraintEqualToAnchor(bottomLayoutGuide.topAnchor, constant: -20) //Implied call of self.bottomLayoutGuide. Anchor 20 points **above** the top of the tab bar.
        //To anchor to the blue guide line that is inset from the left 
        //edge of the screen in InterfaceBuilder:
        let margins = view.layoutMarginsGuide  //Now the guide is a property of the View.
        let leadingButtonConstraint = myButton.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor)

        bottomButtonConstraint.active = true
        leadingButtonConstraint.active = true
    }


    func getCurrentLocation(sender: UIButton) {
        print("Current Location button clicked!")
    }

The button is anchored to the bottom left corner, above the tab bar.

Good MapReduce examples

From time to time I present MR concepts to people. I find processing tasks familiar to people and then map them to the MR paradigm.

Usually I take two things:

  1. Group By / Aggregations. Here the advantage of the shuffling stage is clear. An explanation that shuffling is also distributed sort + an explanation of distributed sort algorithm also helps.

  2. Join of two tables. People working with DB are familiar with the concept and its scalability problem. Show how it can be done in MR.

How to create Drawable from resource

If you are trying to get the drawable from the view where the image is set as,

ivshowing.setBackgroundResource(R.drawable.one);

then the drawable will return only null value with the following code...

   Drawable drawable = (Drawable) ivshowing.getDrawable();

So, it's better to set the image with the following code, if you wanna retrieve the drawable from a particular view.

 ivshowing.setImageResource(R.drawable.one);

only then the drawable will we converted exactly.

How can I convert an image into a Base64 string?

Here is the encoding and decoding code in Kotlin:

 fun encode(imageUri: Uri): String {
    val input = activity.getContentResolver().openInputStream(imageUri)
    val image = BitmapFactory.decodeStream(input , null, null)

    // Encode image to base64 string
    val baos = ByteArrayOutputStream()
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos)
    var imageBytes = baos.toByteArray()
    val imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT)
    return imageString
}

fun decode(imageString: String) {

    // Decode base64 string to image
    val imageBytes = Base64.decode(imageString, Base64.DEFAULT)
    val decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)

    imageview.setImageBitmap(decodedImage)
}

How do I get the position selected in a RecyclerView?

I think the most correct way to get item position is

View.OnClickListener onClickListener = new View.OnClickListener() {
    @Override public void onClick(View v) {
      View view = v;
      View parent = (View) v.getParent();
      while (!(parent instanceof RecyclerView)){
        view=parent;
        parent = (View) parent.getParent();
      }
      int position = recyclerView.getChildAdapterPosition(view);
}

Because view, you click not always the root view of your row layout. If view is not a root one (e.g buttons), you will get Class cast exception. Thus at first we need to find the view, which is the a dirrect child of you reciclerview. Then, find position using recyclerView.getChildAdapterPosition(view);

How to execute a raw update sql with dynamic binding in rails

Here's a trick I recently worked out for executing raw sql with binds:

binds = SomeRecord.bind(a_string_field: value1, a_date_field: value2) +
        SomeOtherRecord.bind(a_numeric_field: value3)
SomeRecord.connection.exec_query <<~SQL, nil, binds
  SELECT *
  FROM some_records
  JOIN some_other_records ON some_other_records.record_id = some_records.id
  WHERE some_records.a_string_field = $1
    AND some_records.a_date_field < $2
    AND some_other_records.a_numeric_field > $3
SQL

where ApplicationRecord defines this:

# Convenient way of building custom sql binds
def self.bind(column_values)
  column_values.map do |column_name, value|
    [column_for_attribute(column_name), value]
  end
end

and that is similar to how AR binds its own queries.

PHP: If internet explorer 6, 7, 8 , or 9

Notice the case in 'Trident':

if (isset($_SERVER['HTTP_USER_AGENT']) &&
    ((strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false) || strpos($_SERVER['HTTP_USER_AGENT'], 'Trident') !== false)) {   
     // IE is here :-(
    }

Bulk Insert Correctly Quoted CSV File in SQL Server

Unfortunately SQL Server interprets the quoted comma as a delimiter. This applies to both BCP and bulk insert .

From http://msdn.microsoft.com/en-us/library/ms191485%28v=sql.100%29.aspx

If a terminator character occurs within the data, it is interpreted as a terminator, not as data, and the data after that character is interpreted as belonging to the next field or record. Therefore, choose your terminators carefully to make sure that they never appear in your data.

Shell command to tar directory excluding certain files/folders

gnu tar v 1.26 the --exclude needs to come after archive file and backup directory arguments, should have no leading or trailing slashes, and prefers no quotes (single or double). So relative to the PARENT directory to be backed up, it's:

tar cvfz /path_to/mytar.tgz ./dir_to_backup --exclude=some_path/to_exclude

Default FirebaseApp is not initialized

Installed Firebase Via Android Studio Tools...Firebase...

I did the installation via the built-in tools from Android Studio (following the latest docs from Firebase). This installed the basic dependencies but when I attempted to connect to the database it always gave me the error that I needed to call initialize first, even though I was:

Default FirebaseApp is not initialized in this process . Make sure to call FirebaseApp.initializeApp(Context) first.

I was getting this error no matter what I did.

Finally, after seeing a comment in one of the other answers I changed the following in my gradle from version 4.1.0 to :

classpath 'com.google.gms:google-services:4.0.1'

When I did that I finally saw an error that helped me:

File google-services.json is missing. The Google Services Plugin cannot function without it. Searched Location: C:\Users\%username%\AndroidStudioProjects\TxtFwd\app\src\nullnull\debug\google-services.json
C:\Users\%username%\AndroidStudioProjects\TxtFwd\app\src\debug\nullnull\google-services.json
C:\Users\%username%\AndroidStudioProjects\TxtFwd\app\src\nullnull\google-services.json
C:\Users\%username%\AndroidStudioProjects\TxtFwd\app\src\debug\google-services.json
C:\Users\%username%\AndroidStudioProjects\TxtFwd\app\src\nullnullDebug\google-services.json
C:\Users\%username%\AndroidStudioProjects\TxtFwd\app\google-services.json

That's the problem. It seems that the 4.1.0 version doesn't give that build error for some reason -- doesn't mention that you have a missing google-services.json file. I don't have the google-services.json file in my app so I went out and added it.

But since this was an upgrade which used an existing realtime firsbase database I had never had to generate that file in the past. I went to firebase and generated it and added it and it fixed the problem.

Changed Back to 4.1.0

Once I discovered all of this then I changed the classpath variable back (to 4.1.0) and rebuilt and it crashed again with the error that it hasn't been initalized.

Root Issues

  • Building with 4.1.0 doesn't provide you with a valid error upon precompile so you may not know what is going on.
  • Running against 4.1.0 causes the initialization error.

ASP.NET Web Api: The requested resource does not support http method 'GET'

If you are decorating your method with HttpGet, add the following using at the top of the controller:

using System.Web.Http;

If you are using System.Web.Mvc, then this problem can occur.

Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement

try this with sql2012 or above,

this will be help to delete all objects by selected schema

DECLARE @MySchemaName VARCHAR(50)='dbo', @sql VARCHAR(MAX)='';
DECLARE @SchemaName VARCHAR(255), @ObjectName VARCHAR(255), @ObjectType VARCHAR(255), @ObjectDesc VARCHAR(255), @Category INT;

DECLARE cur CURSOR FOR
    SELECT  (s.name)SchemaName, (o.name)ObjectName, (o.type)ObjectType,(o.type_desc)ObjectDesc,(so.category)Category
    FROM    sys.objects o
    INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
    INNER JOIN sysobjects so ON so.name=o.name
    WHERE s.name = @MySchemaName
    AND so.category=0
    AND o.type IN ('P','PC','U','V','FN','IF','TF','FS','FT','PK','TT')

OPEN cur
FETCH NEXT FROM cur INTO @SchemaName,@ObjectName,@ObjectType,@ObjectDesc,@Category

SET @sql='';
WHILE @@FETCH_STATUS = 0 BEGIN    
    IF @ObjectType IN('FN', 'IF', 'TF', 'FS', 'FT') SET @sql=@sql+'Drop Function '+@MySchemaName+'.'+@ObjectName+CHAR(13)
    IF @ObjectType IN('V') SET @sql=@sql+'Drop View '+@MySchemaName+'.'+@ObjectName+CHAR(13)
    IF @ObjectType IN('P') SET @sql=@sql+'Drop Procedure '+@MySchemaName+'.'+@ObjectName+CHAR(13)
    IF @ObjectType IN('U') SET @sql=@sql+'Drop Table '+@MySchemaName+'.'+@ObjectName+CHAR(13)

    --PRINT @ObjectName + ' | ' + @ObjectType
    FETCH NEXT FROM cur INTO @SchemaName,@ObjectName,@ObjectType,@ObjectDesc,@Category
END
CLOSE cur;    
DEALLOCATE cur;
SET @sql=@sql+CASE WHEN LEN(@sql)>0 THEN 'Drop Schema '+@MySchemaName+CHAR(13) ELSE '' END
PRINT @sql
EXECUTE (@sql)

Android button background color

Just use a MaterialButton and the app:backgroundTint attribute:

<MaterialButton
  app:backgroundTint="@color/my_color_selector"

enter image description here

How to get the current time in milliseconds in C Programming

quick answer

#include<stdio.h>   
#include<time.h>   

int main()   
{   
    clock_t t1, t2;  
    t1 = clock();   
    int i;
    for(i = 0; i < 1000000; i++)   
    {   
        int x = 90;  
    }   

    t2 = clock();   

    float diff = ((float)(t2 - t1) / 1000000.0F ) * 1000;   
    printf("%f",diff);   

    return 0;   
}

Pandas column of lists, create a row for each list element

lst_col = 'samples'

r = pd.DataFrame({
      col:np.repeat(df[col].values, df[lst_col].str.len())
      for col in df.columns.drop(lst_col)}
    ).assign(**{lst_col:np.concatenate(df[lst_col].values)})[df.columns]

Result:

In [103]: r
Out[103]:
    samples  subject  trial_num
0      0.10        1          1
1     -0.20        1          1
2      0.05        1          1
3      0.25        1          2
4      1.32        1          2
5     -0.17        1          2
6      0.64        1          3
7     -0.22        1          3
8     -0.71        1          3
9     -0.03        2          1
10    -0.65        2          1
11     0.76        2          1
12     1.77        2          2
13     0.89        2          2
14     0.65        2          2
15    -0.98        2          3
16     0.65        2          3
17    -0.30        2          3

PS here you may find a bit more generic solution


UPDATE: some explanations: IMO the easiest way to understand this code is to try to execute it step-by-step:

in the following line we are repeating values in one column N times where N - is the length of the corresponding list:

In [10]: np.repeat(df['trial_num'].values, df[lst_col].str.len())
Out[10]: array([1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3], dtype=int64)

this can be generalized for all columns, containing scalar values:

In [11]: pd.DataFrame({
    ...:           col:np.repeat(df[col].values, df[lst_col].str.len())
    ...:           for col in df.columns.drop(lst_col)}
    ...:         )
Out[11]:
    trial_num  subject
0           1        1
1           1        1
2           1        1
3           2        1
4           2        1
5           2        1
6           3        1
..        ...      ...
11          1        2
12          2        2
13          2        2
14          2        2
15          3        2
16          3        2
17          3        2

[18 rows x 2 columns]

using np.concatenate() we can flatten all values in the list column (samples) and get a 1D vector:

In [12]: np.concatenate(df[lst_col].values)
Out[12]: array([-1.04, -0.58, -1.32,  0.82, -0.59, -0.34,  0.25,  2.09,  0.12,  0.83, -0.88,  0.68,  0.55, -0.56,  0.65, -0.04,  0.36, -0.31])

putting all this together:

In [13]: pd.DataFrame({
    ...:           col:np.repeat(df[col].values, df[lst_col].str.len())
    ...:           for col in df.columns.drop(lst_col)}
    ...:         ).assign(**{lst_col:np.concatenate(df[lst_col].values)})
Out[13]:
    trial_num  subject  samples
0           1        1    -1.04
1           1        1    -0.58
2           1        1    -1.32
3           2        1     0.82
4           2        1    -0.59
5           2        1    -0.34
6           3        1     0.25
..        ...      ...      ...
11          1        2     0.68
12          2        2     0.55
13          2        2    -0.56
14          2        2     0.65
15          3        2    -0.04
16          3        2     0.36
17          3        2    -0.31

[18 rows x 3 columns]

using pd.DataFrame()[df.columns] will guarantee that we are selecting columns in the original order...

Installing Homebrew on OS X

I faced the same problem of brew command not found while installing Homebrew on mac BigSur with M1 processor.

I - Install XCode if it is not installed yet.

II - Select terminal.app in Finder.

III - RMB click on Terminal and select "Get Info"

IV - Select Open using Rosetta checkbox.

V - Close any open Terminal windows.

VI - Open a new Terminal window and install Hobebrew:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

VII - Test Homebrew installation.

IIX - Uncheck Open using Rosetta checkbox.

Combining node.js and Python

This sounds like a scenario where zeroMQ would be a good fit. It's a messaging framework that's similar to using TCP or Unix sockets, but it's much more robust (http://zguide.zeromq.org/py:all)

There's a library that uses zeroMQ to provide a RPC framework that works pretty well. It's called zeroRPC (http://www.zerorpc.io/). Here's the hello world.

Python "Hello x" server:

import zerorpc

class HelloRPC(object):
    '''pass the method a name, it replies "Hello name!"'''
    def hello(self, name):
        return "Hello, {0}!".format(name)

def main():
    s = zerorpc.Server(HelloRPC())
    s.bind("tcp://*:4242")
    s.run()

if __name__ == "__main__" : main()

And the node.js client:

var zerorpc = require("zerorpc");

var client = new zerorpc.Client();
client.connect("tcp://127.0.0.1:4242");
//calls the method on the python object
client.invoke("hello", "World", function(error, reply, streaming) {
    if(error){
        console.log("ERROR: ", error);
    }
    console.log(reply);
});

Or vice-versa, node.js server:

var zerorpc = require("zerorpc");

var server = new zerorpc.Server({
    hello: function(name, reply) {
        reply(null, "Hello, " + name, false);
    }
});

server.bind("tcp://0.0.0.0:4242");

And the python client

import zerorpc, sys

c = zerorpc.Client()
c.connect("tcp://127.0.0.1:4242")
name = sys.argv[1] if len(sys.argv) > 1 else "dude"
print c.hello(name)

How do I access properties of a javascript object if I don't know the names?

Old versions of JavaScript (< ES5) require using a for..in loop:

for (var key in data) {
  if (data.hasOwnProperty(key)) {
    // do something with key
  }
}

ES5 introduces Object.keys and Array#forEach which makes this a little easier:

var data = { foo: 'bar', baz: 'quux' };

Object.keys(data); // ['foo', 'baz']
Object.keys(data).map(function(key){ return data[key] }) // ['bar', 'quux']
Object.keys(data).forEach(function (key) {
  // do something with data[key]
});

ES2017 introduces Object.values and Object.entries.

Object.values(data) // ['bar', 'quux']
Object.entries(data) // [['foo', 'bar'], ['baz', 'quux']]

Downloading images with node.js

var fs = require('fs'),
http = require('http'),
https = require('https');

var Stream = require('stream').Transform;

var downloadImageToUrl = (url, filename, callback) => {

    var client = http;
    if (url.toString().indexOf("https") === 0){
      client = https;
     }

    client.request(url, function(response) {                                        
      var data = new Stream();                                                    

      response.on('data', function(chunk) {                                       
         data.push(chunk);                                                         
      });                                                                         

      response.on('end', function() {                                             
         fs.writeFileSync(filename, data.read());                               
      });                                                                         
   }).end();
};

downloadImageToUrl('https://www.google.com/images/srpr/logo11w.png', 'public/uploads/users/abc.jpg');

How do I check if an array includes a value in JavaScript?

We use this snippet (works with objects, arrays, strings):

/*
 * @function
 * @name Object.prototype.inArray
 * @description Extend Object prototype within inArray function
 *
 * @param {mix}    needle       - Search-able needle
 * @param {bool}   searchInKey  - Search needle in keys?
 *
 */
Object.defineProperty(Object.prototype, 'inArray',{
    value: function(needle, searchInKey){

        var object = this;

        if( Object.prototype.toString.call(needle) === '[object Object]' || 
            Object.prototype.toString.call(needle) === '[object Array]'){
            needle = JSON.stringify(needle);
        }

        return Object.keys(object).some(function(key){

            var value = object[key];

            if( Object.prototype.toString.call(value) === '[object Object]' || 
                Object.prototype.toString.call(value) === '[object Array]'){
                value = JSON.stringify(value);
            }

            if(searchInKey){
                if(value === needle || key === needle){
                return true;
                }
            }else{
                if(value === needle){
                    return true;
                }
            }
        });
    },
    writable: true,
    configurable: true,
    enumerable: false
});

Usage:

var a = {one: "first", two: "second", foo: {three: "third"}};
a.inArray("first");          //true
a.inArray("foo");            //false
a.inArray("foo", true);      //true - search by keys
a.inArray({three: "third"}); //true

var b = ["one", "two", "three", "four", {foo: 'val'}];
b.inArray("one");         //true
b.inArray('foo');         //false
b.inArray({foo: 'val'})   //true
b.inArray("{foo: 'val'}") //false

var c = "String";
c.inArray("S");        //true
c.inArray("s");        //false
c.inArray("2", true);  //true
c.inArray("20", true); //false

How to get start and end of previous month in VB

firstDay = DateSerial(Year(DateAdd("m", -1, Now)), Month(DateAdd("m", -1, Now)), 1)
lastDay = DateAdd("d", -1, DateSerial(Year(Now), Month(Now), 1))

This is another way to do it, but I think Remou's version looks cleaner.

Is it not possible to define multiple constructors in Python?

Jack M. is right. Do it this way:

>>> class City:
...     def __init__(self, city=None):
...         self.city = city
...     def __repr__(self):
...         if self.city:  return self.city
...         return ''
...
>>> c = City('Berlin')
>>> print c
Berlin
>>> c = City()
>>> print c

>>>

What is the difference between up-casting and down-casting with respect to class variable

1.- Upcasting.

Doing an upcasting, you define a tag of some type, that points to an object of a subtype (Type and subtype may be called class and subclass, if you feel more comfortable...).

Animal animalCat = new Cat();

What means that such tag, animalCat, will have the functionality (the methods) of type Animal only, because we've declared it as type Animal, not as type Cat.

We are allowed to do that in a "natural/implicit/automatic" way, at compile-time or at a run-time, mainly because Cat inherits some of its functionality from Animal; for example, move(). (At least, cat is an animal, isn't it?)

2.- Downcasting.

But, what would happen if we need to get the functionality of Cat, from our type Animal tag?.

As we have created the animalCat tag pointing to a Cat object, we need a way to call the Cat object methods, from our animalCat tag in a some smart pretty way.

Such procedure is what we call Downcasting, and we can do it only at the run-time.

Time for some code:

public class Animal {
    public String move() {
        return "Going to somewhere";
    }
}

public class Cat extends Animal{
    public String makeNoise() {
        return "Meow!";
    }   
}

public class Test {

    public static void main(String[] args) {
        
    //1.- Upcasting 
    //  __Type_____tag________object
        Animal animalCat = new Cat();
    //Some animal movement
        System.out.println(animalCat.move());
        //prints "Going to somewhere"
        
    //2.- Downcasting   
    //Now you wanna make some Animal noise.
        //First of all: type Animal hasn't any makeNoise() functionality.
        //But Cat can do it!. I wanna be an Animal Cat now!!
        
        //___________________Downcast__tag_____ Cat's method
        String animalNoise = ( (Cat) animalCat ).makeNoise();
        
        System.out.println(animalNoise);
        //Prints "Meow!", as cats usually done.
        
    //3.- An Animal may be a Cat, but a Dog or a Rhinoceros too.
        //All of them have their own noises and own functionalities.
        //Uncomment below and read the error in the console:
        
    //  __Type_____tag________object
        //Cat catAnimal = new Animal();
        
    }

}

Joining two lists together

I just wanted to test how Union works with the default comparer on overlapping collections of reference type objects.

My object is:

class MyInt
{
    public int val;

    public override string ToString()
    {
        return val.ToString();
    }
}

My test code is:

MyInt[] myInts1 = new MyInt[10];
MyInt[] myInts2 = new MyInt[10];
int overlapFrom = 4;
Console.WriteLine("overlapFrom: {0}", overlapFrom);

Action<IEnumerable<MyInt>, string> printMyInts = (myInts, myIntsName) => Console.WriteLine("{2} ({0}): {1}", myInts.Count(), string.Join(" ", myInts), myIntsName);

for (int i = 0; i < myInts1.Length; i++)
    myInts1[i] = new MyInt { val = i };
printMyInts(myInts1, nameof(myInts1));

int j = 0;
for (; j + overlapFrom < myInts1.Length; j++)
    myInts2[j] = myInts1[j + overlapFrom];
for (; j < myInts2.Length; j++)
    myInts2[j] = new MyInt { val = j + overlapFrom };
printMyInts(myInts2, nameof(myInts2));

IEnumerable<MyInt> myUnion = myInts1.Union(myInts2);
printMyInts(myUnion, nameof(myUnion));

for (int i = 0; i < myInts2.Length; i++)
    myInts2[i].val += 10;
printMyInts(myInts2, nameof(myInts2));
printMyInts(myUnion, nameof(myUnion));

for (int i = 0; i < myInts1.Length; i++)
    myInts1[i].val = i;
printMyInts(myInts1, nameof(myInts1));
printMyInts(myUnion, nameof(myUnion));

The output is:

overlapFrom: 4
myInts1 (10): 0 1 2 3 4 5 6 7 8 9
myInts2 (10): 4 5 6 7 8 9 10 11 12 13
myUnion (14): 0 1 2 3 4 5 6 7 8 9 10 11 12 13
myInts2 (10): 14 15 16 17 18 19 20 21 22 23
myUnion (14): 0 1 2 3 14 15 16 17 18 19 20 21 22 23
myInts1 (10): 0 1 2 3 4 5 6 7 8 9
myUnion (14): 0 1 2 3 4 5 6 7 8 9 20 21 22 23

So, everything works fine.

TypeError: Invalid dimensions for image data when plotting array with imshow()

There is a (somewhat) related question on StackOverflow:

Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeezed or sliced into a 2D array.

More generally, the reason for the Exception

TypeError: Invalid dimensions for image data

is shown here: matplotlib.pyplot.imshow() needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!

You can easily check this with (these checks are done by imshow, this function is only meant to give a more specific message in case it's not a valid input):

from __future__ import print_function
import numpy as np

def valid_imshow_data(data):
    data = np.asarray(data)
    if data.ndim == 2:
        return True
    elif data.ndim == 3:
        if 3 <= data.shape[2] <= 4:
            return True
        else:
            print('The "data" has 3 dimensions but the last dimension '
                  'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
                  ''.format(data.shape[2]))
            return False
    else:
        print('To visualize an image the data must be 2 dimensional or '
              '3 dimensional, not "{}".'
              ''.format(data.ndim))
        return False

In your case:

>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False

The np.asarray is what is done internally by matplotlib.pyplot.imshow so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list) it's necessary.


In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()

import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0)  # or axis=1
plt.imshow(a)
plt.show()

enter image description here

or just use something that accepts 1D arrays like plot:

a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()

enter image description here

Get the last element of a std::string

In C++11 and beyond, you can use the back member function:

char ch = myStr.back();

In C++03, std::string::back is not available due to an oversight, but you can get around this by dereferencing the reverse_iterator you get back from rbegin:

char ch = *myStr.rbegin();

In both cases, be careful to make sure the string actually has at least one character in it! Otherwise, you'll get undefined behavior, which is a Bad Thing.

Hope this helps!

Efficient iteration with index in Scala

The proposed solutions suffer from the fact that they either explicitly iterate over a collection or stuff the collection into a function. It is more natural to stick with the usual idioms of Scala and put the index inside the usual map- or foreach-methods. This can be done using memoizing. The resulting code might look like

myIterable map (doIndexed(someFunction))

Here is a way to achieve this purpose. Consider the following utility:

object TraversableUtil {
    class IndexMemoizingFunction[A, B](f: (Int, A) => B) extends Function1[A, B] {
        private var index = 0
        override def apply(a: A): B = {
            val ret = f(index, a)
            index += 1
            ret
        }
    }

    def doIndexed[A, B](f: (Int, A) => B): A => B = {
        new IndexMemoizingFunction(f)
    }
}

This is already all you need. You can apply this for instance as follows:

import TraversableUtil._
List('a','b','c').map(doIndexed((i, char) => char + i))

which results in the list

List(97, 99, 101)

This way, you can use the usual Traversable-functions at the expense of wrapping your effective function. Enjoy!

How to remove anaconda from windows completely?

For windows-

  1. In the Control Panel, choose Add or Remove Programs or Uninstall a program, and then select Python 3.6 (Anaconda) or your version of Python.
  2. Use Windows Explorer to delete the envs and pkgs folders prior to Running the uninstall in the root of your installation.

How do I use LINQ Contains(string[]) instead of Contains(string)

I believe you could also do something like this.

from xx in table
where (from yy in string[] 
       select yy).Contains(xx.uid.ToString())
select xx

How to set environment variables from within package.json?

Although not directly answering the question I´d like to share an idea on top of the other answers. From what I got each of these would offer some level of complexity to achieve cross platform independency.

On my scenario all I wanted, originally, to set a variable to control whether or not to secure the server with JWT authentication (for development purposes)

After reading the answers I decided simply to create 2 different files, with authentication turned on and off respectively.

  "scripts": {
    "dev": "nodemon --debug  index_auth.js",
    "devna": "nodemon --debug  index_no_auth.js",
  }

The files are simply wrappers that call the original index.js file (which I renamed to appbootstrapper.js):

//index_no_auth.js authentication turned off
const bootstrapper = require('./appbootstrapper');
bootstrapper(false);

//index_auth.js authentication turned on
const bootstrapper = require('./appbootstrapper');
bootstrapper(true);

class AppBootStrapper {

    init(useauth) {
        //real initialization
    }
}

Perhaps this can help someone else

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

This Works For me !!!

Call a Function without Parameter

$("#CourseSelect").change(function(e1) {
   loadTeachers();
});

Call a Function with Parameter

$("#CourseSelect").change(function(e1) {
    loadTeachers($(e1.target).val());
});

Download text/csv content as files from server in Angular

$http service returns a promise which has two callback methods as shown below.

$http({method: 'GET', url: '/someUrl'}).
  success(function(data, status, headers, config) {
     var anchor = angular.element('<a/>');
     anchor.attr({
         href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
         target: '_blank',
         download: 'filename.csv'
     })[0].click();

  }).
  error(function(data, status, headers, config) {
    // handle error
  });

How to add days to the current date?

Add Days in Date in SQL

 DECLARE @NEWDOB DATE=null
 
 SET @NEWDOB= (SELECT DOB, DATEADD(dd,45,DOB)AS NEWDOB FROM tbl_Employees)

JWT authentication for ASP.NET Web API

I think you should use some 3d party server to support the JWT token and there is no out of the box JWT support in WEB API 2.

However there is an OWIN project for supporting some format of signed token (not JWT). It works as a reduced OAuth protocol to provide just a simple form of authentication for a web site.

You can read more about it e.g. here.

It's rather long, but most parts are details with controllers and ASP.NET Identity that you might not need at all. Most important are

Step 9: Add support for OAuth Bearer Tokens Generation

Step 12: Testing the Back-end API

There you can read how to set up endpoint (e.g. "/token") that you can access from frontend (and details on the format of the request).

Other steps provide details on how to connect that endpoint to the database, etc. and you can chose the parts that you require.

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

Setting the default page for ASP.NET (Visual Studio) server configuration

One way to achieve this is to add a DefaultDocument settings in the Web.config.

  <system.webServer>
   <defaultDocument>
    <files>
      <clear />
      <add value="DefaultPage.aspx" />
    </files>
   </defaultDocument>
  </system.webServer>

json call with C#

In your code you don't get the HttpResponse, so you won't see what the server side sends you back.

you need to get the Response similar to the way you get (make) the Request. So

public static bool SendAnSMSMessage(string message)
{
  var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
  httpWebRequest.ContentType = "text/json";
  httpWebRequest.Method = "POST";

  using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
  {
    string json = "{ \"method\": \"send\", " +
                      "  \"params\": [ " +
                      "             \"IPutAGuidHere\", " +
                      "             \"[email protected]\", " +
                      "             \"MyTenDigitNumberWasHere\", " +
                      "             \"" + message + "\" " +
                      "             ] " +
                      "}";

    streamWriter.Write(json);
  }
  var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
  using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
  {
    var responseText = streamReader.ReadToEnd();
    //Now you have your response.
    //or false depending on information in the response
    return true;        
  }
}

I also notice in the pennysms documentation that they expect a content type of "text/json" and not "application/json". That may not make a difference, but it's worth trying in case it doesn't work.

mysql delete under safe mode

I have a far more simple solution, it is working for me; it is also a workaround but might be usable and you dont have to change your settings. I assume you can use value that will never be there, then you use it on your WHERE clause

DELETE FROM MyTable WHERE MyField IS_NOT_EQUAL AnyValueNoItemOnMyFieldWillEverHave

I don't like that solution either too much, that's why I am here, but it works and it seems better than what it has been answered

How to convert image to byte array

Code:

using System.IO;

byte[] img = File.ReadAllBytes(openFileDialog1.FileName);

How to define a Sql Server connection string to use in VB.NET?

Imports System.Data.SqlClient
Imports System.Data.Sql
Imports System.IO
Imports System.Configuration
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConString").ConnectionString
Dim cn As New SqlConnection(connectionString)
Dim cmd As New SqlCommand
Dim dr As SqlDataAdapter

How can I issue a single command from the command line through sql plus?

I'm able to run an SQL query by piping it to SQL*Plus:

@echo select count(*) from table; | sqlplus username/password@database

Give

@echo execute some_procedure | sqlplus username/password@databasename

a try.

Docker CE on RHEL - Requires: container-selinux >= 2.9

The best way to resolve this one is. Download the latest container-selinux package from http://mirror.centos.org/centos/7/extras/x86_64/Packages/ into the VM or the Machine where docker needs to be installed. Error : sometime it will ask for red hat subscription to download from repo. we can do it manually with out subscription as below Run the below command this will install dependencies manually rpm -i container-selinux-2.107-3.el7.noarch.rpm then run the yum install docker-ce

thanks Saa

What exactly is \r in C language?

It's Carriage Return. Source: http://msdn.microsoft.com/en-us/library/6aw8xdf2(v=vs.80).aspx

The following repeats the loop until the user has pressed the Return key.

while(ch!='\r')
{
  ch=getche();
}

Cell spacing in UICollectionView

I have tried iago849's answer and it worked.

Swift 4

open override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    guard let answer = super.layoutAttributesForElements(in: rect) else {
        return nil
    }
    let count = answer.count
    for i in 1..<count {
        let currentLayoutAttributes = answer[i]
        let prevLayoutAttributes = answer[i-1]
        let origin = prevLayoutAttributes.frame.maxX
        if (origin + CGFloat(spacing) + currentLayoutAttributes.frame.size.width) < self.collectionViewContentSize.width && currentLayoutAttributes.frame.origin.x > prevLayoutAttributes.frame.origin.x {
            var frame = currentLayoutAttributes.frame
            frame.origin.x = origin + CGFloat(spacing)
            currentLayoutAttributes.frame = frame
        }
    }
    return answer
}

Here is the link for the github project. https://github.com/vishalwaka/MultiTags

SVG fill color transparency / alpha?

To make a fill completely transparent, fill="transparent" seems to work in modern browsers. But it didn't work in Microsoft Word (for Mac), I had to use fill-opacity="0".