Programs & Examples On #Street address

Street address refers to postal addresses, or delivery points, that can be used for physical delivery of mail or goods.

How to parse freeform street/postal address out of text, and into components

I'm late to the party, here is an Excel VBA script I wrote years ago for Australia. It can be easily modified to support other Countries. I've made a GitHub repository of the C# code here. I've hosted it on my site and you can download it here: http://jeremythompson.net/rocks/ParseAddress.xlsm

Strategy

For any country with a PostCode that's numeric or can be matched with a RegEx my strategy works very well:

  1. First we detect the First and Surname which are assumed to be the top line. Its easy to skip the name and start with the address by unticking the checkbox (called 'Name is top row' as shown below).

  2. Next its safe to expect the Address consisting of the Street and Number come before the Suburb and the St, Pde, Ave, Av, Rd, Cres, loop, etc is a separator.

  3. Detecting the Suburb vs the State and even Country can trick the most sophisticated parsers as there can be conflicts. To overcome this I use a PostCode look up based on the fact that after stripping Street and Apartment/Unit numbers as well as the PoBox,Ph,Fax,Mobile etc, only the PostCode number will remain. This is easy to match with a regEx to then look up the suburb(s) and country.

Your National Post Office Service will provide a list of post codes with Suburbs and States free of charge that you can store in an excel sheet, db table, text/json/xml file, etc.

  1. Finally, since some Post Codes have multiple Suburbs we check which suburb appears in the Address.

Example

enter image description here

VBA Code

DISCLAIMER, I know this code is not perfect, or even written well however its very easy to convert to any programming language and run in any type of application.The strategy is the answer depending on your country and rules, take this code as an example:

Option Explicit

Private Const TopRow As Integer = 0

Public Sub ParseAddress()
Dim strArr() As String
Dim sigRow() As String
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim Stat As String
Dim SpaceInName As Integer
Dim Temp As String
Dim PhExt As String

On Error Resume Next

Temp = ActiveSheet.Range("Address")

'Split info into array
strArr = Split(Temp, vbLf)

'Trim the array
For i = 0 To UBound(strArr)
strArr(i) = VBA.Trim(strArr(i))
Next i

'Remove empty items/rows    
ReDim sigRow(LBound(strArr) To UBound(strArr))
For i = LBound(strArr) To UBound(strArr)
    If Trim(strArr(i)) <> "" Then
        sigRow(j) = strArr(i)
        j = j + 1
    End If
Next i
ReDim Preserve sigRow(LBound(strArr) To j)

'Find the name (MUST BE ON THE FIRST ROW UNLESS CHECKBOX UNTICKED)
i = TopRow
If ActiveSheet.Shapes("chkFirst").ControlFormat.Value = 1 Then

SpaceInName = InStr(1, sigRow(i), " ", vbTextCompare) - 1

