Programs & Examples On #Eclipse 3.5

For issues relating to configuring or using Eclipse, version 3.5. Also known as Eclipse Galileo. Use this tag for questions which are specific to this Eclipse release, in most cases you should also specify the eclipse tag.

Eclipse 3.5 Unable to install plugins

We had tons of issues here, namely with the proxy support. We ended-up using Pulse: http://www.poweredbypulse.com/

Pulse has built-in support for a few plugin, however, you can add third-party plugin and even local jar file quite easily.

Strangely it does not always use the built-in Eclipse feature, so sometimes when Eclipse become difficult ( like in our case for the proxy business ), you can work-around it with Pulse.

How do I enable the column selection mode in Eclipse?

Additionally, you can change the keys view window -> preferences then type: 'keys' and when the key preference page opens you can type 'toggle block selection' and voila!

Difference between Eclipse Europa, Helios, Galileo

Those are just version designations (just like windows xp, vista or windows 7) which they are using to name their major releases, instead of using version numbers. so you'll want to use the newest eclipse version available, which is helios (or 3.6 which is the corresponding version number).

How to change resolution (DPI) of an image?

It's simply a matter of scaling the image width and height up by the correct ratio. Not all images formats support a DPI metatag, and when they do, all they're telling your graphics software to do is divide the image by the ratio supplied.

For example, if you export a 300dpi image from Photoshop to a JPEG, the image will appear to be very large when viewed in your picture viewing software. This is because the DPI information isn't supported in JPEG and is discarded when saved. This means your picture viewer doesn't know what ratio to divide the image by and instead displays the image at at 1:1 ratio.

To get the ratio you need to scale the image by, see the code below. Just remember, this will stretch the image, just like it would in Photoshop. You're essentially quadrupling the size of the image so it's going to stretch and may produce artifacts.

Pseudo code

ratio = 300.0 / 72.0   // 4.167
image.width * ratio
image.height * ratio

Javascript Object push() function

push() is for arrays, not objects, so use the right data structure.

var data = [];
// ...
data[0] = { "ID": "1", "Status": "Valid" };
data[1] = { "ID": "2", "Status": "Invalid" };
// ...
var tempData = [];
for ( var index=0; index<data.length; index++ ) {
    if ( data[index].Status == "Valid" ) {
        tempData.push( data );
    }
}
data = tempData;

How to stop EditText from gaining focus at Activity startup in Android

Do this and get your job done!

android:focusable="true"
android:focusableInTouchMode="true" 

Issue with Task Scheduler launching a task

On properties,

Check whether radio button is selected for

Run only when user is logged on 

If you selected for the above option then that is the reason why it is failed.

so change the option to

Run whether user is logged on or not

OR

In other case, user might have changed his/her login credentials

How can I run code on a background thread on Android?

IF you need to:

  1. execute code on a background Thread

  2. execute code that DOES NOT touch/update the UI

  3. execute (short) code which will take at most a few seconds to complete

THEN use the following clean and efficient pattern which uses AsyncTask:

AsyncTask.execute(new Runnable() {
   @Override
   public void run() {
      //TODO your background code
   }
});

How to check if element has any children in Javascript?

A couple of ways:

if (element.firstChild) {
    // It has at least one
}

or the hasChildNodes() function:

if (element.hasChildNodes()) {
    // It has at least one
}

or the length property of childNodes:

if (element.childNodes.length > 0) { // Or just `if (element.childNodes.length)`
    // It has at least one
}

If you only want to know about child elements (as opposed to text nodes, attribute nodes, etc.) on all modern browsers (and IE8 — in fact, even IE6) you can do this: (thank you Florian!)

if (element.children.length > 0) { // Or just `if (element.children.length)`
    // It has at least one element as a child
}

That relies on the children property, which wasn't defined in DOM1, DOM2, or DOM3, but which has near-universal support. (It works in IE6 and up and Chrome, Firefox, and Opera at least as far back as November 2012, when this was originally written.) If supporting older mobile devices, be sure to check for support.

If you don't need IE8 and earlier support, you can also do this:

if (element.firstElementChild) {
    // It has at least one element as a child
}

That relies on firstElementChild. Like children, it wasn't defined in DOM1-3 either, but unlike children it wasn't added to IE until IE9. The same applies to childElementCount:

if (element.childElementCount !== 0) {
    // It has at least one element as a child
}

If you want to stick to something defined in DOM1 (maybe you have to support really obscure browsers), you have to do more work:

var hasChildElements, child;
hasChildElements = false;
for (child = element.firstChild; child; child = child.nextSibling) {
    if (child.nodeType == 1) { // 1 == Element
        hasChildElements = true;
        break;
    }
}

All of that is part of DOM1, and nearly universally supported.

It would be easy to wrap this up in a function, e.g.:

function hasChildElement(elm) {
    var child, rv;

    if (elm.children) {
        // Supports `children`
        rv = elm.children.length !== 0;
    } else {
        // The hard way...
        rv = false;
        for (child = element.firstChild; !rv && child; child = child.nextSibling) {
            if (child.nodeType == 1) { // 1 == Element
                rv = true;
            }
        }
    }
    return rv;
}

Run Executable from Powershell script with parameters

Here is an alternative method for doing multiple args. I use it when the arguments are too long for a one liner.

$app = 'C:\Program Files\MSBuild\test.exe'
$arg1 = '/genmsi'
$arg2 = '/f'
$arg3 = '$MySourceDirectory\src\Deployment\Installations.xml'

& $app $arg1 $arg2 $arg3

Android SDK folder taking a lot of disk space. Do we need to keep all of the System Images?

System images are pre-installed Android operating systems, and are only used by emulators. If you use your real Android device for debugging, you no longer need them, so you can remove them all.

The cleanest way to remove them is using SDK Manager. Open up SDK Manager and uncheck those system images and then apply.

Also feel free to remove other components (e.g. old SDK levels) that are of no use.

How to get twitter bootstrap modal to close (after initial launch)

I had the same problem in the iphone or desktop, didnt manage to close the dialog when pressing the close button.

i found out that The <button> tag defines a clickable button and is needed to specify the type attribute for a element as follow:

<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

check the example code for bootstrap modals at : BootStrap javascript Page

Maven: how to override the dependency added by a library

The accepted answer is correct but I'd like to add my two cents. I've run into a problem where I had a project A that had a project B as a dependency. Both projects use slf4j but project B uses log4j while project A uses logback. Project B uses slf4j 1.6.1, while project A uses slf4j 1.7.5 (due to the already included logback 1.2.3 dependency).

The problem: Project A couldn't find a function that exists on slf4j 1.7.5, after checking eclipe's dependency hierarchy tab I found out that during build it was using slf4j 1.6.1 from project B, instead of using logback's slf4j 1.7.5.

I solved the issue by changing the order of the dependencies on project A pom, when I moved project B entry below the logback entry then maven started to build the project using slf4j 1.7.5.

Edit: Adding the slf4j 1.7.5 dependency before Project B dependency worked too.

How do I get the YouTube video ID from a URL?

This definitely requires regex:

Copy into Ruby IRB:

