Programs & Examples On #Delphi

Delphi is a language for rapid development of native Windows, macOS, Linux, iOS, and Android applications through use of Object Pascal. The name refers to the Delphi language as well as its libraries, compiler and IDE which is used to help edit and debug Delphi projects.

How to track down access violation "at address 00000000"

Here is a real quick temporary fix, at least until you reboot again but it will get rid of a persistent access. I had installed a program that works fine but for some reason, there is a point that did not install correctly in the right file. So when it cannot access the file, it pops up the access denied but instead of just one, it keeps trying to start it up so even searching for the location to stop it permanently, it will continue to pop up more and more and more every 3 seconds. To stop that from happening at least temporarily, do the following...

  1. Ctl+Alt+Del
  2. Open your Task Manager
  3. Note down the name of the program that's requesting access (you may see it in your application's tab)
  4. Click on your Processes tab
  5. Scroll through until you find the Process matching the program name and click on it
  6. Click End Process

That will prevent the window from persistently popping up, at least until you reboot. I know that does not solve the problem but like anything, there is a process of elimination and this step here will at least make it a little less annoying.

Is there a program to decompile Delphi?

Here's a list : http://delphi.about.com/od/devutilities/a/decompiling_3.htm (and this page mentions some more : http://www.program-transformation.org/Transform/DelphiDecompilers )

I've used DeDe on occasion, but it's not really all that powerfull, and it's not up-to-date with current Delphi versions (latest version it supports is Delphi 7 I believe)

What do I do when my program crashes with exception 0xc0000005 at address 0?

I was getting the same issue with a different application,

Faulting application name: javaw.exe, version: 8.0.51.16, time stamp: 0x55763d32
Faulting module name: mscorwks.dll, version: 2.0.50727.5485, time stamp: 0x53a11d6c
Exception code: 0xc0000005
Fault offset: 0x0000000000501090
Faulting process id: 0x2960
Faulting application start time: 0x01d0c39a93c695f2
Faulting application path: C:\Program Files\Java\jre1.8.0_51\bin\javaw.exe
Faulting module path:C:\Windows\Microsoft.NET\Framework64\v2.0.50727\mscorwks.dll

I was using the The Enhanced Mitigation Experience Toolkit (EMET) from Microsoft and I found by disabling the EMET features on javaw.exe in my case as this was the faulting application, it enabled my application to run successfully. Make sure you don't have any similar software with security protections on memory.

How do I include a newline character in a string in Delphi?

my_string := 'Hello,' + #13#10 + 'world!';

#13#10 is the CR/LF characters in decimal

Split a string into an array of strings based on a delimiter

I wrote this function which returns linked list of separated strings by specific delimiter. Pure free pascal without modules.

Program split_f;

type
    PTItem = ^TItem;
    TItem = record
        str : string;
        next : PTItem;
    end;

var
    s : string;
    strs : PTItem;

procedure split(str : string;delim : char;var list : PTItem);
var
    i : integer;
    buff : PTItem;
begin
    new(list);
    buff:= list;
    buff^.str:='';
    buff^.next:=nil;

    for i:=1 to length(str) do begin
        if (str[i] = delim) then begin
            new(buff^.next);
            buff:=buff^.next;
            buff^.str := '';
            buff^.next := nil;
        end
        else
        buff^.str:= buff^.str+str[i];
    end;
end;

procedure print(var list:PTItem);
var
    buff : PTItem;
begin
    buff := list;
    while buff<>nil do begin
        writeln(buff^.str);
        buff:= buff^.next;
    end;
end;

begin

    s := 'Hi;how;are;you?';

    split(s, ';', strs);
    print(strs);


end.

Indentation shortcuts in Visual Studio

Tab to tab right, shift-tab to tab left.

The application was unable to start correctly (0xc000007b)

You can have this if you are trying to manifest your application that it has a dependancy on the Microsoft.Windows.Common-Controls assembly. You do this when you want to load Version 6 of the common controls library - so that visual styles are applied to common controls.

You probably followed Microsoft's original documentation way back from Windows XP days, and added the following to your application's manifest:

<!-- Dependancy on Common Controls version 6 -->
<dependency>
    <dependentAssembly>
        <assemblyIdentity
                type="win32"
                name="Microsoft.Windows.Common-Controls"
                version="6.0.0.0"
                processorArchitecture="X86"
                publicKeyToken="6595b64144ccf1df"
                language="*"/>
    </dependentAssembly>
</dependency>

Windows XP is no longer the OS, and you're no longer a 32-bit application. In the intervening 17 years Microsoft updated their documentation; now it's time for you to update your manifest:

<!-- Dependancy on Common Controls version 6 -->
<dependency>
    <dependentAssembly>
        <assemblyIdentity
                type="win32"
                name="Microsoft.Windows.Common-Controls"
                version="6.0.0.0"
                processorArchitecture="*"
                publicKeyToken="6595b64144ccf1df"
                language="*"/>
    </dependentAssembly>
</dependency>

Raymond Chen has a lovely history of the Common Controls:

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

The most likely explanations for that error are:

  1. The file you are attempting to load is not an executable file. CreateProcess requires you to provide an executable file. If you wish to be able to open any file with its associated application then you need ShellExecute rather than CreateProcess.
  2. There is a problem loading one of the dependencies of the executable, i.e. the DLLs that are linked to the executable. The most common reason for that is a mismatch between a 32 bit executable and a 64 bit DLL, or vice versa. To investigate, use Dependency Walker's profile mode to check exactly what is going wrong.

Reading down to the bottom of the code, I can see that the problem is number 1.

Convert web page to image

http://code.google.com/p/wkhtmltopdf/ again..

Somebody mentioned this already.. I will write about it in more detail...

Contrary to what the name implies, there is html page to image converter as well.
It supports png and jpeg.
One can modify the user agent string of all requested urls and minimum width and height of the webpage.
It is possible to add new headers and set it for all requests.
It works on Windows and Linux.
It can ignore webpage errors.
It uses Webkit and Qt library. It installs easily, no additional libaries are needed
(everything is included in the distribution).
It is free and regularly updated. There are binaries available for both Linux and Windows.
It can handle flash on Windows. (It may do so on Linux as well, untested)

Up, Down, Left and Right arrow keys do not trigger KeyDown event

I was having the exact same problem. I considered the answer @Snarfblam provided; however, if you read the documentation on MSDN, the ProcessCMDKey method is meant to override key events for menu items in an application.

I recently stumbled across this article from microsoft, which looks quite promising: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown.aspx. According to microsoft, the best thing to do is set e.IsInputKey=true; in the PreviewKeyDown event after detecting the arrow keys. Doing so will fire the KeyDown event.

This worked quite well for me and was less hack-ish than overriding the ProcessCMDKey.

Performance differences between ArrayList and LinkedList

Ignore this answer for now. The other answers, particularly that of aix, are mostly correct. Over the long term they're the way to bet. And if you have enough data (on one benchmark on one machine, it seemed to be about one million entries) ArrayList and LinkedList do currently work as advertized. However, there are some fine points that apply in the early 21st century.

Modern computer technology seems, by my testing, to give an enormous edge to arrays. Elements of an array can be shifted and copied at insane speeds. As a result arrays and ArrayList will, in most practical situations, outperform LinkedList on inserts and deletes, often dramatically. In other words, ArrayList will beat LinkedList at its own game.

The downside of ArrayList is it tends to hang onto memory space after deletions, where LinkedList gives up space as it gives up entries.

The bigger downside of arrays and ArrayList is they fragment free memory and overwork the garbage collector. As an ArrayList expands, it creates new, bigger arrays, copies the old array to the new one, and frees the old one. Memory fills with big contiguous chunks of free memory that are not big enough for the next allocation. Eventually there's no suitable space for that allocation. Even though 90% of memory is free, no individual piece is big enough to do the job. The GC will work frantically to move things around, but if it takes too long to rearrange the space, it will throw an OutOfMemoryException. If it doesn't give up, it can still slow your program way down.

The worst of it is this problem can be hard to predict. Your program will run fine one time. Then, with a bit less memory available, with no warning, it slows or stops.

LinkedList uses small, dainty bits of memory and GC's love it. It still runs fine when you're using 99% of your available memory.

So in general, use ArrayList for smaller sets of data that are not likely to have most of their contents deleted, or when you have tight control over creation and growth. (For instance, creating one ArrayList that uses 90% of memory and using it without filling it for the duration of the program is fine. Continually creating and freeing ArrayList instances that use 10% of memory will kill you.) Otherwise, go with LinkedList (or a Map of some sort if you need random access). If you have very large collections (say over 100,000 elements), no concerns about the GC, and plan lots of inserts and deletes and no random access, run a few benchmarks to see what's fastest.

How do I update all my CPAN modules to their latest versions?

Try perl -MCPAN -e "upgrade /(.\*)/". It works fine for me.

How to test enum types?

If you use all of the months in your code, your IDE won't let you compile, so I think you don't need unit testing.

But if you are using them with reflection, even if you delete one month, it will compile, so it's valid to put a unit test.

onKeyDown event not working on divs in React

You're missing the binding of the method in the constructor. This is how React suggests that you do it:

class Whatever {
  constructor() {
    super();
    this.onKeyPressed = this.onKeyPressed.bind(this);
  }

  onKeyPressed(e) {
    // your code ...
  }

  render() {
    return (<div onKeyDown={this.onKeyPressed} />);
  }
}

There are other ways of doing this, but this will be the most efficient at runtime.

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

I had this same problem, restart the command prompt and then check try mvn --version. It was probably set and working the whole time but command prompt needed to be restarted to be able to access the new system variable.

What are the specific differences between .msi and setup.exe file?

An MSI is a Windows Installer database. Windows Installer (a service installed with Windows) uses this to install software on your system (i.e. copy files, set registry values, etc...).

A setup.exe may either be a bootstrapper or a non-msi installer. A non-msi installer will extract the installation resources from itself and manage their installation directly. A bootstrapper will contain an MSI instead of individual files. In this case, the setup.exe will call Windows Installer to install the MSI.

Some reasons you might want to use a setup.exe:

  • Windows Installer only allows one MSI to be installing at a time. This means that it is difficult to have an MSI install other MSIs (e.g. dependencies like the .NET framework or C++ runtime). Since a setup.exe is not an MSI, it can be used to install several MSIs in sequence.
  • You might want more precise control over how the installation is managed. An MSI has very specific rules about how it manages the installations, including installing, upgrading, and uninstalling. A setup.exe gives complete control over the software configuration process. This should only be done if you really need the extra control since it is a lot of work, and it can be tricky to get it right.

How to pass command-line arguments to a PowerShell ps1 file

You may not get "xuxu p1 p2 p3 p4" as it seems. But when you are in PowerShell and you set

PS > set-executionpolicy Unrestricted -scope currentuser

You can run those scripts like this:

./xuxu p1 p2 p3 p4

or

.\xuxu p1 p2 p3 p4

or

./xuxu.ps1 p1 p2 p3 p4

I hope that makes you a bit more comfortable with PowerShell.

What is the difference between 'E', 'T', and '?' for Java generics?

A type variable, <T>, can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable.

The most commonly used type parameter names are:

  • E - Element (used extensively by the Java Collections Framework)
  • K - Key
  • N - Number
  • T - Type
  • V - Value

In Java 7 it is permitted to instantiate like this:

Foo<String, Integer> foo = new Foo<>(); // Java 7
Foo<String, Integer> foo = new Foo<String, Integer>(); // Java 6

How do I give PHP write access to a directory?

1st Figure out which user is owning httpd process using the following command

ps aux | grep httpd

you will get a several line response like this:

phpuser   17121  0.0  0.2 414060  7928 ?        SN   03:49   0:00 /usr/sbin/httpd

Here 1st column shows the user name. So now you know the user who is trying to write files, which is in this case phpuser You can now go ahead and set the permission for directory where your php script is trying to write something:

sudo chown phpuser:phpuser PhpCanWriteHere
sudo chmod 755 PhpCanWriteHere

How do I migrate an SVN repository with history to a new Git repository?

Several answers here refer to https://github.com/nirvdrum/svn2git, but for large repositories this can be slow. I had a try using https://github.com/svn-all-fast-export/svn2git instead which is a tool with exactly the same name but was used to migrate KDE from SVN to Git.

Slightly more work to set it up but when done the conversion itself for me took minutes where the other script spent hours.

JavaScriptSerializer - JSON serialization of enum as string

I wasn't able to change the source model like in the top answer (of @ob.), and I didn't want to register it globally like @Iggy. So I combined https://stackoverflow.com/a/2870420/237091 and @Iggy's https://stackoverflow.com/a/18152942/237091 to allow setting up the string enum converter on during the SerializeObject command itself:

Newtonsoft.Json.JsonConvert.SerializeObject(
    objectToSerialize, 
    Newtonsoft.Json.Formatting.None, 
    new Newtonsoft.Json.JsonSerializerSettings()
    {
        Converters = new List<Newtonsoft.Json.JsonConverter> {
            new Newtonsoft.Json.Converters.StringEnumConverter()
        }
    })

What's a "static method" in C#?

From another point of view: Consider that you want to make some changes on a single String. for example you want to make the letters Uppercase and so on. you make another class named "Tools" for these actions. there is no meaning of making instance of "Tools" class because there is not any kind of entity available inside that class (compare to "Person" or "Teacher" class). So we use static keyword in order to use "Tools" class without making any instance of that, and when you press dot after class name ("Tools") you can have access to the methods you want.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Tools.ToUpperCase("Behnoud Sherafati"));
        Console.ReadKey();
    }
}

public static class Tools
{
    public static string ToUpperCase(string str)
    {
        return str.ToUpper();

    }
}
}

Skip Git commit hooks

For those very beginners who has spend few hours for this commit (with comment and no verify) with no further issue

git commit -m "Some comments" --no-verify

Return Max Value of range that is determined by an Index & Match lookup

You can easily change the match-type to 1 when you are looking for the greatest value or to -1 when looking for the smallest value.

adding child nodes in treeview