If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
ActiveSheet.Range("FirstName") = VBA.Left(sigRow(i), SpaceInName)
Else
 If MsgBox("First Name: " & VBA.Mid$(sigRow(i), 1, SpaceInName), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("FirstName") = VBA.Left(sigRow(i), SpaceInName)
End If

If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
ActiveSheet.Range("Surname") = VBA.Mid(sigRow(i), SpaceInName + 2)
Else
  If MsgBox("Surame: " & VBA.Mid(sigRow(i), SpaceInName + 2), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Surname") = VBA.Mid(sigRow(i), SpaceInName + 2)
End If
sigRow(i) = ""
End If

'Find the Street by looking for a "St, Pde, Ave, Av, Rd, Cres, loop, etc"
For i = 1 To UBound(sigRow)
If Len(sigRow(i)) > 0 Then
    For j = 0 To 8
    If InStr(1, VBA.UCase(sigRow(i)), Street(j), vbTextCompare) > 0 Then

    'Find the position of the street in order to get the suburb
    SpaceInName = InStr(1, VBA.UCase(sigRow(i)), Street(j), vbTextCompare) + Len(Street(j)) - 1

    'If its a po box then add 5 chars
    If VBA.Right(Street(j), 3) = "BOX" Then SpaceInName = SpaceInName + 5

    If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
    ActiveSheet.Range("Street") = VBA.Mid(sigRow(i), 1, SpaceInName)
    Else
      If MsgBox("Street Address: " & VBA.Mid(sigRow(i), 1, SpaceInName), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Street") = VBA.Mid(sigRow(i), 1, SpaceInName)
    End If
    'Trim the Street, Number leaving the Suburb if its exists on the same line
    sigRow(i) = VBA.Mid(sigRow(i), SpaceInName) + 2
    sigRow(i) = Replace(sigRow(i), VBA.Mid(sigRow(i), 1, SpaceInName), "")

    GoTo PastAddress:
    End If
    Next j
End If
Next i
PastAddress:

'Mobile
For i = 1 To UBound(sigRow)
If Len(sigRow(i)) > 0 Then
    For j = 0 To 3
    Temp = Mb(j)
        If VBA.Left(VBA.UCase(sigRow(i)), Len(Temp)) = Temp Then
        If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
        ActiveSheet.Range("Mobile") = VBA.Mid(sigRow(i), Len(Temp) + 2)
        Else
          If MsgBox("Mobile: " & VBA.Mid(sigRow(i), Len(Temp) + 2), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Mobile") = VBA.Mid(sigRow(i), Len(Temp) + 2)
        End If
    sigRow(i) = ""
    GoTo PastMobile:
    End If
    Next j
End If
Next i
PastMobile:

'Phone
For i = 1 To UBound(sigRow)
If Len(sigRow(i)) > 0 Then
    For j = 0 To 1
    Temp = Ph(j)
        If VBA.Left(VBA.UCase(sigRow(i)), Len(Temp)) = Temp Then

            'TODO: Detect the intl or national extension here.. or if we can from the postcode.
            If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
            ActiveSheet.Range("Phone") = VBA.Mid(sigRow(i), Len(Temp) + 3)
            Else
              If MsgBox("Phone: " & VBA.Mid(sigRow(i), Len(Temp) + 3), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Phone") = VBA.Mid(sigRow(i), Len(Temp) + 3)
            End If

        sigRow(i) = ""
        GoTo PastPhone:
        End If
    Next j
End If
Next i
PastPhone:


'Email
For i = 1 To UBound(sigRow)
    If Len(sigRow(i)) > 0 Then
        'replace with regEx search
        If InStr(1, sigRow(i), "@", vbTextCompare) And InStr(1, VBA.UCase(sigRow(i)), ".CO", vbTextCompare) Then
        Dim email As String
        email = sigRow(i)
        email = Replace(VBA.UCase(email), "EMAIL:", "")
        email = Replace(VBA.UCase(email), "E-MAIL:", "")
        email = Replace(VBA.UCase(email), "E:", "")
        email = Replace(VBA.UCase(Trim(email)), "E ", "")
        email = VBA.LCase(email)

            If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
            ActiveSheet.Range("Email") = email
            Else
              If MsgBox("Email: " & email, vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Email") = email
            End If
        sigRow(i) = ""
        Exit For
        End If
    End If
Next i

'Now the only remaining items will be the postcode, suburb, country
'there shouldn't be any numbers (eg. from PoBox,Ph,Fax,Mobile) except for the Post Code

'Join the string and filter out the Post Code
Temp = Join(sigRow, vbCrLf)
Temp = Trim(Temp)

For i = 1 To Len(Temp)

Dim postCode As String
postCode = VBA.Mid(Temp, i, 4)

'In Australia PostCodes are 4 digits
If VBA.Mid(Temp, i, 1) <> " " And IsNumeric(postCode) Then

    If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
    ActiveSheet.Range("PostCode") = postCode
    Else
      If MsgBox("Post Code: " & postCode, vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("PostCode") = postCode
    End If

    'Lookup the Suburb and State based on the PostCode, the PostCode sheet has the lookup
    Dim mySuburbArray As Range
    Set mySuburbArray = Sheets("PostCodes").Range("A2:B16670")

    Dim suburbs As String
    For j = 1 To mySuburbArray.Columns(1).Cells.Count
    If mySuburbArray.Cells(j, 1) = postCode Then
        'Check if the suburb is listed in the address
        If InStr(1, UCase(Temp), mySuburbArray.Cells(j, 2), vbTextCompare) > 0 Then

        'Set the Suburb and State
        ActiveSheet.Range("Suburb") = mySuburbArray.Cells(j, 2)
        Stat = mySuburbArray.Cells(j, 3)
        ActiveSheet.Range("State") = Stat

        'Knowing the State - for Australia we can get the telephone Ext
        PhExt = PhExtension(VBA.UCase(Stat))
        ActiveSheet.Range("PhExt") = PhExt

        'remove the phone extension from the number
        Dim prePhone As String
        prePhone = ActiveSheet.Range("Phone")
        prePhone = Replace(prePhone, PhExt & " ", "")
        prePhone = Replace(prePhone, "(" & PhExt & ") ", "")
        prePhone = Replace(prePhone, "(" & PhExt & ")", "")
        ActiveSheet.Range("Phone") = prePhone
        Exit For
        End If
    End If
    Next j
Exit For
End If
Next i

End Sub


Private Function PhExtension(ByVal State As String) As String
Select Case State
Case Is = "NSW"
PhExtension = "02"
Case Is = "QLD"
PhExtension = "07"
Case Is = "VIC"
PhExtension = "03"
Case Is = "NT"
PhExtension = "04"
Case Is = "WA"
PhExtension = "05"
Case Is = "SA"
PhExtension = "07"
Case Is = "TAS"
PhExtension = "06"
End Select
End Function

Private Function Ph(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
Ph = "PH"
Case Is = 1
Ph = "PHONE"
'Case Is = 2
'Ph = "P"
End Select
End Function

Private Function Mb(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
Mb = "MB"
Case Is = 1
Mb = "MOB"
Case Is = 2
Mb = "CELL"
Case Is = 3
Mb = "MOBILE"
'Case Is = 4
'Mb = "M"
End Select
End Function

Private Function Fax(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
Fax = "FAX"
Case Is = 1
Fax = "FACSIMILE"
'Case Is = 2
'Fax = "F"
End Select
End Function

Private Function State(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
State = "NSW"
Case Is = 1
State = "QLD"
Case Is = 2
State = "VIC"
Case Is = 3
State = "NT"
Case Is = 4
State = "WA"
Case Is = 5
State = "SA"
Case Is = 6
State = "TAS"
End Select
End Function

Private Function Street(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
Street = " ST"
Case Is = 1
Street = " RD"
Case Is = 2
Street = " AVE"
Case Is = 3
Street = " AV"
Case Is = 4
Street = " CRES"
Case Is = 5
Street = " LOOP"
Case Is = 6
Street = "PO BOX"
Case Is = 7
Street = " STREET"
Case Is = 8
Street = " ROAD"
Case Is = 9
Street = " AVENUE"
Case Is = 10
Street = " CRESENT"
Case Is = 11
Street = " PARADE"
Case Is = 12
Street = " PDE"
Case Is = 13
Street = " LANE"
Case Is = 14
Street = " COURT"
Case Is = 15
Street = " BLVD"
Case Is = 16
Street = "P.O. BOX"
Case Is = 17
Street = "P.O BOX"
Case Is = 18
Street = "PO BOX"
Case Is = 19
Street = "POBOX"
End Select
End Function

Parse usable Street Address, City, State, Zip from a string

Since there is chance of error in word, think about using SOUNDEX combined with LCS algorithm to compare strings, this will help a lot !

mysql datatype for telephone number and address

varchar or text should be the best datatypes for storing mobile numbers I guess.

Address validation using Google Maps API

I am both a web developer and a former employee of one of the companies you mentioned. I completely understand where you're coming from. Verifying addresses seems like a simple problem to tackle, but it's very much an iceberg. I suppose one workaround to the legal constraints of the Google or Yahoo! Maps APIs is to request your users verify their addresses on a map. If I were in your shoes, though, I wouldn't go that route.

The reason address verification services are so expensive is that they require licenses and ongoing relationships with grumpy, bureaucratic postal authorities (including the Royal Mail). Unfortunately, postal authorities are the best (and often the only) sources of data against which to verify addresses, so there really isn't any other way to go about it. The bottom line is you need to weigh the cost of bad addresses (usually a question of mail volume) against the cost of the software to verify them. Irish postal data is even more rubbish than Irish postal formats (which frequently omit building numbers), so there's little you can do about those addresses.

How do you perform address validation?

There is no global solution. For any given country it is at best rather tricky.

In the UK, the PostOffice controlls postal addresses, and can provide (at a cost) address information for validation purposes.

Government agencies also keep an extensive list of addresses, and these are centrally collated in the NLPG (National Land and Property Gazetteer).

Actually validating against these lists is very difficult. Most people don't even know exactly how their address as it is held by the PostOffice. Some businesses don't even know what number they are on a particular street.

Your best bet is to approach a company that specialises in this kind of thing.

How to convert an address to a latitude/longitude?

Google has a geocoding API which seems to work pretty well for most of the locations that they have Google Maps data for.

http://googlemapsapi.blogspot.com/2006/06/geocoding-at-last.html

They provide online geocoding (via JavaScript):

http://code.google.com/apis/maps/documentation/services.html#Geocoding

Or backend geocoding (via an HTTP request):

http://code.google.com/apis/maps/documentation/services.html#Geocoding_Direct

The data is usually the same used by Google Maps itself. (note that there are some exceptions to this, such as the UK or Israel, where the data is from a different source and of slightly reduced quality)

Using Address Instead Of Longitude And Latitude With Google Maps API

See this example, initializes the map to "San Diego, CA".

Uses the Google Maps Javascript API v3 Geocoder to translate the address into coordinates that can be displayed on the map.

<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
  var geocoder;
  var map;
  var address ="San Diego, CA";
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 8,
      center: latlng,
    mapTypeControl: true,
    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
    navigationControl: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    if (geocoder) {
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
          map.setCenter(results[0].geometry.location);

            var infowindow = new google.maps.InfoWindow(
                { content: '<b>'+address+'</b>',
                  size: new google.maps.Size(150,50)
                });
    
            var marker = new google.maps.Marker({
                position: results[0].geometry.location,
                map: map, 
                title:address
            }); 
            google.maps.event.addListener(marker, 'click', function() {
                infowindow.open(map,marker);
            });

          } else {
            alert("No results found");
          }
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
    }
  }
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
 <div id="map_canvas" style="width:100%; height:100%">
</body>
</html>

working code snippet:

_x000D_
_x000D_
var geocoder;
var map;
var address = "San Diego, CA";

function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var myOptions = {
    zoom: 8,
    center: latlng,
    mapTypeControl: true,
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
    },
    navigationControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  if (geocoder) {
    geocoder.geocode({
      'address': address
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
          map.setCenter(results[0].geometry.location);

          var infowindow = new google.maps.InfoWindow({
            content: '<b>' + address + '</b>',
            size: new google.maps.Size(150, 50)
          });

          var marker = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map,
            title: address
          });
          google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map, marker);
          });

        } else {
          alert("No results found");
        }
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
}
google.maps.event.addDomListener(window, 'load', initialize);
_x000D_
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
}
_x000D_
<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" ></div>
_x000D_
_x000D_
_x000D_

Android: Reverse geocoding - getFromLocation

I've heard that Geocoder is on the buggy side. I recently put together an example application that uses Google's http geocoding service to lookup location from lat/long. Feel free to check it out here

http://www.smnirven.com/?p=39

How to order results with findBy() in Doctrine

$ens = $em->getRepository('AcmeBinBundle:Marks')
              ->findBy(
                 array(), 
                 array('id' => 'ASC')
               );

is there any IE8 only css hack?

I was looking for a good option for IE10 and below CSS styling (but it would work for IE8 only as well) and I came up with this idea:

<!--[if lt IE 10]><div class="column IE10-fix"><![endif]-->
<!--[if !lt IE 10]><!--><div class="column"><!--<![endif]-->

I declare my div or whatever you want with an extra class, this allows me to have extra CSS in the same stylesheet in a very readable manner.

It's W3C valid and not a weird CSS hack.

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

I got solution. For pre-8.0 devices, you have to just use startService(), but for post-7.0 devices, you have to use startForgroundService(). Here is sample for code to start service.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(new Intent(context, ServedService.class));
    } else {
        context.startService(new Intent(context, ServedService.class));
    }

And in service class, please add the code below for notification:

@Override
public void onCreate() {
    super.onCreate();
    startForeground(1,new Notification());
}

Where O is Android version 26.

If you don't want your service to run in Foreground and want it to run in background instead, post Android O you must bind the service to a connection like below:

Intent serviceIntent = new Intent(context, ServedService.class);
context.startService(serviceIntent);
context.bindService(serviceIntent, new ServiceConnection() {
     @Override
     public void onServiceConnected(ComponentName name, IBinder service) {
         //retrieve an instance of the service here from the IBinder returned 
         //from the onBind method to communicate with 
     }

     @Override
     public void onServiceDisconnected(ComponentName name) {
     }
}, Context.BIND_AUTO_CREATE);

How can apply multiple background color to one div

Sorry for misunderstanding, from what I understood you want your DIV to have three different colors with different heights. This is the output of my code:

output,

If this is what you want try this code:

_x000D_
_x000D_
div {_x000D_
    height: 100px;_x000D_
    width:400px;_x000D_
    position: relative;_x000D_
}_x000D_
.c {_x000D_
    background: blue; /* Old browsers */_x000D_
}_x000D_
_x000D_
.c:after{_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width:20%;_x000D_
    left:0;_x000D_
    height:110%;_x000D_
    background: yellow;_x000D_
}_x000D_
.c:before{_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    width:40%;_x000D_
    left:60%;_x000D_
    height:140%;_x000D_
    background: green;_x000D_
}
_x000D_
<div class="c"></div>
_x000D_
_x000D_
_x000D_

Insert multiple rows into single column

to insert values for a particular column with other columns remain same:-

INSERT INTO `table_name`(col1,col2,col3)
   VALUES (1,'val1',0),(1,'val2',0),(1,'val3',0)

How to change the port of Tomcat from 8080 to 80?

On a Linux Debian-based (so Ubuntu included) you have also to go to /etc/default/tomcat7, uncomment the #AUTHBIND=no line and set its value to 'yes', in order to let the server bind on a privileged port.

Photoshop text tool adds punctuation to the beginning of text

Select all text afected by this issue:

Window -> Character, click the icon next to hide the Character Window, Middle Western Features and select Left-to-right character direction.

How do I remove blank pages coming between two chapters in Appendix?

If you specify the option 'openany' in the \documentclass declaration each chapter in the book (I'm guessing you're using the book class as chapters open on the next page in reports and articles don't have chapters) will open on a new page, not necessarily the next odd-numbered page.

Of course, that's not quite what you want. I think you want to set openany for chapters in the appendix. 'fraid I don't know how to do that, I suspect that you need to roll up your sleeves and wrestle with TeX itself

XPath: select text node

your xpath should work . i have tested your xpath and mine in both MarkLogic and Zorba Xquery/ Xpath implementation.

Both should work.

/node/child::text()[1] - should return Text1
/node/child::text()[2] - should return text2


/node/text()[1] - should return Text1
/node/text()[2] - should return text2

How do I set hostname in docker-compose?

This seems to work correctly. If I put your config into a file:

$ cat > compose.yml <<EOF
dns:
  image: phensley/docker-dns
  hostname: affy
  domainname: affy.com
  volumes:
    - /var/run/docker.sock:/docker.sock
EOF

And then bring things up:

$ docker-compose -f compose.yml up
Creating tmp_dns_1...
Attaching to tmp_dns_1
dns_1 | 2015-04-28T17:47:45.423387 [dockerdns] table.add tmp_dns_1.docker -> 172.17.0.5

And then check the hostname inside the container, everything seems to be fine:

$ docker exec -it stack_dns_1 hostname
affy.affy.com

How to simulate a real mouse click using java?

FYI, in newer versions of Windows, there's a new setting where if a program is running in Adminstrator mode, then another program not in administrator mode, cannot send any clicks or other input events to it. Check your source program to which you are trying to send the click (right click -> properties), and see if the 'run as administrator' checkbox is selected.

Is there StartsWith or Contains in t sql with variables?

I would use

like 'Express Edition%'

Example:

DECLARE @edition varchar(50); 
set @edition = cast((select SERVERPROPERTY ('edition')) as varchar)

DECLARE @isExpress bit
if @edition like 'Express Edition%'
    set @isExpress = 1;
else
    set @isExpress = 0;

print @isExpress

Cast Object to Generic Type for returning

I stumble upon this question and it grabbed my interest. The accepted answer is completely correct, but I thought I do provide my findings at JVM byte code level to explain why the OP encounter the ClassCastException.

I have the code which is pretty much the same as OP's code:

public static <T> T convertInstanceOfObject(Object o) {
    try {
       return (T) o;
    } catch (ClassCastException e) {
        return null;
    }
}

public static void main(String[] args) {
    String k = convertInstanceOfObject(345435.34);
    System.out.println(k);
}

and the corresponding byte code is:

public static <T> T convertInstanceOfObject(java.lang.Object);
    Code:
       0: aload_0
       1: areturn
       2: astore_1
       3: aconst_null
       4: areturn
    Exception table:
       from    to  target type
           0     1     2   Class java/lang/ClassCastException

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #3                  // double 345435.34d
       3: invokestatic  #5                  // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
       6: invokestatic  #6                  // Method convertInstanceOfObject:(Ljava/lang/Object;)Ljava/lang/Object;
       9: checkcast     #7                  // class java/lang/String
      12: astore_1
      13: getstatic     #8                  // Field java/lang/System.out:Ljava/io/PrintStream;
      16: aload_1
      17: invokevirtual #9                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      20: return

Notice that checkcast byte code instruction happens in the main method not the convertInstanceOfObject and convertInstanceOfObject method does not have any instruction that can throw ClassCastException. Because the main method does not catch the ClassCastException hence when you execute the main method you will get a ClassCastException and not the expectation of printing null.

Now I modify the code to the accepted answer:

public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
        try {
            return clazz.cast(o);
        } catch (ClassCastException e) {
            return null;
        }
    }
    public static void main(String[] args) {
        String k = convertInstanceOfObject(345435.34, String.class);
        System.out.println(k);
    }

The corresponding byte code is:

public static <T> T convertInstanceOfObject(java.lang.Object, java.lang.Class<T>);
    Code:
       0: aload_1
       1: aload_0
       2: invokevirtual #2                  // Method java/lang/Class.cast:(Ljava/lang/Object;)Ljava/lang/Object;
       5: areturn
       6: astore_2
       7: aconst_null
       8: areturn
    Exception table:
       from    to  target type
           0     5     6   Class java/lang/ClassCastException

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #4                  // double 345435.34d
       3: invokestatic  #6                  // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
       6: ldc           #7                  // class java/lang/String
       8: invokestatic  #8                  // Method convertInstanceOfObject:(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;
      11: checkcast     #7                  // class java/lang/String
      14: astore_1
      15: getstatic     #9                  // Field java/lang/System.out:Ljava/io/PrintStream;
      18: aload_1
      19: invokevirtual #10                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      22: return

Notice that there is an invokevirtual instruction in the convertInstanceOfObject method that calls Class.cast() method which throws ClassCastException which will be catch by the catch(ClassCastException e) bock and return null; hence, "null" is printed to console without any exception.

Reading RFID with Android phones

I recently worked on a project to read the RFID tags. The project used the Devices from manufacturers like Zebra (we were using RFD8500 ) & TSL.

More devices are from Motorola & other vendors as well!

We have to use the native SDK api's provided by the manufacturer, how it works is by pairing the device by the Bluetooth of the phones and so the data transfer between both devices take place! The programming is based on subscribe pattern where the scan should be read by the device trigger(hardware trigger) or soft trigger (from the application).

The Tag read gives us the tagId & the RSSI which is the distance factor from the RFID tags!

This is the sample app:

We get all the device paired to our Android/iOS phones :

get device list

connect

connected

Scan

IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

If nothing of this helps (my case), you can set it in your pom.xml, like this:

<properties>
  <maven.compiler.source>1.7</maven.compiler.source>
  <maven.compiler.target>1.7</maven.compiler.target>
</properties>

As this cool guy mentioned here: https://stackoverflow.com/a/25888116/1643465

Escape Character in SQL Server

You could use the **\** character before the value you want to escape e.g insert into msglog(recipient) values('Mr. O\'riely') select * from msglog where recipient = 'Mr. O\'riely'

Getting a link to go to a specific section on another page

To link from a page to another section of the page, I navigate through the page depending on the page's location to the other, at the URL bar, and add the #id. So what I mean;

<a href = "../#the_part_that_you_want">This takes you #the_part_that_you_want at the page before</a>

IIS7: Setup Integrated Windows Authentication like in IIS6

Two-stage authentication is not supported with IIS7 Integrated mode. Authentication is now modularized, so rather than IIS performing authentication followed by asp.net performing authentication, it all happens at the same time.

You can either:

  1. Change the app domain to be in IIS6 classic mode...
  2. Follow this example (old link) of how to fake two-stage authentication with IIS7 integrated mode.
  3. Use Helicon Ape and mod_auth to provide basic authentication

Basic Apache commands for a local Windows machine

Going back to absolute basics here. The answers on this page and a little googling have brought me to the following resolution to my issue. Steps to restart the apache service with Xampp installed:-

  1. Click the start button and type CMD (if on Windows Vista or later and Apache is installed as a service make sure this is an elevated command prompt)
  2. In the command window that appears type cd C:\xampp\apache\bin (the default installation path for Xampp)
  3. Then type httpd -k restart

I hope that this is of use to others just starting out with running a local Apache server.

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

Creating BufferedReader from Files.newBufferedReader

Files.newBufferedReader(Paths.get("a.txt"), StandardCharsets.UTF_8);

when running the application it may throw the following exception:

java.nio.charset.MalformedInputException: Input length = 1

But

new BufferedReader(new InputStreamReader(new FileInputStream("a.txt"),"utf-8"));

works well.

The different is that, the former uses CharsetDecoder default action.

The default action for malformed-input and unmappable-character errors is to report them.

while the latter uses the REPLACE action.

cs.newDecoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE)

Uncompress tar.gz file

gunzip <filename>

then

tar -xvf <tar-file-name>

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

Swift 5 : For evenly distributed spaces between cells with dynamic cell width to make the best of container space you may use the code snippet below by providing a minimumCellWidth value.

private func collectionViewLayout() -> UICollectionViewLayout {
    
    let layout = UICollectionViewFlowLayout()
    layout.sectionHeadersPinToVisibleBounds = true
    // Important: if direction is horizontal use minimumItemSpacing instead. 
    layout.scrollDirection = .vertical
    
    let itemHeight: CGFloat = 240
    let minCellWidth :CGFloat = 130.0
    let minItemSpacing: CGFloat = 10
    let containerWidth: CGFloat = self.view.bounds.width
    let maxCellCountPerRow: CGFloat =  floor((containerWidth - minItemSpacing) / (minCellWidth+minItemSpacing ))
    
    let itemWidth: CGFloat = floor( ((containerWidth - (2 * minItemSpacing) - (maxCellCountPerRow-1) * minItemSpacing) / maxCellCountPerRow  ) )
    // Calculate the remaining space after substracting calculating cellWidth (Divide by 2 because of left and right insets)
    let inset = max(minItemSpacing, floor( (containerWidth - (maxCellCountPerRow*itemWidth) - (maxCellCountPerRow-1)*minItemSpacing) / 2 ) )

    
    layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
    layout.minimumInteritemSpacing = min(minItemSpacing,inset)
    layout.minimumLineSpacing = minItemSpacing
    layout.sectionInset = UIEdgeInsets(top: minItemSpacing, left: inset, bottom: minItemSpacing, right: inset)

    
    return layout
}

Get type of all variables

You can use class(x) to check the variable type. If requirement is to check all variables type of a data frame then sapply(x, class) can be used.

Add legend to ggplot2 line plot

I really like the solution proposed by @Brian Diggs. However, in my case, I create the line plots in a loop rather than giving them explicitly because I do not know apriori how many plots I will have. When I tried to adapt the @Brian's code I faced some problems with handling the colors correctly. Turned out I needed to modify the aesthetic functions. In case someone has the same problem, here is the code that worked for me.

I used the same data frame as @Brian:

data <- structure(list(month = structure(c(1317452400, 1317538800, 1317625200, 1317711600, 
                                       1317798000, 1317884400, 1317970800, 1318057200, 
                                       1318143600, 1318230000, 1318316400, 1318402800, 
                                       1318489200, 1318575600, 1318662000, 1318748400, 
                                       1318834800, 1318921200, 1319007600, 1319094000), 
                                     class = c("POSIXct", "POSIXt"), tzone = ""),
                   TempMax = c(26.58, 27.78, 27.9, 27.44, 30.9, 30.44, 27.57, 25.71, 
                               25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 26.58, 26.18, 
                               25.19, 24.19, 27.65, 23.92), 
                   TempMed = c(22.88, 22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52,
                                 19.71, 20.73, 23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 
                                 20.45, 19.42, 19.97, 19.61), 
                   TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 16.88, 16.82, 
                               14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01, 16.95, 
                               17.55, 15.21, 14.22, 16.42)), 
              .Names = c("month", "TempMax", "TempMed", "TempMin"), 
              row.names = c(NA, 20L), class = "data.frame")  

In my case, I generate my.cols and my.names dynamically, but I don't want to make things unnecessarily complicated so I give them explicitly here. These three lines make the ordering of the legend and assigning colors easier.

my.cols <- heat.colors(3, alpha=1)
my.names <- c("TempMin", "TempMed", "TempMax")
names(my.cols) <- my.names

And here is the plot:

p <-  ggplot(data, aes(x = month))

for (i in 1:3){
  p <- p + geom_line(aes_(y = as.name(names(data[i+1])), colour = 
colnames(data[i+1])))#as.character(my.names[i])))
}
p + scale_colour_manual("", 
                        breaks = as.character(my.names),
                        values = my.cols)
p

enter image description here

How do I insert an image in an activity with android studio?

When you have image into yours drawable gallery then you just need to pick the option of image view pick and drag into app activity you want to show and select the required image.

Basic example of using .ajax() with JSONP?

There is even easier way how to work with JSONP using jQuery

$.getJSON("http://example.com/something.json?callback=?", function(result){
   //response data are now in the result variable
   alert(result);
});

The ? on the end of the URL tells jQuery that it is a JSONP request instead of JSON. jQuery registers and calls the callback function automatically.

For more detail refer to the jQuery.getJSON documentation.

Remove element from JSON Object

JSfiddle

function deleteEmpty(obj){
        for(var k in obj)
         if(k == "children"){
             if(obj[k]){
                     deleteEmpty(obj[k]);
             }else{
                   delete obj.children;
              } 
         }
    }

for(var i=0; i< a.children.length; i++){
 deleteEmpty(a.children[i])
}

Move to next item using Java 8 foreach loop in stream

Using return; will work just fine. It will not prevent the full loop from completing. It will only stop executing the current iteration of the forEach loop.

Try the following little program:

public static void main(String[] args) {
    ArrayList<String> stringList = new ArrayList<>();
    stringList.add("a");
    stringList.add("b");
    stringList.add("c");

    stringList.stream().forEach(str -> {
        if (str.equals("b")) return; // only skips this iteration.

        System.out.println(str);
    });
}

Output:

a
c

Notice how the return; is executed for the b iteration, but c prints on the following iteration just fine.

Why does this work?

The reason the behavior seems unintuitive at first is because we are used to the return statement interrupting the execution of the whole method. So in this case, we expect the main method execution as a whole to be halted.

However, what needs to be understood is that a lambda expression, such as:

str -> {
    if (str.equals("b")) return;

    System.out.println(str);
}

... really needs to be considered as its own distinct "method", completely separate from the main method, despite it being conveniently located within it. So really, the return statement only halts the execution of the lambda expression.

The second thing that needs to be understood is that:

stringList.stream().forEach()

... is really just a normal loop under the covers that executes the lambda expression for every iteration.

With these 2 points in mind, the above code can be rewritten in the following equivalent way (for educational purposes only):

public static void main(String[] args) {
    ArrayList<String> stringList = new ArrayList<>();
    stringList.add("a");
    stringList.add("b");
    stringList.add("c");

    for(String s : stringList) {
        lambdaExpressionEquivalent(s);
    }
}

private static void lambdaExpressionEquivalent(String str) {
    if (str.equals("b")) {
        return;
    }

    System.out.println(str);
}

With this "less magic" code equivalent, the scope of the return statement becomes more apparent.

Automatic creation date for Django model form objects?

Well, the above answer is correct, auto_now_add and auto_now would do it, but it would be better to make an abstract class and use it in any model where you require created_at and updated_at fields.

class TimeStampMixin(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

Now anywhere you want to use it you can do a simple inherit and you can use timestamp in any model you make like.

class Posts(TimeStampMixin):
    name = models.CharField(max_length=50)
    ...
    ...

In this way, you can leverage object-oriented reusability, in Django DRY(don't repeat yourself)

Regex pattern including all special characters

Please use this.. it is simplest.

\p{Punct} Punctuation: One of !"#$%&'()*+,-./:;<=>?@[]^_`{|}~

https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

    StringBuilder builder = new StringBuilder(checkstring);
    String regex = "\\p{Punct}"; //Special character : `~!@#$%^&*()-_+=\|}{]["';:/?.,><
    //change your all special characters to "" 
    Pattern  pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(builder.toString());
    checkstring=matcher.replaceAll("");

How to combine GROUP BY and ROW_NUMBER?

;with C as
(
  select Rel.t2ID,
         Rel.t1ID,
         t1.Price,
         row_number() over(partition by Rel.t2ID order by t1.Price desc) as rn
  from @t1 as T1
    inner join @relation as Rel
      on T1.ID = Rel.t1ID
)
select T2.ID as T2ID,
       T2.Name as T2Name,
       T2.Orders,
       T1.ID as T1ID,
       T1.Name as T1Name,
       T1Sum.Price
from @t2 as T2
  inner join (
              select C1.t2ID,
                     sum(C1.Price) as Price,
                     C2.t1ID
              from C as C1
                inner join C as C2 
                  on C1.t2ID = C2.t2ID and
                     C2.rn = 1
              group by C1.t2ID, C2.t1ID
             ) as T1Sum
    on T2.ID = T1Sum.t2ID
  inner join @t1 as T1
    on T1.ID = T1Sum.t1ID

jQuery SVG, why can't I addClass?

Here is my rather inelegant but working code that deals with the following issues (without any dependencies):

  • classList not existing on <svg> elements in IE
  • className not representing the class attribute on <svg> elements in IE
  • Old IE's broken getAttribute() and setAttribute() implementations

It uses classList where possible.

Code:

var classNameContainsClass = function(fullClassName, className) {
    return !!fullClassName &&
           new RegExp("(?:^|\\s)" + className + "(?:\\s|$)").test(fullClassName);
};

var hasClass = function(el, className) {
    if (el.nodeType !== 1) {
        return false;
    }
    if (typeof el.classList == "object") {
        return (el.nodeType == 1) && el.classList.contains(className);
    } else {
        var classNameSupported = (typeof el.className == "string");
        var elClass = classNameSupported ? el.className : el.getAttribute("class");
        return classNameContainsClass(elClass, className);
    }
};

var addClass = function(el, className) {
    if (el.nodeType !== 1) {
        return;
    }
    if (typeof el.classList == "object") {
        el.classList.add(className);
    } else {
        var classNameSupported = (typeof el.className == "string");
        var elClass = classNameSupported ?
            el.className : el.getAttribute("class");
        if (elClass) {
            if (!classNameContainsClass(elClass, className)) {
                elClass += " " + className;
            }
        } else {
            elClass = className;
        }
        if (classNameSupported) {
            el.className = elClass;
        } else {
            el.setAttribute("class", elClass);
        }
    }
};

var removeClass = (function() {
    function replacer(matched, whiteSpaceBefore, whiteSpaceAfter) {
        return (whiteSpaceBefore && whiteSpaceAfter) ? " " : "";
    }

    return function(el, className) {
        if (el.nodeType !== 1) {
            return;
        }
        if (typeof el.classList == "object") {
            el.classList.remove(className);
        } else {
            var classNameSupported = (typeof el.className == "string");
            var elClass = classNameSupported ?
                el.className : el.getAttribute("class");
            elClass = elClass.replace(new RegExp("(^|\\s)" + className + "(\\s|$)"), replacer);
            if (classNameSupported) {
                el.className = elClass;
            } else {
                el.setAttribute("class", elClass);
            }
        }
    }; //added semicolon here
})();

Example usage:

var el = document.getElementById("someId");
if (hasClass(el, "someClass")) {
    removeClass(el, "someClass");
}
addClass(el, "someOtherClass");

Compare integer in bash, unary operator expected

Judging from the error message the value of i was the empty string when you executed it, not 0.

Is it bad to have my virtualenv directory inside my git repository?

I used to do the same until I started using libraries that are compiled differently depending on the environment such as PyCrypto. My PyCrypto mac wouldn't work on Cygwin wouldn't work on Ubuntu.

It becomes an utter nightmare to manage the repository.

Either way I found it easier to manage the pip freeze & a requirements file than having it all in git. It's cleaner too since you get to avoid the commit spam for thousands of files as those libraries get updated...

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint

Go to the Design, right click on your Widget, Constraint Layout >> Infer Constraints. You can observe that some code has been automatically added to your Text.

What, exactly, is needed for "margin: 0 auto;" to work?

It's perhaps interesting that you do not have to specify width for a <button> element to make it work - just make sure it has display:block : http://jsfiddle.net/muhuyttr/

Scala best way of turning a Collection into a Map-by-key?

You can use

c map (t => t.getP -> t) toMap

but be aware that this needs 2 traversals.

How to generate a random string in Ruby

I like Radar's answer best, so far, I think. I'd tweak a bit like this:

CHARS = ('a'..'z').to_a + ('A'..'Z').to_a
def rand_string(length=8)
  s=''
  length.times{ s << CHARS[rand(CHARS.length)] }
  s
end

Insert current date into a date column using T-SQL?

UPDATE Table
SET DateColumn=GETDATE()
WHERE UserID=@UserID

If you're inserting into a table, and will always need to put the current date, I would recommend setting GETDATE() as the default value for that column, and don't allow NULLs

Render HTML to an image

I read the answer by Sjeiti which I found very interesting, where you with just a few plain JavaScript lines can render HTML in an image.

We of course have to be aware of the limitations of this method (please read about some of them in his answer).

Here I have taken his code a couple of steps further.

An SVG-image has in principle infinite resolution, since it is vector graphics. But you might have noticed that the image that Sjeiti's code generated did not have a high resolution. This can be fixed by scaling the SVG-image before transferring it to the canvas-element, which I have done in the last one of the two (runnable) example codes i give below. The other thing I have implemented in that code is the last step, namely saving it as a PNG-file. Just to complete the whole thing.

So, I give two runnable snippets of code:

The first one demonstrates the infinite resolution of an SVG. Run it and zoom in with your browser to see that the resolution does not diminish as you zoom in.

In the snippet that you can run I have used backticks to specify a so called template string with line breaks so that you can more clearly see the HTML that is rendered. But otherwise, if that HTML is within one line, then the code will be very short, like this.

const body = document.getElementsByTagName('BODY')[0];
const img = document.createElement('img')
img.src = 'data:image/svg+xml,' + encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml" style="border:1px solid red;padding:20px;"><style>em {color:red;}.test {color:blue;}</style>What you see here is only an image, nothing else.<br /><br /><em>I</em> really like <span class="test">cheese.</span><br /><br />Zoom in to check the resolution!</div></foreignObject></svg>`);        
body.appendChild(img);

Here it comes as a runnable snippet.

_x000D_
_x000D_
const body = document.getElementsByTagName('BODY')[0];
const img = document.createElement('img')
img.src = 'data:image/svg+xml,' + encodeURIComponent(`
  <svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
    <foreignObject width="100%" height="100%">
      <div xmlns="http://www.w3.org/1999/xhtml" style="border:1px solid red;padding:20px;">
        <style>
          em {
            color:red;
          }
          .test {
            color:blue;
          }
        </style>
        What you see here is only an image, nothing
        else.<br />
        <br />
        <em>I</em> really like <span class="test">cheese.</span><br />
        <br />
        Zoom in to check the resolution!
      </div>
    </foreignObject>
  </svg>
`);
body.appendChild(img);
_x000D_
_x000D_
_x000D_

Zoom in and check the infinite resolution of the SVG.

The next runnable, below, is the one that implements the two extra steps which I mentioned above, namely improving resolution by first scaling the SVG, and then the saving as a PNG-image.

_x000D_
_x000D_
window.addEventListener("load", doit, false)
var canvas;
var ctx;
var tempImg;
function doit() {
    const body = document.getElementsByTagName('BODY')[0];
    const scale = document.getElementById('scale').value;
    let trans = document.getElementById('trans').checked;
  if (trans) {
    trans = '';
  } else {
    trans = 'background-color:white;';
  }
    let source = `
        <div xmlns="http://www.w3.org/1999/xhtml" style="border:1px solid red;padding:20px;${trans}">
            <style>
                em {
                    color:red;
                }
                .test {
                    color:blue;
                }
            </style>
            What you see here is only an image, nothing
            else.<br />
            <br />
            <em>I</em> really like <span class="test">cheese.</span><br />
            <br />
            <div style="text-align:center;">
                Scaling:
                <br />
                ${scale} times!
            </div>
        </div>`
    document.getElementById('source').innerHTML = source;
    canvas = document.createElement('canvas');
    ctx = canvas.getContext('2d');
    canvas.width = 200*scale;
    canvas.height = 200*scale;
    tempImg = document.createElement('img');
    tempImg.src = 'data:image/svg+xml,' + encodeURIComponent(`
        <svg xmlns="http://www.w3.org/2000/svg" width="${200*scale}" height="${200*scale}">
            <foreignObject 
                style="
                    width:200px;
                    height:200px;
                    transform:scale(${scale});
                "
            >` + source + `
            </foreignObject>
        </svg>
    `);
}
function saveAsPng(){
    ctx.drawImage(tempImg, 0, 0);
    var a  = document.createElement('a');
    a.href = canvas.toDataURL('image/png');
    a.download = 'image.png';
    a.click();
}
_x000D_
<table border="0">
    <tr>
        <td colspan="2">
            The claims in the HTML-text is only true for the image created when you click the button.
        </td>
    </tr>
    <tr>
        <td width="250">
            <div id="source" style="width:200px;height:200px;">
            </div>
        </td>
        <td valign="top">
            <div>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;In this example the PNG-image will be squarish even if the HTML here on the left is not exactly squarish. That can be fixed.<br>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;To increase the resolution of the image you can change the scaling with this slider.
                <div style="text-align:right;margin:5px 0px;">
                    <label style="background-color:#FDD;border:1px solid #F77;padding:0px 10px;"><input id="trans" type="checkbox" onchange="doit();" />&nbsp;&nbsp;Make it transparent</label>
                </div>
                <span style="white-space:nowrap;">1<input id="scale" type="range" min="1" max="10" step="0.25" value="2" oninput="doit();" style="width:150px;vertical-align:-8px;" />10&nbsp;&nbsp;<button onclick="saveAsPng();">Save as PNG-image</button></span>
            </div>
            
        </td>
    </tr>
</table>
_x000D_
_x000D_
_x000D_

Try with different scalings. If you for example set scaling to 10, then you get a very good resolution in the generated PNG-image. And I added a little extra feature: a checkbox so that you can make the PNG-image transparent if you like.

Notice:

The Save-button does not work in Chrome and Edge when this script is run here at Stack Overflow. The reason is this https://www.chromestatus.com/feature/5706745674465280 .

Therefore I have also put this snippet on https://jsfiddle.net/7gozdq5v/ where it works for those browsers.

Accessing Session Using ASP.NET Web API

Why to avoid using Session in WebAPI?

Performance, performance, performance!

There's a very good, and often overlooked reason why you shouldn't be using Session in WebAPI at all.

The way ASP.NET works when Session is in use is to serialize all requests received from a single client. Now I'm not talking about object serialization - but running them in the order received and waiting for each to complete before running the next. This is to avoid nasty thread / race conditions if two requests each try to access Session simultaneously.

Concurrent Requests and Session State

Access to ASP.NET session state is exclusive per session, which means that if two different users make concurrent requests, access to each separate session is granted concurrently. However, if two concurrent requests are made for the same session (by using the same SessionID value), the first request gets exclusive access to the session information. The second request executes only after the first request is finished. (The second session can also get access if the exclusive lock on the information is freed because the first request exceeds the lock time-out.) If the EnableSessionState value in the @ Page directive is set to ReadOnly, a request for the read-only session information does not result in an exclusive lock on the session data. However, read-only requests for session data might still have to wait for a lock set by a read-write request for session data to clear.

So what does this mean for Web API? If you have an application running many AJAX requests then only ONE is going to be able to run at a time. If you have a slower request then it will block all others from that client until it is complete. In some applications this could lead to very noticeably sluggish performance.

So you should probably use an MVC controller if you absolutely need something from the users session and avoid the unncesessary performance penalty of enabling it for WebApi.

You can easily test this out for yourself by just putting Thread.Sleep(5000) in a WebAPI method and enable Session. Run 5 requests to it and they will take a total of 25 seconds to complete. Without Session they'll take a total of just over 5 seconds.

(This same reasoning applies to SignalR).

Python group by

Python's built-in itertools module actually has a groupby function , but for that the elements to be grouped must first be sorted such that the elements to be grouped are contiguous in the list:

from operator import itemgetter
sortkeyfn = itemgetter(1)
input = [('11013331', 'KAT'), ('9085267', 'NOT'), ('5238761', 'ETH'), 
 ('5349618', 'ETH'), ('11788544', 'NOT'), ('962142', 'ETH'), ('7795297', 'ETH'), 
 ('7341464', 'ETH'), ('9843236', 'KAT'), ('5594916', 'ETH'), ('1550003', 'ETH')] 
input.sort(key=sortkeyfn)

Now input looks like:

[('5238761', 'ETH'), ('5349618', 'ETH'), ('962142', 'ETH'), ('7795297', 'ETH'),
 ('7341464', 'ETH'), ('5594916', 'ETH'), ('1550003', 'ETH'), ('11013331', 'KAT'),
 ('9843236', 'KAT'), ('9085267', 'NOT'), ('11788544', 'NOT')]

groupby returns a sequence of 2-tuples, of the form (key, values_iterator). What we want is to turn this into a list of dicts where the 'type' is the key, and 'items' is a list of the 0'th elements of the tuples returned by the values_iterator. Like this:

from itertools import groupby
result = []
for key,valuesiter in groupby(input, key=sortkeyfn):
    result.append(dict(type=key, items=list(v[0] for v in valuesiter)))

Now result contains your desired dict, as stated in your question.

You might consider, though, just making a single dict out of this, keyed by type, and each value containing the list of values. In your current form, to find the values for a particular type, you'll have to iterate over the list to find the dict containing the matching 'type' key, and then get the 'items' element from it. If you use a single dict instead of a list of 1-item dicts, you can find the items for a particular type with a single keyed lookup into the master dict. Using groupby, this would look like:

result = {}
for key,valuesiter in groupby(input, key=sortkeyfn):
    result[key] = list(v[0] for v in valuesiter)

result now contains this dict (this is similar to the intermediate res defaultdict in @KennyTM's answer):

{'NOT': ['9085267', '11788544'], 
 'ETH': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 
 'KAT': ['11013331', '9843236']}

(If you want to reduce this to a one-liner, you can:

result = dict((key,list(v[0] for v in valuesiter)
              for key,valuesiter in groupby(input, key=sortkeyfn))

or using the newfangled dict-comprehension form:

result = {key:list(v[0] for v in valuesiter)
              for key,valuesiter in groupby(input, key=sortkeyfn)}

Listing only directories using ls in Bash?

Try this one. It works for all Linux distribution.

ls -ltr | grep drw

Running sites on "localhost" is extremely slow

In my case, originally the following error was occurring:

Cannot read configuration file due to insufficient permissions

I fixed the error by using the proposed solution and restarted the application through IIS Manager. The original error was gone but the application was taking forever to load. I gave the permissions to IIS_IUSRS again but this time to the whole deployment folder. After this, the application was able to load though an error was showing up:

This configuration section cannot be used at this path

After resolving the above-mentioned error using the solution, the application was finally loading without giving any error.

How do I force git to use LF instead of CR+LF under windows?

The proper way to get LF endings in Windows is to first set core.autocrlf to false:

git config --global core.autocrlf false

You need to do this if you are using msysgit, because it sets it to true in its system settings.

Now git won’t do any line ending normalization. If you want files you check in to be normalized, do this: Set text=auto in your .gitattributes for all files:

* text=auto

And set core.eol to lf:

git config --global core.eol lf

Now you can also switch single repos to crlf (in the working directory!) by running

git config core.eol crlf

After you have done the configuration, you might want git to normalize all the files in the repo. To do this, go to to the root of your repo and run these commands:

git rm --cached -rf .
git diff --cached --name-only -z | xargs -n 50 -0 git add -f

If you now want git to also normalize the files in your working directory, run these commands:

git ls-files -z | xargs -0 rm
git checkout .

Putting an if-elif-else statement on one line?

Just nest another if clause in the else statement. But that doesn't make it look any prettier.

>>> x=5
>>> x if x>0 else ("zero" if x==0 else "invalid value")
5
>>> x = 0
>>> x if x>0 else ("zero" if x==0 else "invalid value")
'zero'
>>> x = -1
>>> x if x>0 else ("zero" if x==0 else "invalid value")
'invalid value'

Difference between window.location.href and top.location.href

top object makes more sense inside frames. Inside a frame, window refers to current frame's window while top refers to the outermost window that contains the frame(s). So:

window.location.href = 'somepage.html'; means loading somepage.html inside the frame.

top.location.href = 'somepage.html'; means loading somepage.html in the main browser window.

Two other interesting objects are self and parent.

What's the scope of a variable initialized in an if statement?

Unlike languages such as C, a Python variable is in scope for the whole of the function (or class, or module) where it appears, not just in the innermost "block". It is as though you declared int x at the top of the function (or class, or module), except that in Python you don't have to declare variables.

Note that the existence of the variable x is checked only at runtime -- that is, when you get to the print x statement. If __name__ didn't equal "__main__" then you would get an exception: NameError: name 'x' is not defined.

How to find whether a ResultSet is empty or not in Java?

Do this using rs.next():

while (rs.next())
{
    ...
}

If the result set is empty, the code inside the loop won't execute.

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

   SELECT CONVERT(varchar(11),getdate(),101)  -- mm/dd/yyyy

   SELECT CONVERT(varchar(11),getdate(),103)  -- dd/mm/yyyy

Check this . I am assuming D30.SPGD30_TRACKED_ADJUSTMENT_X is of datetime datatype .
That is why i am using CAST() function to make it as an character expression because CHARINDEX() works on character expression.
Also I think there is no need of OR condition.

select case when CHARINDEX('-',cast(D30.SPGD30_TRACKED_ADJUSTMENT_X as varchar )) > 0 

then 'Score Calculation - '+CONVERT(VARCHAR(11), D30.SPGD30_TRACKED_ADJUSTMENT_X, 103)
end

EDIT:

select case when CHARINDEX('-',D30.SPGD30_TRACKED_ADJUSTMENT_X) > 0 
then 'Score Calculation - '+
CONVERT( VARCHAR(11), CAST(D30.SPGD30_TRACKED_ADJUSTMENT_X as DATETIME) , 103)
end

See this link for conversion to other date formats: https://www.w3schools.com/sql/func_sqlserver_convert.asp

How do I determine whether my calculation of pi is accurate?

The Taylor series is one way to approximate pi. As noted it converges slowly.

The partial sums of the Taylor series can be shown to be within some multiplier of the next term away from the true value of pi.

Other means of approximating pi have similar ways to calculate the max error.

We know this because we can prove it mathematically.

Turning off eslint rule for a specific file

To temporarily disable rule warnings in your file, use block comments in the following format:

/* eslint-disable */

This will disable ESLint until the

/* eslint-enable */

comment is reached.

You can read more about this topic here.

Simple mediaplayer play mp3 from file path?

2020 - NOV

This worked for me:

final File file = new File(getFilesDir(), "test.wav");//OR path to existing file
mediaPlayer = MediaPlayer.create(getApplicationContext(), Uri.fromFile(file));
mediaPlayer.start();

How to send emails from my Android application?

I've been using this since long time ago and it seems good, no non-email apps showing up. Just another way to send a send email intent:

Intent intent = new Intent(Intent.ACTION_SENDTO); // it's not ACTION_SEND
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject of email");
intent.putExtra(Intent.EXTRA_TEXT, "Body of email");
intent.setData(Uri.parse("mailto:[email protected]")); // or just "mailto:" for blank
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // this will make such that when user returns to your app, your app is displayed, instead of the email app.
startActivity(intent);

make an html svg object also a clickable link

Would like to take credit for this but I found a solution here:

https://teamtreehouse.com/forum/how-do-you-make-a-svg-clickable

add the following to the css for the anchor:

a.svg {
  position: relative;
  display: inline-block; 
}
a.svg:after {
  content: ""; 
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left:0;
}


<a href="#" class="svg">
  <object data="random.svg" type="image/svg+xml">
    <img src="random.jpg" />
  </object>
</a>

Link works on the svg and on the fallback.

Mysql service is missing

Go to your mysql bin directory and install mysql service again:

c:
cd \mysql\bin
mysqld-nt.exe --install

or if mysqld-nt.exe is missing (depending on version):

mysqld.exe --install

Then go to services, start the service and set it to automatic start.

How do I modify fields inside the new PostgreSQL JSON datatype?

what do you think about this solution ?

It will add the new value or update an existing one.

Edit: edited to make it work with null and empty object

Edit2: edited to make it work with object in the object...

create or replace function updateJsonb(object1 json, object2 json)
returns jsonb
language plpgsql
as
$$
declare
    result jsonb;
    tempObj1 text;
    tempObj2 text;

begin
    tempObj1 = substr(object1::text, 2, length(object1::text) - 2); --remove the first { and last }
    tempObj2 = substr(object2::text, 2, length(object2::text) - 2); --remove the first { and last }

    IF object1::text != '{}' and object1::text != 'null' and object1::text != '[]' THEN
        result = ('{' || tempObj1 || ',' || tempObj2 || '}')::jsonb;
    ELSE
        result = ('{' || tempObj2 || '}')::jsonb;
    END IF;
    return result;
end;
$$;

usage:

update table_name
set data = updatejsonb(data, '{"test": "ok"}'::json)

Checkout another branch when there are uncommitted changes on the current branch

In case you don't want this changes to be committed at all do git reset --hard.

Next you can checkout to wanted branch, but remember that uncommitted changes will be lost.

What is the default text size on Android?

http://petrnohejl.github.io/Android-Cheatsheet-For-Graphic-Designers/

Text size

Type    Dimension
Micro   12 sp
Small   14 sp
Medium  18 sp
Large   22 sp

Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'

I solved this issue for myself by changing the following line in the Visual Studio project's .csproj file:

This threw the 'cannot import' error:

<PropertyGroup>
<SignManifests>true</SignManifests>
</PropertyGroup>

Changing the value to false made the error go away.

"You have mail" message in terminal, os X

I was also having this issue of "You have mail" coming up every time I started Terminal.

What I discovered is this.

Something I'd installed (not entirely sure what, but possibly a script or something associated with an Alfred Workflow [at a guess]) made a change to the OS X system to start presenting Terminal bash notifications. Prior to that, it appears Wordpress had attempted to use the Local Mail system to send a message. The message bounced, due to it having an invalid Recipient address. The bounced message then ended up in the local system mail inbox. So Terminal (bash) was then notifying me that "You have mail".

You can access the mail by simply using the command

mail

This launches you into Mail, and it will right away show you a list of messages that are stored there. If you want to see the content of the first message, use

t

This will show you the content of the first message, in full. You'll need to scroll down through the message to view it all, by hitting the down-arrow key.

If you want to jump to the end of the message, use the

spacebar

If you want to abort viewing the message, use

q 

To view the next message in the queue use

n

... assuming there's more than one message.

NOTE: You need to use these commands at the mail ? command prompt. They won't work whilst you are in the process of viewing a message. Hitting n whilst viewing a message will just cause an error message related to regular expressions. So, if in the midst of viewing a message, hit q to quit from that, or hit spacebar to jump to the end of the message, and then at the ? prompt, hit n.

Viewing the content of the messages in this way may help you identify what attempted to send the message(s).

You can also view a specific message by just inputting its number at the ? prompt. 3, for instance, will show you the content of the third message (if there are that many in there).

DELETING MESSAGES

Use the d command (at the ? command prompt )

d [message number]

To delete each message when you are done looking at them. For example, d 2 will delete message number 2. Or you can delete a list of messages, such as d 1 2 5 7. Or you can delete a range of messages with (for example), d 3-10. You can find the message numbers in the list of messages mail shows you.

To delete all the messages, from the mail prompt (?) use the command d *.

As per a comment on this post, you will need to use q to quit mail, which also saves any changes.

If you'd like to see the mail all in one output, use this command at the bash prompt (i.e. not from within mail, but from your regular command prompt):

cat /var/mail/<username>

And, if you wish to delete the emails all in one hit, use this command

sudo rm /var/mail/<username>

In my particular case, there were a number of messages. It looks like the one was a returned message that bounced. It was sent by a local Wordpress installation. It was a notification for when user "Admin" (me) changed its password. Two additional messages where there. Both seemed to be to the same incident.

What I don't know, and can't answer for you either, is WHY I only recently started seeing this mail notification each time I open Terminal. The mails were generated a couple of months ago, and yet I only noticed this "you have mail" appearing in the last few weeks. I suspect it's the result of something a workflow I installed in Alfred, and that workflow using Terminal bash to provide notifications... or something along those lines.

Simply deleting the messages

If you have no interest in determining the source of the messages, and just wish to get rid of them, it may be easier to do so without using the mail command (which can be somewhat fiddly). As pointed out by a few other people, you can use this command instead:

sudo rm /var/mail/YOURUSERNAME

Appending a line break to an output file in a shell script

You can do that without an I/O redirection:

sed -i 's/$/\n/' filename

You can also use this command to append a newline to a list of files:

find dir -name filepattern | xargs sed -i 's/$/\n/' filename

For echo, some shells implement it as a shell builtin command. It might not accept the -e option. If you still want to use echo, try to find where the echo binary file is, using which echo. In most cases, it is located in /bin/echo, so you can use /bin/echo -e "\n" to echo a new line.

Remove spaces from std::string in C++

For trimming, use boost string algorithms:

#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost;

// ...

string str1(" hello world! ");
trim(str1);      // str1 == "hello world!"

"Debug certificate expired" error in Eclipse Android plugins

I had this problem couple of weeks ago. I first tried the troubleshooting on the Android developer site, but without luck. After that I reinstalled the Android SDK, which solved my problem.

Gunicorn worker timeout error

Frank's answer pointed me in the right direction. I have a Digital Ocean droplet accessing a managed Digital Ocean Postgresql database. All I needed to do was add my droplet to the database's "Trusted Sources".

(click on database in DO console, then click on settings. Edit Trusted Sources and select droplet name (click in editable area and it will be suggested to you)).

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

I also experienced this error when working with CMake:

No CMAKE_C_COMPILER could be found.
No CMAKE_CXX_COMPILER could be found.

The 'warning' box in the MSDN library article Visual C++ in Visual Studio 2015 gave me the help that I needed.

Visual Studio 2015 doesn't come with C++ installed by default. So, creating a new C++ project will prompt you to download the necessary C++ components.

Why is Java Vector (and Stack) class considered obsolete or deprecated?

Vector synchronizes on each individual operation. That's almost never what you want to do.

Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time, which would cause a ConcurrentModificationException in the iterating thread) but also slower (why take out a lock repeatedly when once will be enough)?

Of course, it also has the overhead of locking even when you don't need to.

Basically, it's a very flawed approach to synchronization in most situations. As Mr Brian Henk pointed out, you can decorate a collection using the calls such as Collections.synchronizedList - the fact that Vector combines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns.

As for a Stack equivalent - I'd look at Deque/ArrayDeque to start with.

Simple way to transpose columns and rows in SQL?

I'd like to point out few more solutions to transposing columns and rows in SQL.

The first one is - using CURSOR. Although the general consensus in the professional community is to stay away from SQL Server Cursors, there are still instances whereby the use of cursors is recommended. Anyway, Cursors present us with another option to transpose rows into columns.

  • Vertical expansion

    Similar to the PIVOT, the cursor has the dynamic capability to append more rows as your dataset expands to include more policy numbers.

  • Horizontal expansion

    Unlike the PIVOT, the cursor excels in this area as it is able to expand to include newly added document, without altering the script.

  • Performance breakdown

    The major limitation of transposing rows into columns using CURSOR is a disadvantage that is linked to using cursors in general – they come at significant performance cost. This is because the Cursor generates a separate query for each FETCH NEXT operation.

Another solution of transposing rows into columns is by using XML.

The XML solution to transposing rows into columns is basically an optimal version of the PIVOT in that it addresses the dynamic column limitation.

The XML version of the script addresses this limitation by using a combination of XML Path, dynamic T-SQL and some built-in functions (i.e. STUFF, QUOTENAME).

  • Vertical expansion

    Similar to the PIVOT and the Cursor, newly added policies are able to be retrieved in the XML version of the script without altering the original script.

  • Horizontal expansion

    Unlike the PIVOT, newly added documents can be displayed without altering the script.

  • Performance breakdown

    In terms of IO, the statistics of the XML version of the script is almost similar to the PIVOT – the only difference is that the XML has a second scan of dtTranspose table but this time from a logical read – data cache.

You can find some more about these solutions (including some actual T-SQL exmaples) in this article: https://www.sqlshack.com/multiple-options-to-transposing-rows-into-columns/

What is considered a good response time for a dynamic, personalized web application?

It depends on what keeps your users happy. For example, Gmail takes quite a while to open at first, but users wait because it is worth waiting for.

How to get just the date part of getdate()?

SELECT CAST(FLOOR(CAST(GETDATE() AS float)) as datetime)

or

SELECT CONVERT(datetime,FLOOR(CONVERT(float,GETDATE())))

document.getElementById('btnid').disabled is not working in firefox and chrome

Try setting the disabled attribute directly:

if ( someCondition == true ) {
   document.getElementById('btn1').setAttribute('disabled', 'disabled');
} else {
   document.getElementById('btn1').removeAttribute('disabled');
}

Python int to binary string?

For those of us who need to convert signed integers (range -2**(digits-1) to 2**(digits-1)-1) to 2's complement binary strings, this works:

def int2bin(integer, digits):
    if integer >= 0:
        return bin(integer)[2:].zfill(digits)
    else:
        return bin(2**digits + integer)[2:]

This produces:

>>> int2bin(10, 8)
'00001010'
>>> int2bin(-10, 8)
'11110110'
>>> int2bin(-128, 8)
'10000000'
>>> int2bin(127, 8)
'01111111'

POST request not allowed - 405 Not Allowed - nginx, even with headers included

This configuration to your nginx.conf should help you.

https://gist.github.com/baskaran-md/e46cc25ccfac83f153bb

server {
    listen       80;
    server_name  localhost;

    location / {
        root   html;
        index  index.html index.htm;
    }

    error_page  404     /404.html;
    error_page  403     /403.html;

    # To allow POST on static pages
    error_page  405     =200 $uri;

    # ...
}

How to load an ImageView by URL in Android?

1. Picasso allows for hassle-free image loading in your application—often in one line of code!

Use Gradle:

implementation 'com.squareup.picasso:picasso:(insert latest version)'

Just one line of code!

Picasso.get().load("http://i.imgur.com/DvpvklR.png").into(imageView);

2. Glide An image loading and caching library for Android focused on smooth scrolling

Use Gradle:

repositories {
  mavenCentral() 
  google()
}

dependencies {
   implementation 'com.github.bumptech.glide:glide:4.11.0'
   annotationProcessor 'com.github.bumptech.glide:compiler4.11.0'
}

// For a simple view:

  Glide.with(this).load("http://i.imgur.com/DvpvklR.png").into(imageView);

3. fresco is a powerful system for displaying images in Android applications.Fresco takes care of image loading and display, so you don't have to.

Getting Started with Fresco

AngularJS: ng-show / ng-hide not working with `{{ }}` interpolation

You can't use {{}} when using angular directives for binding with ng-model but for binding non-angular attributes you would have to use {{}}..

Eg:

ng-show="my-model"
title = "{{my-model}}"

SyntaxError: Unexpected Identifier in Chrome's Javascript console

Replace

 var myNewString = myOldString.replace ("username," visitorName);

with

 var myNewString = myOldString.replace("username", visitorName);

How to skip a iteration/loop in while-loop

You don't need to skip the iteration, since the rest of it is in the else statement, it will only be executed if the condition is not true.

But if you really need to skip it, you can use the continue; statement.

HTML: How to create a DIV with only vertical scroll-bars for long paragraphs?

This is my mix:

overflow-y: scroll;
height: 13em; // Initial height.
resize: vertical; // Allow user to change the vertical size.
max-height: 31em; // If you want to constrain the max size.

Zookeeper connection error

I faced the same issue and found it was due to zookeeper cluster nodes needs ports opened to communicate with each other.

server.1=xx.xx.xx.xx:2888:3888

server.2=xx.xx.xx.xx:2888:3888

server.3=xx.xx.xx.xx:2888:3888

once i allowed these ports through aws security group and restarted. All worked fine for me

How do I make a JAR from a .java file?

Although it is not recommended method but still it works
[7-Zip Software is needed]
Procedure to get jar from java files:

  • place all java files in one folder

  • right click on the folder enter image description here

  • now click on Add to archive you will get something like shown below enter image description here

  • now just change zip to jar and click on ok

.m2 , settings.xml in Ubuntu

As per Where is Maven Installed on Ubuntu it will first create your settings.xml on /usr/share/maven2/, then you can copy to your home folder as jens mentioned

$ cp /usr/share/maven3/conf/settings.xml ~/.m2/settings.xml

docker command not found even though installed with apt-get

The Ubuntu package docker actually refers to a GUI application, not the beloved DevOps tool we've come out to look for.

The instructions for docker can be followed per instructions on the docker page here: https://docs.docker.com/engine/install/ubuntu/

=== UPDATED (thanks @Scott Stensland) ===

You now run the following install script to get docker:

`sudo curl -sSL https://get.docker.com/ | sh`
  • Note: review the script on the website and make sure you have the right link before continuing since you are running this as sudo.

This will run a script that installs docker. Note the last part of the script:

If you would like to use Docker as a non-root user, you should now consider
adding your user to the "docker" group with something like:

  `sudo usermod -aG docker stens`

Remember that you will have to log out and back in for this to take effect!

To update Docker run:

`sudo apt-get update && sudo apt-get upgrade`

For more details on what's going on, See the docker install documentation or @Scott Stensland's answer below

.

=== UPDATE: For those uncomfortable w/ sudo | sh ===

Some in the comments have mentioned that it a risk to run an arbitrary script as sudo. The above option is a convenience script from docker to make the task simple. However, for those that are security-focused but don't want to read the script you can do the following:

  1. Add Dependencies
sudo apt-get update; \
sudo apt-get install \
 apt-transport-https \
 ca-certificates \
 curl \
 gnupg-agent \
 software-properties-common
  1. Add docker gpg key

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

(Security check, verify key fingerprint 9DC8 5822 9FC7 DD38 854A E2D8 8D81 803C 0EBF CD88

$ sudo apt-key fingerprint 0EBFCD88

pub   rsa4096 2017-02-22 [SCEA]
      9DC8 5822 9FC7 DD38 854A  E2D8 8D81 803C 0EBF CD88
uid           [ unknown] Docker Release (CE deb) <[email protected]>
sub   rsa4096 2017-02-22 [S]

)

  1. Setup Repository
sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"
  1. Install Docker
sudo apt-get update; \
sudo apt-get install docker-ce docker-ce-cli containerd.io

If you want to verify that it worked run: sudo docker run hello-world


The following explains why it is named like this: Why install docker on ubuntu should be `sudo apt-get install docker.io`?

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

Is there any sizeof-like method in Java?

You can use Integer.SIZE / 8, Double.SIZE / 8, etc. for primitive types from Java 1.5.

jQuery/Javascript function to clear all the fields of a form

function reset_form() {
 $('#ID_OF_FORM').each (function(){  
    this.reset();
 }); 
}

How to delete all instances of a character in a string in python?

Strings are immutable in Python, which means once a string is created, you cannot alter the contents of the strings. If at all, you need to change it, a new instance of the string will be created with the alterations.

Having that in mind, we have so many ways to solve this

  1. Using str.replace,

    >>> "it is icy".replace("i", "")
    't s cy'
    
  2. Using str.translate,

    >>> "it is icy".translate(None, "i")
    't s cy'
    
  3. Using Regular Expression,

    >>> import re
    >>> re.sub(r'i', "", "it is icy")
    't s cy'
    
  4. Using comprehension as a filter,

    >>> "".join([char for char in "it is icy" if char != "i"])
    't s cy'
    
  5. Using filter function

    >>> "".join(filter(lambda char: char != "i", "it is icy"))
    't s cy'
    

Timing comparison

def findreplace(m_string, char):
    m_string = list(m_string)
    for k in m_string:
        if k == char:
            del(m_string[m_string.index(k)])
    return "".join(m_string)

def replace(m_string, char):
    return m_string.replace("i", "")

def translate(m_string, char):
    return m_string.translate(None, "i")

from timeit import timeit

print timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
print timeit("replace('it is icy','i')", "from __main__ import replace")
print timeit("translate('it is icy','i')", "from __main__ import translate")

Result

1.64474582672
0.29278588295
0.311302900314

str.replace and str.translate methods are 8 and 5 times faster than the accepted answer.

Note: Comprehension method and filter methods are expected to be slower, for this case, since they have to create list and then they have to be traversed again to construct a string. And re is a bit overkill for a single character replacement. So, they all are excluded from the timing comparison.

Java default constructor

A default constructor does not take any arguments:

public class Student { 
    // default constructor
    public Student() {   

    }
}

Compiler error "archive for required library could not be read" - Spring Tool Suite

I was using Eclipse as IDE and I was getting very same error. I had to do Project->Maven->Update Project. Select all the checkboxes below except "offline" esp. the one "Force update of snapshots/releases" and click OK. Did the Clean Build for the Project again.

How to center a button within a div?

Responsive CSS option to center a button vertically and horizontally without being concerned with parent element size (using data attribute hooks for clarity and separation concerns):

HTML

<div data-element="card">
  <div data-container="button"><button>CTA...</button></div>
</div>

CSS

[data-container="button"] {
  position: absolute;
  top: 50%;
  text-align: center;
  width: 100%;
}

Fiddle: https://jsfiddle.net/crrollyson/zebo1z8f/

What is Java String interning?

JLS

JLS 7 3.10.5 defines it and gives a practical example:

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

Example 3.10.5-1. String Literals

The program consisting of the compilation unit (§7.3):

package testPackage;
class Test {
    public static void main(String[] args) {
        String hello = "Hello", lo = "lo";
        System.out.print((hello == "Hello") + " ");
        System.out.print((Other.hello == hello) + " ");
        System.out.print((other.Other.hello == hello) + " ");
        System.out.print((hello == ("Hel"+"lo")) + " ");
        System.out.print((hello == ("Hel"+lo)) + " ");
        System.out.println(hello == ("Hel"+lo).intern());
    }
}
class Other { static String hello = "Hello"; }

and the compilation unit:

package other;
public class Other { public static String hello = "Hello"; }

produces the output:

true true true true false true

JVMS

JVMS 7 5.1 says says that interning is implemented magically and efficiently with a dedicated CONSTANT_String_info struct (unlike most other objects which have more generic representations):

A string literal is a reference to an instance of class String, and is derived from a CONSTANT_String_info structure (§4.4.3) in the binary representation of a class or interface. The CONSTANT_String_info structure gives the sequence of Unicode code points constituting the string literal.

The Java programming language requires that identical string literals (that is, literals that contain the same sequence of code points) must refer to the same instance of class String (JLS §3.10.5). In addition, if the method String.intern is called on any string, the result is a reference to the same class instance that would be returned if that string appeared as a literal. Thus, the following expression must have the value true:

("a" + "b" + "c").intern() == "abc"

To derive a string literal, the Java Virtual Machine examines the sequence of code points given by the CONSTANT_String_info structure.

  • If the method String.intern has previously been called on an instance of class String containing a sequence of Unicode code points identical to that given by the CONSTANT_String_info structure, then the result of string literal derivation is a reference to that same instance of class String.

  • Otherwise, a new instance of class String is created containing the sequence of Unicode code points given by the CONSTANT_String_info structure; a reference to that class instance is the result of string literal derivation. Finally, the intern method of the new String instance is invoked.

Bytecode

Let's decompile some OpenJDK 7 bytecode to see interning in action.

If we decompile:

public class StringPool {
    public static void main(String[] args) {
        String a = "abc";
        String b = "abc";
        String c = new String("abc");
        System.out.println(a);
        System.out.println(b);
        System.out.println(a == c);
    }
}

we have on the constant pool:

#2 = String             #32   // abc
[...]
#32 = Utf8               abc

and main:

 0: ldc           #2          // String abc
 2: astore_1
 3: ldc           #2          // String abc
 5: astore_2
 6: new           #3          // class java/lang/String
 9: dup
10: ldc           #2          // String abc
12: invokespecial #4          // Method java/lang/String."<init>":(Ljava/lang/String;)V
15: astore_3
16: getstatic     #5          // Field java/lang/System.out:Ljava/io/PrintStream;
19: aload_1
20: invokevirtual #6          // Method java/io/PrintStream.println:(Ljava/lang/String;)V
23: getstatic     #5          // Field java/lang/System.out:Ljava/io/PrintStream;
26: aload_2
27: invokevirtual #6          // Method java/io/PrintStream.println:(Ljava/lang/String;)V
30: getstatic     #5          // Field java/lang/System.out:Ljava/io/PrintStream;
33: aload_1
34: aload_3
35: if_acmpne     42
38: iconst_1
39: goto          43
42: iconst_0
43: invokevirtual #7          // Method java/io/PrintStream.println:(Z)V

Note how:

  • 0 and 3: the same ldc #2 constant is loaded (the literals)
  • 12: a new string instance is created (with #2 as argument)
  • 35: a and c are compared as regular objects with if_acmpne

The representation of constant strings is quite magic on the bytecode:

and the JVMS quote above seems to say that whenever the Utf8 pointed to is the same, then identical instances are loaded by ldc.

I have done similar tests for fields, and:

  • static final String s = "abc" points to the constant table through the ConstantValue Attribute
  • non-final fields don't have that attribute, but can still be initialized with ldc

Conclusion: there is direct bytecode support for the string pool, and the memory representation is efficient.

Bonus: compare that to the Integer pool, which does not have direct bytecode support (i.e. no CONSTANT_String_info analogue).

initialize a numpy array

For your first array example use,

a = numpy.arange(5)

To initialize big_array, use

big_array = numpy.zeros((10,4))

This assumes you want to initialize with zeros, which is pretty typical, but there are many other ways to initialize an array in numpy.

Edit: If you don't know the size of big_array in advance, it's generally best to first build a Python list using append, and when you have everything collected in the list, convert this list to a numpy array using numpy.array(mylist). The reason for this is that lists are meant to grow very efficiently and quickly, whereas numpy.concatenate would be very inefficient since numpy arrays don't change size easily. But once everything is collected in a list, and you know the final array size, a numpy array can be efficiently constructed.

When should I use uuid.uuid1() vs. uuid.uuid4() in python?

uuid1() is guaranteed to not produce any collisions (under the assumption you do not create too many of them at the same time). I wouldn't use it if it's important that there's no connection between the uuid and the computer, as the mac address gets used to make it unique across computers.

You can create duplicates by creating more than 214 uuid1 in less than 100ns, but this is not a problem for most use cases.

uuid4() generates, as you said, a random UUID. The chance of a collision is really, really, really small. Small enough, that you shouldn't worry about it. The problem is, that a bad random-number generator makes it more likely to have collisions.

This excellent answer by Bob Aman sums it up nicely. (I recommend reading the whole answer.)

Frankly, in a single application space without malicious actors, the extinction of all life on earth will occur long before you have a collision, even on a version 4 UUID, even if you're generating quite a few UUIDs per second.

In git, what is the difference between merge --squash and rebase?

Both git merge --squash and git rebase --interactive can produce a "squashed" commit.
But they serve different purposes.

will produce a squashed commit on the destination branch, without marking any merge relationship.
(Note: it does not produce a commit right away: you need an additional git commit -m "squash branch")
This is useful if you want to throw away the source branch completely, going from (schema taken from SO question):

 git checkout stable

      X                   stable
     /                   
a---b---c---d---e---f---g tmp

to:

git merge --squash tmp
git commit -m "squash tmp"

      X-------------------G stable
     /                   
a---b---c---d---e---f---g tmp

and then deleting tmp branch.


Note: git merge has a --commit option, but it cannot be used with --squash. It was never possible to use --commit and --squash together.
Since Git 2.22.1 (Q3 2019), this incompatibility is made explicit:

See commit 1d14d0c (24 May 2019) by Vishal Verma (reloadbrain).
(Merged by Junio C Hamano -- gitster -- in commit 33f2790, 25 Jul 2019)

merge: refuse --commit with --squash

Previously, when --squash was supplied, 'option_commit' was silently dropped. This could have been surprising to a user who tried to override the no-commit behavior of squash using --commit explicitly.

git/git builtin/merge.c#cmd_merge() now includes:

if (option_commit > 0)
    die(_("You cannot combine --squash with --commit."));

replays some or all of your commits on a new base, allowing you to squash (or more recently "fix up", see this SO question), going directly to:

git checkout tmp
git rebase -i stable

      stable
      X-------------------G tmp
     /                     
a---b

If you choose to squash all commits of tmp (but, contrary to merge --squash, you can choose to replay some, and squashing others).

So the differences are:

  • squash does not touch your source branch (tmp here) and creates a single commit where you want.
  • rebase allows you to go on on the same source branch (still tmp) with:
    • a new base
    • a cleaner history

Singletons vs. Application Context in Android?

Consider both at the same time:

  • having singleton objects as static instances inside the classes.
  • having a common class (Context) that returns the singleton instances for all the singelton objects in your application, which has the advantage that the method names in Context will be meaningful for example: context.getLoggedinUser() instead of User.getInstance().

Furthermore, I suggest that you expand your Context to include not only access to singleton objects but some functionalities that need to be accessed globally, like for example: context.logOffUser(), context.readSavedData(), etc. Probably renaming the Context to Facade would make sense then.

Case insensitive access for generic dictionary

For you LINQers out there that never use a regular dictionary constructor

myCollection.ToDictionary(x => x.PartNumber, x => x.PartDescription, StringComparer.OrdinalIgnoreCase)

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

I found the problem that was causing the HTTP error.

In the setFalse() function that is triggered by the Save button my code was trying to submit the form that contained the button.

        function setFalse(){
            document.getElementById("hasId").value ="false";
            document.deliveryForm.submit();
            document.submitForm.submit();

when I remove the document.submitForm.submit(); it works:

        function setFalse(){
            document.getElementById("hasId").value ="false";
            document.deliveryForm.submit()

@Roger Lindsjö Thank you for spotting my error where I wasn't passing on the right parameter!

How can I create objects while adding them into a vector?

I know the thread is already all, but as I was checking through I've come up with a solution (code listed below). Hope it can help.

#include <iostream>
#include <vector>

class Box
{
    public:

    static int BoxesTotal;
    static int BoxesEver;
    int Id;

    Box()
    {
        ++BoxesTotal;
        ++BoxesEver;
        Id = BoxesEver;
        std::cout << "Box (" << Id << "/" << BoxesTotal << "/" << BoxesEver << ") initialized." << std::endl;
    }

    ~Box()
    {
        std::cout << "Box (" << Id << "/" << BoxesTotal << "/" << BoxesEver << ") ended." << std::endl;
        --BoxesTotal;
    }

};

int Box::BoxesTotal = 0;
int Box::BoxesEver = 0;

int main(int argc, char* argv[])
{
    std::cout << "Objects (Boxes) example." << std::endl;
    std::cout << "------------------------" << std::endl;

    std::vector <Box*> BoxesTab;

    Box* Indicator;
    for (int i = 1; i<4; ++i)
    {
        std::cout << "i = " << i << ":" << std::endl;
        Box* Indicator = new(Box);
        BoxesTab.push_back(Indicator);
        std::cout << "Adres Blowera: " <<  BoxesTab[i-1] << std::endl;
    }

    std::cout << "Summary" << std::endl;
    std::cout << "-------" << std::endl;
    for (int i=0; i<3; ++i)
    {
        std::cout << "Adres Blowera: " <<  BoxesTab[i] << std::endl;
    }

    std::cout << "Deleting" << std::endl;
    std::cout << "--------" << std::endl;
    for (int i=0; i<3; ++i)
    {
        std::cout << "Deleting Box: " << i+1 << " (" <<  BoxesTab[i] << ") " << std::endl;
        Indicator = (BoxesTab[i]);
        delete(Indicator);
    }

    return 0;
}

And the result it produces is:

Objects (Boxes) example.
------------------------
i = 1:
Box (1/1/1) initialized.
Adres Blowera: 0xdf8ca0
i = 2:
Box (2/2/2) initialized.
Adres Blowera: 0xdf8ce0
i = 3:
Box (3/3/3) initialized.
Adres Blowera: 0xdf8cc0
Summary
-------
Adres Blowera: 0xdf8ca0
Adres Blowera: 0xdf8ce0
Adres Blowera: 0xdf8cc0
Deleting
--------
Deleting Box: 1 (0xdf8ca0) 
Box (1/3/3) ended.
Deleting Box: 2 (0xdf8ce0) 
Box (2/2/3) ended.
Deleting Box: 3 (0xdf8cc0) 
Box (3/1/3) ended.

plot legends without border and with white background

Use option bty = "n" in legend to remove the box around the legend. For example:

legend(1, 5,
       "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",
       bty = "n")

How to remove all line breaks from a string

If you want to remove all control characters, including CR and LF, you can use this:

myString.replace(/[^\x20-\x7E]/gmi, "")

It will remove all non-printable characters. This are all characters NOT within the ASCII HEX space 0x20-0x7E. Feel free to modify the HEX range as needed.

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?

  
from chromedriver_py import binary_path
 
 
chrome_options = webdriver.ChromeOptions()
   chrome_options.add_argument('--headless')
   chrome_options.add_argument('--no-sandbox')
   chrome_options.add_argument('--disable-gpu')
   chrome_options.add_argument('--window-size=1280x1696')
   chrome_options.add_argument('--user-data-dir=/tmp/user-data')
   chrome_options.add_argument('--hide-scrollbars')
   chrome_options.add_argument('--enable-logging')
   chrome_options.add_argument('--log-level=0')
   chrome_options.add_argument('--v=99')
   chrome_options.add_argument('--single-process')
   chrome_options.add_argument('--data-path=/tmp/data-path')
   chrome_options.add_argument('--ignore-certificate-errors')
   chrome_options.add_argument('--homedir=/tmp')
   chrome_options.add_argument('--disk-cache-dir=/tmp/cache-dir')
   chrome_options.add_argument('user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36')
   
  driver = webdriver.Chrome(executable_path = binary_path,options=chrome_options)

How to delete a character from a string using Python

card = random.choice(cards)
cardsLeft = cards.replace(card, '', 1)

How to remove one character from a string: Here is an example where there is a stack of cards represented as characters in a string. One of them is drawn (import random module for the random.choice() function, that picks a random character in the string). A new string, cardsLeft, is created to hold the remaining cards given by the string function replace() where the last parameter indicates that only one "card" is to be replaced by the empty string...

How to install Python package from GitHub?

You need to use the proper git URL:

pip install git+https://github.com/jkbr/httpie.git#egg=httpie

Also see the VCS Support section of the pip documentation.

Don’t forget to include the egg=<projectname> part to explicitly name the project; this way pip can track metadata for it without having to have run the setup.py script.

How to remove all callbacks from a Handler?

If you don't have the Runnable references, on the first callback, get the obj of the message, and use removeCallbacksAndMessages() to remove all related callbacks.

What is the correct way to free memory in C#

The .NET garbage collector takes care of all this for you.

It is able to determine when objects are no longer referenced and will (eventually) free the memory that had been allocated to them.

how to change default python version?

Check the location of python 3

$ which python3
/usr/local/bin/python3

Write alias in bash_profile

vi ~/.bash_profile  
alias python='/usr/local/bin/python3'

Reload bash_profile

source ~/.bash_profile

Confirm python command

$ python --version
Python 3.6.5

Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server."

answer for me was to fix a gridview control which contained a template field that had a dropdownlist which was loaded with a monstrous amount of selectable items- i replaced the DDL with a label field whose data is generated from a function. (i was originally going to allow gridview editing, but have switched to allowing edits on a separate panel displaying the DDL for that field for just that record). hope this might help someone.

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

I got the same error and ended up using a pre-built distribution of numpy available in SourceForge (similarly, a distribution of matplotlib can be obtained).

Builds for both 32-bit 2.7 and 3.3/3.4 are available.
PyCharm detected them straight away, of course.

Angular : Manual redirect to route

You may have enough correct answers for your question but in case your IDE gives you the warning

Promise returned from navigate is ignored

you may either ignore that warning or use this.router.navigate(['/your-path']).then().

How to call a JavaScript function within an HTML body

Try to use createChild() method of DOM or insertRow() and insertCell() method of table object in script tag.

Multiple conditions in an IF statement in Excel VBA

In VBA we can not use if jj = 5 or 6 then we must use if jj = 5 or jj = 6 then

maybe this:

If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then

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);

Set div height to fit to the browser using CSS

I think the fastest way is to use grid system with fractions. So your container have 100vw, which is 100% of the window width and 100vh which is 100% of the window height.

Using fractions or 'fr' you can choose the width you like. the sum of the fractions equals to 100%, in this example 4fr. So the first part will be 1fr (25%) and the seconf is 3fr (75%)

More about fr units here.

_x000D_
_x000D_
.container{
  width: 100vw;
  height:100vh; 
  display: grid;
  grid-template-columns: 1fr 3fr;
}

/*You don't need this*/
.div1{
  background-color: yellow;
}

.div2{
  background-color: red;
}
_x000D_
<div class='container'>
  <div class='div1'>This is div 1</div>
  <div class='div2'>This is div 2</div>
</div>
_x000D_
_x000D_
_x000D_

How can you program if you're blind?

NVDA is a good open source screen reader for win.

Creating a div element inside a div element in javascript

Yes, you either need to do this onload or in a <script> tag after the closing </body> tag, when the lc element is already found in the document's DOM tree.

Disable keyboard on EditText

I found this solution which works for me. It also places the cursor, when clicked on EditText at the correct position.

EditText editText = (EditText)findViewById(R.id.edit_mine);
// set OnTouchListener to consume the touch event
editText.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            v.onTouchEvent(event);   // handle the event first
            InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);  // hide the soft keyboard 
            }                
            return true;
        }
    });

Fixed header table with horizontal scrollbar and vertical scrollbar on

Here's a solution which again is not a CSS only solution. It is similar to avrahamcool's solution in that it uses a few lines of jQuery, but instead of changing heights and moving the header along, all it does is changing the width of tbody based on how far its parent table is scrolled along to the right.

An added bonus with this solution is that it works with a semantically valid HTML table.

It works great on all recent browser versions (IE10, Chrome, FF) and that's it, the scrolling functionality breaks on older versions.

But then the fact that you are using a semantically valid HTML table will save the day and ensure the table is still displayed properly, it's only the scrolling functionality that won't work on older browsers.

Here's a jsFiddle for demonstration purposes.

CSS

table {
    width: 300px;
    overflow-x: scroll;
    display: block;
}
thead, tbody {
    display: block;
}
tbody {
    overflow-y: scroll;
    overflow-x: hidden;
    height: 140px;
}
td, th {
    min-width: 100px;
}

JS

$("table").on("scroll", function () {
    $("table > *").width($("table").width() + $("table").scrollLeft());
});

I needed a version which degrades nicely in IE9 (no scrolling, just a normal table). Posting the fiddle here as it is an improved version. All you need to do is set a height on the tr.

Additional CSS to make this solution degrade nicely in IE9

tr {
    height: 25px; /* This could be any value, it just needs to be set. */ 
}

Here's a jsFiddle demonstrating the nicely degrading in IE9 version of this solution.

Edit: Updated fiddle links to link to a version of the fiddle which contains fixes for issues mentioned in the comments. Just adding a snippet with the latest and greatest version while I'm at it:

_x000D_
_x000D_
$('table').on('scroll', function() {_x000D_
  $("table > *").width($("table").width() + $("table").scrollLeft());_x000D_
});
_x000D_
html {_x000D_
  font-family: verdana;_x000D_
  font-size: 10pt;_x000D_
  line-height: 25px;_x000D_
}_x000D_
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
  width: 300px;_x000D_
  overflow-x: scroll;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
thead {_x000D_
  background-color: #EFEFEF;_x000D_
}_x000D_
_x000D_
thead,_x000D_
tbody {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
tbody {_x000D_
  overflow-y: scroll;_x000D_
  overflow-x: hidden;_x000D_
  height: 140px;_x000D_
}_x000D_
_x000D_
td,_x000D_
th {_x000D_
  min-width: 100px;_x000D_
  height: 25px;_x000D_
  border: dashed 1px lightblue;_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
  max-width: 100px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column 1</th>_x000D_
      <th>Column 2</th>_x000D_
      <th>Column 3</th>_x000D_
      <th>Column 4</th>_x000D_
      <th>Column 5</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>AAAAAAAAAAAAAAAAAAAAAAAAAA</td>_x000D_
      <td>Row 1</td>_x000D_
      <td>Row 1</td>_x000D_
      <td>Row 1</td>_x000D_
      <td>Row 1</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 2</td>_x000D_
      <td>Row 2</td>_x000D_
      <td>Row 2</td>_x000D_
      <td>Row 2</td>_x000D_
      <td>Row 2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 3</td>_x000D_
      <td>Row 3</td>_x000D_
      <td>Row 3</td>_x000D_
      <td>Row 3</td>_x000D_
      <td>Row 3</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 4</td>_x000D_
      <td>Row 4</td>_x000D_
      <td>Row 4</td>_x000D_
      <td>Row 4</td>_x000D_
      <td>Row 4</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 5</td>_x000D_
      <td>Row 5</td>_x000D_
      <td>Row 5</td>_x000D_
      <td>Row 5</td>_x000D_
      <td>Row 5</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 6</td>_x000D_
      <td>Row 6</td>_x000D_
      <td>Row 6</td>_x000D_
      <td>Row 6</td>_x000D_
      <td>Row 6</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 7</td>_x000D_
      <td>Row 7</td>_x000D_
      <td>Row 7</td>_x000D_
      <td>Row 7</td>_x000D_
      <td>Row 7</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 8</td>_x000D_
      <td>Row 8</td>_x000D_
      <td>Row 8</td>_x000D_
      <td>Row 8</td>_x000D_
      <td>Row 8</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 9</td>_x000D_
      <td>Row 9</td>_x000D_
      <td>Row 9</td>_x000D_
      <td>Row 9</td>_x000D_
      <td>Row 9</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 10</td>_x000D_
      <td>Row 10</td>_x000D_
      <td>Row 10</td>_x000D_
      <td>Row 10</td>_x000D_
      <td>Row 10</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to schedule a task to run when shutting down windows

What I can suggest doing is creating a shortcut to the .bat file (for example on your desktop) and a when you want to shutdown your computer (and run the .bat file) click on the shortcut you created. After doing this, edit the .bat file and add this line of code to the end or where needed:

c:\windows\system32\shutdown -s -f -t 00

What this does it is

  1. Runs the shutdown process
  2. Displays a alert
  3. Forces all running processes to stop
  4. Executes immediately

Find if a textbox is disabled or not using jquery

 if($("element_selector").attr('disabled') || $("element_selector").prop('disabled'))
 {

    // code when element is disabled

  }

Eclipse: Enable autocomplete / content assist

If you are only unfamiliar with the auto-complete while typing syntax or inbuilt methods in the eclipse you can simply type the desired syntax or method name and press Ctrl+Space that will display the list of desired options and you can select one of them.

If the auto-complete option is not enabled then you have to check your settings from Windows menu -> Preferences -> Java -> Editor -> Content assist

SSIS Connection not found in package

i had the same issue and niether of the above resoved it. It turns out there was an old sql task that was disabled on the bottom right corner of my ssis that i really had to look for to find. Once i deleted this all was well

Javascript variable access in HTML

The info inside the <script> tag is then processed inside it to access other parts. If you want to change the text inside another paragraph, then first give the paragraph an id, then set a variable to it using getElementById([id]) to access it ([id] means the id you gave the paragraph). Next, use the innerHTML built-in variable with whatever your variable was called and a '.' (dot) to show that it is based on the paragraph. You can set it to whatever you want, but be aware that to set a paragraph to a tag (<...>), then you have to still put it in speech marks.

Example:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <body>_x000D_
        <!--\|/id here-->_x000D_
        <p id="myText"></p>_x000D_
        <p id="myTextTag"></p>_x000D_
        <script>_x000D_
            <!--Here we retrieve the text and show what we want to write..._x000D_
            var text = document.getElementById("myText");_x000D_
            var tag = document.getElementById("myTextTag");_x000D_
            var toWrite = "Hello"_x000D_
            var toWriteTag = "<a href='https://stackoverflow.com'>Stack Overflow</a>"_x000D_
            <!--...and here we are actually affecting the text.-->_x000D_
            text.innerHTML = toWrite_x000D_
            tag.innerHTML = toWriteTag_x000D_
        </script>_x000D_
    <body>_x000D_
<html>
_x000D_
_x000D_
_x000D_

Can't start Tomcat as Windows Service

Go to Start > Configure Tomcat >

  • Startup > Mode = Java
  • Shutdown > Mode = Java

This worked for me!

Can I make a function available in every controller in angular?

You basically have two options, either define it as a service, or place it on your root scope. I would suggest that you make a service out of it to avoid polluting the root scope. You create a service and make it available in your controller like this:

<!doctype html>
<html ng-app="myApp">
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
    <script type="text/javascript">
    var myApp = angular.module('myApp', []);

    myApp.factory('myService', function() {
        return {
            foo: function() {
                alert("I'm foo!");
            }
        };
    });

    myApp.controller('MainCtrl', ['$scope', 'myService', function($scope, myService) {
        $scope.callFoo = function() {
            myService.foo();
        }
    }]);
    </script>
</head>
<body ng-controller="MainCtrl">
    <button ng-click="callFoo()">Call foo</button>
</body>
</html>

If that's not an option for you, you can add it to the root scope like this:

<!doctype html>
<html ng-app="myApp">
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
    <script type="text/javascript">
    var myApp = angular.module('myApp', []);

    myApp.run(function($rootScope) {
        $rootScope.globalFoo = function() {
            alert("I'm global foo!");
        };
    });

    myApp.controller('MainCtrl', ['$scope', function($scope){

    }]);
    </script>
</head>
<body ng-controller="MainCtrl">
    <button ng-click="globalFoo()">Call global foo</button>
</body>
</html>

That way, all of your templates can call globalFoo() without having to pass it to the template from the controller.

How do change the color of the text of an <option> within a <select>?

You just need to add disabled as option attribute

<option disabled>select one option</option>

Attach a file from MemoryStream to a MailMessage in C#

I think this code will help you:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;

public partial class _Default : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {

  }

  protected void btnSubmit_Click(object sender, EventArgs e)
  {
    try
    {
      MailAddress SendFrom = new MailAddress(txtFrom.Text);
      MailAddress SendTo = new MailAddress(txtTo.Text);

      MailMessage MyMessage = new MailMessage(SendFrom, SendTo);

      MyMessage.Subject = txtSubject.Text;
      MyMessage.Body = txtBody.Text;

      Attachment attachFile = new Attachment(txtAttachmentPath.Text);
      MyMessage.Attachments.Add(attachFile);

      SmtpClient emailClient = new SmtpClient(txtSMTPServer.Text);
      emailClient.Send(MyMessage);

      litStatus.Text = "Message Sent";
    }
    catch (Exception ex)
    {
      litStatus.Text = ex.ToString();
    }
  }
}

Get current time in hours and minutes

With bash version >= 4.2:

printf "%(%H:%M)T\n"

or

printf -v foo "%(%H:%M)T\n"
echo "$foo"

See: man bash

Why is pydot unable to find GraphViz's executables in Windows 8?

For me: (Win10, Anaconda3) Make sure you have done "conda install graphviz"

I have to add to the PATH: C:\Users\username\Anaconda3\Library\bin\graphviz

To modify PATH go to Control Panel > System and Security > System > Advanced System Settings > Environment Variables > Path > Edit > New

MAKE SURE TO RESTART YOUR IDE AFTER THIS. It should work

How to get root access on Android emulator?

I know this question is pretty old. But we can able to get root in Emulator with the help of Magisk by following https://github.com/shakalaca/MagiskOnEmulator

Basically, it patch initrd.img(if present) and ramdisk.img for working with Magisk.

Showing the same file in both columns of a Sublime Text window

It is possible to edit same file in Split mode. It is best explained in following youtube video.

https://www.youtube.com/watch?v=q2cMEeE1aOk

Downloading a large file using curl

Find below code if you want to download the contents of the specified URL also want to saves it to a file.

<?php
$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL,'http://news.google.com/news?hl=en&topic=t&output=rss');

$fp = fopen('rss.xml', 'w+');
/**
* Ask cURL to write the contents to a file
*/
curl_setopt($ch, CURLOPT_FILE, $fp);

curl_exec ($ch);

curl_close ($ch);
fclose($fp);
?>

If you want to downloads file from the FTP server you can use php FTP extension. Please find below code:

<?php
$SERVER_ADDRESS="";
$SERVER_USERNAME="";
$SERVER_PASSWORD="";
$conn_id = ftp_connect($SERVER_ADDRESS);

// login with username and password
$login_result = ftp_login($conn_id, $SERVER_USERNAME, $SERVER_PASSWORD);

$server_file="test.pdf" //FTP server file path 
$local_file = "new.pdf"; //Local server file path 

##----- DOWNLOAD $SERVER_FILE AND SAVE TO $LOCAL_FILE--------##
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
    echo "Successfully written to $local_file\n";
} else {
    echo "There was a problem\n";
}

ftp_close($conn_id);
?>

HTML Button : Navigate to Other Page - Different Approaches

I make a link. A link is a link. A link navigates to another page. That is what links are for and everybody understands that. So Method 3 is the only correct method in my book.

I wouldn't want my link to look like a button at all, and when I do, I still think functionality is more important than looks.

Buttons are less accessible, not only due to the need of Javascript, but also because tools for the visually impaired may not understand this Javascript enhanced button well.

Method 4 would work as well, but it is more a trick than a real functionality. You abuse a form to post 'nothing' to this other page. It's not clean.

Insert data into a view (SQL Server)

Go to design for that table. Now, on the right, set the ID column as the column in question. It will now auto populate without specification.

Angularjs simple file download causes router to redirect

in template

<md-button class="md-fab md-mini md-warn md-ink-ripple" ng-click="export()" aria-label="Export">
<md-icon class="material-icons" alt="Export" title="Export" aria-label="Export">
    system_update_alt
</md-icon></md-button>

in controller

     $scope.export = function(){ $window.location.href = $scope.export; };

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE

How to set up ES cluster?

It is usually handled automatically.

If autodiscovery doesn't work. Edit the elastic search config file, by enabling unicast discovery

Node 1:

    cluster.name: mycluster
    node.name: "node1"
    node.master: true
    node.data: true
    discovery.zen.ping.multicast.enabled: false
    discovery.zen.ping.unicast.hosts: ["node1.example.com"]

Node 2:

    cluster.name: mycluster
    node.name: "node2"
    node.master: false
    node.data: true
    discovery.zen.ping.multicast.enabled: false
    discovery.zen.ping.unicast.hosts: ["node1.example.com"]

and so on for node 3,4,5. Make node 1 master, and the rest only as data nodes.

Edit: Please note that by ES rule, if you have N nodes, then by convention, N/2+1 nodes should be masters for fail-over mechanisms They may or may not be data nodes, though.

Also, in case auto-discovery doesn't work, most probable reason is because the network doesn't allow it (and therefore disabled). If too many auto-discovery pings take place across multiple servers, the resources to manage those pings will prevent other services from running correctly.

For ex, think of a 10,000 node cluster and all 10,000 nodes doing the auto-pings.

Extracting an attribute value with beautifulsoup

You can try gazpacho:

Install it using pip install gazpacho

Get the HTML and make the Soup using:

from gazpacho import get, Soup

soup = Soup(get("http://ip.add.ress.here/"))  # get directly returns the html

inputs = soup.find('input', attrs={'name': 'stainfo'})  # Find all the input tags

if inputs:
    if type(inputs) is list:
        for input in inputs:
             print(input.attr.get('value'))
    else:
         print(inputs.attr.get('value'))
else:
     print('No <input> tag found with the attribute name="stainfo")

Regular expression for letters, numbers and - _

This is the pattern you are looking for

/^[\w-_.]*$/

What this means:

  • ^ Start of string
  • [...] Match characters inside
  • \w Any word character so 0-9 a-z A-Z
  • -_. Match - and _ and .
  • * Zero or more of pattern or unlimited
  • $ End of string

If you want to limit the amount of characters:

/^[\w-_.]{0,5}$/

{0,5} Means 0-5 characters

How to Turn Off Showing Whitespace Characters in Visual Studio IDE

CTRL+R, CTRL+W : Toggle showing whitespace

or under the Edit Menu:

  • Edit -> Advanced -> View White Space

[BTW, it also appears you are using Tabs. It's common practice to have the IDE turn Tabs into spaces (often 4), via Options.]

jquery stop child triggering parent event

Or this:

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

Set value to an entire column of a pandas dataframe

Assuming your Data frame is like 'Data' you have to consider if your data is a string or an integer. Both are treated differently. So in this case you need be specific about that.

import pandas as pd

data = [('001','xxx'), ('002','xxx'), ('003','xxx'), ('004','xxx'), ('005','xxx')]

df = pd.DataFrame(data,columns=['issueid', 'industry'])

print("Old DataFrame")
print(df)

df.loc[:,'industry'] = str('yyy')

print("New DataFrame")
print(df)

Now if want to put numbers instead of letters you must create and array

list_of_ones = [1,1,1,1,1]
df.loc[:,'industry'] = list_of_ones
print(df)

Or if you are using Numpy

import numpy as np
n = len(df)
df.loc[:,'industry'] = np.ones(n)
print(df)

Simulate Keypress With jQuery

Another option:

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

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

Jquery asp.net Button Click Event via ajax

In the client side handle the click event of the button, use the ClientID property to get he id of the button:

$(document).ready(function() {
$("#<%=myButton.ClientID %>,#<%=muSecondButton.ClientID%>").click(

    function() {
     $.get("/myPage.aspx",{id:$(this).attr('id')},function(data) {
       // do something with the data
     return false;
     }
    });
 });

In your page on the server:

protected void Page_Load(object sender,EventArgs e) {
 // check if it is an ajax request
 if (Request.Headers["X-Requested-With"] == "XMLHttpRequest") {
  if (Request.QueryString["id"]==myButton.ClientID) {
    // call the click event handler of the myButton here
    Response.End();
  }
  if (Request.QueryString["id"]==mySecondButton.ClientID) {
    // call the click event handler of the mySecondButton here
    Response.End();
  }
 }
}

535-5.7.8 Username and Password not accepted

Goto config/initializers/setup_mail.rb Check whether the configuration there matches the configuration written in the development.rb file.It should look like the following in both files:

config.action_mailer.smtp_settings = {
     :address =>"[email protected]",
     :port => 587,
     :domain => "gmail.com",
     :user_name => "[email protected]",
     :password => "********",
     :authentication => 'plain',
     :enable_starttls_auto => true,
     :openssl_verify_mode => 'none' 
     } 

This will most certainly solve your problem.

linux: kill background task

There's a special variable for this in bash:

kill $!

$! expands to the PID of the last process executed in the background.

Fade In Fade Out Android Animation in Java

Another alternative:

No need to define 2 animation for fadeIn and fadeOut. fadeOut is reverse of fadeIn.

So you can do this with Animation.REVERSE like this:

AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
alphaAnimation.setDuration(1000);
alphaAnimation.setRepeatCount(1);
alphaAnimation.setRepeatMode(Animation.REVERSE);
view.findViewById(R.id.imageview_logo).startAnimation(alphaAnimation);

then onAnimationEnd:

alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
    @Override
        public void onAnimationStart(Animation animation) {
            //TODO: Run when animation start
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            //TODO: Run when animation end
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            //TODO: Run when animation repeat
        }
    });

How can I reference a commit in an issue comment on GitHub?

If you are trying to reference a commit in another repo than the issue is in, you can prefix the commit short hash with reponame@.

Suppose your commit is in the repo named dev, and the GitLab issue is in the repo named test. You can leave a comment on the issue and reference the commit by dev@e9c11f0a (where e9c11f0a is the first 8 letters of the sha hash of the commit you want to link to) if that makes sense.

How can I get a resource "Folder" from inside my jar File?

Another solution, you can do it using ResourceLoader like this:

import org.springframework.core.io.Resource;
import org.apache.commons.io.FileUtils;

@Autowire
private ResourceLoader resourceLoader;

...

Resource resource = resourceLoader.getResource("classpath:/path/to/you/dir");
File file = resource.getFile();
Iterator<File> fi = FileUtils.iterateFiles(file, null, true);
while(fi.hasNext()) {
    load(fi.next())
}

Android Starting Service at Boot Time , How to restart service class after device Reboot?

First register a receiver in your manifest.xml file:

    <receiver android:name="com.mileagelog.service.Broadcast_PowerUp" >
        <intent-filter>
            <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
            <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
        </intent-filter>
    </receiver>

and then write a broadcast for this receiver like:

public class Broadcast_PowerUp extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (action.equals(Intent.ACTION_POWER_CONNECTED)) {
        Toast.makeText(context, "Service_PowerUp Started",
                Toast.LENGTH_LONG).show();


    } else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {



        Toast.makeText(context, "Service_PowerUp Stoped", Toast.LENGTH_LONG)
        .show();
    }
  }
}

Size of Matrix OpenCV

If you are using the Python wrappers, then (assuming your matrix name is mat):

  • mat.shape gives you an array of the type- [height, width, channels]

  • mat.size gives you the size of the array

Sample Code:

import cv2
mat = cv2.imread('sample.png')
height, width, channel = mat.shape[:3]
size = mat.size

How to use GNU Make on Windows?

I'm using GNU Make from the GnuWin32 project, see http://gnuwin32.sourceforge.net/ but there haven't been any updates for a while now, so I'm not sure on this project's status.

How to loop through a dataset in powershell?

The PowerShell string evaluation is calling ToString() on the DataSet. In order to evaluate any properties (or method calls), you have to force evaluation by enclosing the expression in $()

for($i=0;$i -lt $ds.Tables[1].Rows.Count;$i++)
{ 
  write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"
}

Additionally foreach allows you to iterate through a collection or array without needing to figure out the length.

Rewritten (and edited for compile) -

foreach ($Row in $ds.Tables[1].Rows)
{ 
  write-host "value is : $($Row[0])"
}

Remove a prefix from a string

Short and sweet:

def remove_prefix(text, prefix):
    return text[text.startswith(prefix) and len(prefix):]

How do I subscribe to all topics of a MQTT broker

Use the wildcard "#" but beware that at some point you will have to somehow understand the data passing through the bus!

VBoxManage: error: Failed to create the host-only adapter

  • CentOS Linux release 7.2.1511 (Core)
  • VirtualBox-5.0

I came across this tread while searching Google for... VBoxManage: error: Failed to create the host-only adapter

I was using VirtualBox-5.0 to test some virtual machines created with Vagrant and setting private networks in my Vagrantfile web.vm.network "private_network", ip: "192.168.10.2"

When evoking the command $ vagrant up I would get the above mentioned error along with /dev/vboxnetcrl does not exist.

It seems that my version of VirtualBox did not have the proper kernel module compiled for my version of Linux and the device, /dev/vboxnetcrl, does not get created.

Since I wanted to test virtual machine and not troubleshoot VirtualBox, my work around (not a solution) was to:

 # yum remove VirtualBox-5.0
 # yum install VirtualBox-4.3 

After that I was able to create the virtual machines with specified host-adapters. And of course, under VirtualBox-4.3, /dev/vboxnetcrl was there.

Now on to testing my VMs. And when I have time, I'll see if I can get it working under VirtualBox 5.0

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

I had problems closing the bootstrap modal dialog, if it was opened with:

$('#myModal').modal('show');

I solved this problem opening the dialog by the following link:

<a href="#myModal" data-toggle="modal">Open my dialog</a>

Do not forget the initialization:

$('#myModal').modal({show: false});

I also used the following attributes for the closing button:

data-dismiss="modal" data-target="#myModal"

How to have conditional elements and keep DRY with Facebook React's JSX?

What about this. Let's define a simple helping If component.

var If = React.createClass({
    render: function() {
        if (this.props.test) {
            return this.props.children;
        }
        else {
            return false;
        }
    }
});

And use it this way:

render: function () {
    return (
        <div id="page">
            <If test={this.state.banner}>
                <div id="banner">{this.state.banner}</div>
            </If>
            <div id="other-content">
                blah blah blah...
            </div>
        </div>
    );
}

UPDATE: As my answer is getting popular, I feel obligated to warn you about the biggest danger related to this solution. As pointed out in another answer, the code inside the <If /> component is executed always regardless of whether the condition is true or false. Therefore the following example will fail in case the banner is null (note the property access on the second line):

<If test={this.state.banner}>
    <div id="banner">{this.state.banner.url}</div>
</If>

You have to be careful when you use it. I suggest reading other answers for alternative (safer) approaches.

UPDATE 2: Looking back, this approach is not only dangerous but also desperately cumbersome. It's a typical example of when a developer (me) tries to transfer patterns and approaches he knows from one area to another but it doesn't really work (in this case other template languages).

If you need a conditional element, do it like this:

render: function () {
    return (
        <div id="page">
            {this.state.banner &&
                <div id="banner">{this.state.banner}</div>}
            <div id="other-content">
                blah blah blah...
            </div>
        </div>
    );
}

If you also need the else branch, just use a ternary operator:

{this.state.banner ?
   <div id="banner">{this.state.banner}</div> :
   <div>There is no banner!</div>
}

It's way shorter, more elegant and safe. I use it all the time. The only disadvantage is that you cannot do else if branching that easily but that is usually not that common.

Anyway, this is possible thanks to how logical operators in JavaScript work. The logical operators even allow little tricks like this:

<h3>{this.state.banner.title || 'Default banner title'}</h3>

DELETE ... FROM ... WHERE ... IN

You can achieve this using exists:

DELETE
  FROM table1
 WHERE exists(
           SELECT 1
             FROM table2
            WHERE table2.stn = table1.stn
              and table2.jaar = year(table1.datum)
       )

How to match, but not capture, part of a regex?

Update: Thanks to Germán Rodríguez Herrera!

In javascript try: /123-(apple(?=-)|banana(?=-)|(?!-))-?456/

Remember that the result is in group 1

Debuggex Demo

SQL Server default character encoding

If you need to know the default collation for a newly created database use:

SELECT SERVERPROPERTY('Collation')

This is the server collation for the SQL Server instance that you are running.

Generate GUID in MySQL for existing Data?

Just a minor addition to make as I ended up with a weird result when trying to modify the UUIDs as they were generated. I found the answer by Rakesh to be the simplest that worked well, except in cases where you want to strip the dashes.

For reference:

UPDATE some_table SET some_field=(SELECT uuid());

This worked perfectly on its own. But when I tried this:

UPDATE some_table SET some_field=(REPLACE((SELECT uuid()), '-', ''));

Then all the resulting values were the same (not subtly different - I quadruple checked with a GROUP BY some_field query). Doesn't matter how I situated the parentheses, the same thing happens.

UPDATE some_table SET some_field=(REPLACE(SELECT uuid(), '-', ''));

It seems when surrounding the subquery to generate a UUID with REPLACE, it only runs the UUID query once, which probably makes perfect sense as an optimization to much smarter developers than I, but it didn't to me.

To resolve this, I just split it into two queries:

UPDATE some_table SET some_field=(SELECT uuid());
UPDATE some_table SET some_field=REPLACE(some_field, '-', '');

Simple solution, obviously, but hopefully this will save someone the time that I just lost.

Auto-increment primary key in SQL tables

Although the following is not way to do it in GUI but you can get autoincrementing simply using the IDENTITY datatype(start, increment):

CREATE TABLE "dbo"."TableName"
(
   id int IDENTITY(1,1) PRIMARY KEY NOT NULL,
   name varchar(20),
);

the insert statement should list all columns except the id column (it will be filled with autoincremented value):

INSERT INTO "dbo"."TableName" (name) VALUES ('alpha');
INSERT INTO "dbo"."TableName" (name) VALUES ('beta');

and the result of

SELECT id, name FROM "dbo"."TableName";

will be

id    name
--------------------------
1     alpha
2     beta

How to properly compare two Integers in Java?

this method compares two Integer with null check, see tests

public static boolean compare(Integer int1, Integer int2) {
    if(int1!=null) {
        return int1.equals(int2);
    } else {
        return int2==null;
    }
    //inline version:
    //return (int1!=null) ? int1.equals(int2) : int2==null;
}

//results:
System.out.println(compare(1,1));           //true
System.out.println(compare(0,1));           //false
System.out.println(compare(1,0));           //false
System.out.println(compare(null,0));        //false
System.out.println(compare(0,null));        //false
System.out.println(compare(null,null));     //true

Best C++ IDE or Editor for Windows

M$ VS2008 is a better IDE for this.

Angular2 dynamic change CSS property

I did this plunker to explore one way to do what you want.

Here I get mystyle from the parent component but you can get it from a service.

import {Component, View} from 'angular2/angular2'

@Component({
  selector: '[my-person]',
  inputs: [
    'name',
    'mystyle: customstyle'
  ],
  host: {
    '[style.backgroundColor]': 'mystyle.backgroundColor'
  }
})
@View({
  template: `My Person Component: {{ name }}`
})
export class Person {}

Git clone particular version of remote repository

The source tree you are requiring is still available within the git repository, however, you will need the SHA1 of the commit that you are interested in. I would assume that you can get the SHA1 from the current clone you have?

If you can get that SHA1, the you can create a branch / reset there to have the identical repository.

Commands as per Rui's answer

Using ORDER BY and GROUP BY together

Here is the simplest solution

select m_id,v_id,max(timestamp) from table group by m_id;

Group by m_id but get max of timestamp for each m_id.

count number of characters in nvarchar column

I had a similar problem recently, and here's what I did:

    SELECT
         columnname as 'Original_Value',
         LEN(LTRIM(columnname)) as 'Orig_Val_Char_Count',
         N'['+columnname+']' as 'UnicodeStr_Value',
         LEN(N'['+columnname+']')-2 as 'True_Char_Count'
    FROM mytable 

The first two columns look at the original value and count the characters (minus leading/trailing spaces).

I needed to compare that with the true count of characters, which is why I used the second LEN function. It sets the column value to a string, forces that string to Unicode, and then counts the characters.

By using the brackets, you ensure that any leading or trailing spaces are also counted as characters; of course, you don't want to count the brackets themselves, so you subtract 2 at the end.

ReportViewer Client Print Control "Unable to load client print control"?

I got this working with out removing any patches. The above patch was not working too. Finally what I did was on the IIS server install the following patch and reset / restart the IIS server. This is not for report manager application. This is for any ASP.NET Web application developed in .net3.5 using VS2008 http://www.microsoft.com/downloads/details.aspx?familyid=6AE0AA19-3E6C-474C-9D57-05B2347456B1&displaylang=en

Stop executing further code in Java

Just do:

public void onClick() {
    if(condition == true) {
        return;
    }
    string.setText("This string should not change if condition = true");
}

It's redundant to write if(condition == true), just write if(condition) (This way, for example, you'll not write = by mistake).