var url = "http://www.youtube.com/watch?v=NLqASIXrVbY"
var VID_REGEX = /(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/
url.match(VID_REGEX)[1]

See for all test cases: https://gist.github.com/blairanderson/b264a15a8faaac9c6318

Why Would I Ever Need to Use C# Nested Classes

A nested class can have private, protected and protected internal access modifiers along with public and internal.

For example, you are implementing the GetEnumerator() method that returns an IEnumerator<T> object. The consumers wouldn't care about the actual type of the object. All they know about it is that it implements that interface. The class you want to return doesn't have any direct use. You can declare that class as a private nested class and return an instance of it (this is actually how the C# compiler implements iterators):

class MyUselessList : IEnumerable<int> {
    // ...
    private List<int> internalList;
    private class UselessListEnumerator : IEnumerator<int> {
        private MyUselessList obj;
        public UselessListEnumerator(MyUselessList o) {
           obj = o;
        }
        private int currentIndex = -1;
        public int Current {
           get { return obj.internalList[currentIndex]; }
        }
        public bool MoveNext() { 
           return ++currentIndex < obj.internalList.Count;
        }
    }
    public IEnumerator<int> GetEnumerator() {
        return new UselessListEnumerator(this);
    }
}

How to get "GET" request parameters in JavaScript?

try the below code, it will help you get the GET parameters from url . for more details.

 var url_string = window.location.href; // www.test.com?filename=test
    var url = new URL(url_string);
    var paramValue = url.searchParams.get("filename");
    alert(paramValue)

How do I modify a MySQL column to allow NULL?

Use: ALTER TABLE mytable MODIFY mycolumn VARCHAR(255);

Best way to generate xml?

Using lxml:

from lxml import etree

# create XML 
root = etree.Element('root')
root.append(etree.Element('child'))
# another child with text
child = etree.Element('child')
child.text = 'some text'
root.append(child)

# pretty string
s = etree.tostring(root, pretty_print=True)
print s

Output:

<root>
  <child/>
  <child>some text</child>
</root>

See the tutorial for more information.

Is there a Mutex in Java?

See this page: http://www.oracle.com/technetwork/articles/javase/index-140767.html

It has a slightly different pattern which is (I think) what you are looking for:

try {
  mutex.acquire();
  try {
    // do something
  } finally {
    mutex.release();
  }
} catch(InterruptedException ie) {
  // ...
}

In this usage, you're only calling release() after a successful acquire()

How to get exception message in Python properly

I too had the same problem. Digging into this I found that the Exception class has an args attribute, which captures the arguments that were used to create the exception. If you narrow the exceptions that except will catch to a subset, you should be able to determine how they were constructed, and thus which argument contains the message.

try:
   # do something that may raise an AuthException
except AuthException as ex:
   if ex.args[0] == "Authentication Timeout.":
      # handle timeout
   else:
      # generic handling

JOIN two SELECT statement results

SELECT t1.ks, t1.[# Tasks], COALESCE(t2.[# Late], 0) AS [# Late]
FROM 
    (SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks) t1
LEFT JOIN
    (SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks) t2
ON (t1.ks = t2.ks);

Delegation: EventEmitter or Observable in Angular

you can use BehaviourSubject as described above or there is one more way:

you can handle EventEmitter like this: first add a selector

import {Component, Output, EventEmitter} from 'angular2/core';

@Component({
// other properties left out for brevity
selector: 'app-nav-component', //declaring selector
template:`
  <div class="nav-item" (click)="selectedNavItem(1)"></div>
`
 })

 export class Navigation {

@Output() navchange: EventEmitter<number> = new EventEmitter();

selectedNavItem(item: number) {
    console.log('selected nav item ' + item);
    this.navchange.emit(item)
}

}

Now you can handle this event like let us suppose observer.component.html is the view of Observer component

<app-nav-component (navchange)="recieveIdFromNav($event)"></app-nav-component>

then in the ObservingComponent.ts

export class ObservingComponent {

 //method to recieve the value from nav component

 public recieveIdFromNav(id: number) {
   console.log('here is the id sent from nav component ', id);
 }

 }

How to get the current TimeStamp?

I think you are looking for this function:

http://doc.qt.io/qt-5/qdatetime.html#toTime_t

uint QDateTime::toTime_t () const

Returns the datetime as the number of seconds that have passed since 1970-01-01T00:00:00, > Coordinated Universal Time (Qt::UTC).

On systems that do not support time zones, this function will behave as if local time were Qt::UTC.

See also setTime_t().

How to indent/format a selection of code in Visual Studio Code with Ctrl + Shift + F

I want to indent a specific section of code in Visual Studio Code:

  • Select the lines you want to indent, and
  • use Ctrl + ] to indent them.

If you want to format a section (instead of indent it):

  • Select the lines you want to format,
  • use Ctrl + K, Ctrl + F to format them.

How to add extension methods to Enums

All answers are great, but they are talking about adding extension method to a specific type of enum.

What if you want to add a method to all enums like returning an int of current value instead of explicit casting?

public static class EnumExtensions
{
    public static int ToInt<T>(this T soure) where T : IConvertible//enum
    {
        if (!typeof(T).IsEnum)
            throw new ArgumentException("T must be an enumerated type");

        return (int) (IConvertible) soure;
    }

    //ShawnFeatherly funtion (above answer) but as extention method
    public static int Count<T>(this T soure) where T : IConvertible//enum
    {
        if (!typeof(T).IsEnum)
            throw new ArgumentException("T must be an enumerated type");

        return Enum.GetNames(typeof(T)).Length;
    }
}

The trick behind IConvertible is its Inheritance Hierarchy see MDSN

Thanks to ShawnFeatherly for his answer

Table header to stay fixed at the top when user scrolls it out of view with jQuery

This is by far the best solution I've found for having a fixed table header.

UPDATE 5/11: Fixed horizontal scrolling bug as pointed out by Kerry Johnson

Codepen: https://codepen.io/josephting/pen/demELL

_x000D_
_x000D_
;(function($) {_x000D_
   $.fn.fixMe = function() {_x000D_
      return this.each(function() {_x000D_
         var $this = $(this),_x000D_
            $t_fixed;_x000D_
         function init() {_x000D_
            $this.wrap('<div class="container" />');_x000D_
            $t_fixed = $this.clone();_x000D_
            $t_fixed.find("tbody").remove().end().addClass("fixed").insertBefore($this);_x000D_
            resizeFixed();_x000D_
         }_x000D_
         function resizeFixed() {_x000D_
           $t_fixed.width($this.outerWidth());_x000D_
            $t_fixed.find("th").each(function(index) {_x000D_
               $(this).css("width",$this.find("th").eq(index).outerWidth()+"px");_x000D_
            });_x000D_
         }_x000D_
         function scrollFixed() {_x000D_
            var offsetY = $(this).scrollTop(),_x000D_
            offsetX = $(this).scrollLeft(),_x000D_
            tableOffsetTop = $this.offset().top,_x000D_
            tableOffsetBottom = tableOffsetTop + $this.height() - $this.find("thead").height(),_x000D_
            tableOffsetLeft = $this.offset().left;_x000D_
            if(offsetY < tableOffsetTop || offsetY > tableOffsetBottom)_x000D_
               $t_fixed.hide();_x000D_
            else if(offsetY >= tableOffsetTop && offsetY <= tableOffsetBottom && $t_fixed.is(":hidden"))_x000D_
               $t_fixed.show();_x000D_
            $t_fixed.css("left", tableOffsetLeft - offsetX + "px");_x000D_
         }_x000D_
         $(window).resize(resizeFixed);_x000D_
         $(window).scroll(scrollFixed);_x000D_
         init();_x000D_
      });_x000D_
   };_x000D_
})(jQuery);_x000D_
_x000D_
$(document).ready(function(){_x000D_
   $("table").fixMe();_x000D_
   $(".up").click(function() {_x000D_
      $('html, body').animate({_x000D_
      scrollTop: 0_x000D_
   }, 2000);_x000D_
 });_x000D_
});
_x000D_
body{_x000D_
  font:1.2em normal Arial,sans-serif;_x000D_
  color:#34495E;_x000D_
}_x000D_
_x000D_
h1{_x000D_
  text-align:center;_x000D_
  text-transform:uppercase;_x000D_
  letter-spacing:-2px;_x000D_
  font-size:2.5em;_x000D_
  margin:20px 0;_x000D_
}_x000D_
_x000D_
.container{_x000D_
  width:90%;_x000D_
  margin:auto;_x000D_
}_x000D_
_x000D_
table{_x000D_
  border-collapse:collapse;_x000D_
  width:100%;_x000D_
}_x000D_
_x000D_
.blue{_x000D_
  border:2px solid #1ABC9C;_x000D_
}_x000D_
_x000D_
.blue thead{_x000D_
  background:#1ABC9C;_x000D_
}_x000D_
_x000D_
.purple{_x000D_
  border:2px solid #9B59B6;_x000D_
}_x000D_
_x000D_
.purple thead{_x000D_
  background:#9B59B6;_x000D_
}_x000D_
_x000D_
thead{_x000D_
  color:white;_x000D_
}_x000D_
_x000D_
th,td{_x000D_
  text-align:center;_x000D_
  padding:5px 0;_x000D_
}_x000D_
_x000D_
tbody tr:nth-child(even){_x000D_
  background:#ECF0F1;_x000D_
}_x000D_
_x000D_
tbody tr:hover{_x000D_
background:#BDC3C7;_x000D_
  color:#FFFFFF;_x000D_
}_x000D_
_x000D_
.fixed{_x000D_
  top:0;_x000D_
  position:fixed;_x000D_
  width:auto;_x000D_
  display:none;_x000D_
  border:none;_x000D_
}_x000D_
_x000D_
.scrollMore{_x000D_
  margin-top:600px;_x000D_
}_x000D_
_x000D_
.up{_x000D_
  cursor:pointer;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h1>&darr; SCROLL &darr;</h1>_x000D_
<table class="blue">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Colonne 1</th>_x000D_
      <th>Colonne 2</th>_x000D_
      <th>Colonne 3</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>MaisMaisMaisMaisMaisMaisMaisMaisMaisMaisMaisMaisMaisMaisMaisMaisMaisMaisMaisMais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
       <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
_x000D_
<h1 class="scrollMore">&darr; SCROLL MORE &darr;</h1>_x000D_
<table class="purple">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Colonne 1</th>_x000D_
      <th>Colonne 2</th>_x000D_
      <th>Colonne 3</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
       <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
       <tr>_x000D_
      <td>Non</td>_x000D_
      <td>Mais</td>_x000D_
      <td>Allo !</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
<h1 class="up scrollMore">&uarr; UP &uarr;</h1>
_x000D_
_x000D_
_x000D_

jQuery.inArray(), how to use it right?

$.inArray() does the EXACT SAME THING as myarray.indexOf() and returns the index of the item you are checking the array for the existence of. It's just compatible with earlier versions of IE before IE9. The best choice is probably to use myarray.includes() which returns a boolean true/false value. See snippet below for output examples of all 3 methods.

_x000D_
_x000D_
// Declare the array and define it's values_x000D_
var myarray = ['Cat', 'Dog', 'Fish'];_x000D_
_x000D_
// Display the return value of each jQuery function _x000D_
// when a radio button is selected_x000D_
$('input:radio').change( function() {_x000D_
_x000D_
  // Get the value of the selected radio_x000D_
  var selectedItem = $('input:radio[name=arrayItems]:checked').val();_x000D_
  $('.item').text( selectedItem );_x000D_
  _x000D_
  // Calculate and display the index of the selected item_x000D_
  $('#indexVal').text( myarray.indexOf(selectedItem) );_x000D_
  _x000D_
  // Calculate and display the $.inArray() value for the selected item_x000D_
  $('#inArrVal').text( $.inArray(selectedItem, myarray) );_x000D_
  _x000D_
  // Calculate and display the .includes value for the selected item_x000D_
  $('#includeVal').text( myarray.includes(selectedItem) );_x000D_
});
_x000D_
#results { line-height: 1.8em; }_x000D_
#resultLabels { width: 14em; display: inline-block; margin-left: 10px; float: left; }_x000D_
label { margin-right: 1.5em; }_x000D_
.space { margin-right: 1.5em; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
Click a radio button to display the output of_x000D_
&nbsp;<code>$.inArray()</code>_x000D_
&nbsp;vs. <code>myArray.indexOf()</code>_x000D_
&nbsp;vs. <code>myarray.includes()</code>_x000D_
&nbsp;when tested against_x000D_
&nbsp;<code>myarray = ['Cat', 'Dog', 'Fish'];</code><br><br>_x000D_
_x000D_
<label><input type="radio" name="arrayItems" value="Cat"> Cat</label>_x000D_
<label><input type="radio" name="arrayItems" value="Dog"> Dog</label>_x000D_
<label><input type="radio" name="arrayItems" value="Fish"> Fish</label>  _x000D_
<label><input type="radio" name="arrayItems" value="N/A"> ? Not in Array</label>_x000D_
<br><br>_x000D_
_x000D_
<div id="results">_x000D_
  <strong>Results:</strong><br>_x000D_
  <div id="resultLabels">_x000D_
    myarray.indexOf( "<span class="item">item</span>" )<br>_x000D_
    $.inArray( "<span class="item">item</span>", myarray )<br>_x000D_
    myarray.includes( "<span class="item">item</span>" )_x000D_
  </div>_x000D_
  <div id="resultOutputs">_x000D_
    <span class="space">=</span><span id="indexVal"></span><br>_x000D_
    <span class="space">=</span><span id="inArrVal"></span><br>_x000D_
    <span class="space">=</span><span id="includeVal"></span>_x000D_
  </div>_x000D_
 </div>
_x000D_
_x000D_
_x000D_

Fastest way to ping a network range and return responsive hosts?

You should use NMAP:

nmap -T5 -sP 192.168.0.0-255

How to Initialize char array from a string

The compilation problem only occurs for me (gcc 4.3, ubuntu 8.10) if the three variables are global. The problem is that C doesn't work like a script languages, so you cannot take for granted that the initialization of u and t occur after the one of s. That's why you get a compilation error. Now, you cannot initialize t and y they way you did it before, that's why you will need a char*. The code that do the work is the following:

#include <stdio.h>
#include <stdlib.h>

#define STR "ABCD"

const char s[] = STR;
char* t;
char* u;

void init(){
    t = malloc(sizeof(STR)-1);
    t[0] = s[0];
    t[1] = s[1];
    t[2] = s[2];
    t[3] = s[3];


    u = malloc(sizeof(STR)-1);
    u[0] = s[3];
    u[1] = s[2];
    u[2] = s[1];
    u[3] = s[0];
}

int main(void) {
    init();
    puts(t);
    puts(u);

    return EXIT_SUCCESS;
}

Could not instantiate mail function. Why this error occurring

In CentOS this might be caused by the SELinux policy. Execute the following code to see if it is enabled.

getsebool httpd_can_sendmail

You can enable it by calling the command below. The -P parameter makes it permanent.

setsebool -P httpd_can_sendmail 1

Best way to check if a URL is valid

You can use this function, but its will return false if website offline.

  function isValidUrl($url) {
    $url = parse_url($url);
    if (!isset($url["host"])) return false;
    return !(gethostbyname($url["host"]) == $url["host"]);
}

how to set background image in submit button?

You can try the following code:

background-image:url('url of your image') 10px 10px no-repeat

Can I make 'git diff' only the line numbers AND changed file names?

git diff master --compact-summary

Output is:

 src/app/components/common/sidebar/toolbar/toolbar.component.html   |  2 +-
 src/app/components/common/sidebar/toolbar/toolbar.component.scss   |  2 --

This is exactly what you need. Same format as when you making commit or pulling new commits from remote.

PS: That's wired that nobody answered this way.

ResourceDictionary in a separate assembly

An example, just to make this a 15 seconds answer -

Say you have "styles.xaml" in a WPF library named "common" and you want to use it from your main application project:

  1. Add a reference from the main project to "common" project
  2. Your app.xaml should contain:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/Common;component/styles.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

How can I find out what FOREIGN KEY constraint references a table in SQL Server?

You could use this query to display Foreign key constaraints:

SELECT
K_Table = FK.TABLE_NAME,
FK_Column = CU.COLUMN_NAME,
PK_Table = PK.TABLE_NAME,
PK_Column = PT.COLUMN_NAME,
Constraint_Name = C.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
SELECT i1.TABLE_NAME, i2.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT ON PT.TABLE_NAME = PK.TABLE_NAME
---- optional:
ORDER BY
1,2,3,4
WHERE PK.TABLE_NAME='YourTable'

Taken from http://blog.sqlauthority.com/2006/11/01/sql-server-query-to-display-foreign-key-relationships-and-name-of-the-constraint-for-each-table-in-database/

Spring 3 MVC resources and tag <mvc:resources />

You can keep rsouces directory in Directory NetBeans: Web Pages Eclipse: webapps

File: dispatcher-servlet.xml

<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <context:component-scan base-package="controller" />

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />

    <mvc:resources location="/resources/theme_name/" mapping="/resources/**"  cache-period="10000"/>
    <mvc:annotation-driven/>

</beans>

File: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
        <url-pattern>*.css</url-pattern>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
</web-app>

In JSP File

<link href="<c:url value="/resources/css/default.css"/>" rel="stylesheet" type="text/css"/>

Change input value onclick button - pure javascript or jQuery

using html5 data attribute...

try this

Html

Product price: $<span id="product_price">500</span>

<br>Total price: $500
<br>
<input type="button" data-quantity="2" value="2&#x00A;Qty">
<input type="button" data-quantity="4" class="mnozstvi_sleva" value="4&#x00A;Qty">
<br>Total
<input type="text" id="count" value="1">

JS

$(function(){
$('input:button').click(function () {
  $('#count').val($(this).data('quantity') * $('#product_price').text());
});
});

fiddle here

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

You should simply create your own folder in htdocs and save your .html and .php files in it. An example is create a folder called myNewFolder directly in htdocs. Don't put it in index.html. Then save all your.html and .php files in it like this-> "localhost/myNewFolder/myFilename.html" or "localhost/myNewFolder/myFilename.php" I hope this helps.

Removing index column in pandas when reading a csv

you can specify which column is an index in your csv file by using index_col parameter of from_csv function if this doesn't solve you problem please provide example of your data

How to run a javascript function during a mouseover on a div

Here's a jQuery solution.

<script type="text/javascript" src="/path/to/your/copy/of/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#sub1").mouseover(function() {
        $("#welcome").toggle();
    });
});
</script>

Using this markup:

<div id="sub1">some text</div>
<div id="welcome" style="display:none;">Welcome message</div>

You didn't really specify if (or when) you wanted to hide the welcome message, but this would toggle hiding or showing each time you moused over the text.

RE error: illegal byte sequence on Mac OS X

A sample command that exhibits the symptom: sed 's/./@/' <<<$'\xfc' fails, because byte 0xfc is not a valid UTF-8 char.
Note that, by contrast, GNU sed (Linux, but also installable on macOS) simply passes the invalid byte through, without reporting an error.

Using the formerly accepted answer is an option if you don't mind losing support for your true locale (if you're on a US system and you never need to deal with foreign characters, that may be fine.)

However, the same effect can be had ad-hoc for a single command only:

LC_ALL=C sed -i "" 's|"iphoneos-cross","llvm-gcc:-O3|"iphoneos-cross","clang:-Os|g' Configure

Note: What matters is an effective LC_CTYPE setting of C, so LC_CTYPE=C sed ... would normally also work, but if LC_ALL happens to be set (to something other than C), it will override individual LC_*-category variables such as LC_CTYPE. Thus, the most robust approach is to set LC_ALL.

However, (effectively) setting LC_CTYPE to C treats strings as if each byte were its own character (no interpretation based on encoding rules is performed), with no regard for the - multibyte-on-demand - UTF-8 encoding that OS X employs by default, where foreign characters have multibyte encodings.

In a nutshell: setting LC_CTYPE to C causes the shell and utilities to only recognize basic English letters as letters (the ones in the 7-bit ASCII range), so that foreign chars. will not be treated as letters, causing, for instance, upper-/lowercase conversions to fail.

Again, this may be fine if you needn't match multibyte-encoded characters such as é, and simply want to pass such characters through.

If this is insufficient and/or you want to understand the cause of the original error (including determining what input bytes caused the problem) and perform encoding conversions on demand, read on below.


The problem is that the input file's encoding does not match the shell's.
More specifically, the input file contains characters encoded in a way that is not valid in UTF-8 (as @Klas Lindbäck stated in a comment) - that's what the sed error message is trying to say by invalid byte sequence.

Most likely, your input file uses a single-byte 8-bit encoding such as ISO-8859-1, frequently used to encode "Western European" languages.

Example:

The accented letter à has Unicode codepoint 0xE0 (224) - the same as in ISO-8859-1. However, due to the nature of UTF-8 encoding, this single codepoint is represented as 2 bytes - 0xC3 0xA0, whereas trying to pass the single byte 0xE0 is invalid under UTF-8.

Here's a demonstration of the problem using the string voilà encoded as ISO-8859-1, with the à represented as one byte (via an ANSI-C-quoted bash string ($'...') that uses \x{e0} to create the byte):

Note that the sed command is effectively a no-op that simply passes the input through, but we need it to provoke the error:

  # -> 'illegal byte sequence': byte 0xE0 is not a valid char.
sed 's/.*/&/' <<<$'voil\x{e0}'

To simply ignore the problem, the above LCTYPE=C approach can be used:

  # No error, bytes are passed through ('á' will render as '?', though).
LC_CTYPE=C sed 's/.*/&/' <<<$'voil\x{e0}'

If you want to determine which parts of the input cause the problem, try the following:

  # Convert bytes in the 8-bit range (high bit set) to hex. representation.
  # -> 'voil\x{e0}'
iconv -f ASCII --byte-subst='\x{%02x}' <<<$'voil\x{e0}'

The output will show you all bytes that have the high bit set (bytes that exceed the 7-bit ASCII range) in hexadecimal form. (Note, however, that that also includes correctly encoded UTF-8 multibyte sequences - a more sophisticated approach would be needed to specifically identify invalid-in-UTF-8 bytes.)


Performing encoding conversions on demand:

Standard utility iconv can be used to convert to (-t) and/or from (-f) encodings; iconv -l lists all supported ones.

Examples:

Convert FROM ISO-8859-1 to the encoding in effect in the shell (based on LC_CTYPE, which is UTF-8-based by default), building on the above example:

  # Converts to UTF-8; output renders correctly as 'voilà'
sed 's/.*/&/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')"

Note that this conversion allows you to properly match foreign characters:

  # Correctly matches 'à' and replaces it with 'ü': -> 'voilü'
sed 's/à/ü/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')"

To convert the input BACK to ISO-8859-1 after processing, simply pipe the result to another iconv command:

sed 's/à/ü/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')" | iconv -t ISO-8859-1

Process list on Linux via Python

You can use a third party library, such as PSI:

PSI is a Python package providing real-time access to processes and other miscellaneous system information such as architecture, boottime and filesystems. It has a pythonic API which is consistent accross all supported platforms but also exposes platform-specific details where desirable.

How to print multiple lines of text with Python

