Programs & Examples On #Runkit

PECL runkit extension

Windows equivalent of the 'tail' command

I don't think there is way out of the box. There is no such command in DOS and batch files are far to limited to simulate it (without major pain).

Ruby/Rails: converting a Date to a UNIX timestamp

I get the following when I try it:

>> Date.today.to_time.to_i
=> 1259244000
>> Time.now.to_i
=> 1259275709

The difference between these two numbers is due to the fact that Date does not store the hours, minutes or seconds of the current time. Converting a Date to a Time will result in that day, midnight.

Github permission denied: ssh add agent has no identities

For my mac Big Sur, with gist from answers above, following steps work for me.

$ ssh-keygen -q -t rsa -N 'password' -f ~/.ssh/id_rsa
$ ssh-add ~/.ssh/id_rsa

And added ssh public key to git hub by following instruction;

https://docs.github.com/en/github/authenticating-to-github/adding-a-new-ssh-key-to-your-github-account

If all gone well, you should be able to get the following result;

$ ssh -T [email protected]
Hi user_name! You've successfully authenticated,...

Regarding 'main(int argc, char *argv[])'

argc is the number of command line arguments given to the program at runtime, and argv is an array of arrays of characters (rather, an array of C-strings) containing these arguments. If you know you're not going to need the command line arguments, you can declare your main at taking a void argument, instead:

int main(void) {
    /* ... */ 
}

Those are the only two prototypes defined for main as per the standards, but some compilers allow a return type of void as well. More on this on Wikipedia.

How to exit git log or git diff

In this case, as snarly suggested, typing q is the intended way to quit git log (as with most other pagers or applications that use pagers).

However normally, if you just want to abort a command that is currently executing, you can try ctrl+c (doesn't seem to work for git log, however) or ctrl+z (although in bash, ctrl-z will freeze the currently running foreground process, which can then be thawed as a background process with the bg command).

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

You had selected the time format wrong

<?php 
date_default_timezone_set('GMT');

echo date("Y-m-d,h:m:s");
?>

How can I simulate a click to an anchor tag?

Here is a complete test case that simulates the click event, calls all handlers attached (however they have been attached), maintains the "target" attribute ("srcElement" in IE), bubbles like a normal event would, and emulates IE's recursion-prevention. Tested in FF 2, Chrome 2.0, Opera 9.10 and of course IE (6):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function fakeClick(event, anchorObj) {
  if (anchorObj.click) {
    anchorObj.click()
  } else if(document.createEvent) {
    if(event.target !== anchorObj) {
      var evt = document.createEvent("MouseEvents"); 
      evt.initMouseEvent("click", true, true, window, 
          0, 0, 0, 0, 0, false, false, false, false, 0, null); 
      var allowDefault = anchorObj.dispatchEvent(evt);
      // you can check allowDefault for false to see if
      // any handler called evt.preventDefault().
      // Firefox will *not* redirect to anchorObj.href
      // for you. However every other browser will.
    }
  }
}
</script>
</head>
<body>

<div onclick="alert('Container clicked')">
  <a id="link" href="#" onclick="alert((event.target || event.srcElement).innerHTML)">Normal link</a>
</div>

<button type="button" onclick="fakeClick(event, document.getElementById('link'))">
  Fake Click on Normal Link
</button>

<br /><br />

<div onclick="alert('Container clicked')">
    <div onclick="fakeClick(event, this.getElementsByTagName('a')[0])"><a id="link2" href="#" onclick="alert('foo')">Embedded Link</a></div>
</div>

<button type="button" onclick="fakeClick(event, document.getElementById('link2'))">Fake Click on Embedded Link</button>

</body>
</html>

Demo here.

It avoids recursion in non-IE browsers by inspecting the event object that is initiating the simulated click, by inspecting the target attribute of the event (which remains unchanged during propagation).

Obviously IE does this internally holding a reference to its global event object. DOM level 2 defines no such global variable, so for that reason the simulator must pass in its local copy of event.

How can you run a Java program without main method?

Up to and including Java 6 it was possible to do this using the Static Initialization Block as was pointed out in the question Printing message on Console without using main() method. For instance using the following code:

public class Foo {
    static {
         System.out.println("Message");
         System.exit(0);
    } 
}

The System.exit(0) lets the program exit before the JVM is looking for the main method, otherwise the following error will be thrown:

Exception in thread "main" java.lang.NoSuchMethodError: main

In Java 7, however, this does not work anymore, even though it compiles, the following error will appear when you try to execute it:

The program compiled successfully, but main class was not found. Main class should contain method: public static void main (String[] args).

Here an alternative is to write your own launcher, this way you can define entry points as you want.

In the article JVM Launcher you will find the necessary information to get started:

This article explains how can we create a Java Virtual Machine Launcher (like java.exe or javaw.exe). It explores how the Java Virtual Machine launches a Java application. It gives you more ideas on the JDK or JRE you are using. This launcher is very useful in Cygwin (Linux emulator) with Java Native Interface. This article assumes a basic understanding of JNI.

How can I apply a border only inside a table?

If you are doing what I believe you are trying to do, you'll need something a little more like this:

table {
  border-collapse: collapse;
}
table td, table th {
  border: 1px solid black;
}
table tr:first-child th {
  border-top: 0;
}
table tr:last-child td {
  border-bottom: 0;
}
table tr td:first-child,
table tr th:first-child {
  border-left: 0;
}
table tr td:last-child,
table tr th:last-child {
  border-right: 0;
}

jsFiddle Demo

The problem is that you are setting a 'full border' around all the cells, which make it appear as if you have a border around the entire table.

Cheers.

EDIT: A little more info on those pseudo-classes can be found on quirksmode, and, as to be expected, you are pretty much S.O.L. in terms of IE support.

How do I write a batch script that copies one directory to another, replaces old files?

It seems that the latest function for this in windows 7 is robocopy.

Usage example:

robocopy <source> <destination> /e /xf <file to exclude> <another file>

/e copies subdirectories including empty ones, /xf excludes certain files from being copied.

More options here: http://technet.microsoft.com/en-us/library/cc733145(v=ws.10).aspx

How to save LogCat contents to file?

An additional tip if you want only the log shown in the past half hour with timestamps, or within another set time. Adjust date format to match your system. This one works on Ubuntu 16.04LTS:

adb shell logcat -d -v time -t "$(date '+%m-%d %H:%M:%S.%3N' -d '30 minutes ago')" > log_name.log

How to Generate Barcode using PHP and Display it as an Image on the same page

There is a library for this BarCode PHP. You just need to include a few files:

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

You can generate many types of barcodes, namely 1D or 2D. Add the required library:

require_once('class/BCGcode39.barcode.php');

Generate the colours:

// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);

After you have added all the codes, you will get this way:

Example

Since several have asked for an example here is what I was able to do to get it done

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

require_once('class/BCGcode128.barcode.php');

header('Content-Type: image/png');

$color_white = new BCGColor(255, 255, 255);

$code = new BCGcode128();
$code->parse('HELLO');

$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);

$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);

If you want to actually create the image file so you can save it then change

$drawing = new BCGDrawing('', $color_white);

to

$drawing = new BCGDrawing('image.png', $color_white);

MySQL: ignore errors when importing?

Use the --force (-f) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.

For example:

mysql -u userName -p -f -D dbName < script.sql

Programmatically add new column to DataGridView

Keep it simple

dataGridView1.Columns.Add("newColumnName", "Column Name in Text");

To add rows

dataGridView1.Rows.Add("Value for column#1"); // [,"column 2",...]

How do you access the value of an SQL count () query in a Java program

It's similar to above but you can try like

public Integer count(String tableName) throws CrateException {
        String query = String.format("Select count(*) as size from %s", tableName);
        try (Statement s = connection.createStatement()) {
            try (ResultSet resultSet = queryExecutor.executeQuery(s, query)) {
                Preconditions.checkArgument(resultSet.next(), "Result set is empty");
                return resultSet.getInt("size");
            }
        } catch (SQLException e) {
            throw new CrateException(e);
        }
    }
}

How to put a component inside another component in Angular2?

You don't put a component in directives

You register it in @NgModule declarations:

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App , MyChildComponent ],
  bootstrap: [ App ]
})

and then You just put it in the Parent's Template HTML as : <my-child></my-child>

That's it.

java.sql.SQLException: Exhausted Resultset

This occurs typically when the stmt is reused butexpecting a different ResultSet, try creting a new stmt and executeQuery. It fixed it for me!

How to enable php7 module in apache?

For Windows users looking for solution of same problem. I just repleced

LoadModule php7_module "C:/xampp/php/php7apache2_4.dll"

in my /conf/extra/http?-xampp.conf

Calling a phone number in swift

For swift 3.0

if let url = URL(string: "tel://\(number)"), UIApplication.shared.canOpenURL(url) {
    if #available(iOS 10, *) {
        UIApplication.shared.open(url)
    } else {
        UIApplication.shared.openURL(url)
    }
}
else {
    print("Your device doesn't support this feature.")
}

How do I find ' % ' with the LIKE operator in SQL Server?

Try this:

declare @var char(3)
set @var='[%]'
select Address from Accomodation where Address like '%'+@var+'%' 

You must use [] cancels the effect of wildcard, so you read % as a normal character, idem about character _

Javac is not found

You don't have jdk1.7.0_17 in your PATH - check again. There is only JRE which may not contain 'javac' compiler.

Besides it is best to set JAVA_HOME variable, and then include it in PATH.

How line ending conversions work with git core.autocrlf between different operating systems

Did some tests both on linux and windows. I use a test file containing lines ending in LF and also lines ending in CRLF.
File is committed , removed and then checked out. The value of core.autocrlf is set before commit and also before checkout. The result is below.

commit core.autocrlf false, remove, checkout core.autocrlf false: LF=>LF   CRLF=>CRLF  
commit core.autocrlf false, remove, checkout core.autocrlf input: LF=>LF   CRLF=>CRLF  
commit core.autocrlf false, remove, checkout core.autocrlf true : LF=>LF   CRLF=>CRLF  
commit core.autocrlf input, remove, checkout core.autocrlf false: LF=>LF   CRLF=>LF  
commit core.autocrlf input, remove, checkout core.autocrlf input: LF=>LF   CRLF=>LF  
commit core.autocrlf input, remove, checkout core.autocrlf true : LF=>CRLF CRLF=>CRLF  
commit core.autocrlf true, remove, checkout core.autocrlf false: LF=>LF   CRLF=>LF  
commit core.autocrlf true, remove, checkout core.autocrlf input: LF=>LF   CRLF=>LF  
commit core.autocrlf true,  remove, checkout core.autocrlf true : LF=>CRLF CRLF=>CRLF  

How do I call a Django function on button click?

here is a pure-javascript, minimalistic approach. I use JQuery but you can use any library (or even no libraries at all).

<html>
    <head>
        <title>An example</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script>
            function call_counter(url, pk) {
                window.open(url);
                $.get('YOUR_VIEW_HERE/'+pk+'/', function (data) {
                    alert("counter updated!");
                });
            }
        </script>
    </head>
    <body>
        <button onclick="call_counter('http://www.google.com', 12345);">
            I update object 12345
        </button>
        <button onclick="call_counter('http://www.yahoo.com', 999);">
            I update object 999
        </button>
    </body>
</html>

Alternative approach

Instead of placing the JavaScript code, you can change your link in this way:

<a target="_blank" 
    class="btn btn-info pull-right" 
    href="{% url YOUR_VIEW column_3_item.pk %}/?next={{column_3_item.link_for_item|urlencode:''}}">
    Check It Out
</a>

and in your views.py:

def YOUR_VIEW_DEF(request, pk):
    YOUR_OBJECT.objects.filter(pk=pk).update(views=F('views')+1)
    return HttpResponseRedirect(request.GET.get('next')))

How to perform a fade animation on Activity transition?

you can also use this code in your style.xml file so you don't need to write anything else in your activity.java

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowAnimationStyle">@style/AppTheme.WindowTransition</item>
</style>

<!-- Setting window animation -->
<style name="AppTheme.WindowTransition">
    <item name="android:windowEnterAnimation">@android:anim/fade_in</item>
    <item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>

Can you animate a height change on a UITableViewCell when selected?

I like the answer by Simon Lee. I didn't actually try that method but it looks like it would change the size of all the cells in the list. I was hoping for a change of just the cell that is tapped. I kinda did it like Simon but with just a little difference. This will change the look of a cell when it is selected. And it does animate. Just another way to do it.

Create an int to hold a value for the current selected cell index:

int currentSelection;

Then:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    int row = [indexPath row];
    selectedNumber = row;
    [tableView beginUpdates];
    [tableView endUpdates];
}

Then:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    if ([indexPath row] == currentSelection) {
        return  80;
    }
    else return 40;


}

I am sure you can make similar changes in tableView:cellForRowAtIndexPath: to change the type of cell or even load a xib file for the cell.

Like this, the currentSelection will start at 0. You would need to make adjustments if you didn't want the first cell of the list (at index 0) to look selected by default.

'^M' character at end of lines

An alternative to dos2unix command would be using standard utilities like sed.

For example, dos to unix:

sed 's/\r$//' dos.txt > unix.txt

unix to dos:

sed 's/$/\r/' unix.txt > dos.txt

Unique Key constraints for multiple columns in Entity Framework

If you're using Code-First, you can implement a custom extension HasUniqueIndexAnnotation

using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.ModelConfiguration.Configuration;

internal static class TypeConfigurationExtensions
{
    public static PrimitivePropertyConfiguration HasUniqueIndexAnnotation(
        this PrimitivePropertyConfiguration property, 
        string indexName,
        int columnOrder)
    {
        var indexAttribute = new IndexAttribute(indexName, columnOrder) { IsUnique = true };
        var indexAnnotation = new IndexAnnotation(indexAttribute);

        return property.HasColumnAnnotation(IndexAnnotation.AnnotationName, indexAnnotation);
    }
}

Then use it like so:

this.Property(t => t.Email)
    .HasColumnName("Email")
    .HasMaxLength(250)
    .IsRequired()
    .HasUniqueIndexAnnotation("UQ_User_EmailPerApplication", 0);

this.Property(t => t.ApplicationId)
    .HasColumnName("ApplicationId")
    .HasUniqueIndexAnnotation("UQ_User_EmailPerApplication", 1);

Which will result in this migration:

public override void Up()
{
    CreateIndex("dbo.User", new[] { "Email", "ApplicationId" }, unique: true, name: "UQ_User_EmailPerApplication");
}

public override void Down()
{
    DropIndex("dbo.User", "UQ_User_EmailPerApplication");
}

And eventually end up in database as:

CREATE UNIQUE NONCLUSTERED INDEX [UQ_User_EmailPerApplication] ON [dbo].[User]
(
    [Email] ASC,
    [ApplicationId] ASC
)

rails 3 validation on uniqueness on multiple attributes

In Rails 2, I would have written:

validates_uniqueness_of :zipcode, :scope => :recorded_at

In Rails 3:

validates :zipcode, :uniqueness => {:scope => :recorded_at}

For multiple attributes:

validates :zipcode, :uniqueness => {:scope => [:recorded_at, :something_else]}

Twitter bootstrap collapse: change display of toggle button

Add some jquery code, you need jquery to do this :

<script>
        $(".btn[data-toggle='collapse']").click(function() {
            if ($(this).text() == '+') {
                $(this).text('-');
            } else {
                $(this).text('+');
            }
        });
        </script>

isPrime Function for Python Language

With n**.5, you are not squaring n, but taking the square root.

Consider the number 20; the integer factors are 1, 2, 4, 5, 10, and 20. When you divide 20 by 2 and get 10, you know that it is also divisible by 10, without having to check. When you divide it by 4 and get 5, you know it is divisible by both 4 and 5, without having to check for 5.

After reaching this halfway point in the factors, you will have no more numbers to check which you haven't already recognized as factors earlier. Therefore, you only need to go halfway to see if something is prime, and this halfway point can be found by taking the number's square root.

Also, the reason 1 isn't a prime number is because prime numbers are defined as having 2 factors, 1 and itself. i.e 2 is 1*2, 3 is 1*3, 5 is 1*5. But 1 (1*1) only has 1 factor, itself. Therefore, it doesn't meet this definition.

How to return a html page from a restful controller in spring boot?