How to specify the current directory as path in VBA?

If the path you want is the one to the workbook running the macro, and that workbook has been saved, then

ThisWorkbook.Path

is what you would use.

Explanation of JSONB introduced by PostgreSQL

  • hstore is more of a "wide column" storage type, it is a flat (non-nested) dictionary of key-value pairs, always stored in a reasonably efficient binary format (a hash table, hence the name).
  • json stores JSON documents as text, performing validation when the documents are stored, and parsing them on output if needed (i.e. accessing individual fields); it should support the entire JSON spec. Since the entire JSON text is stored, its formatting is preserved.
  • jsonb takes shortcuts for performance reasons: JSON data is parsed on input and stored in binary format, key orderings in dictionaries are not maintained, and neither are duplicate keys. Accessing individual elements in the JSONB field is fast as it doesn't require parsing the JSON text all the time. On output, JSON data is reconstructed and initial formatting is lost.

IMO, there is no significant reason for not using jsonb once it is available, if you are working with machine-readable data.

'gulp' is not recognized as an internal or external command

I solved the problem by uninstalling NodeJs and gulp then re-installing both again.

To install gulp globally I executed the following command

npm install -g gulp

Python Pylab scatter plot error bars (the error on each point is unique)

This is almost like the other answer but you don't need a scatter plot at all, you can simply specify a scatter-plot-like format (fmt-parameter) for errorbar:

import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
e = [0.5, 1., 1.5, 2.]
plt.errorbar(x, y, yerr=e, fmt='o')
plt.show()

Result:

enter image description here

A list of the avaiable fmt parameters can be found for example in the plot documentation:

character   description
'-'     solid line style
'--'    dashed line style
'-.'    dash-dot line style
':'     dotted line style
'.'     point marker
','     pixel marker
'o'     circle marker
'v'     triangle_down marker
'^'     triangle_up marker
'<'     triangle_left marker
'>'     triangle_right marker
'1'     tri_down marker
'2'     tri_up marker
'3'     tri_left marker
'4'     tri_right marker
's'     square marker
'p'     pentagon marker
'*'     star marker
'h'     hexagon1 marker
'H'     hexagon2 marker
'+'     plus marker
'x'     x marker
'D'     diamond marker
'd'     thin_diamond marker
'|'     vline marker
'_'     hline marker

Replace values in list using Python

Build a new list with a list comprehension:

new_items = [x if x % 2 else None for x in items]

You can modify the original list in-place if you want, but it doesn't actually save time:

items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for index, item in enumerate(items):
    if not (item % 2):
        items[index] = None

Here are (Python 3.6.3) timings demonstrating the non-timesave:

In [1]: %%timeit
   ...: items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   ...: for index, item in enumerate(items):
   ...:     if not (item % 2):
   ...:         items[index] = None
   ...:
1.06 µs ± 33.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [2]: %%timeit
   ...: items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   ...: new_items = [x if x % 2 else None for x in items]
   ...:
891 ns ± 13.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

And Python 2.7.6 timings:

In [1]: %%timeit
   ...: items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   ...: for index, item in enumerate(items):
   ...:     if not (item % 2):
   ...:         items[index] = None
   ...: 
1000000 loops, best of 3: 1.27 µs per loop
In [2]: %%timeit
   ...: items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   ...: new_items = [x if x % 2 else None for x in items]
   ...: 
1000000 loops, best of 3: 1.14 µs per loop

Argument list too long error for rm, cp, mv commands

You can create a temp folder, move all the files and sub-folders you want to keep into the temp folder then delete the old folder and rename the temp folder to the old folder try this example until you are confident to do it live:

mkdir testit
cd testit
mkdir big_folder tmp_folder
touch big_folder/file1.pdf
touch big_folder/file2.pdf
mv big_folder/file1,pdf tmp_folder/
rm -r big_folder
mv tmp_folder big_folder

the rm -r big_folder will remove all files in the big_folder no matter how many. You just have to be super careful you first have all the files/folders you want to keep, in this case it was file1.pdf

What is the point of the diamond operator (<>) in Java 7?

The point for diamond operator is simply to reduce typing of code when declaring generic types. It doesn't have any effect on runtime whatsoever.