You can use triple quotes (single ' or double "):

a = """
text
text
text
"""

print(a)

Checking for Undefined In React

You can try adding a question mark as below. This worked for me.

 componentWillReceiveProps(nextProps) {
    this.setState({
        title: nextProps?.blog?.title,
        body: nextProps?.blog?.content
     })
    }

SQL Server : Arithmetic overflow error converting expression to data type int

Change SUM(billableDuration) AS NumSecondsDelivered to

sum(cast(billableDuration as bigint)) or

sum(cast(billableDuration as numeric(12, 0))) according to your need.

The resultant type of of Sum expression is the same as the data type used. It throws error at time of overflow. So casting the column to larger capacity data type and then using Sum operation works fine.

What is the location of mysql client ".my.cnf" in XAMPP for Windows?

Go to control panel ? services, look for MySQL and right click choose properties. If there, in “path to EXE file”, there is a parameter like

--defaults-file="X:\path\to\my.ini"

this is the file the server actually uses (independent of what mysql --help prints).

Case vs If Else If: Which is more efficient?

I believe because cases must be constant values, the switch statement does the equivelent of a goto, so based on the value of the variable it jumps to the right case, whereas in the if/then statement it must evaluate each expression.

How do I detect what .NET Framework versions and service packs are installed?

The registry is the official way to detect if a specific version of the Framework is installed.

enter image description here

Which registry keys are needed change depending on the Framework version you are looking for:

Framework Version  Registry Key
------------------------------------------------------------------------------------------
1.0                HKLM\Software\Microsoft\.NETFramework\Policy\v1.0\3705 
1.1                HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322\Install 
2.0                HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Install 
3.0                HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\Setup\InstallSuccess 
3.5                HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Install 
4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Client\Install
4.0 Full Profile   HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full\Install

Generally you are looking for:

"Install"=dword:00000001

except for .NET 1.0, where the value is a string (REG_SZ) rather than a number (REG_DWORD).

Determining the service pack level follows a similar pattern:

Framework Version  Registry Key
------------------------------------------------------------------------------------------
1.0                HKLM\Software\Microsoft\Active Setup\Installed Components\{78705f0d-e8db-4b2d-8193-982bdda15ecd}\Version 
1.0[1]             HKLM\Software\Microsoft\Active Setup\Installed Components\{FDC11A6F-17D1-48f9-9EA3-9051954BAA24}\Version 
1.1                HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322\SP 
2.0                HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\SP 
3.0                HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\SP 
3.5                HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\SP 
4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Client\Servicing
4.0 Full Profile   HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full\Servicing

[1] Windows Media Center or Windows XP Tablet Edition

As you can see, determining the SP level for .NET 1.0 changes if you are running on Windows Media Center or Windows XP Tablet Edition. Again, .NET 1.0 uses a string value while all of the others use a DWORD.

For .NET 1.0 the string value at either of these keys has a format of #,#,####,#. The last # is the Service Pack level.

While I didn't explicitly ask for this, if you want to know the exact version number of the Framework you would use these registry keys:

Framework Version  Registry Key
------------------------------------------------------------------------------------------
1.0                HKLM\Software\Microsoft\Active Setup\Installed Components\{78705f0d-e8db-4b2d-8193-982bdda15ecd}\Version 
1.0[1]             HKLM\Software\Microsoft\Active Setup\Installed Components\{FDC11A6F-17D1-48f9-9EA3-9051954BAA24}\Version 
1.1                HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322 
2.0[2]             HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Version 
2.0[3]             HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Increment
3.0                HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\Version 
3.5                HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Version 
4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Version 
4.0 Full Profile   HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Version 

[1] Windows Media Center or Windows XP Tablet Edition
[2] .NET 2.0 SP1
[3] .NET 2.0 Original Release (RTM)

Again, .NET 1.0 uses a string value while all of the others use a DWORD.

Additional Notes

  • for .NET 1.0 the string value at either of these keys has a format of #,#,####,#. The #,#,#### portion of the string is the Framework version.

  • for .NET 1.1, we use the name of the registry key itself, which represents the version number.

  • Finally, if you look at dependencies, .NET 3.0 adds additional functionality to .NET 2.0 so both .NET 2.0 and .NET 3.0 must both evaulate as being installed to correctly say that .NET 3.0 is installed. Likewise, .NET 3.5 adds additional functionality to .NET 2.0 and .NET 3.0, so .NET 2.0, .NET 3.0, and .NET 3. should all evaluate to being installed to correctly say that .NET 3.5 is installed.

  • .NET 4.0 installs a new version of the CLR (CLR version 4.0) which can run side-by-side with CLR 2.0.

Update for .NET 4.5

There won't be a v4.5 key in the registry if .NET 4.5 is installed. Instead you have to check if the HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full key contains a value called Release. If this value is present, .NET 4.5 is installed, otherwise it is not. More details can be found here and here.

Opencv - Grayscale mode Vs gray color conversion

Note: This is not a duplicate, because the OP is aware that the image from cv2.imread is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)

To illustrate, I've opened up this same color JPEG image:

enter image description here

once using the conversion

img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

and another by loading it in gray scale mode

img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom

enter image description here

I've summed up the diff too to see

import numpy as np
np.sum(diff)
# I got 6143, on a 494 x 750 image

I tried all cv2.imread() modes

Among all the IMREAD_ modes for cv2.imread(), only IMREAD_COLOR and IMREAD_ANYCOLOR can be converted using COLOR_BGR2GRAY, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE

The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)

Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.

In brief, let's not mix the versions and types in the processing pipeline.

So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)

How to stop default link click behavior with jQuery

This code strip all event listeners

var old_element=document.getElementsByClassName(".update-cart");    
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);  

Center text in table cell

I would recommend using CSS for this. You should create a CSS rule to enforce the centering, for example:

.ui-helper-center {
    text-align: center;
}

And then add the ui-helper-center class to the table cells for which you wish to control the alignment:

<td class="ui-helper-center">Content</td>

EDIT: Since this answer was accepted, I felt obligated to edit out the parts that caused a flame-war in the comments, and to not promote poor and outdated practices.

See Gabe's answer for how to include the CSS rule into your page.

IIS7 URL Redirection from root to sub directory

Here it is. Add this code to your web.config file:

<system.webServer>
    <rewrite>
        <rules>
            <rule name="Root Hit Redirect" stopProcessing="true">
                <match url="^$" />
                <action type="Redirect" url="/menu_1/MainScreen.aspx" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

It will do 301 Permanent Redirect (URL will be changed in browser). If you want to have such "redirect" to be invisible (rewrite, internal redirect), then use this rule (the only difference is that "Redirect" has been replaced by "Rewrite"):

<system.webServer>
    <rewrite>
        <rules>
            <rule name="Root Hit Redirect" stopProcessing="true">
                <match url="^$" />
                <action type="Rewrite" url="/menu_1/MainScreen.aspx" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

How to implement a Navbar Dropdown Hover in Bootstrap v4?

Andrei's "complete" jQuery+CSS solution has the right intent, but it's verbose and still incomplete. Incomplete because while it probably covers all the necessary DOM changes, it's missing the firing of custom events. Verbose because it's wheel-reinventing when Bootstrap already provides the dropdown() method, which does everything.

So the correct, DRY solution, which does not rely on the CSS hack often repeated among other answers, is just jQuery:

$('body').on('mouseover mouseout', '.dropdown', function(e) {
    $(e.target).dropdown('toggle');
});

Difference between socket and websocket?

Regarding your question (b), be aware that the Websocket specification hasn't been finalised. According to the W3C:

Implementors should be aware that this specification is not stable.

Personally I regard Websockets to be waaay too bleeding edge to use at present. Though I'll probably find them useful in a year or so.

How to force Laravel Project to use HTTPS for all routes?

I used this at the end of the web.php or api.php file and it worked perfectly:

URL::forceScheme('https');

Empty set literal?

Adding to the crazy ideas: with Python 3 accepting unicode identifiers, you could declare a variable ? = frozenset() (? is U+03D5) and use it instead.

read file in classpath

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class readFile {
    /**
     * feel free to make any modification I have have been here so I feel you
     * 
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        File dir = new File(".");// read file from same directory as source //
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                // if you wanna read file name with txt files
                if (file.getName().contains("txt")) {
                    System.out.println(file.getName());
                }

                // if you want to open text file and read each line then
                if (file.getName().contains("txt")) {
                    try {
                        // FileReader reads text files in the default encoding.
                        FileReader fileReader = new FileReader(
                                file.getAbsolutePath());
                        // Always wrap FileReader in BufferedReader.
                        BufferedReader bufferedReader = new BufferedReader(
                                fileReader);
                        String line;
                        // get file details and get info you need.
                        while ((line = bufferedReader.readLine()) != null) {
                            System.out.println(line);
                            // here you can say...
                            // System.out.println(line.substring(0, 10)); this
                            // prints from 0 to 10 indext
                        }
                    } catch (FileNotFoundException ex) {
                        System.out.println("Unable to open file '"
                                + file.getName() + "'");
                    } catch (IOException ex) {
                        System.out.println("Error reading file '"
                                + file.getName() + "'");
                        // Or we could just do this:
                        ex.printStackTrace();
                    }
                }
            }
        }

    }`enter code here`

}

Git pull command from different user

Was looking for the solution of a similar problem. Thanks to the answer provided by Davlet and Cupcake I was able to solve my problem.

Posting this answer here since I think this is the intended question

So I guess generally the problem that people like me face is what to do when a repo is cloned by another user on a server and that user is no longer associated with the repo.

How to pull from the repo without using the credentials of the old user ?

You edit the .git/config file of your repo.

and change

url = https://<old-username>@github.com/abc/repo.git/

to

url = https://<new-username>@github.com/abc/repo.git/

After saving the changes, from now onwards git pull will pull data while using credentials of the new user.

I hope this helps anyone with a similar problem

jQuery click anywhere in the page except on 1 div

here is what i did. wanted to make sure i could click any of the children in my datepicker without closing it.

$('html').click(function(e){
    if (e.target.id == 'menu_content' || $(e.target).parents('#menu_content').length > 0) {
        // clicked menu content or children
    } else {
        // didnt click menu content
    }
});

my actual code:

$('html').click(function(e){
    if (e.target.id != 'datepicker'
        && $(e.target).parents('#datepicker').length == 0
        && !$(e.target).hasClass('datepicker')
    ) {
        $('#datepicker').remove();
    }
});

Cannot use a CONTAINS or FREETEXT predicate on table or indexed view because it is not full-text indexed

  1. Make sure you have full-text search feature installed.

    Full-Text Search setup

  2. Create full-text search catalog.

     use AdventureWorks
     create fulltext catalog FullTextCatalog as default
    
     select *
     from sys.fulltext_catalogs
    
  3. Create full-text search index.

     create fulltext index on Production.ProductDescription(Description)
     key index PK_ProductDescription_ProductDescriptionID
    

    Before you create the index, make sure:
    - you don't already have full-text search index on the table as only one full-text search index allowed on a table
    - a unique index exists on the table. The index must be based on single-key column, that does not allow NULL.
    - full-text catalog exists. You have to specify full-text catalog name explicitly if there is no default full-text catalog.

You can do step 2 and 3 in SQL Sever Management Studio. In object explorer, right click on a table, select Full-Text index menu item and then Define Full-Text Index... sub-menu item. Full-Text indexing wizard will guide you through the process. It will also create a full-text search catalog for you if you don't have any yet.

enter image description here

You can find more info at MSDN

VS Code - Search for text in all files in a directory

You can do Edit, Find in Files (or Ctrl+Shift+F - default key binding, Cmd+Shift+F on MacOS) to search the Currently open Folder.

There is an ellipsis on the dialog where you can include/exclude files, and options in the search box for matching case/word and using Regex.

CSS way to horizontally align table

Add to the div style:

width: fit-content;

LINQ Group By into a Dictionary Object

I cannot comment on @Michael Blackburn, but I guess you got the downvote because the GroupBy is not necessary in this case.

Use it like:

var lookupOfCustomObjects = listOfCustomObjects.ToLookup(o=>o.PropertyName);
var listWithAllCustomObjectsWithPropertyName = lookupOfCustomObjects[propertyName]

Additionally, I've seen this perform way better than when using GroupBy().ToDictionary().

How to read from stdin line by line in Node

shareing for others:

read stream line by line,should be good for large files piped into stdin, my version:

var n=0;
function on_line(line,cb)
{
    ////one each line
    console.log(n++,"line ",line);
    return cb();
    ////end of one each line
}

var fs = require('fs');
var readStream = fs.createReadStream('all_titles.txt');
//var readStream = process.stdin;
readStream.pause();
readStream.setEncoding('utf8');

var buffer=[];
readStream.on('data', (chunk) => {
    const newlines=/[\r\n]+/;
    var lines=chunk.split(newlines)
    if(lines.length==1)
    {
        buffer.push(lines[0]);
        return;
    }   

    buffer.push(lines[0]);
    var str=buffer.join('');
    buffer.length=0;
    readStream.pause();

    on_line(str,()=>{
        var i=1,l=lines.length-1;
        i--;
        function while_next()
        {
            i++;
            if(i<l)
            {
                return on_line(lines[i],while_next);
            }
            else
            {
                buffer.push(lines.pop());
                lines.length=0;
                return readStream.resume();
            }
        }
        while_next();
    });
  }).on('end', ()=>{
      if(buffer.length)
          var str=buffer.join('');
          buffer.length=0;
        on_line(str,()=>{
            ////after end
            console.error('done')
            ////end after end
        });
  });
readStream.resume();

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

on the BlueStacks emulator worked for me the following solution

Go to ”Settings” -> “Applications” -> “Manage Applications” and select “All

Go to “Google Play Services Framework” and select “Clear Data” & “Clear Cache” to remove all the data.

Go to “Google Play Store” and Select “Clear Data” & “Clear Cache” to remove all the data regarding Google Play Store.

Go to “Settings” -> “Accounts” -> “Google” -> Select “Your Account

Go to “Menu” and Select “Remove Account”.

Now “Restart” your mobile device.

Go to “Menu” and “Add Your Account”.

and try to perform update or download.

How to get substring in C

#include <stdio.h>
#include <string.h>

int main() {
    char src[] = "SexDrugsRocknroll";
    char dest[5] = { 0 }; // 4 chars + terminator */
    int len = strlen(src);
    int i = 0;

    while (i*4 < len) {
        strncpy(dest, src+(i*4), 4);
        i++;

        printf("loop %d : %s\n", i, dest);
    }
}

Parsing huge logfiles in Node.js - read in line-by-line

You can use the inbuilt readline package, see docs here. I use stream to create a new output stream.

var fs = require('fs'),
    readline = require('readline'),
    stream = require('stream');

var instream = fs.createReadStream('/path/to/file');
var outstream = new stream;
outstream.readable = true;
outstream.writable = true;

var rl = readline.createInterface({
    input: instream,
    output: outstream,
    terminal: false
});

rl.on('line', function(line) {
    console.log(line);
    //Do your stuff ...
    //Then write to outstream
    rl.write(cubestuff);
});

Large files will take some time to process. Do tell if it works.

What are the differences between a program and an application?

I use the term program to include applications (apps), utilities and even operating systems like windows, linux and mac OS. We kinda need an overall term for all the different terms available. It might be wrong but works for me. :)

How to change PHP version used by composer

If anyone is still having trouble, remember you can run composer with any php version that you have installed e.g. $ php7.3 -f /usr/local/bin/composer update

Use which composer command to help locate the composer executable.

Navigation Drawer (Google+ vs. YouTube)

Edit #3:

The Navigation Drawer pattern is officially described in the Android documentation!

enter image description here Check out the following links:

  • Design docs can be found here.
  • Developer docs can be found here.

Edit #2:

Roman Nurik (an Android design engineer at Google) has confirmed that the recommended behavior is to not move the Action Bar when opening the drawer (like the YouTube app). See this Google+ post.


Edit #1:

I answered this question a while ago, but I'm back to re-emphasize that Prixing has the best fly-out menu out there... by far. It's absolutely beautiful, perfectly smooth, and it puts Facebook, Google+, and YouTube to shame. EverNote is pretty good too... but still not as perfect as Prixing. Check out this series of posts on how the flyout menu was implemented (from none other than the head developer at Prixing himself!).