You can improve that code

 private void Form1_Load(object sender, EventArgs e)
    {
        /*
         D:\root\Project1\A\A.pdf
         D:\root\Project1\B\t.pdf
         D:\root\Project2\c.pdf
         */
        List<string> n = new List<string>();
        List<string> kn = new List<string>();
        n = Directory.GetFiles(@"D:\root\", "*.*", SearchOption.AllDirectories).ToList();
        kn = Directory.GetDirectories(@"D:\root\", "*.*", SearchOption.AllDirectories).ToList();
        foreach (var item in kn)
        {
            treeView1.Nodes.Add(item.ToString());
        }
        for (int i = 0; i < treeView1.Nodes.Count; i++)
        {
            n = Directory.GetFiles(treeView1.Nodes[i].Text, "*.*", SearchOption.AllDirectories).ToList();
            for (int zik = 0; zik < n.Count; zik++)
            {
                treeView1.Nodes[i].Nodes.Add(n[zik].ToString());
            }
        }        
    }

Smart way to truncate long strings

Here's my solution, which has a few improvements over other suggestions:

String.prototype.truncate = function(){
    var re = this.match(/^.{0,25}[\S]*/);
    var l = re[0].length;
    var re = re[0].replace(/\s$/,'');
    if(l < this.length)
        re = re + "&hellip;";
    return re;
}

// "This is a short string".truncate();
"This is a short string"

// "Thisstringismuchlongerthan25characters".truncate();
"Thisstringismuchlongerthan25characters"

// "This string is much longer than 25 characters and has spaces".truncate();
"This string is much longer&hellip;"

It:

  • Truncates on the first space after 25 characters
  • Extends the JavaScript String object, so it can be used on (and chained to) any string.
  • Will trim the string if truncation results in a trailing space;
  • Will add the unicode hellip entity (ellipsis) if the truncated string is longer than 25 characters

How to check if Thread finished execution

If you don't want to block the current thread by waiting/checking for the other running thread completion, you can implement callback method like this.

Action onCompleted = () => 
{  
    //On complete action
};

var thread = new Thread(
  () =>
  {
    try
    {
      // Do your work
    }
    finally
    {
      onCompleted();
    }
  });
thread.Start();

If you are dealing with controls that doesn't support cross-thread operation, then you have to invoke the callback method

this.Invoke(onCompleted);

Eventviewer eventid for lock and unlock

For Windows 10 the event ID for lock=4800 and unlock=4801.

As it says in the answer provided by Mario and User 00000, you will need to enable logging of lock and unlock events by using their method described above by running gpedit.msc and navigating to the branch they indicated:

Computer Configuration -> Windows Settings -> Security Settings -> Advanced Audit Policy Configuration -> System Audit Policies - Local Group Policy Object -> Logon/Logoff -> Audit Other Login/Logoff

Enable for both success and failure events.

After enabling logging of those events you can filter for Event ID 4800 and 4801 directly.

This method works for Windows 10 as I just used it to filter my security logs after locking and unlocking my computer.

$lookup on ObjectId's in an array

Aggregating with $lookup and subsequent $group is pretty cumbersome, so if (and that's a medium if) you're using node & Mongoose or a supporting library with some hints in the schema, you could use a .populate() to fetch those documents:

var mongoose = require("mongoose"),
    Schema = mongoose.Schema;

var productSchema = Schema({ ... });

var orderSchema = Schema({
  _id     : Number,
  products: [ { type: Schema.Types.ObjectId, ref: "Product" } ]
});

var Product = mongoose.model("Product", productSchema);
var Order   = mongoose.model("Order", orderSchema);

...

Order
    .find(...)
    .populate("products")
    ...

Passing data between controllers in Angular JS?

I saw the answers here, and it is answering the question of sharing data between controllers, but what should I do if I want one controller to notify the other about the fact that the data has been changed (without using broadcast)? EASY! Just using the famous visitor pattern:

myApp.service('myService', function() {

    var visitors = [];

    var registerVisitor = function (visitor) {
        visitors.push(visitor);
    }

    var notifyAll = function() {
        for (var index = 0; index < visitors.length; ++index)
            visitors[index].visit();
    }

    var myData = ["some", "list", "of", "data"];

    var setData = function (newData) {
        myData = newData;
        notifyAll();
    }

    var getData = function () {
        return myData;
    }

    return {
        registerVisitor: registerVisitor,
        setData: setData,
        getData: getData
    };
}

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

        var setData = function (data) {
            myService.setData(data);
        }

    }
]);

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

        myService.registerVisitor(this);

        this.visit = function () {
            $scope.data = myService.getData();
        }

        $scope.data = myService.getData();
    }
]);

In this simple manner, one controller can update another controller that some data has been updated.

In jQuery, what's the best way of formatting a number to 2 decimal places?

If you're doing this to several fields, or doing it quite often, then perhaps a plugin is the answer.
Here's the beginnings of a jQuery plugin that formats the value of a field to two decimal places.
It is triggered by the onchange event of the field. You may want something different.

<script type="text/javascript">

    // mini jQuery plugin that formats to two decimal places
    (function($) {
        $.fn.currencyFormat = function() {
            this.each( function( i ) {
                $(this).change( function( e ){
                    if( isNaN( parseFloat( this.value ) ) ) return;
                    this.value = parseFloat(this.value).toFixed(2);
                });
            });
            return this; //for chaining
        }
    })( jQuery );

    // apply the currencyFormat behaviour to elements with 'currency' as their class
    $( function() {
        $('.currency').currencyFormat();
    });

</script>   
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">

Update multiple rows in same query using PostgreSQL

For updating multiple rows in a single query, you can try this

UPDATE table_name
SET 
column_1 = CASE WHEN any_column = value and any_column = value THEN column_1_value end,
column_2 = CASE WHEN any_column = value and any_column = value THEN column_2_value end,
column_3 = CASE WHEN any_column = value and any_column = value THEN column_3_value end,
.
.
.
column_n = CASE WHEN any_column = value and any_column = value THEN column_n_value end

if you don't need additional condition then remove and part of this query

How to Set AllowOverride all

If you are using Linux you may edit the code in the directory of

/etc/httpd/conf/httpd.conf

now, here find the code line kinda like

# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#
    AllowOverride None
#
# Controls who can get stuff from this server.
#
    Order allow,deny
    Allow from all

</Directory>

Change the AllowOveride None to AllowOveride All

Now now you can set any kind of rule in your .httacess file inside your directories if any other operating system just try to find the file of httpd.conf and edit it.

Multiple distinct pages in one HTML file

I used the following trick for the same problem. The good thing is it doesn't require any javascript.

CSS:

.body {
     margin: 0em;
}

.page {
    width: 100vw;
    height: 100vh;
    position: fixed;
    top: 0;
    left: -100vw;
    overflow-y: auto;
    z-index: 0;
    background-color: hsl(0,0%,100%);
}

  .page:target {
    left: 0vw;
    z-index: 1;
}

HTML:

<ul>
    <li>Click <a href="#one">here</a> for page 1</li>
    <li>Click <a href="#two">here</a> for page 2</li>
</ul>

<div class="page" id="one">
    Content of page 1 goes here.

    <ul>
        <li><a href="#">Back</a></li>
        <li><a href="#two">Page 2</a></li>
    </ul>
</div>

<div class="page" id="two">
    Content of page 2 goes here.

    <ul style="margin-bottom: 100vh;">
        <li><a href="#">Back</a></li>
        <li><a href="#one">Page 1</a></li>
    </ul>
</div>

See a JSFiddle.

Added advantage: as your url changes along, you can use it to link to specific pages. This is something the method won't let you do.

Hope this helps!

How to get the date and time values in a C program?

strftime (C89)

Martin mentioned it, here's an example:

main.c

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

int main(void) {
    time_t t = time(NULL);
    struct tm *tm = localtime(&t);
    char s[64];
    assert(strftime(s, sizeof(s), "%c", tm));
    printf("%s\n", s);
    return 0;
}

GitHub upstream.

Compile and run:

gcc -std=c89 -Wall -Wextra -pedantic -o main.out main.c
./main.out

Sample output:

Thu Apr 14 22:39:03 2016

The %c specifier produces the same format as ctime.

One advantage of this function is that it returns the number of bytes written, allowing for better error control in case the generated string is too long:

RETURN VALUE

  Provided  that  the  result string, including the terminating null byte, does not exceed max bytes, strftime() returns the number of bytes (excluding the terminating null byte) placed in the array s.  If the length of the result string (including the terminating null byte) would exceed max bytes, then
   strftime() returns 0, and the contents of the array are undefined.
  Note that the return value 0 does not necessarily indicate an error.  For example, in many locales %p yields an empty string.  An empty format string will likewise yield an empty string.

asctime and ctime (C89, deprecated in POSIX 7)

asctime is a convenient way to format a struct tm:

main.c

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

int main(void) {
    time_t t = time(NULL);
    struct tm *tm = localtime(&t);
    printf("%s", asctime(tm));
    return 0;
}

Sample output:

Wed Jun 10 16:10:32 2015

And there is also ctime() which the standard says is a shortcut for:

asctime(localtime())

As mentioned by Jonathan Leffler, the format has the shortcoming of not having timezone information.

POSIX 7 marked those functions as "obsolescent" so they could be removed in future versions:

The standard developers decided to mark the asctime() and asctime_r() functions obsolescent even though asctime() is in the ISO C standard due to the possibility of buffer overflow. The ISO C standard also provides the strftime() function which can be used to avoid these problems.

C++ version of this question: How to get current time and date in C++?

Tested in Ubuntu 16.04.

How to connect to a MySQL Data Source in Visual Studio

In order to get the MySQL Database item in the Choose Data Source window, one should install the MySQL for Visual Studio package available here (the last version today is 1.2.6):

https://dev.mysql.com/downloads/windows/visualstudio/

How to dump raw RTSP stream to file?

With this command I had poor image quality

ffmpeg -i rtsp://192.168.XXX.XXX:554/live.sdp -vcodec copy -acodec copy -f mp4 -y MyVideoFFmpeg.mp4

With this, almost without delay, I got good image quality.

ffmpeg -i rtsp://192.168.XXX.XXX:554/live.sdp -b 900k -vcodec copy -r 60 -y MyVdeoFFmpeg.avi

Button text toggle in jquery

If you're setting the button text by using the 'value' attribute you'll need to set

  • $(this).val()

instead of:

  • $(this).text()

Also in my situation it worked better to add the JQuery direct to the onclick event of the button:

onclick="$(this).val(function (i, text) { return text == 'PUSH ME' ? 'DON'T PUSH ME' : 'PUSH ME'; });"

selenium - chromedriver executable needs to be in PATH

Try this :

pip install webdriver-manager
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(ChromeDriverManager().install())

Nested iframes, AKA Iframe Inception

You probably have a timing issue. Your document.ready commend is probably firing before the the second iFrame is loaded. You dont have enough info to help much further- but let us know if that seems like the possible issue.

Uninstall Node.JS using Linux command line?

Edit: If you know which package manager was used to install, it is best to uninstall with the same package manager. Examples for apt, make, yum are in other answers.

This is a manual approach:

Running which node will return something like /path/bin/node.

Then run cd /path

This is all that is added by Node.JS.

rm -r bin/node bin/node-waf include/node lib/node lib/pkgconfig/nodejs.pc share/man/man1/node.1

Now the only thing I don't know about is npm and what it has installed. If you install npm again into a custom path that starts off empty, then you can see what it adds and then you will be able to make a list for npm similar to the above list I made for node.

Convert wchar_t to char

Here's another way of doing it, remember to use free() on the result.

char* wchar_to_char(const wchar_t* pwchar)
{
    // get the number of characters in the string.
    int currentCharIndex = 0;
    char currentChar = pwchar[currentCharIndex];

    while (currentChar != '\0')
    {
        currentCharIndex++;
        currentChar = pwchar[currentCharIndex];
    }

    const int charCount = currentCharIndex + 1;

    // allocate a new block of memory size char (1 byte) instead of wide char (2 bytes)
    char* filePathC = (char*)malloc(sizeof(char) * charCount);

    for (int i = 0; i < charCount; i++)
    {
        // convert to char (1 byte)
        char character = pwchar[i];

        *filePathC = character;

        filePathC += sizeof(char);

    }
    filePathC += '\0';

    filePathC -= (sizeof(char) * charCount);

    return filePathC;
}

Relative Paths in Javascript in an external file

Please use the following syntax to enjoy the luxury of asp.net tilda ("~") in javascript

<script src=<%=Page.ResolveUrl("~/MasterPages/assets/js/jquery.js")%>></script>

Is it possible to create a File object from InputStream

If you do not want to use other library, here is a simple function to convert InputStream to OutputStream.

public static void copyStream(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while ((read = in.read(buffer)) != -1) {
        out.write(buffer, 0, read);
    }
}

Now you can easily write an Inputstream into file by using FileOutputStream-

FileOutputStream out = new FileOutputStream(outFile);
copyStream (inputStream, out);
out.close();

Integration Testing POSTing an entire object to Spring MVC controller

One of the main purposes of integration testing with MockMvc is to verify that model objects are correclty populated with form data.

In order to do it you have to pass form data as they're passed from actual form (using .param()). If you use some automatic conversion from NewObject to from data, your test won't cover particular class of possible problems (modifications of NewObject incompatible with actual form).

How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

You can get all keys in the Request.Form and then compare and get your desired values.

Your method body will look like this: -

List<int> listValues = new List<int>();
foreach (string key in Request.Form.AllKeys)
{
    if (key.StartsWith("List"))
    {
        listValues.Add(Convert.ToInt32(Request.Form[key]));
    }
}

How to add new DataRow into DataTable?

If need to copy from another table then need to copy structure first:

DataTable copyDt = existentDt.Clone();
copyDt.ImportRow(existentDt.Rows[0]);

Open source PDF library for C/C++ application?

I worked on a project that required a pdf report. After searching for online I found the PoDoFo library. Seemed very robust. I did not need all the features, so I created a wrapper to abstract away some of the complexity. Wasn't too difficult. You can find the library here:

http://podofo.sourceforge.net/

Enjoy!

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

select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
  from (select id, name, author_id, count(1) as count_1
          from names
          group by id, name, author_id) n1
inner join (select distinct(author_id), count(1) as total_count
              from names) n2
  on (n2.author_id = n1.author_id)
Where true

used distinct if more inner join, because more join group performance is slow

How to create a directory if it doesn't exist using Node.js?

I had to create sub-directories if they didn't exist. I used this:

const path = require('path');
const fs = require('fs');