The only difference if you specify in Java 5 and 6,

List<String> list = new ArrayList();

is that you have to specify @SuppressWarnings("unchecked") to the list (otherwise you will get an unchecked cast warning). My understanding is that diamond operator is trying to make development easier. It's got nothing to do on runtime execution of generics at all.

Adding script tag to React/JSX

I tried to edit the accepted answer by @Alex McMillan but it won't let me so heres a separate answer where your able to get the value of the library your loading in. A very important distinction that people asked for and I needed for my implementation with stripe.js.

useScript.js

import { useState, useEffect } from 'react'

export const useScript = (url, name) => {

  const [lib, setLib] = useState({})

  useEffect(() => {
    const script = document.createElement('script')

    script.src = url
    script.async = true
    script.onload = () => setLib({ [name]: window[name] })

    document.body.appendChild(script)

    return () => {
      document.body.removeChild(script)
    }
  }, [url])

  return lib

}

usage looks like

const PaymentCard = (props) => {
  const { Stripe } = useScript('https://js.stripe.com/v2/', 'Stripe')
}

NOTE: Saving the library inside an object because often times the library is a function and React will execute the function when storing in state to check for changes -- which will break libs (like Stripe) that expect to be called with specific args -- so we store that in an object to hide that from React and protect library functions from being called.