Original Answer:

Adam Powell and Richard Fulcher talk about this at 49:47 - 52:50 in the Google I/O talk titled "Navigation in Android".

To summarize their answer, as of the date of this posting the slide out navigation menu is not officially part of the Android application design standard. As you have probably discovered, there's currently no native support for this feature, but there was talk about making this an addition to an upcoming revision of the support package.

With regards to the YouTube and G+ apps, it does seem odd that they behave differently. My best guess is that the reason the YouTube app fixes the position of the action bar is,

  1. One of the most important navigational options for users using the YouTube app is search, which is performed in the SearchView in the action bar. It would make sense to make the action bar static in this regard, since it would allow the user to always have the option to search for new videos.

  2. The G+ app uses a ViewPager to display its content, so making the pull out menu specific to the layout content (i.e. everything under the action bar) wouldn't make much sense. Swiping is supposed to provide a means of navigating between pages, not a means of global navigation. This might be why they decided to do it differently in the G+ app than they did in the YouTube app.

    On another note, check out the Google Play app for another version of the "pull out menu" (when you are at the left most page, swipe left and a pull out, "half-page" menu will appear).

You're right in that this isn't very consistent behavior, but it doesn't seem like there is a 100% consensus within the Android team on how this behavior should be implemented yet. I wouldn't be surprised if in the future the apps are updated so that the navigation in both apps are identical (they seemed very keen on making navigation consistent across all Google-made apps in the talk).

addID in jQuery?

Like this :

var id = $('div.foo').attr('id');
$('div.foo').attr('id', id + ' id_adding');
  1. get actual ID
  2. put actuel ID and add the new one

Angular 2: Get Values of Multiple Checked Checkboxes

I just faced this issue, and decided to make everything work with as less variables as i can, to keep workspace clean. Here is example of my code

<input type="checkbox" (change)="changeModel($event, modelArr, option.value)" [checked]="modelArr.includes(option.value)" />

Method, which called on change is pushing value in model, or removing it.

public changeModel(ev, list, val) {
  if (ev.target.checked) {
    list.push(val);
  } else {
    let i = list.indexOf(val);
    list.splice(i, 1);
  }
}

str.startswith with a list of strings to test for

You can also use any(), map() like so:

if any(map(l.startswith, x)):
    pass # Do something

Or alternatively, using a generator expression:

if any(l.startswith(s) for s in x)
    pass # Do something

SELECT query with CASE condition and SUM()

Select SUM(CASE When CPayment='Cash' Then CAmount Else 0 End ) as CashPaymentAmount,
       SUM(CASE When CPayment='Check' Then CAmount Else 0 End ) as CheckPaymentAmount
from TableOrderPayment
Where ( CPayment='Cash' Or CPayment='Check' ) AND CDate<=SYSDATETIME() and CStatus='Active';

How to get rid of blank pages in PDF exported from SSRS

I recently inherited a report that I needed to make a few changes. After following all the recommendations above, it did not help. The report historically had this extra page, and nobody could figure out why.

I right clicked on the tablix and selected properties. There was a checkbox checked that said add a page break after. After removing this, it prints on one page now.

enter image description here

What is the python "with" statement designed for?

points 1, 2, and 3 being reasonably well covered:

4: it is relatively new, only available in python2.6+ (or python2.5 using from __future__ import with_statement)

What's is the difference between train, validation and test set, in neural networks?

Would appreciate any thoughts on the situation with 3 data sets. Say a logistic regression model is fitted yielding the following accuracy (Gini): Train: 70%; Test 58% and Out-of-time validation: 66%.

Actually all the possible combinations of predictors bring the same results with quite a huge drop between train and test data sets. The sample size is around 8k divided into train and test 70/30. OOT sample contains a few thousands of cases. Regularization, ensembles didn't help in solving this.

I doubt whether this is something I should concern if OOT performance is acceptable and close to train sample performance?

SQL Server 2008 - Login failed. The login is from an untrusted domain and cannot be used with Windows authentication

Just found this thread and posted an alternative answer (copied below) here: https://stackoverflow.com/a/37853766/1948625

Specifically on this question, if the dot "." used in the -S value of the command line means the same as 127.0.0.1, then it could be the same issue as the connection string of the other question. Use the hostname instead, or check your hosts file.