function ensureDirectoryExists(p) {
    //console.log(ensureDirectoryExists.name, {p});
    const d = path.dirname(p);
    if (d && d !== p) {
        ensureDirectoryExists(d);
    }
    if (!fs.existsSync(d)) {
        fs.mkdirSync(d);
    }
}

How do I convert an NSString value to NSData?

In case of Swift Developer coming here,

to convert from NSString / String to NSData

var _nsdata = _nsstring.dataUsingEncoding(NSUTF8StringEncoding)

MySQL load NULL values from CSV data

This will do what you want. It reads the fourth field into a local variable, and then sets the actual field value to NULL, if the local variable ends up containing an empty string:

LOAD DATA INFILE '/tmp/testdata.txt'
INTO TABLE moo
FIELDS TERMINATED BY ","
LINES TERMINATED BY "\n"
(one, two, three, @vfour, five)
SET four = NULLIF(@vfour,'')
;

If they're all possibly empty, then you'd read them all into variables and have multiple SET statements, like this:

LOAD DATA INFILE '/tmp/testdata.txt'
INTO TABLE moo
FIELDS TERMINATED BY ","
LINES TERMINATED BY "\n"
(@vone, @vtwo, @vthree, @vfour, @vfive)
SET
one = NULLIF(@vone,''),
two = NULLIF(@vtwo,''),
three = NULLIF(@vthree,''),
four = NULLIF(@vfour,'')
;

Add a prefix string to beginning of each line

awk '$0="prefix"$0' file > new_file

With Perl(in place replacement):

perl -pi 's/^/prefix/' file

Why use getters and setters/accessors?

From a object orientation design standpoint both alternatives can be damaging to the maintenance of the code by weakening the encapsulation of the classes. For a discussion you can look into this excellent article: http://typicalprogrammer.com/?p=23

How to terminate the script in JavaScript?

If you just want to stop further code from executing without "throwing" any error, you can temporarily override window.onerror as shown in cross-exit:

function exit(code) {
    const prevOnError = window.onerror
    window.onerror = () => {
        window.onerror = prevOnError
        return true
    }

    throw new Error(`Script termination with code ${code || 0}.`)
}

console.log("This message is logged.");
exit();
console.log("This message isn't logged.");

SQL Server: Get data for only the past year

Look up dateadd in BOL

dateadd(yy,-1,getdate())

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

JPQL mostly is case-insensitive. One of the things that is case-sensitive is Java entity names. Change your query to:

"SELECT r FROM FooBar r"

Auto highlight text in a textbox control

On events "Enter" (for example: press Tab key) or "First Click" all text will be selected. dotNET 4.0

public static class TbHelper
{
    // Method for use
    public static void SelectAllTextOnEnter(TextBox Tb)
    {
        Tb.Enter += new EventHandler(Tb_Enter);
        Tb.Click += new EventHandler(Tb_Click);
    }

    private static TextBox LastTb;

    private static void Tb_Enter(object sender, EventArgs e)
    {
        var Tb = (TextBox)sender;
        Tb.SelectAll();
        LastTb = Tb;
    }

    private static void Tb_Click(object sender, EventArgs e)
    {
        var Tb = (TextBox)sender;
        if (LastTb == Tb)
        {
            Tb.SelectAll();
            LastTb = null;
        }
    }
}

Suppress Scientific Notation in Numpy When Creating Array From Nested List

Python Force-suppress all exponential notation when printing numpy ndarrays, wrangle text justification, rounding and print options:

What follows is an explanation for what is going on, scroll to bottom for code demos.

Passing parameter suppress=True to function set_printoptions works only for numbers that fit in the default 8 character space allotted to it, like this:

import numpy as np
np.set_printoptions(suppress=True) #prevent numpy exponential 
                                   #notation on print, default False

#            tiny     med  large
a = np.array([1.01e-5, 22, 1.2345678e7])  #notice how index 2 is 8 
                                          #digits wide

print(a)    #prints [ 0.0000101   22.     12345678. ]

However if you pass in a number greater than 8 characters wide, exponential notation is imposed again, like this:

np.set_printoptions(suppress=True)

a = np.array([1.01e-5, 22, 1.2345678e10])    #notice how index 2 is 10
                                             #digits wide, too wide!

#exponential notation where we've told it not to!
print(a)    #prints [1.01000000e-005   2.20000000e+001   1.23456780e+10]

numpy has a choice between chopping your number in half thus misrepresenting it, or forcing exponential notation, it chooses the latter.

Here comes set_printoptions(formatter=...) to the rescue to specify options for printing and rounding. Tell set_printoptions to just print bare a bare float:

np.set_printoptions(suppress=True,
   formatter={'float_kind':'{:f}'.format})

a = np.array([1.01e-5, 22, 1.2345678e30])  #notice how index 2 is 30
                                           #digits wide.  

#Ok good, no exponential notation in the large numbers:
print(a)  #prints [0.000010 22.000000 1234567799999999979944197226496.000000] 

We've force-suppressed the exponential notation, but it is not rounded or justified, so specify extra formatting options:

np.set_printoptions(suppress=True,
   formatter={'float_kind':'{:0.2f}'.format})  #float, 2 units 
                                               #precision right, 0 on left

a = np.array([1.01e-5, 22, 1.2345678e30])   #notice how index 2 is 30
                                            #digits wide

print(a)  #prints [0.00 22.00 1234567799999999979944197226496.00]

The drawback for force-suppressing all exponential notion in ndarrays is that if your ndarray gets a huge float value near infinity in it, and you print it, you're going to get blasted in the face with a page full of numbers.

Full example Demo 1:

from pprint import pprint
import numpy as np
#chaotic python list of lists with very different numeric magnitudes
my_list = [[3.74, 5162, 13683628846.64, 12783387559.86, 1.81],
           [9.55, 116, 189688622.37, 260332262.0, 1.97],
           [2.2, 768, 6004865.13, 5759960.98, 1.21],
           [3.74, 4062, 3263822121.39, 3066869087.9, 1.93],
           [1.91, 474, 44555062.72, 44555062.72, 0.41],
           [5.8, 5006, 8254968918.1, 7446788272.74, 3.25],
           [4.5, 7887, 30078971595.46, 27814989471.31, 2.18],
           [7.03, 116, 66252511.46, 81109291.0, 1.56],
           [6.52, 116, 47674230.76, 57686991.0, 1.43],
           [1.85, 623, 3002631.96, 2899484.08, 0.64],
           [13.76, 1227, 1737874137.5, 1446511574.32, 4.32],
           [13.76, 1227, 1737874137.5, 1446511574.32, 4.32]]

#convert python list of lists to numpy ndarray called my_array
my_array = np.array(my_list)

#This is a little recursive helper function converts all nested 
#ndarrays to python list of lists so that pretty printer knows what to do.
def arrayToList(arr):
    if type(arr) == type(np.array):
        #If the passed type is an ndarray then convert it to a list and
        #recursively convert all nested types
        return arrayToList(arr.tolist())
    else:
        #if item isn't an ndarray leave it as is.
        return arr

#suppress exponential notation, define an appropriate float formatter
#specify stdout line width and let pretty print do the work
np.set_printoptions(suppress=True,
   formatter={'float_kind':'{:16.3f}'.format}, linewidth=130)
pprint(arrayToList(my_array))

Prints:

array([[           3.740,         5162.000,  13683628846.640,  12783387559.860,            1.810],
       [           9.550,          116.000,    189688622.370,    260332262.000,            1.970],
       [           2.200,          768.000,      6004865.130,      5759960.980,            1.210],
       [           3.740,         4062.000,   3263822121.390,   3066869087.900,            1.930],
       [           1.910,          474.000,     44555062.720,     44555062.720,            0.410],
       [           5.800,         5006.000,   8254968918.100,   7446788272.740,            3.250],
       [           4.500,         7887.000,  30078971595.460,  27814989471.310,            2.180],
       [           7.030,          116.000,     66252511.460,     81109291.000,            1.560],
       [           6.520,          116.000,     47674230.760,     57686991.000,            1.430],
       [           1.850,          623.000,      3002631.960,      2899484.080,            0.640],
       [          13.760,         1227.000,   1737874137.500,   1446511574.320,            4.320],
       [          13.760,         1227.000,   1737874137.500,   1446511574.320,            4.320]])

Full example Demo 2:

import numpy as np  
#chaotic python list of lists with very different numeric magnitudes 

#            very tiny      medium size            large sized
#            numbers        numbers                numbers

my_list = [[0.000000000074, 5162, 13683628846.64, 1.01e10, 1.81], 
           [1.000000000055,  116, 189688622.37, 260332262.0, 1.97], 
           [0.010000000022,  768, 6004865.13,   -99e13, 1.21], 
           [1.000000000074, 4062, 3263822121.39, 3066869087.9, 1.93], 
           [2.91,            474, 44555062.72, 44555062.72, 0.41], 
           [5,              5006, 8254968918.1, 7446788272.74, 3.25], 
           [0.01,           7887, 30078971595.46, 27814989471.31, 2.18], 
           [7.03,            116, 66252511.46, 81109291.0, 1.56], 
           [6.52,            116, 47674230.76, 57686991.0, 1.43], 
           [1.85,            623, 3002631.96, 2899484.08, 0.64], 
           [13.76,          1227, 1737874137.5, 1446511574.32, 4.32], 
           [13.76,          1337, 1737874137.5, 1446511574.32, 4.32]] 
import sys 
#convert python list of lists to numpy ndarray called my_array 
my_array = np.array(my_list) 
#following two lines do the same thing, showing that np.savetxt can 
#correctly handle python lists of lists and numpy 2D ndarrays. 
np.savetxt(sys.stdout, my_list, '%19.2f') 
np.savetxt(sys.stdout, my_array, '%19.2f') 

Prints:

 0.00             5162.00      13683628846.64      10100000000.00              1.81
 1.00              116.00        189688622.37        260332262.00              1.97
 0.01              768.00          6004865.13 -990000000000000.00              1.21
 1.00             4062.00       3263822121.39       3066869087.90              1.93
 2.91              474.00         44555062.72         44555062.72              0.41
 5.00             5006.00       8254968918.10       7446788272.74              3.25
 0.01             7887.00      30078971595.46      27814989471.31              2.18
 7.03              116.00         66252511.46         81109291.00              1.56
 6.52              116.00         47674230.76         57686991.00              1.43
 1.85              623.00          3002631.96          2899484.08              0.64
13.76             1227.00       1737874137.50       1446511574.32              4.32
13.76             1337.00       1737874137.50       1446511574.32              4.32
 0.00             5162.00      13683628846.64      10100000000.00              1.81
 1.00              116.00        189688622.37        260332262.00              1.97
 0.01              768.00          6004865.13 -990000000000000.00              1.21
 1.00             4062.00       3263822121.39       3066869087.90              1.93
 2.91              474.00         44555062.72         44555062.72              0.41
 5.00             5006.00       8254968918.10       7446788272.74              3.25
 0.01             7887.00      30078971595.46      27814989471.31              2.18
 7.03              116.00         66252511.46         81109291.00              1.56
 6.52              116.00         47674230.76         57686991.00              1.43
 1.85              623.00          3002631.96          2899484.08              0.64
13.76             1227.00       1737874137.50       1446511574.32              4.32
13.76             1337.00       1737874137.50       1446511574.32              4.32

Notice that rounding is consistent at 2 units precision, and exponential notation is suppressed in both the very large e+x and very small e-x ranges.

How do I convert an enum to a list in C#?

Language[] result = (Language[])Enum.GetValues(typeof(Language))

IntelliJ show JavaDocs tooltip on mouse over

I tried many ways mentioned here, especially the preference - editor - general - code completion - show documentation popup in.. isn't working in version 2019.2.2

Finally, i am just using F1 while caret is on the type/method and it displays the documentation nicely. This is not ideal but helpful.

DirectX SDK (June 2010) Installation Problems: Error Code S1023

Find Microsoft Visual C++ 2010 x86/x64 Redistributable – 10.0.xxxxx in the control panel of the add or remove programs if xxxxx > 30319 renmove it

I just wanted to say that this(I also emptied my temp folder, in Computer->C:->Properties->Disk Cleanup) made the DirectX June 2010 SDK install without failure, I have Vista32bit for all it matters. Thank you Mr.Lyn! :)

Find the index of a char in string?

"abcdefgh..".IndexOf("d")

returns 3

In general returns first occurrence index, if not present returns -1

session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

This error message...

Selenium message:session not created: This version of ChromeDriver only supports Chrome version 74
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Mac OS X 10.14.3 x86_64)

...implies that the ChromeDriver expects the Chrome Browser version to be 74.


Quick installation of the latest ChromeDriver

To install the latest version of ChromeDriver you can use:

  • Mac users with Homebrew: brew tap homebrew/cask && brew cask install chromedriver
  • Debian based Linux distros: sudo apt-get install chromium-chromedriver
  • Windows users with Chocolatey installed: choco install chromedriver

Analysis

Your main issue is the incompatibility between the version of the binaries you are using as follows:

Supports Chrome v74

  • You are using the currently released chrome=73.0

So there is a clear mismatch between the ChromeDriver v74.0.3729.6 and the Chrome Browser v73.0


Solution

  • Downgrade ChromeDriver to ChromeDriver v73.0.3683.68 level.
  • Keep Chrome version at Chrome v73 level. (as per ChromeDriver v73.0.3683.68 release notes)
  • Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.
  • If your base Web Client version is too old, then uninstall it and install a recent GA and released version of Web Client.
  • Execute your @Test.
  • Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.

Reference

You can find a relevant detailed discussion in:

BeautifulSoup: extract text from anchor tag

I would suggest going the lxml route and using xpath.

from lxml import etree
# data is the variable containing the html
data = etree.HTML(data)
anchor = data.xpath('//a[@class="title"]/text()')

How to create local notifications?

