Programs & Examples On #Shiro

Apache Shiro is a Java security framework that performs authentication, authorization, cryptography, and session management.

MySQL Query GROUP BY day / month / year

You can do this simply Mysql DATE_FORMAT() function in GROUP BY. You may want to add an extra column for added clarity in some cases such as where records span several years then same month occurs in different years.Here so many option you can customize this. Please read this befor starting. Hope it should be very helpful for you. Here is sample query for your understanding

    DATE_FORMAT(record_date, '%Y-%m-%d') AS DAY,
    DATE_FORMAT(record_date, '%Y-%m') AS MONTH,
    DATE_FORMAT(record_date, '%Y') AS YEAR

    YEAR = 2009
    DATE_FORMAT(record_date, '%Y-%m-%d ');

How to execute function in SQL Server 2008

It looks like there's something else called Afisho_rankimin in your DB so the function is not being created. Try calling your function something else. E.g.

CREATE FUNCTION dbo.Afisho_rankimin1(@emri_rest int)
       Declare @rankimi int
       Select @rankimi=dbo.RESTORANTET.Rankimi
       Where  dbo.RESTORANTET.ID_Rest=@emri_rest
       RETURN @rankimi

Note that you need to call this only once, not every time you call the function. After that try calling

SELECT dbo.Afisho_rankimin1(5) AS Rankimi 

How to upload and parse a CSV file in php

You can try with this:

function doParseCSVFile($filesArray)
    if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) { 

        $strFilePath = $filesArray['frmUpload']['tmp_name']; 

        $strFileHandle = fopen($strFilePath,"r");
        $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 
        $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 

        do { 
            if ($line_of_text[0]) { 
                $strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
        } while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);

    } else {
        return FALSE;

JUnit tests pass in Eclipse but fail in Maven Surefire

This doesn't exactly apply to your situation, but I had the same thing -- tests that would pass in Eclipse failed when the test goal from Maven was run.

It turned out to be a test earlier in my suite, in a different package. This took me a week to solve!

An earlier test was testing some Logback classes, and created a Logback context from a config file.

The later test was testing a subclass of Spring's SimpleRestTemplate, and somehow, the earlier Logback context was held, with DEBUG on. This caused extra calls to be made in RestTemplate to log HttpStatus, etc.

It's another thing to check if one ever gets into this situation. I fixed my problem by injecting some Mocks into my Logback test class, so that no real Logback contexts were created.

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

Save the execution file on your desktop Make sure you note the name of your file Go to start and type cmd right click on it

select run as administrator press enter

then you something below

C:\Users\your computer name\Desktop>

If you are seeing


make sure you change it using CD

type the name of your file

C:\Users\your computer name\Desktop>the name of the file your copy.exe/ACTION=install /SKIPRULES=PerfMonCounterNotCorruptedCheck

Is it possible to view RabbitMQ message contents directly from the command line?

Here are the commands I use to get the contents of the queue:

RabbitMQ version 3.1.5 on Fedora linux using

Here are my exchanges:

eric@dev ~ $ sudo python rabbitmqadmin list exchanges
| vhost |        name        |  type   | auto_delete | durable | internal |
| /     |                    | direct  | False       | True    | False    |
| /     | kowalski           | topic   | False       | True    | False    |

Here is my queue:

eric@dev ~ $ sudo python rabbitmqadmin list queues
| vhost |   name   | auto_delete | consumers | durable | exclusive_consumer_tag |     idle_since      | memory | messages | messages_ready | messages_unacknowledged |        node         | policy | status  |
| /     | myqueue  | False       | 0         | True    |                        | 2014-09-10 13:32:18 | 13760  | 0        | 0              | 0                       |rabbit@ip-11-1-52-125|        | running |

Cram some items into myqueue:

curl -i -u guest:guest http://localhost:15672/api/exchanges/%2f/kowalski/publish -d '{"properties":{},"routing_key":"abcxyz","payload":"foobar","payload_encoding":"string"}'
HTTP/1.1 200 OK
Server: MochiWeb/1.1 WebMachine/1.10.0 (never breaks eye contact)
Date: Wed, 10 Sep 2014 17:46:59 GMT
content-type: application/json
Content-Length: 15
Cache-Control: no-cache


RabbitMQ see messages in queue:

eric@dev ~ $ sudo python rabbitmqadmin get queue=myqueue requeue=true count=10
| routing_key | exchange | message_count |                        payload        | payload_bytes | payload_encoding | properties | redelivered |
| abcxyz      | kowalski | 10            | foobar                                | 6             | string           |            | True        |
| abcxyz      | kowalski | 9             | {'testdata':'test'}                   | 19            | string           |            | True        |
| abcxyz      | kowalski | 8             | {'mykey':'myvalue'}                   | 19            | string           |            | True        |
| abcxyz      | kowalski | 7             | {'mykey':'myvalue'}                   | 19            | string           |            | True        |

DataTables: Cannot read property style of undefined

In my case, I was updating the server-sided datatable twice and it gives me this error. Hope it helps someone.

CSS Div width percentage and padding without breaking layout

If you want the #header to be the same width as your container, with 10px of padding, you can leave out its width declaration. That will cause it to implicitly take up its entire parent's width (since a div is by default a block level element).

Then, since you haven't defined a width on it, the 10px of padding will be properly applied inside the element, rather than adding to its width:

#container {
    position: relative;
    width: 80%;

#header {
    position: relative;
    height: 50px;
    padding: 10px;

You can see it in action here.

The key when using percentage widths and pixel padding/margins is not to define them on the same element (if you want to accurately control the size). Apply the percentage width to the parent and then the pixel padding/margin to a display: block child with no width set.


Another option for dealing with this is to use the box-sizing CSS rule:

#container { 
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */

    /* Since this element now uses border-box sizing, the 10px of horizontal
       padding will be drawn inside the 80% width */
    width: 80%;
    padding: 0 10px;

Here's a post talking about how box-sizing works.

Python 3.6 install win32api?

Information provided by @Gord

As of September 2019 pywin32 is now available from PyPI and installs the latest version (currently version 224). This is done via the pip command

pip install pywin32

If you wish to get an older version the sourceforge link below would probably have the desired version, if not you can use the command, where xxx is the version you require, e.g. 224

pip install pywin32==xxx

This differs to the pip command below as that one uses pypiwin32 which currently installs an older (namely 223)

Browsing the docs I see no reason for these commands to work for all python3.x versions, I am unsure on python2.7 and below so you would have to try them and if they do not work then the solutions below will work.

Probably now undesirable solutions but certainly still valid as of September 2019

There is no version of specific version ofwin32api. You have to get the pywin32module which currently cannot be installed via pip. It is only available from this link at the moment.

The install does not take long and it pretty much all done for you. Just make sure to get the right version of it depending on your python version :)


Since I posted my answer there are other alternatives to downloading the win32api module.

It is now available to download through pip using this command;

pip install pypiwin32

Also it can be installed from this GitHub repository as provided in comments by @Heath

Setting DEBUG = False causes 500 Error

In my case, reading docs of third party apps properly saved me.

The culprit? django_compressor

I had

{% load compress %}
{% compress css %}
 ... css files linked here ..
{% endcompress %}

DEBUG = True always gave me 500. To fix it, I needed a line in my settings to get it running


Get first 100 characters from string, respecting full words

This function shortens a string by adding "..." at a word boundary whenever possible. The returned string will have a maximum length of $len including "...".