Old question, and my symptoms are slightly different, but same error. My connection string was correct (Integrated security, and I don't provide user and pwd) with data source set to 127.0.0.1. It worked fine for years.

But recently I added a line in the static host file for testing purposes (C:\Windows\System32\drivers\etc\hosts)

127.0.0.1           www.blablatestsite.com

Removing this line and the error is gone.

I got a clue from this article (https://support.microsoft.com/en-gb/kb/896861) which talks about hostnames and loopback.

Other possible fix (if you need to keep that line in the hosts file) is to use the hostname (like MYSERVER01) instead of 127.0.0.1 in the data source of the connection string.

Plotting multiple lines, in different colors, with pandas dataframe

If you have seaborn installed, an easier method that does not require you to perform pivot:

import seaborn as sns

sns.lineplot(data=df, x='x', y='y', hue='color')

Remove a string from the beginning of a string

Remove www. from beginning of string, this is the easiest way (ltrim)

$a="www.google.com";
echo ltrim($a, "www.");

Disable nginx cache for JavaScript files

Remember set sendfile off; or cache headers doesn't work. I use this snipped:

location / {

        index index.php index.html index.htm;
        try_files $uri $uri/ =404; #.s. el /index.html para html5Mode de angular

        #.s. kill cache. use in dev
        sendfile off;
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
        proxy_no_cache 1;
        proxy_cache_bypass 1; 
    }

How to build and use Google TensorFlow C++ api

If you don't want to build Tensorflow yourself and your operating system is Debian or Ubuntu, you can download prebuilt packages with the Tensorflow C/C++ libraries. This distribution can be used for C/C++ inference with CPU, GPU support is not included:

https://github.com/kecsap/tensorflow_cpp_packaging/releases

There are instructions written how to freeze a checkpoint in Tensorflow (TFLearn) and load this model for inference with the C/C++ API:

https://github.com/kecsap/tensorflow_cpp_packaging/blob/master/README.md

Beware: I am the developer of this Github project.

How to scroll to top of the page in AngularJS?

use: $anchorScroll();

with $anchorScroll property

What is the equivalent of ngShow and ngHide in Angular 2+?

Use the [hidden] attribute:

[hidden]="!myVar"

Or you can use *ngIf

*ngIf="myVar"

These are two ways to show/hide an element. The only difference is: *ngIf will remove the element from DOM while [hidden] will tell the browser to show/hide an element using CSS display property by keeping the element in DOM.

Objective-C: Calling selectors with multiple arguments

@Shane Arney

performSelector:withObject:withObject:

You might also want to mention that this method is only for passing maximum 2 arguments, and it cannot be delayed. (such as performSelector:withObject:afterDelay:).

kinda weird that apple only supports 2 objects to be send and didnt make it more generic.

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

One possibility is, if you are familiar with PDF format:

  1. Create some simply PDF with one page (Page should be contained within one object)
  2. Copy object multiply times
  3. Add references to the copied objects to the page catalog
  4. Fix xref table

You get an valid document of any size, entire file will be processed by a reader.

SPAN vs DIV (inline-block)

If you want to have a valid xhtml document then you cannot put a div inside of a paragraph.

Also, a div with the property display: inline-block works differently than a span. A span is by default an inline element, you cannot set the width, height, and other properties associated with blocks. On the other hand, an element with the property inline-block will still "flow" with any surrounding text but you may set properties such as width, height, etc. A span with the property display:block will not flow in the same way as an inline-block element but will create a carriage return and have default margin.

Note that inline-block is not supported in all browsers. For instance in Firefox 2 and less you must use:

display: -moz-inline-stack;

which displays slightly different than an inline block element in FF3.

There is a great article here on creating cross browser inline-block elements.

Specifying ssh key in ansible playbook file

If you run your playbook with ansible-playbook -vvv you'll see the actual command being run, so you can check whether the key is actually being included in the ssh command (and you might discover that the problem was the wrong username rather than the missing key).

I agree with Brian's comment above (and zigam's edit) that the vars section is too late. I also tested including the key in the on-the-fly definition of the host like this

# fails
- name: Add all instance public IPs to host group
  add_host: hostname={{ item.public_ip }} groups=ec2hosts ansible_ssh_private_key_file=~/.aws/dev_staging.pem
  loop: "{{ ec2.instances }}"

but that fails too.

So this is not an answer. Just some debugging help and things not to try.

Get random item from array

If you don't mind picking the same item again at some other time:

$items[rand(0, count($items) - 1)];

Set color of TextView span in Android

If you want more control, you might want to check the TextPaint class. Here is how to use it:

final ClickableSpan clickableSpan = new ClickableSpan() {
    @Override
    public void onClick(final View textView) {
        //Your onClick code here
    }

    @Override
    public void updateDrawState(final TextPaint textPaint) {
        textPaint.setColor(yourContext.getResources().getColor(R.color.orange));
        textPaint.setUnderlineText(true);
    }
};

git checkout tag, git pull fails in branch

You need to set up your tracking (upstream) for the current branch

git branch --set-upstream master origin/master

Is already deprecated instead of that you can use --track flag

git branch --track master origin/master

I also like the doc reference that @casey notice:

-u <upstream>
  Set up <branchname>'s tracking information so <upstream> is considered  
  <branchname>'s upstream branch. If no <branchname> is specified,  
  then it defaults to the current branch.

Is it possible in Java to access private fields via reflection

Yes, it absolutely is - assuming you've got the appropriate security permissions. Use Field.setAccessible(true) first if you're accessing it from a different class.

import java.lang.reflect.*;

class Other
{
    private String str;
    public void setStr(String value)
    {
        str = value;
    }
}

class Test
{
    public static void main(String[] args)
        // Just for the ease of a throwaway test. Don't
        // do this normally!
        throws Exception
    {
        Other t = new Other();
        t.setStr("hi");
        Field field = Other.class.getDeclaredField("str");
        field.setAccessible(true);
        Object value = field.get(t);
        System.out.println(value);
    }
}

And no, you shouldn't normally do this... it's subverting the intentions of the original author of the class. For example, there may well be validation applied in any situation where the field can normally be set, or other fields may be changed at the same time. You're effectively violating the intended level of encapsulation.

.gitignore file for java eclipse project

put .gitignore in your main catalog

git status (you will see which files you can commit)
git add -A
git commit -m "message"
git push

Convert float to string with precision & number of decimal digits specified?

Here I am providing a negative example where your want to avoid when converting floating number to strings.

float num=99.463;
float tmp1=round(num*1000);
float tmp2=tmp1/1000;
cout << tmp1 << " " << tmp2 << " " << to_string(tmp2) << endl;

You get

99463 99.463 99.462997

Note: the num variable can be any value close to 99.463, you will get the same print out. The point is to avoid the convenient c++11 "to_string" function. It took me a while to get out this trap. The best way is the stringstream and sprintf methods (C language). C++11 or newer should provided a second parameter as the number of digits after the floating point to show. Right now the default is 6. I am positing this so that others won't wast time on this subject.

I wrote my first version, please let me know if you find any bug that needs to be fixed. You can control the exact behavior with the iomanipulator. My function is for showing the number of digits after the decimal point.

string ftos(float f, int nd) {
   ostringstream ostr;
   int tens = stoi("1" + string(nd, '0'));
   ostr << round(f*tens)/tens;
   return ostr.str();
}

How to check if function exists in JavaScript?

For me the easiest way :

function func_exists(fname)
{
  return (typeof window[fname] === 'function');
}

Create Word Document using PHP in Linux

There are 2 options to create quality word documents. Use COM to communicate with word (this requires a windows php server at least). Use openoffice and it's API to create and save documents in word format.

How do I restrict my EditText input to numerical (possibly decimal and signed) input?

TO set the input type of EditText as decimal use this code:

EditText edit = new EditText(this);
edit.SetRawInputType(Android.Text.InputTypes.NumberFlagDecimal | Android.Text.InputTypes.ClassNumber);

prevent iphone default keyboard when focusing an <input>

You can add a callback function to your DatePicker to tell it to blur the input field before showing the DatePicker.

$('.selector').datepicker({
   beforeShow: function(){$('input').blur();}
});

Note: The iOS keyboard will appear for a fraction of a second and then hide.

Running ASP.Net on a Linux based server

Since the technologies evolve and this question is top ranked in google, we need to include beyond the mono the new asp.net core, which is a complete rewrite of the asp.net to run for production in Linux and Windows and for development for Linux, Windows and Mac:

You can develop and run your ASP.NET Core apps cross-platform on Windows, Mac and Linux. ASP.NET Core is open source at GitHub.

Calculate the number of business days between two dates?

So I had a similar task except I had to calculate business days left (from date should not be more than to date), and end date should skip to next business day.

To make it more understandable/readable, I did this in the following steps

  1. Updated toDate to the next business day if it is on weekend.

  2. Find out the number of complete weeks between dates, and for each complete week consider 5 days in running total.

  3. Now days left are only different of from and to weekdays (it won't be more than 6 days), so wrote a small loop to get it (skip Saturday and Sunday)

     public static int GetBusinessDaysLeft(DateTime fromDate, DateTime toDate)
     {
         //Validate that startDate should be less than endDate
         if (fromDate >= toDate) return 0;
    
         //Move end date to Monday if on weekends
         if (toDate.DayOfWeek == DayOfWeek.Saturday || toDate.DayOfWeek == DayOfWeek.Sunday)
             while (toDate.DayOfWeek != DayOfWeek.Monday)
                 toDate = toDate.AddDays(+1);
    
         //Consider 5 days per complete week in between start and end dates
         int remainder, quotient = Math.DivRem((toDate - fromDate).Days, 7, out remainder);
         var daysDiff = quotient * 5;
    
         var curDay = fromDate;
         while (curDay.DayOfWeek != toDate.DayOfWeek)
         {
             curDay = curDay.AddDays(1);
             if (curDay.DayOfWeek == DayOfWeek.Saturday || curDay.DayOfWeek == DayOfWeek.Sunday)
                 continue;
    
             daysDiff += 1;
         }
         return daysDiff;
     }
    

What is the most effective way for float and double comparison?

As others have pointed out, using a fixed-exponent epsilon (such as 0.0000001) will be useless for values away from the epsilon value. For example, if your two values are 10000.000977 and 10000, then there are NO 32-bit floating-point values between these two numbers -- 10000 and 10000.000977 are as close as you can possibly get without being bit-for-bit identical. Here, an epsilon of less than 0.0009 is meaningless; you might as well use the straight equality operator.

Likewise, as the two values approach epsilon in size, the relative error grows to 100%.

Thus, trying to mix a fixed point number such as 0.00001 with floating-point values (where the exponent is arbitrary) is a pointless exercise. This will only ever work if you can be assured that the operand values lie within a narrow domain (that is, close to some specific exponent), and if you properly select an epsilon value for that specific test. If you pull a number out of the air ("Hey! 0.00001 is small, so that must be good!"), you're doomed to numerical errors. I've spent plenty of time debugging bad numerical code where some poor schmuck tosses in random epsilon values to make yet another test case work.

If you do numerical programming of any kind and believe you need to reach for fixed-point epsilons, READ BRUCE'S ARTICLE ON COMPARING FLOATING-POINT NUMBERS.

Comparing Floating Point Numbers

Default password of mysql in ubuntu server 16.04

As of Ubuntu 20.04, using the default MariaDB 10.3 package, these were the necessary steps (remix of earlier answers from this thread):

  1. Log in to mysql as root: sudo mysql -u root
  2. Update the password:
USE mysql;
UPDATE user set authentication_string=PASSWORD("YOUR-NEW-ROOT-PASSWORD") where User='root';
UPDATE user set plugin="mysql_native_password" where User='root';
FLUSH privileges;
QUIT
  1. sudo service mysql restart

After this, you can connect to your local mysql with your new password: mysql -u root -p

SQL Server: Examples of PIVOTing String data

I had a situation where I was parsing strings and the first two positions of the string in question would be the field names of a healthcare claims coding standard. So I would strip out the strings and get values for F4, UR and UQ or whatnot. This was great on one record or a few records for one user. But when I wanted to see hundreds of records and the values for all usersz it needed to be a PIVOT. This was wonderful especially for exporting lots of records to excel. The specific reporting request I had received was "every time someone submitted a claim for Benadryl, what value did they submit in fields F4, UR, and UQ. I had an OUTER APPLY that created the ColTitle and the value fields below

PIVOT(
  min(value)
  FOR ColTitle in([F4], [UR], [UQ])
 )

How to set div width using ng-style

ngStyle accepts a map:

$scope.myStyle = {
    "width" : "900px",
    "background" : "red"
};

Fiddle

Python Pandas replicate rows in dataframe

Other way is using concat() function:

import pandas as pd

In [603]: df = pd.DataFrame({'col1':list("abc"),'col2':range(3)},index = range(3))

In [604]: df
Out[604]: 
  col1  col2
0    a     0
1    b     1
2    c     2

In [605]: pd.concat([df]*3, ignore_index=True) # Ignores the index
Out[605]: 
  col1  col2
0    a     0
1    b     1
2    c     2
3    a     0
4    b     1
5    c     2
6    a     0
7    b     1
8    c     2

In [606]: pd.concat([df]*3)
Out[606]: 
  col1  col2
0    a     0
1    b     1
2    c     2
0    a     0
1    b     1
2    c     2
0    a     0
1    b     1
2    c     2

Select multiple rows with the same value(s)

You need to understand that when you include GROUP BY in your query you are telling SQL to combine rows. you will get one row per unique Locus value. The Having then filters those groups. Usually you specify an aggergate function in the select list like:

--show how many of each Locus there is
SELECT COUNT(*),Locus FROM Genes GROUP BY Locus

--only show the groups that have more than one row in them
SELECT COUNT(*),Locus FROM Genes GROUP BY Locus HAVING COUNT(*)>1

--to just display all the rows for your condition, don't use GROUP BY or HAVING
SELECT * FROM Genes WHERE Locus = '3' AND Chromosome = '10'

How do I break out of nested loops in Java?

I never use labels. It seems like a bad practice to get into. Here's what I would do:

boolean finished = false;
for (int i = 0; i < 5 && !finished; i++) {
    for (int j = 0; j < 5; j++) {
        if (i * j > 6) {
            finished = true;
            break;
        }
    }
}

Java8: sum values from specific field of the objects in a list

You can try

int sum = list.stream().filter(o->o.field>10).mapToInt(o->o.field).sum();

Like explained here

GridLayout (not GridView) how to stretch all children evenly

In my case I was adding the buttons dynamically so my solution required some XML part and some Java part. I had to find and mix solutions from a few different places and thought I will share it here so someone else looking for the similar solution might find it helpful.

First part of my layout file XML...

<android.support.v7.widget.GridLayout
    xmlns:grid="http://schemas.android.com/apk/res-auto"
    android:id="@+id/gl_Options"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    grid:useDefaultMargins="true">
</android.support.v7.widget.GridLayout>

grid:useDefaultMargins="true" is not required but I added because that looked better to me, you may apply other visual affects (e.g. padding) as mentioned in some answers here. Now for the buttons as I have to add them dynamically. Here is the Java part of my code to make these buttons, I am including only those lines related to this context. Assume I have to make buttons from as many myOptions are available to my code and I am not copying the OnClickListener code as well.

import android.support.v7.widget.GridLayout;   //Reference to Library

public class myFragment extends Fragment{
    GridLayout gl_Options;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        gl_AmountOptions = (GridLayout)view.findViewById( R.id.gl_AmountOptions );
        ...
        gl_Options.removeAllViews();     // Remove all existing views
        gl_AmountOptions.setColumnCount( myOptions.length <= 9 ? 3: 4 );  // Set appropriate number of columns

        for( String opt : myOptions ) {
            GridLayout.LayoutParams lParams   = new GridLayout.LayoutParams( GridLayout.spec( GridLayout.UNDEFINED, 1f), GridLayout.spec( GridLayout.UNDEFINED, 1f));
            // The above defines LayoutParameters as not specified Column and Row with grid:layout_columnWeight="1" and grid:layout_rowWeight="1"
            lParams.width = 0;    // Setting width to "0dp" so weight is applied instead

            Button b = new Button(this.getContext());
            b.setText( opt );
            b.setLayoutParams(lParams);
            b.setOnClickListener( myClickListener );
            gl_Options.addView( b );
        }
    }
}

As we are using GridLayout from support library and not the standard GridLayout, we have to tell grade about that in YourProject.grade file.

dependencies {
    compile 'com.android.support:appcompat-v7:23.4.0'
    ...
    compile 'com.android.support:gridlayout-v7:23.4.0'
}

How to replace (null) values with 0 output in PIVOT

You have to account for all values in the pivot set. you can accomplish this using a cartesian product.

select pivoted.*
from (
    select cartesian.key1, cartesian.key2, isnull(relationship.[value],'nullvalue') as [value]
    from (
      select k1.key1, k2.key2
      from ( select distinct key1 from relationship) k1
          ,( select distinct key2 from relationship) k2
    ) cartesian
      left outer join relationship on relationship.key1 = cartesian.key1 and  relationship.key2 = carterisan.key2
) data
  pivot (
    max(data.value) for ([key2_v1], [key2_v2], [key2_v3], ...)
  ) pivoted

What is the significance of url-pattern in web.xml and how to configure servlet?

Servlet-mapping has two child tags, url-pattern and servlet-name. url-pattern specifies the type of urls for which, the servlet given in servlet-name should be called. Be aware that, the container will use case-sensitive for string comparisons for servlet matching.

First specification of url-pattern a web.xml file for the server context on the servlet container at server .com matches the pattern in <url-pattern>/status/*</url-pattern> as follows:

http://server.com/server/status/synopsis               = Matches
http://server.com/server/status/complete?date=today    = Matches
http://server.com/server/status                        = Matches
http://server.com/server/server1/status                = Does not match

Second specification of url-pattern A context located at the path /examples on the Agent at example.com matches the pattern in <url-pattern>*.map</url-pattern> as follows:

 http://server.com/server/US/Oregon/Portland.map    = Matches
 http://server.com/server/US/server/Seattle.map     = Matches
 http://server.com/server/Paris.France.map          = Matches
 http://server.com/server/US/Oregon/Portland.MAP    = Does not match, the extension is uppercase
 http://example.com/examples/interface/description/mail.mapi  =Does not match, the extension is mapi rather than map`

Third specification of url-mapping,A mapping that contains the pattern <url-pattern>/</url-pattern> matches a request if no other pattern matches. This is the default mapping. The servlet mapped to this pattern is called the default servlet.

The default mapping is often directed to the first page of an application. Explicitly providing a default mapping also ensures that malformed URL requests into the application return are handled by the application rather than returning an error.

The servlet-mapping element below maps the server servlet instance to the default mapping.

<servlet-mapping>
  <servlet-name>server</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

For the context that contains this element, any request that is not handled by another mapping is forwarded to the server servlet.

And Most importantly we should Know about Rule for URL path mapping

  1. The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the servlet.
  2. The container will recursively try to match the longest path-prefix. This is done by stepping down the path tree a directory at a time, using the ’/’ character as a path separator. The longest match determines the servlet selected.
  3. If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container will try to match a servlet that handles requests for the extension. An extension is defined as the part of the last segment after the last ’.’ character.
  4. If neither of the previous three rules result in a servlet match, the container will attempt to serve content appropriate for the resource requested. If a “default” servlet is defined for the application, it will be used.

Reference URL Pattern

Android SDK location

If you have downloaded sdk manager zip (from https://developer.android.com/studio/#downloads), then you have Android SDK Location as root of the extracted folder.

So silly, But it took time for me as a beginner.

ActiveMQ connection refused

Your application is not able to connect to activemq. Check that your activemq is running and listening on localhost 61616.

You can try using: netstat -a to check if the activemq process has started. Or try check if you can access your actvemq using admin page: localhost:8161/admin/queues.jsp

On mac you will start your activemq using:

$ACTMQ_HOME/bin/activemq start 

Or if your config file (activemq.xml ) if located in another location you can use:

$ACTMQ_HOME/bin/activemq start xbean:file:${location_of_your_config_file}

In your case the executable is under: bin/macosx/activemq so you need to use: $ACTMQ_HOME/bin/macosx/activemq start

The program can't start because MSVCR110.dll is missing from your computer

I would like to quote an answer given by Microsoft support engineer at here:-

http://answers.microsoft.com/en-us/windows/forum/windows_8-winapps/the-program-cant-start-because-msvcr110dll-is/f052d325-3af9-4ae5-990b-b080799724db

Hi Henny, MSVCR110.dll is the Microsoft Visual C++ Redistributable dll that is needed for projects built with Visual Studio 2011. The dll letters spell this out. MS = Microsoft, V = Visual, C = C++, R = Redistributable For Winroy to get started, this file is probably needed. This error appears when you wish to run a software which require the Microsoft Visual C++ Redistributable 2012. The redistributable can easily be downloaded on the Microsoft website as x86 or x64 edition. Depending on the software you wish to install you need to install either the 32 bit or the 64 bit version. Refer the following link: http://www.microsoft.com/en-us/download/details.aspx?id=30679# Please let us know if the issue persists. We will be happy to assist you further. Thanks, Yaqub Khan - Microsoft Support Engineer

Populate a datagridview with sql query results

You don't need bindingSource1

Just set dataGridView1.DataSource = table;

git push to specific branch

The answers in question you linked-to are all about configuring git so that you can enter very short git push commands and have them do whatever you want. Which is great, if you know what you want and how to spell that in Git-Ese, but you're new to git! :-)

In your case, Petr Mensik's answer is the (well, "a") right one. Here's why:

The command git push remote roots around in your .git/config file to find the named "remote" (e.g., origin). The config file lists:

  • where (URL-wise) that remote "lives" (e.g., ssh://hostname/path)
  • where pushes go, if different
  • what gets pushed, if you didn't say what branch(es) to push
  • what gets fetched when you run git fetch remote

When you first cloned the repo—whenever that was—git set up default values for some of these. The URL is whatever you cloned from and the rest, if set or unset, are all "reasonable" defaults ... or, hmm, are they?

The issue with these is that people have changed their minds, over time, as to what is "reasonable". So now (depending on your version of git and whether you've configured things in detail), git may print a lot of warnings about defaults changing in the future. Adding the name of the "branch to push"—amd_qlp_tester—(1) shuts it up, and (2) pushes just that one branch.

If you want to push more conveniently, you could do that with:

git push origin

or even:

git push

but whether that does what you want, depends on whether you agree with "early git authors" that the original defaults are reasonable, or "later git authors" that the original defaults aren't reasonable. So, when you want to do all the configuration stuff (eventually), see the question (and answers) you linked-to.

As for the name origin/amd_qlp_tester in the first place: that's actually a local entity (a name kept inside your repo), even though it's called a "remote branch". It's git's best guess at "where amd_qlp_tester is over there". Git updates it when it can.

How to inherit constructors?

Do i really have to copy all constructors from Foo into Bar and Bah? And then if i change a constructor signature in Foo, do i have to update it in Bar and Bah?

Yes, if you use constructors to create instances.

Is there no way to inherit constructors?

Nope.

Is there no way to encourage code reuse?

Well, I won't get into whether inheriting constructors would be a good or bad thing and whether it would encourage code reuse, since we don't have them and we're not going to get them. :-)

But here in 2014, with the current C#, you can get something very much like inherited constructors by using a generic create method instead. It can be a useful tool to have in your belt, but you wouldn't reach for it lightly. I reached for it recently when faced with needing to pass something into the constructor of a base type used in a couple of hundred derived classes (until recently, the base didn't need any arguments, and so the default constructor was fine — the derived classes didn't declare constructors at all, and got the automatically-supplied one).

It looks like this:

// In Foo:
public T create<T>(int i) where: where T : Foo, new() {
    T obj = new T();
    // Do whatever you would do with `i` in `Foo(i)` here, for instance,
    // if you save it as a data member;  `obj.dataMember = i;`
    return obj;
}

That says that you can call the generic create function using a type parameter which is any subtype of Foo that has a zero-arguments constructor.

Then, instead of doing Bar b new Bar(42), you'd do this:

var b = Foo.create<Bar>(42);
// or
Bar b = Foo.create<Bar>(42);
// or
var b = Bar.create<Bar>(42); // But you still need the <Bar> bit
// or
Bar b = Bar.create<Bar>(42);

There I've shown the create method being on Foo directly, but of course it could be in a factory class of some sort, if the information it's setting up can be set by that factory class.

Just for clarity: The name create isn't important, it could be makeThingy or whatever else you like.

Full Example

using System.IO;
using System;

class Program
{
    static void Main()
    {
        Bar b1 = Foo.create<Bar>(42);
        b1.ShowDataMember("b1");

        Bar b2 = Bar.create<Bar>(43); // Just to show `Foo.create` vs. `Bar.create` doesn't matter
        b2.ShowDataMember("b2");
    }

    class Foo
    {
        public int DataMember { get; private set; }

        public static T create<T>(int i) where T: Foo, new()
        {
            T obj = new T();
            obj.DataMember = i;
            return obj;
        }
    }

    class Bar : Foo
    {
        public void ShowDataMember(string prefix)
        {
            Console.WriteLine(prefix + ".DataMember = " + this.DataMember);
        }
    }
}

Convert laravel object to array

$res = ActivityServer::query()->select('channel_id')->where(['id' => $id])->first()->attributesToArray();

I use get(), it returns an object, I use the attributesToArray() to change the object attribute to an array.

What is the simplest C# function to parse a JSON string into an object?

I think this is what you want:

JavaScriptSerializer JSS = new JavaScriptSerializer();
T obj = JSS.Deserialize<T>(String);

Import JSON file in React

there are multiple ways to do this without using any third-party code or libraries (the recommended way).

1st STATIC WAY: create a .json file then import it in your react component example

my file name is "example.json"

{"example" : "my text"}

the example key inside the example.json can be anything just keep in mind to use double quotes to prevent future issues.

How to import in react component

import myJson from "jsonlocation";

and you can use it anywhere like this

myJson.example

now there are a few things to consider. With this method, you are forced to declare your import at the top of the page and cannot dynamically import anything.

Now, what about if we want to dynamically import the JSON data? example a multi-language support website?

2 DYNAMIC WAY

1st declare your JSON file exactly like my example above

but this time we are importing the data differently.

let language = require('./en.json');

this can access the same way.

but wait where is the dynamic load?

here is how to load the JSON dynamically

let language = require(`./${variable}.json`);

now make sure all your JSON files are within the same directory

here you can use the JSON the same way as the first example

myJson.example

what changed? the way we import because it is the only thing we really need.

I hope this helps.

Remove all special characters with RegExp

str.replace(/\s|[0-9_]|\W|[#$%^&*()]/g, "") I did sth like this. But there is some people who did it much easier like str.replace(/\W_/g,"");

Serializing list to JSON

Yes, but then what do you do about the django objects? simple json tends to choke on them.

If the objects are individual model objects (not querysets, e.g.), I have occasionally stored the model object type and the pk, like so:

seralized_dict = simplejson.dumps(my_dict, 
                     default=lambda a: "[%s,%s]" % (str(type(a)), a.pk)
                     )

to de-serialize, you can reconstruct the object referenced with model.objects.get(). This doesn't help if you are interested in the object details at the type the dict is stored, but it's effective if all you need to know is which object was involved.

How to automatically generate getters and setters in Android Studio

for macOS, ?+N by default.

Right-click and choose "Generate..." to see current mapping. You can select multiple fields for which to generate getters/setters with one step.

See http://www.jetbrains.com/idea/webhelp/generating-getters-and-setters.html

How to set the width of a RaisedButton in Flutter?

If you have a button inside a Column() and want the button to take maximum width, set:

crossAxisAlignment: CrossAxisAlignment.stretch

in your Column widget. Now everything under this Column() will have maximum available width

INSERT ... ON DUPLICATE KEY (do nothing)

HOW TO IMPLEMENT 'insert if not exist'?

1. REPLACE INTO

pros:

  1. simple.

cons:

  1. too slow.

  2. auto-increment key will CHANGE(increase by 1) if there is entry matches unique key or primary key, because it deletes the old entry then insert new one.

2. INSERT IGNORE

pros:

  1. simple.

cons:

  1. auto-increment key will not change if there is entry matches unique key or primary key but auto-increment index will increase by 1

  2. some other errors/warnings will be ignored such as data conversion error.

3. INSERT ... ON DUPLICATE KEY UPDATE

pros:

  1. you can easily implement 'save or update' function with this

cons:

  1. looks relatively complex if you just want to insert not update.

  2. auto-increment key will not change if there is entry matches unique key or primary key but auto-increment index will increase by 1

4. Any way to stop auto-increment key increasing if there is entry matches unique key or primary key?

As mentioned in the comment below by @toien: "auto-increment column will be effected depends on innodb_autoinc_lock_mode config after version 5.1" if you are using innodb as your engine, but this also effects concurrency, so it needs to be well considered before used. So far I'm not seeing any better solution.

Adding elements to a C# array

You can use a generic collection, like List<>

List<string> list = new List<string>();

// add
list.Add("element");

// remove
list.Remove("element");

how to display data values on Chart.js

Based on @Ross's answer answer for Chart.js 2.0 and up, I had to include a little tweak to guard against the case when the bar's heights comes too chose to the scale boundary.

Example

The animation attribute of the bar chart's option:

animation: {
            duration: 500,
            easing: "easeOutQuart",
            onComplete: function () {
                var ctx = this.chart.ctx;
                ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
                ctx.textAlign = 'center';
                ctx.textBaseline = 'bottom';

                this.data.datasets.forEach(function (dataset) {
                    for (var i = 0; i < dataset.data.length; i++) {
                        var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
                            scale_max = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._yScale.maxHeight;
                        ctx.fillStyle = '#444';
                        var y_pos = model.y - 5;
                        // Make sure data value does not get overflown and hidden
                        // when the bar's value is too close to max value of scale
                        // Note: The y value is reverse, it counts from top down
                        if ((scale_max - model.y) / scale_max >= 0.93)
                            y_pos = model.y + 20; 
                        ctx.fillText(dataset.data[i], model.x, y_pos);
                    }
                });               
            }
        }

JavaScript property access: dot notation vs. brackets?

You have to use square bracket notation when -

  1. The property name is number.

    var ob = {
      1: 'One',
      7 : 'Seven'
    }
    ob.7  // SyntaxError
    ob[7] // "Seven"
    
  2. The property name has special character.

    var ob = {
      'This is one': 1,
      'This is seven': 7,
    }  
    ob.'This is one'  // SyntaxError
    ob['This is one'] // 1
    
  3. The property name is assigned to a variable and you want to access the property value by this variable.

    var ob = {
      'One': 1,
      'Seven': 7,
    }
    
    var _Seven = 'Seven';
    ob._Seven  // undefined
    ob[_Seven] // 7
    

Inline <style> tags vs. inline css properties

Whenever is possible is preferable to use class .myclass{} and identifier #myclass{}, so use a dedicated css file or tag <style></style> within an html. Inline style is good to change css option dynamically with javascript.

How to select a directory and store the location using tkinter in Python

This code may be helpful for you.

from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()

jQuery ajax post file field

File uploads can not be done this way, no matter how you break it down. If you want to do an ajax/async upload, I would suggest looking into something like Uploadify, or Valums

Export to xls using angularjs

One starting point could be to use this directive (ng-csv) just download the file as csv and that's something excel can understand

http://ngmodules.org/modules/ng-csv

Maybe you can adapt this code (updated link):

http://jsfiddle.net/Sourabh_/5ups6z84/2/

Altough it seems XMLSS (it warns you before opening the file, if you choose to open the file it will open correctly)

var tableToExcel = (function() {

  var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }

  return function(table, name) {
    if (!table.nodeType) table = document.getElementById(table)
    var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
    window.location.href = uri + base64(format(template, ctx))
  }
})()

How do I concatenate two strings in Java?

You can concatenate Strings using the + operator:

String a="hello ";
String b="world.";
System.out.println(a+b);

Output:

hello world.

That's it

What is the difference between Bower and npm?

Found this useful explanation from http://ng-learn.org/2013/11/Bower-vs-npm/

On one hand npm was created to install modules used in a node.js environment, or development tools built using node.js such Karma, lint, minifiers and so on. npm can install modules locally in a project ( by default in node_modules ) or globally to be used by multiple projects. In large projects the way to specify dependencies is by creating a file called package.json which contains a list of dependencies. That list is recognized by npm when you run npm install, which then downloads and installs them for you.

On the other hand bower was created to manage your frontend dependencies. Libraries like jQuery, AngularJS, underscore, etc. Similar to npm it has a file in which you can specify a list of dependencies called bower.json. In this case your frontend dependencies are installed by running bower install which by default installs them in a folder called bower_components.

As you can see, although they perform a similar task they are targeted to a very different set of libraries.

JPA Query.getResultList() - use in a generic way

If you need a more convenient way to access the results, it's possible to transform the result of an arbitrarily complex SQL query to a Java class with minimal hassle:

Query query = em.createNativeQuery("select 42 as age, 'Bob' as name from dual", 
        MyTest.class);
MyTest myTest = (MyTest) query.getResultList().get(0);
assertEquals("Bob", myTest.name);

The class needs to be declared an @Entity, which means you must ensure it has an unique @Id.

@Entity
class MyTest {
    @Id String name;
    int age;
}

Check table exist or not before create it in Oracle

As Rene also commented, it's quite uncommon to check first and then create the table. If you want to have a running code according to your method, this will be:

declare
nCount NUMBER;
v_sql LONG;

begin
SELECT count(*) into nCount FROM dba_tables where table_name = 'EMPLOYEE';
IF(nCount <= 0)
THEN
v_sql:='
create table EMPLOYEE
(
ID NUMBER(3),
NAME VARCHAR2(30) NOT NULL
)';
execute immediate v_sql;

END IF;
end;

But I'd rather go catch on the Exception, saves you some unnecessary lines of code:

declare
v_sql LONG;
begin

v_sql:='create table EMPLOYEE
  (
  ID NUMBER(3),
  NAME VARCHAR2(30) NOT NULL
  )';
execute immediate v_sql;

EXCEPTION
    WHEN OTHERS THEN
      IF SQLCODE = -955 THEN
        NULL; -- suppresses ORA-00955 exception
      ELSE
         RAISE;
      END IF;
END; 
/

How do you calculate the variance, median, and standard deviation in C++ or Java?

To calculate the mean, loop through the list/array of numbers, keeping track of the partial sums and the length. Then return the sum/length.

double sum = 0.0;
int length = 0;

for( double number : numbers ) {
    sum += number;
    length++;
}

return sum/length;

Variance is calculated similarly. Standard deviation is simply the square root of the variance:

double stddev = Math.sqrt( variance );

Android - How to download a file from a webserver

Download File Usind Download Manager

    DownloadManager downloadmanager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    Uri uri = Uri.parse("https://www.globalgreyebooks.com/content/books/ebooks/game-of-life.pdf");

    DownloadManager.Request request = new DownloadManager.Request(uri);
    request.setTitle("My File");
    request.setDescription("Downloading");//request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,"game-of-life");
    downloadmanager.enqueue(request);

Header div stays at top, vertical scrolling div below with scrollbar only attached to that div

Here is a demo. Use position:fixed; top:0; left:0; so the header always stay on top.

?#header {
    background:red;
    height:50px;
    width:100%;
    position:fixed;
    top:0;
    left:0;    
}.scroller {
    height:300px; 
    overflow:scroll;    
}

Can I delete data from the iOS DeviceSupport directory?

More Suggestive answer supporting rmaddy's answer as our primary purpose is to delete unnecessary file and folder:

  1. Delete this folder after every few days interval. Most of the time, it occupy huge space!

      ~/Library/Developer/Xcode/DerivedData
    
  2. All your targets are kept in the archived form in Archives folder. Before you decide to delete contents of this folder, here is a warning - if you want to be able to debug deployed versions of your App, you shouldn’t delete the archives. Xcode will manage of archives and creates new file when new build is archived.

      ~/Library/Developer/Xcode/Archives
    
  3. iOS Device Support folder creates a subfolder with the device version as an identifier when you attach the device. Most of the time it’s just old stuff. Keep the latest version and rest of them can be deleted (if you don’t have an app that runs on 5.1.1, there’s no reason to keep the 5.1.1 directory/directories). If you really don't need these, delete. But we should keep a few although we test app from device mostly.

    ~/Library/Developer/Xcode/iOS DeviceSupport
    
  4. Core Simulator folder is familiar for many Xcode users. It’s simulator’s territory; that's where it stores app data. It’s obvious that you can toss the older version simulator folder/folders if you no longer support your apps for those versions. As it is user data, no big issue if you delete it completely but it’s safer to use ‘Reset Content and Settings’ option from the menu to delete all of your app data in a Simulator.

      ~/Library/Developer/CoreSimulator 
    

(Here's a handy shell command for step 5: xcrun simctl delete unavailable )

  1. Caches are always safe to delete since they will be recreated as necessary. This isn’t a directory; it’s a file of kind Xcode Project. Delete away!

    ~/Library/Caches/com.apple.dt.Xcode
    
  2. Additionally, Apple iOS device automatically syncs specific files and settings to your Mac every time they are connected to your Mac machine. To be on safe side, it’s wise to use Devices pane of iTunes preferences to delete older backups; you should be retaining your most recent back-ups off course.

     ~/Library/Application Support/MobileSync/Backup
    

Source: https://ajithrnayak.com/post/95441624221/xcode-users-can-free-up-space-on-your-mac

I got back about 40GB!

fetch from origin with deleted remote branches?

Regarding git fetch -p, its behavior changed in Git 1.9, and only Git 2.9.x/2.10 reflects that.

See commit 9e70233 (13 Jun 2016) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 1c22105, 06 Jul 2016)

fetch: document that pruning happens before fetching

This was changed in 10a6cc8 (fetch --prune: Run prune before fetching, 2014-01-02), but it seems that nobody in that discussion realized we were advertising the "after" explicitly.

So the documentation now states:

Before fetching, remove any remote-tracking references that no longer exist on the remote

That is because:

When we have a remote-tracking branch named "frotz/nitfol" from a previous fetch, and the upstream now has a branch named "frotz", fetch would fail to remove "frotz/nitfol" with a "git fetch --prune" from the upstream. git would inform the user to use "git remote prune" to fix the problem.

Change the way "fetch --prune" works by moving the pruning operation before the fetching operation. This way, instead of warning the user of a conflict, it automatically fixes it.

Commit only part of a file in Git

vim-gitgutter plugin can stage hunks without leaving vim editor using

:GitGutterStageHunk

Beside this, it provides other cool features like a diff sign column as in some modern IDEs

If only part of hunk should be staged vim-fugitive

:Gdiff

allows visual range selection then :'<,'>diffput or :'<,'>diffget to stage/revert individual line changes.

How do I stop/start a scheduled task on a remote computer programmatically?

Note: "schtasks" (see the other, accepted response) has replaced "at". However, "at" may be of use if the situation calls for compatibility with older versions of Windows that don't have schtasks.

Command-line help for "at":

C:\>at /?
The AT command schedules commands and programs to run on a computer at
a specified time and date. The Schedule service must be running to use
the AT command.

AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]]
AT [\\computername] time [/INTERACTIVE]
    [ /EVERY:date[,...] | /NEXT:date[,...]] "command"

\\computername     Specifies a remote computer. Commands are scheduled on the
                   local computer if this parameter is omitted.
id                 Is an identification number assigned to a scheduled
                   command.
/delete            Cancels a scheduled command. If id is omitted, all the
                   scheduled commands on the computer are canceled.
/yes               Used with cancel all jobs command when no further
                   confirmation is desired.
time               Specifies the time when command is to run.
/interactive       Allows the job to interact with the desktop of the user
                   who is logged on at the time the job runs.
/every:date[,...]  Runs the command on each specified day(s) of the week or
                   month. If date is omitted, the current day of the month
                   is assumed.
/next:date[,...]   Runs the specified command on the next occurrence of the
                   day (for example, next Thursday).  If date is omitted, the
                   current day of the month is assumed.
"command"          Is the Windows NT command, or batch program to be run.

CSS Calc Viewport Units Workaround?

Before I answer this, I'd like to point out that Chrome and IE 10+ actually supports calc with viewport units.

FIDDLE (In IE10+)

Solution (for other browsers): box-sizing

1) Start of by setting your height as 100vh.

2) With box-sizing set to border-box - add a padding-top of 75vw. This means that the padding will be part f the inner height.

3) Just offset the extra padding-top with a negative margin-top

FIDDLE

div
{
    /*height: calc(100vh - 75vw);*/
    height: 100vh;
    margin-top: -75vw;
    padding-top: 75vw;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    background: pink;
}