MVC pattern on Android

According to the explanation that the Xamarin team explained (on the iOS MVC "I know it seems weird, but wait a second"):

  • The model (data or application logic),
  • The view (user interface), and
  • The controller (code behind).

I can say this:

The model on Android is simply the parcelable object. The view is the XML layout, and the controller is the (activity + its fragment).

*This is just my opinion, not from any resource or a book.

a page can have only one server-side form tag

I think you did like this:

<asp:Content ID="Content2" ContentPlaceHolderID="MasterContent" runat="server">
  <form id="form1" runat="server">

 </form>
</asp:Content>

The form tag isn't needed. because you already have the same tag in the master page.

So you just remove that and it should be working.

How to convert all elements in an array to integer in JavaScript?

_x000D_
_x000D_
var arr = ["1", "2", "3"];_x000D_
arr = arr.map(Number);_x000D_
console.log(arr); // [1, 2, 3]
_x000D_
_x000D_
_x000D_

Getting coordinates of marker in Google Maps API

Also, you can display current position by "drag" listener and write it to visible or hidden field. You may also need to store zoom. Here's copy&paste from working tool:

            function map_init() {
            var lt=48.451778;
            var lg=31.646305;

            var myLatlng = new google.maps.LatLng(lt,lg);
            var mapOptions = {
                center: new google.maps.LatLng(lt,lg),
                zoom: 6,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById('map'),mapOptions);   
            var marker = new google.maps.Marker({
                position:myLatlng,
                map:map,
                draggable:true
            });

            google.maps.event.addListener(
                marker,
                'drag',
                function() {
                    document.getElementById('lat1').innerHTML = marker.position.lat().toFixed(6);
                    document.getElementById('lng1').innerHTML = marker.position.lng().toFixed(6);
                    document.getElementById('zoom').innerHTML = mapObject.getZoom();

                    // Dynamically show it somewhere if needed
                    $(".x").text(marker.position.lat().toFixed(6));
                    $(".y").text(marker.position.lng().toFixed(6));
                    $(".z").text(map.getZoom());

                }
            );                  
            }