function truncate($str, $len) {
  $tail = max(0, $len-10);
  $trunk = substr($str, 0, $tail);
  $trunk .= strrev(preg_replace('~^..+?[\s,:]\b|^...~', '...', strrev(substr($str, $tail, $len-$tail))));
  return $trunk;

Examples outputs:

  • truncate("Thanks for contributing an answer to Stack Overflow!", 15)
    returns "Thanks for..."
  • truncate("To learn more, see our tips on writing great answers.", 15)
    returns "To learn more..." (comma also truncated)
  • truncate("Pseudopseudohypoparathyroidism", 15)
    returns "Pseudopseudo..."

Append Char To String in C?

You can use strncat()

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

int main(void){
  char hi[6];
  char ch = '!';
  strcpy(hi, "hello");

  strncat(hi, &ch, 1);
  printf("%s\n", hi);

How to copy Outlook mail message into excel using VBA or Macros

New introduction 2

In the previous version of macro "SaveEmailDetails" I used this statement to find Inbox:

Set FolderTgt = CreateObject("Outlook.Application"). _

I have since installed a newer version of Outlook and I have discovered that it does not use the default Inbox. For each of my email accounts, it created a separate store (named for the email address) each with its own Inbox. None of those Inboxes is the default.

This macro, outputs the name of the store holding the default Inbox to the Immediate Window:

Sub DsplUsernameOfDefaultStore()

  Dim NS As Outlook.NameSpace
  Dim DefaultInboxFldr As MAPIFolder

  Set NS = CreateObject("Outlook.Application").GetNamespace("MAPI")
  Set DefaultInboxFldr = NS.GetDefaultFolder(olFolderInbox)

  Debug.Print DefaultInboxFldr.Parent.Name

End Sub

On my installation, this outputs: "Outlook Data File".

I have added an extra statement to macro "SaveEmailDetails" that shows how to access the Inbox of any store.

New introduction 1

A number of people have picked up the macro below, found it useful and have contacted me directly for further advice. Following these contacts I have made a few improvements to the macro so I have posted the revised version below. I have also added a pair of macros which together will return the MAPIFolder object for any folder with the Outlook hierarchy. These are useful if you wish to access other than a default folder.

The original text referenced one question by date which linked to an earlier question. The first question has been deleted so the link has been lost. That link was to Update excel sheet based on outlook mail (closed)

Original text

There are a surprising number of variations of the question: "How do I extract data from Outlook emails to Excel workbooks?" For example, two questions up on [outlook-vba] the same question was asked on 13 August. That question references a variation from December that I attempted to answer.

For the December question, I went overboard with a two part answer. The first part was a series of teaching macros that explored the Outlook folder structure and wrote data to text files or Excel workbooks. The second part discussed how to design the extraction process. For this question Siddarth has provided an excellent, succinct answer and then a follow-up to help with the next stage.

What the questioner of every variation appears unable to understand is that showing us what the data looks like on the screen does not tell us what the text or html body looks like. This answer is an attempt to get past that problem.

The macro below is more complicated than Siddarth’s but a lot simpler that those I included in my December answer. There is more that could be added but I think this is enough to start with.

The macro creates a new Excel workbook and outputs selected properties of every email in Inbox to create this worksheet:

Example of worksheet created by macro

Near the top of the macro there is a comment containing eight hashes (#). The statement below that comment must be changed because it identifies the folder in which the Excel workbook will be created.

All other comments containing hashes suggest amendments to adapt the macro to your requirements.

How are the emails from which data is to be extracted identified? Is it the sender, the subject, a string within the body or all of these? The comments provide some help in eliminating uninteresting emails. If I understand the question correctly, an interesting email will have Subject = "Task Completed".

The comments provide no help in extracting data from interesting emails but the worksheet shows both the text and html versions of the email body if they are present. My idea is that you can see what the macro will see and start designing the extraction process.

This is not shown in the screen image above but the macro outputs two versions on the text body. The first version is unchanged which means tab, carriage return, line feed are obeyed and any non-break spaces look like spaces. In the second version, I have replaced these codes with the strings [TB], [CR], [LF] and [NBSP] so they are visible. If my understanding is correct, I would expect to see the following within the second text body:

Activity[TAB]Count[CR][LF]Open[TAB]35[CR][LF]HCQA[TAB]42[CR][LF]HCQC[TAB]60[CR][LF]HAbst[TAB]50 45 5 2 2 1[CR][LF] and so on

Extracting the values from the original of this string should not be difficult.

I would try amending my macro to output the extracted values in addition to the email’s properties. Only when I have successfully achieved this change would I attempt to write the extracted data to an existing workbook. I would also move processed emails to a different folder. I have shown where these changes must be made but give no further help. I will respond to a supplementary question if you get to the point where you need this information.

Good luck.

Latest version of macro included within the original text

Option Explicit
Public Sub SaveEmailDetails()

  ' This macro creates a new Excel workbook and writes to it details
  ' of every email in the Inbox.

  ' Lines starting with hashes either MUST be changed before running the
  ' macro or suggest changes you might consider appropriate.

  Dim AttachCount As Long
  Dim AttachDtl() As String
  Dim ExcelWkBk As Excel.Workbook
  Dim FileName As String
  Dim FolderTgt As MAPIFolder
  Dim HtmlBody As String
  Dim InterestingItem As Boolean
  Dim InxAttach As Long
  Dim InxItemCrnt As Long
  Dim PathName As String
  Dim ReceivedTime As Date
  Dim RowCrnt As Long
  Dim SenderEmailAddress As String
  Dim SenderName As String
  Dim Subject As String
  Dim TextBody As String
  Dim xlApp As Excel.Application

  ' The Excel workbook will be created in this folder.
  ' ######## Replace "C:\DataArea\SO" with the name of a folder on your disc.
  PathName = "C:\DataArea\SO"

  ' This creates a unique filename.
  ' #### If you use a version of Excel 2003, change the extension to "xls".
  FileName = Format(Now(), "yymmdd hhmmss") & ".xlsx"

  ' Open own copy of Excel
  Set xlApp = Application.CreateObject("Excel.Application")
  With xlApp
    ' .Visible = True         ' This slows your macro but helps during debugging
    .ScreenUpdating = False ' Reduces flash and increases speed
    ' Create a new workbook
    ' #### If updating an existing workbook, replace with an
    ' #### Open workbook statement.
    Set ExcelWkBk = xlApp.Workbooks.Add
    With ExcelWkBk
      ' #### None of this code will be useful if you are adding
      ' #### to an existing workbook.  However, it demonstrates a
      ' #### variety of useful statements.
      .Worksheets("Sheet1").Name = "Inbox"    ' Rename first worksheet
      With .Worksheets("Inbox")
        ' Create header line
        With .Cells(1, "A")
          .Value = "Field"
          .Font.Bold = True
        End With
        With .Cells(1, "B")
          .Value = "Value"
          .Font.Bold = True
        End With
        .Columns("A").ColumnWidth = 18
        .Columns("B").ColumnWidth = 150
      End With
    End With
    RowCrnt = 2
  End With

  ' FolderTgt is the folder I am going to search.  This statement says
  ' I want to seach the Inbox.  The value "olFolderInbox" can be replaced
  ' to allow any of the standard folders to be searched.
  ' See FindSelectedFolder() for a routine that will search for any folder.
  Set FolderTgt = CreateObject("Outlook.Application"). _
  ' #### Use the following the access a non-default Inbox.
  ' #### Change "Xxxx" to name of one of your store you want to access.
  Set FolderTgt = Session.Folders("Xxxx").Folders("Inbox")

  ' This examines the emails in reverse order. I will explain why later.
  For InxItemCrnt = FolderTgt.Items.Count To 1 Step -1
    With FolderTgt.Items.Item(InxItemCrnt)
      ' A folder can contain several types of item: mail items, meeting items,
      ' contacts, etc.  I am only interested in mail items.
      If .Class = olMail Then
        ' Save selected properties to variables
        ReceivedTime = .ReceivedTime
        Subject = .Subject
        SenderName = .SenderName
        SenderEmailAddress = .SenderEmailAddress
        TextBody = .Body
        HtmlBody = .HtmlBody
        AttachCount = .Attachments.Count
        If AttachCount > 0 Then
          ReDim AttachDtl(1 To 7, 1 To AttachCount)
          For InxAttach = 1 To AttachCount
            ' There are four types of attachment:
            '  *   olByValue       1
            '  *   olByReference   4
            '  *   olEmbeddedItem  5
            '  *   olOLE           6
            Select Case .Attachments(InxAttach).Type
              Case olByValue
            AttachDtl(1, InxAttach) = "Val"
              Case olEmbeddeditem
            AttachDtl(1, InxAttach) = "Ebd"
              Case olByReference
            AttachDtl(1, InxAttach) = "Ref"
              Case olOLE
            AttachDtl(1, InxAttach) = "OLE"
              Case Else
            AttachDtl(1, InxAttach) = "Unk"
            End Select
            ' Not all types have all properties.  This code handles
            ' those missing properties of which I am aware.  However,
            ' I have never found an attachment of type Reference or OLE.
            ' Additional code may be required for them.
            Select Case .Attachments(InxAttach).Type
              Case olEmbeddeditem
                AttachDtl(2, InxAttach) = ""
              Case Else
                AttachDtl(2, InxAttach) = .Attachments(InxAttach).PathName
            End Select
            AttachDtl(3, InxAttach) = .Attachments(InxAttach).FileName
            AttachDtl(4, InxAttach) = .Attachments(InxAttach).DisplayName
            AttachDtl(5, InxAttach) = "--"
            ' I suspect Attachment had a parent property in early versions
            ' of Outlook. It is missing from Outlook 2016.
            On Error Resume Next
            AttachDtl(5, InxAttach) = .Attachments(InxAttach).Parent
            On Error GoTo 0
            AttachDtl(6, InxAttach) = .Attachments(InxAttach).Position
            ' Class 5 is attachment.  I have never seen an attachment with
            ' a different class and do not see the purpose of this property.
            ' The code will stop here if a different class is found.
            Debug.Assert .Attachments(InxAttach).Class = 5
            AttachDtl(7, InxAttach) = .Attachments(InxAttach).Class
        End If
        InterestingItem = True
        InterestingItem = False
      End If
    End With
    ' The most used properties of the email have been loaded to variables but
    ' there are many more properies.  Press F2.  Scroll down classes until
    ' you find MailItem.  Look through the members and note the name of
    ' any properties that look useful.  Look them up using VB Help.

    ' #### You need to add code here to eliminate uninteresting items.
    ' #### For example:
    'If SenderEmailAddress <> "[email protected]" Then
    '  InterestingItem = False
    'End If
    'If InStr(Subject, "Accounts payable") = 0 Then
    '  InterestingItem = False
    'End If
    'If AttachCount = 0 Then
    '  InterestingItem = False
    'End If

    ' #### If the item is still thought to be interesting I
    ' #### suggest extracting the required data to variables here.

    ' #### You should consider moving processed emails to another
    ' #### folder.  The emails are being processed in reverse order
    ' #### to allow this removal of an email from the Inbox without
    ' #### effecting the index numbers of unprocessed emails.

    If InterestingItem Then
      With ExcelWkBk
        With .Worksheets("Inbox")
          ' #### This code creates a dividing row and then
          ' #### outputs a property per row.  Again it demonstrates
          ' #### statements that are likely to be useful in the final
          ' #### version
          ' Create dividing row between emails
          .Rows(RowCrnt).RowHeight = 5
          .Range(.Cells(RowCrnt, "A"), .Cells(RowCrnt, "B")) _
                                      .Interior.Color = RGB(0, 255, 0)
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Sender name"
          .Cells(RowCrnt, "B").Value = SenderName
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Sender email address"
          .Cells(RowCrnt, "B").Value = SenderEmailAddress
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Received time"
          With .Cells(RowCrnt, "B")
            .NumberFormat = "@"
            .Value = Format(ReceivedTime, "mmmm d, yyyy h:mm")
          End With
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Subject"
          .Cells(RowCrnt, "B").Value = Subject
          RowCrnt = RowCrnt + 1
          If AttachCount > 0 Then
            .Cells(RowCrnt, "A").Value = "Attachments"
            .Cells(RowCrnt, "B").Value = "Inx|Type|Path name|File name|Display name|Parent|Position|Class"
            RowCrnt = RowCrnt + 1
            For InxAttach = 1 To AttachCount
              .Cells(RowCrnt, "B").Value = InxAttach & "|" & _
                                           AttachDtl(1, InxAttach) & "|" & _
                                           AttachDtl(2, InxAttach) & "|" & _
                                           AttachDtl(3, InxAttach) & "|" & _
                                           AttachDtl(4, InxAttach) & "|" & _
                                           AttachDtl(5, InxAttach) & "|" & _
                                           AttachDtl(6, InxAttach) & "|" & _
                                           AttachDtl(7, InxAttach)
              RowCrnt = RowCrnt + 1
          End If
          If TextBody <> "" Then

            ' ##### This code was in the original version of the macro
            ' ##### but I did not find it as useful as the other version of
            ' ##### the text body.  See below
            ' This outputs the text body with CR, LF and TB obeyed
            'With .Cells(RowCrnt, "A")
            '  .Value = "text body"
            '  .VerticalAlignment = xlTop
            'End With
            'With .Cells(RowCrnt, "B")
            '  ' The maximum size of a cell 32,767
            '  .Value = Mid(TextBody, 1, 32700)
            '  .WrapText = True
            'End With
            'RowCrnt = RowCrnt + 1

            ' This outputs the text body with NBSP, CR, LF and TB
            ' replaced by strings.
            With .Cells(RowCrnt, "A")
              .Value = "text body"
              .VerticalAlignment = xlTop
            End With
            TextBody = Replace(TextBody, Chr(160), "[NBSP]")
            TextBody = Replace(TextBody, vbCr, "[CR]")
            TextBody = Replace(TextBody, vbLf, "[LF]")
            TextBody = Replace(TextBody, vbTab, "[TB]")
            With .Cells(RowCrnt, "B")
              ' The maximum size of a cell 32,767
              .Value = Mid(TextBody, 1, 32700)
              .WrapText = True
            End With
            RowCrnt = RowCrnt + 1
          End If

          If HtmlBody <> "" Then

            ' ##### This code was in the original version of the macro
            ' ##### but I did not find it as useful as the other version of
            ' ##### the html body.  See below
            ' This outputs the html body with CR, LF and TB obeyed
            'With .Cells(RowCrnt, "A")
            '  .Value = "Html body"
            '  .VerticalAlignment = xlTop
            'End With
            'With .Cells(RowCrnt, "B")
            '  .Value = Mid(HtmlBody, 1, 32700)
            '  .WrapText = True
            'End With
            'RowCrnt = RowCrnt + 1

            ' This outputs the html body with NBSP, CR, LF and TB
            ' replaced by strings.
            With .Cells(RowCrnt, "A")
              .Value = "Html body"
              .VerticalAlignment = xlTop
            End With
            HtmlBody = Replace(HtmlBody, Chr(160), "[NBSP]")
            HtmlBody = Replace(HtmlBody, vbCr, "[CR]")
            HtmlBody = Replace(HtmlBody, vbLf, "[LF]")
            HtmlBody = Replace(HtmlBody, vbTab, "[TB]")
            With .Cells(RowCrnt, "B")
              .Value = Mid(HtmlBody, 1, 32700)
              .WrapText = True
            End With
            RowCrnt = RowCrnt + 1

          End If
        End With
      End With
    End If

  With xlApp
    With ExcelWkBk
      ' Write new workbook to disc
      If Right(PathName, 1) <> "\" Then
        PathName = PathName & "\"
      End If
      .SaveAs FileName:=PathName & FileName
    End With
    .Quit   ' Close our copy of Excel
  End With

  Set xlApp = Nothing       ' Clear reference to Excel

End Sub

Macros not included in original post but which some users of above macro have found useful.

Public Sub FindSelectedFolder(ByRef FolderTgt As MAPIFolder, _
                              ByVal NameTgt As String, ByVal NameSep As String)

  ' This routine (and its sub-routine) locate a folder within the hierarchy and
  ' returns it as an object of type MAPIFolder

  ' NameTgt   The name of the required folder in the format:
  '              FolderName1 NameSep FolderName2 [ NameSep FolderName3 ] ...
  '           If NameSep is "|", an example value is "Personal Folders|Inbox"
  '           FolderName1 must be an outer folder name such as
  '           "Personal Folders". The outer folder names are typically the names
  '           of PST files.  FolderName2 must be the name of a folder within
  '           Folder1; in the example "Inbox".  FolderName2 is compulsory.  This
  '           routine cannot return a PST file; only a folder within a PST file.
  '           FolderName3, FolderName4 and so on are optional and allow a folder
  '           at any depth with the hierarchy to be specified.
  ' NameSep   A character or string used to separate the folder names within
  '           NameTgt.
  ' FolderTgt On exit, the required folder.  Set to Nothing if not found.

  ' This routine initialises the search and finds the top level folder.
  ' FindSelectedSubFolder() is used to find the target folder within the
  ' top level folder.

  Dim InxFolderCrnt As Long
  Dim NameChild As String
  Dim NameCrnt As String
  Dim Pos As Long
  Dim TopLvlFolderList As Folders

  Set FolderTgt = Nothing   ' Target folder not found

  Set TopLvlFolderList = _

  ' Split NameTgt into the name of folder at current level
  ' and the name of its children
  Pos = InStr(NameTgt, NameSep)
  If Pos = 0 Then
    ' I need at least a level 2 name
    Exit Sub
  End If
  NameCrnt = Mid(NameTgt, 1, Pos - 1)
  NameChild = Mid(NameTgt, Pos + 1)

  ' Look for current name.  Drop through and return nothing if name not found.
  For InxFolderCrnt = 1 To TopLvlFolderList.Count
    If NameCrnt = TopLvlFolderList(InxFolderCrnt).Name Then
      ' Have found current name. Call FindSelectedSubFolder() to
      ' look for its children
      Call FindSelectedSubFolder(TopLvlFolderList.Item(InxFolderCrnt), _
                                            FolderTgt, NameChild, NameSep)
      Exit For
    End If

End Sub
Public Sub FindSelectedSubFolder(FolderCrnt As MAPIFolder, _
                      ByRef FolderTgt As MAPIFolder, _
                      ByVal NameTgt As String, ByVal NameSep As String)

  ' See FindSelectedFolder() for an introduction to the purpose of this routine.
  ' This routine finds all folders below the top level

  ' FolderCrnt The folder to be seached for the target folder.
  ' NameTgt    The NameTgt passed to FindSelectedFolder will be of the form:
  '               A|B|C|D|E
  '            A is the name of outer folder which represents a PST file.
  '            FindSelectedFolder() removes "A|" from NameTgt and calls this
  '            routine with FolderCrnt set to folder A to search for B.
  '            When this routine finds B, it calls itself with FolderCrnt set to
  '            folder B to search for C.  Calls are nested to whatever depth are
  '            necessary.
  ' NameSep    As for FindSelectedSubFolder
  ' FolderTgt  As for FindSelectedSubFolder

  Dim InxFolderCrnt As Long
  Dim NameChild As String
  Dim NameCrnt As String
  Dim Pos As Long

  ' Split NameTgt into the name of folder at current level
  ' and the name of its children
  Pos = InStr(NameTgt, NameSep)
  If Pos = 0 Then
    NameCrnt = NameTgt
    NameChild = ""
    NameCrnt = Mid(NameTgt, 1, Pos - 1)
    NameChild = Mid(NameTgt, Pos + 1)
  End If

  ' Look for current name.  Drop through and return nothing if name not found.
  For InxFolderCrnt = 1 To FolderCrnt.Folders.Count
    If NameCrnt = FolderCrnt.Folders(InxFolderCrnt).Name Then
      ' Have found current name.
      If NameChild = "" Then
        ' Have found target folder
        Set FolderTgt = FolderCrnt.Folders(InxFolderCrnt)
        'Recurse to look for children
        Call FindSelectedSubFolder(FolderCrnt.Folders(InxFolderCrnt), _
                                            FolderTgt, NameChild, NameSep)
      End If
      Exit For
    End If

  ' If NameCrnt not found, FolderTgt will be returned unchanged.  Since it is
  ' initialised to Nothing at the beginning, that will be the returned value.

End Sub

Read XML file into XmlDocument

Hope you dont mind Xml.Linq and .net3.5+

XElement ele = XElement.Load("text.xml");
String aXmlString = ele.toString(SaveOptions.DisableFormatting);

Depending on what you are interested in, you can probably skip the whole 'string' var part and just use XLinq objects

Usage of MySQL's "IF EXISTS"

You cannot use IF control block OUTSIDE of functions. So that affects both of your queries.

Turn the EXISTS clause into a subquery instead within an IF function

             SELECT *
             FROM gdata_calendars
             WHERE `group` =  ? AND id = ?), 1, 0)

In fact, booleans are returned as 1 or 0

         SELECT *
         FROM gdata_calendars
         WHERE `group` =  ? AND id = ?)

How to pass multiple arguments in processStartInfo?

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = @"/c -sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer"

use /c as a cmd argument to close cmd.exe once its finish processing your commands

Convert MFC CString to integer

A _ttoi function can convert CString to integer, both wide char and ansi char can work. Below is the details:

CString str = _T("123");
int i = _ttoi(str);

Move an item inside a list?

l = list(...)
if item in l:
    l.remove(item) #  checks if the item to be moved is present in the list 

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I was facing the similar type of issue: Code Snippet :

<c:forEach items="${orderList}" var="xx"> ${} <br>

There was a space after orderlist like this : "${orderList} " because of which the xx variable was getting coverted into String and was not able to call

So make sure about space. They play crucial role sometimes. :p

How npm start runs a server on port 8000

You can change the port in the console by running the following on Windows:


For Mac, Linux or Windows WSL use the following:

export PORT=8000

The export sets the environment variable for the current shell and all child processes like npm that might use it.

If you want the environment variable to be set just for the npm process, precede the command with the environment variable like this (on Mac and Linux and Windows WSL):

PORT=8000 npm run start

Inline list initialization in VB.NET

Use this syntax for VB.NET 2005/2008 compatibility:

Dim theVar As New List(Of String)(New String() {"one", "two", "three"})

Although the VB.NET 2010 syntax is prettier.

Hidden features of Python

string-escape and unicode-escape encodings

Lets say you have a string from outer source, that contains \n, \t and so on. How to transform them into new-line or tab? Just decode string using string-escape encoding!

>>> print s
>>> print s.decode('string-escape')
Stack   overflow

Another problem. You have normal string with unicode literals like \u01245. How to make it work? Just decode string using unicode-escape encoding!

>>> s = '\u041f\u0440\u0438\u0432\u0456\u0442, \u0441\u0432\u0456\u0442!'
>>> print s
\u041f\u0440\u0438\u0432\u0456\u0442, \u0441\u0432\u0456\u0442!
>>> print unicode(s)
\u041f\u0440\u0438\u0432\u0456\u0442, \u0441\u0432\u0456\u0442!
>>> print unicode(s, 'unicode-escape')
??????, ????!

Cast IList to List

The other answers all recommend to use AddRange with an IList.

A more elegant solution that avoids the casting is to implement an extension to IList to do the job.


Public Sub AddRange(Of T)(ByRef Exttype As IList(Of T), ElementsToAdd As IEnumerable(Of T))
   For Each ele In ElementsToAdd
End Sub

And in C#:

public void AddRange<T>(this ref IList<T> Exttype, IEnumerable<T> ElementsToAdd)
    foreach (var ele in ElementsToAdd)

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved

My problem was the location of the config file.

In eclipse settings (Windows->preferences->maven->User Settings) the default config file for maven points to C:\users\*yourUser*\.m2\settings.xml. If you unzip maven and install it in a folder of your choice the file will be inside *yourMavenInstallDir*/conf/, thus probably not where eclipse thinks (mine was not). If this is the case maven won't load correctly. You just need to set the "User Settings" path to point to the right file.

How do I replicate a \t tab space in HTML?

I need a code that has the same function as the /t escape character

What function do you mean, creating a tabulator space?