How do I vertically align text in a div?

You can align center text vertically inside a div using Flexbox.

<div>
   <p class="testimonialText">This is the testimonial text.</p>
</div>

div {
   display: flex;
   align-items: center;
}

You can learn more about it at A Complete Guide to Flexbox.

SQL Server CTE and recursion example

    --DROP TABLE #Employee
    CREATE TABLE #Employee(EmpId BIGINT IDENTITY,EmpName VARCHAR(25),Designation VARCHAR(25),ManagerID BIGINT)

    INSERT INTO #Employee VALUES('M11M','Manager',NULL)
    INSERT INTO #Employee VALUES('P11P','Manager',NULL)

    INSERT INTO #Employee VALUES('AA','Clerk',1)
    INSERT INTO #Employee VALUES('AB','Assistant',1)
    INSERT INTO #Employee VALUES('ZC','Supervisor',2)
    INSERT INTO #Employee VALUES('ZD','Security',2)


    SELECT * FROM #Employee (NOLOCK)

    ;
    WITH Emp_CTE 
    AS
    (
        SELECT EmpId,EmpName,Designation, ManagerID
              ,CASE WHEN ManagerID IS NULL THEN EmpId ELSE ManagerID END ManagerID_N
        FROM #Employee  
    )
    select EmpId,EmpName,Designation, ManagerID
    FROM Emp_CTE
    order BY ManagerID_N, EmpId