Follow below steps:

  1. Must put the html files in resources/templates/

  2. Replace the @RestController with @Controller

  3. Remove if you are using any view resolvers.

  4. Your controller method should return file name of view without extension like return "index"

  5. Include the below dependencies:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>`
    

How to expand and compute log(a + b)?

In general, one doesn't expand out log(a + b); you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:

log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)

(In fact, this identity is often used when implementing log in math libraries).

C++, How to determine if a Windows Process is running?

I found this today, it is from 2003. It finds a process by name, you don't even need the pid.

\#include windows.h

\#include tlhelp32.h

\#include iostream.h

int FIND_PROC_BY_NAME(const char *);

int main(int argc, char *argv[])

{

//  Check whether a process is currently running, or not

char szName[100]="notepad.exe";   // Name of process to find

int isRunning;

    isRunning=FIND_PROC_BY_NAME(szName);

    // Note: isRunning=0 means process not found, =1 means yes, it is found in memor
    return isRunning;
}

int FIND_PROC_BY_NAME(const char *szToFind)

// Created: 12/29/2000  (RK)

// Last modified: 6/16/2003  (RK)

// Please report any problems or bugs to [email protected]

// The latest version of this routine can be found at:

//     http://www.neurophys.wisc.edu/ravi/software/killproc/

// Check whether the process "szToFind" is currently running in memory

// This works for Win/95/98/ME and also Win/NT/2000/XP

// The process name is case-insensitive, i.e. "notepad.exe" and "NOTEPAD.EXE"

// will both work (for szToFind)

// Return codes are as follows:

//   0   = Process was not found

//   1   = Process was found

//   605 = Unable to search for process

//   606 = Unable to identify system type

//   607 = Unsupported OS

//   632 = Process name is invalid

// Change history:

//  3/10/2002   - Fixed memory leak in some cases (hSnapShot and

//                and hSnapShotm were not being closed sometimes)

//  6/13/2003   - Removed iFound (was not being used, as pointed out

//                by John Emmas)

{

    BOOL bResult,bResultm;
    DWORD aiPID[1000],iCb=1000,iNumProc,iV2000=0;
    DWORD iCbneeded,i;
    char szName[MAX_PATH],szToFindUpper[MAX_PATH];
    HANDLE hProc,hSnapShot,hSnapShotm;
    OSVERSIONINFO osvi;
    HINSTANCE hInstLib;
    int iLen,iLenP,indx;
    HMODULE hMod;
    PROCESSENTRY32 procentry;      
    MODULEENTRY32 modentry;

    // PSAPI Function Pointers.
     BOOL (WINAPI *lpfEnumProcesses)( DWORD *, DWORD cb, DWORD * );
     BOOL (WINAPI *lpfEnumProcessModules)( HANDLE, HMODULE *,
        DWORD, LPDWORD );
     DWORD (WINAPI *lpfGetModuleBaseName)( HANDLE, HMODULE,
        LPTSTR, DWORD );

      // ToolHelp Function Pointers.
      HANDLE (WINAPI *lpfCreateToolhelp32Snapshot)(DWORD,DWORD) ;
      BOOL (WINAPI *lpfProcess32First)(HANDLE,LPPROCESSENTRY32) ;
      BOOL (WINAPI *lpfProcess32Next)(HANDLE,LPPROCESSENTRY32) ;
      BOOL (WINAPI *lpfModule32First)(HANDLE,LPMODULEENTRY32) ;
      BOOL (WINAPI *lpfModule32Next)(HANDLE,LPMODULEENTRY32) ;

    // Transfer Process name into "szToFindUpper" and
    // convert it to upper case
    iLenP=strlen(szToFind);
    if(iLenP<1 || iLenP>MAX_PATH) return 632;
    for(indx=0;indx<iLenP;indx++)
        szToFindUpper[indx]=toupper(szToFind[indx]);
    szToFindUpper[iLenP]=0;

    // First check what version of Windows we're in
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    bResult=GetVersionEx(&osvi);
    if(!bResult)     // Unable to identify system version
        return 606;

    // At Present we only support Win/NT/2000 or Win/9x/ME
    if((osvi.dwPlatformId != VER_PLATFORM_WIN32_NT) &&
        (osvi.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS))
        return 607;

    if(osvi.dwPlatformId==VER_PLATFORM_WIN32_NT)
    {
        // Win/NT or 2000 or XP

         // Load library and get the procedures explicitly. We do
         // this so that we don't have to worry about modules using
         // this code failing to load under Windows 95, because
         // it can't resolve references to the PSAPI.DLL.
         hInstLib = LoadLibraryA("PSAPI.DLL");
         if(hInstLib == NULL)
            return 605;

         // Get procedure addresses.
         lpfEnumProcesses = (BOOL(WINAPI *)(DWORD *,DWORD,DWORD*))
            GetProcAddress( hInstLib, "EnumProcesses" ) ;
         lpfEnumProcessModules = (BOOL(WINAPI *)(HANDLE, HMODULE *,
            DWORD, LPDWORD)) GetProcAddress( hInstLib,
            "EnumProcessModules" ) ;
         lpfGetModuleBaseName =(DWORD (WINAPI *)(HANDLE, HMODULE,
            LPTSTR, DWORD )) GetProcAddress( hInstLib,
            "GetModuleBaseNameA" ) ;

         if( lpfEnumProcesses == NULL ||
            lpfEnumProcessModules == NULL ||
            lpfGetModuleBaseName == NULL)
            {
               FreeLibrary(hInstLib);
               return 605;
            }

        bResult=lpfEnumProcesses(aiPID,iCb,&iCbneeded);
        if(!bResult)
        {
            // Unable to get process list, EnumProcesses failed
            FreeLibrary(hInstLib);
            return 605;
        }

        // How many processes are there?
        iNumProc=iCbneeded/sizeof(DWORD);

        // Get and match the name of each process
        for(i=0;i<iNumProc;i++)
        {
            // Get the (module) name for this process

            strcpy(szName,"Unknown");
            // First, get a handle to the process
            hProc=OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,FALSE,
                aiPID[i]);
            // Now, get the process name
            if(hProc)
            {
               if(lpfEnumProcessModules(hProc,&hMod,sizeof(hMod),&iCbneeded) )
               {
                  iLen=lpfGetModuleBaseName(hProc,hMod,szName,MAX_PATH);
               }
            }
            CloseHandle(hProc);
            // Match regardless of lower or upper case
            if(strcmp(_strupr(szName),szToFindUpper)==0)
            {
                // Process found
                FreeLibrary(hInstLib);
                return 1;
            }
        }
    }

    if(osvi.dwPlatformId==VER_PLATFORM_WIN32_WINDOWS)
    {
        // Win/95 or 98 or ME

        hInstLib = LoadLibraryA("Kernel32.DLL");
        if( hInstLib == NULL )
            return FALSE ;

        // Get procedure addresses.
        // We are linking to these functions of Kernel32
        // explicitly, because otherwise a module using
        // this code would fail to load under Windows NT,
        // which does not have the Toolhelp32
        // functions in the Kernel 32.
        lpfCreateToolhelp32Snapshot=
            (HANDLE(WINAPI *)(DWORD,DWORD))
            GetProcAddress( hInstLib,
            "CreateToolhelp32Snapshot" ) ;
        lpfProcess32First=
            (BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))
            GetProcAddress( hInstLib, "Process32First" ) ;
        lpfProcess32Next=
            (BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))
            GetProcAddress( hInstLib, "Process32Next" ) ;
        lpfModule32First=
            (BOOL(WINAPI *)(HANDLE,LPMODULEENTRY32))
            GetProcAddress( hInstLib, "Module32First" ) ;
        lpfModule32Next=
            (BOOL(WINAPI *)(HANDLE,LPMODULEENTRY32))
            GetProcAddress( hInstLib, "Module32Next" ) ;
        if( lpfProcess32Next == NULL ||
            lpfProcess32First == NULL ||
            lpfModule32Next == NULL ||
            lpfModule32First == NULL ||
            lpfCreateToolhelp32Snapshot == NULL )
        {
            FreeLibrary(hInstLib);
            return 605;
        }

        // The Process32.. and Module32.. routines return names in all uppercase

        // Get a handle to a Toolhelp snapshot of all the systems processes.

        hSnapShot = lpfCreateToolhelp32Snapshot(
            TH32CS_SNAPPROCESS, 0 ) ;
        if( hSnapShot == INVALID_HANDLE_VALUE )
        {
            FreeLibrary(hInstLib);
            return 605;
        }

        // Get the first process' information.
        procentry.dwSize = sizeof(PROCESSENTRY32);
        bResult=lpfProcess32First(hSnapShot,&procentry);

        // While there are processes, keep looping and checking.
        while(bResult)
        {
            // Get a handle to a Toolhelp snapshot of this process.
            hSnapShotm = lpfCreateToolhelp32Snapshot(
                TH32CS_SNAPMODULE, procentry.th32ProcessID) ;
            if( hSnapShotm == INVALID_HANDLE_VALUE )
            {
                CloseHandle(hSnapShot);
                FreeLibrary(hInstLib);
                return 605;
            }
            // Get the module list for this process
            modentry.dwSize=sizeof(MODULEENTRY32);
            bResultm=lpfModule32First(hSnapShotm,&modentry);

            // While there are modules, keep looping and checking
            while(bResultm)
            {
                if(strcmp(modentry.szModule,szToFindUpper)==0)
                {
                    // Process found
                    CloseHandle(hSnapShotm);
                    CloseHandle(hSnapShot);
                    FreeLibrary(hInstLib);
                    return 1;
                }
                else
                {  // Look for next modules for this process
                    modentry.dwSize=sizeof(MODULEENTRY32);
                    bResultm=lpfModule32Next(hSnapShotm,&modentry);
                }
            }

            //Keep looking
            CloseHandle(hSnapShotm);
            procentry.dwSize = sizeof(PROCESSENTRY32);
            bResult = lpfProcess32Next(hSnapShot,&procentry);
        }
        CloseHandle(hSnapShot);
    }
    FreeLibrary(hInstLib);
    return 0;

}

Adding and using header (HTTP) in nginx

You can use upstream headers (named starting with $http_) and additional custom headers. For example:

add_header X-Upstream-01 $http_x_upstream_01;
add_header X-Hdr-01  txt01;

next, go to console and make request with user's header:

curl -H "X-Upstream-01: HEADER1" -I http://localhost:11443/

the response contains X-Hdr-01, seted by server and X-Upstream-01, seted by client:

HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Mon, 30 Nov 2015 23:54:30 GMT
Content-Type: text/html;charset=UTF-8
Connection: keep-alive
X-Hdr-01: txt01
X-Upstream-01: HEADER1

Disable ScrollView Programmatically?

I had a layout over the NestedScrollView consuming the touch event and disable the scroll:

progressBarLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return true;
            }
        });

and to enable:

progressBarLayout.setOnTouchListener(null);

python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

This takes the last. Not the maximum though:

In [10]: df.drop_duplicates(subset='A', keep="last")
Out[10]: 
   A   B
1  1  20
3  2  40
4  3  10

You can do also something like:

In [12]: df.groupby('A', group_keys=False).apply(lambda x: x.loc[x.B.idxmax()])
Out[12]: 
   A   B
A       
1  1  20
2  2  40
3  3  10

Disable submit button ONLY after submit

Reading the comments, it seems that these solutions are not consistent across browsers. Decided then to think how I would have done this 10 years ago before the advent of jQuery and event function binding.

So here is my retro hipster solution:

<script type="text/javascript">
var _formConfirm_submitted = false;
</script>
<form name="frmConfirm" onsubmit="if( _formConfirm_submitted == false ){ _formConfirm_submitted = true;return true }else{ alert('your request is being processed!'); return false;  }" action="" method="GET">

<input type="submit" value="submit - but only once!"/>
</form>

The main point of difference is that I am relying on the ability to stop a form submitting through returning false on the submit handler, and I am using a global flag variable - which will make me go straight to hell!

But on the plus side, I cannot imagine any browser compatibility issues - hey, it would probably even work in Netscape!

How to copy a folder via cmd?

xcopy  e:\source_folder f:\destination_folder /e /i /h

The /h is just in case there are hidden files. The /i creates a destination folder if there are muliple source files.

SQL Server - Adding a string to a text column (concat equivalent)

like said before best would be to set datatype of the column to nvarchar(max), but if that's not possible you can do the following using cast or convert:

-- create a test table 
create table test (
    a text
) 
-- insert test value
insert into test (a) values ('this is a text')
-- the following does not work !!!
update test set a = a + ' and a new text added'
-- but this way it works: 
update test set a = cast ( a as nvarchar(max))  + cast (' and a new text added' as nvarchar(max) )
-- test result
select * from test
-- column a contains:
this is a text and a new text added

hope that helps

DateTime2 vs DateTime in SQL Server

The MSDN documentation for datetime recommends using datetime2. Here is their recommendation:

Use the time, date, datetime2 and datetimeoffset data types for new work. These types align with the SQL Standard. They are more portable. time, datetime2 and datetimeoffset provide more seconds precision. datetimeoffset provides time zone support for globally deployed applications.

datetime2 has larger date range, a larger default fractional precision, and optional user-specified precision. Also depending on the user-specified precision it may use less storage.

Interfaces with static fields in java for sharing 'constants'

Instead of implementing a "constants interface", in Java 1.5+, you can use static imports to import the constants/static methods from another class/interface:

import static com.kittens.kittenpolisher.KittenConstants.*;

This avoids the ugliness of making your classes implement interfaces that have no functionality.

As for the practice of having a class just to store constants, I think it's sometimes necessary. There are certain constants that just don't have a natural place in a class, so it's better to have them in a "neutral" place.

But instead of using an interface, use a final class with a private constructor. (Making it impossible to instantiate or subclass the class, sending a strong message that it doesn't contain non-static functionality/data.)

Eg:

/** Set of constants needed for Kitten Polisher. */
public final class KittenConstants
{
    private KittenConstants() {}

    public static final String KITTEN_SOUND = "meow";
    public static final double KITTEN_CUTENESS_FACTOR = 1;
}

Android XML Percent Symbol

to escape the percent symbol, you just need %%

for example :

String.format("%1$d%%", 10)

returns "10%"

onclick event pass <li> id or value

<li>s don't have a value - only form inputs do. In fact, you're not supposed to even include the value attribute in the HTML for <li>s.

You can rely on .innerHTML instead:

getPaging(this.innerHTML)

Or maybe the id:

getPaging(this.id);

However, it's easier (and better practice) to add the click handlers from JavaScript code, and not include them in the HTML. Seeing as you're already using jQuery, this can easily be done by changing your HTML to:

<li class="clickMe">1</li>
<li class="clickMe">2</li>

And use the following JavaScript:

$(function () {
    $('.clickMe').click(function () {
        var str = $(this).text();
        $('#loading-content').load('dataSearch.php?' + str, hideLoader);
    });
});

This will add the same click handler to all your <li class="clickMe">s, without requiring you to duplicate your onclick="getPaging(this.value)" code for each of them.

Get yesterday's date in bash on Linux, DST-safe

you can use

date -d "30 days ago" +"%d/%m/%Y"

to get the date from 30 days ago, similarly you can replace 30 with x amount of days

Regular expression for not allowing spaces in the input field

If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()

Than Below string will work

'^\\S*$'

It's same regex @Bergi mentioned just the string version for new RegExp constructor

Google Maps V3 marker with label

Support for single character marker labels was added to Google Maps in version 3.21 (Aug 2015). See the new marker label API.

You can now create your label marker like this:

var marker = new google.maps.Marker({
  position: new google.maps.LatLng(result.latitude, result.longitude), 
  icon: markerIcon,
  label: {
    text: 'A'
  }
});

If you would like to see the 1 character restriction removed, please vote for this issue.

Update October 2016:

This issue was fixed and as of version 3.26.10, Google Maps natively supports multiple character labels in combination with custom icons using MarkerLabels.

What is boilerplate code?

From whatis.techtarget.com :

In information technology, a boilerplate is a unit of writing that can be reused over and over without change. By extension, the idea is sometimes applied to reusable programming as in "boilerplate code." The term derives from steel manufacturing, where boilerplate is steel rolled into large plates for use in steam boilers. The implication is either that boilerplate writing has been time-tested and strong as "steel," or possibly that it has been rolled out into something strong enough for repeated reuse.

Beyond programming :

A boilerplate can be compared to a certain kind of template, which can be thought of as a fill-in-the-blanks boilerplate. Some typical boilerplates include: mission statements, safety warnings, commonly used installation procedures, copyright statements, and responsibility disclaimers.

In my experience as a programmer, the proper kind of boilerplate code is typically a bunch of code that you start off with that's not large and/or complicated enough to be called a framework.

A typical example would be the HTML5 Boilerplate.

How do I update the password for Git?

Tried everything but nothing worked. Then the following did work.

  1. Before any of the above steps, lock and unlock the keychain again coz sometimes it sorta gets stuck.
  2. Install the GitHub Desktop — it helps.

Complex JSON nesting of objects and arrays

Make sure you follow the language definition for JSON. In your second example, the section:

"labs":[{
    ""
}]

Is invalid since an object must be composed of zero or more key-value pairs "a" : "b", where "b" may be any valid value. Some parsers may automatically interpret { "" } to be { "" : null }, but this is not a clearly defined case.

Also, you are using a nested array of objects [{}] quite a bit. I would only do this if:

  1. There is no good "identifier" string for each object in the array.
  2. There is some clear reason for having an array over a key-value for that entry.

What's the difference between jquery.js and jquery.min.js?

In easy language, both versions are absolutely the same. Only difference is:

  • min.js is for websites (online)

  • .js is for developers, guys who needs to read, learn about or/and understand jquery codes, for ie plugin development (offline, local work).

Docker - Ubuntu - bash: ping: command not found

Generally people pull the official image of Ubuntu/CentOS but they don't realize that these images are minimal and doesn't have any thing on the top of that.

For Ubuntu, this image is built from official rootfs tarballs provided by Canonical. Given that it is a minimal install of Ubuntu, this image only includes the C, C.UTF-8, and POSIX locales by default.

One can install net-tools (includes ifconfig, netstat), ip-utils(includes ping) andy other likes curl etc on container and can create image from container or can write Dockerfile that will install these tool while creating image.

Below is Dockerfile example, while creating image from this it will include these tools:

FROM vkitpro/ubuntu16.04
RUN     apt-get  update -y \
&& apt-get upgrade -y \
&& apt-get install iputils-ping -y \
&& apt-get install net-tools -y \
CMD bash

or launch container from base image and install these utilities on container and then commit to image. docker commit -m "any descriptive message" container_id image_name:lattest

That image will have all thing installed.

No module named MySQLdb

mysqldb is a module for Python that doesn't come pre-installed or with Django. You can download mysqldb here.

Best way to integrate Python and JavaScript?

How about pyjs?

From the above website:

pyjs is a Rich Internet Application (RIA) Development Platform for both Web and Desktop. With pyjs you can write your JavaScript-powered web applications entirely in Python.

Use of "instanceof" in Java

Basically, you check if an object is an instance of a specific class. You normally use it, when you have a reference or parameter to an object that is of a super class or interface type and need to know whether the actual object has some other type (normally more concrete).

Example:

public void doSomething(Number param) {
  if( param instanceof Double) {
    System.out.println("param is a Double");
  }
  else if( param instanceof Integer) {
    System.out.println("param is an Integer");
  }

  if( param instanceof Comparable) {
    //subclasses of Number like Double etc. implement Comparable
    //other subclasses might not -> you could pass Number instances that don't implement that interface
    System.out.println("param is comparable"); 
  }
}

Note that if you have to use that operator very often it is generally a hint that your design has some flaws. So in a well designed application you should have to use that operator as little as possible (of course there are exceptions to that general rule).

How can I align all elements to the left in JPanel?

The easiest way I've found to place objects on the left is using FlowLayout.

JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));

adding a component normally to this panel will place it on the left

max value of integer

The strict equivalent of the java int is long int in C.

Edit: If int32_t is defined, then it is the equivalent in terms of precision. long int guarantee the precision of the java int, because it is guarantee to be at least 32 bits in size.

Android: Share plain text using intent (to all messaging apps)

Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");

Intent shareIntent = Intent.createChooser(sendIntent, null);
startActivity(shareIntent);

Regex that accepts only numbers (0-9) and NO characters

Your regex ^[0-9] matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $ to the end:

^[0-9]*$

This accepts any number of digits, including none. To accept one or more digits, change the * to +. To accept exactly one digit, just remove the *.

UPDATE: You mixed up the arguments to IsMatch. The pattern should be the second argument, not the first:

if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))

CAUTION: In JavaScript, \d is equivalent to [0-9], but in .NET, \d by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9] (or supply the RegexOptions.ECMAScript flag).

Get the _id of inserted document in Mongo database in NodeJS

I actually did a console.log() for the second parameter in the callback function for insert. There is actually a lot of information returned apart from the inserted object itself. So the code below explains how you can access it's id.

collection.insert(objToInsert, function (err, result){
    if(err)console.log(err);
    else {
        console.log(result["ops"][0]["_id"]);
        // The above statement will output the id of the 
        // inserted object
       }
});

Remove file from SVN repository without deleting local copy

In TortoiseSVN, you can also Shift + right-click to get a menu that includes "Delete (keep local)".

HTML5 Canvas background image

Theres a few ways you can do this. You can either add a background to the canvas you are currently working on, which if the canvas isn't going to be redrawn every loop is fine. Otherwise you can make a second canvas underneath your main canvas and draw the background to it. The final way is to just use a standard <img> element placed under the canvas. To draw a background onto the canvas element you can do something like the following:

Live Demo

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");

canvas.width = 903;
canvas.height = 657;


var background = new Image();
background.src = "http://www.samskirrow.com/background.png";

// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
    ctx.drawImage(background,0,0);   
}

// Draw whatever else over top of it on the canvas.

Text size and different android screen sizes

I did same by dimension and paint something like (with dp but only for text and in drawText())

XML:

   <dimen name="text_size">30sp</dimen>

Code:

   Paint p =new Paint();
       p.setTextSize(getResources().getDimension(R.dimen.text_Size));

What's the difference between an Angular component and module

Well, it's too late to post an answer, but I feel my explanation will be easy to understand for beginners with Angular. The following is one of the examples that I give during my presentation.

Consider your angular Application as a building. A building can have N number of apartments in it. An apartment is considered as a module. An Apartment can then have N number of rooms which correspond to the building blocks of an Angular application named components.

Now each apartment (Module)` will have rooms (Components), lifts (Services) to enable larger movement in and out the apartments, wires (Pipes) to transform around and make it useful in the apartments.