No such thing in HTML, you'll have to use HTML elements for that. (A <table> may make sense for tabular data, or a description list <dl> for definitions.)

Changing MongoDB data store directory

In debian/ubuntu, you'll need to edit the /etc/init.d/mongodb script. Really, this file should be pulling the settings from /etc/mongodb.conf but it doesn't seem to pull the default directory (probably a bug)

This is a bit of a hack, but adding these to the script made it start correctly:




DAEMON_OPTS=${DAEMON_OPTS:-"--unixSocketPrefix=$RUNDIR --config $CONF run"}


DAEMON_OPTS=${DAEMON_OPTS:-"--unixSocketPrefix=$RUNDIR --dbpath $DBDIR --config $CONF run"}

Java current machine name and logged in user?

To get the currently logged in user:


To get the host name of the machine:


To answer the last part of your question, the Java API says that getHostName() will return

the host name for this IP address, or if the operation is not allowed by the security check, the textual representation of the IP address.

Why is HttpContext.Current null?

Clearly HttpContext.Current is not null only if you access it in a thread that handles incoming requests. That's why it works "when i use this code in another class of a page".

It won't work in the scheduling related class because relevant code is not executed on a valid thread, but a background thread, which has no HTTP context associated with.

Overall, don't use Application["Setting"] to store global stuffs, as they are not global as you discovered.

If you need to pass certain information down to business logic layer, pass as arguments to the related methods. Don't let your business logic layer access things like HttpContext or Application["Settings"], as that violates the principles of isolation and decoupling.

Update: Due to the introduction of async/await it is more often that such issues happen, so you might consider the following tip,

In general, you should only call HttpContext.Current in only a few scenarios (within an HTTP module for example). In all other cases, you should use

instead of HttpContext.Current.

phpmailer - The following SMTP Error: Data not accepted

We send email via the Gmail SMTP servers, and we get this exact error from PHPMailer sometimes when we hit our Gmail send limits.

You can check if it's the same thing happening to you by going into Gmail and trying to manually send an email. In our case that displays the more helpful error message about sending limits.

Value Change Listener to JTextField

it was the update version of Codemwnci. his code is quite fine and works great except the error message. To avoid error you must change the condition statement.

  // Listen for changes in the text