Add shadow to custom shape on Android

enter image description here

  <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >

        <solid android:color="@android:color/white" >
        </solid>

        <stroke
            android:width="1dp"
            android:color="@color/LightGrey" >
        </stroke>

        <padding
            android:bottom="5dp"
            android:left="2dp"
            android:right="2dp"
            android:top="5dp" >
        </padding>

        <corners
            android:bottomLeftRadius="20dp"
            android:bottomRightRadius="20dp"
            android:radius="12dp"
            android:topLeftRadius="20dp"
            android:topRightRadius="20dp" />

        <gradient
            android:angle="90"
            android:centerColor="@android:color/white"
            android:centerY="0.2"
            android:endColor="#99e0e0e0"
            android:startColor="@android:color/white"
            android:type="linear" />

    </shape>

Custom li list-style with font-awesome icon

As per the Font Awesome Documentation:

<ul class="fa-ul">
  <li><i class="fa-li fa fa-check"></i>Barbabella</li>
  <li><i class="fa-li fa fa-check"></i>Barbaletta</li>
  <li><i class="fa-li fa fa-check"></i>Barbalala</li>
</ul>

Or, using Jade:

ul.fa-ul
  li
    i.fa-li.fa.fa-check
    | Barbabella
  li
    i.fa-li.fa.fa-check
    | Barbaletta
  li
    i.fa-li.fa.fa-check
    | Barbalala

How to set 777 permission on a particular folder?

Easiest way to set permissions to 777 is to connect to Your server through FTP Application like FileZilla, right click on folder, module_installation, and click Change Permissions - then write 777 or check all permissions.

Javascript event handler with parameters

Given the update to the original question, it seems like there is trouble with the context ("this") while passing event handlers. The basics are explained e.g. here http://www.w3schools.com/js/js_function_invocation.asp

A simple working version of your example could read

var doClick = function(event, additionalParameter){
    // do stuff with event and this being the triggering event and caller
}

element.addEventListener('click', function(event)
{
  var additionalParameter = ...;
  doClick.call(this, event, additionalParameter );
}, false);

See also Javascript call() & apply() vs bind()?

Regular expression for a string that does not start with a sequence

You could use a negative look-ahead assertion:

^(?!tbd_).+

Or a negative look-behind assertion:

(^.{1,3}$|^.{4}(?<!tbd_).*)

Or just plain old character sets and alternations:

^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*

IOException: read failed, socket might closed - Bluetooth on Android 4.3

i also faced with this problem,you could solve it in 2 ways , as mentioned earlier use reflection to create the socket Second one is, client is looking for a server with given UUID and if your server isn't running parallel to client then this happens. Create a server with given client UUID and then listen and accept the client from server side.It will work.

How to convert JSON data into a Python object

If you're using Python 3.5+, you can use jsons to serialize and deserialize to plain old Python objects:

import jsons

response = request.POST

# You'll need your class attributes to match your dict keys, so in your case do:
response['id'] = response.pop('user_id')

# Then you can load that dict into your class:
user = jsons.load(response, FbApiUser)

user.save()

You could also make FbApiUser inherit from jsons.JsonSerializable for more elegance:

user = FbApiUser.from_json(response)

These examples will work if your class consists of Python default types, like strings, integers, lists, datetimes, etc. The jsons lib will require type hints for custom types though.

Android SDK installation doesn't find JDK

I downloaded the .zip archive instead and ran SDK Manager.exe, and it worked like a charm. You had the same issue with the .exe otherwise.

How to check the multiple permission at single request in Android M?

check More than one Permission and Request if Not Granted

 public void checkPermissions(){
    if(ContextCompat.checkSelfPermission(getApplicationContext(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(getApplicationContext(),Manifest.permission.CAMERA)==PackageManager.PERMISSION_GRANTED){
        //Do_SOme_Operation();
    }else{
        requestStoragePermission();
    }
}

public void requestStoragePermission(){
    ActivityCompat.requestPermissions(this
            ,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},1234);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode){
        case 1234:if(grantResults[0]==PackageManager.PERMISSION_GRANTED && grantResults[1]==PackageManager.PERMISSION_GRANTED){
  // Do_SOme_Operation();
        }

        default:super.onRequestPermissionsResult(requestCode,permissions,grantResults);
    }
}

CSS selector for "foo that contains bar"?

No, what you are looking for would be called a parent selector. CSS has none; they have been proposed multiple times but I know of no existing or forthcoming standard including them. You are correct that you would need to use something like jQuery or use additional class annotations to achieve the effect you want.

Here are some similar questions with similar results:

Check for internet connection with Swift

As of iOS 12, NWPathMonitor replaced Reachability. Use this:

import Network


struct Internet {
 
 private static let monitor = NWPathMonitor()
 
 static var active = false
 static var expensive = false
 
 /// Monitors internet connectivity changes. Updates with every change in connectivity.
 /// Updates variables for availability and if it's expensive (cellular).
 static func start() {
  guard monitor.pathUpdateHandler == nil else { return }
  
  monitor.pathUpdateHandler = { update in
   Internet.active = update.status == .satisfied ? true : false
   Internet.expensive = update.isExpensive ? true : false
  }
  
  monitor.start(queue: DispatchQueue(label: "InternetMonitor"))
 }
 
}

In use:

Internet.start()

if Internet.active {
 // do something
}
  
if Internet.expensive {
 // device is using Cellular data or WiFi hotspot
}

How do I start a process from C#?

Just as Matt says, use Process.Start.

You can pass a URL, or a document. They will be started by the registered application.

Example:

Process.Start("Test.Txt");

This will start Notepad.exe with Text.Txt loaded.

When to use %r instead of %s in Python?

Use the %r for debugging, since it displays the "raw" data of the variable, but the others are used for displaying to users.

That's how %r formatting works; it prints it the way you wrote it (or close to it). It's the "raw" format for debugging. Here \n used to display to users doesn't work. %r shows the representation if the raw data of the variable.

months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print "Here are the months: %r" % months

Output:

Here are the months: '\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug'

Check this example from Learn Python the Hard Way.

Linux configure/make, --prefix?

In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198

Trying to fire the onload event on script tag

I faced a similar problem, trying to test if jQuery is already present on a page, and if not force it's load, and then execute a function. I tried with @David Hellsing workaround, but with no chance for my needs. In fact, the onload instruction was immediately evaluated, and then the $ usage inside this function was not yet possible (yes, the huggly "$ is not a function." ^^).

So, I referred to this article : https://developer.mozilla.org/fr/docs/Web/Events/load and attached a event listener to my script object.

var script = document.createElement('script');
script.type = "text/javascript";
script.addEventListener("load", function(event) {
    console.log("script loaded :)");
    onjqloaded();
});
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);

For my needs, it works fine now. Hope this can help others :)

Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?

Differences

  • KEY or INDEX refers to a normal non-unique index. Non-distinct values for the index are allowed, so the index may contain rows with identical values in all columns of the index. These indexes don't enforce any restraints on your data so they are used only for access - for quickly reaching certain ranges of records without scanning all records.

  • UNIQUE refers to an index where all rows of the index must be unique. That is, the same row may not have identical non-NULL values for all columns in this index as another row. As well as being used to quickly reach certain record ranges, UNIQUE indexes can be used to enforce restraints on data, because the database system does not allow the distinct values rule to be broken when inserting or updating data.

    Your database system may allow a UNIQUE index to be applied to columns which allow NULL values, in which case two rows are allowed to be identical if they both contain a NULL value (the rationale here is that NULL is considered not equal to itself). Depending on your application, however, you may find this undesirable: if you wish to prevent this, you should disallow NULL values in the relevant columns.

  • PRIMARY acts exactly like a UNIQUE index, except that it is always named 'PRIMARY', and there may be only one on a table (and there should always be one; though some database systems don't enforce this). A PRIMARY index is intended as a primary means to uniquely identify any row in the table, so unlike UNIQUE it should not be used on any columns which allow NULL values. Your PRIMARY index should be on the smallest number of columns that are sufficient to uniquely identify a row. Often, this is just one column containing a unique auto-incremented number, but if there is anything else that can uniquely identify a row, such as "countrycode" in a list of countries, you can use that instead.

    Some database systems (such as MySQL's InnoDB) will store a table's records on disk in the order in which they appear in the PRIMARY index.

  • FULLTEXT indexes are different from all of the above, and their behaviour differs significantly between database systems. FULLTEXT indexes are only useful for full text searches done with the MATCH() / AGAINST() clause, unlike the above three - which are typically implemented internally using b-trees (allowing for selecting, sorting or ranges starting from left most column) or hash tables (allowing for selection starting from left most column).

    Where the other index types are general-purpose, a FULLTEXT index is specialised, in that it serves a narrow purpose: it's only used for a "full text search" feature.

Similarities

  • All of these indexes may have more than one column in them.

  • With the exception of FULLTEXT, the column order is significant: for the index to be useful in a query, the query must use columns from the index starting from the left - it can't use just the second, third or fourth part of an index, unless it is also using the previous columns in the index to match static values. (For a FULLTEXT index to be useful to a query, the query must use all columns of the index.)