You will also have places like swimming pool, tennis court which are being shared by all building residents. So these can be considered as components inside SharedModule.

Basically, the difference is as follows,

Table showing key differences between Module and Component

Follow my slides to understand the building blocks of an Angular application

Here is my session on Building Blocks of Angular for beginners

What is REST? Slightly confused

REST is a software design pattern typically used for web applications. In layman's terms this means that it is a commonly used idea used in many different projects. It stands for REpresentational State Transfer. The basic idea of REST is treating objects on the server-side (as in rows in a database table) as resources than can be created or destroyed.

The most basic way of thinking about REST is as a way of formatting the URLs of your web applications. For example, if your resource was called "posts", then:

/posts Would be how a user would access ALL the posts, for displaying.

/posts/:id Would be how a user would access and view an individual post, retrieved based on their unique id.

/posts/new Would be how you would display a form for creating a new post.

Sending a POST request to /users would be how you would actually create a new post on the database level.

Sending a PUT request to /users/:id would be how you would update the attributes of a given post, again identified by a unique id.

Sending a DELETE request to /users/:id would be how you would delete a given post, again identified by a unique id.

As I understand it, the REST pattern was mainly popularized (for web apps) by the Ruby on Rails framework, which puts a big emphasis on RESTful routes. I could be wrong about that though.

I may not be the most qualified to talk about it, but this is how I've learned it (specifically for Rails development).

When someone refers to a "REST api," generally what they mean is an api that uses RESTful urls for retrieving data.

How to create a fixed sidebar layout with Bootstrap 4?

My version:

div#dashmain { margin-left:150px; }
div#dashside {position:fixed; width:150px; height:100%; }
<div id="dashside"></div>
<div id="dashmain">                        
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">Content</div>
        </div>            
    </div>        
</div>

Move textfield when keyboard appears swift

If you're using Auto Layout, I assume you've set the Bottom Space to Superview constraint. If that's the case, you simply have to update the constraint's value. Here's how you do it with a little bit of animation.

func keyboardWasShown(notification: NSNotification) {
    let info = notification.userInfo!
    let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()

    UIView.animateWithDuration(0.1, animations: { () -> Void in
        self.bottomConstraint.constant = keyboardFrame.size.height + 20
    })
}

The hardcoded 20 is added only to pop the textfield above the keyboard just a bit. Otherwise the keyboard's top margin and textfield's bottom margin would be touching.

When the keyboard is dismissed, reset the constraint's value to its original one.

java.net.UnknownHostException: Invalid hostname for server: local

Trying to connect to your local computer.try with the hostname "localhost" instead or perhaps ::/ - the last one is ipv6

Javascript Print iframe contents only

At this time, there is no need for the script tag inside the iframe. This works for me (tested in Chrome, Firefox, IE11 and node-webkit 0.12):

<script>
window.onload = function() {
    var body = 'dddddd';
    var newWin = document.getElementById('printf').contentWindow;
    newWin.document.write(body);
    newWin.document.close(); //important!
    newWin.focus(); //IE fix
    newWin.print();
}
</script>

<iframe id="printf"></iframe>

Thanks to all answers, save my day.

iOS 7 UIBarButton back button arrow color

If you are using storyboards you could set the navigation bar tint colour.

enter image description here

enter image description here

mongodb: insert if not exists

I don't think mongodb supports this type of selective upserting. I have the same problem as LeMiz, and using update(criteria, newObj, upsert, multi) doesn't work right when dealing with both a 'created' and 'updated' timestamp. Given the following upsert statement:

update( { "name": "abc" }, 
        { $set: { "created": "2010-07-14 11:11:11", 
                  "updated": "2010-07-14 11:11:11" }},
        true, true ) 

Scenario #1 - document with 'name' of 'abc' does not exist: New document is created with 'name' = 'abc', 'created' = 2010-07-14 11:11:11, and 'updated' = 2010-07-14 11:11:11.

Scenario #2 - document with 'name' of 'abc' already exists with the following: 'name' = 'abc', 'created' = 2010-07-12 09:09:09, and 'updated' = 2010-07-13 10:10:10. After the upsert, the document would now be the same as the result in scenario #1. There's no way to specify in an upsert which fields be set if inserting, and which fields be left alone if updating.

My solution was to create a unique index on the critera fields, perform an insert, and immediately afterward perform an update just on the 'updated' field.

How to get started with Windows 7 gadgets

I have started writing one tutorial for everyone on this topic, see making gadgets for Windows 7.

Removing a list of characters in string

If you're using python2 and your inputs are strings (not unicodes), the absolutely best method is str.translate:

>>> chars_to_remove = ['.', '!', '?']
>>> subj = 'A.B!C?'
>>> subj.translate(None, ''.join(chars_to_remove))
'ABC'

Otherwise, there are following options to consider:

A. Iterate the subject char by char, omit unwanted characters and join the resulting list:

>>> sc = set(chars_to_remove)
>>> ''.join([c for c in subj if c not in sc])
'ABC'

(Note that the generator version ''.join(c for c ...) will be less efficient).

B. Create a regular expression on the fly and re.sub with an empty string:

>>> import re
>>> rx = '[' + re.escape(''.join(chars_to_remove)) + ']'
>>> re.sub(rx, '', subj)
'ABC'

(re.escape ensures that characters like ^ or ] won't break the regular expression).

C. Use the mapping variant of translate:

>>> chars_to_remove = [u'd', u'G', u'?']
>>> subj = u'A?BdCG'
>>> dd = {ord(c):None for c in chars_to_remove}
>>> subj.translate(dd)
u'ABC'

Full testing code and timings:

#coding=utf8

import re

def remove_chars_iter(subj, chars):
    sc = set(chars)
    return ''.join([c for c in subj if c not in sc])

def remove_chars_re(subj, chars):
    return re.sub('[' + re.escape(''.join(chars)) + ']', '', subj)

def remove_chars_re_unicode(subj, chars):
    return re.sub(u'(?u)[' + re.escape(''.join(chars)) + ']', '', subj)

def remove_chars_translate_bytes(subj, chars):
    return subj.translate(None, ''.join(chars))

def remove_chars_translate_unicode(subj, chars):
    d = {ord(c):None for c in chars}
    return subj.translate(d)

import timeit, sys

def profile(f):
    assert f(subj, chars_to_remove) == test
    t = timeit.timeit(lambda: f(subj, chars_to_remove), number=1000)
    print ('{0:.3f} {1}'.format(t, f.__name__))

print (sys.version)
PYTHON2 = sys.version_info[0] == 2

print ('\n"plain" string:\n')

chars_to_remove = ['.', '!', '?']
subj = 'A.B!C?' * 1000
test = 'ABC' * 1000

profile(remove_chars_iter)
profile(remove_chars_re)

if PYTHON2:
    profile(remove_chars_translate_bytes)
else:
    profile(remove_chars_translate_unicode)

print ('\nunicode string:\n')

if PYTHON2:
    chars_to_remove = [u'd', u'G', u'?']
    subj = u'A?BdCG'
else:
    chars_to_remove = ['d', 'G', '?']
    subj = 'A?BdCG'

subj = subj * 1000
test = 'ABC' * 1000

profile(remove_chars_iter)

if PYTHON2:
    profile(remove_chars_re_unicode)
else:
    profile(remove_chars_re)

profile(remove_chars_translate_unicode)

Results:

2.7.5 (default, Mar  9 2014, 22:15:05) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)]

"plain" string:

0.637 remove_chars_iter
0.649 remove_chars_re
0.010 remove_chars_translate_bytes

unicode string:

0.866 remove_chars_iter
0.680 remove_chars_re_unicode
1.373 remove_chars_translate_unicode

---

3.4.2 (v3.4.2:ab2c023a9432, Oct  5 2014, 20:42:22) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]

"plain" string:

0.512 remove_chars_iter
0.574 remove_chars_re
0.765 remove_chars_translate_unicode

unicode string:

0.817 remove_chars_iter
0.686 remove_chars_re
0.876 remove_chars_translate_unicode

(As a side note, the figure for remove_chars_translate_bytes might give us a clue why the industry was reluctant to adopt Unicode for such a long time).

How can I convert a string to upper- or lower-case with XSLT?

upper-case(string) and lower-case(string)

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

You're not reading the file content:

my_file_contents = f.read()

See the docs for further infos

You could, without calling read() or readlines() loop over your file object:

f = open('goodlines.txt')
for line in f:
    print(line)

If you want a list out of it (without \n as you asked)

my_list = [line.rstrip('\n') for line in f]

Detect whether current Windows version is 32 bit or 64 bit

Check the Registry for the existence of HKLM\SOFTWARE\Wow6432Node - If it's there, the system is 64-bit - 32-bit, otherwise.

Jackson overcoming underscores in favor of camel-case

If you want this for a Single Class, you can use the PropertyNamingStrategy with the @JsonNaming, something like this:

@JsonNaming(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy.class)
public static class Request {

    String businessName;
    String businessLegalName;

}

Will serialize to:

{
    "business_name" : "",
    "business_legal_name" : ""
}

Since Jackson 2.7 the LowerCaseWithUnderscoresStrategy in deprecated in favor of SnakeCaseStrategy, so you should use:

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public static class Request {

    String businessName;
    String businessLegalName;

}

How to create a collapsing tree table in html/css/js?

In modern browsers, you need only very little to code to create a collapsible tree :