textField.getDocument().addDocumentListener(new DocumentListener() {
  public void changedUpdate(DocumentEvent e) {
  public void removeUpdate(DocumentEvent e) {
  public void insertUpdate(DocumentEvent e) {

  public void warn() {
     if (textField.getText().length()>0){
          "Error: Please enter number bigger than 0", "Error Massage",

Swift days between two NSDates

This returns an absolute difference in days between some Date and today:

extension Date {
  func daysFromToday() -> Int {
    return abs(Calendar.current.dateComponents([.day], from: self, to: Date()).day!)

and then use it:

if someDate.daysFromToday() >= 7 {
  // at least a week from today

cast or convert a float to nvarchar?

Check STR. You need something like SELECT STR([Column_Name],10,0) ** This is SQL Server solution, for other servers check their docs.

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

If all you need as a way to parse a dynamic string and load components by their selectors, you may also find the ngx-dynamic-hooks library useful. I initially created this as part of a personal project but didn't see anything like it around, so I polished it up a bit and made it public.

Some tidbids:

  • You can load any components into a dynamic string by their selector (or any other pattern of your choice!)
  • Inputs and outputs can be se just like in a normal template
  • Components can be nested without restrictions
  • You can pass live data from the parent component into the dynamically loaded components (and even use it to bind inputs/outputs)
  • You can control which components can load in each outlet and even which inputs/outputs you can give them
  • The library uses Angular's built-in DOMSanitizer to be safe to use even with potentially unsafe input.

Notably, it does not rely on a runtime-compiler like some of the other responses here. Because of that, you can't use template syntax. On the flipside, this means it works in both JiT and AoT-modes as well as both Ivy and the old template engine, as well as being much more secure to use in general.

See it in action in this Stackblitz.

Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook

Plotly is missing in this list. I've linked the python binding page. It definitively has animated and interative 3D Charts. And since it is Open Source most of that is available offline. Of course it is working with Jupyter

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

From Twitter Bootstrap documentation:

  • small grid (= 768px) = .col-sm-*,
  • medium grid (= 992px) = .col-md-*,
  • large grid (= 1200px) = .col-lg-*.

How to change the href for a hyperlink using jQuery


$("a").attr("href", "")

will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. "anchor") anchor tags:

<a name="MyLinks"></a>
<a href="">The CodeProject</a>

...Then you probably don't want to accidentally add href attributes to them. For safety then, we can specify that our selector will only match <a> tags with an existing href attribute:

$("a[href]") //...

Of course, you'll probably have something more interesting in mind. If you want to match an anchor with a specific existing href, you might use something like this:

$("a[href='']").attr('href', '')

This will find links where the href exactly matches the string A more involved task might be matching, then updating only part of the href:

      this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/, 

The first part selects only links where the href starts with Then, a function is defined that uses a simple regular expression to replace this part of the URL with a new one. Note the flexibility this gives you - any sort of modification to the link could be done here.

JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object

if any problem for JAVA installation version

C:\Where JAVA

will give the location of java it picking up. If you have any path other than your installation, remove those files or rename it (may be as _backup). you will get proper version of java file.

Check for false

If you want it to check explicit for it to not be false (boolean value) you have to use

if(borrar() !== false)

But in JavaScript we usually use falsy and truthy and you could use


but then values 0, '', null, undefined, null and NaN would not generate the alert.

The following values are always falsy:

,0 (zero)
,'' or "" (empty string)

Everything else is truthy. That includes:

'0' (a string containing a single zero)
,'false' (a string containing the text “false”)
,[] (an empty array)
,{} (an empty object)
,function(){} (an “empty” function)


As an extra perk to convert any value to true or false (boolean type), use double exclamation mark:

!![] === true
!!'false' === true
!!false === false
!!undefined === false

What version of Python is on my Mac?

If you have both Python2 and Python3 installed on your Mac, you can use

python --version

to check the version of Python2, and

python3 --version

to check the version of Python3.

However, if only Python3 is installed, then your system might use python instead of python3 for Python3. In this case, you can just use

python --version

to check the version of Python3.

Create a text file for download on-the-fly


    header('Content-type: text/plain');
    header('Content-Disposition: attachment;
            filename="<name for the created file>"');
    assign file content to a PHP Variable $content
    echo $content;

HTML5 Email Validation

The input type=email page of the site notes that an email address is any string which matches the following regular expression:


Use the required attribute and a pattern attribute to require the value to match the regex pattern.


How to create helper file full of functions in react native?

Quick note: You are importing a class, you can't call properties on a class unless they are static properties. Read more about classes here:

There's an easy way to do this, though. If you are making helper functions, you should instead make a file that exports functions like this:

export function HelloChandu() {


export function HelloTester() {


Then import them like so:

import { HelloChandu } from './helpers'


import functions from './helpers' then functions.HelloChandu

how to call a onclick function in <a> tag?

Try onclick function separately it can give you access to execute your function which can be used to open up a new window, for this purpose you first need to create a javascript function there you can define it and in your anchor tag you just need to call your function.


function newwin() {      'lead_data.php?leadid=1','myWin','width=400,height=650')

See how to call it from your anchor tag

<a onclick='newwin()'>Anchor</a>


Visit this jsbin

May be this will help you a lot to understand your problem.

How do you add Boost libraries in CMakeLists.txt?

You can use find_package to search for available boost libraries. It defers searching for Boost to FindBoost.cmake, which is default installed with CMake.

Upon finding Boost, the find_package() call will have filled many variables (check the reference for FindBoost.cmake). Among these are BOOST_INCLUDE_DIRS, Boost_LIBRARIES and Boost_XXX_LIBRARY variabels, with XXX replaced with specific Boost libraries. You can use these to specify include_directories and target_link_libraries.

For example, suppose you would need boost::program_options and boost::regex, you would do something like:

find_package( Boost REQUIRED COMPONENTS program_options regex )
include_directories( ${Boost_INCLUDE_DIRS} )
add_executable( run main.cpp ) # Example application based on main.cpp

# Alternatively you could use ${Boost_LIBRARIES} here.
target_link_libraries( run ${Boost_PROGRAM_OPTIONS_LIBRARY} ${Boost_REGEX_LIBRARY} )

Some general tips:

  • When searching, FindBoost checks the environment variable $ENV{BOOST_ROOT}. You can set this variable before calling find_package if necessary.
  • When you have multiple build-versions of boost (multi-threaded, static, shared, etc.) you can specify you desired configuration before calling find_package. Do this by setting some of the following variables to On: Boost_USE_STATIC_LIBS, Boost_USE_MULTITHREADED, Boost_USE_STATIC_RUNTIME
  • When searching for Boost on Windows, take care with the auto-linking. Read the "NOTE for Visual Studio Users" in the reference.
    • My advice is to disable auto-linking and use cmake's dependency handling: add_definitions( -DBOOST_ALL_NO_LIB )
    • In some cases, you may need to explicitly specify that a dynamic Boost is used: add_definitions( -DBOOST_ALL_DYN_LINK )

How to use an existing database with an Android application

If you are having pre built data base than copy it in asset folder and create an new class as DataBaseHelper which implements SQLiteOpenHelper Than use following code:


import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHelperClass extends SQLiteOpenHelper{
 //The Android's default system path of your application database.
private static String DB_PATH = "/data/data/package_name/databases/";
// Data Base Name.
private static final String DATABASE_NAME = "DBName.sqlite";
// Data Base Version.
private static final int DATABASE_VERSION = 1;
// Table Names of Data Base.
static final String TABLE_Name = "tableName";

public Context context;
static SQLiteDatabase sqliteDataBase;

 * Constructor
 * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
 * @param context
 * Parameters of super() are    1. Context
 *                              2. Data Base Name.
 *                              3. Cursor Factory.
 *                              4. Data Base Version.
public DataBaseHelperClass(Context context) {       
    super(context, DATABASE_NAME, null ,DATABASE_VERSION);
    this.context = context;

 * Creates a empty database on the system and rewrites it with your own database.
 * By calling this method and empty database will be created into the default system path
 * of your application so we are gonna be able to overwrite that database with our database.
 * */
public void createDataBase() throws IOException{
    //check if the database exists
    boolean databaseExist = checkDataBase();

        // Do Nothing.
    }// end if else dbExist
} // end createDataBase().

 * Check if the database already exist to avoid re-copying the file each time you open the application.
 * @return true if it exists, false if it doesn't
public boolean checkDataBase(){
    File databaseFile = new File(DB_PATH + DATABASE_NAME);
    return databaseFile.exists();        

 * Copies your database from your local assets-folder to the just created empty database in the
 * system folder, from where it can be accessed and handled.
 * This is done by transferring byte stream.
 * */
private void copyDataBase() throws IOException{ 
    //Open your local db as the input stream
    InputStream myInput = context.getAssets().open(DATABASE_NAME); 
    // Path to the just created empty db
    String outFileName = DB_PATH + DATABASE_NAME; 
    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName); 
    //transfer bytes from the input file to the output file
    byte[] buffer = new byte[1024];
    int length;
    while ((length =>0){
        myOutput.write(buffer, 0, length);

    //Close the streams

 * This method opens the data base connection.
 * First it create the path up till data base of the device.
 * Then create connection with data base.
public void openDataBase() throws SQLException{      
    //Open the database
    String myPath = DB_PATH + DATABASE_NAME;
    sqliteDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);  

 * This Method is used to close the data base connection.
public synchronized void close() { 
    if(sqliteDataBase != null)

* Apply your methods and class to fetch data using raw or queries on data base using 
* following demo example code as:
public String getUserNameFromDB(){
    String query = "select User_First_Name From "+TABLE_USER_DETAILS;
    Cursor cursor = sqliteDataBase.rawQuery(query, null);
    String userName = null;
                userName = cursor.getString(0);
            }while (cursor.moveToNext());
    return userName;

public void onCreate(SQLiteDatabase db) {
    // No need to write the create table query.
    // As we are using Pre built data base.
    // Which is ReadOnly.

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // No need to write the update table query.
    // As we are using Pre built data base.
    // Which is ReadOnly.
    // We should not update it as requirements of application.

Hope this will help you...

What is the proper #include for the function 'sleep()'?

sleep is a non-standard function.

  • On UNIX, you shall include <unistd.h>.
  • On MS-Windows, Sleep is rather from <windows.h>.

In every case, check the documentation.

Resizing an image in an HTML5 canvas

Fast and simple Javascript image resizer:

const blitz = Blitz.create()

/* Promise */
    source: DOM Image/DOM Canvas/jQuery/DataURL/File,
    width: 400,
    height: 600
}).then(output => {
    // handle output
})catch(error => {
    // handle error

/* Await */
let resized = await blizt({...})

/* Old school callback */
const blitz = Blitz.create('callback')
blitz({...}, function(output) {
    // run your callback.


This is really after many rounds of research, reading and trying.

The resizer algorithm uses @ViliusL's Hermite script (Hermite resizer is really the fastest and gives reasonably good output). Extended with features you need.

Forks 1 worker to do the resizing so that it doesn't freeze your browser when resizing, unlike all other JS resizers out there.

adding css class to multiple elements

try this:

.button input, .button a {
//css here

That will apply the style to all a tags nested inside of <p class="button"></p>

How do I group Windows Form radio buttons?

You should place all the radio buttons of the group inside the same container such as a GroupBox or Panel.

Convert javascript object or array to json for ajax data

You can use JSON.stringify(object) with an object and I just wrote a function that'll recursively convert an array to an object, like this JSON.stringify(convArrToObj(array)), which is the following code (more detail can be found on this answer):

// Convert array to object
var convArrToObj = function(array){
    var thisEleObj = new Object();
    if(typeof array == "object"){
        for(var i in array){
            var thisEle = convArrToObj(array[i]);
            thisEleObj[i] = thisEle;
    }else {
        thisEleObj = array;
    return thisEleObj;

To make it more generic, you can override the JSON.stringify function and you won't have to worry about it again, to do this, just paste this at the top of your page:

// Modify JSON.stringify to allow recursive and single-level arrays
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
        }else {
            thisEleObj = array;
        return thisEleObj;
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        return oldJSONStringify(convArrToObj(input));

And now JSON.stringify will accept arrays or objects! (link to jsFiddle with example)


Here's another version that's a tad bit more efficient, although it may or may not be less reliable (not sure -- it depends on if JSON.stringify(array) always returns [], which I don't see much reason why it wouldn't, so this function should be better as it does a little less work when you use JSON.stringify with an object):

    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
        }else {
            thisEleObj = array;
        return thisEleObj;
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        if(oldJSONStringify(input) == '[]')
            return oldJSONStringify(convArrToObj(input));
            return oldJSONStringify(input);

jsFiddle with example here

js Performance test here, via jsPerf

Python None comparison: should I use "is" or ==?

is is generally preferred when comparing arbitrary objects to singletons like None because it is faster and more predictable. is always compares by object identity, whereas what == will do depends on the exact type of the operands and even on their ordering.

This recommendation is supported by PEP 8, which explicitly states that "comparisons to singletons like None should always be done with is or is not, never the equality operators."

Search a whole table in mySQL for a string

Try something like this:

SELECT * FROM clients WHERE CONCAT(field1, '', field2, '', fieldn) LIKE "%Mary%"

You may want to see SQL docs for additional information on string operators and regular expressions.

Edit: There may be some issues with NULL fields, so just in case you may want to use IFNULL(field_i, '') instead of just field_i

Case sensitivity: You can use case insensitive collation or something like this:


Just search all field: I believe there is no way to make an SQL-query that will search through all field without explicitly declaring field to search in. The reason is there is a theory of relational databases and strict rules for manipulating relational data (something like relational algebra or codd algebra; these are what SQL is from), and theory doesn't allow things such as "just search all fields". Of course actual behaviour depends on vendor's concrete realisation. But in common case it is not possible. To make sure, check SELECT operator syntax (WHERE section, to be precise).

SQL query to find third highest salary in company

SELECT Max(salary) 
FROM   employee 
WHERE  salary < (SELECT Max(salary) 
                 FROM   employee 
                 WHERE  salary NOT IN(SELECT Max(salary) 
                                      FROM   employee)) 

hope this helped you

Enable binary mode while restoring a Database from an SQL dump

I had the same problem, but found out that the dump file was actually a MSSQL Server backup, not MySQL.

Sometimes legacy backup files play tricks on us. Check your dump file.

On terminal window:

~$ cat mybackup.dmp 

The result was:

TAPE??G?"5,^}???Microsoft SQL ServerSPAD^LSFMB8..... etc...

To stop processing the cat command:


How can I rename a field for all documents in MongoDB?

I am using ,Mongo 3.4.0

The $rename operator updates the name of a field and has the following form:

{$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } }

for e.g

db.getCollection('user').update( { _id: 1 }, { $rename: { 'fname': 'FirstName', 'lname': 'LastName' } } )

The new field name must differ from the existing field name. To specify a in an embedded document, use dot notation.

This operation renames the field nmae to name for all documents in the collection:

db.getCollection('user').updateMany( {}, { $rename: { "add": "Address" } } )

db.getCollection('user').update({}, {$rename:{"name.first":"name.FirstName"}}, false, true);

In the method above false, true are: { upsert:false, multi:true }.To update all your records, You need the multi:true.

Rename a Field in an Embedded Document

db.getCollection('user').update( { _id: 1 }, { $rename: { "name.first": "name.fname" } } )

use link :

How to add a downloaded .box file to Vagrant?

F:\PuppetLab\src\boxes>vagrant box add precise32 file:///F:/PuppetLab/src/boxes/
==> box: Adding box 'precise32' (v0) for provider:
    box: Downloading: file:///F:/PuppetLab/src/boxes/
    box: Progress: 100% (Rate: 1200k/s, Estimated time remaining: --:--:--)
==> box: Successfully added box 'precise32' (v0) for 'virtualbox'!

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i -q:v 0 output.mp4

Edit a commit message in SourceTree Windows (already pushed to remote)

Here are the steps to edit the commit message of a previous commit (which is not the most recent commit) using SourceTree for Windows version

Step 1

Select the commit immediately before the commit that you want to edit. For example, if I want to edit the commit with message "FOOBAR!" then I need to select the commit that comes right before it:

Selecting commit before the one that I want to edit.

Step 2

Right-click on the selected commit and click Rebase children...interactively:

Selecting "Rebase children interactively".

Step 3

Select the commit that you want to edit, then click Edit Message at the bottom. In this case, I'm selecting the commit with the message "FOOBAR!":

Select the commit that you want to edit.

Step 4

Edit the commit message, and then click OK. In my example, I've added "SHAZBOT! SKADOOSH!"

Edit the commit message

Step 5

When you return to interactive rebase window, click on OK to finish the rebase:

Click OK to finish.

Step 6

At this point, you'll need to force-push your new changes since you've rebased commits that you've already pushed. However, the current version of SourceTree for Windows does not allow you to force-push through the GUI, so you'll need to use Git from the command line anyways in order to do that.

Click Terminal from the GUI to open up a terminal.

Click Terminal

Step 7

From the terminal force-push with the following command,

git push origin <branch> -f

where <branch> is the name of the branch that you want to push, and -f means to force the push. The force push will overwrite your commits on your remote repo, but that's OK in your case since you said that you're not sharing your repo with other people.

That's it! You're done!

How do I fix a "Expected Primary-expression before ')' token" error?

showInventory(player); is passing a type as parameter. That's illegal, you need to pass an object.

For example, something like:

player p;

I'm guessing you have something like this:

int main()
   player player;

which is awful. First, don't name the object the same as your type. Second, in order for the object to be visible inside the function, you'll need to pass it as parameter:

int main()
   player p;


std::string toDo(player& p) 

Change input value onclick button - pure javascript or jQuery

This will work fine for you

   <!DOCTYPE html>
    <script src=""></script>

    function myfun(){

        var data=$("#select").val();
    <p>id <input type="text" name="user" id="disp"></p>
    <select id="select" onclick="myfun()">
    <option name="1"value="one">1</option>
    <option name="2"value="two">2</option>
    <option name="3"value="three"></option>

Best practices for adding .gitignore file for Python projects?

Here are some other files that may be left behind by setuptools:


How to expand 'select' option width after the user wants to select an option

Place it in a div and give it an id

<div id=myForm>

then create a really really simple css to go with it.

#myForm select { 
width:200px; }

#myForm select:focus {
width:auto; }

That's all you need.

What is the right way to check for a null string in Objective-C?

Whats with all these "works for me answers" ? We're all coding in the same language and the rules are

  1. Ensure the reference isn't nil
  2. Check and make sure the length of the string isn't 0

That is what will work for all. If a given solution only "works for you", its only because your application flow won't allow for a scenario where the reference may be null or the string length to be 0. The proper way to do this is the method that will handle what you want in all cases.

Sort Java Collection

Use a Comparator:

List<CustomObject> list = new ArrayList<CustomObject>();
Comparator<CustomObject> comparator = new Comparator<CustomObject>() {
    public int compare(CustomObject left, CustomObject right) {
        return left.getId() - right.getId(); // use your logic

Collections.sort(list, comparator); // use the comparator as much as u want

Additionally, if CustomObjectimplements Comparable, then just use Collections.sort(list)

With JDK 8 the syntax is much simpler.

List<CustomObject> list = getCustomObjectList();
Collections.sort(list, (left, right) -> left.getId() - right.getId());

Much simplier

List<CustomObject> list = getCustomObjectList();
list.sort((left, right) -> left.getId() - right.getId());


List<CustomObject> list = getCustomObjectList();

Obviously the initial code can be used for JDK 8 too.

Starting Docker as Daemon on Ubuntu

This problem really cost me some hours.

My system is Ubuntu 14.04, I installed docker by sudo apt-get install docker, and typed some other commands that caused the problem.

  1. I google "unknown job:", answers did not take effect.

  2. I looked for reasons of "unknown job" in /etc/init.d/, found no proper answer .

  3. I looked for way to debug script in /etc/init.d/, found no proper answer.

  4. Then, I did a clean:

    1. sudo apt-get remove
    2. rm every suspicious file by find / -name "*docker*", such as /etc/init/, /etc/init.d/ .
  5. Follow the latest official document:, there is a lot of outdated documentation which can be misleading.

Finally, it fixed the problem.

Note: If you are in China, because of the GFW, you may need to set the https_proxy to install docker from .

Where can I get a virtual machine online? has a free VM running Ubuntu. The specs are pretty good, 1 gig memory for example. They have a terminal online you can access through their website, or use SSH. The VM will go to sleep approximately 20 minutes after you log out. The reason is to discourage users from running live production code on the VM. The VM resides behind a proxy. Running web servers that only speak HTTP (port 80) should work just fine, but I think you'll get into a lot of trouble whenever you want to work directly with other ports. Many mind-like alternatives offer similar setups. Good luck!

I had the same idea as you but given all restrictions everybody keep imposing everywhere I feel that I must go out and pay for a VPS.

scroll up and down a div on button click using jquery

scrollBottom is not a method in jQuery.


Try this:

   $("#upClick").on("click" ,function(){
          scrollTop:  scrolled

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

Maybe It is OpenJPA's bug, When rollback it reset the @Version field, but the pcVersionInit keep true. I have a AbstraceEntity which declared the @Version field. I can workaround it by reset the pcVersionInit field. But It is not a good idea. I think it not work when have cascade persist entity.

    private static Field PC_VERSION_INIT = null;
    static {
        try {
            PC_VERSION_INIT = AbstractEntity.class.getDeclaredField("pcVersionInit");
        } catch (NoSuchFieldException | SecurityException e) {

    public T call(final EntityManager em) {
                if (PC_VERSION_INIT != null && isDetached(entity)) {
                    try {
                        PC_VERSION_INIT.set(entity, false);
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                return entity;

             * @param entity
             * @param detached
             * @return
            private boolean isDetached(final Object entity) {
                if (entity instanceof PersistenceCapable) {
                    PersistenceCapable pc = (PersistenceCapable) entity;
                    if (pc.pcIsDetached() == Boolean.TRUE) {
                        return true;
                return false;

Split string into array of character strings

To sum up the other answers...

This works on all Java versions:


This only works on Java 8 and up:


Selected tab's color in Bottom Navigation View

Instead of creating selector, Best way to create a style.

<style name="AppTheme.BottomBar">
    <item name="colorPrimary">@color/colorAccent</item> 

and to change the text size, selected or non selected.

<dimen name="design_bottom_navigation_text_size" tools:override="true">11sp</dimen>
<dimen name="design_bottom_navigation_active_text_size" tools:override="true">12sp</dimen>

Enjoy Android!

How do I programmatically change file permissions?

There is an example class on Oracle Docs which works very much similar to the UNIX chmod. It works with java se 7+ though.

Print in one line dynamically

A comma at the end of the print statement omits the new line.

for i in xrange(1,100):
  print i,

but this does not overwrite.

Using Mockito with multiple calls to the same method with the same arguments

You can even chain doReturn() method invocations like this


cute isn't it :)

error: This is probably not a problem with npm. There is likely additional logging output above

I already have the same problem . and I fix it using npm update & npm cache clean --force

flutter run: No connected devices

Setting the Environment System variable:

Variable Value ANDROID_HOME D:\Android_Sdk\Sdk (your path)

Writing a dictionary to a csv file with one line for every 'key: value'

Just to give an option, writing a dictionary to csv file could also be done with the pandas package. With the given example it could be something like this:

mydict = {'key1': 'a', 'key2': 'b', 'key3': 'c'}

import pandas as pd

(pd.DataFrame.from_dict(data=mydict, orient='index')
   .to_csv('dict_file.csv', header=False))

The main thing to take into account is to set the 'orient' parameter to 'index' inside the from_dict method. This lets you choose if you want to write each dictionary key in a new row.

Additionaly, inside the to_csv method the header parameter is set to False just to have only the dictionary elements without annoying rows. You can always set column and index names inside the to_csv method.

Your output would look like this:


If instead you want the keys to be the column's names, just use the default 'orient' parameter that is 'columns', as you could check in the documentation links.

Git push rejected after feature branch rebase

Fetch new changes of master and rebase feature branch on top of latest master

git checkout master
git pull
git checkout feature
git pull --rebase origin master
git push origin feature

How to flush output after each `echo` call?

Anti-virus software may also be interfering with output flushing. In my case, Kaspersky Anti-Virus 2013 was holding data chunks before sending it to the browser, even though I was using an accepted solution.

MultipartException: Current request is not a multipart request

When you are using Postman for multipart request then don't specify a custom Content-Type in Header. So your Header tab in Postman should be empty. Postman will determine form-data boundary. In Body tab of Postman you should select form-data and select file type. You can find related discussion at

Single TextView with multiple colored text

Use SpannableStringBuilder

SpannableStringBuilder builder = new SpannableStringBuilder();

SpannableString str1= new SpannableString("Text1");
str1.setSpan(new ForegroundColorSpan(Color.RED), 0, str1.length(), 0);

SpannableString str2= new SpannableString(appMode.toString());
str2.setSpan(new ForegroundColorSpan(Color.GREEN), 0, str2.length(), 0);

TextView tv = (TextView) view.findViewById(;
tv.setText( builder, TextView.BufferType.SPANNABLE);

How to add a new row to datagridview programmatically

This is how I add a row if the dgrview is empty: (myDataGridView has two columns in my example)

DataGridViewRow row = new DataGridViewRow();

row.Cells[0].Value = "some value";
row.Cells[1].Value = "next columns value";


According to docs: "CreateCells() clears the existing cells and sets their template according to the supplied DataGridView template".

How can I determine if a .NET assembly was built for x86 or x64?

You can use the CorFlags CLI tool (for instance, C:\Program Files\Microsoft SDKs\Windows\v7.0\Bin\CorFlags.exe) to determine the status of an assembly, based on its output and opening an assembly as a binary asset you should be able to determine where you need to seek to determine if the 32BIT flag is set to 1 (x86) or 0 (Any CPU or x64, depending on PE):

Option    | PE    | 32BIT
x86       | PE32  | 1
Any CPU   | PE32  | 0
x64       | PE32+ | 0

The blog post x64 Development with .NET has some information about corflags.

Even better, you can use Module.GetPEKind to determine whether an assembly is PortableExecutableKinds value PE32Plus (64-bit), Required32Bit (32-bit and WOW), or ILOnly (any CPU) along with other attributes.

PHP MySQL Google Chart JSON - Complete Example

Some might encounter this error (I got it while implementing PHP-MySQLi-JSON-Google Chart Example):

You called the draw() method with the wrong type of data rather than a DataTable or DataView.

The solution would be: replace jsapi and just use loader.js with:

google.charts.load('current', {packages: ['corechart']}) and 

-- according to the release notes --> The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.

Git Server Like GitHub?

If you just want your repository in a central place, this is quite easy with distributed version control like Git:
You can just put your central repository in some shared folder on a central machine and everybody can clone it from there.

If you want a "real" website on your local server, I know of the Git hosting website
It seems to have less features than GitHub, but unlike GitHub, you can get the source code and host it on your own local server.

Disclaimer: I only read about, I never tried it myself!

Android SQLite Example

Sqlite helper class helps us to manage database creation and version management. SQLiteOpenHelper takes care of all database management activities. To use it,
1.Override onCreate(), onUpgrade() methods of SQLiteOpenHelper. Optionally override onOpen() method.
2.Use this subclass to create either a readable or writable database and use the SQLiteDatabase's four API methods insert(), execSQL(), update(), delete() to create, read, update and delete rows of your table.

Example to create a MyEmployees table and to select and insert records:

public class MyDatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "DBName";

    private static final int DATABASE_VERSION = 2;

    // Database creation sql statement
    private static final String DATABASE_CREATE = "create table MyEmployees
                                 ( _id integer primary key,name text not null);";

    public MyDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    // Method is called during creation of the database
    public void onCreate(SQLiteDatabase database) {

    // Method is called during an upgrade of the database,
    public void onUpgrade(SQLiteDatabase database,int oldVersion,int newVersion){
                         "Upgrading database from version " + oldVersion + " to "
                         + newVersion + ", which will destroy all old data");
        database.execSQL("DROP TABLE IF EXISTS MyEmployees");

Now you can use this class as below,

public class MyDB{  

    private MyDatabaseHelper dbHelper;  

    private SQLiteDatabase database;  

    public final static String EMP_TABLE="MyEmployees"; // name of table 

    public final static String EMP_ID="_id"; // id value for employee
    public final static String EMP_NAME="name";  // name of employee

     * @param context 
    public MyDB(Context context){  
        dbHelper = new MyDatabaseHelper(context);  
        database = dbHelper.getWritableDatabase();  

    public long createRecords(String id, String name){  
        ContentValues values = new ContentValues();  
        values.put(EMP_ID, id);  
        values.put(EMP_NAME, name);  
        return database.insert(EMP_TABLE, null, values);  

    public Cursor selectRecords() {
        String[] cols = new String[] {EMP_ID, EMP_NAME};  
        Cursor mCursor = database.query(true, EMP_TABLE,cols,null  
            , null, null, null, null, null);  
        if (mCursor != null) {  
        return mCursor; // iterate to get each value.

Now you can use MyDB class in you activity to have all the database operations. The create records will help you to insert the values similarly you can have your own functions for update and delete.

Apply CSS styles to an element depending on its child elements

In my case, I had to change the cell padding of an element that contained an input checkbox for a table that's being dynamically rendered with DataTables:

<td class="dt-center">
    <input class="a" name="constCheck" type="checkbox" checked="">

After implementing the following line code within the initComplete function I was able to produce the correct padding, which fixed the rows from being displayed with an abnormally large height

 $('tbody td:has(input.a)').css('padding', '0px');

Now, you can see that the correct styles are being applied to the parent element:

<td class=" dt-center" style="padding: 0px;">
    <input class="a" name="constCheck" type="checkbox" checked="">

Essentially, this answer is an extension of @KP's answer, but the more collaboration of implementing this the better. In summation, I hope this helps someone else because it works! Lastly, thank you so much @KP for leading me in the right direction!

fill an array in C#

Write yourself an extension method

public static class ArrayExtensions {
    public static void Fill<T>(this T[] originalArray, T with) {
        for(int i = 0; i < originalArray.Length; i++){
            originalArray[i] = with;

and use it like

int foo[] = new int[]{0,0,0,0,0};

will fill all the elements with 13

Tools for making latex tables in R

Another R package for aggregating multiple regression models into LaTeX tables is texreg.

How to resolve the C:\fakepath?

Hy there , in my case i am using development environment, so i was want to upload those data in asynchronus ajax request , in [webMethod] you can not catch the file uploader since it is not static element , so i had to make a turnover for such solution by fixing the path , than convert the wanted image into bytes to save it in DB .

Here is my javascript function , hope it helps you:

function FixPath(Path)
             var HiddenPath = Path.toString();

             if (HiddenPath.indexOf("FakePath") > 1)
                 var UnwantedLength = HiddenPath.indexOf("FakePath") + 7;
                 MainStringLength = HiddenPath.length - UnwantedLength;
                 var thisArray =[];
                 var i = 0;
                 var FinalString= "";
                 while (i < MainStringLength)
                     thisArray[i] = HiddenPath[UnwantedLength + i + 1];
                 var j = 0;
                 while (j < MainStringLength-1)
                     if (thisArray[j] != ",")
                         FinalString += thisArray[j];
                 FinalString = "~" + FinalString;
                 return FinalString;
                 return HiddenPath;

here only for testing :

 $(document).ready(function () {
// this will give you : ~/EnsaLmadiLiYghiz

In VBA get rid of the case sensitivity when comparing words?

You can convert both the values to lower case and compare.

Here is an example:

If LCase(Range("J6").Value) = LCase("Tawi") Then
   Range("J6").Value = "Tawi-Tawi"
End If

How to create a custom attribute in C#

While the code to create a custom Attribute is fairly simple, it's very important that you understand what attributes are:

Attributes are metadata compiled into your program. Attributes themselves do not add any functionality to a class, property or module - just data. However, using reflection, one can leverage those attributes in order to create functionality.

So, for instance, let's look at the Validation Application Block, from Microsoft's Enterprise Library. If you look at a code example, you'll see:

    /// <summary>
    /// blah blah code.
    /// </summary>
    [StringLengthValidator(8, RangeBoundaryType.Inclusive, 8, RangeBoundaryType.Inclusive, MessageTemplate = "\"{1}\" must always have \"{4}\" characters.")]
    public string Code { get; set; }

From the snippet above, one might guess that the code will always be validated, whenever changed, accordingly to the rules of the Validator (in the example, have at least 8 characters and at most 8 characters). But the truth is that the Attribute does nothing; as mentioned previously, it only adds metadata to the property.

However, the Enterprise Library has a Validation.Validate method that will look into your object, and for each property, it'll check if the contents violate the rule informed by the attribute.

So, that's how you should think about attributes -- a way to add data to your code that might be later used by other methods/classes/etc.

Authentication plugin 'caching_sha2_password' is not supported

pip install -U mysql-connector-python this worked for me, if you already have installed mysql-connector-python and then follow this answer

Setting mime type for excel document

For .xls use the following content-type


For Excel 2007 version and above .xlsx files format


The default XML namespace of the project must be the MSBuild XML namespace

I was getting the same messages while I was running just msbuild from powershell.

dotnet msbuild "./project.csproj" worked for me.

Can anyone explain python's relative imports?

Checking it out in python3:

python -V
Python 3.6.5


+-- sub

import sub.relative

print('Hello from')

- sub/
from .. import parent

If we run it like this(just to make sure PYTHONPATH is empty):

PYTHONPATH='' python3


Traceback (most recent call last):
  File "", line 1, in <module>
    import sub.relative
  File "/python-import-examples/so-example-v1/sub/", line 1, in <module>
    from .. import parent
ValueError: attempted relative import beyond top-level package

If we change import in sub/

- sub/
import parent

If we run it like this:

PYTHONPATH='' python3


Hello from


+-- sub

print('Hello from')

- sub/
print('Hello from')

- sub/
import relative
from .. import parent

Run it like:

PYTHONPATH='' python3 sub/


Hello from
Traceback (most recent call last):
  File "sub/", line 2, in <module>
    from .. import parent
ValueError: attempted relative import beyond top-level package

If we change import in sub/

- sub/
import relative
import parent

Run it like:

PYTHONPATH='' python3 sub/


Hello from
Traceback (most recent call last):
  File "sub/", line 3, in <module>
    import parent
ModuleNotFoundError: No module named 'parent'

Run it like:

PYTHONPATH='.' python3 sub/


Hello from
Hello from

Also it's better to use import from root folder, i.e.:

- sub/
import sub.relative
import parent

Run it like:

PYTHONPATH='.' python3 sub/


Hello from
Hello from

How can I calculate the difference between two ArrayLists?

EDIT: Original question did not specify language. My answer is in C#.

You should instead use HashSet for this purpose. If you must use ArrayList, you could use the following extension methods:

var a = arrayListA.Cast<DateTime>();
var b = arrayListB.Cast<DateTime>();    
var c = b.Except(a);

var arrayListC = new ArrayList(c.ToArray());

using HashSet...

var a = new HashSet<DateTime>(); // ...and fill it
var b = new HashSet<DateTime>(); // ...and fill it
b.ExceptWith(a); // removes from b items that are in a

Bootstrap Modal Backdrop Remaining

An issue I was having (may help someone) was simply that I was using a partial to load the Modal.

<li data-toggle="modal" data-target="#priceInfoModal">
<label>Listing Price</label>
<i class="fa fa-money"></i>

I had placed the partial call inside the same list item So data-target="#priceInfoModal" and div id="priceInfoModal" were in the same container causing me to not be able to close my modal

Shell Scripting: Using a variable to define a path

To add to the above correct answer :- For my case in shell, this code worked (working on sqoop)

--options-file  $ROOT_PATH/query.txt

HTML5 Canvas background image

Why don't you style it out:

<canvas id="canvas" width="800" height="600" style="background: url('./images/image.jpg')">
  Your browser does not support the canvas element.

How can I get a file's size in C++?

If you're on Linux, seriously consider just using the g_file_get_contents function from glib. It handles all the code for loading a file, allocating memory, and handling errors.

Reading rows from a CSV file in Python

The csv module handles csv files by row. If you want to handle it by column, pandas is a good solution.

Besides, there are 2 ways to get all (or specific) columns with pure simple Python code.

1. csv.DictReader

with open('demo.csv') as file:
    data = {}
    for row in csv.DictReader(file):
        for key, value in row.items():
            if key not in data:
                data[key] = []

It is easy to understand.

2. csv.reader with zip

with open('demo.csv') as file:
    data = {values[0]: values[1:] for values in zip(*csv.reader(file))}

This is not very clear, but efficient.

zip(x, y, z) transpose (x, y, z), while x, y, z are lists. *csv.reader(file) make (x, y, z) for zip, with column names.

Demo Result

The content of demo.csv:


The result of 1:

>>> print(data)
{'c': ['3', '6', '9'], 'b': ['2', '5', '8'], 'a': ['1', '4', '7']}

The result of 2:

>>> print(data)
{'c': ('3', '6', '9'), 'b': ('2', '5', '8'), 'a': ('1', '4', '7')}

failed to load ad : 3

in my case :
I/Ads: Ad failed to load : Account not approved yet.

but you need to implement the listener for knowing the error

First import the listener : import;
Second create variable : private final String TAG2 = com.ringtones.splash.class.getSimpleName();

            mAdView.setAdListener(new AdListener() {
            public void onAdLoaded() {Log.d(TAG2, "google banner ad loaded"); }
            public void onAdFailedToLoad(LoadAdError adError) {Log.d(TAG2, "google banner ad failed to load : "+ adError.getMessage());}
            public void onAdOpened() {Log.d(TAG2, "google banner ad opened");}
            public void onAdClicked() {Log.d(TAG2, "google banner ad clicked");}
            public void onAdLeftApplication() {Log.d(TAG2, "google banner ad left application");}
            public void onAdClosed() {Log.d(TAG2, "google banner ad closed");}

Getting Unexpected Token Export

Install the babel packages @babel/core and @babel/preset which will convert ES6 to a commonjs target as node js doesn't understand ES6 targets directly

npm install --save-dev @babel/core @babel/preset-env

Then you need to create one configuration file with name .babelrc in your project's root directory and add this code there

{ "presets": ["@babel/preset-env"] }

Error: [$injector:unpr] Unknown provider: $routeProvider

In angular 1.4 +, in addition to adding the dependency

angular.module('myApp', ['ngRoute'])

,we also need to reference the separate angular-route.js file

<script src="angular.js">
<script src="angular-route.js">


Hide axis and gridlines Highcharts

This has always worked well for me:

yAxes: [{
         ticks: {
                 display: false;

How to kill a child process after a given timeout in Bash?

(As seen in: BASH FAQ entry #68: "How do I run a command, and have it abort (timeout) after N seconds?")

If you don't mind downloading something, use timeout (sudo apt-get install timeout) and use it like: (most Systems have it already installed otherwise use sudo apt-get install coreutils)

timeout 10 ping

If you don't want to download something, do what timeout does internally:

( cmdpid=$BASHPID; (sleep 10; kill $cmdpid) & exec ping )

In case that you want to do a timeout for longer bash code, use the second option as such:

( cmdpid=$BASHPID; 
    (sleep 10; kill $cmdpid) \
   & while ! ping -w 1 
         echo crap; 
     done )

Do you have to put Task.Run in a method to make it async?

When you use Task.Run to run a method, Task gets a thread from threadpool to run that method. So from the UI thread's perspective, it is "asynchronous" as it doesn't block UI thread.This is fine for desktop application as you usually don't need many threads to take care of user interactions.

However, for web application each request is serviced by a thread-pool thread and thus the number of active requests can be increased by saving such threads. Frequently using threadpool threads to simulate async operation is not scalable for web applications.

True Async doesn't necessarily involving using a thread for I/O operations, such as file / DB access etc. You can read this to understand why I/O operation doesn't need threads.

In your simple example,it is a pure CPU-bound calculation, so using Task.Run is fine.

What is a PDB file?

I had originally asked myself the question "Do I need a PDB file deployed to my customer's machine?", and after reading this post, decided to exclude the file.

Everything worked fine, until today, when I was trying to figure out why a message box containing an Exception.StackTrace was missing the file and line number information - necessary for troubleshooting the exception. I re-read this post and found the key nugget of information: that although the PDB is not necessary for the app to run, it is necessary for the file and line numbers to be present in the StackTrace string. I included the PDB file in the executable folder and now all is fine.

header('HTTP/1.0 404 Not Found'); not doing anything

After writing

header('HTTP/1.0 404 Not Found');

add one more header for any inexisting page on your site. It works, for sure.

header("Location: http://yoursite/nowhere");

How to get the width and height of an android.widget.ImageView?

The reason the ImageView's dimentions are 0 is because when you are querying them, the view still haven't performed the layout and measure steps. You only told the view how it would "behave" in the layout, but it still didn't calculated where to put each view.

How do you decide the size to give to the image view? Can't you simply use one of the scaling options natively implemented?

Remove plot axis values

you can also put labels inside plot:

plot(spline(sub$day, sub$counts), type ='l', labels = FALSE)

you'll get a warning. i think this is because labels is actually a parameter that's being passed down to a subroutine that plot runs (axes?). the warning will pop up because it wasn't directly a parameter of the plot function.

Combine two ActiveRecord::Relation objects

Relation objects can be converted to arrays. This negates being able to use any ActiveRecord methods on them afterwards, but I didn't need to. I did this:

name_relation = first_name_relation + last_name_relation

Ruby 1.9, rails 3.2

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

In my case, I was using Babel with the babel-plugin-transform-inline-environment-variables plugin. Apparently, Heroku does not set the PORT env variable when doing a deployment, so process.env.PORT will be replaced by undefined, and your code will fallback to the development port which Heroku does not know anything about.

Configure Nginx with proxy_pass

Nginx prefers prefix-based location matches (not involving regular expression), that's why in your code block, /stash redirects are going to /.

The algorithm used by Nginx to select which location to use is described thoroughly here:

MongoDb query condition on comparing 2 fields

You can use $expr ( 3.6 mongo version operator ) to use aggregation functions in regular query.

Compare query operators vs aggregation comparison operators.

Regular Query:

db.T.find({$expr:{$gt:["$Grade1", "$Grade2"]}})

Aggregation Query:

db.T.aggregate({$match:{$expr:{$gt:["$Grade1", "$Grade2"]}}})

How is a CSS "display: table-column" supposed to work?

The CSS table model is based on the HTML table model

A table is divided into ROWS, and each row contains one or more cells. Cells are children of ROWS, they are NEVER children of columns.

"display: table-column" does NOT provide a mechanism for making columnar layouts (e.g. newspaper pages with multiple columns, where content can flow from one column to the next).

Rather, "table-column" ONLY sets attributes that apply to corresponding cells within the rows of a table. E.g. "The background color of the first cell in each row is green" can be described.

The table itself is always structured the same way it is in HTML.

In HTML (observe that "td"s are inside "tr"s, NOT inside "col"s):

<table ..>
  <col .. />
  <col .. />
  <tr ..>
    <td ..></td>
    <td ..></td>
  <tr ..>
    <td ..></td>
    <td ..></td>

Corresponding HTML using CSS table properties (Note that the "column" divs do not contain any contents -- the standard does not allow for contents directly in columns):

.mytable {_x000D_
  display: table;_x000D_
.myrow {_x000D_
  display: table-row;_x000D_
.mycell {_x000D_
  display: table-cell;_x000D_
.column1 {_x000D_
  display: table-column;_x000D_
  background-color: green;_x000D_
.column2 {_x000D_
  display: table-column;_x000D_
<div class="mytable">_x000D_
  <div class="column1"></div>_x000D_
  <div class="column2"></div>_x000D_
  <div class="myrow">_x000D_
    <div class="mycell">contents of first cell in row 1</div>_x000D_
    <div class="mycell">contents of second cell in row 1</div>_x000D_
  <div class="myrow">_x000D_
    <div class="mycell">contents of first cell in row 2</div>_x000D_
    <div class="mycell">contents of second cell in row 2</div>_x000D_

OPTIONAL: both "rows" and "columns" can be styled by assigning multiple classes to each row and cell as follows. This approach gives maximum flexibility in specifying various sets of cells, or individual cells, to be styled:

//Useful css declarations, depending on what you want to affect, include:_x000D_
/* all cells (that have "class=mycell") */_x000D_
.mycell {_x000D_
/* class row1, wherever it is used */_x000D_
.row1 {_x000D_
/* all the cells of row1 (if you've put "class=mycell" on each cell) */_x000D_
.row1 .mycell {_x000D_
/* cell1 of row1 */_x000D_
.row1 .cell1 {_x000D_
/* cell1 of all rows */_x000D_
.cell1 {_x000D_
/* row1 inside class mytable (so can have different tables with different styles) */_x000D_
.mytable .row1 {_x000D_
/* all the cells of row1 of a mytable */_x000D_
.mytable .row1 .mycell {_x000D_
/* cell1 of row1 of a mytable */_x000D_
.mytable .row1 .cell1 {_x000D_
/* cell1 of all rows of a mytable */_x000D_
.mytable .cell1 {_x000D_
<div class="mytable">_x000D_
  <div class="column1"></div>_x000D_
  <div class="column2"></div>_x000D_
  <div class="myrow row1">_x000D_
    <div class="mycell cell1">contents of first cell in row 1</div>_x000D_
    <div class="mycell cell2">contents of second cell in row 1</div>_x000D_
  <div class="myrow row2">_x000D_
    <div class="mycell cell1">contents of first cell in row 2</div>_x000D_
    <div class="mycell cell2">contents of second cell in row 2</div>_x000D_

In today's flexible designs, which use <div> for multiple purposes, it is wise to put some class on each div, to help refer to it. Here, what used to be <tr> in HTML became class myrow, and <td> became class mycell. This convention is what makes the above CSS selectors useful.

PERFORMANCE NOTE: putting class names on each cell, and using the above multi-class selectors, is better performance than using selectors ending with *, such as .row1 * or even .row1 > *. The reason is that selectors are matched last first, so when matching elements are being sought, .row1 * first does *, which matches all elements, and then checks all the ancestors of each element, to find if any ancestor has class row1. This might be slow in a complex document on a slow device. .row1 > * is better, because only the immediate parent is examined. But it is much better still to immediately eliminate most elements, via .row1 .cell1. (.row1 > .cell1 is an even tighter spec, but it is the first step of the search that makes the biggest difference, so it usually isn't worth the clutter, and the extra thought process as to whether it will always be a direct child, of adding the child selector >.)

The key point to take away re performance is that the last item in a selector should be as specific as possible, and should never be *.

Truncate/round whole number in JavaScript?

Convert the number to a string and throw away everything after the decimal.

trunc = function(n) { return Number(String(n).replace(/\..*/, "")) }

trunc(-1.5) === -1

trunc(1.5) === 1

Edit 2013-07-10

As pointed out by minitech and on second thought the string method does seem a bit excessive. So comparing the various methods listed here and elsewhere:

function trunc1(n){ return parseInt(n, 10); }
function trunc2(n){ return n - n % 1; }
function trunc3(n) { return Math[n > 0 ? "floor" : "ceil"](n); }
function trunc4(n) { return Number(String(n).replace(/\..*/, "")); }

function getRandomNumber() { return Math.random() * 10; }

function test(func, desc) {
    var t1, t2;
    var ave = 0;
    for (var k = 0; k < 10; k++) {
        t1 = new Date().getTime();
        for (var i = 0; i < 1000000; i++) {
        t2 = new Date().getTime();
        ave += t2 - t1;
    } + " => " + (ave / 10));

test("trunc1", "parseInt");
test("trunc2", "mod");
test("trunc3", "Math");
test("trunc4", "String");

The results, which may vary based on the hardware, are as follows:

parseInt => 258.7
mod      => 246.2
Math     => 243.8
String   => 1373.1

The Math.floor / ceil method being marginally faster than parseInt and mod. String does perform poorly compared to the other methods.

Sample database for exercise

You want huge?

Here's a small table: create table foo (id int not null primary key auto_increment, crap char(2000));

insert into foo(crap) values ('');

-- each time you run the next line, the number of rows in foo doubles. insert into foo( crap ) select * from foo;

run it twenty more times, you have over a million rows to play with.

Yes, if he's looking for looks of relations to navigate, this is not the answer. But if by huge he means to test performance and his ability to optimize, this will do it. I did exactly this (and then updated with random values) to test an potential answer I had for another question. (And didn't answer it, because I couldn't come up with better performance than what that asker had.)

Had he asked for "complex", I'd have gien a differnt answer. To me,"huge" implies "lots of rows".

Because you don't need huge to play with tables and relations. Consider a table, by itself, with no nullable columns. How many different kinds of rows can there be? Only one, as all columns must have some value as none can be null.

Every nullable column multiples by two the number of different kinds of rows possible: a row where that column is null, an row where it isn't null.

Now consider the table, not in isolation. Consider a table that is a child table: for every child that has an FK to the parent, that, is a many-to-one, there can be 0, 1 or many children. So we multiply by three times the count we got in the previous step (no rows for zero, one for exactly one, two rows for many). For any grandparent to which the parent is a many, another three.

For many-to-many relations, we can have have no relation, a one-to-one, a one-to-many, many-to-one, or a many-to-many. So for each many-to-many we can reach in a graph from the table, we multiply the rows by nine -- or just like two one-to manys. If the many-to-many also has data, we multiply by the nullability number.

Tables that we can't reach in our graph -- those that we have no direct or indirect FK to, don't multiply the rows in our table.

By recursively multiplying the each table we can reach, we can come up with the number of rows needed to provide one of each "kind", and we need no more than those to test every possible relation in our schema. And we're nowhere near huge.

Switching a DIV background image with jQuery

This works on all current browsers on WinXP. Basically just checking what the current backgrond image is. If it's image1, show image2, otherwise show image1.

The jsapi stuff just loads jQuery from the Google CDN (easier for testing a misc file on the desktop).

The replace is for cross-browser compatibility (opera and ie add quotes to the url and firefox, chrome and safari remove quotes).

        <script src=""></script>
          google.load("jquery", "1.2.6");
          google.setOnLoadCallback(function() {
            var original_image = 'url(';
            var second_image = 'url(';

            $('.mydiv').click(function() {
                if ($(this).css('background-image').replace(/"/g, '') == original_image) {
                    $(this).css('background-image', second_image);
                } else {
                    $(this).css('background-image', original_image);

                return false;

            .mydiv {
                background-image: url('');
                width: 100px;
                height: 100px;
        <div class="mydiv">&nbsp;</div>

How to add multiple files to Git at the same time

When you change files or add a new ones in repository you first must stage them.

git add <file>

or if you want to stage all

git add .

By doing this you are telling to git what files you want in your next commit. Then you do:

git commit -m 'your message here'

You use

git push origin master

where origin is the remote repository branch and master is your local repository branch.

Refresh (reload) a page once using jQuery?

For refreshing page with javascript, you can simply use:


How to install requests module in Python 3.4, instead of 2.7

i was facing same issue in beautiful soup , I solved this issue by this command , your issue will also get rectified . You are unable to install requests in python 3.4 because your python libraries are not updated . use this command apt-get install python3-requests Just run it will ask you to add 222 MB space in your hard disk , just press Y and wait for completing process, after ending up whole process . check your problem will be resolved.

Convert Dictionary<string,string> to semicolon separated string in c#

For Linq to work over Dictionary you need at least .Net v3.5 and using System.Linq;.

Some alternatives:

string myDesiredOutput = string.Join(";", myDict.Select(x => string.Join("=", x.Key, x.Value)));


string myDesiredOutput = string.Join(";", myDict.Select(x => $"{x.Key}={x.Value}"));

If you can't use Linq for some reason, use Stringbuilder:

StringBuilder sb = new StringBuilder();
var isFirst = true;
foreach(var x in myDict) 
  if (isFirst) 
    isFirst = false;

string myDesiredOutput = sb.ToString(); 



Facebook share link - can you customize the message body text?

Like @Ardee said you sharer.php uses data from the meta tags, the Dialog API accepts parameters. Facebook have removed the ability to use the message parameter but you can use the quote parameter which can be useful in a lot of cases e.g.

enter image description here

Just have to create an app id:

Then make sure the redirect url domain is listed in the accepted domains for that app.

Angular2 - Input Field To Accept Only Numbers

If you use primeng and Angular 6 or above there is the p-inputMask component. It prevents alpha typing AND negative values

How to disable an Android button?

You just write a single line of code in your activity

Button btn = (Button) findViewById(;

When you want to enable the same button just write

Button btn = (Button) findViewById(;

Route [login] not defined

Laravel has introduced Named Routes in Laravel 4.2.


Named Routes allows you to give names to your router path. Hence using the name we can call the routes in required file.


Named Routes created in two different way : as and name()


            return view('about');


 return view('about');

How we use in views?

<a href="{{ URL::route("about-as") }}">about-as</a>

Hence laravel 'middleware'=>'auth' has already predefined for redirect as login page if user has not yet logged in.Hence we should use as keyword

    return view('login');

How to run a hello.js file in Node.js on windows?

Just change file association of .js file to node.exe and you can run directly from explorer.

1) Right click on the file -> Select "Open with" -> Select "Choose another program"
2) Check box "Always use this app to open .js file"
3) Click "More apps" -> "Look for another app in PC"
4) Navigate to node.js installation directory.(Default C:\Program Files\nodejs\node.exe"
5) Click "Open" and you can just see cmd flashing

Now you will be able to run any .js files directly just by double clicking.

Note: Adding below code to the end of js file will be useful as it will keep the console open for a keystroke.

console.log('Press any key to exit');

process.stdin.on('data', process.exit.bind(process, 0));

Splitting a string into separate variables

An array is created with the -split operator. Like so,

$myString="Four score and seven years ago"
$arr = $myString -split ' '
$arr # Print output

When you need a certain item, use array index to reach it. Mind that index starts from zero. Like so,

$arr[2] # 3rd element
$arr[4] # 5th element

How do I measure time elapsed in Java?

Byte Stream Reader Elapsed Time for 23.7 MB is 96 secs

import java.util.Scanner;

class ElaspedTimetoCopyAFileUsingByteStream

    private long startTime = 0;
    private long stopTime = 0;
    private boolean running = false;

    public void start() 
        this.startTime = System.currentTimeMillis();
        this.running = true;

    public void stop() 
        this.stopTime = System.currentTimeMillis();
        this.running = false;

    public long getElapsedTime() 
        long elapsed;
        if (running) {
             elapsed = (System.currentTimeMillis() - startTime);
        else {
            elapsed = (stopTime - startTime);
        return elapsed;

    public long getElapsedTimeSecs()                 
        long elapsed;
        if (running) 
            elapsed = ((System.currentTimeMillis() - startTime) / 1000);
            elapsed = ((stopTime - startTime) / 1000);
        return elapsed;

    public static void main(String[] args) throws IOException
        ElaspedTimetoCopyAFileUsingByteStream  s = new ElaspedTimetoCopyAFileUsingByteStream();

        FileInputStream in = null;
        FileOutputStream out = null;

      try {
         in = new FileInputStream("vowels.txt");   // 23.7  MB File
         out = new FileOutputStream("output.txt");

         int c;
         while ((c = != -1) {
      }finally {
         if (in != null) {
         if (out != null) {

        System.out.println("elapsed time in seconds: " + s.getElapsedTimeSecs());

[Elapsed Time for Byte Stream Reader][1]

**Character Stream Reader Elapsed Time for 23.7 MB is 3 secs**

import java.util.Scanner;

class ElaspedTimetoCopyAFileUsingCharacterStream

    private long startTime = 0;
    private long stopTime = 0;
    private boolean running = false;

    public void start() 
        this.startTime = System.currentTimeMillis();
        this.running = true;

    public void stop() 
        this.stopTime = System.currentTimeMillis();
        this.running = false;

    public long getElapsedTime() 
        long elapsed;
        if (running) {
             elapsed = (System.currentTimeMillis() - startTime);
        else {
            elapsed = (stopTime - startTime);
        return elapsed;

    public long getElapsedTimeSecs()                 
        long elapsed;
        if (running) 
            elapsed = ((System.currentTimeMillis() - startTime) / 1000);
            elapsed = ((stopTime - startTime) / 1000);
        return elapsed;

    public static void main(String[] args) throws IOException
        ElaspedTimetoCopyAFileUsingCharacterStream  s = new ElaspedTimetoCopyAFileUsingCharacterStream();

         FileReader in = null;                // CharacterStream Reader
      FileWriter out = null;

      try {
         in = new FileReader("vowels.txt");    // 23.7 MB
         out = new FileWriter("output.txt");

         int c;
         while ((c = != -1) {
      }finally {
         if (in != null) {
         if (out != null) {

        System.out.println("elapsed time in seconds: " + s.getElapsedTimeSecs());

[Elapsed Time for Character Stream Reader][2]


How to redirect to another page in node.js

You should return the line that redirects

return res.redirect('/UserHomePage');

Detect home button press in android

Jack's answer is perfectly working for click event while longClick is considering is as menu button click.

By the way, if anyone is wondering how to do via kotlin,

class HomeButtonReceiver(private var context: Context,private var listener: OnHomeButtonClickListener) {
    private val mFilter: IntentFilter = IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
    private var mReceiver: InnerReceiver = InnerReceiver()

    fun startWatch() {
        context.registerReceiver(mReceiver, mFilter)

    fun stopWatch() {

    inner class InnerReceiver: BroadcastReceiver() {
        private val systemDialogReasonKey = "reason"
        private val systemDialogReasonHomeKey = "homekey"
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent?.action
            if (action == Intent.ACTION_CLOSE_SYSTEM_DIALOGS) {
                val reason = intent.getStringExtra(systemDialogReasonKey)
                if (reason != null && reason == systemDialogReasonHomeKey) {

How do you run a script on login in *nix?

I was frustrated with this problem for days. Nothing worked on ubuntu. If I put the call in /etc/profile it all crashed at login attempt. I couldn't use "Startup Applications" as that was not what I wanted. That only sets the script for that current user.

Finally I found this little article:

The solution would be:

  1. find out the $XDG_CONFIG_DIRS path:


  2. put your script in that directory

Compare two Lists for differences

I think you're looking for a method like this:

public static IEnumerable<TResult> CompareSequences<T1, T2, TResult>(IEnumerable<T1> seq1,
    IEnumerable<T2> seq2, Func<T1, T2, TResult> comparer)
    var enum1 = seq1.GetEnumerator();
    var enum2 = seq2.GetEnumerator();

    while (enum1.MoveNext() && enum2.MoveNext())
        yield return comparer(enum1.Current, enum2.Current);

It's untested, but it should do the job nonetheless. Note that what's particularly useful about this method is that it's full generic, i.e. it can take two sequences of arbitrary (and different) types and return objects of any type.

This solution of course assumes that you want to compare the nth item of seq1 with the nth item in seq2. If you want to do match the elements in the two sequences based on a particular property/comparison, then you'll want to perform some sort of join operation (as suggested by danbruc using Enumerable.Join. Do let me know if it neither of these approaches is quite what I'm after and maybe I can suggest something else.

Edit: Here's an example of how you might use the CompareSequences method with the comparer function you originally posted.

// Prints out to the console all the results returned by the comparer function (CompareTwoClass_ReturnDifferences in this case).
var results = CompareSequences(list1, list2, CompareTwoClass_ReturnDifferences);
int index;    

foreach(var element in results)
    Console.WriteLine("{0:#000} {1}", index++, element.ToString());

Val and Var in Kotlin

Simply think Val like final Variable in java

HTML5 Local storage vs. Session storage

Late answer but felt to add some points here.

Session storage will be available for specific tab where as we can use Local storage through out the browser. Both are default to same origin and we can also store values manually with key, value pairs (value must be string).

Once tab (session) of the browser is closed then Session storage will be cleared on that tab, where as in case of Local storage we need to clear it explicitly. Maximum storage limit respectively 5MB and 10MB.

We can save and retrieve the data like below,

To Save:

sessionStorage.setItem('id', noOfClicks);   // localStorage.setItem('id', noOfClicks);

sessionStorage.setItem('userDetails', JSON.stringify(userDetails));   // if it's object

To Get:

sessionStorage.getItem('id');    // localStorage.getItem('id');

User user = JSON.parse(sessionStorage.getItem("userDetails")) as User;  // if it's object

To Modify:

sessionStorage.removeItem('id');    // localStorage.removeItem('id');

sessionStorage.clear();   // localStorage.clear();

P.S: getItem() also return back the data as string and we need convert it into JSON format to access if it's object.

You can read more about Browser Storages here..

  1. Difference between localStorage, sessionStorage and cookies

  2. localstorage-vs-sessionstorage

Eclipse IDE for Java - Full Dark Theme

I've build a win 7 dark theme base on the popular windows 7 'concave 7' theme for eclipse dark juno theme. And I also create a dark theme inspired from the editor color theme 'Zenburn' created by Janni Nurmin

Here are photos of this theme:

All settings of this theme is available on github:

And feedback and suggestion is appreciated, thank you!

Java Mouse Event Right Click

I've seen


be used before. I'm fairly new to Java so I'm happy to hear thoughts about this approach :)

How do I get video durations with YouTube API version 3?

I wrote the following class to get YouTube video duration using the YouTube API v3 (it returns thumbnails as well):

class Youtube
    static $api_key = '<API_KEY>';
    static $api_base = '';
    static $thumbnail_base = '';

    // $vid - video id in youtube
    // returns - video info
    public static function getVideoInfo($vid)
        $params = array(
            'part' => 'contentDetails',
            'id' => $vid,
            'key' => self::$api_key,

        $api_url = Youtube::$api_base . '?' . http_build_query($params);
        $result = json_decode(@file_get_contents($api_url), true);

            return null;
        $vinfo = $result['items'][0]['contentDetails'];

        $interval = new DateInterval($vinfo['duration']);
        $vinfo['duration_sec'] = $interval->h * 3600 + $interval->i * 60 + $interval->s;

        $vinfo['thumbnail']['default']       = self::$thumbnail_base . $vid . '/default.jpg';
        $vinfo['thumbnail']['mqDefault']     = self::$thumbnail_base . $vid . '/mqdefault.jpg';
        $vinfo['thumbnail']['hqDefault']     = self::$thumbnail_base . $vid . '/hqdefault.jpg';
        $vinfo['thumbnail']['sdDefault']     = self::$thumbnail_base . $vid . '/sddefault.jpg';
        $vinfo['thumbnail']['maxresDefault'] = self::$thumbnail_base . $vid . '/maxresdefault.jpg';

        return $vinfo;

Please note that you'll need API_KEY to use the YouTube API:

  1. Create a new project here:
  2. Enable "YouTube Data API" under "APIs & auth" -> APIs
  3. Create a new server key under "APIs & auth" -> Credentials

Compare two dates with JavaScript

Subtract two date get the difference in millisecond, if you get 0 it's the same date

function areSameDate(d1, d2){
    return d1 - d2 === 0

How to read file with space separated values in pandas

If you can't get text parsing to work using the accepted answer (e.g if your text file contains non uniform rows) then it's worth trying with Python's csv library - here's an example using a user defined Dialect:

 import csv

 csv.register_dialect('skip_space', skipinitialspace=True)
 with open(my_file, 'r') as f:
      reader=csv.reader(f , delimiter=' ', dialect='skip_space')
      for item in reader:

Bootstrap 3 Navbar with Logo

The easiest and best answer for this question is to set a max width and height depending on your logo, the image will be a max of 50px high but no longer than 200px.

<a href="index.html">
<img src="imgs/brand-w.png" style="max-height:50px;max-width:200px;">

This will vary depending on your logo size and the nav bar items you have.

docker error: /var/run/docker.sock: no such file or directory

I also got this error. Though, I did not use boot2docker but just installed "plain" docker on Ubuntu (see

I got the error ("dial unix /var/run/docker.sock: no such file or directory. Are you trying to connect to a TLS-enabled daemon without TLS?") because the docker daemon was not running, yet.

On Ubuntu, you need to start the service:

sudo service docker start

See also

Write in body request with HttpClient

If your xml is written by java.lang.String you can just using HttpClient in this way

    public void post() throws Exception{
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("");
        String xml = "<xml>xxxx</xml>";
        HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());

pay attention to the Exceptions.

BTW, the example is written by the httpclient version 4.x

Flatten List in LINQ

If you have a List<List<int>> k you can do

List<int> flatList= k.SelectMany( v => v).ToList();

How to delete items from a dictionary while iterating over it?

There is a way that may be suitable if the items you want to delete are always at the "beginning" of the dict iteration

while mydict:
    key, value = next(iter(mydict.items()))
    if should_delete(key, value):
       del mydict[key]

The "beginning" is only guaranteed to be consistent for certain Python versions/implementations. For example from What’s New In Python 3.7

the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec.

This way avoids a copy of the dict that a lot of the other answers suggest, at least in Python 3.

Run a PostgreSQL .sql file using command line arguments

You can give both user name and PASSSWORD on the command line itself.

   psql "dbname='urDbName' user='yourUserName' password='yourPasswd' host='yourHost'" -f yourFileName.sql

How to detect a loop in a linked list?

You could even do it in constant O(1) time (although it would not be very fast or efficient): There is a limited amount of nodes your computer's memory can hold, say N records. If you traverse more than N records, then you have a loop.

no such file to load -- rubygems (LoadError)

I have also met the same problem using rbenv + passenger + nginx. my solution is simply adding these 2 line of code to your nginx config:

passenger_default_user root;
passenger_default_group root;

the detailed answer is here:

Access a global variable in a PHP function

It is not working because you have to declare which global variables you'll be accessing:

$data = 'My data';

function menugen() {
    global $data; // <-- Add this line

    echo "[" . $data . "]";


Otherwise you can access it as $GLOBALS['data']. See Variable scope.

Even if a little off-topic, I'd suggest you avoid using globals at all and prefer passing as parameters.

How to convert SQL Server's timestamp column to datetime format

for me works: TO_DATE('19700101', 'yyyymmdd') + (TIME / 24 / 60 / 60) (oracle DB)

Why do we use __init__ in Python classes?

Following with your car example: when you get a car, you just don't get a random car, I mean, you choose the color, the brand, number of seats, etc. And some stuff is also "initialize" without you choosing for it, like number of wheels or registration number.

class Car:
    def __init__(self, color, brand, number_of_seats):
        self.color = color
        self.brand = brand
        self.number_of_seats = number_of_seats
        self.number_of_wheels = 4
        self.registration_number = GenerateRegistrationNumber()

So, in the __init__ method you defining the attributes of the instance you're creating. So, if we want a blue Renault car, for 2 people, we would initialize or instance of Car like:

my_car = Car('blue', 'Renault', 2)

This way, we are creating an instance of the Car class. The __init__ is the one that is handling our specific attributes (like color or brand) and its generating the other attributes, like registration_number.

How to set a value for a span using jQuery

You can do:



$("#submittername").html("testing <b>1 2 3</b>");

Using Mockito to stub and execute methods for testing

So, the idea of mocking the class under test is anathima to testing practice. You should NOT do this. Because you have done so, your test is entering Mockito's mocking classes not your class under test.

Spying will also not work because this only provides a wrapper / proxy around the spied class. Once execution is inside the class it will not go through the proxy and therefore not hit the spy. UPDATE: although I believe this to be true of Spring proxies it appears to not be true of Mockito spies. I set up a scenario where method m1() calls m2(). I spy the object and stub m2() to doNothing. When I invoke m1() in my test, m2() of the class is not reached. Mockito invokes the stub. So using a spy to accomplish what is being asked is possible. However, I would reiterate that I would consider it bad practice (IMHO).

You should mock all the classes on which the class under test depends. This will allow you to control the behavior of the methods invoked by the method under test in that you control the class that those methods invoke.

If your class creates instances of other classes, consider using factories.

AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

As answered by @Dark Falcon, I simply dealt with it.

In my case, I am using node.js server, and creating a session if it does not exist. Since the OPTIONS method does not have the session details in it, it ended up creating a new session for every POST method request.

So in my app routine to create-session-if-not-exist, I just added a check to see if method is OPTIONS, and if so, just skip session creating part:

    app.use(function(req, res, next) {
        if (req.method !== "OPTIONS") {
            if (req.session && {
                 // Session exists
                 // Create session
        } else {
           // If request method is OPTIONS, just skip this part and move to the next method.

Check if argparse optional argument is set or not

As @Honza notes is None is a good test. It's the default default, and the user can't give you a string that duplicates it.

You can specify another default='mydefaultvalue, and test for that. But what if the user specifies that string? Does that count as setting or not?

You can also specify default=argparse.SUPPRESS. Then if the user does not use the argument, it will not appear in the args namespace. But testing that might be more complicated: # raises an AttributeError
hasattr(args, 'foo')  # returns False
getattr(args, 'foo', 'other') # returns 'other'

Internally the parser keeps a list of seen_actions, and uses it for 'required' and 'mutually_exclusive' testing. But it isn't available to you out side of parse_args.

How to convert LINQ query result to List?

List<course> = (from c in obj.tbCourses
                new course(c)).toList();

You can convert the entity object to a list directly on the call. There are methods to converting it to different data struct (list, array, dictionary, lookup, or string)

mysql is not recognised as an internal or external command,operable program or batch

I am using xampp. For me best option is to change environment variables. Environment variable changing window is shared by @Abu Bakr in this thread

I change the path value as C:\xampp\mysql\bin; and it is working nice

Update multiple rows using select statement

If you have ids in both tables, the following works:

update table2
    set value = (select value from table1 where =

Perhaps a better approach is a join:

update table2
    set value = table1.value
    from table1
    where =

Note that this syntax works in SQL Server but may be different in other databases.

ExecuteReader: Connection property has not been initialized

use this and pass connection object :

 SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)values('"+this .name1 .SelectedValue +"','"+this .iteration .SelectedValue +"')",conn);

How to define optional methods in Swift protocol?

The other answers here involving marking the protocol as "@objc" do not work when using swift-specific types.

struct Info {
    var height: Int
    var weight: Int

@objc protocol Health {
    func isInfoHealthy(info: Info) -> Bool
//Error "Method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C"

In order to declare optional protocols that work well with swift, declare the functions as variables instead of func's.

protocol Health {
    var isInfoHealthy: (Info) -> (Bool)? { get set }

And then implement the protocol as follows

class Human: Health {
    var isInfoHealthy: (Info) -> (Bool)? = { info in
        if info.weight < 200 && info.height > 72 {
            return true
        return false
    //Or leave out the implementation and declare it as:  
    //var isInfoHealthy: (Info) -> (Bool)?

You can then use "?" to check whether or not the function has been implemented

func returnEntity() -> Health {
    return Human()

var anEntity: Health = returnEntity()

var isHealthy = anEntity.isInfoHealthy(Info(height: 75, weight: 150))? 
//"isHealthy" is true

Does Visual Studio have code coverage for unit tests?

Toni's answer is very useful, but I thought a quick start for total beginners to test coverage assessment (like I am).

As already mentioned, Visual Studio Professional and Community Editions do not have built-in test coverage support. However, it can be obtained quite easily. I will write step-by-step configuration for use with NUnit tests within Visual Studion 2015 Professional.

  1. Install OpenCover NUGet component using NuGet interface

  2. Get OpenCoverUI extension. This can be installed directly from Visual Studio by using Tools -> Extensions and Updates

  3. Configure OpenCoverUI to use the appropriate executables, by accessing Tools -> Options -> OpenCover.UI Options -> General

NUnit Path: must point to the `nunit-console.exe file. This can be found only within NUnit 2.xx version, which can be downloaded from here.

OpenCover Path: this should point to the installed package, usually <solution path>\packages\OpenCover.4.6.519\tools\OpenCover.Console.exe

  1. Install ReportGenerator NUGet package

  2. Access OpenCover Test Explorer from OpenCover menu. Try discovering tests from there. If it fails, check Output windows for more details.

  3. Check OpenCover Results (within OpenCover menu) for more details. It will output details such as Code Coverage in a tree based view. You can also highlight code that is or is not covered (small icon in the top-left).

NOTE: as mentioned, OpenCoverUI does not support latest major version of NUnit (3.xx). However, if nothing specific to this version is used within tests, it will work with no problems, regardless of having installed NUnit 3.xx version.

This covers the quick start. As already mentioned in the comments, for more advanced configuration and automation check this article.

How to get the version of ionic framework?

At some point in time the object changed from ionic to an uppercase Ionic.

As of July 2017 you need to put Ionic.version into your console to get the version number.

Float right and position absolute doesn't work together

I was able to absolutely position a right-floated element with one layer of nesting and a tricky margin:

function test() {_x000D_
.right {_x000D_
#box {_x000D_
  position:absolute; background:#feb;_x000D_
  width:20em; margin-left:-20em; padding:1ex;_x000D_
#box.hide {_x000D_
  <div class="right">_x000D_
    <button onclick="test()">box</button>_x000D_
    <div id="box">Lorem ipsum dolor sit amet, consectetur adipiscing elit,_x000D_
      sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
      Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris_x000D_
      nisi ut aliquip ex ea commodo consequat._x000D_
    Lorem ipsum dolor sit amet, consectetur adipiscing elit,_x000D_
    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris_x000D_
    nisi ut aliquip ex ea commodo consequat._x000D_

I decided to make this toggleable so you can see how it does not affect the flow of the surrounding text (run it and press the button to show/hide the floated absolute box).

Process list on Linux via Python

from psutil import process_iter
from termcolor import colored

names = []
ids = []

x = 0
z = 0
k = 0
for proc in process_iter():
    name =
    y = len(name)
    if y>x:
        x = y
    if y<x:
        k = y
    id =
    names.insert(z, name)
    ids.insert(z, id)
    z += 1

print(colored("Process Name", 'yellow'), (x-k-5)*" ", colored("Process Id", 'magenta'))
for b in range(len(names)-1):
    z = x
    print(colored(names[b], 'cyan'),(x-len(names[b]))*" ",colored(ids[b], 'white'))

React - Component Full Screen (with height 100%)

#app {
  height: 100%;
  min-height: 100vh;

Always full height of view min

Use Expect in a Bash script to provide a password to an SSH command

Also make sure to use

send -- "$PWD\r"

instead, as passwords starting with a dash (-) will fail otherwise.

The above won't interpret a string starting with a dash as an option to the send command.

React-Redux: Actions must be plain objects. Use custom middleware for async actions

For future seekers who might have dropped simple details like me, in my case I just have forgotten to call my action function with parentheses.


export function addNewComponent() {
  return {


import React, { useEffect } from 'react';
import { addNewComponent } from '../../redux/actions';

  useEffect(() => {
    dispatch(refreshAllComponents); // <= Here was what I've missed.
  }, []);

I've forgotten to dispatch the action function with (). So doing this solved my issue.

  useEffect(() => {
  }, []);

Again this might have nothing to do with OP's problem, but I hope I helps people with the same problem as mine.

How does internationalization work in JavaScript?

Localization support in legacy browsers is poor. Originally, this was due to phrases in the ECMAScript language spec that look like this:

Produces a string value that represents the value of the Number formatted according to the conventions of the host environment’s current locale. This function is implementation-dependent, and it is permissible, but not encouraged, for it to return the same thing as toString.

Every localization method defined in the spec is defined as "implementation-dependent", which results in a lot of inconsistencies. In this instance, Chrome Opera and Safari would return the same thing as .toString(). Firefox and IE will return locale formatted strings, and IE even includes a thousand separator (perfect for currency strings). Chrome was recently updated to return a thousands-separated string, though with no fixed decimal.

For modern environments, the ECMAScript Internationalization API spec, a new standard that complements the ECMAScript Language spec, provides much better support for string comparison, number formatting, and the date and time formatting; it also fixes the corresponding functions in the Language Spec. An introduction can be found here. Implementations are available in:

  • Chrome 24
  • Firefox 29
  • Internet Explorer 11
  • Opera 15

There is also a compatibility implementation, Intl.js, which will provide the API in environments where it doesn't already exist.

Determining the user's preferred language remains a problem since there's no specification for obtaining the current language. Each browser implements a method to obtain a language string, but this could be based on the user's operating system language or just the language of the browser:

// navigator.userLanguage for IE, navigator.language for others
var lang = navigator.language || navigator.userLanguage;

A good workaround for this is to dump the Accept-Language header from the server to the client. If formatted as a JavaScript, it can be passed to the Internationalization API constructors, which will automatically pick the best (or first-supported) locale.

In short, you have to put in a lot of the work yourself, or use a framework/library, because you cannot rely on the browser to do it for you.

Various libraries and plugins for localization:

  • Others:

Feel free to add/edit.

Zabbix server is not running: the information displayed may not be current

Never had the problem until it suddenly appeared once, for me, the solution was to add (uncomment) the following line in /etc/zabbix/zabbix_server.conf


How to repeat a string a variable number of times in C++?

You should write your own stream manipulator

cout << multi(5) << "whatever" << "lolcat";

ssh: Could not resolve hostname Name or service not known; fatal: The remote end hung up unexpectedly

Recently, I have seen this problem too. Below, you have my solution:

  1. ping, if ping failed. it is DNS error.
  2. sudo vim /etc/resolv.conf, the add: nameserver nameserver

Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart or fix it up

I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):

ssh -T [email protected]

Upon receiving a successful response, I could fetch/push to the repo with ssh.

I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.

disable textbox using jquery?

Sorry for being so late at the party, but I see some room for improvement here. Not concerning "disable textbox", but to the radionbox selection and code simplification, making it a bit more future proof, for later changes.

First of all, you shouldn't use .each() and use the index to point out a specific radio button. If you work with a dynamic set of radio buttons or if you add or remove some radio buttons afterwards, then your code will react on the wrong button!

Next, but that wasn't probably the case when the OP was made, I prefer to use .on('click', function(){...}) instead of click...

Lst but not least, also the code could be made more simple and future proof by selecting the radio button based on it's name (but that appeared already in a post).

So I ended up with the following code.

HTML (based on code of o.k.w)

<span id="radiobutt">
    <input type="radio" name="rad1" value="1" />
    <input type="radio" name="rad1" value="2" />
    <input type="radio" name="rad1" value="3" />
    <input type="text" id="textbox1" />
    <input type="checkbox" id="checkbox1" />


$("[name='rad1']").on('click', function() {
    var disable = $(this).val() === "2";
    $("#textbox1").prop("disabled", disable); 
    $("#checkbox1").prop("disabled", disable); 

What is Dispatcher Servlet in Spring?

DispatcherServlet is Spring MVC's implementation of the front controller pattern.

See description in the Spring docs here.

Essentially, it's a servlet that takes the incoming request, and delegates processing of that request to one of a number of handlers, the mapping of which is specific in the DispatcherServlet configuration.

What possibilities can cause "Service Unavailable 503" error?

Primarily what that means is that there are too many concurrent requests and further that they exceed the default 1000 queued requests. That is there are 1000 or more queued requests to your website.

This could happen (assuming there are no faults in your app) if there are long running tasks and as a result the Request queue is backed up.

Depending on how the application pool has been set up you may see this kind of thing. Typically, the app pool's Process Model has an item called Maximum Worker Processes. By default this is 1. If you set it to more than 1 (typically up to a max of the number of cores on the hardware) you may not see this happen.

Just to note that unless the site is extremely busy you should not see this. If you do, it's really pointing to long running tasks

How do I download the Android SDK without downloading Android Studio?

Navigate to the "Get just the command line tools" section of the android downloads page, and download the tools for your system.

For Windows:

Extract the contents to C:\Android\android-sdk

Navigate to C:\Android\android-sdk\tools\bin and open a command line window
(shift + right click)

Run the following to download the latest android package:

sdkmanager "platforms;android-25" 

Update everything

sdkmanager --update

Other operation systems Do pretty much the same, but not using windows directories.

The sdkmanager page gives more info in to what commands to use to install your sdk.

Manifest merger failed : uses-sdk:minSdkVersion 14

In Android Studio 1.1.0: File - Project Structure - Tab Flavors - Select Min SDK Version which is higher than in Manifest

Get absolute path of initially run script

If you're looking for the absolute path relative to the server root, I've found that this works well:


How do I deal with special characters like \^$.?*|+()[{ in my regex?

Escape with a double backslash

R treats backslashes as escape values for character constants. (... and so do regular expressions. Hence the need for two backslashes when supplying a character argument for a pattern. The first one isn't actually a character, but rather it makes the second one into a character.) You can see how they are processed using cat.

y <- "double quote: \", tab: \t, newline: \n, unicode point: \u20AC"
## [1] "double quote: \", tab: \t, newline: \n, unicode point: €"
## double quote: ", tab:    , newline: 
## , unicode point: €

Further reading: Escaping a backslash with a backslash in R produces 2 backslashes in a string, not 1

To use special characters in a regular expression the simplest method is usually to escape them with a backslash, but as noted above, the backslash itself needs to be escaped.

grepl("\\[", "a[b")
## [1] TRUE

To match backslashes, you need to double escape, resulting in four backslashes.

grepl("\\\\", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

The rebus package contains constants for each of the special characters to save you mistyping slashes.

## [1] "\\["
## [1] "\\\\"

For more examples see:


Your problem can be solved this way:

grepl(OPEN_BRACKET, "a[b")

Form a character class

You can also wrap the special characters in square brackets to form a character class.

grepl("[?]", "a?b")
## [1] TRUE

Two of the special characters have special meaning inside character classes: \ and ^.

Backslash still needs to be escaped even if it is inside a character class.

grepl("[\\\\]", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

Caret only needs to be escaped if it is directly after the opening square bracket.

grepl("[ ^]", "a^b")  # matches spaces as well.
## [1] TRUE
grepl("[\\^]", "a^b") 
## [1] TRUE

rebus also lets you form a character class.

## <regex> [?]

Use a pre-existing character class

If you want to match all punctuation, you can use the [:punct:] character class.

grepl("[[:punct:]]", c("//", "[", "(", "{", "?", "^", "$"))

stringi maps this to the Unicode General Category for punctuation, so its behaviour is slightly different.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "[[:punct:]]")

You can also use the cross-platform syntax for accessing a UGC.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "\\p{P}")

Use \Q \E escapes

Placing characters between \\Q and \\E makes the regular expression engine treat them literally rather than as regular expressions.

grepl("\\Q.\\E", "a.b")
## [1] TRUE

rebus lets you write literal blocks of regular expressions.

## <regex> \Q.\E

Don't use regular expressions

Regular expressions are not always the answer. If you want to match a fixed string then you can do, for example:

grepl("[", "a[b", fixed = TRUE)
stringr::str_detect("a[b", fixed("["))
stringi::stri_detect_fixed("a[b", "[")

split string only on first instance - java

String string = "This is test string on web";
String splitData[] = string.split("\\s", 2);

Result ::
splitData[0] =>  This
splitData[1] =>  is test string  

String string = "This is test string on web";
String splitData[] = string.split("\\s", 3);

Result ::
splitData[0] =>  This
splitData[1] =>  is
splitData[1] =>  test string on web

By default split method create n number's of arrays on the basis of given regex. But if you want to restrict number of arrays to create after a split than pass second argument as an integer argument.

How to respond to clicks on a checkbox in an AngularJS directive?

Liviu's answer was extremely helpful for me. Hope this is not bad form but i made a fiddle that may help someone else out in the future.

Two important pieces that are needed are:

    $scope.entities = [{
    "title": "foo",
    "id": 1
}, {
    "title": "bar",
    "id": 2
}, {
    "title": "baz",
    "id": 3
$scope.selected = [];

SQL Server Insert Example

To insert a single row of data:

VALUES (1, 'Mike', 'Jones');

To do an insert on specific columns (as opposed to all of them) you must specify the columns you want to update.

VALUES ('Stephen', 'Jiang');

To insert multiple rows of data in SQL Server 2008 or later:

(2, 'Michael', 'Blythe'),
(3, 'Linda', 'Mitchell'),
(4, 'Jillian', 'Carson'),
(5, 'Garrett', 'Vargas');

To insert multiple rows of data in earlier versions of SQL Server, use "UNION ALL" like so:

SELECT 'James', 'Bond' UNION ALL
SELECT 'Miss', 'Moneypenny' UNION ALL
SELECT 'Raoul', 'Silva'

Note, the "INTO" keyword is optional in INSERT queries. Source and more advanced querying can be found here.

How do I import a specific version of a package using go get?

You can use git checkout to get an specific version and build your program using this version.


export GOPATH=~/
go get
cd ~/src/
git tag -l
# supose tag v0.0.2 is correct version
git checkout tags/v0.0.2
go run whateverpackage/main.go

How to remove index.php from URLs?

Mainly If you are using Linux Based system Like 'Ubuntu' and this is only suggested for localhost user not for the server.

Follow all the steps mentioned in the previous answers. +

Check in Apache configuration for it. (AllowOverride All) If AllowOverride value is none then change it to All and restart apache again.

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted

Let me know if this step help anyone. As it can save you time if you find it earlier.

enter image description here

I am adding the exact lines from my htaccess file in localhost. for your reference

Around line number 110

<IfModule mod_rewrite.c>

## enable rewrites

Options +FollowSymLinks
RewriteEngine on

## you can put here your magento root folder
## path relative to web root

#RewriteBase /

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Images are for some user who understand easily from image the from the text:

enter image description here

Mongoose: findOneAndUpdate doesn't return updated document

For anyone using the Node.js driver instead of Mongoose, you'll want to use {returnOriginal:false} instead of {new:true}.

How do I read an image file using Python?

The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.

from PIL import Image
jpgfile ="picture.jpg")

print(jpgfile.bits, jpgfile.size, jpgfile.format)

gdb: "No symbol table is loaded"

I have the same problem and I followed this Post, it solved my problem.

Follow the following 2 steps:

  1. Make sure the optimization level is -O0
  2. Add -ggdb flag when compiling your program

Good luck!

A hex viewer / editor plugin for Notepad++?

Is a completely different (but still free) application an option? I use HxD, and it serves me better than the Notepad++ plugin. It can calculate hashes, open memory of a process, it is fast at opening files of any size, and it works exceptionally well with the clipboard.

I used to use the Notepad++ plugin, but not anymore.

Android set bitmap to Imageview

Please try this:

byte[] decodedString = Base64.decode(person_object.getPhoto(),Base64.NO_WRAP);
InputStream inputStream  = new ByteArrayInputStream(decodedString);
Bitmap bitmap  = BitmapFactory.decodeStream(inputStream);

How to have multiple conditions for one if statement in python

Darian Moody has a nice solution to this challenge in his blog post:

a = 1
b = 2
c = True

rules = [a == 1,
         b == 2,
         c == True]

if all(rules):

The all() method returns True when all elements in the given iterable are true. If not, it returns False.

You can read a little more about it in the python docs here and more information and examples here.

(I also answered the similar question with this info here - How to have multiple conditions for one if statement in python)

How to define dimens.xml for every different screen size in android?

we want to see the changes of required view size in different screens.

We need to create a different values folders for different screens and put dimens.xml file based on screen densities.

I have taken one TextView and observed the changes when i changed dimens.xml in different values folders.

Please follow the process

normal - xhdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - xhdpi \ dimens.xml

nexus 5X ( 5.2" * 1080 * 1920 : 420dpi )

nexus 6P ( 5.7" * 1440 * 2560 : 560dpi)

nexus 6 ( 6.0" * 1440 * 2560 : 560dpi)

nexus 5 (5.0", 1080 1920 : xxhdpi)

nexus 4 (4.7", 768 * 1280 : xhdpi)

Galaxy nexus (4.7", 720 * 1280 : xhdpi)

4.65" 720p ( 720 * 1280 : xhdpi )

4.7" WXGA ( 1280 * 720 : Xhdpi )

Xlarge - xhdpi \ dimens.xml

The below devices can change the sizes of screens when we change the Xlarge - xhdpi \ dimens.xml

nexus 9 ( 8.9", 2048 * 1556 : xhdpi)

nexus 10 (10.1", 2560 * 1600 : xhdpi)

large - xhdpi \ dimens.xml

The below devices can change the sizes of screens when we change the large - xhdpi \ dimens.xml

nexus 7 ( 7.0", 1200 * 1920: xhdpi)

nexus 7 (2012) (7.0", 800 * 1280 : tvdpi)

The below screens are visible in " Search Generic Phones and Tablets "

large - mdpi \ dimens.xml

The below devices can change the sizes of screens when we change the large - mdpi \ dimens.xml

5.1" WVGA ( 480 * 800 : mdpi )

5.4" FWVGA ( 480 * 854 : mdpi )

7.0" WSVGA (Tablet) ( 1024 * 600 : mdpi )

normal - hdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - hdpi \ dimens.xml

nexus s ( 4.0", 480 * 800 : hdpi )

nexus one ( 3.7", 480 * 800: hdpi)

small - ldpi \ dimens.xml

The below devices can change the sizes of screens when we change the small - ldpi \ dimens.xml

2.7" QVGA Slider ( 240 * 320 : ldpi )

2.7" QVGA ( 240 * 320 : ldpi )

xlarge - mdpi \ dimens.xml

The below devices can change the sizes of screens when we change the xlarge - mdpi \ dimens.xml

10.1" WXGA ( tABLET) ( 1280 * 800 : MDPI )

normal - ldpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - ldpi \ dimens.xml

3.3" WQVGA ( 240 * 400 : LDPI )

3.4" WQVGA ( 240 * 432 : LDPI )

normal - hdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - hdpi \ dimens.xml

4.0" WVGA ( 480 * 800 : hdpi )

3.7" WVGA ( 480 * 800 : hdpi )

3.7" FWVGA Slider ( 480 * 854 : hdpi )

normal - mdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - mdpi \ dimens.xml

3.2" HVGA Slider ( ADP1 ) ( 320 * 480 : MDPI )

3.2" QVGA ( ADP2 ) ( 320 * 480 : MDPI )

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

I use this:


It works for Hash and ActiveSupport::HashWithIndifferentAccess.

Add missing dates to pandas dataframe

Here's a nice method to fill in missing dates into a dataframe, with your choice of fill_value, days_back to fill in, and sort order (date_order) by which to sort the dataframe:

def fill_in_missing_dates(df, date_col_name = 'date',date_order = 'asc', fill_value = 0, days_back = 30):

    df.index = pd.DatetimeIndex(df.index)
    d =
    d2 = d - timedelta(days = days_back)
    idx = pd.date_range(d2, d, freq = "D")
    df = df.reindex(idx,fill_value=fill_value)
    df[date_col_name] = pd.DatetimeIndex(df.index)

    return df

delete_all vs destroy_all?

You are right. If you want to delete the User and all associated objects -> destroy_all However, if you just want to delete the User without suppressing all associated objects -> delete_all

According to this post : Rails :dependent => :destroy VS :dependent => :delete_all

  • destroy / destroy_all: The associated objects are destroyed alongside this object by calling their destroy method
  • delete / delete_all: All associated objects are destroyed immediately without calling their :destroy method

MatPlotLib: Multiple datasets on the same scatter plot

I don't know, it works fine for me. Exact commands:

import scipy, pylab
ax = pylab.subplot(111)
ax.scatter(scipy.randn(100), scipy.randn(100), c='b')
ax.scatter(scipy.randn(100), scipy.randn(100), c='r')

Python - Passing a function into another function

Treat function as variable in your program so you can just pass them to other functions easily:

def test ():
   print "test was invoked"

def invoker(func):

invoker(test)  # prints test was invoked