- (void)applicationDidEnterBackground:(UIApplication *)application
{
   UILocalNotification *notification = [[UILocalNotification alloc]init];
   notification.repeatInterval = NSDayCalendarUnit;
   [notification setAlertBody:@"Hello world"];
   [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
   [notification setTimeZone:[NSTimeZone  defaultTimeZone]];
   [application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
}

This is worked, but in iOS 8.0 and later, your application must register for user notifications using -[UIApplication registerUserNotificationSettings:] before being able to schedule and present UILocalNotifications, do not forget this.

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

Changing the ng-src value is actually very simple. Like this:

<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>

Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/

How to convert byte array to string

Depending on the encoding you wish to use:

var str = System.Text.Encoding.Default.GetString(result);

Private pages for a private Github repo

If you press admin on a private repo and scroll down to the part about pages, it writes that it'll be public. I'll check later if .htaccess control or similar is possible, but I don't have much hope for it.

How to check if ZooKeeper is running or up from command prompt?

To check if Zookeeper is accessible. One method is to simply telnet to the proper port and execute the stats command.

root@host:~# telnet localhost 2181
Trying 127.0.0.1...
Connected to myhost.
Escape character is '^]'.
stats
Zookeeper version: 3.4.3-cdh4.0.1--1, built on 06/28/2012 23:59 GMT
Clients:

Latency min/avg/max: 0/0/677
Received: 4684478
Sent: 4687034
Outstanding: 0
Zxid: 0xb00187dd0
Mode: leader
Node count: 127182
Connection closed by foreign host.

How to call getResources() from a class which has no context?

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. It is an "interface" that allows access to application specific resources and class and information about application environment. Your activities and services also extend Context to they inherit all those methods to access the environment information in which the application is running.

This means you must have to pass context to the specific class if you want to get/modify some specific information about the resources. You can pass context in the constructor like

public classname(Context context, String s1) 
{
...
}

Java: Clear the console

Try this: only works on console, not in NetBeans integrated console.

public static void cls(){
    try {

     if (System.getProperty("os.name").contains("Windows"))
         new ProcessBuilder("cmd", "/c", 
                  "cls").inheritIO().start().waitFor();
     else
         Runtime.getRuntime().exec("clear");
    } catch (IOException | InterruptedException ex) {}
}

AngularJS - Passing data between pages

You need to create a service to be able to share data between controllers.

app.factory('myService', function() {
 var savedData = {}
 function set(data) {
   savedData = data;
 }
 function get() {
  return savedData;
 }

 return {
  set: set,
  get: get
 }

});

In your controller A:

myService.set(yourSharedData);

In your controller B:

$scope.desiredLocation = myService.get();

Remember to inject myService in the controllers by passing it as a parameter.

Difference between Hive internal tables and external tables?

External hive table has advantages that it does not remove files when we drop tables,we can set row formats with different settings , like serde....delimited

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

According to the HTML standard, the content model of the HTML element is:

A head element followed by a body element.

You can either define the BODY element in the source code:

<html>
    <body>
        ... web-page ...
    </body>
</html>

or you can omit the BODY element:

<html>
    ... web-page ...
</html>

However, it is invalid to place the BODY element inside the web-page content (in-between other elements or text content), like so:

<html>
    ... content ...
    <body>
        ... content ...
    </body>
    ... content ...
</html>

Default value in an asp.net mvc view model

Set this in the constructor:

public class SearchModel
{
    public bool IsMale { get; set; }
    public bool IsFemale { get; set; }

    public SearchModel()
    { 
        IsMale = true;
        IsFemale = true;
    }
}

Then pass it to the view in your GET action:

[HttpGet]
public ActionResult Search()
{
    return new View(new SearchModel());
}

How can I select an element by name with jQuery?

Here's a simple solution: $('td[name=tcol1]')

How to change status bar color to match app in Lollipop? [Android]

Just add this in you styles.xml. The colorPrimary is for the action bar and the colorPrimaryDark is for the status bar.

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:colorPrimary">@color/primary</item>
    <item name="android:colorPrimaryDark">@color/primary_dark</item>
</style>

This picture from developer android explains more about color pallete. You can read more on this link.

enter image description here

Setting ANDROID_HOME enviromental variable on Mac OS X

Setup ANDROID_HOME , JAVA_HOME enviromental variable on Mac OS X

Add In .bash_profile file

export JAVA_HOME=$(/usr/libexec/java_home)

export ANDROID_HOME=/Users/$USER/Library/Android/sdk

export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

For Test

echo $ANDROID_HOME
echo $JAVA_HOME

php static function

Simply, static functions function independently of the class where they belong.

$this means, this is an object of this class. It does not apply to static functions.

class test {
    public function sayHi($hi = "Hi") {
        $this->hi = $hi;
        return $this->hi;
    }
}
class test1 {
    public static function sayHi($hi) {
        $hi = "Hi";
        return $hi;
    }
}

//  Test
$mytest = new test();
print $mytest->sayHi('hello');  // returns 'hello'
print test1::sayHi('hello');    //  returns 'Hi'

Simple DateTime sql query

You missed single quote sign:

SELECT * 
FROM TABLENAME 
WHERE DateTime >= '12/04/2011 12:00:00 AM' AND DateTime <= '25/05/2011 3:53:04 AM'

Also, it is recommended to use ISO8601 format YYYY-MM-DDThh:mm:ss.nnn[ Z ], as this one will not depend on your server's local culture.

SELECT *
FROM TABLENAME 
WHERE 
    DateTime >= '2011-04-12T00:00:00.000' AND 
    DateTime <= '2011-05-25T03:53:04.000'

Convert command line arguments into an array in Bash

Maybe this can help:

myArray=("$@") 

also you can iterate over arguments by omitting 'in':

for arg; do
   echo "$arg"
done

will be equivalent

for arg in "${myArray[@]}"; do
   echo "$arg"
done

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

I really like Darren Cook's and stacker's answers to this problem. I was in the midst of throwing my thoughts into a comment on those, but I believe my approach is too answer-shaped to not leave here.

In short summary, you've identified an algorithm to determine that a Coca-Cola logo is present at a particular location in space. You're now trying to determine, for arbitrary orientations and arbitrary scaling factors, a heuristic suitable for distinguishing Coca-Cola cans from other objects, inclusive of: bottles, billboards, advertisements, and Coca-Cola paraphernalia all associated with this iconic logo. You didn't call out many of these additional cases in your problem statement, but I feel they're vital to the success of your algorithm.

The secret here is determining what visual features a can contains or, through the negative space, what features are present for other Coke products that are not present for cans. To that end, the current top answer sketches out a basic approach for selecting "can" if and only if "bottle" is not identified, either by the presence of a bottle cap, liquid, or other similar visual heuristics.

The problem is this breaks down. A bottle could, for example, be empty and lack the presence of a cap, leading to a false positive. Or, it could be a partial bottle with additional features mangled, leading again to false detection. Needless to say, this isn't elegant, nor is it effective for our purposes.

To this end, the most correct selection criteria for cans appear to be the following:

  • Is the shape of the object silhouette, as you sketched out in your question, correct? If so, +1.
  • If we assume the presence of natural or artificial light, do we detect a chrome outline to the bottle that signifies whether this is made of aluminum? If so, +1.
  • Do we determine that the specular properties of the object are correct, relative to our light sources (illustrative video link on light source detection)? If so, +1.
  • Can we determine any other properties about the object that identify it as a can, including, but not limited to, the topological image skew of the logo, the orientation of the object, the juxtaposition of the object (for example, on a planar surface like a table or in the context of other cans), and the presence of a pull tab? If so, for each, +1.

Your classification might then look like the following:

  • For each candidate match, if the presence of a Coca Cola logo was detected, draw a gray border.
  • For each match over +2, draw a red border.

This visually highlights to the user what was detected, emphasizing weak positives that may, correctly, be detected as mangled cans.

The detection of each property carries a very different time and space complexity, and for each approach, a quick pass through http://dsp.stackexchange.com is more than reasonable for determining the most correct and most efficient algorithm for your purposes. My intent here is, purely and simply, to emphasize that detecting if something is a can by invalidating a small portion of the candidate detection space isn't the most robust or effective solution to this problem, and ideally, you should take the appropriate actions accordingly.

And hey, congrats on the Hacker News posting! On the whole, this is a pretty terrific question worthy of the publicity it received. :)

Export to csv in jQuery

You can't avoid a server call here, JavaScript simply cannot (for security reasons) save a file to the user's file system. You'll have to submit your data to the server and have it send the .csv as a link or an attachment directly.

HTML5 has some ability to do this (though saving really isn't specified - just a use case, you can read the file if you want), but there's no cross-browser solution in place now.

Transparent background on winforms?

A simple solution to get a transparent background in a windows form is to overwrite the OnPaintBackground method like this:

protected override void OnPaintBackground(PaintEventArgs e)
{
    //empty implementation
}

(Notice that the base.OnpaintBackground(e) is removed from the function)

Passing multiple parameters with $.ajax url

why not just pass an data an object with your key/value pairs then you don't have to worry about encoding

$.ajax({
    type: "Post",
    url: "getdata.php",
    data:{
       timestamp: timestamp,
       uid: id,
       uname: name
    },
    async: true,
    cache: false,
    success: function(data) {


    };
}?);?

Combine multiple results in a subquery into a single comma-separated value

In MySQL there is a group_concat function that will return what you're asking for.

SELECT TableA.ID, TableA.Name, group_concat(TableB.SomeColumn) 
as SomColumnGroup FROM TableA LEFT JOIN TableB ON 
TableB.TableA_ID = TableA.ID

cmd line rename file with date and time

Digging up the old thread because all solutions have missed the simplest fix...

It is failing because the substitution of the time variable results in a space in the filename, meaning it treats the last part of the filename as a parameter into the command.

The simplest solution is to just surround the desired filename in quotes "filename".

Then you can have any date pattern you want (with the exception of those illegal characters such as /,\,...)

I would suggest reverse date order YYYYMMDD-HHMM:

ren "somefile.txt" "somefile-%date:~10,4%%date:~7,2%%date:~4,2%-%time:~0,2%%time:~3,2%.txt"

MSSQL Regular expression

As above the question was originally about MySQL

Use REGEXP, not LIKE:

SELECT * FROM `table` WHERE ([url] NOT REGEXP '^[-A-Za-z0-9/.]+$')

How can I change Eclipse theme?

The best way to Install new themes in any Eclipse platform is to use the Eclipse Marketplace.

1.Go to Help > Eclipse Marketplace

2.Search for "Color Themes"

3.Install and Restart

4.Go to Window > Preferences > General > Appearance > Color Themes

5.Select anyone and Apply. Restart.

What is causing this error - "Fatal error: Unable to find local grunt"

Being new to grunt and setting it up, I am running (perhaps foolishly) my grunt project/folder from a Google Drive so I can access the same code/builds from either my laptop or workstation.

There is a fair bit of synchronisation of the nodes_modules folders back to Google Drive and there seemed to be a conflict at some point, and the /nodes_modules/grunt folder was renamed to /nodes_modules/grunt (1)

Renaming it back by removing the (1) seemed to fix it for me.

Plot a legend outside of the plotting area in base graphics?

No one has mentioned using negative inset values for legend. Here is an example, where the legend is to the right of the plot, aligned to the top (using keyword "topright").

# Random data to plot:
A <- data.frame(x=rnorm(100, 20, 2), y=rnorm(100, 20, 2))
B <- data.frame(x=rnorm(100, 21, 1), y=rnorm(100, 21, 1))

# Add extra space to right of plot area; change clipping to figure
par(mar=c(5.1, 4.1, 4.1, 8.1), xpd=TRUE)

# Plot both groups
plot(y ~ x, A, ylim=range(c(A$y, B$y)), xlim=range(c(A$x, B$x)), pch=1,
               main="Scatter plot of two groups")
points(y ~ x, B, pch=3)

# Add legend to top right, outside plot region
legend("topright", inset=c(-0.2,0), legend=c("A","B"), pch=c(1,3), title="Group")

The first value of inset=c(-0.2,0) might need adjusting based on the width of the legend.

legend_right

reading text file with utf-8 encoding using java

You are reading the file right but the problem seems to be with the default encoding of System.out. Try this to print the UTF-8 string-

PrintStream out = new PrintStream(System.out, true, "UTF-8");
out.println(str);

How do I replace text in a selection?

As @JOPLOmacedo stated, ctrl + F is what you need, but if you can't use that shortcut you can check in menu:

  • Find -> Find..

    and there you have it.
    You can also set a custom keybind for Find going in:

  • Preferences -> Key Bindings - User

    As your request for the selection only request, there is a button right next to the search field where you can opt-in for "in selection".

  • How to use UIVisualEffectView to Blur Image?

    Just put this blur view on the imageView. Here is an example in Objective-C:

    UIVisualEffect *blurEffect;
    blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    
    UIVisualEffectView *visualEffectView;
    visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    
    visualEffectView.frame = imageView.bounds;
    [imageView addSubview:visualEffectView];
    

    and Swift:

    var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light))    
    
    visualEffectView.frame = imageView.bounds
    
    imageView.addSubview(visualEffectView)
    

    Can I automatically increment the file build version when using Visual Studio?

    How to get the version {major}.{year}.1{date}.1{time}

    This one is kind of experimental, but I like it. Inspired by Jeff Atwood @ CodingHorror (link).

    The resulting version number becomes 1.2016.10709.11641 (meaning 2016-07-09 16:41), which allows for

    • poor mans zero padding (with the stupid leading 1s)
    • nearly-human readable local DateTime embedded into the version number
    • leaving Major version alone for really major breaking changes.

    Add a new item to your project, select General -> Text Template, name it something like CustomVersionNumber and (where applicable) comment out the AssemblyVersion and AssemblyFileVersion in Properties/AssemblyInfo.cs.

    Then, when saving this file, or building the project, this will regenerate a .cs file located as a sub-item under the created .tt file.

    <#@ template language="C#" #>
    <#@ assembly name="System.Core" #>
    <#@ import namespace="System.Linq" #>
    
    //
    // This code was generated by a tool. Any changes made manually will be lost
    // the next time this code is regenerated.
    //
    
    using System.Reflection;
    
    <#
        var date = DateTime.Now;
        int major = 1;
        int minor = date.Year;
        int build = 10000 + int.Parse(date.ToString("MMdd"));
        int revision = 10000 + int.Parse(date.ToString("HHmm"));
    #>
    
    [assembly: AssemblyVersion("<#= $"{major}.{minor}.{build}.{revision}" #>")]
    [assembly: AssemblyFileVersion("<#= $"{major}.{minor}.{build}.{revision}" #>")]
    

    how to extract only the year from the date in sql server 2008?

    You can use year() function in sql to get the year from the specified date.

    Syntax:

    YEAR ( date )
    

    For more information check here

    Why is it common to put CSRF prevention tokens in cookies?

    A good reason, which you have sort of touched on, is that once the CSRF cookie has been received, it is then available for use throughout the application in client script for use in both regular forms and AJAX POSTs. This will make sense in a JavaScript heavy application such as one employed by AngularJS (using AngularJS doesn't require that the application will be a single page app, so it would be useful where state needs to flow between different page requests where the CSRF value cannot normally persist in the browser).

    Consider the following scenarios and processes in a typical application for some pros and cons of each approach you describe. These are based on the Synchronizer Token Pattern.

    Request Body Approach

    1. User successfully logs in.
    2. Server issues auth cookie.
    3. User clicks to navigate to a form.
    4. If not yet generated for this session, server generates CSRF token, stores it against the user session and outputs it to a hidden field.
    5. User submits form.
    6. Server checks hidden field matches session stored token.

    Advantages:

    • Simple to implement.
    • Works with AJAX.
    • Works with forms.
    • Cookie can actually be HTTP Only.

    Disadvantages:

    • All forms must output the hidden field in HTML.
    • Any AJAX POSTs must also include the value.
    • The page must know in advance that it requires the CSRF token so it can include it in the page content so all pages must contain the token value somewhere, which could make it time consuming to implement for a large site.

    Custom HTTP Header (downstream)

    1. User successfully logs in.
    2. Server issues auth cookie.
    3. User clicks to navigate to a form.
    4. Page loads in browser, then an AJAX request is made to retrieve the CSRF token.
    5. Server generates CSRF token (if not already generated for session), stores it against the user session and outputs it to a header.
    6. User submits form (token is sent via hidden field).
    7. Server checks hidden field matches session stored token.

    Advantages:

    Disadvantages:

    • Doesn't work without an AJAX request to get the header value.
    • All forms must have the value added to its HTML dynamically.
    • Any AJAX POSTs must also include the value.
    • The page must make an AJAX request first to get the CSRF token, so it will mean an extra round trip each time.
    • Might as well have simply output the token to the page which would save the extra request.

    Custom HTTP Header (upstream)

    1. User successfully logs in.
    2. Server issues auth cookie.
    3. User clicks to navigate to a form.
    4. If not yet generated for this session, server generates CSRF token, stores it against the user session and outputs it in the page content somewhere.
    5. User submits form via AJAX (token is sent via header).
    6. Server checks custom header matches session stored token.

    Advantages:

    Disadvantages:

    • Doesn't work with forms.
    • All AJAX POSTs must include the header.

    Custom HTTP Header (upstream & downstream)

    1. User successfully logs in.
    2. Server issues auth cookie.
    3. User clicks to navigate to a form.
    4. Page loads in browser, then an AJAX request is made to retrieve the CSRF token.
    5. Server generates CSRF token (if not already generated for session), stores it against the user session and outputs it to a header.
    6. User submits form via AJAX (token is sent via header) .
    7. Server checks custom header matches session stored token.

    Advantages:

    Disadvantages:

    • Doesn't work with forms.
    • All AJAX POSTs must also include the value.
    • The page must make an AJAX request first to get the CRSF token, so it will mean an extra round trip each time.

    Set-Cookie

    1. User successfully logs in.
    2. Server issues auth cookie.
    3. User clicks to navigate to a form.
    4. Server generates CSRF token, stores it against the user session and outputs it to a cookie.
    5. User submits form via AJAX or via HTML form.
    6. Server checks custom header (or hidden form field) matches session stored token.
    7. Cookie is available in browser for use in additional AJAX and form requests without additional requests to server to retrieve the CSRF token.

    Advantages:

    • Simple to implement.
    • Works with AJAX.
    • Works with forms.
    • Doesn't necessarily require an AJAX request to get the cookie value. Any HTTP request can retrieve it and it can be appended to all forms/AJAX requests via JavaScript.
    • Once the CSRF token has been retrieved, as it is stored in a cookie the value can be reused without additional requests.

    Disadvantages:

    • All forms must have the value added to its HTML dynamically.
    • Any AJAX POSTs must also include the value.
    • The cookie will be submitted for every request (i.e. all GETs for images, CSS, JS, etc, that are not involved in the CSRF process) increasing request size.
    • Cookie cannot be HTTP Only.

    So the cookie approach is fairly dynamic offering an easy way to retrieve the cookie value (any HTTP request) and to use it (JS can add the value to any form automatically and it can be employed in AJAX requests either as a header or as a form value). Once the CSRF token has been received for the session, there is no need to regenerate it as an attacker employing a CSRF exploit has no method of retrieving this token. If a malicious user tries to read the user's CSRF token in any of the above methods then this will be prevented by the Same Origin Policy. If a malicious user tries to retrieve the CSRF token server side (e.g. via curl) then this token will not be associated to the same user account as the victim's auth session cookie will be missing from the request (it would be the attacker's - therefore it won't be associated server side with the victim's session).

    As well as the Synchronizer Token Pattern there is also the Double Submit Cookie CSRF prevention method, which of course uses cookies to store a type of CSRF token. This is easier to implement as it does not require any server side state for the CSRF token. The CSRF token in fact could be the standard authentication cookie when using this method, and this value is submitted via cookies as usual with the request, but the value is also repeated in either a hidden field or header, of which an attacker cannot replicate as they cannot read the value in the first place. It would be recommended to choose another cookie however, other than the authentication cookie so that the authentication cookie can be secured by being marked HttpOnly. So this is another common reason why you'd find CSRF prevention using a cookie based method.

    Efficient thresholding filter of an array with numpy

    b = a[a>threshold] this should do

    I tested as follows:

    import numpy as np, datetime
    # array of zeros and ones interleaved
    lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()
    
    t0 = datetime.datetime.now()
    flt = lrg[lrg==0]
    print datetime.datetime.now() - t0
    
    t0 = datetime.datetime.now()
    flt = np.array(filter(lambda x:x==0, lrg))
    print datetime.datetime.now() - t0
    

    I got

    $ python test.py
    0:00:00.028000
    0:00:02.461000
    

    http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

    How do I open workbook programmatically as read-only?

    Does this work?

    Workbooks.Open Filename:=filepath, ReadOnly:=True
    

    Or, as pointed out in a comment, to keep a reference to the opened workbook:

    Dim book As Workbook
    Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)
    

    Quickest way to clear all sheet contents VBA

    Technically, and from Comintern's accepted workaround, I believe you actually want to Delete all the Cells in the Sheet. Which removes Formatting (See footnote for exceptions), etc. as well as the Cells Contents. I.e. Sheets("Zeroes").Cells.Delete

    Combined also with UsedRange, ScreenUpdating and Calculation skipping it should be nearly intantaneous:

    Sub DeleteCells ()
        Application.Calculation = XlManual
        Application.ScreenUpdating = False
        Sheets("Zeroes").UsedRange.Delete
        Application.ScreenUpdating = True
        Application.Calculation = xlAutomatic
    End Sub
    

    Or if you prefer to respect the Calculation State Excel is currently in:

    Sub DeleteCells ()
        Dim SaveCalcState
        SaveCalcState = Application.Calculation
        Application.Calculation = XlManual
        Application.ScreenUpdating = False
        Sheets("Zeroes").UsedRange.Delete
        Application.ScreenUpdating = True
        Application.Calculation = SaveCalcState
    End Sub
    

    Footnote: If formatting was applied for an Entire Column, then it is not deleted. This includes Font Colour, Fill Colour and Borders, the Format Category (like General, Date, Text, Etc.) and perhaps other properties too, but

    Conditional formatting IS deleted, as is Entire Row formatting.

    (Entire Column formatting is quite useful if you are importing raw data repeatedly to a sheet as it will conform to the Formats originally applied if a simple Paste-Values-Only type import is done.)

    How to reset a select element with jQuery

    If you don't want to use the first option (in case the field is hidden or something) then the following jQuery code is enough:

    _x000D_
    _x000D_
    $(document).ready(function(){_x000D_
        $('#but').click(function(){_x000D_
            $('#baba').val(false);_x000D_
        })_x000D_
    });
    _x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>_x000D_
    <select id="baba">_x000D_
    <option>select something</option>_x000D_
    <option value="1">something 1</option>_x000D_
    <option value=2">something 2</option>_x000D_
    </select>_x000D_
        _x000D_
        <input type="button" id="but" value="click">
    _x000D_
    _x000D_
    _x000D_

    datatable jquery - table header width not aligned with body width

    I was using Bootstrap 4, and had added the class table-sm to my table. That messed up the formatting. Removing that class fixed the problem.


    If you can't remove that class, I would suspect that adding it via javascript to the headers table would work. Datatables uses two tables to display a table when scrollX is enabled -- one for the header, and one for the body.

    Why use $_SERVER['PHP_SELF'] instead of ""

    In addition to above answers, another way of doing it is $_SERVER['PHP_SELF'] or simply using an empty string is to use __DIR__.
    OR
    If you're on a lower PHP version (<5.3), a more common alternative is to use dirname(__FILE__)
    Both returns the folder name of the file in context.

    EDIT
    As Boann pointed out that this returns the on-disk location of the file. WHich you would not ideally expose as a url. In that case dirname($_SERVER['PHP_SELF']) can return the folder name of the file in context.

    jQuery Clone table row

    Is very simple to clone the last row with jquery pressing a button:

    Your Table HTML:

    <table id="tableExample">
        <thead>
            <tr>
                <th>ID</th>
                <th>Header 1</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>Line 1</td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="2"><button type="button" id="addRowButton">Add row</button></td>
            </tr>
        </tfoot>
    </table>
    

    JS:

    $(document).on('click', '#addRowButton', function() {
        var table = $('#tableExample'),
            lastRow = table.find('tbody tr:last'),
            rowClone = lastRow.clone();
    
        table.find('tbody').append(rowClone);
    });
    

    Regards!

    How to stop a function

    This will end the function, and you can even customize the "Error" message:

    import sys
    
    def end():
        if condition:
            # the player wants to play again:
            main()
        elif not condition:
            sys.exit("The player doesn't want to play again") #Right here 
    

    How to find the php.ini file used by the command line?

    Do

    find / -type f -name "php.ini" 
    

    This will output all files named php.ini.

    Find out which one you're using, usually apache2/php.ini

    How to find the minimum value in an ArrayList, along with the index number? (Java)

    Here's what I do. I find the minimum first then after the minimum is found, it is removed from ArrayList.

    ArrayList<Integer> a = new ArrayList<>();
    a.add(3);
    a.add(6);
    a.add(2);
    a.add(5);
    
    while (a.size() > 0) {
        int min = 1000;
        for (int b:a) {
            if (b < min)
                min = b;
        }
        System.out.println("minimum: " + min);
        System.out.println("index of min: " + a.indexOf((Integer) min));
        a.remove((Integer) min);
    }
    

    How do I read the first line of a file using cat?

    cat alone may not be possible, but if you don't want to use head this works:

     cat <file> | awk 'NR == 1'
    

    Checking if object is empty, works with ng-show but not from controller?

    Or, if using lo-dash: _.empty(value).

    "Checks if value is empty. Arrays, strings, or arguments objects with a length of 0 and objects with no own enumerable properties are considered "empty"."

    Copy the entire contents of a directory in C#

    Sorry for the previous code, it still had bugs :( (fell prey to the fastest gun problem) . Here it is tested and working. The key is the SearchOption.AllDirectories, which eliminates the need for explicit recursion.

    string path = "C:\\a";
    string[] dirs = Directory.GetDirectories(path, "*.*", SearchOption.AllDirectories);
    string newpath = "C:\\x";
    try
    {
        Directory.CreateDirectory(newpath);
    }
    catch (IOException ex)
    {
        Console.WriteLine(ex.Message);
    }
    for (int j = 0; j < dirs.Length; j++)
    {
        try
        {
            Directory.CreateDirectory(dirs[j].Replace(path, newpath));
        }
        catch (IOException ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
    
    string[] files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
    for (int j = 0; j < files.Length; j++)            
    {
        try
        {
            File.Copy(files[j], files[j].Replace(path, newpath));
        }
        catch (IOException ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
    

    How does createOrReplaceTempView work in Spark?

    SparkSQl support writing programs using Dataset and Dataframe API, along with it need to support sql.

    In order to support Sql on DataFrames, first it requires a table definition with column names are required, along with if it creates tables the hive metastore will get lot unnecessary tables, because Spark-Sql natively resides on hive. So it will create a temporary view, which temporarily available in hive for time being and used as any other hive table, once the Spark Context stop it will be removed.

    In order to create the view, developer need an utility called createOrReplaceTempView

    How to get a resource id with a known resource name?

    I have found this class very helpful to handle with resources. It has some defined methods to deal with dimens, colors, drawables and strings, like this one:

    public static String getString(Context context, String stringId) {
        int sid = getStringId(context, stringId);
        if (sid > 0) {
            return context.getResources().getString(sid);
        } else {
            return "";
        }
    }
    

    How do I set the selected item in a comboBox to match my string using C#?

    Have you tried the Text property? It works for me.

    ComboBox1.Text = "test1";
    

    The SelectedText property is for the selected portion of the editable text in the textbox part of the combo box.

    Android WebView, how to handle redirects in app instead of opening a browser

    Create a WebViewClient, and override the shouldOverrideUrlLoading method.

    webview.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url){
            // do your handling codes here, which url is the requested url
            // probably you need to open that url rather than redirect:
            view.loadUrl(url);
            return false; // then it is not handled by default action
       }
    });
    

    How to install wget in macOS?

    ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
    

    And then install wget with brew and also enable openressl for TLS support

    brew install wget --with-libressl
    

    It worked perfectly for me.

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

    1. remove unwanted dependencies from package.json
    2. npm i

    "npm i" will not only install missing deps, it updates node_modules to match the package.json

    Reverse order of foreach list items

    Walking Backwards

    If you're looking for a purely PHP solution, you can also simply count backwards through the list, access it front-to-back:

    $accounts = Array(
      '@jonathansampson',
      '@f12devtools',
      '@ieanswers'
    );
    
    $index = count($accounts);
    
    while($index) {
      echo sprintf("<li>%s</li>", $accounts[--$index]);
    }
    

    The above sets $index to the total number of elements, and then begins accessing them back-to-front, reducing the index value for the next iteration.

    Reversing the Array

    You could also leverage the array_reverse function to invert the values of your array, allowing you to access them in reverse order:

    $accounts = Array(
      '@jonathansampson',
      '@f12devtools',
      '@ieanswers'
    );
    
    foreach ( array_reverse($accounts) as $account ) {
      echo sprintf("<li>%s</li>", $account);
    }
    

    How to keep a VMWare VM's clock in sync?

    VMware experiences a lot of clock drift. This Google search for 'vmware clock drift' links to several articles.

    The first hit may be the most useful for you: http://www.fjc.net/linux/linux-and-vmware-related-issues/linux-2-6-kernels-and-vmware-clock-drift-issues

    How to check if an user is logged in Symfony2 inside a controller?

    To add to answer given by Anil, In symfony3, you can use $this->getUser() to determine if the user is logged in, a simple condition like if(!$this->getUser()) {} will do.

    If you look at the source code which is available in base controller, it does the exact same thing defined by Anil.

    Multiple condition in single IF statement

    Yes it is, there have to be boolean expresion after IF. Here you have a direct link. I hope it helps. GL!

    error: expected unqualified-id before ‘.’ token //(struct)

    The struct's name is ReducedForm; you need to make an object (instance of the struct or class) and use that. Do this:

    ReducedForm MyReducedForm;
    MyReducedForm.iSimplifiedNumerator = iNumerator/iGreatCommDivisor;
    MyReducedForm.iSimplifiedDenominator = iDenominator/iGreatCommDivisor;
    

    Python TypeError must be str not int

    Python comes with numerous ways of formatting strings:

    New style .format(), which supports a rich formatting mini-language:

    >>> temperature = 10
    >>> print("the furnace is now {} degrees!".format(temperature))
    the furnace is now 10 degrees!
    

    Old style % format specifier:

    >>> print("the furnace is now %d degrees!" % temperature)
    the furnace is now 10 degrees!
    

    In Py 3.6 using the new f"" format strings:

    >>> print(f"the furnace is now {temperature} degrees!")
    the furnace is now 10 degrees!
    

    Or using print()s default separator:

    >>> print("the furnace is now", temperature, "degrees!")
    the furnace is now 10 degrees!
    

    And least effectively, construct a new string by casting it to a str() and concatenating:

    >>> print("the furnace is now " + str(temperature) + " degrees!")
    the furnace is now 10 degrees!
    

    Or join()ing it:

    >>> print(' '.join(["the furnace is now", str(temperature), "degrees!"]))
    the furnace is now 10 degrees!
    

    How do I properly escape quotes inside HTML attributes?

    You really should only allow untrusted data into a whitelist of good attributes like: align, alink, alt, bgcolor, border, cellpadding, cellspacing, class, color, cols, colspan, coords, dir, face, height, hspace, ismap, lang, marginheight, marginwidth, multiple, nohref, noresize, noshade, nowrap, ref, rel, rev, rows, rowspan, scrolling, shape, span, summary, tabindex, title, usemap, valign, value, vlink, vspace, width

    You really want to keep untrusted data out of javascript handlers as well as id or name attributes (they can clobber other elements in the DOM).

    Also, if you are putting untrusted data into a SRC or HREF attribute, then its really a untrusted URL so you should validate the URL, make sure its NOT a javascript: URL, and then HTML entity encode.

    More details on all of there here: https://www.owasp.org/index.php/Abridged_XSS_Prevention_Cheat_Sheet

    Escape a string for a sed replace pattern

    Warning: This does not consider newlines. For a more in-depth answer, see this SO-question instead. (Thanks, Ed Morton & Niklas Peter)

    Note that escaping everything is a bad idea. Sed needs many characters to be escaped to get their special meaning. For example, if you escape a digit in the replacement string, it will turn in to a backreference.

    As Ben Blank said, there are only three characters that need to be escaped in the replacement string (escapes themselves, forward slash for end of statement and & for replace all):

    ESCAPED_REPLACE=$(printf '%s\n' "$REPLACE" | sed -e 's/[\/&]/\\&/g')
    # Now you can use ESCAPED_REPLACE in the original sed statement
    sed "s/KEYWORD/$ESCAPED_REPLACE/g"
    

    If you ever need to escape the KEYWORD string, the following is the one you need:

    sed -e 's/[]\/$*.^[]/\\&/g'

    And can be used by:

    KEYWORD="The Keyword You Need";
    ESCAPED_KEYWORD=$(printf '%s\n' "$KEYWORD" | sed -e 's/[]\/$*.^[]/\\&/g');
    
    # Now you can use it inside the original sed statement to replace text
    sed "s/$ESCAPED_KEYWORD/$ESCAPED_REPLACE/g"
    

    Remember, if you use a character other than / as delimiter, you need replace the slash in the expressions above wih the character you are using. See PeterJCLaw's comment for explanation.

    Edited: Due to some corner cases previously not accounted for, the commands above have changed several times. Check the edit history for details.

    How to change the URL from "localhost" to something else, on a local system using wampserver?

    They are probably using a virtual host (http://www.keanei.com/2011/07/14/creating-virtual-hosts-with-wamp/)

    You can go into your Apache configuration file (httpd.conf) or your virtual host configuration file (recommended) and add something like:

    <VirtualHost *:80>
        DocumentRoot /www/ap-mispro
        ServerName ap-mispro
    
        # Other directives here
    </VirtualHost>
    

    And when you call up http://ap-mispro/ you would see whatever is in C:/wamp/www/ap-mispro (assuming default directory structure). The ServerName and DocumentRoot do no have to have the same name at all. Other factors needed to make this work:

    1. You have to make sure httpd-vhosts.conf is included by httpd.conf for your changes in that file to take effect.
    2. When you make changes to either file, you have to restart Apache to see your changes.
    3. You have to change your hosts file http://en.wikipedia.org/wiki/Hosts_(file) for your computer to know where to go when you type http://ap-mispro into your browser. This change to your hosts file will only apply to your computer - not that it sounds like you are trying from anyone else's.

    There are plenty more things to know about virtual hosts but this should get you started.

    How to generate unique ID with node.js

    Extending from YaroslavGaponov's answer, the simplest implementation is just using Math.random().

    Math.random()
    

    Mathematically, the chances of fractions being the same in a real space [0, 1] is theoretically 0. Probability-wise it is approximately close to 0 for a default length of 16 decimals in node.js. And this implementation should also reduce arithmetic overflows as no operations are performed. Also, it is more memory efficient compared to a string as Decimals occupy less memory than strings.

    I call this the "Fractional-Unique-ID".

    Wrote code to generate 1,000,000 Math.random() numbers and could not find any duplicates (at least for default decimal points of 16). See code below (please provide feedback if any):

    random_numbers = [] 
    for (i = 0; i < 1000000; i++) { 
       random_numbers.push(Math.random()); 
       //random_numbers.push(Math.random().toFixed(13)) //depends decimals default 16 
    } 
    
    if (i === 1000000) { 
       console.log("Before checking duplicate"); 
       console.log(random_numbers.length); 
       console.log("After checking duplicate"); 
       random_set = new Set(random_numbers); // Set removes duplicates
       console.log([...random_set].length); // length is still the same after removing
    } 
    

    How to dismiss ViewController in Swift?

    For reference, be aware that you might be dismissing the wrong view controller. For example, if you have an alert box or modal showing on top of another modal. (You could have a Twitter post alert showing on top of your current modal alert, for example). In this case, you need to call dismiss twice, or use an unwind segue.

    Has Facebook sharer.php changed to no longer accept detailed parameters?

    Facebook no longer supports custom parameters in sharer.php

    The sharer will no longer accept custom parameters and facebook will pull the information that is being displayed in the preview the same way that it would appear on facebook as a post from the url OG meta tags.

    Use dialog/feeds instead of sharer.php

    https://www.facebook.com/dialog/feed?
      app_id=145634995501895
      &display=popup&caption=An%20example%20caption 
      &link=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2Fdialogs%2F
      &redirect_uri=https://developers.facebook.com/tools/explorer
    

    Official answer from fb team

    Hide separator line on one UITableViewCell

    cell.separatorInset = UIEdgeInsetsMake(0.0, cell.bounds.size.width, 0.0, -cell.bounds.size.width)
    

    works well in iOS 10.2

    enter image description here

    Conversion from byte array to base64 and back

    The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

    The way you get your original array back is by using Convert.FromBase64String:

     byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);
    

    What exactly is a Context in Java?

    In programming terms, it's the larger surrounding part which can have any influence on the behaviour of the current unit of work. E.g. the running environment used, the environment variables, instance variables, local variables, state of other classes, state of the current environment, etcetera.

    In some API's you see this name back in an interface/class, e.g. Servlet's ServletContext, JSF's FacesContext, Spring's ApplicationContext, Android's Context, JNDI's InitialContext, etc. They all often follow the Facade Pattern which abstracts the environmental details the enduser doesn't need to know about away in a single interface/class.

    How to Calculate Jump Target Address and Branch Target Address?

    For small functions like this you could just count by hand how many hops it is to the target, from the instruction under the branch instruction. If it branches backwards make that hop number negative. if that number doesn't require all 16 bits, then for every number to the left of the most significant of your hop number, make them 1's, if the hop number is positive make them all 0's Since most branches are close to they're targets, this saves you a lot of extra arithmetic for most cases.

    • chris

    Insert if not exists Oracle

    It that code is on the client then you have many trips to the server so to eliminate that.

    Insert all the data into a temportary table say T with the same structure as myFoo

    Then

    insert myFoo
      select *
         from t
           where t.primary_key not in ( select primary_key from myFoo) 
    

    This should work on other databases as well - I have done this on Sybase

    It is not the best if very few of the new data is to be inserted as you have copied all the data over the wire.

    Count number of rows per group and add result to original data frame

    Using sqldf package:

    library(sqldf)
    
    sqldf("select a.*, b.cnt
           from df a,
               (select name, type, count(1) as cnt
                from df
                group by name, type) b
          where a.name = b.name and
                a.type = b.type")
    
    #    name  type num cnt
    # 1 black chair   4   2
    # 2 black chair   5   2
    # 3 black  sofa  12   1
    # 4   red  sofa   4   1
    # 5   red plate   3   1
    

    What is the difference between "expose" and "publish" in Docker?

    Basically, you have three options:

    1. Neither specify EXPOSE nor -p
    2. Only specify EXPOSE
    3. Specify EXPOSE and -p

    1) If you specify neither EXPOSE nor -p, the service in the container will only be accessible from inside the container itself.

    2) If you EXPOSE a port, the service in the container is not accessible from outside Docker, but from inside other Docker containers. So this is good for inter-container communication.

    3) If you EXPOSE and -p a port, the service in the container is accessible from anywhere, even outside Docker.

    The reason why both are separated is IMHO because:

    • choosing a host port depends on the host and hence does not belong to the Dockerfile (otherwise it would be depending on the host),
    • and often it's enough if a service in a container is accessible from other containers.

    The documentation explicitly states:

    The EXPOSE instruction exposes ports for use within links.

    It also points you to how to link containers, which basically is the inter-container communication I talked about.

    PS: If you do -p, but do not EXPOSE, Docker does an implicit EXPOSE. This is because if a port is open to the public, it is automatically also open to other Docker containers. Hence -p includes EXPOSE. That's why I didn't list it above as a fourth case.

    how do I create an infinite loop in JavaScript

    You can also use a while loop:

    while (true) {
        //your code
    }
    

    How to install pandas from pip on windows cmd?

    Please Ensure you are using a virtualEnv this is how :

    virtualenv -p python3 envname
    
    source env/bin/activate
    pip install pandas
    

    on windows you have to add scripts exe in the CLASSPATH in order to use pip command

    C:\Python34\Scripts\pip3.exe
    

    i suggest you to use MINGW he can gives you a better environment to work with python

    Detect iPad users using jQuery?

    I use this:

    function fnIsAppleMobile() 
    {
        if (navigator && navigator.userAgent && navigator.userAgent != null) 
        {
            var strUserAgent = navigator.userAgent.toLowerCase();
            var arrMatches = strUserAgent.match(/(iphone|ipod|ipad)/);
            if (arrMatches != null) 
                 return true;
        } // End if (navigator && navigator.userAgent) 
    
        return false;
    } // End Function fnIsAppleMobile
    
    
    var bIsAppleMobile = fnIsAppleMobile(); // TODO: Write complaint to CrApple asking them why they don't update SquirrelFish with bugfixes, then remove
    

    How should I store GUID in MySQL tables?

    My DBA asked me when I asked about the best way to store GUIDs for my objects why I needed to store 16 bytes when I could do the same thing in 4 bytes with an Integer. Since he put that challenge out there to me I thought now was a good time to mention it. That being said...

    You can store a guid as a CHAR(16) binary if you want to make the most optimal use of storage space.

    Initializing a struct to 0

    See §6.7.9 Initialization:

    21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

    So, yes both of them work. Note that in C99 a new way of initialization, called designated initialization can be used too:

    myStruct _m1 = {.c2 = 0, .c1 = 1};
    

    How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

    In the %run magic documentation you can find:

    -i run the file in IPython’s namespace instead of an empty one. This is useful if you are experimenting with code written in a text editor which depends on variables defined interactively.

    Therefore, supplying -i does the trick:

    %run -i 'script.py'
    

    The "correct" way to do it

    Maybe the command above is just what you need, but with all the attention this question gets, I decided to add a few more cents to it for those who don't know how a more pythonic way would look like.
    The solution above is a little hacky, and makes the code in the other file confusing (Where does this x variable come from? and what is the f function?).

    I'd like to show you how to do it without actually having to execute the other file over and over again.
    Just turn it into a module with its own functions and classes and then import it from your Jupyter notebook or console. This also has the advantage of making it easily reusable and jupyters contextassistant can help you with autocompletion or show you the docstring if you wrote one.
    If you're constantly editing the other file, then autoreload comes to your help.

    Your example would look like this:
    script.py

    import matplotlib.pyplot as plt
    
    def myplot(f, x):
        """
        :param f: function to plot
        :type f: callable
        :param x: values for x
        :type x: list or ndarray
    
        Plots the function f(x).
        """
        # yes, you can pass functions around as if
        # they were ordinary variables (they are)
        plt.plot(x, f(x))
        plt.xlabel("Eje $x$",fontsize=16)
        plt.ylabel("$f(x)$",fontsize=16)
        plt.title("Funcion $f(x)$")
    

    Jupyter console

    In [1]: import numpy as np
    
    In [2]: %load_ext autoreload
    
    In [3]: %autoreload 1
    
    In [4]: %aimport script
    
    In [5]: def f(x):
          :     return np.exp(-x ** 2)
          :
          :
    
    In [6]: x = np.linspace(-1, 3, 100)
    
    In [7]: script.myplot(f, x)
    
    In [8]: ?script.myplot
    Signature: script.myplot(f, x)
    Docstring:
    :param f: function to plot
    :type f: callable
    :param x: x values
    :type x: list or ndarray
    File:      [...]\script.py
    Type:      function
    

    Recursively list all files in a directory including files in symlink directories

    The -L option to ls will accomplish what you want. It dereferences symbolic links.

    So your command would be:

    ls -LR
    

    You can also accomplish this with

    find -follow
    

    The -follow option directs find to follow symbolic links to directories.

    On Mac OS X use

    find -L
    

    as -follow has been deprecated.

    Python how to plot graph sine wave

    • Setting the x-axis with np.arange(0, 1, 0.001) gives an array from 0 to 1 in 0.001 increments.
      • x = np.arange(0, 1, 0.001) returns an array of 1000 points from 0 to 1, and y = np.sin(2*np.pi*x) you will get the sin wave from 0 to 1 sampled 1000 times

    I hope this will help:

    import matplotlib.pyplot as plt
    import numpy as np
    
    
    Fs = 8000
    f = 5
    sample = 8000
    x = np.arange(sample)
    y = np.sin(2 * np.pi * f * x / Fs)
    plt.plot(x, y)
    plt.xlabel('sample(n)')
    plt.ylabel('voltage(V)')
    plt.show()
    

    enter image description here

    P.S.: For comfortable work you can use The Jupyter Notebook.

    Google Forms file upload complete example

    As of October 2016, Google has added a file upload question type in native Google Forms, no Google Apps Script needed. See documentation.

    How to add an ORDER BY clause using CodeIgniter's Active Record methods?

    Using this code to multiple order by in single query.

    $this->db->from($this->table_name);
    $this->db->order_by("column1 asc,column2 desc");
    $query = $this->db->get(); 
    return $query->result();
    

    Turn off warnings and errors on PHP and MySQL

    PHP error_reporting reference:

    // Turn off all error reporting
    error_reporting(0);
    
    // Report simple running errors
    error_reporting(E_ERROR | E_WARNING | E_PARSE);
    
    // Reporting E_NOTICE can be good too (to report uninitialized
    // variables or catch variable name misspellings ...)
    error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
    
    // Report all errors except E_NOTICE
    // This is the default value set in php.ini
    error_reporting(E_ALL ^ E_NOTICE);
    
    // Report all PHP errors (see changelog)
    error_reporting(E_ALL);
    
    // Report all PHP errors
    error_reporting(-1);
    
    // Same as error_reporting(E_ALL);
    ini_set('error_reporting', E_ALL);
    

    Return in Scala

    Use case match for early return purpose. It will force you to declare all return branches explicitly, preventing the careless mistake of forgetting to write return somewhere.

    Deleting specific rows from DataTable

    I know this is, very, old question, and I have similar situation few days ago.

    Problem was, in my table are approx. 10000 rows, so looping trough DataTable rows was very slow.

    Finally, I found much faster solution, where I make copy of source DataTable with desired results, clear source DataTable and merge results from temporary DataTable into source one.

    note : instead search for Joe in DataRow called name You have to search for all records whose not have name Joe (little opposite way of searching)

    There is example (vb.net) :

    'Copy all rows into tmpTable whose not contain Joe in name DataRow
    Dim tmpTable As DataTable = drPerson.Select("name<>'Joe'").CopyToTable
    'Clear source DataTable, in Your case dtPerson
    dtPerson.Clear()
    'merge tmpTable into dtPerson (rows whose name not contain Joe)
    dtPerson.Merge(tmpTable)
    tmpTable = Nothing
    

    I hope so this shorter solution will help someone.

    There is c# code (not sure is it correct because I used online converter :( ):

    //Copy all rows into tmpTable whose not contain Joe in name DataRow
    DataTable tmpTable = drPerson.Select("name<>'Joe'").CopyToTable;
    //Clear source DataTable, in Your case dtPerson
    dtPerson.Clear();
    //merge tmpTable into dtPerson (rows whose name not contain Joe)
    dtPerson.Merge(tmpTable);
    tmpTable = null;
    

    Of course, I used Try/Catch in case if there is no result (for example, if Your dtPerson don't contain name Joe it will throw exception), so You do nothing with Your table, it stays unchanged.

    Why do we use web.xml?

    Web.xml is called as deployment descriptor file and its is is an XML file that contains information on the configuration of the web application, including the configuration of servlets.

    How can I find the number of years between two dates?

    I would recommend using the great Joda-Time library for everything date related in Java.

    For your needs you can use the Years.yearsBetween() method.

    Breaking up long strings on multiple lines in Ruby without stripping newlines

    I had this problem when I try to write a very long url, the following works.

    image_url = %w(
        http://minio.127.0.0.1.xip.io:9000/
        bucket29/docs/b7cfab0e-0119-452c-b262-1b78e3fccf38/
        28ed3774-b234-4de2-9a11-7d657707f79c?
        X-Amz-Algorithm=AWS4-HMAC-SHA256&
        X-Amz-Credential=ABABABABABABABABA
        %2Fus-east-1%2Fs3%2Faws4_request&
        X-Amz-Date=20170702T000940Z&
        X-Amz-Expires=3600&X-Amz-SignedHeaders=host&
        X-Amz-Signature=ABABABABABABABABABABAB
        ABABABABABABABABABABABABABABABABABABA
    ).join
    

    Note, there must not be any newlines, white spaces when the url string is formed. If you want newlines, then use HEREDOC.

    Here you have indentation for readability, ease of modification, without the fiddly quotes and backslashes on every line. The cost of joining the strings should be negligible.

    How to avoid reverse engineering of an APK file?

    Your client should hire someone that knows what they are doing, who can make the right decisions and can mentor you.

    Talk above about you having some ability to change the transaction processing system on the backend is absurd - you shouldn't be allowed to make such architectural changes, so don't expect to be able to.

    My rationale on this:

    Since your domain is payment processing, its safe to assume that PCI DSS and/or PA DSS (and potential state/federal law) will be significant to your business - to be compliant you must show you are secure. To be insecure then find out (via testing) that you aren't secure, then fixing, retesting, etcetera until security can be verified at a suitable level = expensive, slow, high-risk way to success. To do the right thing, think hard up front, commit experienced talent to the job, develop in a secure manner, then test, fix (less), etcetera (less) until security can be verified at a suitable level = inexpensive, fast, low-risk way to success.

    C#: how to get first char of a string?

    MyString.Remove(1, 2); also works

    Usage of MySQL's "IF EXISTS"

    SELECT IF((
         SELECT count(*) FROM gdata_calendars 
         WHERE `group` =  ? AND id = ?)
    ,1,0);
    

    For Detail explanation you can visit here

    Laravel migration: unique key is too long, even if specified

    I added to the migration itself

    Schema::defaultStringLength(191);
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
    

    yes, I know I need to consider it on every migration but I would rather that than have it tucked away in some completely unrelated service provider

    CSS get height of screen resolution

    You could use viewport-percentage lenghts.

    See: http://stanhub.com/how-to-make-div-element-100-height-of-browser-window-using-css-only/

    It works like this:

    .element{
        height: 100vh; /* For 100% screen height */
        width:  100vw; /* For 100% screen width */
    }
    

    More info also available through Mozilla Developer Network and W3C.

    submitting a form when a checkbox is checked

    $(document).ready(
        function()
        {
            $("input:checkbox").change(
                function()
                {
                    if( $(this).is(":checked") )
                    {
                        $("#formName").submit();
                    }
                }
            )
        }
    );
    

    Though it would probably be better to add classes to each of the checkboxes and do

    $(".checkbox_class").change();
    

    so that you can choose which checkboxes submit the form instead of all of them doing it.

    What are the special dollar sign shell variables?

    Take care with some of the examples; $0 may include some leading path as well as the name of the program. Eg save this two line script as ./mytry.sh and the execute it.

    #!/bin/bash
    
    echo "parameter 0 --> $0" ; exit 0
    

    Output:

    parameter 0 --> ./mytry.sh
    

    This is on a current (year 2016) version of Bash, via Slackware 14.2

    What's the main difference between int.Parse() and Convert.ToInt32

    Have a look in reflector:

    int.Parse("32"):

    public static int Parse(string s)
    {
        return System.Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
    }
    

    which is a call to:

    internal static unsafe int ParseInt32(string s, NumberStyles style, NumberFormatInfo info)
    {
        byte* stackBuffer = stackalloc byte[1 * 0x72];
        NumberBuffer number = new NumberBuffer(stackBuffer);
        int num = 0;
        StringToNumber(s, style, ref number, info, false);
        if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
        {
            if (!HexNumberToInt32(ref number, ref num))
            {
                throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
            }
            return num;
        }
        if (!NumberToInt32(ref number, ref num))
        {
            throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
        }
        return num;
    }
    

    Convert.ToInt32("32"):

    public static int ToInt32(string value)
    {
        if (value == null)
        {
            return 0;
        }
        return int.Parse(value, CultureInfo.CurrentCulture);
    }
    

    As the first (Dave M's) comment says.

    How to prevent a browser from storing passwords

    This is not possible in modern browsers, and for good reason. Modern browsers offer password managers, which enable users to use stronger passwords than they would usually.

    As explained by MDN: How to Turn Off Form Autocompletion:

    Modern browsers implement integrated password management: when the user enters a username and password for a site, the browser offers to remember it for the user. When the user visits the site again, the browser autofills the login fields with the stored values.

    Additionally, the browser enables the user to choose a master password that the browser will use to encrypt stored login details.

    Even without a master password, in-browser password management is generally seen as a net gain for security. Since users do not have to remember passwords that the browser stores for them, they are able to choose stronger passwords than they would otherwise.

    For this reason, many modern browsers do not support autocomplete="off" for login fields:

    • If a site sets autocomplete="off" for a form, and the form includes username and password input fields, then the browser will still offer to remember this login, and if the user agrees, the browser will autofill those fields the next time the user visits the page.

    • If a site sets autocomplete="off" for username and password input fields, then the browser will still offer to remember this login, and if the user agrees, the browser will autofill those fields the next time the user visits the page.

    This is the behavior in Firefox (since version 38), Google Chrome (since 34), and Internet Explorer (since version 11).

    If an author would like to prevent the autofilling of password fields in user management pages where a user can specify a new password for someone other than themself, autocomplete="new-password" should be specified, though support for this has not been implemented in all browsers yet.

    NSUserDefaults - How to tell if a key exists

    objectForKey: will return nil if it doesn't exist.

    Get all messages from Whatsapp

    You can get access to the WhatsApp data base located on the SD card only as a root user I think. if you open "\data\data\com.whatsapp" you will see that "databases" is linked to "\firstboot\sqlite\com.whatsapp\"

    Set an empty DateTime variable

    A string is a sequence of characters. So it makes sense to have an empty string, which is just an empty sequence of characters.

    But DateTime is just a single value, so it's doesn't make sense to talk about an “empty” DateTime.

    If you want to represent the concept of “no value”, that's represented as null in .Net. And if you want to use that with value types, you need to explicitly make them nullable. That means either using Nullable<DateTime>, or the equivalent DateTime?.

    DateTime (just like all value types) also has a default value, that's assigned to uninitialized fields and you can also get it by new DateTime() or default(DateTime). But you probably don't want to use it, since it represents valid date: 1.1.0001 0:00:00.

    How to time Java program execution speed

    Be aware that there are some issues where System#nanoTime() cannot be reliably used on multi-core CPU's to record elapsed time ... each core has maintains its own TSC (Time Stamp Counter): this counter is used to obtain the nano time (really it is the number of ticks since the CPU booted).

    Hence, unless the OS does some TSC time warping to keep the cores in sync, then if a thread gets scheduled on one core when the initial time reading is taken, then switched to a different core, the relative time can sporadically appear to jump backwards and forwards.

    I observed this some time ago on AMD/Solaris where elapsed times between two timing points were sometimes coming back as either negative values or unexpectedly large positive numbers. There was a Solaris kernel patch and a BIOS setting required to force the AMD PowerNow! off, which appeared to solved it.

    Also, there is (AFAIK) a so-far unfixed bug when using java System#nanoTime() in a VirtualBox environment; causing all sorts of bizarre intermittent threading problems for us as much of the java.util.concurrency package relies on nano time.

    See also:

    Is System.nanoTime() completely useless? http://vbox.innotek.de/pipermail/vbox-trac/2010-January/135631.html

    Rebuild all indexes in a Database

    Replace the "YOUR DATABASE NAME" in the query below.

        DECLARE @Database NVARCHAR(255)   
        DECLARE @Table NVARCHAR(255)  
        DECLARE @cmd NVARCHAR(1000)  
    
        DECLARE DatabaseCursor CURSOR READ_ONLY FOR  
        SELECT name FROM master.sys.databases   
        WHERE name IN ('YOUR DATABASE NAME')  -- databases
        AND state = 0 -- database is online
        AND is_in_standby = 0 -- database is not read only for log shipping
        ORDER BY 1  
    
        OPEN DatabaseCursor  
    
        FETCH NEXT FROM DatabaseCursor INTO @Database  
        WHILE @@FETCH_STATUS = 0  
        BEGIN  
    
           SET @cmd = 'DECLARE TableCursor CURSOR READ_ONLY FOR SELECT ''['' + table_catalog + ''].['' + table_schema + ''].['' +  
           table_name + '']'' as tableName FROM [' + @Database + '].INFORMATION_SCHEMA.TABLES WHERE table_type = ''BASE TABLE'''   
    
           -- create table cursor  
           EXEC (@cmd)  
           OPEN TableCursor   
    
           FETCH NEXT FROM TableCursor INTO @Table   
           WHILE @@FETCH_STATUS = 0   
           BEGIN
              BEGIN TRY   
                 SET @cmd = 'ALTER INDEX ALL ON ' + @Table + ' REBUILD' 
                 PRINT @cmd -- uncomment if you want to see commands
                 EXEC (@cmd) 
              END TRY
              BEGIN CATCH
                 PRINT '---'
                 PRINT @cmd
                 PRINT ERROR_MESSAGE() 
                 PRINT '---'
              END CATCH
    
              FETCH NEXT FROM TableCursor INTO @Table   
           END   
    
           CLOSE TableCursor   
           DEALLOCATE TableCursor  
    
           FETCH NEXT FROM DatabaseCursor INTO @Database  
        END  
        CLOSE DatabaseCursor   
        DEALLOCATE DatabaseCursor
    

    CakePHP 3.0 installation: intl extension missing from system

    I had the same problem in windows The error was that I had installed several versions of PHP and the Environment Variables were routing to wrong Path of php see image example

    How do I connect C# with Postgres?

    Here is a walkthrough, Using PostgreSQL in your C# (.NET) application (An introduction):

    In this article, I would like to show you the basics of using a PostgreSQL database in your .NET application. The reason why I'm doing this is the lack of PostgreSQL articles on CodeProject despite the fact that it is a very good RDBMS. I have used PostgreSQL back in the days when PHP was my main programming language, and I thought.... well, why not use it in my C# application.

    Other than that you will need to give us some specific problems that you are having so that we can help diagnose the problem.

    How to validate date with format "mm/dd/yyyy" in JavaScript?

    function fdate_validate(vi)
    {
      var parts =vi.split('/');
      var result;
      var mydate = new Date(parts[2],parts[1]-1,parts[0]);
      if (parts[2] == mydate.getYear() && parts[1]-1 == mydate.getMonth() && parts[0] == mydate.getDate() )
      {result=0;}
      else
      {result=1;}
      return(result);
    }
    

    How to fill 100% of remaining height?

    You should be able to do this if you add in a div (#header below) to wrap your contents of 1.

    1. If you float #header, the content from #someid will be forced to flow around it.

    2. Next, you set #header's width to 100%. This will make it expand to fill the width of the containing div, #full. This will effectively push all of #someid's content below #header since there is no room to flow around the sides anymore.

    3. Finally, set #someid's height to 100%, this will make it the same height as #full.

    JSFiddle

    HTML

    <div id="full">
        <div id="header">Contents of 1</div>
        <div id="someid">Contents of 2</div>
    </div>
    

    CSS

    html, body, #full, #someid {
      height: 100%;
    }
    
    #header {
      float: left;
      width: 100%;
    }
    

    Update

    I think it's worth mentioning that flexbox is well supported across modern browsers today. The CSS could be altered have #full become a flex container, and #someid should set it's flex grow to a value greater than 0.

    html, body, #full {
      height: 100%;
    }
    
    #full {
      display: flex;
      flex-direction: column;
    }
    
    #someid {
      flex-grow: 1;
    }
    

    How to Update a Component without refreshing full page - Angular

    To refresh the component at regular intervals I found this the best method. In the ngOnInit method setTimeOut function

    ngOnInit(): void {
      setTimeout(() => { this.ngOnInit() }, 1000 * 10)
    }
    //10 is the number of seconds
    

    Java ArrayList how to add elements at the beginning

    What you are describing, is an appropriate situation to use Queue.

    Since you want to add new element, and remove the old one. You can add at the end, and remove from the beginning. That will not make much of a difference.

    Queue has methods add(e) and remove() which adds at the end the new element, and removes from the beginning the old element, respectively.

    Queue<Integer> queue = new LinkedList<Integer>();
    queue.add(5);
    queue.add(6);
    queue.remove();  // Remove 5
    

    So, every time you add an element to the queue you can back it up with a remove method call.


    UPDATE: -

    And if you want to fix the size of the Queue, then you can take a look at: - ApacheCommons#CircularFifoBuffer

    From the documentation: -

    CircularFifoBuffer is a first in first out buffer with a fixed size that replaces its oldest element if full.

    Buffer queue = new CircularFifoBuffer(2); // Max size
    
    queue.add(5);
    queue.add(6);
    queue.add(7);  // Automatically removes the first element `5`
    

    As you can see, when the maximum size is reached, then adding new element automatically removes the first element inserted.

    Count how many rows have the same value

    Try this Query

    select NUM, count(1) as count 
    from tbl 
    where num = 1
    group by NUM
    --having count(1) (You condition)
    

    SQL FIDDLE

    Switch statement equivalent in Windows batch file

    I guess all other options would be more cryptic. For those who like readable and non-cryptic code:

    IF        "%ID%"=="0" (
        REM do something
    
    ) ELSE IF "%ID%"=="1" (
        REM do something else
    
    ) ELSE IF "%ID%"=="2" (
        REM do another thing
    
    ) ELSE (
        REM default case...
    )
    

    It's like an anecdote:

    Magician: Put the egg under the hat, do the magic passes ... Remove the hat and ... get the same egg but in the side view ...

    The IF ELSE solution isn't that bad. It's almost as good as python's if elif else. More cryptic 'eggs' can be found here.

    Redis: How to access Redis log file

    Check your error log file and then use the tail command as:

    tail -200f /var/log/redis_6379.log
    

    or

     tail -200f /var/log/redis.log
    

    According to your error file name..

    Retrieve a single file from a repository

    If your Git repository hosted on Azure-DevOps (VSTS) you can retrieve a single file with Rest API.

    The format of this API looks like this:

     https://dev.azure.com/{organization}/_apis/git/repositories/{repositoryId}/items?path={pathToFile}&api-version=4.1?download=true
    

    For example:

     https://dev.azure.com/{organization}/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/items?scopePath=/MyWebSite/MyWebSite/Views/Home/_Home.cshtml&download=true&api-version=4.1
    

    MVC Razor @foreach

    I'm using @foreach when I send an entity that contains a list of entities ( for example to display 2 grids in 1 view )

    For example if I'm sending as model the entity Foo that contains Foo1(List<Foo1>) and Foo2(List<Foo2>)

    I can refer to the first List with:

    @foreach (var item in Model.Foo.Foo1)
    {
        @Html.DisplayFor(modelItem=> item.fooName)
    }
    

    The Use of Multiple JFrames: Good or Bad Practice?

    It is not a good practice but even though you wish to use it you can use the singleton pattern as its good. I have used the singleton patterns in most of my project its good.

    How do I force "git pull" to overwrite local files?

    The only thing that worked for me was:

    git reset --hard HEAD~5
    

    This will take you back five commits and then with

    git pull
    

    I found that by looking up how to undo a Git merge.

    Copy files from one directory into an existing directory

    For inside some directory, this will be use full as it copy all contents from "folder1" to new directory "folder2" inside some directory.

    $(pwd) will get path for current directory.

    Notice the dot (.) after folder1 to get all contents inside folder1

    cp -r $(pwd)/folder1/. $(pwd)/folder2
    

    How to make a select with array contains value clause in psql

    Try

    SELECT * FROM table WHERE arr @> ARRAY['s']::varchar[]
    

    error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied

    First, sudo pip install 'package-name' means nothing it will return

    sudo: pip: command not found
    

    You get the Permission denied, you shouldn't use pip install as root anyway. You can just install the packages into your own user like mentionned above with

    pip install 'package-name' --user
    

    and it will work as you intend. If you need it in any other user just run the same command and you'll be good to go.

    Send Email Intent

    Sometimes you need to open default email app to view the inbox without creating a new letter, in this case it will help:

    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_APP_EMAIL);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
    

    Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

    In Java8

    //will prints each element line by line
    stack.forEach(System.out::println);
    

    or

    //to print with commas
    stack.forEach(
        (ele) -> {
            System.out.print(ele + ",");
        }
    );
    

    How do I change selected value of select2 dropdown with JqGrid?

    My Expected code :

    $('#my-select').val('').change();
    

    working perfectly thank to @PanPipes for the usefull one.

    Speed up rsync with Simultaneous/Concurrent File Transfers?

    I've developed a python package called: parallel_sync

    https://pythonhosted.org/parallel_sync/pages/examples.html

    Here is a sample code how to use it:

    from parallel_sync import rsync
    creds = {'user': 'myusername', 'key':'~/.ssh/id_rsa', 'host':'192.168.16.31'}
    rsync.upload('/tmp/local_dir', '/tmp/remote_dir', creds=creds)
    

    parallelism by default is 10; you can increase it:

    from parallel_sync import rsync
    creds = {'user': 'myusername', 'key':'~/.ssh/id_rsa', 'host':'192.168.16.31'}
    rsync.upload('/tmp/local_dir', '/tmp/remote_dir', creds=creds, parallelism=20)
    

    however note that ssh typically has the MaxSessions by default set to 10 so to increase it beyond 10, you'll have to modify your ssh settings.

    What are the differences between delegates and events?

    Delegate is a type-safe function pointer. Event is an implementation of publisher-subscriber design pattern using delegate.

    Classpath resource not found when running as jar

    If you want to use a file:

    ClassPathResource classPathResource = new ClassPathResource("static/something.txt");
    
    InputStream inputStream = classPathResource.getInputStream();
    File somethingFile = File.createTempFile("test", ".txt");
    try {
        FileUtils.copyInputStreamToFile(inputStream, somethingFile);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    

    Hex colors: Numeric representation for "transparent"?

    I was also trying for transparency - maybe you could try leaving blank the value of background e.g. something like

    bgcolor=" "
    

    Maven: Non-resolvable parent POM

    I had similar problem at my work.

    Building the parent project without dependency created parent_project.pom file in the .m2 folder.

    Then add the child module in the parent POM and run Maven build.

    <modules>
        <module>module1</module>
        <module>module2</module>
        <module>module3</module>
        <module>module4</module>
    </modules>
    

    How to Execute a Python File in Notepad ++?

    I usually prefer running my python scripts on python native IDLE interactive shell rather than from command prompt or something like that. I've tried it, and it works for me. Just open "Run > Run...", then paste the code below

    python  -m idlelib.idle -r "$(FULL_CURRENT_PATH)"
    

    After that, you can save it with your hotkey.

    You must ensure your desired python is added and registered in your environment variables.

    PHP foreach with Nested Array?

    Both syntaxes are correct. But the result would be Array. You probably want to do something like this:

    foreach ($tmpArray[1] as $value) {
      echo $value[0];
      foreach($value[1] as $val){
        echo $val;
      }
    }
    

    This will print out the string "two" ($value[0]) and the integers 4, 5 and 6 from the array ($value[1]).

    What's the Use of '\r' escape sequence?

    The program is printing "Hey this is my first hello world ", then it is moving the cursor back to the beginning of the line. How this will look on the screen depends on your environment. It appears the beginning of the string is being overwritten by something, perhaps your command line prompt.

    Counting words in string

    I know its late but this regex should solve your problem. This will match and return the number of words in your string. Rather then the one you marked as a solution, which would count space-space-word as 2 words even though its really just 1 word.

    function countWords(str) {
        var matches = str.match(/\S+/g);
        return matches ? matches.length : 0;
    }
    

    Android - Dynamically Add Views into View

    Use the LayoutInflater to create a view based on your layout template, and then inject it into the view where you need it.

    LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = vi.inflate(R.layout.your_layout, null);
    
    // fill in any details dynamically here
    TextView textView = (TextView) v.findViewById(R.id.a_text_view);
    textView.setText("your text");
    
    // insert into main view
    ViewGroup insertPoint = (ViewGroup) findViewById(R.id.insert_point);
    insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
    

    You may have to adjust the index where you want to insert the view.

    Additionally, set the LayoutParams according to how you would like it to fit in the parent view. e.g. with FILL_PARENT, or MATCH_PARENT, etc.

    How to get VM arguments from inside of Java application?

    I found that HotSpot lists all the VM arguments in the management bean except for -client and -server. Thus, if you infer the -client/-server argument from the VM name and add this to the runtime management bean's list, you get the full list of arguments.

    Here's the SSCCE:

    import java.util.*;
    import java.lang.management.ManagementFactory;
    
    class main {
      public static void main(final String[] args) {
        System.out.println(fullVMArguments());
      }
    
      static String fullVMArguments() {
        String name = javaVmName();
        return (contains(name, "Server") ? "-server "
          : contains(name, "Client") ? "-client " : "")
          + joinWithSpace(vmArguments());
      }
    
      static List<String> vmArguments() {
        return ManagementFactory.getRuntimeMXBean().getInputArguments();
      }
    
      static boolean contains(String s, String b) {
        return s != null && s.indexOf(b) >= 0;
      }
    
      static String javaVmName() {
        return System.getProperty("java.vm.name");
      }
    
      static String joinWithSpace(Collection<String> c) {
        return join(" ", c);
      }
    
      public static String join(String glue, Iterable<String> strings) {
        if (strings == null) return "";
        StringBuilder buf = new StringBuilder();
        Iterator<String> i = strings.iterator();
        if (i.hasNext()) {
          buf.append(i.next());
          while (i.hasNext())
            buf.append(glue).append(i.next());
        }
        return buf.toString();
      }
    }
    

    Could be made shorter if you want the arguments in a List<String>.

    Final note: We might also want to extend this to handle the rare case of having spaces within command line arguments.

    Redefine tab as 4 spaces

    Permanent for all users (when you alone on server):

    # echo "set tabstop=4" >> /etc/vim/vimrc
    

    Appends the setting in the config file. Normally on new server apt-get purge nano mc and all other to save your time. Otherwise, you will redefine editor in git, crontab etc.

    What are the different types of keys in RDBMS?

    There also exists a UNIQUE KEY. The main difference between PRIMARY KEY and UNIQUE KEY is that the PRIMARY KEY never takes NULL value while a UNIQUE KEY may take NULL value. Also, there can be only one PRIMARY KEY in a table while UNIQUE KEY may be more than one.

    How to check if a Constraint exists in Sql server?

    You can use the one above with one caveat:

    IF EXISTS(
        SELECT 1 FROM sys.foreign_keys 
        WHERE parent_object_id = OBJECT_ID(N'dbo.TableName') 
            AND name = 'CONSTRAINTNAME'
    )
    BEGIN 
        ALTER TABLE TableName DROP CONSTRAINT CONSTRAINTNAME 
    END 
    

    Need to use the name = [Constraint name] since a table may have multiple foreign keys and still not have the foreign key being checked for

    How to change navigation bar color in iOS 7 or 6?

    One more thing, if you want to change the navigation bg color in UIPopover you need to set barStyle to UIBarStyleBlack

    if([UINavigationBar instancesRespondToSelector:@selector(barTintColor)]){ //iOS7
        navigationController.navigationBar.barStyle = UIBarStyleBlack;
        navigationController.navigationBar.barTintColor = [UIColor redColor];
    }