C++: constructor initializer for arrays

This is my solution for your reference:

struct Foo
{
    Foo(){}//used to make compiler happy!
    Foo(int x){/*...*/}
};

struct Bar
{
    Foo foo[3];

    Bar()
    {
        //initialize foo array here:
        for(int i=0;i<3;++i)
        {
            foo[i]=Foo(4+i);
        }
    }
};

Can You Get A Users Local LAN IP Address Via JavaScript?

I cleaned up mido's post and then cleaned up the function that they found. This will either return false or an array. When testing remember that you need to collapse the array in the web developer console otherwise it's nonintuitive default behavior may deceive you in to thinking that it is returning an empty array.

function ip_local()
{
 var ip = false;
 window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection || false;

 if (window.RTCPeerConnection)
 {
  ip = [];
  var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};
  pc.createDataChannel('');
  pc.createOffer(pc.setLocalDescription.bind(pc), noop);

  pc.onicecandidate = function(event)
  {
   if (event && event.candidate && event.candidate.candidate)
   {
    var s = event.candidate.candidate.split('\n');
    ip.push(s[0].split(' ')[4]);
   }
  }
 }

 return ip;
}

Additionally please keep in mind folks that this isn't something old-new like CSS border-radius though one of those bits that is outright not supported by IE11 and older. Always use object detection, test in reasonably older browsers (e.g. Firefox 4, IE9, Opera 12.1) and make sure your newer scripts aren't breaking your newer bits of code. Additionally always detect standards compliant code first so if there is something with say a CSS prefix detect the standard non-prefixed code first and then fall back as in the long term support will eventually be standardized for the rest of it's existence.

How to restart remote MySQL server running on Ubuntu linux?

  • To restart mysql use this command

sudo service mysql restart

Or

sudo restart mysql

Reference

How to get a list of images on docker registry v2

I wrote an easy-to-use command line tool for listing images in various ways (like list all images, list all tags of those images, list all layers of those tags).

It also allows you to delete unused images in various ways, like delete only older tags of a single image or from all images etc. This is convenient when you are filling your registry from a CI server and want to keep only latest/stable versions.

It is written in python and does not need you to download bulky big custom registry images.

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

If you're open to a PHP solution:

<td><img src='<?PHP
  $path1 = "path/to/your/image.jpg";
  $path2 = "alternate/path/to/another/image.jpg";

  echo file_exists($path1) ? $path1 : $path2; 
  ?>' alt='' />
</td>

////EDIT OK, here's a JS version:

<table><tr>
<td><img src='' id='myImage' /></td>
</tr></table>

<script type='text/javascript'>
  document.getElementById('myImage').src = "newImage.png";

  document.getElementById('myImage').onload = function() { 
    alert("done"); 
  }

  document.getElementById('myImage').onerror = function() { 
    alert("Inserting alternate");
    document.getElementById('myImage').src = "alternate.png"; 
  }
</script>

Creating a list of dictionaries results in a list of copies of the same dictionary

You have misunderstood the Python list object. It is similar to a C pointer-array. It does not actually "copy" the object which you append to it. Instead, it just store a "pointer" to that object.

Try the following code:

>>> d={}
>>> dlist=[]
>>> for i in xrange(0,3):
    d['data']=i
    dlist.append(d)
    print(d)

{'data': 0}
{'data': 1}
{'data': 2}
>>> print(dlist)
[{'data': 2}, {'data': 2}, {'data': 2}]

So why is print(dlist) not the same as print(d)?

The following code shows you the reason:

>>> for i in dlist:
    print "the list item point to object:", id(i)

the list item point to object: 47472232
the list item point to object: 47472232
the list item point to object: 47472232

So you can see all the items in the dlist is actually pointing to the same dict object.

The real answer to this question will be to append the "copy" of the target item, by using d.copy().

>>> dlist=[]
>>> for i in xrange(0,3):
    d['data']=i
    dlist.append(d.copy())
    print(d)

{'data': 0}
{'data': 1}
{'data': 2}
>>> print dlist
[{'data': 0}, {'data': 1}, {'data': 2}]

Try the id() trick, you can see the list items actually point to completely different objects.

>>> for i in dlist:
    print "the list item points to object:", id(i)

the list item points to object: 33861576
the list item points to object: 47472520
the list item points to object: 47458120

How can I generate an apk that can run without server with react-native?

If you get an error involving index.android.js. This is because you are using the new React-native version (I am using 0.55.4) Just replace the "index.android.js" to "index.js"

react-native bundle --platform android --dev false --entry-file index.js   --bundle-output android/app/src/main/assets/index.android.bundle   --assets-dest android/app/src/main/res/

Programmatically create a UIView with color gradient

You can create a custom class GradientView:

Swift 5

class GradientView: UIView {
    override open class var layerClass: AnyClass {
       return CAGradientLayer.classForCoder()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        let gradientLayer = layer as! CAGradientLayer
        gradientLayer.colors = [UIColor.white.cgColor, UIColor.black.cgColor]
    }
}

In the storyboard, set the class type to any view that you want to have gradient background:

enter image description here

This is better in the following ways:

  • No need to set frame of CLayer
  • Use NSConstraint as usual on the UIView
  • Don't need to create sublayers (less memory use)

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

Change Your Web.Config file as below. It will act like charm.

In node <system.webServer> add below portion of code

<modules runAllManagedModulesForAllRequests="true">
  <remove name="WebDAVModule"/>
</modules>

After adding, your Web.Config will look like below

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
        <remove name="WebDAVModule"/>
    </modules>
    <httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
    </httpProtocol>
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
</system.webServer>

How to get just numeric part of CSS property with jQuery?

You can implement this very simple jQuery plugin:

Plugin Definition:

(function($) {
   $.fn.cssValue = function(p) {
      var result;
      return isNaN(result = parseFloat(this.css(p))) ? 0 : result;
   };
})(jQuery);

It is resistant to NaN values that may occur in old IE version (will return 0 instead)

Usage:

$(this).cssValue('marginBottom');

Enjoy! :)

Why won't eclipse switch the compiler to Java 8?

Old question, but posting the answer incase it helps someone. Already build path was configured to use JDK 1.2.81 However, build was failing with the error below:

 lambda expressions are not supported in -source 1.5
[ERROR]   (use -source 8 or higher to enable lambda expressions)

In the latest Eclipse (Photon), adding the below entry to pom.xml worked.

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
  </properties>

Android studio- "SDK tools directory is missing"

I faced with the same error.

The solution:

Change your proxy settings. For me I tried all the things like uninstall and system config but it did not work. When I changed the proxy settings, the list appeared in System Settings->Android SDK->SDK Platforms tab

Still you cannot select the platforms as it is not yet downloaded automatically during installation because of proxy. So just select next and it will download SDK Platforms.

Once this is done, then you can select your platforms and again say ok to download files for that platform.

Now, the last part, once the platform is downloaded successfully then in my case I also had to download NDK.

With the above steps I could successfully create an app. Happy coding!

JavaScript ternary operator example with functions

The ternary style is generally used to save space. Semantically, they are identical. I prefer to go with the full if/then/else syntax because I don't like to sacrifice readability - I'm old-school and I prefer my braces.

The full if/then/else format is used for pretty much everything. It's especially popular if you get into larger blocks of code in each branch, you have a muti-branched if/else tree, or multiple else/ifs in a long string.

The ternary operator is common when you're assigning a value to a variable based on a simple condition or you are making multiple decisions with very brief outcomes. The example you cite actually doesn't make sense, because the expression will evaluate to one of the two values without any extra logic.

Good ideas:

this > that ? alert(this) : alert(that);  //nice and short, little loss of meaning

if(expression)  //longer blocks but organized and can be grasped by humans
{
    //35 lines of code here
}
else if (something_else)
{
    //40 more lines here
}
else if (another_one)  /etc, etc
{
    ...

Less good:

this > that ? testFucntion() ? thirdFunction() ? imlost() : whathappuh() : lostinsyntax() : thisisprobablybrokennow() ? //I'm lost in my own (awful) example by now.
//Not complete... or for average humans to read.

if(this != that)  //Ternary would be done by now
{
    x = this;
}
else
}
    x = this + 2;
}

A really basic rule of thumb - can you understand the whole thing as well or better on one line? Ternary is OK. Otherwise expand it.

Permissions error when connecting to EC2 via SSH on Mac OSx

I had met this problem too.And I found that happend beacuse I forgot to add the user-name before the host name: like this:

ssh -i test.pem ec2-32-122-42-91.us-west-2.compute.amazonaws.com

and I add the user name:

ssh -i test.pem [email protected]

it works!

Disable Buttons in jQuery Mobile

If I'm reading this question correctly, you may be missing that a jQuery mobile "button" widget is not the same thing as an HTML button element. I think this boils down to you can't call $('input').button('disable') unless you have previously called $('input').button(); to initialize a jQuery Mobile button widget on your input.

Of course, you may not want to be using jQuery button widget functionality, in which case Alexander's answer should set you right.

Checking version of angular-cli that's installed?

In Command line we can check our installed ng version.

ng -v OR ng --version OR ng version

This will give you like this :

 _                      _                 ____ _     ___

   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / ? \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
               |___/

Angular CLI: 1.6.5
Node: 8.0.0
OS: linux x64
Angular: 
...

How do I programmatically change file permissions?

Apache ant chmod (not very elegant, adding it for completeness) credit shared with @msorsky

    Chmod chmod = new Chmod();
    chmod.setProject(new Project());
    FileSet mySet = new FileSet();
    mySet.setDir(new File("/my/path"));
    mySet.setIncludes("**");
    chmod.addFileset(mySet);
    chmod.setPerm("+w");
    chmod.setType(new FileDirBoth());
    chmod.execute();

_csv.Error: field larger than field limit (131072)

This could be because your CSV file has embedded single or double quotes. If your CSV file is tab-delimited try opening it as:

c = csv.reader(f, delimiter='\t', quoting=csv.QUOTE_NONE)

How to set data attributes in HTML elements

Vanilla Javascript solution

HTML

<div id="mydiv" data-myval="10"></div>

JavaScript:

  • Using DOM's getAttribute() property

     var brand = mydiv.getAttribute("data-myval")//returns "10"
     mydiv.setAttribute("data-myval", "20")      //changes "data-myval" to "20"
     mydiv.removeAttribute("data-myval")         //removes "data-myval" attribute entirely
    
  • Using JavaScript's dataset property

    var myval = mydiv.dataset.myval     //returns "10"
    mydiv.dataset.myval = '20'          //changes "data-myval" to "20"
    mydiv.dataset.myval = null          //removes "data-myval" attribute
    

Pointers in JavaScript?

You refer to 'x' from window object

var x = 0;

function a(key, ref) {
    ref = ref || window;  // object reference - default window
    ref[key]++;
}

a('x');                   // string
alert(x);

How do I run a program from command prompt as a different user and as an admin

The easiest is to create a batch file (.bat) and run that as administrator.

Right click and 'Run as administrator'

What is the best collation to use for MySQL with PHP?

Be very, very aware of this problem that can occur when using utf8_general_ci.

MySQL will not distinguish between some characters in select statements, if the utf8_general_ci collation is used. This can lead to very nasty bugs - especially for example, where usernames are involved. Depending on the implementation that uses the database tables, this problem could allow malicious users to create a username matching an administrator account.

This problem exposes itself at the very least in early 5.x versions - I'm not sure if this behaviour as changed later.

I'm no DBA, but to avoid this problem, I always go with utf8-bin instead of a case-insensitive one.

The script below describes the problem by example.

-- first, create a sandbox to play in
CREATE DATABASE `sandbox`;
use `sandbox`;

-- next, make sure that your client connection is of the same 
-- character/collate type as the one we're going to test next:
charset utf8 collate utf8_general_ci

-- now, create the table and fill it with values
CREATE TABLE `test` (`key` VARCHAR(16), `value` VARCHAR(16) )
    CHARACTER SET utf8 COLLATE utf8_general_ci;

INSERT INTO `test` VALUES ('Key ONE', 'value'), ('Key TWO', 'valúe');

-- (verify)
SELECT * FROM `test`;

-- now, expose the problem/bug:
SELECT * FROM test WHERE `value` = 'value';

--
-- Note that we get BOTH keys here! MySQLs UTF8 collates that are 
-- case insensitive (ending with _ci) do not distinguish between 
-- both values!
--
-- collate 'utf8_bin' doesn't have this problem, as I'll show next:
--

-- first, reset the client connection charset/collate type
charset utf8 collate utf8_bin

-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin;

-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';

--
-- Note that we get just one key now, as you'd expect.
--
-- This problem appears to be specific to utf8. Next, I'll try to 
-- do the same with the 'latin1' charset:
--

-- first, reset the client connection charset/collate type
charset latin1 collate latin1_general_ci

-- next, convert the values that we've previously inserted
-- in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET latin1 COLLATE latin1_general_ci;

-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';

--
-- Again, only one key is returned (expected). This shows 
-- that the problem with utf8/utf8_generic_ci isn't present 
-- in latin1/latin1_general_ci
--
-- To complete the example, I'll check with the binary collate
-- of latin1 as well:

-- first, reset the client connection charset/collate type
charset latin1 collate latin1_bin

-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET latin1 COLLATE latin1_bin;

-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';

--
-- Again, only one key is returned (expected).
--
-- Finally, I'll re-introduce the problem in the exact same 
-- way (for any sceptics out there):

-- first, reset the client connection charset/collate type
charset utf8 collate utf8_generic_ci

-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

-- now, re-check for the problem/bug
SELECT * FROM test WHERE `value` = 'value';

--
-- Two keys.
--

DROP DATABASE sandbox;

What does the Excel range.Rows property really do?

There is another way, take this as example

Dim sr As String    
sr = "6:10"
Rows(sr).Select

All you need to do is to convert your variables iStartRow, iEndRow to a string.

How can I display a messagebox in ASP.NET?

Make a method of MsgBox in your page.


public void MsgBox(String ex, Page pg,Object obj) 
{
    string s = "<SCRIPT language='javascript'>alert('" + ex.Replace("\r\n", "\\n").Replace("'", "") + "'); </SCRIPT>";
    Type cstype = obj.GetType();
    ClientScriptManager cs = pg.ClientScript;
    cs.RegisterClientScriptBlock(cstype, s, s.ToString());
}

and when you want to use msgbox just put this line

MsgBox("! your message !", this.Page, this);

Converting a value to 2 decimal places within jQuery

you can use just javascript for it

var total =10.8
(total).toFixed(2); 10.80


alert(total.toFixed(2))); 

Getting only hour/minute of datetime

Try this:

String hourMinute = DateTime.Now.ToString("HH:mm");

Now you will get the time in hour:minute format.

MongoDB "root" user

Mongodb user management:

roles list:

read
readWrite
dbAdmin
userAdmin
clusterAdmin
readAnyDatabase
readWriteAnyDatabase
userAdminAnyDatabase
dbAdminAnyDatabase

create user:

db.createUser(user, writeConcern)

db.createUser({ user: "user",
  pwd: "pass",
  roles: [
    { role: "read", db: "database" } 
  ]
})

update user:

db.updateUser("user",{
  roles: [
    { role: "readWrite", db: "database" } 
  ]
})

drop user:

db.removeUser("user")

or

db.dropUser("user")

view users:

db.getUsers();