_x000D_
_x000D_
var tree = document.querySelectorAll('ul.tree a:not(:last-child)');_x000D_
for(var i = 0; i < tree.length; i++){_x000D_
    tree[i].addEventListener('click', function(e) {_x000D_
        var parent = e.target.parentElement;_x000D_
        var classList = parent.classList;_x000D_
        if(classList.contains("open")) {_x000D_
            classList.remove('open');_x000D_
            var opensubs = parent.querySelectorAll(':scope .open');_x000D_
            for(var i = 0; i < opensubs.length; i++){_x000D_
                opensubs[i].classList.remove('open');_x000D_
            }_x000D_
        } else {_x000D_
            classList.add('open');_x000D_
        }_x000D_
        e.preventDefault();_x000D_
    });_x000D_
}
_x000D_
body {_x000D_
    font-family: Arial;_x000D_
}_x000D_
_x000D_
ul.tree li {_x000D_
    list-style-type: none;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
ul.tree li ul {_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
ul.tree li.open > ul {_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
ul.tree li a {_x000D_
    color: black;_x000D_
    text-decoration: none;_x000D_
}_x000D_
_x000D_
ul.tree li a:before {_x000D_
    height: 1em;_x000D_
    padding:0 .1em;_x000D_
    font-size: .8em;_x000D_
    display: block;_x000D_
    position: absolute;_x000D_
    left: -1.3em;_x000D_
    top: .2em;_x000D_
}_x000D_
_x000D_
ul.tree li > a:not(:last-child):before {_x000D_
    content: '+';_x000D_
}_x000D_
_x000D_
ul.tree li.open > a:not(:last-child):before {_x000D_
    content: '-';_x000D_
}
_x000D_
<ul class="tree">_x000D_
  <li><a href="#">Part 1</a>_x000D_
    <ul>_x000D_
      <li><a href="#">Item A</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item B</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item C</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item D</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item E</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </li>_x000D_
_x000D_
  <li><a href="#">Part 2</a>_x000D_
    <ul>_x000D_
      <li><a href="#">Item A</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item B</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item C</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item D</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item E</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </li>_x000D_
_x000D_
  <li><a href="#">Part 3</a>_x000D_
    <ul>_x000D_
      <li><a href="#">Item A</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item B</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item C</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item D</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item E</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

(see also this Fiddle)

Pressing Ctrl + A in Selenium WebDriver

WebDriver driver = new FirefoxDriver();

Actions action = new Actions(driver); 

action.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();

This method removes the extra call ( String.ValueOf() ) to convert unicode to string.

Add an index (numeric ID) column to large data frame

If your data.frame is a data.table, you can use special symbol .I:

data[, ID := .I]

PHP - Check if the page run on Mobile or Desktop browser

There is a very nice PHP library for detecting mobile clients here: http://mobiledetect.net

Using that it's quite easy to only display content for a mobile:

include 'Mobile_Detect.php';
$detect = new Mobile_Detect();

// Check for any mobile device.
if ($detect->isMobile()){
   // mobile content
}
else {
   // other content for desktops
}

How to preview git-pull without doing fetch?

I may be late to the party, but this is something which bugged me for too long. In my experience, I would rather want to see which changes are pending than update my working copy and deal with those changes.

This goes in the ~/.gitconfig file:

[alias]
        diffpull=!git fetch && git diff HEAD..@{u}

It fetches the current branch, then does a diff between the working copy and this fetched branch. So you should only see the changes that would come with git pull.

Send and receive messages through NSNotificationCenter in Objective-C?

if you're using NSNotificationCenter for updating your view, don't forget to send it from the main thread by calling dispatch_async:

dispatch_async(dispatch_get_main_queue(),^{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"my_notification" object:nil];
});

How to open this .DB file?

I don't think there is a way to tell which program to use from just the .db extension. It could even be an encrypted database which can't be opened. You can MS Access, or a sqlite manager.

Edit: Try to rename the file to .txt and open it with a text editor. The first couple of words in the file could tell you the DB Type.

If it is a SQLite database, it will start with "SQLite format 3"

How to add,set and get Header in request of HttpClient?

You can test-drive this code exactly as is using the public GitHub API (don't go over the request limit):

public class App {

    public static void main(String[] args) throws IOException {

        CloseableHttpClient client = HttpClients.custom().build();

        // (1) Use the new Builder API (from v4.3)
        HttpUriRequest request = RequestBuilder.get()
                .setUri("https://api.github.com")
                // (2) Use the included enum
                .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                // (3) Or your own
                .setHeader("Your own very special header", "value")
                .build();

        CloseableHttpResponse response = client.execute(request);

        // (4) How to read all headers with Java8
        List<Header> httpHeaders = Arrays.asList(response.getAllHeaders());
        httpHeaders.stream().forEach(System.out::println);

        // close client and response
    }
}

scikit-learn random state in splitting dataset

random_state is None by default which means every time when you run your program you will get different output because of splitting between train and test varies within.

random_state = any int value means every time when you run your program you will get tehe same output because of splitting between train and test does not varies within.

How to update PATH variable permanently from Windows command line?

You can use:

setx PATH "%PATH%;C:\\Something\\bin"

However, setx will truncate the stored string to 1024 bytes, potentially corrupting the PATH.

/M will change the PATH in HKEY_LOCAL_MACHINE instead of HKEY_CURRENT_USER. In other words, a system variable, instead of the user's. For example:

SETX /M PATH "%PATH%;C:\your path with spaces"

You have to keep in mind, the new PATH is not visible in your current cmd.exe.

But if you look in the registry or on a new cmd.exe with "set p" you can see the new value.

What does ECU units, CPU core and memory mean when I launch a instance

ECU = EC2 Compute Unit. More from here: http://aws.amazon.com/ec2/faqs/#What_is_an_EC2_Compute_Unit_and_why_did_you_introduce_it

Amazon EC2 uses a variety of measures to provide each instance with a consistent and predictable amount of CPU capacity. In order to make it easy for developers to compare CPU capacity between different instance types, we have defined an Amazon EC2 Compute Unit. The amount of CPU that is allocated to a particular instance is expressed in terms of these EC2 Compute Units. We use several benchmarks and tests to manage the consistency and predictability of the performance from an EC2 Compute Unit. One EC2 Compute Unit provides the equivalent CPU capacity of a 1.0-1.2 GHz 2007 Opteron or 2007 Xeon processor. This is also the equivalent to an early-2006 1.7 GHz Xeon processor referenced in our original documentation. Over time, we may add or substitute measures that go into the definition of an EC2 Compute Unit, if we find metrics that will give you a clearer picture of compute capacity.

INSERT INTO...SELECT for all MySQL columns

The correct syntax is described in the manual. Try this:

INSERT INTO this_table_archive (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00';

If the id columns is an auto-increment column and you already have some data in both tables then in some cases you may want to omit the id from the column list and generate new ids instead to avoid insert an id that already exists in the original table. If your target table is empty then this won't be an issue.

How to count down in for loop?

In python, when you have an iterable, usually you iterate without an index:

letters = 'abcdef' # or a list, tupple or other iterable
for l in letters:
    print(l)

If you need to traverse the iterable in reverse order, you would do:

for l in letters[::-1]:
    print(l)

When for any reason you need the index, you can use enumerate:

for i, l in enumerate(letters, start=1): #start is 0 by default
    print(i,l)

You can enumerate in reverse order too...

for i, l in enumerate(letters[::-1])
    print(i,l)

ON ANOTHER NOTE...

Usually when we traverse an iterable we do it to apply the same procedure or function to each element. In these cases, it is better to use map:

If we need to capitilize each letter:

map(str.upper, letters)

Or get the Unicode code of each letter:

map(ord, letters)

WARNING: UNPROTECTED PRIVATE KEY FILE! when trying to SSH into Amazon EC2 Instance

Change the File Permission using chmod command

sudo chmod 700 keyfile.pem

What does $@ mean in a shell script?

$@ is nearly the same as $*, both meaning "all command line arguments". They are often used to simply pass all arguments to another program (thus forming a wrapper around that other program).

The difference between the two syntaxes shows up when you have an argument with spaces in it (e.g.) and put $@ in double quotes:

wrappedProgram "$@"
# ^^^ this is correct and will hand over all arguments in the way
#     we received them, i. e. as several arguments, each of them
#     containing all the spaces and other uglinesses they have.
wrappedProgram "$*"
# ^^^ this will hand over exactly one argument, containing all
#     original arguments, separated by single spaces.
wrappedProgram $*
# ^^^ this will join all arguments by single spaces as well and
#     will then split the string as the shell does on the command
#     line, thus it will split an argument containing spaces into
#     several arguments.

Example: Calling

wrapper "one two    three" four five "six seven"

will result in:

"$@": wrappedProgram "one two    three" four five "six seven"
"$*": wrappedProgram "one two    three four five six seven"
                             ^^^^ These spaces are part of the first
                                  argument and are not changed.
$*:   wrappedProgram one two three four five six seven

Make absolute positioned div expand parent div height

Try this, it was worked for me

.child {
    width: 100%;
    position: absolute;
    top: 0px;
    bottom: 0px;
    z-index: 1;
}

It will set child height to parent height

Render Partial View Using jQuery in ASP.NET MVC

@tvanfosson rocks with his answer.

However, I would suggest an improvement within js and a small controller check.

When we use @Url helper to call an action, we are going to receive a formatted html. It would be better to update the content (.html) not the actual element (.replaceWith).

More about at: What's the difference between jQuery's replaceWith() and html()?

$.get( '@Url.Action("details","user", new { id = Model.ID } )', function(data) {
    $('#detailsDiv').html(data);
}); 

This is specially useful in trees, where the content can be changed several times.

At the controller we can reuse the action depending on requester:

public ActionResult Details( int id )
{
    var model = GetFooModel();
    if (Request.IsAjaxRequest())
    {
        return PartialView( "UserDetails", model );
    }
    return View(model);
}

Absolute positioning ignoring padding of parent

Could have easily done using an extra level of Div.

<div style="background-color: blue; padding: 10px; position: relative; height: 100px;">
  <div style="position: absolute; left: 0px; right: 0px; bottom: 10px; padding:0px 10px;">
    <div style="background-color: gray;">css sux</div>
  </div>
</div>

Demo: https://jsfiddle.net/soxv3vr0/

Binding a WPF ComboBox to a custom list

You set the DisplayMemberPath and the SelectedValuePath to "Name", so I assume that you have a class PhoneBookEntry with a public property Name.

Have you set the DataContext to your ConnectionViewModel object?

I copied you code and made some minor modifications, and it seems to work fine. I can set the viewmodels PhoneBookEnty property and the selected item in the combobox changes, and I can change the selected item in the combobox and the view models PhoneBookEntry property is set correctly.

Here is my XAML content:

<Window x:Class="WpfApplication6.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
<Grid>
    <StackPanel>
        <Button Click="Button_Click">asdf</Button>
        <ComboBox ItemsSource="{Binding Path=PhonebookEntries}"
                  DisplayMemberPath="Name"
                  SelectedValuePath="Name"
                  SelectedValue="{Binding Path=PhonebookEntry}" />
    </StackPanel>
</Grid>
</Window>

And here is my code-behind:

namespace WpfApplication6
{

    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            ConnectionViewModel vm = new ConnectionViewModel();
            DataContext = vm;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ((ConnectionViewModel)DataContext).PhonebookEntry = "test";
        }
    }

    public class PhoneBookEntry
    {
        public string Name { get; set; }

        public PhoneBookEntry(string name)
        {
            Name = name;
        }

        public override string ToString()
        {
            return Name;
        }
    }

    public class ConnectionViewModel : INotifyPropertyChanged
    {
        public ConnectionViewModel()
        {
            IList<PhoneBookEntry> list = new List<PhoneBookEntry>();
            list.Add(new PhoneBookEntry("test"));
            list.Add(new PhoneBookEntry("test2"));
            _phonebookEntries = new CollectionView(list);
        }

        private readonly CollectionView _phonebookEntries;
        private string _phonebookEntry;

        public CollectionView PhonebookEntries
        {
            get { return _phonebookEntries; }
        }

        public string PhonebookEntry
        {
            get { return _phonebookEntry; }
            set
            {
                if (_phonebookEntry == value) return;
                _phonebookEntry = value;
                OnPropertyChanged("PhonebookEntry");
            }
        }

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}

Edit: Geoffs second example does not seem to work, which seems a bit odd to me. If I change the PhonebookEntries property on the ConnectionViewModel to be of type ReadOnlyCollection, the TwoWay binding of the SelectedValue property on the combobox works fine.

Maybe there is an issue with the CollectionView? I noticed a warning in the output console:

System.Windows.Data Warning: 50 : Using CollectionView directly is not fully supported. The basic features work, although with some inefficiencies, but advanced features may encounter known bugs. Consider using a derived class to avoid these problems.

Edit2 (.NET 4.5): The content of the DropDownList can be based on ToString() and not of DisplayMemberPath, while DisplayMemberPath specifies the member for the selected and displayed item only.

How to detect escape key press with pure JS or jQuery?

Below is the code that not only disables the ESC key but also checks the condition where it is pressed and depending on the situation, it will do the action or not.

In this example,

e.preventDefault();

will disable the ESC key-press action.

You may do anything like to hide a div with this:

document.getElementById('myDivId').style.display = 'none';

Where the ESC key pressed is also taken into consideration:

(e.target.nodeName=='BODY')

You may remove this if condition part if you like to apply to this to all. Or you may target INPUT here to only apply this action when the cursor is in input box.

window.addEventListener('keydown', function(e){
    if((e.key=='Escape'||e.key=='Esc'||e.keyCode==27) && (e.target.nodeName=='BODY')){
        e.preventDefault();
        return false;
    }
}, true);

How do I dump the data of some SQLite3 tables?

You're not saying what you wish to do with the dumped file.

I would use the following to get a CSV file, which I can import into almost everything

.mode csv 
-- use '.separator SOME_STRING' for something other than a comma.
.headers on 
.out file.csv 
select * from MyTable;

If you want to reinsert into a different SQLite database then:

.mode insert <target_table_name>
.out file.sql 
select * from MyTable;

Javascript - object key->value

I use the following syntax:

objTest = {"error": true, "message": "test message"};

get error:

 var name = "error"
 console.log(objTest[name]);

get message:

 name = "message"
 console.log(objTest[name]);

What does body-parser do with express?

It parses the HTTP request body. This is usually necessary when you need to know more than just the URL you hit, particular in the context of a POST or PUT PATCH HTTP request where the information you want is contains in the body.

Basically its a middleware for parsing JSON, plain text, or just returning a raw Buffer object for you to deal with as you require.

MongoDB: update every document on one field

Regardless of the version, for your example, the <update> is:

{  $set: { lastLookedAt: Date.now() / 1000 }  }

However, depending on your version of MongoDB, the query will look different. Regardless of version, the key is that the empty condition {} will match any document. In the Mongo shell, or with any MongoDB client:

$version >= 3.2:

db.foo.updateMany( {}, <update> )
  • {} is the condition (the empty condition matches any document)

3.2 > $version >= 2.2:

db.foo.update( {}, <update>, { multi: true } )
  • {} is the condition (the empty condition matches any document)
  • {multi: true} is the "update multiple documents" option

$version < 2.2:

db.foo.update( {}, <update>, false, true )
  • {} is the condition (the empty condition matches any document)
  • false is for the "upsert" parameter
  • true is for the "multi" parameter (update multiple records)

How can I update NodeJS and NPM to the next versions?

As you may already know, npm is currently bundled with node.js. It means that if you have installed node.js, you've already installed npm as well.

Also, pay attention to the node.js and npm release versions table that shows us approximate versions compatibility. Sometimes, versions discrepancy may cause incompatibility errors.

So, if you're a developer, it's kinda "best practice" to manage your development environment using one of the node.js version managers.

Here is a list and usage notes of some of the most popular:

Homebrew (macOS)

If you're on macOS, you can use Homebrew.

Actually, it's not just a node.js version manager.

To install Homebrew to your Mac:

$ ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

To install node.js and npm using Homebrew, run:

$ brew install node

Later, you will be able to update them using:

$ brew update && brew upgrade node

Also, you can switch between node.js versions as well:

$ brew switch node 0.10.26

npm will be upgraded/downgraded automatically.

n (macOS, Linux)

n is most likely to rvm (Ruby Version Manager), and is used to manage node.js and npm versions simultaneously. It is written on pure Linux shell, and available as an npm module. So, if you already have any node.js version installed, you can install/update the n package through npm:

$ npm install -g n

Downloading, installing and switching to node.js and npm versions is as easy as:

$ n 0.10.26
$ n 0.8.17
$ n 0.9.6

To download, install, and switch to the latest official release, use:

$ n latest

To download, install, and switch to the latest stable official release, use:

$ n stable

To switch to the previously active version (aka $ cd -), use:

$ n prev

If you want to see the list of installed node.js versions, just run n from your command line. The output will be something like the following:

$ n

  0.10.26
• 0.8.17
  0.9.6

Where the dot (•) means that it's a currently active version. To select another node.js version from the list, use Up/Down arrow keys and activate using the Enter key.

To list the versions available to install:

$ n lsr

nvm (macOS, Linux)

nvm is also like rvm, even the command names and usage are very similar.

To install nvm you can use the installation script (requires git) using cURL:

$ curl https://raw.github.com/creationix/nvm/master/install.sh | sh

or wget:

$ wget -qO- https://raw.github.com/creationix/nvm/master/install.sh | sh

To download and install a specific node.js and npm version, use:

$ nvm install 0.10

Then, you can switch to the installed version, using:

$ nvm use 0.10

Also, you can create the .nvmrc file containing the version number, then switch to the specified version using the following command:

$ nvm use

To see the list of installed node.js versions, use:

$ nvm ls

To list the versions available to install:

$ nvm ls-remote

nvm-windows (Windows)

nvm-windows is a node.js version management utility for Windows, ironically written in Go.

It is not the same thing as nvm. However, the usage as a node.js version manager is very similar.

To install nvm-windows, it is required to uninstall any existing versions of node.js and npm beforehand. Then, download and run the latest installer from releases.

To upgrade nvm-windows, run the new installer. It will safely overwrite the files it needs to update without touching your node.js installations.

nvm-windows runs in an Admin shell. You'll need to start Powershell or Command Prompt as Administrator to use nvm-windows.

Before using, you may also need to enable nvm-windows with the following command:

C:\> nvm on

To download and install a specific node.js and npm version, use:

C:\> nvm install 0.12

Then, you can switch to the installed version, using:

C:\> nvm use 0.12

If you want to see the list of installed node.js versions, use:

C:\> nvm list

To list the versions available to install:

C:\> nvm list available

How to get the response of XMLHttpRequest?

You can get it by XMLHttpRequest.responseText in XMLHttpRequest.onreadystatechange when XMLHttpRequest.readyState equals to XMLHttpRequest.DONE.

Here's an example (not compatible with IE6/7).

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);

For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.

$.get('http://example.com', function(responseText) {
    alert(responseText);
});

Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.

How to reformat JSON in Notepad++?

If you don't want to install a Notepad++ plugin but you have Firefox and a JSON plugin for Firefox, you can select Run -> Launch in Firefox. You get the contents formatted as JSON using your Firefox plugin.

This is what I personally do.

Installing a plain plugin jar in Eclipse 3.5

For Eclipse Mars (I've just verified that) you to do this (assuming that C:\eclipseMarsEE is root folder of your Eclipse):

  1. Add plugins folder to C:\eclipseMarsEE\dropins so that it looks like: C:\eclipseMarsEE\dropins\plugins
  2. Then add plugin you want to install into that folder: C:\eclipseMarsEE\dropins\plugins\someplugin.jar
  3. Start Eclipse with clean option.
  4. If you are using shortcut on desktop then just right click on Eclipse icon > Properties and in Target field add: -clean like this: C:\eclipseMarsEE\eclipse.exe -clean

enter image description here

  1. Start Eclipse and verify that your plugin works.
  2. Remove -clean option from Target field.

How to count the number of rows in excel with data?

I compared all possibilities with a long test sheet:

0,140625 sec for

lastrow = calcws.Cells.Find("*", [A1], , , xlByColumns, xlPrevious).row

0 sec for

iLastRow = calcws.Cells(rows.count, "a").End(xlUp).row

and

numofrows = calcws.Cells.SpecialCells(xlLastCell).row

0,0078125 sec for

lastrow = calcws.UsedRange.rows.count
Do While 1
    If calcws.Cells(lastrow, 1).Value = "" Then
        lastrow = lastrow - 1
    Else
        Exit Do
    End If
Loop

I think the favourites are obvious...

How to declare a global variable in C++

In addition to other answers here, if the value is an integral constant, a public enum in a class or struct will work. A variable - constant or otherwise - at the root of a namespace is another option, or a static public member of a class or struct is a third option.

MyClass::eSomeConst (enum)
MyNamespace::nSomeValue 
MyStruct::nSomeValue (static) 

What is difference between INNER join and OUTER join

Inner join matches tables on keys, but outer join matches keys just for one side. For example when you use left outer join the query brings the whole left side table and matches the right side to the left table primary key and where there is not matched places null.

Write-back vs Write-Through caching?

maybe this article can help you link here

Write-through: Write is done synchronously both to the cache and to the backing store.

Write-back (or Write-behind): Writing is done only to the cache. A modified cache block is written back to the store, just before it is replaced.

Write-through: When data is updated, it is written to both the cache and the back-end storage. This mode is easy for operation but is slow in data writing because data has to be written to both the cache and the storage.

Write-back: When data is updated, it is written only to the cache. The modified data is written to the back-end storage only when data is removed from the cache. This mode has fast data write speed but data will be lost if a power failure occurs before the updated data is written to the storage.

Is it possible to write to the console in colour in .NET?

Yes, it's easy and possible. Define first default colors.

Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.White;
Console.Clear();

Console.Clear() it's important in order to set new console colors. If you don't make this step you can see combined colors when ask for values with Console.ReadLine().

Then you can change the colors on each print:

Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Red text over black.");

When finish your program, remember reset console colors on finish:

Console.ResetColor();
Console.Clear();

Now with netcore we have another problem if you want to "preserve" the User experience because terminal have different colors on each Operative System.

I'm making a library that solves this problem with Text Format: colors, alignment and lot more. Feel free to use and contribute.

https://github.com/deinsoftware/colorify/ and also available as NuGet package

Colors for Windows/Linux (Dark):
enter image description here

Colors for MacOS (Light):
enter image description here

How to ignore ansible SSH authenticity checking?

Changing host_key_checking to false for all hosts is a very bad idea.

The only time you want to ignore it, is on "first contact", which these two tasks will accomplish:

    - name: Check SSH known_hosts for {{ inventory_hostname }}
      local_action: shell ssh-keygen -F {{ inventory_hostname }}
      register: checkForKnownHostsEntry
      failed_when: false
      changed_when: false
      ignore_errors: yes
    - name: Add {{ inventory_hostname }} to SSH known hosts automatically
      when: checkForKnownHostsEntry.rc == 1
      changed_when: checkForKnownHostsEntry.rc == 1
      set_fact:
        ansible_ssh_common_args: '-o StrictHostKeyChecking=no'

So we only turn off host key checking if we don't have the host key in our known_hosts file.

Get environment variable value in Dockerfile

You should use the ARG directive in your Dockerfile which is meant for this purpose.

The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

So your Dockerfile will have this line:

ARG request_domain

or if you'd prefer a default value:

ARG request_domain=127.0.0.1

Now you can reference this variable inside your Dockerfile:

ENV request_domain=$request_domain

then you will build your container like so:

$ docker build --build-arg request_domain=mydomain Dockerfile


Note 1: Your image will not build if you have referenced an ARG in your Dockerfile but excluded it in --build-arg.

Note 2: If a user specifies a build argument that was not defined in the Dockerfile, the build outputs a warning:

[Warning] One or more build-args [foo] were not consumed.

Java: Literal percent sign in printf statement

You can use StringEscapeUtils from Apache Commons Logging utility or escape manually using code for each character.

How can I create directory tree in C++/Linux?

Easy with Boost.Filesystem: create_directories

#include <boost/filesystem.hpp>
//...
boost::filesystem::create_directories("/tmp/a/b/c");

Returns: true if a new directory was created, otherwise false.

T-SQL split string

All the functions for string splitting that use some kind of Loop-ing (iterations) have bad performance. They should be replaced with set-based solution.

This code executes excellent.

CREATE FUNCTION dbo.SplitStrings
(
   @List       NVARCHAR(MAX),
   @Delimiter  NVARCHAR(255)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
   RETURN 
   (  
      SELECT Item = y.i.value('(./text())[1]', 'nvarchar(4000)')
      FROM 
      ( 
        SELECT x = CONVERT(XML, '<i>' 
          + REPLACE(@List, @Delimiter, '</i><i>') 
          + '</i>').query('.')
      ) AS a CROSS APPLY x.nodes('i') AS y(i)
   );
GO

CSS flexbox not working in IE10

As Ennui mentioned, IE 10 supports the -ms prefixed version of Flexbox (IE 11 supports it unprefixed). The errors I can see in your code are:

  • You should have display: -ms-flexbox instead of display: -ms-flex
  • I think you should specify all 3 flex values, like flex: 0 1 auto to avoid ambiguity

So the final updated code is...

.flexbox form {
    display: -webkit-flex;
    display: -moz-flex;
    display: -ms-flexbox;
    display: -o-flex;
    display: flex;

    /* Direction defaults to 'row', so not really necessary to specify */
    -webkit-flex-direction: row;
    -moz-flex-direction: row;
    -ms-flex-direction: row;
    -o-flex-direction: row;
    flex-direction: row;
}

.flexbox form input[type=submit] {
    width: 31px;
}

.flexbox form input[type=text] {
    width: auto;

    /* Flex should have 3 values which is shorthand for 
       <flex-grow> <flex-shrink> <flex-basis> */
    -webkit-flex: 1 1 auto;
    -moz-flex: 1 1 auto;
    -ms-flex: 1 1 auto;
    -o-flex: 1 1 auto;
    flex: 1 1 auto;

    /* I don't think you need 'display: flex' on child elements * /
    display: -webkit-flex;
    display: -moz-flex;
    display: -ms-flex;
    display: -o-flex;
    display: flex;
    /**/
}

How to make borders collapse (on a div)?

Example of using border-collapse: separate; as

  • container displayed as table:

    ol[type="I"]>li{
      display: table;
      border-collapse: separate;
      border-spacing: 1rem;
    }
    
  • How do I get the current GPS location programmatically in Android?

    Now that Google Play locations services are here, I recommend that developers start using the new fused location provider. You will find it easier to use and more accurate. Please watch the Google I/O video Beyond the Blue Dot: New Features in Android Location by the two guys who created the new Google Play location services API.

    I've been working with location APIs on a number of mobile platforms, and I think what these two guys have done is really revolutionary. It's gotten rid of a huge amount of the complexities of using the various providers. Stack Overflow is littered with questions about which provider to use, whether to use last known location, how to set other properties on the LocationManager, etc. This new API that they have built removes most of those uncertainties and makes the location services a pleasure to use.

    I've written an Android app that periodically gets the location using Google Play location services and sends the location to a web server where it is stored in a database and can be viewed on Google Maps. I've written both the client software (for Android, iOS, Windows Phone and Java ME) and the server software (for ASP.NET and SQL Server or PHP and MySQL). The software is written in the native language on each platform and works properly in the background on each. Lastly, the software has the MIT License. You can find the Android client here:

    https://github.com/nickfox/GpsTracker/tree/master/phoneClients/android

    iFrame Height Auto (CSS)

     <div id="content" >
        <h1>Update Information</h1>
        <div id="support-box">
            <div id="wrapper">
                <iframe name="frame" id="frame" src="http://website.org/update.php" allowtransparency="true" frameborder="0"></iframe>
            </div>
        </div>
      </div>
     #support-box {
            width: 50%;
            float: left;
            display: block;
            height: 20rem; /* is support box height you can change as per your requirement*/
            background-color:#000;
        }
        #wrapper {
            width: 90%;
            display: block;
            position: relative;
            top: 50%;
            transform: translateY(-50%);
             background:#ddd;
           margin:auto;
           height:100px; /* here the height values are automatic you can leave this if you can*/
    
        }
        #wrapper iframe {
            width: 100%;
            display: block;
            padding:10px;
            margin:auto;
        }
    

    https://jsfiddle.net/umd2ahce/1/

    MySQL: Enable LOAD DATA LOCAL INFILE

    Another way is to use the mysqlimport client program.

    You invoke it as follows:

    mysqlimport -uTheUsername -pThePassword --local yourDatabaseName tableName.txt
    

    This generates a LOAD DATA statement which loads tableName.txt into the tableName table.

    Keep in mind the following:

    mysqlimport determines the table name from the file you provide; using all text from the start of the file name up to the first period as the table name. So, if you wish to load several files to the same table you could distinguish them like tableName.1.txt, tableName.2.txt,..., etc, for example.

    AngularJS Folder Structure

    I like this entry about angularjs structure

    It's written by one of the angularjs developers, so should give you a good insight

    Here's an excerpt:

    root-app-folder
    +-- index.html
    +-- scripts
    ¦   +-- controllers
    ¦   ¦   +-- main.js
    ¦   ¦   +-- ...
    ¦   +-- directives
    ¦   ¦   +-- myDirective.js
    ¦   ¦   +-- ...
    ¦   +-- filters
    ¦   ¦   +-- myFilter.js
    ¦   ¦   +-- ...
    ¦   +-- services
    ¦   ¦   +-- myService.js
    ¦   ¦   +-- ...
    ¦   +-- vendor
    ¦   ¦   +-- angular.js
    ¦   ¦   +-- angular.min.js
    ¦   ¦   +-- es5-shim.min.js
    ¦   ¦   +-- json3.min.js
    ¦   +-- app.js
    +-- styles
    ¦   +-- ...
    +-- views
        +-- main.html
        +-- ...
    

    How to join three table by laravel eloquent model

    $articles =DB::table('articles')
                    ->join('categories','articles.id', '=', 'categories.id')
                    ->join('user', 'articles.user_id', '=', 'user.id')
                    ->select('articles.id','articles.title','articles.body','user.user_name', 'categories.category_name')
                    ->get();
    return view('myarticlesview',['articles'=>$articles]);
    

    Make xargs execute the command once for each line of input

    It seems to me all existing answers on this page are wrong, including the one marked as correct. That stems from the fact that the question is ambiguously worded.

    Summary:   If you want to execute the command "exactly once for each line of input," passing the entire line (without newline) to the command as a single argument, then this is the best UNIX-compatible way to do it:

    ... | tr '\n' '\0' | xargs -0 -n1 ...
    

    If you are using GNU xargs and don't need to be compatible with all other UNIX's (FreeBSD, Mac OS X, etc.) then you can use the GNU-specific option -d:

    ... | xargs -d\\n -n1 ...
    

    Now for the long explanation…


    There are two issues to take into account when using xargs:

    1. how does it split the input into "arguments"; and
    2. how many arguments to pass the child command at a time.

    To test xargs' behavior, we need an utility that shows how many times it's being executed and with how many arguments. I don't know if there is a standard utility to do that, but we can code it quite easily in bash:

    #!/bin/bash
    echo -n "-> "; for a in "$@"; do echo -n "\"$a\" "; done; echo
    

    Assuming you save it as show in your current directory and make it executable, here is how it works:

    $ ./show one two 'three and four'
    -> "one" "two" "three and four" 
    

    Now, if the original question is really about point 2. above (as I think it is, after reading it a few times over) and it is to be read like this (changes in bold):

    How can I make xargs execute the command exactly once for each argument of input given? Its default behavior is to chunk the input into arguments and execute the command as few times as possible, passing multiple arguments to each instance.

    then the answer is -n 1.

    Let's compare xargs' default behavior, which splits the input around whitespace and calls the command as few times as possible:

    $ echo one two 'three and four' | xargs ./show 
    -> "one" "two" "three" "and" "four" 
    

    and its behavior with -n 1:

    $ echo one two 'three and four' | xargs -n 1 ./show 
    -> "one" 
    -> "two" 
    -> "three" 
    -> "and" 
    -> "four" 
    

    If, on the other hand, the original question was about point 1. input splitting and it was to be read like this (many people coming here seem to think that's the case, or are confusing the two issues):

    How can I make xargs execute the command with exactly one argument for each line of input given? Its default behavior is to chunk the lines around whitespace.

    then the answer is more subtle.

    One would think that -L 1 could be of help, but it turns out it doesn't change argument parsing. It only executes the command once for each input line, with as many arguments as were there on that input line:

    $ echo $'one\ntwo\nthree and four' | xargs -L 1 ./show 
    -> "one" 
    -> "two" 
    -> "three" "and" "four" 
    

    Not only that, but if a line ends with whitespace, it is appended to the next:

    $ echo $'one \ntwo\nthree and four' | xargs -L 1 ./show 
    -> "one" "two" 
    -> "three" "and" "four" 
    

    Clearly, -L is not about changing the way xargs splits the input into arguments.

    The only argument that does so in a cross-platform fashion (excluding GNU extensions) is -0, which splits the input around NUL bytes.

    Then, it's just a matter of translating newlines to NUL with the help of tr:

    $ echo $'one \ntwo\nthree and four' | tr '\n' '\0' | xargs -0 ./show 
    -> "one " "two" "three and four" 
    

    Now the argument parsing looks all right, including the trailing whitespace.

    Finally, if you combine this technique with -n 1, you get exactly one command execution per input line, whatever input you have, which may be yet another way to look at the original question (possibly the most intuitive, given the title):

    $ echo $'one \ntwo\nthree and four' | tr '\n' '\0' | xargs -0 -n1 ./show 
    -> "one " 
    -> "two" 
    -> "three and four" 
    

    As mentioned above, if you are using GNU xargs you can replace the tr with the GNU-specific option -d:

    $ echo $'one \ntwo\nthree and four' | xargs -d\\n -n1 ./show 
    -> "one " 
    -> "two" 
    -> "three and four" 
    

    How to check if internet connection is present in Java?

    People have suggested using INetAddress.isReachable. The problem is that some sites configure their firewalls to block ICMP Ping messages. So a "ping" might fail even though the web service is accessible.

    And of course, the reverse is true as well. A host may respond to a ping even though the webserver is down.

    And of course, a machine may be unable to connect directly to certain (or all) web servers due to local firewall restrictions.

    The fundamental problem is that "can connect to the internet" is an ill-defined question, and this kind of thing is difficult to test without:

    1. information on the user's machine and "local" networking environment, and
    2. information on what the app needs to access.

    So generally, the simplest solution is for an app to just try to access whatever it needs to access, and fall back on human intelligence to do the diagnosis.

    Python - round up to the nearest ten

    You can use math.ceil() to round up, and then multiply by 10

    import math
    
    def roundup(x):
        return int(math.ceil(x / 10.0)) * 10
    

    To use just do

    >>roundup(45)
    50
    

    Undo scaffolding in Rails

    So, Process you should follow to undo scaffolding in rails 4. Run Command as below:

    1. rails d scaffold FooBar
    2. rake db:rollback if you_had_run_rake db:migrate after creating above scaffold?

    That's it!

    Cheers!

    Pro JavaScript programmer interview questions (with answers)

    intermediate programmers should have technical mastery of their tools.

    if he's passed the technical phone screen-esque questions above, make him sketch out something stupid on the spot, like an ajax url shortner. then grill him on his portfolio. no amazing portfolio = intermediate developer in this domain and not the guy you want in charge of your shiny new project.

    How to run a shell script on a Unix console or Mac terminal?

    For the bourne shell:

    sh myscript.sh
    

    For bash:

    bash myscript.sh
    

    Inline for loop

    What you are using is called a list comprehension in Python, not an inline for-loop (even though it is similar to one). You would write your loop as a list comprehension like so:

    p = [q.index(v) if v in q else 99999 for v in vm]
    

    When using a list comprehension, you do not call list.append because the list is being constructed from the comprehension itself. Each item in the list will be what is returned by the expression on the left of the for keyword, which in this case is q.index(v) if v in q else 99999. Incidentially, if you do use list.append inside a comprehension, then you will get a list of None values because that is what the append method always returns.

    How to count duplicate rows in pandas dataframe?

    You can groupby on all the columns and call size the index indicates the duplicate values:

    In [28]:
    df.groupby(df.columns.tolist(),as_index=False).size()
    
    Out[28]:
    one    three  two  
    False  False  True     1
    True   False  False    2
           True   True     1
    dtype: int64
    

    Why is Dictionary preferred over Hashtable in C#?

    In .NET, the difference between Dictionary<,> and HashTable is primarily that the former is a generic type, so you get all the benefits of generics in terms of static type checking (and reduced boxing, but this isn't as big as people tend to think in terms of performance - there is a definite memory cost to boxing, though).

    How to disable scrolling in UITableView table when the content fits on the screen

    You can edit this in your storyboard (if you are using one). Under the table view there is a checkbox that says "Scrolling Enabled". Uncheck it and you're done.

    Excel 2007 - Compare 2 columns, find matching values

    VLOOKUP deosnt work for String literals

    CSS Change List Item Background Color with Class

    1) You can use the !important rule, like this:

    .selected
    {
      background-color:red !important;
    }
    

    See http://www.w3.org/TR/CSS2/cascade.html#important-rules for more info.

    2) In your example you can also get the red background by using ul.nav li.selected instead of just .selected. This makes the selector more specific.

    See http://www.w3.org/TR/CSS2/cascade.html#specificity for more info.

    What is the difference between .text, .value, and .value2?

    target.Value will give you a Variant type

    target.Value2 will give you a Variant type as well but a Date is coerced to a Double

    target.Text attempts to coerce to a String and will fail if the underlying Variant is not coercable to a String type

    The safest thing to do is something like

    Dim v As Variant
    v = target.Value 'but if you don't want to handle date types use Value2
    

    And check the type of the variant using VBA.VarType(v) before you attempt an explicit coercion.

    Git push existing repo to a new and different remote repo server?

    To push your existing repo into different, you need to:

    1. Clone the original repo first.

      git clone https://git.fedorahosted.org/cgit/rhq/rhq.git
      
    2. Push the cloned sources to your new repository:

      cd rhq
      git push https://github.com/user/example master:master
      

    You may change master:master into source:destination branch.


    If you want to push specific commit (branch), then do:

    1. On the original repo, create and checkout a new branch:

      git checkout -b new_branch
      
    2. Choose and reset to the point which you want to start with:

      git log # Find the interesting hash
      git reset 4b62bdc9087bf33cc01d0462bf16bbf396369c81 --hard
      

      Alternatively select the commit by git cherry-pick to append into existing HEAD.

    3. Then push to your new repo:

      git push https://github.com/user/example new_branch:master
      

      If you're rebasing, use -f for force push (not recommended). Run git reflog to see history of changes.

    excel VBA run macro automatically whenever a cell is changed

    Another option is

    Private Sub Worksheet_Change(ByVal Target As Range)
        IF Target.Address = "$D$2" Then
            MsgBox("Cell D2 Has Changed.")
        End If
    End Sub
    

    I believe this uses fewer resources than Intersect, which will be helpful if your worksheet changes a lot.

    Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

    Had this issue on Python 2.7.9, solved by updating to Python 2.7.10 (unreleased when this question was asked and answered).

    Reading the selected value from asp:RadioButtonList using jQuery

    Andrew Bullock solution works just fine, I just wanted to show you mine and add a warning.

    //Works great

    $('#<%= radBuffetCapacity.ClientID %> input').click(function (e) {
       var val = $('#<%= radBuffetCapacity.ClientID %>').find('input:checked').val();
       //Do whatever
    });
    

    //Warning - works in firefox but not IE8 .. used this for some time before a noticing that it didnt work in IE8... used to everything working in all browsers with jQuery when working in one.

    $('#<%= radBuffetCapacity.ClientID %>').change(function (e) {
       var val = $('#<%= radBuffetCapacity.ClientID %>').find('input:checked').val();
       //Do whatever
    });
    

    Pass array to MySQL stored routine

    I've come up with an awkward but functional solution for my problem. It works for a one-dimensional array (more dimensions would be tricky) and input that fits into a varchar:

      declare pos int;           -- Keeping track of the next item's position
      declare item varchar(100); -- A single item of the input
      declare breaker int;       -- Safeguard for while loop 
    
      -- The string must end with the delimiter
      if right(inputString, 1) <> '|' then
         set inputString = concat(inputString, '|');
      end if;
    
      DROP TABLE IF EXISTS MyTemporaryTable;
      CREATE TEMPORARY TABLE MyTemporaryTable ( columnName varchar(100) );
      set breaker = 0;
    
      while (breaker < 2000) && (length(inputString) > 1) do
         -- Iterate looking for the delimiter, add rows to temporary table.
         set breaker = breaker + 1;
         set pos = INSTR(inputString, '|');
         set item = LEFT(inputString, pos - 1);
         set inputString = substring(inputString, pos + 1);
         insert into MyTemporaryTable values(item);
      end while;
    

    For example, input for this code could be the string Apple|Banana|Orange. MyTemporaryTable will be populated with three rows containing the strings Apple, Banana, and Orange respectively.

    I thought the slow speed of string handling would render this approach useless, but it was quick enough (only a fraction of a second for a 1,000 entries array).

    Hope this helps somebody.

    Implementing SearchView in action bar

    If anyone else is having a nullptr on the searchview variable, I found out that the item setup is a tiny bit different:

    old:

    android:showAsAction="ifRoom"
    android:actionViewClass="android.widget.SearchView"
    

    new:

    app:showAsAction="ifRoom|collapseActionView"
    app:actionViewClass="androidx.appcompat.widget.SearchView"
    

    pre-android x:

    app:showAsAction="ifRoom|collapseActionView"
    app:actionViewClass="android.support.v7.widget.SearchView"
    

    For more information, it's updated documentation is located here.

    How to set selectedIndex of select element using display text?

    Add name attribute to your option:

    <option value="0" name="Chicken">Chicken</option>
    

    With that you can use the HTMLOptionsCollection.namedItem("Chicken").value to set the value of your select element.

    Laravel 5 How to switch from Production mode

    Laravel 5 gets its enviroment related variables from the .env file located in the root of your project. You just need to set APP_ENV to whatever you want, for example:

    APP_ENV=development
    

    This is used to identify the current enviroment. If you want to display errors, you'll need to enable debug mode in the same file:

    APP_DEBUG=true
    

    The role of the .env file is to allow you to have different settings depending on which machine you are running your application. So on your production server, the .env file settings would be different from your local development enviroment.

    TypeScript error TS1005: ';' expected (II)

    Your installation is wrong; you are using a very old compiler version (1.0.3.0).

    tsc --version should return a version of 2.5.2.

    Check where that old compiler is located using: which tsc (or where tsc) and remove it.

    Try uninstalling the "global" typescript

    npm uninstall -g typescript
    

    Installing as part of a local dev dependency of your project

    npm install typescript --save-dev
    

    Execute it from the root of your project

    ./node_modules/.bin/tsc
    

    Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

    Where it is documented:

    From the API documentation under the has_many association in "Module ActiveRecord::Associations::ClassMethods"

    collection.build(attributes = {}, …) Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved. Note: This only works if an associated object already exists, not if it‘s nil!

    The answer to building in the opposite direction is a slightly altered syntax. In your example with the dogs,

    Class Dog
       has_many :tags
       belongs_to :person
    end
    
    Class Person
      has_many :dogs
    end
    
    d = Dog.new
    d.build_person(:attributes => "go", :here => "like normal")
    

    or even

    t = Tag.new
    t.build_dog(:name => "Rover", :breed => "Maltese")
    

    You can also use create_dog to have it saved instantly (much like the corresponding "create" method you can call on the collection)

    How is rails smart enough? It's magic (or more accurately, I just don't know, would love to find out!)

    When should I use semicolons in SQL Server?

    By default, SQL statements are terminated with semicolons. You use a semicolon to terminate statements unless you've (rarely) set a new statement terminator.

    If you're sending just one statement, technically you can dispense with the statement terminator; in a script, as you're sending more than one statement, you need it.

    In practice, always include the terminator even if you're just sending one statement to the database.

    Edit: in response to those saying statement terminators are not required by [particular RDBMS], while that may be true, they're required by the ANSI SQL Standard. In all programming, if we can adhere to a Standard without loss of functionality, we should, because then neither our code or our habits are tied to one proprietary vendor.

    With some C compilers, it's possible to have main return void, even though the Standard requires main to return int. But doing so makes our code, and ourselves, less portable.

    The biggest difficulty in programming effectively isn't learning new things, it's unlearning bad habits. To the extent that we can avoid acquiring bad habits in the first place, it's a win for us, for our code, and for anyone reading or using our code.

    What is the standard naming convention for html/css ids and classes?

    Another reason why many prefer hyphens in CSS id and class names is functionality.

    Using keyboard shortcuts like option + left/right (or ctrl+left/right on Windows) to traverse code word by word stops the cursor at each dash, allowing you to precisely traverse the id or class name using keyboard shortcuts. Underscores and camelCase do not get detected and the cursor will drift right over them as if it were all one single word.

    Filter values only if not null using lambda in Java8

    You can do this in single filter step:

    requiredCars = cars.stream().filter(c -> c.getName() != null && c.getName().startsWith("M"));
    

    If you don't want to call getName() several times (for example, it's expensive call), you can do this:

    requiredCars = cars.stream().filter(c -> {
        String name = c.getName();
        return name != null && name.startsWith("M");
    });
    

    Or in more sophisticated way:

    requiredCars = cars.stream().filter(c -> 
        Optional.ofNullable(c.getName()).filter(name -> name.startsWith("M")).isPresent());
    

    Case insensitive std::string.find()

    Also make sense to provide Boost version: This will modify original strings.

    #include <boost/algorithm/string.hpp>
    
    string str1 = "hello world!!!";
    string str2 = "HELLO";
    boost::algorithm::to_lower(str1)
    boost::algorithm::to_lower(str2)
    
    if (str1.find(str2) != std::string::npos)
    {
        // str1 contains str2
    }
    

    or using perfect boost xpression library

    #include <boost/xpressive/xpressive.hpp>
    using namespace boost::xpressive;
    ....
    std::string long_string( "very LonG string" );
    std::string word("long");
    smatch what;
    sregex re = sregex::compile(word, boost::xpressive::icase);
    if( regex_match( long_string, what, re ) )
    {
        cout << word << " found!" << endl;
    }
    

    In this example you should pay attention that your search word don't have any regex special characters.

    How to assign bean's property an Enum value in Spring config file?

    Use the value child element instead of the value attribute and specify the Enum class name:

    <property name="residence">
        <value type="SocialSecurity$Residence">ALIEN</value>
    </property>
    

    The advantage of this approach over just writing value="ALIEN" is that it also works if Spring can't infer the actual type of the enum from the property (e.g. the property's declared type is an interface).Adapted from araqnid's comment.

    HTML - Display image after selecting filename

    Here You Go:

    HTML

    <!DOCTYPE html>
    <html>
    <head>
    <link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
    <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
    <meta charset=utf-8 />
    <title>JS Bin</title>
    <!--[if IE]>
      <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <style>
      article, aside, figure, footer, header, hgroup, 
      menu, nav, section { display: block; }
    </style>
    </head>
    <body>
      <input type='file' onchange="readURL(this);" />
        <img id="blah" src="#" alt="your image" />
    </body>
    </html>
    

    Script:

    function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
    
                reader.onload = function (e) {
                    $('#blah')
                        .attr('src', e.target.result)
                        .width(150)
                        .height(200);
                };
    
                reader.readAsDataURL(input.files[0]);
            }
        }
    

    Live Demo

    Hibernate Error: a different object with the same identifier value was already associated with the session

    Find the "Cascade" atribute in Hibernate and delete it. When you set "Cascade" available, it will call other operations (save, update and delete) on another entities which has relationship with related classes. So same identities value will be happened. It worked with me.

    Android Overriding onBackPressed()

    At first you must consider that if your activity which I called A extends another activity (B) and in both of

    them you want to use onbackpressed function then every code you have in B runs in A too. So if you want to separate these you should separate them. It means that A should not extend B , then you can have onbackpressed separately for each of them.

    How to prevent caching of my Javascript file?

    Add a random query string to the src

    You could either do this manually by incrementing the querystring each time you make a change:

    <script src="test.js?version=1"></script>
    

    Or if you are using a server side language, you could automatically generate this:

    ASP.NET:

    <script src="test.js?rndstr=<%= getRandomStr() %>"></script>
    

    More info on cache-busting can be found here:

    https://curtistimson.co.uk/post/front-end-dev/what-is-cache-busting/

    What does the C++ standard state the size of int, long type to be?

    As others have answered, the "standards" all leave most of the details as "implementation defined" and only state that type "char" is at leat "char_bis" wide, and that "char <= short <= int <= long <= long long" (float and double are pretty much consistent with the IEEE floating point standards, and long double is typically same as double--but may be larger on more current implementations).

    Part of the reasons for not having very specific and exact values is because languages like C/C++ were designed to be portable to a large number of hardware platforms--Including computer systems in which the "char" word-size may be 4-bits or 7-bits, or even some value other than the "8-/16-/32-/64-bit" computers the average home computer user is exposed to. (Word-size here meaning how many bits wide the system normally operates on--Again, it's not always 8-bits as home computer users may expect.)

    If you really need a object (in the sense of a series of bits representing an integral value) of a specific number of bits, most compilers have some method of specifying that; But it's generally not portable, even between compilers made by the ame company but for different platforms. Some standards and practices (especially limits.h and the like) are common enough that most compilers will have support for determining at the best-fit type for a specific range of values, but not the number of bits used. (That is, if you know you need to hold values between 0 and 127, you can determine that your compiler supports an "int8" type of 8-bits which will be large enought to hold the full range desired, but not something like an "int7" type which would be an exact match for 7-bits.)

    Note: Many Un*x source packages used "./configure" script which will probe the compiler/system's capabilities and output a suitable Makefile and config.h. You might examine some of these scripts to see how they work and how they probe the comiler/system capabilities, and follow their lead.

    Best way to store password in database

    I'd thoroughly recommend reading the articles Enough With The Rainbow Tables: What You Need To Know About Secure Password Schemes [dead link, copy at the Internet Archive] and How To Safely Store A Password.

    Lots of coders, myself included, think they understand security and hashing. Sadly most of us just don't.

    How to scroll HTML page to given anchor?

    In 2018, you don't need jQuery for something simple like this. The built in scrollIntoView() method supports a "behavior" property to smoothly scroll to any element on the page. You can even update the browser URL with a hash to make it bookmarkable.

    From this tutorial on scrolling HTML Bookmarks, here is a native way to add smooth scrolling to all anchor links on your page automatically:

    let anchorlinks = document.querySelectorAll('a[href^="#"]')
     
    for (let item of anchorlinks) { // relitere 
        item.addEventListener('click', (e)=> {
            let hashval = item.getAttribute('href')
            let target = document.querySelector(hashval)
            target.scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            })
            history.pushState(null, null, hashval)
            e.preventDefault()
        })
    }
    

    bootstrap 4 responsive utilities visible / hidden xs sm lg not working

    With Bootstrap 4 .hidden-* classes were completely removed (yes, they were replaced by hidden-*-* but those classes are also gone from v4 alphas).

    Starting with v4-beta, you can combine .d-*-none and .d-*-block classes to achieve the same result.

    visible-* was removed as well; instead of using explicit .visible-* classes, make the element visible by not hiding it (again, use combinations of .d-none .d-md-block). Here is the working example:

    <div class="col d-none d-sm-block">
        <span class="vcard">
            …
        </span>
    </div>
    <div class="col d-none d-xl-block">
        <div class="d-none d-md-block">
                    …
        </div>
        <div class="d-none d-sm-block">
                    …
        </div>
    </div>
    

    class="hidden-xs" becomes class="d-none d-sm-block" (or d-none d-sm-inline-block) ...

    <span class="d-none d-sm-inline">hidden-xs</span>
    
    <span class="d-none d-sm-inline-block">hidden-xs</span>
    

    An example of Bootstrap 4 responsive utilities:

    <div class="d-none d-sm-block"> hidden-xs           
      <div class="d-none d-md-block"> visible-md and up (hidden-sm and down)
        <div class="d-none d-lg-block"> visible-lg and up  (hidden-md and down)
          <div class="d-none d-xl-block"> visible-xl </div>
        </div>
      </div>
    </div>
    
    <div class="d-sm-none"> eXtra Small <576px </div>
    <div class="d-none d-sm-block d-md-none d-lg-none d-xl-none"> SMall =576px </div>
    <div class="d-none d-md-block d-lg-none d-xl-none"> MeDium =768px </div>
    <div class="d-none d-lg-block d-xl-none"> LarGe =992px </div>
    <div class="d-none d-xl-block"> eXtra Large =1200px </div>
    
    <div class="d-xl-none"> hidden-xl (visible-lg and down)         
      <div class="d-lg-none d-xl-none"> visible-md and down (hidden-lg and up)
        <div class="d-md-none d-lg-none d-xl-none"> visible-sm and down  (or hidden-md and up)
          <div class="d-sm-none"> visible-xs </div>
        </div>
      </div>
    </div>
    

    Documentation

    Correct way of getting Client's IP Addresses from http.Request

    Here a completely working example

    package main
    
    import (  
        // Standard library packages
        "fmt"
        "strconv"
        "log"
        "net"
        "net/http"
    
        // Third party packages
        "github.com/julienschmidt/httprouter"
        "github.com/skratchdot/open-golang/open"
    )
    
    
    
    // https://blog.golang.org/context/userip/userip.go
    func getIP(w http.ResponseWriter, req *http.Request, _ httprouter.Params){
        fmt.Fprintf(w, "<h1>static file server</h1><p><a href='./static'>folder</p></a>")
    
        ip, port, err := net.SplitHostPort(req.RemoteAddr)
        if err != nil {
            //return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)
    
            fmt.Fprintf(w, "userip: %q is not IP:port", req.RemoteAddr)
        }
    
        userIP := net.ParseIP(ip)
        if userIP == nil {
            //return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)
            fmt.Fprintf(w, "userip: %q is not IP:port", req.RemoteAddr)
            return
        }
    
        // This will only be defined when site is accessed via non-anonymous proxy
        // and takes precedence over RemoteAddr
        // Header.Get is case-insensitive
        forward := req.Header.Get("X-Forwarded-For")
    
        fmt.Fprintf(w, "<p>IP: %s</p>", ip)
        fmt.Fprintf(w, "<p>Port: %s</p>", port)
        fmt.Fprintf(w, "<p>Forwarded for: %s</p>", forward)
    }
    
    
    func main() {  
        myport := strconv.Itoa(10002);
    
    
        // Instantiate a new router
        r := httprouter.New()
    
        r.GET("/ip", getIP)
    
        // Add a handler on /test
        r.GET("/test", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
            // Simply write some test data for now
            fmt.Fprint(w, "Welcome!\n")
        })  
    
    
        l, err := net.Listen("tcp", "localhost:" + myport)
        if err != nil {
            log.Fatal(err)
        }
        // The browser can connect now because the listening socket is open.
    
    
        //err = open.Start("http://localhost:"+ myport + "/test")
        err = open.Start("http://localhost:"+ myport + "/ip")
        if err != nil {
             log.Println(err)
        }
    
        // Start the blocking server loop.
        log.Fatal(http.Serve(l, r)) 
    }
    

    How to save python screen output to a text file

    Let me summarize all the answers and add some more.

    • To write to a file from within your script, user file I/O tools that are provided by Python (this is the f=open('file.txt', 'w') stuff.

    • If don't want to modify your program, you can use stream redirection (both on windows and on Unix-like systems). This is the python myscript > output.txt stuff.

    • If you want to see the output both on your screen and in a log file, and if you are on Unix, and you don't want to modify your program, you may use the tee command (windows version also exists, but I have never used it)

    • Even better way to send the desired output to screen, file, e-mail, twitter, whatever is to use the logging module. The learning curve here is the steepest among all the options, but in the long run it will pay for itself.

    SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `songs` where `id` = 5 limit 1)

    I am running laravel 5.8 and i experienced the same problem. The solution that worked for me is as follows :

    1. I used bigIncrements('id') to define my primary key.
    2. I used unsignedBigInteger('user_id') to define the foreign referenced key.

          Schema::create('generals', function (Blueprint $table) {
              $table->bigIncrements('id');
              $table->string('general_name');
              $table->string('status');
              $table->timestamps();
          });
      
      
          Schema::create('categories', function (Blueprint $table) {
              $table->bigIncrements('id');
              $table->unsignedBigInteger('general_id');
              $table->foreign('general_id')->references('id')->on('generals');
              $table->string('category_name');
              $table->string('status');
              $table->timestamps();
          });
      

    I hope this helps out.

    JavaScript Promises - reject vs. throw

    Yes, the biggest difference is that reject is a callback function that gets carried out after the promise is rejected, whereas throw cannot be used asynchronously. If you chose to use reject, your code will continue to run normally in asynchronous fashion whereas throw will prioritize completing the resolver function (this function will run immediately).

    An example I've seen that helped clarify the issue for me was that you could set a Timeout function with reject, for example:

    _x000D_
    _x000D_
    new Promise((resolve, reject) => {
      setTimeout(()=>{reject('err msg');console.log('finished')}, 1000);
      return resolve('ret val')
    })
    .then((o) => console.log("RESOLVED", o))
    .catch((o) => console.log("REJECTED", o));
    _x000D_
    _x000D_
    _x000D_

    The above could would not be possible to write with throw.

    _x000D_
    _x000D_
    try{
      new Promise((resolve, reject) => {
        setTimeout(()=>{throw new Error('err msg')}, 1000);
        return resolve('ret val')
      })
      .then((o) => console.log("RESOLVED", o))
      .catch((o) => console.log("REJECTED", o));
    }catch(o){
      console.log("IGNORED", o)
    }
    _x000D_
    _x000D_
    _x000D_

    In the OP's small example the difference in indistinguishable but when dealing with more complicated asynchronous concept the difference between the two can be drastic.

    How do I remove a comma off the end of a string?

    This is a classic question, with two solutions. If you want to remove exactly one comma, which may or may not be there, use:

    if (substr($string, -1, 1) == ',')
    {
      $string = substr($string, 0, -1);
    }
    

    If you want to remove all commas from the end of a line use the simpler:

    $string = rtrim($string, ',');
    

    The rtrim function (and corresponding ltrim for left trim) is very useful as you can specify a range of characters to remove, i.e. to remove commas and trailing whitespace you would write:

    $string = rtrim($string, ", \t\n");
    

    What does "dereferencing" a pointer mean?

    I think all the previous answers are wrong, as they state that dereferencing means accessing the actual value. Wikipedia gives the correct definition instead: https://en.wikipedia.org/wiki/Dereference_operator

    It operates on a pointer variable, and returns an l-value equivalent to the value at the pointer address. This is called "dereferencing" the pointer.

    That said, we can dereference the pointer without ever accessing the value it points to. For example:

    char *p = NULL;
    *p;
    

    We dereferenced the NULL pointer without accessing its value. Or we could do:

    p1 = &(*p);
    sz = sizeof(*p);
    

    Again, dereferencing, but never accessing the value. Such code will NOT crash: The crash happens when you actually access the data by an invalid pointer. However, unfortunately, according the the standard, dereferencing an invalid pointer is an undefined behaviour (with a few exceptions), even if you don't try to touch the actual data.

    So in short: dereferencing the pointer means applying the dereference operator to it. That operator just returns an l-value for your future use.

    How to prevent form from submitting multiple times from client side?

    Here's simple way to do that:

    <form onsubmit="return checkBeforeSubmit()">
      some input:<input type="text">
      <input type="submit" value="submit" />
    </form>
    
    <script type="text/javascript">
      var wasSubmitted = false;    
        function checkBeforeSubmit(){
          if(!wasSubmitted) {
            wasSubmitted = true;
            return wasSubmitted;
          }
          return false;
        }    
    </script>
    

    Basic http file downloading and saving to disk in python?

    Another clean way to save the file is this:

    import csv
    import urllib
    
    urllib.retrieve("your url goes here" , "output.csv")
    

    @class vs. #import

    for extra info about file dependencies & #import & @class check this out:

    http://qualitycoding.org/file-dependencies/ itis good article

    summary of the article

    imports in header files:

    • #import the superclass you’re inheriting, and the protocols you’re implementing.
    • Forward-declare everything else (unless it comes from a framework with a master header).
    • Try to eliminate all other #imports.
    • Declare protocols in their own headers to reduce dependencies.
    • Too many forward declarations? You have a Large Class.

    imports in implementation files:

    • Eliminate cruft #imports that aren’t used.
    • If a method delegates to another object and returns what it gets back, try to forward-declare that object instead of #importing it.
    • If including a module forces you to include level after level of successive dependencies, you may have a set of classes that wants to become a library. Build it as a separate library with a master header, so everything can be brought in as a single prebuilt chunk.
    • Too many #imports? You have a Large Class.

    How to split a line into words separated by one or more spaces in bash?

    s='foo bar baz'
    a=( $s )
    echo ${a[0]}
    echo ${a[1]}
    ...
    

    Python send POST with header

    To make POST request instead of GET request using urllib2, you need to specify empty data, for example:

    import urllib2
    req = urllib2.Request("http://am.domain.com:8080/openam/json/realms/root/authenticate?authIndexType=Module&authIndexValue=LDAP")
    req.add_header('X-OpenAM-Username', 'demo')
    req.add_data('')
    r = urllib2.urlopen(req)
    

    How to get PHP $_GET array?

    Yes, here's a code example with some explanation in comments:

    <?php
     // Fill up array with names
    
    $sql=mysql_query("SELECT * FROM fb_registration");
    while($res=mysql_fetch_array($sql))
    {
    
    
      $a[]=$res['username'];
    //$a[]=$res['password'];
    }
    
    //get the q parameter from URL
    $q=$_GET["q"];
    
    //lookup all hints from array if length of q>0
    
    if (strlen($q) > 0)
      {
      $hint="";
      for($i=0; $i<count($a); $i++)
        {
        if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
          {
          if ($hint=="")
            {
            $hint=$a[$i];
            }
          else
            {
            $hint=$hint." , ".$a[$i];
            }
          }
        }
      }
    ?>
    

    Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org

    This terminal command:

    open /Applications/Python\ 3.7/Install\ Certificates.command

    Found here: https://stackoverflow.com/a/57614113/6207266

    Resolved it for me. With my config

    pip install --upgrade certifi

    had no impact.

    Making macOS Installer Packages which are Developer ID ready

    Our example project has two build targets: HelloWorld.app and Helper.app. We make a component package for each and combine them into a product archive.

    A component package contains payload to be installed by the OS X Installer. Although a component package can be installed on its own, it is typically incorporated into a product archive.

    Our tools: pkgbuild, productbuild, and pkgutil

    After a successful "Build and Archive" open $BUILT_PRODUCTS_DIR in the Terminal.

    $ cd ~/Library/Developer/Xcode/DerivedData/.../InstallationBuildProductsLocation
    $ pkgbuild --analyze --root ./HelloWorld.app HelloWorldAppComponents.plist
    $ pkgbuild --analyze --root ./Helper.app HelperAppComponents.plist
    

    This give us the component-plist, you find the value description in the "Component Property List" section. pkgbuild -root generates the component packages, if you don't need to change any of the default properties you can omit the --component-plist parameter in the following command.

    productbuild --synthesize results in a Distribution Definition.

    $ pkgbuild --root ./HelloWorld.app \
        --component-plist HelloWorldAppComponents.plist \
        HelloWorld.pkg
    $ pkgbuild --root ./Helper.app \
        --component-plist HelperAppComponents.plist \
        Helper.pkg
    $ productbuild --synthesize \
        --package HelloWorld.pkg --package Helper.pkg \
        Distribution.xml 
    

    In the Distribution.xml you can change things like title, background, welcome, readme, license, and so on. You turn your component packages and distribution definition with this command into a product archive:

    $ productbuild --distribution ./Distribution.xml \
        --package-path . \
        ./Installer.pkg
    

    I recommend to take a look at iTunes Installers Distribution.xml to see what is possible. You can extract "Install iTunes.pkg" with:

    $ pkgutil --expand "Install iTunes.pkg" "Install iTunes"
    

    Lets put it together

    I usually have a folder named Package in my project which includes things like Distribution.xml, component-plists, resources and scripts.

    Add a Run Script Build Phase named "Generate Package", which is set to Run script only when installing:

    VERSION=$(defaults read "${BUILT_PRODUCTS_DIR}/${FULL_PRODUCT_NAME}/Contents/Info" CFBundleVersion)
    
    PACKAGE_NAME=`echo "$PRODUCT_NAME" | sed "s/ /_/g"`
    TMP1_ARCHIVE="${BUILT_PRODUCTS_DIR}/$PACKAGE_NAME-tmp1.pkg"
    TMP2_ARCHIVE="${BUILT_PRODUCTS_DIR}/$PACKAGE_NAME-tmp2"
    TMP3_ARCHIVE="${BUILT_PRODUCTS_DIR}/$PACKAGE_NAME-tmp3.pkg"
    ARCHIVE_FILENAME="${BUILT_PRODUCTS_DIR}/${PACKAGE_NAME}.pkg"
    
    pkgbuild --root "${INSTALL_ROOT}" \
        --component-plist "./Package/HelloWorldAppComponents.plist" \
        --scripts "./Package/Scripts" \
        --identifier "com.test.pkg.HelloWorld" \
        --version "$VERSION" \
        --install-location "/" \
        "${BUILT_PRODUCTS_DIR}/HelloWorld.pkg"
    pkgbuild --root "${BUILT_PRODUCTS_DIR}/Helper.app" \
        --component-plist "./Package/HelperAppComponents.plist" \
        --identifier "com.test.pkg.Helper" \
        --version "$VERSION" \
        --install-location "/" \
        "${BUILT_PRODUCTS_DIR}/Helper.pkg"
    productbuild --distribution "./Package/Distribution.xml"  \
        --package-path "${BUILT_PRODUCTS_DIR}" \
        --resources "./Package/Resources" \
        "${TMP1_ARCHIVE}"
    
    pkgutil --expand "${TMP1_ARCHIVE}" "${TMP2_ARCHIVE}"
        
    # Patches and Workarounds
    
    pkgutil --flatten "${TMP2_ARCHIVE}" "${TMP3_ARCHIVE}"
    
    productsign --sign "Developer ID Installer: John Doe" \
        "${TMP3_ARCHIVE}" "${ARCHIVE_FILENAME}"
    

    If you don't have to change the package after it's generated with productbuild you could get rid of the pkgutil --expand and pkgutil --flatten steps. Also you could use the --sign paramenter on productbuild instead of running productsign.

    Sign an OS X Installer

    Packages are signed with the Developer ID Installer certificate which you can download from Developer Certificate Utility.

    They signing is done with the --sign "Developer ID Installer: John Doe" parameter of pkgbuild, productbuild or productsign.

    Note that if you are going to create a signed product archive using productbuild, there is no reason to sign the component packages.

    Developer Certificate Utility

    All the way: Copy Package into Xcode Archive

    To copy something into the Xcode Archive we can't use the Run Script Build Phase. For this we need to use a Scheme Action.

    Edit Scheme and expand Archive. Then click post-actions and add a New Run Script Action:

    In Xcode 6:

    #!/bin/bash
    
    PACKAGES="${ARCHIVE_PATH}/Packages"
      
    PACKAGE_NAME=`echo "$PRODUCT_NAME" | sed "s/ /_/g"`
    ARCHIVE_FILENAME="$PACKAGE_NAME.pkg"
    PKG="${OBJROOT}/../BuildProductsPath/${CONFIGURATION}/${ARCHIVE_FILENAME}"
    
    if [ -f "${PKG}" ]; then
        mkdir "${PACKAGES}"
        cp -r "${PKG}" "${PACKAGES}"
    fi
    

    In Xcode 5, use this value for PKG instead:

    PKG="${OBJROOT}/ArchiveIntermediates/${TARGET_NAME}/BuildProductsPath/${CONFIGURATION}/${ARCHIVE_FILENAME}"
    

    In case your version control doesn't store Xcode Scheme information I suggest to add this as shell script to your project so you can simple restore the action by dragging the script from the workspace into the post-action.

    Scripting

    There are two different kinds of scripting: JavaScript in Distribution Definition Files and Shell Scripts.

    The best documentation about Shell Scripts I found in WhiteBox - PackageMaker How-to, but read this with caution because it refers to the old package format.

    Apple Silicon

    In order for the package to run as arm64, the Distribution file has to specify in its hostArchitectures section that it supports arm64 in addition to x86_64:

    <options hostArchitectures="arm64,x86_64" />
    

    Additional Reading

    Known Issues and Workarounds

    Destination Select Pane

    The user is presented with the destination select option with only a single choice - "Install for all users of this computer". The option appears visually selected, but the user needs to click on it in order to proceed with the installation, causing some confusion.

    Example showing the installer bug

    Apples Documentation recommends to use <domains enable_anywhere ... /> but this triggers the new more buggy Destination Select Pane which Apple doesn't use in any of their Packages.

    Using the deprecate <options rootVolumeOnly="true" /> give you the old Destination Select Pane. Example showing old Destination Select Pane


    You want to install items into the current user’s home folder.

    Short answer: DO NOT TRY IT!

    Long answer: REALLY; DO NOT TRY IT! Read Installer Problems and Solutions. You know what I did even after reading this? I was stupid enough to try it. Telling myself I'm sure that they fixed the issues in 10.7 or 10.8.

    First of all I saw from time to time the above mentioned Destination Select Pane Bug. That should have stopped me, but I ignored it. If you don't want to spend the week after you released your software answering support e-mails that they have to click once the nice blue selection DO NOT use this.

    You are now thinking that your users are smart enough to figure the panel out, aren't you? Well here is another thing about home folder installation, THEY DON'T WORK!

    I tested it for two weeks on around 10 different machines with different OS versions and what not, and it never failed. So I shipped it. Within an hour of the release I heart back from users who just couldn't install it. The logs hinted to permission issues you are not gonna be able to fix.

    So let's repeat it one more time: We do not use the Installer for home folder installations!


    RTFD for Welcome, Read-me, License and Conclusion is not accepted by productbuild.

    Installer supported since the beginning RTFD files to make pretty Welcome screens with images, but productbuild doesn't accept them.

    Workarounds: Use a dummy rtf file and replace it in the package by after productbuild is done.

    Note: You can also have Retina images inside the RTFD file. Use multi-image tiff files for this: tiffutil -cat Welcome.tif Welcome_2x.tif -out FinalWelcome.tif. More details.


    Starting an application when the installation is done with a BundlePostInstallScriptPath script:

    #!/bin/bash
    
    LOGGED_IN_USER_ID=`id -u "${USER}"`
    
    if [ "${COMMAND_LINE_INSTALL}" = "" ]
    then
        /bin/launchctl asuser "${LOGGED_IN_USER_ID}" /usr/bin/open -g PATH_OR_BUNDLE_ID
    fi
    
    exit 0
    

    It is important to run the app as logged in user, not as the installer user. This is done with launchctl asuser uid path. Also we only run it when it is not a command line installation, done with installer tool or Apple Remote Desktop.


    error: the details of the application error from being viewed remotely

    Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.

    Details: To enable the details of this specific error message to be viewable on remote machines, please create a tag within a "web.config" configuration file located in the root directory of the current web application. This tag should then have its "mode" attribute set to "Off".

    changing kafka retention period during runtime

    The following is the right way to alter topic config as of Kafka 0.10.2.0:

    bin/kafka-configs.sh --zookeeper <zk_host> --alter --entity-type topics --entity-name test_topic --add-config retention.ms=86400000
    

    Topic config alter operations have been deprecated for bin/kafka-topics.sh.

    WARNING: Altering topic configuration from this script has been deprecated and may be removed in future releases.
         Going forward, please use kafka-configs.sh for this functionality`
    

    How to enter in a Docker container already running with a new TTY

    The "nsinit" way is:

    install nsinit

    git clone [email protected]:dotcloud/docker.git
    cd docker
    make shell
    

    from inside the container:

    go install github.com/dotcloud/docker/pkg/libcontainer/nsinit/nsinit
    

    from outside:

    docker cp id_docker_container:/go/bin/nsinit /root/
    

    use it

    cd /var/lib/docker/execdriver/native/<container_id>/
    nsinit exec bash
    

    Generate Java classes from .XSD files...?

    the easiest way is using command line. Just type in directory of your .xsd file:

    xjc myFile.xsd.
    

    So, the java will generate all Pojos.

    IntelliJ: Error:java: error: release version 5 not supported

    Took me a while to aggregate an actual solution, but here's how to get rid of this compile error.

    1. Open IntelliJ preferences.

    2. Search for "compiler" (or something like "compi").

    3. Scroll down to Maven -->java compiler. In the right panel will be a list of modules and their associated java compile version "target bytecode version."

    4. Select a version >1.5. You may need to upgrade your jdk if one is not available.

    enter image description here

    Difference between rake db:migrate db:reset and db:schema:load

    • db:migrate runs (single) migrations that have not run yet.

    • db:create creates the database

    • db:drop deletes the database

    • db:schema:load creates tables and columns within the existing database following schema.rb. This will delete existing data.

    • db:setup does db:create, db:schema:load, db:seed

    • db:reset does db:drop, db:setup

    • db:migrate:reset does db:drop, db:create, db:migrate

    Typically, you would use db:migrate after having made changes to the schema via new migration files (this makes sense only if there is already data in the database). db:schema:load is used when you setup a new instance of your app.

    I hope that helps.


    UPDATE for rails 3.2.12:

    I just checked the source and the dependencies are like this now:

    • db:create creates the database for the current env

    • db:create:all creates the databases for all envs

    • db:drop drops the database for the current env

    • db:drop:all drops the databases for all envs

    • db:migrate runs migrations for the current env that have not run yet

    • db:migrate:up runs one specific migration

    • db:migrate:down rolls back one specific migration

    • db:migrate:status shows current migration status

    • db:rollback rolls back the last migration

    • db:forward advances the current schema version to the next one

    • db:seed (only) runs the db/seed.rb file

    • db:schema:load loads the schema into the current env's database

    • db:schema:dump dumps the current env's schema (and seems to create the db as well)

    • db:setup runs db:schema:load, db:seed

    • db:reset runs db:drop db:setup

    • db:migrate:redo runs (db:migrate:down db:migrate:up) or (db:rollback db:migrate) depending on the specified migration

    • db:migrate:reset runs db:drop db:create db:migrate

    For further information please have a look at https://github.com/rails/rails/blob/v3.2.12/activerecord/lib/active_record/railties/databases.rake (for Rails 3.2.x) and https://github.com/rails/rails/blob/v4.0.5/activerecord/lib/active_record/railties/databases.rake (for Rails 4.0.x)

    How do I get the command-line for an Eclipse run configuration?

    Scan your workspace .metadata directory for files called *.launch. I forget which plugin directory exactly holds these records, but it might even be the most basic org.eclipse.plugins.core one.

    Add custom buttons on Slick Carousel

    A variation on the answer by @tallgirltaadaa , draw your own button in the shape of a caret:

    var a = $('.MyCarouselContainer').slick({
        prevArrow: '<canvas class="prevArrowCanvas a-left control-c prev slick-prev" width="15" height="50"></canvas>',
        nextArrow: '<canvas class="nextArrowCanvas a-right control-c next slick-next" width="15" height="50"></canvas>'
    });
    
    function drawNextPreviousArrows(strokeColor) {
        var c = $(".prevArrowCanvas")[0];
        var ctx = c.getContext("2d");
        ctx.clearRect(0, 0, c.width, c.height);
        ctx.moveTo(15, 0);
        ctx.lineTo(0, 25);
        ctx.lineTo(15, 50);
        ctx.lineWidth = 2;
        ctx.strokeStyle = strokeColor;
        ctx.stroke();
        var c = $(".nextArrowCanvas")[0];
        var ctx = c.getContext("2d");
        ctx.clearRect(0, 0, c.width, c.height);
        ctx.moveTo(0, 0);
        ctx.lineTo(15, 25);
        ctx.lineTo(0, 50);
        ctx.lineWidth = 2;
        ctx.strokeStyle = strokeColor;
        ctx.stroke();
    }
    drawNextPreviousArrows("#cccccc");
    

    then add the css

    .slick-prev, .slick-next 
        height: 50px;s
    }
    

    How to get the current directory in a C program?

    Look up the man page for getcwd.

    How to resolve "must be an instance of string, string given" prior to PHP 7?

    As of PHP 7.0 type declarations allow scalar types, so these types are now available: self, array, callable, bool, float, int, string. The first three were available in PHP 5, but the last four are new in PHP 7. If you use anything else (e.g. integer or boolean) that will be interpreted as a class name.

    See the PHP manual for more information.

    Prevent content from expanding grid items

    By default, a grid item cannot be smaller than the size of its content.

    Grid items have an initial size of min-width: auto and min-height: auto.

    You can override this behavior by setting grid items to min-width: 0, min-height: 0 or overflow with any value other than visible.

    From the spec:

    6.6. Automatic Minimum Size of Grid Items

    To provide a more reasonable default minimum size for grid items, this specification defines that the auto value of min-width / min-height also applies an automatic minimum size in the specified axis to grid items whose overflow is visible. (The effect is analogous to the automatic minimum size imposed on flex items.)

    Here's a more detailed explanation covering flex items, but it applies to grid items, as well:

    This post also covers potential problems with nested containers and known rendering differences among major browsers.


    To fix your layout, make these adjustments to your code:

    .month-grid {
      display: grid;
      grid-template: repeat(6, 1fr) / repeat(7, 1fr);
      background: #fff;
      grid-gap: 2px;
      min-height: 0;  /* NEW */
      min-width: 0;   /* NEW; needed for Firefox */
    }
    
    .day-item {
      padding: 10px;
      background: #DFE7E7;
      overflow: hidden;  /* NEW */
      min-width: 0;      /* NEW; needed for Firefox */
    }
    

    jsFiddle demo


    1fr vs minmax(0, 1fr)

    The solution above operates at the grid item level. For a container level solution, see this post:

    Generic htaccess redirect www to non-www

    For those that need to able to access the entire site WITHOUT the 'www' prefix.

    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]
    

    Mare sure you add this to the following file

    /site/location/.htaccess 
    

    How to have stored properties in Swift, the same way I had on Objective-C?

    In PURE SWIFT with WEAK reference handling

    import Foundation
    import UIKit
    
    extension CustomView {
        
        // can make private
        static let storedProperties = WeakDictionary<UIView, Properties>()
        
        struct Properties {
            var url: String = ""
            var status = false
            var desc: String { "url: \(url), status: \(status)" }
        }
        
        var properties: Properties {
            get {
                return CustomView.storedProperties.get(forKey: self) ?? Properties()
            }
            set {
                CustomView.storedProperties.set(forKey: self, object: newValue)
            }
        }
    }
    
    var view: CustomView? = CustomView()
    print("1 print", view?.properties.desc ?? "nil")
    view?.properties.url = "abc"
    view?.properties.status = true
    print("2 print", view?.properties.desc ?? "nil")
    view = nil
    

    WeakDictionary.swift

    import Foundation
    
    private class WeakHolder<T: AnyObject>: Hashable {
        weak var object: T?
        let hash: Int
    
        init(object: T) {
            self.object = object
            hash = ObjectIdentifier(object).hashValue
        }
    
        func hash(into hasher: inout Hasher) {
            hasher.combine(hash)
        }
    
        static func ==(lhs: WeakHolder, rhs: WeakHolder) -> Bool {
            return lhs.hash == rhs.hash
        }
    }
    
    class WeakDictionary<T1: AnyObject, T2> {
        private var dictionary = [WeakHolder<T1>: T2]()
    
        func set(forKey: T1, object: T2?) {
            dictionary[WeakHolder(object: forKey)] = object
        }
    
        func get(forKey: T1) -> T2? {
            let obj = dictionary[WeakHolder(object: forKey)]
            return obj
        }
    
        func forEach(_ handler: ((key: T1, value: T2)) -> Void) {
            dictionary.forEach {
                if let object = $0.key.object, let value = dictionary[$0.key] {
                    handler((object, value))
                }
            }
        }
        
        func clean() {
            var removeList = [WeakHolder<T1>]()
            dictionary.forEach {
                if $0.key.object == nil {
                    removeList.append($0.key)
                }
            }
            removeList.forEach {
                dictionary[$0] = nil
            }
        }
    }
    

    Bootstrap modal appearing under background

    I simply removed the position: fixed style from the _modal.scss file and it seems to work fine for me. I still have the background and it works as expected.

    // Modal background
    .modal-backdrop {
      /* commented out position: fixed - bug fix */
      //position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      z-index: $zindex-modal-backdrop;
      background-color: $modal-backdrop-bg;
      // Fade for backdrop
      &.fade {
        opacity: 0;
      }
    

    Kudos to Rick Strahl for the guidance in "Bootstrap Modal Dialog showing under Modal Background".

    How to state in requirements.txt a direct github source

    Normally your requirements.txt file would look something like this:

    package-one==1.9.4
    package-two==3.7.1
    package-three==1.0.1
    ...
    

    To specify a Github repo, you do not need the package-name== convention.

    The examples below update package-two using a GitHub repo. The text between @ and # denotes the specifics of the package.

    Specify commit hash (41b95ec in the context of updated requirements.txt):

    package-one==1.9.4
    git+git://github.com/path/to/package-two@41b95ec#egg=package-two
    package-three==1.0.1
    

    Specify branch name (master):

    git+git://github.com/path/to/package-two@master#egg=package-two
    

    Specify tag (0.1):

    git+git://github.com/path/to/[email protected]#egg=package-two
    

    Specify release (3.7.1):

    git+git://github.com/path/to/package-two@releases/tag/v3.7.1#egg=package-two
    

    Note that #egg=package-two is not a comment here, it is to explicitly state the package name

    This blog post has some more discussion on the topic.

    Why use 'git rm' to remove a file instead of 'rm'?

    If you just use rm, you will need to follow it up with git add <fileRemoved>. git rm does this in one step.

    You can also use git rm --cached which will remove the file from the index (staging it for deletion on the next commit), but keep your copy in the local file system.

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

    1920 is a generic error code that means the service didn't start. My hunch is this:

    http://blog.iswix.com/2008/09/different-year-same-problem.html

    To confirm, with the installer on the abort, retry, ignore, cancel dialog up... go into services.msc and set the username and password manually. If you get a message saying the user was granted logon as service right, try hitting retry on the MSI dialog and see if it starts.

    It could also be missing dependencies or exceptions being thrown in your code.

    Fastest way to convert a dict's keys & values from `unicode` to `str`?

    If you wanted to do this inline and didn't need recursive descent, this might work:

    DATA = { u'spam': u'eggs', u'foo': True, u'bar': { u'baz': 97 } }
    print DATA
    # "{ u'spam': u'eggs', u'foo': True, u'bar': { u'baz': 97 } }"
    
    STRING_DATA = dict([(str(k), v) for k, v in data.items()])
    print STRING_DATA
    # "{ 'spam': 'eggs', 'foo': True, 'bar': { u'baz': 97 } }"
    

    Replace and overwrite instead of appending

    Using python3 pathlib library:

    import re
    from pathlib import Path
    import shutil
    
    shutil.copy2("/tmp/test.xml", "/tmp/test.xml.bak") # create backup
    filepath = Path("/tmp/test.xml")
    content = filepath.read_text()
    filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))
    

    Similar method using different approach to backups:

    from pathlib import Path
    
    filepath = Path("/tmp/test.xml")
    filepath.rename(filepath.with_suffix('.bak')) # different approach to backups
    content = filepath.read_text()
    filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))
    

    Plot different DataFrames in the same figure

    If you a running Jupyter/Ipython notebook and having problems using;

    ax = df1.plot()

    df2.plot(ax=ax)

    Run the command inside of the same cell!! It wont, for some reason, work when they are separated into sequential cells. For me at least.

    How do you add input from user into list in Python

    shopList = [] 
    maxLengthList = 6
    while len(shopList) < maxLengthList:
        item = input("Enter your Item to the List: ")
        shopList.append(item)
        print shopList
    print "That's your Shopping List"
    print shopList
    

    openssl s_client using a proxy

    Even with openssl v1.1.0 I had some problems passing our proxy, e.g. s_client: HTTP CONNECT failed: 400 Bad Request That forced me to write a minimal Java-class to show the SSL-Handshake

        public static void main(String[] args) throws IOException, URISyntaxException {
        HttpHost proxy = new HttpHost("proxy.my.company", 8080);
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setRoutePlanner(routePlanner)
                .build();
        URI uri = new URIBuilder()
                .setScheme("https")
                .setHost("www.myhost.com")
                .build();
        HttpGet httpget = new HttpGet(uri);
        httpclient.execute(httpget);
    }
    

    With following dependency:

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
            <type>jar</type>
        </dependency>
    

    you can run it with Java SSL Logging turned on

    This should produce nice output like

    trustStore provider is :
    init truststore
    adding as trusted cert:
      Subject: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US
      Issuer:  CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US
      Algorithm: RSA; Serial number: 0xc3517
      Valid from Mon Jun 21 06:00:00 CEST 1999 until Mon Jun 22 06:00:00 CEST 2020
    
    adding as trusted cert:
      Subject: CN=SecureTrust CA, O=SecureTrust Corporation, C=US
      Issuer:  CN=SecureTrust CA, O=SecureTrust Corporation, C=US
    (....)
    

    Paste multiple columns together

    Just to add additional solution with Reduce which probably is slower than do.call but probebly better than apply because it will avoid the matrix conversion. Also, instead a for loop we could just use setdiff in order to remove unwanted columns

    cols <- c('b','c','d')
    data$x <- Reduce(function(...) paste(..., sep = "-"), data[cols])
    data[setdiff(names(data), cols)]
    #   a     x
    # 1 1 a-d-g
    # 2 2 b-e-h
    # 3 3 c-f-i
    

    Alternatively we could update data in place using the data.table package (assuming fresh data)

    library(data.table)
    setDT(data)[, x := Reduce(function(...) paste(..., sep = "-"), .SD[, mget(cols)])]
    data[, (cols) := NULL]
    data
    #    a     x
    # 1: 1 a-d-g
    # 2: 2 b-e-h
    # 3: 3 c-f-i
    

    Another option is to use .SDcols instead of mget as in

    setDT(data)[, x := Reduce(function(...) paste(..., sep = "-"), .SD), .SDcols = cols]
    

    The network adapter could not establish the connection - Oracle 11g

    First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.

    vba: get unique values from array

    If the order of the deduplicated array does not matter to you, you can use my pragmatic function:

    Function DeDupArray(ia() As String)
      Dim newa() As String
      ReDim newa(999)
      ni = -1
      For n = LBound(ia) To UBound(ia)
        dup = False
        If n <= UBound(ia) Then
          For k = n + 1 To UBound(ia)
            If ia(k) = ia(n) Then dup = True
          Next k
    
          If dup = False And Trim(ia(n)) <> "" Then
            ni = ni + 1
            newa(ni) = ia(n)
          End If
        End If
      Next n
    
      If ni > -1 Then
        ReDim Preserve newa(ni)
      Else
        ReDim Preserve newa(1)
      End If
    
      DeDupArray = newa
    End Function
    
    
    
    Sub testdedup()
    Dim m(5) As String
    Dim m2() As String
    
    m(0) = "Horse"
    m(1) = "Cow"
    m(2) = "Dear"
    m(3) = "Horse"
    m(4) = "Joke"
    m(5) = "Cow"
    
    m2 = DeDupArray(m)
    t = ""
    For n = LBound(m2) To UBound(m2)
      t = t & n & "=" & m2(n) & " "
    Next n
    MsgBox t
    End Sub
    

    From the test function, it will result in the following deduplicated array:

    "0=Dear 1=Horse 2=Joke 3=Cow "