more information: https://docs.mongodb.com/manual/reference/security/#read

What's the complete range for Chinese characters in Unicode?

To summarize, it sounds like these are them:

var blocks = [
  [0x3400, 0x4DB5],
  [0x4E00, 0x62FF],
  [0x6300, 0x77FF],
  [0x7800, 0x8CFF],
  [0x8D00, 0x9FCC],
  [0x2e80, 0x2fd5],
  [0x3190, 0x319f],
  [0x3400, 0x4DBF],
  [0x4E00, 0x9FCC],
  [0xF900, 0xFAAD],
  [0x20000, 0x215FF],
  [0x21600, 0x230FF],
  [0x23100, 0x245FF],
  [0x24600, 0x260FF],
  [0x26100, 0x275FF],
  [0x27600, 0x290FF],
  [0x29100, 0x2A6DF],
  [0x2A700, 0x2B734],
  [0x2B740, 0x2B81D]
]

How to insert DECIMAL into MySQL database

I noticed something else about your coding.... look

INSERT INTO reports_services (id,title,description,cost) VALUES (0, 'test title', 'test decription ', '3.80')

in your "CREATE TABLE" code you have the id set to "AUTO_INCREMENT" which means it's automatically generating a result for that field.... but in your above code you include it as one of the insertions and in the "VALUES" you have a 0 there... idk if that's your way of telling us you left it blank because it's set to AUTO_INC. or if that's the actual code you have... if it's the code you have not only should you not be trying to send data to a field set to generate it automatically, but the RIGHT WAY to do it WRONG would be

'0',

you put

0,

lol....so that might be causing some of the problem... I also just noticed in the code after "test description" you have a space before the '.... that might be throwing something off too.... idk.. I hope this helps n maybe resolves some other problem you might be pulling your hair out about now.... speaking of which.... I need to figure out my problem before I tear all my hair out..... good luck.. :)

UPDATE.....

I almost forgot... if you have the 0 there to show that it's blank... you could be entering "test title" as the id and "test description" as the title then "3.whatever cents" for the description leaving "cost" empty...... which could be why it maxed out because if I'm not mistaking you have it set to NOT NULL.... and you left it null... so it forced something... maybe.... lol

Turning off auto indent when pasting text into vim

Sadly I found the vim plugin mentioned not to be working with iTerm2 3.0.15 (to be fair I don't know if this broke on older versions) - but I found this hack instead.

Map command-p to do the paste and using iTerm2 vim keys. Obviously this only works for iTerm2.

How it works. I use "jk" to enter escape mode so you will also need:

:inoremap jk

in your .vimrc.

Then it just invokes P to enter paste mode, "+p to paste from the clipboard and then P to disable paste mode. hth.

enter image description here

Pass variables from servlet to jsp

Besides using an attribute to pass information from a servlet to a JSP page, one can also pass a parameter. That is done simply by redirecting to a URL that specifies the JSP page in question, and adding the normal parameter-passing-through-the-URL mechanism.

An example. The relevant part of the servlet code:

protected void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
    response.setContentType( "text/html" );
    // processing the request not shown...
    //
    // here we decide to send the value "bar" in parameter
    // "foo" to the JSP page example.jsp:
    response.sendRedirect( "example.jsp?foo=bar" );
}

And the relevant part of JSP page example.jsp:

<%
    String fooParameter = request.getParameter( "foo" );
    if ( fooParameter == null )
    {
%>
    <p>No parameter foo given to this page.</p>
<%
    }
    else
    {
%>
    <p>The value of parameter foo is <%= fooParameter.toString() %>.</p>
<%
    }
%>

error::make_unique is not a member of ‘std’

In my case I was needed update the std=c++

I mean in my gradle file was this

android {
    ...

    defaultConfig {
        ...

        externalNativeBuild {
            cmake {
                cppFlags "-std=c++11", "-Wall"
                arguments "-DANDROID_STL=c++_static",
                        "-DARCORE_LIBPATH=${arcore_libpath}/jni",
                        "-DARCORE_INCLUDE=${project.rootDir}/app/src/main/libs"
            }
        }
       ....
    }

I changed this line

android {
    ...

    defaultConfig {
        ...

        externalNativeBuild {
            cmake {
                cppFlags "-std=c++17", "-Wall"   <-- this number from 11 to 17 (or 14)
                arguments "-DANDROID_STL=c++_static",
                        "-DARCORE_LIBPATH=${arcore_libpath}/jni",
                        "-DARCORE_INCLUDE=${project.rootDir}/app/src/main/libs"
            }
        }
       ....
    }

That's it...

How to set text color to a text view programmatically

yourTextView.setTextColor(color);

Or, in your case: yourTextView.setTextColor(0xffbdbdbd);

How to delete files recursively from an S3 bucket

The voted up answer is missing a step.

Per aws s3 help:

Currently, there is no support for the use of UNIX style wildcards in a command's path arguments. However, most commands have --exclude "<value>" and --include "<value>" parameters that can achieve the desired result......... When there are multiple filters, the rule is the filters that appear later in the command take precedence over filters that appear earlier in the command. For example, if the filter parameters passed to the command were --exclude "*" --include "*.txt" All files will be excluded from the command except for files ending with .txt

aws s3 rm --recursive s3://bucket/ --exclude="*" --include="/folder_path/*" 

How can you run a command in bash over and over until success?

To elaborate on @Marc B's answer,

$ passwd
$ while [ $? -ne 0 ]; do !!; done

Is nice way of doing the same thing that's not command specific.

How to change Screen buffer size in Windows Command Prompt from batch script

You can change the buffer size of cmd by clicking the icon at top left corner -->properties --> layout --> screen buffer size.
you can even change it with cmd command

mode con:cols=100 lines=60
Upto lines = 58 the height of the cmd window changes ..
After lines value of 58 the buffer size of the cmd changes...

Chart creating dynamically. in .net, c#

Try to include these lines on your code, after mych.Visible = true;:

ChartArea chA = new ChartArea();
mych.ChartAreas.Add(chA);

Javascript Thousand Separator / string format

If is about localizing thousands separators, delimiters and decimal separators, go with the following:

// --> numObj.toLocaleString( [locales [, options] ] )
parseInt( number ).toLocaleString();

There are several options you can use (and even locales with fallbacks):

_x000D_
_x000D_
number = 123456.7089;_x000D_
_x000D_
result  = parseInt( number ).toLocaleString() + "<br>";_x000D_
result += number.toLocaleString( 'de-DE' ) + "<br>";_x000D_
result += number.toLocaleString( 'ar-EG' ) + "<br>";_x000D_
result += number.toLocaleString( 'ja-JP', { _x000D_
  style           : 'currency',_x000D_
  currency        : 'JPY',_x000D_
  currencyDisplay : 'symbol',_x000D_
  useGrouping     : true_x000D_
} ) + "<br>";_x000D_
result += number.toLocaleString( [ 'jav', 'en' ], { _x000D_
  localeMatcher            : 'lookup',_x000D_
  style                    : 'decimal',_x000D_
  minimumIntegerDigits     : 2,_x000D_
  minimumFractionDigits    : 2,_x000D_
  maximumFractionDigits    : 3,_x000D_
  minimumSignificantDigits : 2,_x000D_
  maximumSignificantDigits : 3_x000D_
} ) + "<br>";_x000D_
_x000D_
var el = document.getElementById( 'result' );_x000D_
el.innerHTML = result;
_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

Details on the MDN info page.

Edit: Commentor @I like Serena adds the following:

To support browsers with a non-English locale where we still want English formatting, use value.toLocaleString('en'). Also works for floating point.

Strange out of memory issue while loading an image to a Bitmap object

I tried Thomas Vervest's approach, but it returns a scale of 1 for image size 2592x1944 when IMAGE_MAX_SIZE is 2048.

This version worked for me based on all the other comments provided by others:

private Bitmap decodeFile (File f) {
    Bitmap b = null;
    try {
        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options ();
        o.inJustDecodeBounds = true;

        FileInputStream fis = new FileInputStream (f);
        try {
            BitmapFactory.decodeStream (fis, null, o);
        } finally {
            fis.close ();
        }

        int scale = 1;
        for (int size = Math.max (o.outHeight, o.outWidth); 
            (size>>(scale-1)) > IMAGE_MAX_SIZE; ++scale);

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options ();
        o2.inSampleSize = scale;
        fis = new FileInputStream (f);
        try {
            b = BitmapFactory.decodeStream (fis, null, o2);
        } finally {
            fis.close ();
        }
    } catch (IOException e) {
    }
    return b;
}

How to refresh Gridview after pressed a button in asp.net

Before data bind change gridview databinding method, assign GridView.EditIndex to -1. It solved the same issue for me :

 gvTypes.EditIndex = -1;
 gvTypes.DataBind();

gvTypes is my GridView ID.

pandas resample documentation

B         business day frequency
C         custom business day frequency (experimental)
D         calendar day frequency
W         weekly frequency
M         month end frequency
SM        semi-month end frequency (15th and end of month)
BM        business month end frequency
CBM       custom business month end frequency
MS        month start frequency
SMS       semi-month start frequency (1st and 15th)
BMS       business month start frequency
CBMS      custom business month start frequency
Q         quarter end frequency
BQ        business quarter endfrequency
QS        quarter start frequency
BQS       business quarter start frequency
A         year end frequency
BA, BY    business year end frequency
AS, YS    year start frequency
BAS, BYS  business year start frequency
BH        business hour frequency
H         hourly frequency
T, min    minutely frequency
S         secondly frequency
L, ms     milliseconds
U, us     microseconds
N         nanoseconds

See the timeseries documentation. It includes a list of offsets (and 'anchored' offsets), and a section about resampling.

Note that there isn't a list of all the different how options, because it can be any NumPy array function and any function that is available via groupby dispatching can be passed to how by name.

C function that counts lines in file

You have a ; at the end of the if. Change:

  if (fp == NULL);
  return 0;

to

  if (fp == NULL) 
    return 0;

Get Date in YYYYMMDD format in windows batch file

If, after reading the other questions and viewing the links mentioned in the comment sections, you still can't figure it out, read on.

First of all, where you're going wrong is the offset.

It should look more like this...

set mydate=%date:~10,4%%date:~6,2%/%date:~4,2%
echo %mydate%

If the date was Tue 12/02/2013 then it would display it as 2013/02/12.

To remove the slashes, the code would look more like

set mydate=%date:~10,4%%date:~7,2%%date:~4,2%
echo %mydate%

which would output 20130212

And a hint for doing it in the future, if mydate equals something like %date:~10,4%%date:~7,2% or the like, you probably forgot a tilde (~).

Open a local HTML file using window.open in Chrome

window.location.href = 'file://///fileserver/upload/Old_Upload/05_06_2019/THRESHOLD/BBH/Look/chrs/Delia';

Nothing Worked for me.

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

The issue is that you are not able to get a connection to MYSQL database and hence it is throwing an error saying that cannot build a session factory.

Please see the error below:

 Caused by: java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO) 

which points to username not getting populated.

Please recheck system properties

dataSource.setUsername(System.getProperty("root"));

some packages seems to be missing as well pointing to a dependency issue:

package org.gjt.mm.mysql does not exist

Please run a mvn dependency:tree command to check for dependencies

div background color, to change onhover

Just make the property !important in your css file so that background color doesnot change on mouse over.This worked for me.

Example:

.fbColor {
    background-color: #3b5998 !important;
    color: white;
}

Using wire or reg with input or output in Verilog

The Verilog code compiler you use will dictate what you have to do. If you use illegal syntax, you will get a compile error.

An output must also be declared as a reg only if it is assigned using a "procedural assignment". For example:

output reg a;
always @* a = b;

There is no need to declare an output as a wire.

There is no need to declare an input as a wire or reg.

Failed to install *.apk on device 'emulator-5554': EOF

Wipe Data and restart the virtual device again fix the issue in my case.

enter image description here

What's the best way to detect a 'touch screen' device using JavaScript?

I would avoid using screen width to determine if a device is a touch device. There are touch screens much larger than 699px, think of Windows 8. Navigatior.userAgent may be nice to override false postives.

I would recommend checking out this issue on Modernizr.

Are you wanting to test if the device supports touch events or is a touch device. Unfortunately, that's not the same thing.

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

  1. Add the following code into startup.cs file.

    public void ConfigureServices(IServiceCollection services)
    {
        string con = Configuration.GetConnectionString("DBConnection");
        services.AddMvc();
        GlobalProperties.DBConnection = con;//DBConnection is a user defined static property of GlobalProperties class
    }
    
  2. Use GlobalProperties.DBConnection property in Context class.

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {  
              optionsBuilder.UseSqlServer(GlobalProperties.DBConnection);
        }
    }
    

How to pass object with NSNotificationCenter

Swift 5

func post() {
    NotificationCenter.default.post(name: Notification.Name("SomeNotificationName"), 
        object: nil, 
        userInfo:["key0": "value", "key1": 1234])
}

func addObservers() {
    NotificationCenter.default.addObserver(self, 
        selector: #selector(someMethod), 
        name: Notification.Name("SomeNotificationName"), 
        object: nil)
}

@objc func someMethod(_ notification: Notification) {
    let info0 = notification.userInfo?["key0"]
    let info1 = notification.userInfo?["key1"]
}

Bonus (that you should definitely do!) :

Replace Notification.Name("SomeNotificationName") with .someNotificationName:

extension Notification.Name {
    static let someNotificationName = Notification.Name("SomeNotificationName")
}

Replace "key0" and "key1" with Notification.Key.key0 and Notification.Key.key1:

extension Notification {
  enum Key: String {
    case key0
    case key1
  }
}

Why should I definitely do this ? To avoid costly typo errors, enjoy renaming, enjoy find usage etc...

Cannot open include file: 'unistd.h': No such file or directory

The "uni" in unistd stands for "UNIX" - you won't find it on a Windows system.

Most widely used, portable libraries should offer alternative builds or detect the platform and only try to use headers/functions that will be provided, so it's worth checking documentation to see if you've missed some build step - e.g. perhaps running "make" instead of loading a ".sln" Visual C++ solution file.

If you need to fix it yourself, remove the include and see which functions are actually needed, then try to find a Windows equivalent.

How to call Oracle MD5 hash function?

To calculate MD5 hash of CLOB content field with my desired encoding without implicitly recoding content to AL32UTF8, I've used this code:

create or replace function clob2blob(AClob CLOB) return BLOB is
  Result BLOB;
  o1 integer;
  o2 integer;
  c integer;
  w integer;
begin
  o1 := 1;
  o2 := 1;
  c := 0;
  w := 0;
  DBMS_LOB.CreateTemporary(Result, true);
  DBMS_LOB.ConvertToBlob(Result, AClob, length(AClob), o1, o2, 0, c, w);
  return(Result);
end clob2blob;
/

update my_table t set t.hash = (rawtohex(DBMS_CRYPTO.Hash(clob2blob(t.content),2)));

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

Topic is a bit old, but since the scripts here detect Firefox as a False Positive (EDGE v12), here is the version I use:

function isIEorEDGE(){
  if (navigator.appName == 'Microsoft Internet Explorer'){
    return true; // IE
  }
  else if(navigator.appName == "Netscape"){                       
     return navigator.userAgent.indexOf('.NET') > -1; // Only Edge uses .NET libraries
  }       

  return false;
}

which of course can be written in a more concise way:

function isIEorEDGE(){
  return navigator.appName == 'Microsoft Internet Explorer' || (navigator.appName == "Netscape" && navigator.userAgent.indexOf('.NET') > -1);
}