Programs & Examples On #Pixastic

Pixastic is a JavaScript library which allows you to perform a variety of operations, filters and fancy effects on images using just a bit of JavaScript.

Resizing an image in an HTML5 canvas

Fast image resize/resample algorithm using Hermite filter with JavaScript. Support transparency, gives good quality. Preview:

enter image description here

Update: version 2.0 added on GitHub (faster, web workers + transferable objects). Finally i got it working!

Git: https://github.com/viliusle/Hermite-resize
Demo: http://viliusle.github.io/miniPaint/

/**
 * Hermite resize - fast image resize/resample using Hermite filter. 1 cpu version!
 * 
 * @param {HtmlElement} canvas
 * @param {int} width
 * @param {int} height
 * @param {boolean} resize_canvas if true, canvas will be resized. Optional.
 */
function resample_single(canvas, width, height, resize_canvas) {
    var width_source = canvas.width;
    var height_source = canvas.height;
    width = Math.round(width);
    height = Math.round(height);

    var ratio_w = width_source / width;
    var ratio_h = height_source / height;
    var ratio_w_half = Math.ceil(ratio_w / 2);
    var ratio_h_half = Math.ceil(ratio_h / 2);

    var ctx = canvas.getContext("2d");
    var img = ctx.getImageData(0, 0, width_source, height_source);
    var img2 = ctx.createImageData(width, height);
    var data = img.data;
    var data2 = img2.data;

    for (var j = 0; j < height; j++) {
        for (var i = 0; i < width; i++) {
            var x2 = (i + j * width) * 4;
            var weight = 0;
            var weights = 0;
            var weights_alpha = 0;
            var gx_r = 0;
            var gx_g = 0;
            var gx_b = 0;
            var gx_a = 0;
            var center_y = (j + 0.5) * ratio_h;
            var yy_start = Math.floor(j * ratio_h);
            var yy_stop = Math.ceil((j + 1) * ratio_h);
            for (var yy = yy_start; yy < yy_stop; yy++) {
                var dy = Math.abs(center_y - (yy + 0.5)) / ratio_h_half;
                var center_x = (i + 0.5) * ratio_w;
                var w0 = dy * dy; //pre-calc part of w
                var xx_start = Math.floor(i * ratio_w);
                var xx_stop = Math.ceil((i + 1) * ratio_w);
                for (var xx = xx_start; xx < xx_stop; xx++) {
                    var dx = Math.abs(center_x - (xx + 0.5)) / ratio_w_half;
                    var w = Math.sqrt(w0 + dx * dx);
                    if (w >= 1) {
                        //pixel too far
                        continue;
                    }
                    //hermite filter
                    weight = 2 * w * w * w - 3 * w * w + 1;
                    var pos_x = 4 * (xx + yy * width_source);
                    //alpha
                    gx_a += weight * data[pos_x + 3];
                    weights_alpha += weight;
                    //colors
                    if (data[pos_x + 3] < 255)
                        weight = weight * data[pos_x + 3] / 250;
                    gx_r += weight * data[pos_x];
                    gx_g += weight * data[pos_x + 1];
                    gx_b += weight * data[pos_x + 2];
                    weights += weight;
                }
            }
            data2[x2] = gx_r / weights;
            data2[x2 + 1] = gx_g / weights;
            data2[x2 + 2] = gx_b / weights;
            data2[x2 + 3] = gx_a / weights_alpha;
        }
    }
    //clear and resize canvas
    if (resize_canvas === true) {
        canvas.width = width;
        canvas.height = height;
    } else {
        ctx.clearRect(0, 0, width_source, height_source);
    }

    //draw
    ctx.putImageData(img2, 0, 0);
}

Use of min and max functions in C++

I always use the min and max macros for ints. I'm not sure why anyone would use fmin or fmax for integer values.

The big gotcha with min and max is that they're not functions, even if they look like them. If you do something like:

min (10, BigExpensiveFunctionCall())

That function call may get called twice depending on the implementation of the macro. As such, its best practice in my org to never call min or max with things that aren't a literal or variable.

google map API zoom range

Available Zoom Levels

Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

  • Road maps - seem to go up to zoom level 22 everywhere
  • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
  • Remote regions of Antarctica: 13
  • Gobi Desert: 17
  • Much of the U.S. and Europe: 21
  • "Deep zoom" locations: 22-23 (see bkaid's link)

Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

Map Scale at Various Zoom Levels

Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)

Formula is from Chris Broadfoot's comment.


Google Maps basics

Zoom Level - zoom

0 - 19

0 lowest zoom (whole world)

19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()


What you're looking for are the scales for each zoom level. Use these:

20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

A default document is not configured for the requested URL, and directory browsing is not enabled on the server

Make sure you have your default page named as index.aspx and not something like main.aspx or home.aspx . And also see to it that all your properties in your class matches exactly with that of your table in the database. Remove any properties that is not in sync with the database. That solved my problem!! :)

How to use curl in a shell script?

#!/bin/bash                                                                                                                                                                                     
CURL='/usr/bin/curl'
RVMHTTP="https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer"
CURLARGS="-f -s -S -k"

# you can store the result in a variable
raw="$($CURL $CURLARGS $RVMHTTP)"

# or you can redirect it into a file:
$CURL $CURLARGS $RVMHTTP > /tmp/rvm-installer

or:

Execute bash script from URL

Windows batch command(s) to read first line from text file

for /f "delims=" %a in (downing.txt) do echo %a & pause>nul

Prints 1st line, then waits for user to press a key to print next line. After printing required lines, press Ctrl+C to stop.

@Ross Presser: This method prints lines only, not prepend line numbers.

Return value in SQL Server stored procedure

@EmailAddress varchar(200),
@NickName varchar(100),
@Password varchar(150),
@Sex varchar(50),
@Age int,
@EmailUpdates int,
@UserId int OUTPUT
DECLARE @AA INT
SET @AA=(SELECT COUNT(UserId) FROM RegUsers WHERE EmailAddress = @EmailAddress)

IF @AA> 0
    BEGIN
        SET @UserId = 0
    END
ELSE
    BEGIN
        INSERT INTO RegUsers (EmailAddress,NickName,PassWord,Sex,Age,EmailUpdates) VALUES (@EmailAddress,@NickName,@Password,@Sex,@Age,@EmailUpdates)
        SELECT SCOPE_IDENTITY()
    END

END

How to get all groups that a user is a member of?

Get group membership for a user:

$strUserName = "Primoz"
$strUser = get-qaduser -SamAccountName $strUserName
$strUser.memberof

See Get Group Membership for a User

But also see Quest's Free PowerShell Commands for Active Directory.

[Edit: Get-ADPrincipalGroupMembership command is included in Powershell since v2 with Windows 2008 R2. See kstrauss' answer below.]

SELECT COUNT in LINQ to SQL C#

Like that

var purchCount = (from purchase in myBlaContext.purchases select purchase).Count();

or even easier

var purchCount = myBlaContext.purchases.Count()

.htaccess redirect all pages to new domain

My reputation won't allow me to comment on an answer, but I just wanted to point out that the highest rated answer here has an error:

RewriteEngine on 
RewriteRule ^(.*)$ http://www.newdomain.com$1 [R=301,L]

should have a slash before the $1, so

RewriteEngine on 
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L]

Instantly detect client disconnection from server socket

You can also check the .IsConnected property of the socket if you were to poll.

Python Iterate Dictionary by Index

Do this:

for i in dict.keys():
  dict[i]

RadioGroup: How to check programmatically

it will work if you put your mOption.check(R.id.option1); into onAttachedToWindow method or like this:

view.post(new Runnable()
{
    public void run() 
    {
        // TODO Auto-generated method stub
        mOption.check(R.id.option1); 
    }
});

the reason may be that check method will only work when the radiogroup is actually rendered.

Rename master branch for both local and remote Git repositories

The selected answer failed when I tried it. It throws an error: refusing to delete the current branch: refs/heads/master. I guess I'll post what works for me:

git checkout master             # if not in master already

git branch placeholder          # create placeholder branch
git checkout placeholder        # checkout to placeholder
git push remote placeholder     # push placeholder to remote repository

git branch -d master            # remove master in local repository
git push remote :master         # remove master from remote repository.

The trick is to checkout to the placeholder right before pushing it to remote repository. The rest is self explanatory, deleting the master branch and push it to the remote repository should works now. Excerpted from here.

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

I think what you're seeing is the hiding and showing of scrollbars. Here's a quick demo showing the width change.

As an aside: do you need to poll constantly? You might be able to optimize your code to run on the resize event, like this:

$(window).resize(function() {
  //update stuff
});

How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

You can take the code above and go one step further by introducing a custom controller factory that injects the HandleErrorWithElmah attribute into every controller.

For more infomation check out my blog series on logging in MVC. The first article covers getting Elmah set up and running for MVC.

There is a link to downloadable code at the end of the article. Hope that helps.

http://dotnetdarren.wordpress.com/

What is the best open XML parser for C++?

TiCPP is a "more c++" version of TinyXML.

'TiCPP' is short for the official name TinyXML++. It is a completely new interface to TinyXML (http://www.grinninglizard.com/tinyxml/) that uses MANY of the C++ strengths. Templates, exceptions, and much better error handling. It is also fully documented in doxygen. It is really cool because this version let's you interface tiny the exact same way as before or you can choose to use the new 'ticpp' classes. All you need to do is define TIXML_USE_TICPP. It has been tested in VC 6.0, VC 7.0, VC 7.1, VC 8.0, MinGW gcc 3.4.5, and in Linux GNU gcc 3+

How to align 3 divs (left/center/right) inside another div?

HTML:

<div id="container" class="blog-pager">
   <div id="left">Left</div>
   <div id="right">Right</div>
   <div id="center">Center</div>    
</div>

CSS:

 #container{width:98%; }
 #left{float:left;}
 #center{text-align:center;}
 #right{float:right;}

text-align:center; gives perfect centre align.

JSFiddle Demo

Get the records of last month in SQL server

All the existing (working) answers have one of two problems:

  1. They will ignore indices on the column being searched
  2. The will (potentially) select data that is not intended, silently corrupting your results.

1. Ignored Indices:

For the most part, when a column being searched has a function called on it (including implicitly, like for CAST), the optimizer must ignore indices on the column and search through every record. Here's a quick example:

We're dealing with timestamps, and most RDBMSs tend to store this information as an increasing value of some sort, usually a long or BIGINTEGER count of milli-/nanoseconds. The current time thus looks/is stored like this:

1402401635000000  -- 2014-06-10 12:00:35.000000 GMT

You don't see the 'Year' value ('2014') in there, do you? In fact, there's a fair bit of complicated math to translate back and forth. So if you call any of the extraction/date part functions on the searched column, the server has to perform all that math just to figure out if you can include it in the results. On small tables this isn't an issue, but as the percentage of rows selected decreases this becomes a larger and larger drain. Then in this case, you're doing it a second time for asking about MONTH... well, you get the picture.

2. Unintended data:

Depending on the particular version of SQL Server, and column datatypes, using BETWEEN (or similar inclusive upper-bound ranges: <=) can result in the wrong data being selected. Essentially, you potentially end up including data from midnight of the "next" day, or excluding some portion of the "current" day's records.

What you should be doing:

So we need a way that's safe for our data, and will use indices (if viable). The correct way is then of the form:

WHERE date_created >= @startOfPreviousMonth AND date_created < @startOfCurrentMonth

Given that there's only one month, @startOfPreviousMonth can be easily substituted for/derived by:

DATEADD(month, -1, @startOCurrentfMonth)

If you need to derive the start-of-current-month in the server, you can do it via the following:

DATEADD(month, DATEDIFF(month, 0, CURRENT_TIMESTAMP), 0)

A quick word of explanation here. The initial DATEDIFF(...) will get the difference between the start of the current era (0001-01-01 - AD, CE, whatever), essentially returning a large integer. This is the count of months to the start of the current month. We then add this number to the start of the era, which is at the start of the given month.

So your full script could/should look similar to the following:

DECLARE @startOfCurrentMonth DATETIME
SET @startOfCurrentMonth = DATEADD(month, DATEDIFF(month, 0, CURRENT_TIMESTAMP), 0)

SELECT *
FROM Member
WHERE date_created >= DATEADD(month, -1, @startOfCurrentMonth) -- this was originally    misspelled
      AND date_created < @startOfCurrentMonth

All date operations are thus only performed once, on one value; the optimizer is free to use indices, and no incorrect data will be included.

calculating number of days between 2 columns of dates in data frame

Without your seeing your data (you can use the output of dput(head(survey)) to show us) this is a shot in the dark:

survey <- data.frame(date=c("2012/07/26","2012/07/25"),tx_start=c("2012/01/01","2012/01/01"))

survey$date_diff <- as.Date(as.character(survey$date), format="%Y/%m/%d")-
                  as.Date(as.character(survey$tx_start), format="%Y/%m/%d")
survey
       date   tx_start date_diff
1 2012/07/26 2012/01/01  207 days
2 2012/07/25 2012/01/01  206 days

Show default value in Spinner in android

Try below:

   <Spinner
    android:id="@+id/YourSpinnerId"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:prompt="Gender" />

How to write hello world in assembler under Windows?

To get an .exe with NASM'compiler and Visual Studio's linker this code works fine:

global WinMain
extern ExitProcess  ; external functions in system libraries 
extern MessageBoxA

section .data 
title:  db 'Win64', 0
msg:    db 'Hello world!', 0

section .text
WinMain:
    sub rsp, 28h  
    mov rcx, 0       ; hWnd = HWND_DESKTOP
    lea rdx,[msg]    ; LPCSTR lpText
    lea r8,[title]   ; LPCSTR lpCaption
    mov r9d, 0       ; uType = MB_OK
    call MessageBoxA
    add rsp, 28h  

    mov  ecx,eax
    call ExitProcess

    hlt     ; never here

If this code is saved on e.g. "test64.asm", then to compile:

nasm -f win64 test64.asm

Produces "test64.obj" Then to link from command prompt:

path_to_link\link.exe test64.obj /subsystem:windows /entry:WinMain  /libpath:path_to_libs /nodefaultlib kernel32.lib user32.lib /largeaddressaware:no

where path_to_link could be C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin or wherever is your link.exe program in your machine, path_to_libs could be C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x64 or wherever are your libraries (in this case both kernel32.lib and user32.lib are on the same place, otherwise use one option for each path you need) and the /largeaddressaware:no option is necessary to avoid linker's complain about addresses to long (for user32.lib in this case). Also, as it is done here, if Visual's linker is invoked from command prompt, it is necessary to setup the environment previously (run once vcvarsall.bat and/or see MS C++ 2010 and mspdb100.dll).

Query based on multiple where clauses in Firebase

Using Firebase's Query API, you might be tempted to try this:

// !!! THIS WILL NOT WORK !!!
ref
  .orderBy('genre')
  .startAt('comedy').endAt('comedy')
  .orderBy('lead')                  // !!! THIS LINE WILL RAISE AN ERROR !!!
  .startAt('Jack Nicholson').endAt('Jack Nicholson')
  .on('value', function(snapshot) { 
      console.log(snapshot.val()); 
  });

But as @RobDiMarco from Firebase says in the comments:

multiple orderBy() calls will throw an error

So my code above will not work.

I know of three approaches that will work.

1. filter most on the server, do the rest on the client

What you can do is execute one orderBy().startAt()./endAt() on the server, pull down the remaining data and filter that in JavaScript code on your client.

ref
  .orderBy('genre')
  .equalTo('comedy')
  .on('child_added', function(snapshot) { 
      var movie = snapshot.val();
      if (movie.lead == 'Jack Nicholson') {
          console.log(movie);
      }
  });

2. add a property that combines the values that you want to filter on

If that isn't good enough, you should consider modifying/expanding your data to allow your use-case. For example: you could stuff genre+lead into a single property that you just use for this filter.

"movie1": {
    "genre": "comedy",
    "name": "As good as it gets",
    "lead": "Jack Nicholson",
    "genre_lead": "comedy_Jack Nicholson"
}, //...

You're essentially building your own multi-column index that way and can query it with:

ref
  .orderBy('genre_lead')
  .equalTo('comedy_Jack Nicholson')
  .on('child_added', function(snapshot) { 
      var movie = snapshot.val();
      console.log(movie);
  });

David East has written a library called QueryBase that helps with generating such properties.

You could even do relative/range queries, let's say that you want to allow querying movies by category and year. You'd use this data structure:

"movie1": {
    "genre": "comedy",
    "name": "As good as it gets",
    "lead": "Jack Nicholson",
    "genre_year": "comedy_1997"
}, //...

And then query for comedies of the 90s with:

ref
  .orderBy('genre_year')
  .startAt('comedy_1990')
  .endAt('comedy_2000')
  .on('child_added', function(snapshot) { 
      var movie = snapshot.val();
      console.log(movie);
  });

If you need to filter on more than just the year, make sure to add the other date parts in descending order, e.g. "comedy_1997-12-25". This way the lexicographical ordering that Firebase does on string values will be the same as the chronological ordering.

This combining of values in a property can work with more than two values, but you can only do a range filter on the last value in the composite property.

A very special variant of this is implemented by the GeoFire library for Firebase. This library combines the latitude and longitude of a location into a so-called Geohash, which can then be used to do realtime range queries on Firebase.

3. create a custom index programmatically

Yet another alternative is to do what we've all done before this new Query API was added: create an index in a different node:

  "movies"
      // the same structure you have today
  "by_genre"
      "comedy"
          "by_lead"
              "Jack Nicholson"
                  "movie1"
              "Jim Carrey"
                  "movie3"
      "Horror"
          "by_lead"
              "Jack Nicholson"
                  "movie2"
      

There are probably more approaches. For example, this answer highlights an alternative tree-shaped custom index: https://stackoverflow.com/a/34105063


If none of these options work for you, but you still want to store your data in Firebase, you can also consider using its Cloud Firestore database.

Cloud Firestore can handle multiple equality filters in a single query, but only one range filter. Under the hood it essentially uses the same query model, but it's like it auto-generates the composite properties for you. See Firestore's documentation on compound queries.

Set iframe content height to auto resize dynamically

In the iframe: So that means you have to add some code in the iframe page. Simply add this script to your code IN THE IFRAME:

<body onload="parent.alertsize(document.body.scrollHeight);">

In the holding page: In the page holding the iframe (in my case with ID="myiframe") add a small javascript:

<script>
function alertsize(pixels){
    pixels+=32;
    document.getElementById('myiframe').style.height=pixels+"px";
}
</script>

What happens now is that when the iframe is loaded it triggers a javascript in the parent window, which in this case is the page holding the iframe.

To that JavaScript function it sends how many pixels its (iframe) height is.

The parent window takes the number, adds 32 to it to avoid scrollbars, and sets the iframe height to the new number.

That's it, nothing else is needed.


But if you like to know some more small tricks keep on reading...

DYNAMIC HEIGHT IN THE IFRAME? If you like me like to toggle content the iframe height will change (without the page reloading and triggering the onload). I usually add a very simple toggle script I found online:

<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
}
</script>

to that script just add:

<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
    parent.alertsize(document.body.scrollHeight); // ADD THIS LINE!
}
</script>

How you use the above script is easy:

<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>

For those that like to just cut and paste and go from there here is the two pages. In my case I had them in the same folder, but it should work cross domain too (I think...)

Complete holding page code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>THE IFRAME HOLDER</title>
<script>
function alertsize(pixels){
    pixels+=32;
    document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
</head>

<body style="background:silver;">
<iframe src='theiframe.htm' style='width:458px;background:white;' frameborder='0' id="myiframe" scrolling="auto"></iframe>
</body>
</html>

Complete iframe code: (this iframe named "theiframe.htm")

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>IFRAME CONTENT</title>
<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
    parent.alertsize(document.body.scrollHeight);
}
</script>
</head>

<body onload="parent.alertsize(document.body.scrollHeight);">
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
THE END

</body>
</html>

Demo

What is an MDF file?

Just to make this absolutely clear for all:

A .MDF file is “typically” a SQL Server data file however it is important to note that it does NOT have to be.

This is because .MDF is nothing more than a recommended/preferred notation but the extension itself does not actually dictate the file type.

To illustrate this, if someone wanted to create their primary data file with an extension of .gbn they could go ahead and do so without issue.

To qualify the preferred naming conventions:

  • .mdf - Primary database data file.
  • .ndf - Other database data files i.e. non Primary.
  • .ldf - Log data file.

Easy way to add drop down menu with 1 - 100 without doing 100 different options?

As everyone else has said, there isn't one in html; however, you could use PUG/Jade. In fact I do this often.

It would look something like this:

select
  - var i = 1
  while i <= 100
    option=i++

This would produce: screenshot of htmltojade.org

(.text+0x20): undefined reference to `main' and undefined reference to function

This rule

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o

is wrong. It says to create a file named producer.o (with -o producer.o), but you want to create a file named main. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o

As Shahbaz rightly points out, the gmake professionals would also use $^ which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ $^

Android runOnUiThread explanation

This should work for you

 public class MyActivity extends Activity {

    protected ProgressDialog mProgressDialog;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        populateTable();
    }

    private void populateTable() {
        mProgressDialog = ProgressDialog.show(this, "Please wait","Long operation starts...", true);
        new Thread() {
            @Override
            public void run() {

                doLongOperation();
                try {

                    // code runs in a thread
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mProgressDialog.dismiss();
                        }
                    });
                } catch (final Exception ex) {
                    Log.i("---","Exception in thread");
                }
            }
        }.start();

    }

    /** fake operation for testing purpose */
    protected void doLongOperation() {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
        }

    }
}

How to output MySQL query results in CSV format?

Also, if you're performing the query on the Bash command line, I believe the tr command can be used to substitute the default tabs to arbitrary delimiters.

$ echo "SELECT * FROM Table123" | mysql Database456 | tr "\t" ,

How to hide TabPage from TabControl

private System.Windows.Forms.TabControl _tabControl;
private System.Windows.Forms.TabPage _tabPage1;
private System.Windows.Forms.TabPage _tabPage2;

...
// Initialise the controls
...

// "hides" tab page 2
_tabControl.TabPages.Remove(_tabPage2);

// "shows" tab page 2
// if the tab control does not contain tabpage2
if (! _tabControl.TabPages.Contains(_tabPage2))
{
    _tabControl.TabPages.Add(_tabPage2);
}

PHP Checking if the current date is before or after a set date

I wanted to set a specific date so have used this to do stuff before 2nd December 2013

if(mktime(0,0,0,12,2,2013) > strtotime('now')) {
    // do stuff
}

The 0,0,0 is midnight, the 12 is the month, the 2 is the day and the 2013 is the year.

How to persist a property of type List<String> in JPA?

This answer was made pre-JPA2 implementations, if you're using JPA2, see the ElementCollection answer above:

Lists of objects inside a model object are generally considered "OneToMany" relationships with another object. However, a String is not (by itself) an allowable client of a One-to-Many relationship, as it doesn't have an ID.

So, you should convert your list of Strings to a list of Argument-class JPA objects containing an ID and a String. You could potentially use the String as the ID, which would save a little space in your table both from removing the ID field and by consolidating rows where the Strings are equal, but you would lose the ability to order the arguments back into their original order (as you didn't store any ordering information).

Alternatively, you could convert your list to @Transient and add another field (argStorage) to your class that is either a VARCHAR() or a CLOB. You'll then need to add 3 functions: 2 of them are the same and should convert your list of Strings into a single String (in argStorage) delimited in a fashion that you can easily separate them. Annotate these two functions (that each do the same thing) with @PrePersist and @PreUpdate. Finally, add the third function that splits the argStorage into the list of Strings again and annotate it @PostLoad. This will keep your CLOB updated with the strings whenever you go to store the Command, and keep the argStorage field updated before you store it to the DB.

I still suggest doing the first case. It's good practice for real relationships later.

Can we make unsigned byte in Java

The fact that primitives are signed in Java is irrelevant to how they're represented in memory / transit - a byte is merely 8 bits and whether you interpret that as a signed range or not is up to you. There is no magic flag to say "this is signed" or "this is unsigned".

As primitives are signed the Java compiler will prevent you from assigning a value higher than +127 to a byte (or lower than -128). However, there's nothing to stop you downcasting an int (or short) in order to achieve this:

int i = 200; // 0000 0000 0000 0000 0000 0000 1100 1000 (200)
byte b = (byte) 200; // 1100 1000 (-56 by Java specification, 200 by convention)

/*
 * Will print a negative int -56 because upcasting byte to int does
 * so called "sign extension" which yields those bits:
 * 1111 1111 1111 1111 1111 1111 1100 1000 (-56)
 *
 * But you could still choose to interpret this as +200.
 */
System.out.println(b); // "-56"

/*
 * Will print a positive int 200 because bitwise AND with 0xFF will
 * zero all the 24 most significant bits that:
 * a) were added during upcasting to int which took place silently
 *    just before evaluating the bitwise AND operator.
 *    So the `b & 0xFF` is equivalent with `((int) b) & 0xFF`.
 * b) were set to 1s because of "sign extension" during the upcasting
 *
 * 1111 1111 1111 1111 1111 1111 1100 1000 (the int)
 * &
 * 0000 0000 0000 0000 0000 0000 1111 1111 (the 0xFF)
 * =======================================
 * 0000 0000 0000 0000 0000 0000 1100 1000 (200)
 */
System.out.println(b & 0xFF); // "200"

/*
 * You would typically do this *within* the method that expected an 
 * unsigned byte and the advantage is you apply `0xFF` only once
 * and than you use the `unsignedByte` variable in all your bitwise
 * operations.
 *
 * You could use any integer type longer than `byte` for the `unsignedByte` variable,
 * i.e. `short`, `int`, `long` and even `char`, but during bitwise operations
 * it would get casted to `int` anyway.
 */
void printUnsignedByte(byte b) {
    int unsignedByte = b & 0xFF;
    System.out.println(unsignedByte); // "200"
}

How to pass a user / password in ansible command

When speaking with remote machines, Ansible by default assumes you are using SSH keys. SSH keys are encouraged but password authentication can also be used where needed by supplying the option --ask-pass. If using sudo features and when sudo requires a password, also supply --ask-become-pass (previously --ask-sudo-pass which has been deprecated).

Never used the feature but the docs say you can.

Sorting hashmap based on keys

Use sorted TreeMap:

Map<String, Float> map = new TreeMap<>(yourMap);

It will automatically put entries sorted by keys. I think natural String ordering will be fine in your case.

Note that HashMap due to lookup optimizations does not preserve order.

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.


Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)


Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.

ADDENDUM

I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

Excel- compare two cell from different sheet, if true copy value from other cell

In your destination field you want to use VLOOKUP like so:

=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)

VLOOKUP Arguments:

  1. The set fields you want to lookup.
  2. The table range you want to lookup up your value against. The first column of your defined table should be the column you want compared against your lookup field. The table range should also contain the value you want to display (Column F).
  3. This defines what field you want to display upon a match.
  4. FALSE tells VLOOKUP to do an exact match.

visual c++: #include files from other projects in the same solution

#include has nothing to do with projects - it just tells the preprocessor "put the contents of the header file here". If you give it a path that points to the correct location (can be a relative path, like ../your_file.h) it will be included correctly.

You will, however, have to learn about libraries (static/dynamic libraries) in order to make such projects link properly - but that's another question.

Clear text field value in JQuery

In simple way, you can use the following code to clear all the text field, textarea, dropdown, radio button, checkbox in a form.

function reset(){
    $('input[type=text]').val('');  
    $('#textarea').val(''); 
    $('input[type=select]').val('');
    $('input[type=radio]').val('');
    $('input[type=checkbox]').val('');  
}

Send form data with jquery ajax json

The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.

To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson function and add contentType: 'application/json;charset=UTF-8' to the jQuery ajax call parameters.

$.ajax({
    url: 'test.php',
    type: "POST",
    dataType: 'json',
    data: formToJson($("form")),
    contentType: 'application/json;charset=UTF-8',
    ...
})

Can I try/catch a warning?

You should probably try to get rid of the warning completely, but if that's not possible, you can prepend the call with @ (i.e. @dns_get_record(...)) and then use any information you can get to figure out if the warning happened or not.

Single TextView with multiple colored text

Using Kotlin and Extensions you can add colored text really easy and clean:

Create a file TextViewExtensions.kt with this content

fun TextView.append(string: String?, @ColorRes color: Int) {
    if (string == null || string.isEmpty()) {
        return
    }

    val spannable: Spannable = SpannableString(string)
    spannable.setSpan(
        ForegroundColorSpan(ContextCompat.getColor(context, color)),
        0,
        spannable.length,
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
    )

    append(spannable)
}

Now is really easy to append text with color

textView.text = "" // Remove old text
textView.append("Red Text", R.color.colorAccent)
textView.append("White Text", android.R.color.white)

Basically is same as @Abdul Rizwan answer but using Kotlin, extensions, some validations and getting color inside extension.

Convert byte[] to char[]

System.Text.Encoding.ChooseYourEncoding.GetString(bytes).ToCharArray();

Substitute the right encoding above: e.g.

System.Text.Encoding.UTF8.GetString(bytes).ToCharArray();

How do I convert strings in a Pandas data frame to a 'date' data type?

Use astype

In [31]: df
Out[31]: 
   a        time
0  1  2013-01-01
1  2  2013-01-02
2  3  2013-01-03

In [32]: df['time'] = df['time'].astype('datetime64[ns]')

In [33]: df
Out[33]: 
   a                time
0  1 2013-01-01 00:00:00
1  2 2013-01-02 00:00:00
2  3 2013-01-03 00:00:00

Getting activity from context in android

This is something that I have used successfully to convert Context to Activity when operating within the UI in fragments or custom views. It will unpack ContextWrapper recursively or return null if it fails.

public Activity getActivity(Context context)
{
    if (context == null)
    {
        return null;
    }
    else if (context instanceof ContextWrapper)
    {
        if (context instanceof Activity)
        {
            return (Activity) context;
        }
        else
        {
            return getActivity(((ContextWrapper) context).getBaseContext());
        }
    }

    return null;
}

Adding +1 to a variable inside a function

Move points into test:

def test():
    points = 0
    addpoint = raw_input ("type ""add"" to add a point")
    ...

or use global statement, but it is bad practice. But better way it move points to parameters:

def test(points=0):
    addpoint = raw_input ("type ""add"" to add a point")
    ...

How to check if an environment variable exists and get its value?

NEW_VAR=""
if [[ ${ENV_VAR} && ${ENV_VAR-x} ]]; then
  NEW_VAR=${ENV_VAR}
else
  NEW_VAR="new value"
fi

What does %s mean in a python format string?

In answer to your second question: What does this code do?...

This is fairly standard error-checking code for a Python script that accepts command-line arguments.

So the first if statement translates to: if you haven't passed me an argument, I'm going to tell you how you should pass me an argument in the future, e.g. you'll see this on-screen:

Usage: myscript.py database-name

The next if statement checks to see if the 'database-name' you passed to the script actually exists on the filesystem. If not, you'll get a message like this:

ERROR: Database database-name was not found!

From the documentation:

argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.

Running unittest with typical test directory structure

The simplest solution for your users is to provide an executable script (runtests.py or some such) which bootstraps the necessary test environment, including, if needed, adding your root project directory to sys.path temporarily. This doesn't require users to set environment variables, something like this works fine in a bootstrap script:

import sys, os

sys.path.insert(0, os.path.dirname(__file__))

Then your instructions to your users can be as simple as "python runtests.py".

Of course, if the path you need really is os.path.dirname(__file__), then you don't need to add it to sys.path at all; Python always puts the directory of the currently running script at the beginning of sys.path, so depending on your directory structure, just locating your runtests.py at the right place might be all that's needed.

Also, the unittest module in Python 2.7+ (which is backported as unittest2 for Python 2.6 and earlier) now has test discovery built-in, so nose is no longer necessary if you want automated test discovery: your user instructions can be as simple as python -m unittest discover.

Could not reserve enough space for object heap to start JVM

It looks like the machine you're trying to run this on has only 256 MB memory.

Maybe the JVM tries to allocate a large, contiguous block of 64 MB memory. The 192 MB that you have free might be fragmented into smaller pieces, so that there is no contiguous block of 64 MB free to allocate.

Try starting your Java program with a smaller heap size, for example:

java -Xms16m ...

comparing 2 strings alphabetically for sorting purposes

Lets say that we have an array of objects:

{ name : String }

then we can sort our array as follows:

array.sort(function(a, b) {
    var orderBool = a.name > b.name;
    return orderBool ? 1 : -1;
});

Note: Be careful for upper letters, you may need to cast your string to lower case due to your purpose.

Are there dictionaries in php?

http://php.net/manual/en/language.types.array.php

<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];
?>

Standard arrays can be used that way.

input() error - NameError: name '...' is not defined

We are using the following that works both python 2 and python 3

#Works in Python 2 and 3:
try: input = raw_input
except NameError: pass
print(input("Enter your name: "))

Align the form to the center in Bootstrap 4

You need to use the various Bootstrap 4 centering methods...

  • Use text-center for inline elements.
  • Use justify-content-center for flexbox elements (ie; form-inline)

https://codeply.com/go/Am5LvvjTxC

Also, to offset the column, the col-sm-* must be contained within a .row, and the .row must be in a container...

<section id="cover">
    <div id="cover-caption">
        <div id="container" class="container">
            <div class="row">
                <div class="col-sm-10 offset-sm-1 text-center">
                    <h1 class="display-3">Welcome to Bootstrap 4</h1>
                    <div class="info-form">
                        <form action="" class="form-inline justify-content-center">
                            <div class="form-group">
                                <label class="sr-only">Name</label>
                                <input type="text" class="form-control" placeholder="Jane Doe">
                            </div>
                            <div class="form-group">
                                <label class="sr-only">Email</label>
                                <input type="text" class="form-control" placeholder="[email protected]">
                            </div>
                            <button type="submit" class="btn btn-success ">okay, go!</button>
                        </form>
                    </div>
                    <br>

                    <a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">?</a>
                </div>
            </div>
        </div>
    </div>
</section>

Extract MSI from EXE

The only way to do that is running the exe and collect the MSI. The thing you must take care of is that if you are tranforming the MSI using MST they might get lost.

I use this batch commandline:

SET TMP=c:\msipath

MD "%TMP%"

SET TEMP=%TMP%

start /d "c:\install" install.exe /L1033

PING 1.1.1.1 -n 1 -w 10000 >NUL

for /R "%TMP%" %%f in (*.msi) do copy "%%f" "%TMP%"

taskkill /F /IM msiexec.exe /T

How do I use CMake?

CMake (Cross platform make) is a build system generator. It doesn't build your source, instead, generates what a build system needs: the build scripts. Doing so you don't need to write or maintain platform specific build files. CMake uses relatively high level CMake language which usually written in CMakeLists.txt files. Your general workflow when consuming third party libraries usually boils down the following commands:

cmake -S thelibrary -B build
cmake --build build
cmake --install build

The first line known as configuration step, this generates the build files on your system. -S(ource) is the library source, and -B(uild) folder. CMake falls back to generate build according to your system. it will be MSBuild on Windows, GNU Makefiles on Linux. You can specify the build using -G(enerator) paramater, like:

cmake -G Ninja -S libSource -B build

end of the this step, generates build scripts, like Makefile, *.sln files etc. on build directory.

The second line invokes the actual build command, it's like invoking make on the build folder.

The third line install the library. If you're on Windows, you can quickly open generated project by, cmake --open build.

Now you can use the installed library on your project with configured by CMake, writing your own CMakeLists.txt file. To do so, you'll need to create a your target and find the package you installed using find_package command, which will export the library target names, and link them against your own target.

How to validate Google reCAPTCHA v3 on server side?

this is solution

index.html

<html>
  <head>
    <title>Google recapcha demo - Codeforgeek</title>
    <script src='https://www.google.com/recaptcha/api.js'></script>
  </head>
  <body>
    <h1>Google reCAPTHA Demo</h1>
    <form id="comment_form" action="form.php" method="post">
      <input type="email" placeholder="Type your email" size="40"><br><br>
      <textarea name="comment" rows="8" cols="39"></textarea><br><br>
      <input type="submit" name="submit" value="Post comment"><br><br>
      <div class="g-recaptcha" data-sitekey="=== Your site key ==="></div>
    </form>
  </body>
</html>

verify.php

<?php
    $email; $comment; $captcha;

    if(isset($_POST['email']))
        $email=$_POST['email'];
    if(isset($_POST['comment']))
        $comment=$_POST['comment'];
    if(isset($_POST['g-recaptcha-response']))
        $captcha=$_POST['g-recaptcha-response'];

    if(!$captcha){
        echo '<h2>Please check the the captcha form.</h2>';
        exit;
    }

    $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRET KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
    if($response['success'] == false)
    {
        echo '<h2>You are spammer ! Get the @$%K out</h2>';
    }
    else
    {
        echo '<h2>Thanks for posting comment.</h2>';
    }
?>

http://codeforgeek.com/2014/12/google-recaptcha-tutorial/

Twitter bootstrap modal-backdrop doesn't disappear

I just spent way too long on this problem :)

While the other answers provided are helpful and valid, it seemed a little messy to me to effectively recreate the modal hiding functionality from Bootstrap, so I found a cleaner solution.

The problem is that there are a chain of events that happen when you call

$("#myModal").modal('hide');
functionThatEndsUpDestroyingTheDOM()

When you then replace a bunch of HTML as the result of the AJAX request, the modal-hiding events don't finish. However, Bootstrap triggers an event when everything is finished, and you can hook into that like so:

$("#myModal").modal('hide').on('hidden.bs.modal', functionThatEndsUpDestroyingTheDOM);

Hope this is helpful!

Java: method to get position of a match in a String?

import java.util.StringTokenizer;

public class Occourence {

  public static void main(String[] args) {
    String key=null,str ="my name noorus my name noorus";        
    int i=0,tot=0;

    StringTokenizer st=new StringTokenizer(str," ");
    while(st.hasMoreTokens())
    {   
        tot=tot+1;
        key = st.nextToken();
        while((i=(str.indexOf(key,i)+1))>0)
        {
            System.out.println("position of "+key+" "+"is "+(i-1));
        }
    }

    System.out.println("total words present in string "+tot);
  }
}

How do I list all loaded assemblies?

Here's what I ended up with. It's a listing of all properties and methods, and I listed all parameters for each method. I didn't succeed on getting all of the values.

foreach(System.Reflection.AssemblyName an in System.Reflection.Assembly.GetExecutingAssembly().GetReferencedAssemblies()){                      
            System.Reflection.Assembly asm = System.Reflection.Assembly.Load(an.ToString());
            foreach(Type type in asm.GetTypes()){   
                //PROPERTIES
                foreach (System.Reflection.PropertyInfo property in type.GetProperties()){
                    if (property.CanRead){
                        Response.Write("<br>" + an.ToString() + "." + type.ToString() + "." + property.Name);       
                    }
                }
                //METHODS
                var methods = type.GetMethods();
                foreach (System.Reflection.MethodInfo method in methods){               
                    Response.Write("<br><b>" + an.ToString() + "."  + type.ToString() + "." + method.Name  + "</b>");   
                    foreach (System.Reflection.ParameterInfo param in method.GetParameters())
                    {
                        Response.Write("<br><i>Param=" + param.Name.ToString());
                        Response.Write("<br>  Type=" + param.ParameterType.ToString());
                        Response.Write("<br>  Position=" + param.Position.ToString());
                        Response.Write("<br>  Optional=" + param.IsOptional.ToString() + "</i>");
                    }
                }
            }
        }

Navigate to another page with a button in angular 2

You can use routerLink in the following manner,

<input type="button" value="Add Bulk Enquiry" [routerLink]="['../addBulkEnquiry']" class="btn">

or use <button [routerLink]="['./url']"> in your case, for more info you could read the entire stacktrace on github https://github.com/angular/angular/issues/9471

the other methods are also correct but they create a dependency on the component file.

Hope your concern is resolved.

Difference between Apache CXF and Axis

Another advantage of CXF: it connects to web servers using NTLMV2 authentication out of the box. (used by Windows 2008 & up) Before using CXF, I hacked Axis2 to use HTTPClient V4 + JCIFS to make this possible.

How can I round down a number in Javascript?

Here is math.floor being used in a simple example. This might help a new developer to get an idea how to use it in a function and what it does. Hope it helps!

<script>

var marks = 0;

function getRandomNumbers(){    //  generate a random number between 1 & 10
    var number = Math.floor((Math.random() * 10) + 1);
    return number;
}

function getNew(){  
/*  
    This function can create a new problem by generating two random numbers. When the page is loading as the first time, this function is executed with the onload event and the onclick event of "new" button.
*/
document.getElementById("ans").focus();
var num1 = getRandomNumbers();
var num2 = getRandomNumbers();
document.getElementById("num1").value = num1;
document.getElementById("num2").value = num2;

document.getElementById("ans").value ="";
document.getElementById("resultBox").style.backgroundColor = "maroon"
document.getElementById("resultBox").innerHTML = "***"

}

function checkAns(){
/*
    After entering the answer, the entered answer will be compared with the correct answer. 
        If the answer is correct, the text of the result box should be "Correct" with a green background and 10 marks should be added to the total marks.
        If the answer is incorrect, the text of the result box should be "Incorrect" with a red background and 3 marks should be deducted from the total.
        The updated total marks should be always displayed at the total marks box.
*/

var num1 = eval(document.getElementById("num1").value);
var num2 = eval(document.getElementById("num2").value);
var answer = eval(document.getElementById("ans").value);

if(answer==(num1+num2)){
    marks = marks + 10;
    document.getElementById("resultBox").innerHTML = "Correct";
    document.getElementById("resultBox").style.backgroundColor = "green";
    document.getElementById("totalMarks").innerHTML= "Total marks : " + marks;

}

else{
    marks = marks - 3;
    document.getElementById("resultBox").innerHTML = "Wrong";
    document.getElementById("resultBox").style.backgroundColor = "red";
    document.getElementById("totalMarks").innerHTML = "Total Marks: " + marks ;
}




}

</script>
</head>

<body onLoad="getNew()">
    <div class="container">
        <h1>Let's add numbers</h1>
        <div class="sum">
            <input id="num1" type="text" readonly> + <input id="num2" type="text" readonly>
        </div>
        <h2>Enter the answer below and click 'Check'</h2>
        <div class="answer">
            <input id="ans" type="text" value="">
        </div>
        <input id="btnchk" onClick="checkAns()" type="button" value="Check" >
        <div id="resultBox">***</div>
        <input id="btnnew" onClick="getNew()" type="button" value="New">
        <div id="totalMarks">Total marks : 0</div>  
    </div>
</body>
</html>

LINQ orderby on date field in descending order

I was trying to also sort by a DateTime field descending and this seems to do the trick:

var ud = (from d in env 
     orderby -d.ReportDate.Ticks                 
     select  d.ReportDate.ToString("yyyy-MMM") ).Distinct(); 

How do we count rows using older versions of Hibernate (~2009)?

Here is what official hibernate docs tell us about this:

You can count the number of query results without returning them:

( (Integer) session.createQuery("select count(*) from ....").iterate().next() ).intValue()

However, it doesn't always return Integer instance, so it is better to use java.lang.Number for safety.

How to replace substrings in windows batch file

Expanding from Andriy M, and yes you can do this from a file, even one with multiple lines

@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "INTEXTFILE=test.txt"
set "OUTTEXTFILE=test_out.txt"
set "SEARCHTEXT=bath"
set "REPLACETEXT=hello"

for /f "delims=" %%A in ('type "%INTEXTFILE%"') do (
    set "string=%%A"
    set "modified=!string:%SEARCHTEXT%=%REPLACETEXT%!"
    echo !modified!>>"%OUTTEXTFILE%"
)

del "%INTEXTFILE%"
rename "%OUTTEXTFILE%" "%INTEXTFILE%"
endlocal

EDIT

Thanks David Nelson, I have updated the script so it doesn't have the hard coded values anymore.

Using Bootstrap Tooltip with AngularJS

If you're building an Angular app, you can use jQuery, but there is a lot of good reasons to try to avoid it in favor of more angular driven paradigms. You can continue to use the styles provided by bootstrap, but replace the jQuery plugins with native angular by using UI Bootstrap

Include the Boostrap CSS files, Angular.js, and ui.Bootstrap.js:

<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.angularjs.org/1.2.20/angular.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.0.js"></script>

Make sure you've injected ui.bootstrap when you create your module like this:

var app = angular.module('plunker', ['ui.bootstrap']);

Then you can use angular directives instead of data attributes picked up by jQuery:

<button type="button" class="btn btn-default" 
        title="Tooltip on left" data-toggle="tooltip" data-placement="left"
        tooltip="Tooltip on left" tooltip-placement="left" >
  Tooltip on left
</button>

Demo in Plunker


Avoiding UI Bootstrap

jQuery.min.js (94kb) + Bootstrap.min.js (32kb) is also giving you more than you need, and much more than ui-bootstrap.min.js (41kb).

And time spent downloading the modules is only one aspect of performance.

If you really wanted to only load the modules you needed, you can "Create a Build" and choose tooltips from the Bootstrap-UI website. Or you can explore the source code for tooltips and pick out what you need.

Here a minified custom build with just the tooltips and templates (6kb)

Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

tl;dr: No! Arrow functions and function declarations / expressions are not equivalent and cannot be replaced blindly.
If the function you want to replace does not use this, arguments and is not called with new, then yes.


As so often: it depends. Arrow functions have different behavior than function declarations / expressions, so let's have a look at the differences first:

1. Lexical this and arguments

Arrow functions don't have their own this or arguments binding. Instead, those identifiers are resolved in the lexical scope like any other variable. That means that inside an arrow function, this and arguments refer to the values of this and arguments in the environment the arrow function is defined in (i.e. "outside" the arrow function):

_x000D_
_x000D_
// Example using a function expression
function createObject() {
  console.log('Inside `createObject`:', this.foo);
  return {
    foo: 42,
    bar: function() {
      console.log('Inside `bar`:', this.foo);
    },
  };
}

createObject.call({foo: 21}).bar(); // override `this` inside createObject
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
// Example using a arrow function
function createObject() {
  console.log('Inside `createObject`:', this.foo);
  return {
    foo: 42,
    bar: () => console.log('Inside `bar`:', this.foo),
  };
}

createObject.call({foo: 21}).bar(); // override `this` inside createObject
_x000D_
_x000D_
_x000D_

In the function expression case, this refers to the object that was created inside the createObject. In the arrow function case, this refers to this of createObject itself.

This makes arrow functions useful if you need to access the this of the current environment:

// currently common pattern
var that = this;
getData(function(data) {
  that.data = data;
});

// better alternative with arrow functions
getData(data => {
  this.data = data;
});

Note that this also means that is not possible to set an arrow function's this with .bind or .call.

If you are not very familiar with this, consider reading

2. Arrow functions cannot be called with new

ES2015 distinguishes between functions that are callable and functions that are constructable. If a function is constructable, it can be called with new, i.e. new User(). If a function is callable, it can be called without new (i.e. normal function call).

Functions created through function declarations / expressions are both constructable and callable.
Arrow functions (and methods) are only callable. class constructors are only constructable.

If you are trying to call a non-callable function or to construct a non-constructable function, you will get a runtime error.


Knowing this, we can state the following.

Replaceable:

  • Functions that don't use this or arguments.
  • Functions that are used with .bind(this)

Not replaceable:

  • Constructor functions
  • Function / methods added to a prototype (because they usually use this)
  • Variadic functions (if they use arguments (see below))

Lets have a closer look at this using your examples:

Constructor function

This won't work because arrow functions cannot be called with new. Keep using a function declaration / expression or use class.

Prototype methods

Most likely not, because prototype methods usually use this to access the instance. If they don't use this, then you can replace it. However, if you primarily care for concise syntax, use class with its concise method syntax:

class User {
  constructor(name) {
    this.name = name;
  }
  
  getName() {
    return this.name;
  }
}

Object methods

Similarly for methods in an object literal. If the method wants to reference the object itself via this, keep using function expressions, or use the new method syntax:

const obj = {
  getName() {
    // ...
  },
};

Callbacks

It depends. You should definitely replace it if you are aliasing the outer this or are using .bind(this):

// old
setTimeout(function() {
  // ...
}.bind(this), 500);

// new
setTimeout(() => {
  // ...
}, 500);

But: If the code which calls the callback explicitly sets this to a specific value, as is often the case with event handlers, especially with jQuery, and the callback uses this (or arguments), you cannot use an arrow function!

Variadic functions

Since arrow functions don't have their own arguments, you cannot simply replace them with an arrow function. However, ES2015 introduces an alternative to using arguments: the rest parameter.

// old
function sum() {
  let args = [].slice.call(arguments);
  // ...
}

// new
const sum = (...args) => {
  // ...
};

Related question:

Further resources:

Tooltip with HTML content without JavaScript

Another similar way to do it by css:

_x000D_
_x000D_
#img {  }_x000D_
#img:hover {visibility:hidden}_x000D_
#thistext {font-size:22px;color:white }_x000D_
#thistext:hover {color:black;}_x000D_
#hoverme {width:50px;height:50px;}_x000D_
_x000D_
#hoverme:hover { _x000D_
background-color:green;_x000D_
position:absolute ;_x000D_
left:300px;_x000D_
top:100px;_x000D_
width:40%;_x000D_
height:20%;_x000D_
}
_x000D_
<p id="hoverme"><img id="img" src="http://a.deviantart.net/avatars/l/o/lol-cat.jpg"></img><span id="thistext">LOCATZ!!!!</span></p>
_x000D_
_x000D_
_x000D_

Try it: http://jsfiddle.net/FdBu7/

And here is some links about transitions and new ways to do it: http://www.w3schools.com/css3/css3_transitions.asp http://dev.opera.com/articles/view/css3-show-and-hide/

Start index for iterating Python list

If all you want is to print from Monday onwards, you can use list's index method to find the position where "Monday" is in the list, and iterate from there as explained in other posts. Using list.index saves you hard-coding the index for "Monday", which is a potential source of error:

days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
for d in days[days.index('Monday'):] :
   print d

Errors: Data path ".builders['app-shell']" should have required property 'class'

I was also coming across this issue and for me when doing more updates more issues occurred.

What worked for me in the end was more or less to remove angular cli and re install it with these steps:

npm uninstall -g @angular/cli
npm cache clean --force
npm install -g @angular/cli

this helped me out source: how to uninstall angular/cli

Parsing XML in Python using ElementTree example

So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:

import elementtree.ElementTree as ET

tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')

print thingy.attrib

and got the following back:

{'name': 'NWIS Time Series Instantaneous Values'}

It appears to have found the timeSeries element without needing to use numerical indices.

What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.

java.lang.ClassCastException

To avoid x !instance of Long prob Add

<property name="openjpa.Compatibility" value="StrictIdentityValues=false"/>

in your persistence.xml

decimal vs double! - Which one should I use and when?

Definitely use integer types for your money computations.
This cannot be emphasized enough since at first glance it might seem that a floating point type is adequate.

Here an example in python code:

>>> amount = float(100.00) # one hundred dollars
>>> print amount
100.0
>>> new_amount = amount + 1
>>> print new_amount
101.0
>>> print new_amount - amount
>>> 1.0

looks pretty normal.

Now try this again with 10^20 Zimbabwe dollars:

>>> amount = float(1e20)
>>> print amount
1e+20
>>> new_amount = amount + 1
>>> print new_amount
1e+20
>>> print new_amount-amount
0.0

As you can see, the dollar disappeared.

If you use the integer type, it works fine:

>>> amount = int(1e20)
>>> print amount
100000000000000000000
>>> new_amount = amount + 1
>>> print new_amount
100000000000000000001
>>> print new_amount - amount
1

How to get ip address of a server on Centos 7 in bash

Enter the command ip addr at the console

enter image description here

Cannot find "Package Explorer" view in Eclipse

Try this

Window > Show View > Package Explorer

it will display the hidden 'Package Explorer' on your eclipse IDE.

• 'Window' is in your Eclipse' menubar.

Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused

Run the following command :

sudo rm /var/lib/mongodb/mongod.lock
sudo service mongod restart

Connection refused to MongoDB errno 111

MacOS:

rm /usr/local/var/mongodb/mongod.lock  
sudo service mongod restart

How can I commit files with git?

I don't know your system environment, but it seems, that you have typed:

git commit

And your default editor has been launched. In the worst case scenario (for you) it could have been vim :)

If you don't know how to quit vim, use :q.

If you have further problems, you could use

git commit -m 'Type your commit message here'

Use of exit() function

Write header file #include<process.h> and replace exit(); with exit(0);. This will definitely work in Turbo C; for other compilers I don't know.

JPA: unidirectional many-to-one and cascading delete

Create a bi-directional relationship, like this:

@Entity
public class Parent implements Serializable {

    @Id
    @GeneratedValue
    private long id;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE)
    private Set<Child> children;
}

Convert International String to \u Codes in java

There's a command-line tool that ships with java called native2ascii. This converts unicode files to ASCII-escaped files. I've found that this is a necessary step for generating .properties files for localization.

JavaFX FXML controller - constructor vs initialize method

In Addition to the above answers, there probably should be noted that there is a legacy way to implement the initialization. There is an interface called Initializable from the fxml library.

import javafx.fxml.Initializable;

class MyController implements Initializable {
    @FXML private TableView<MyModel> tableView;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        tableView.getItems().addAll(getDataFromSource());
    }
}

Parameters:

location - The location used to resolve relative paths for the root object, or null if the location is not known.
resources - The resources used to localize the root object, or null if the root object was not localized. 

And the note of the docs why the simple way of using @FXML public void initialize() works:

NOTE This interface has been superseded by automatic injection of location and resources properties into the controller. FXMLLoader will now automatically call any suitably annotated no-arg initialize() method defined by the controller. It is recommended that the injection approach be used whenever possible.

How is AngularJS different from jQuery

I think this is a very good chart describing the differences in short. A quick glance at it shows most of the differences.

enter image description here

One thing I would like to add is that, AngularJS can be made to follow the MVVM design pattern while jQuery does not follow any of the standard Object Oriented patterns.

Enabling the OpenSSL in XAMPP

Yes, you must open php.ini and remove the semicolon to:

;extension=php_openssl.dll

If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext) and add this to php.ini in the "Dynamic Extensions" section:

extension=php_openssl.dll

Things have changed for PHP > 7. This is what i had to do for PHP 7.2.

Step: 1: Uncomment extension=openssl

Step: 2: Uncomment extension_dir = "ext"

Step: 3: Restart xampp.

Done.

Explanation: ( From php.ini )

If you wish to have an extension loaded automatically, use the following syntax:

extension=modulename

Note : The syntax used in previous PHP versions (extension=<ext>.so and extension='php_<ext>.dll) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>) syntax.

Special Note: Be sure to appropriately set the extension_dir directive.

How to find the Number of CPU Cores via .NET/C#?

From .NET Framework source

You can also get it with PInvoke on Kernel32.dll

The following code is coming more or less from SystemInfo.cs from System.Web source located here:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct SYSTEM_INFO
{
  public ushort wProcessorArchitecture;
  public ushort wReserved;
  public uint dwPageSize;
  public IntPtr lpMinimumApplicationAddress;
  public IntPtr lpMaximumApplicationAddress;
  public IntPtr dwActiveProcessorMask;
  public uint dwNumberOfProcessors;
  public uint dwProcessorType;
  public uint dwAllocationGranularity;
  public ushort wProcessorLevel;
  public ushort wProcessorRevision;
}

internal static class SystemInfo 
{
    static int _trueNumberOfProcessors;
    internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);    

    [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
    internal static extern void GetSystemInfo(out SYSTEM_INFO si);

    [DllImport("kernel32.dll")]
    internal static extern int GetProcessAffinityMask(IntPtr handle, out IntPtr processAffinityMask, out IntPtr systemAffinityMask);

    internal static int GetNumProcessCPUs()
    {
      if (SystemInfo._trueNumberOfProcessors == 0)
      {
        SYSTEM_INFO si;
        GetSystemInfo(out si);
        if ((int) si.dwNumberOfProcessors == 1)
        {
          SystemInfo._trueNumberOfProcessors = 1;
        }
        else
        {
          IntPtr processAffinityMask;
          IntPtr systemAffinityMask;
          if (GetProcessAffinityMask(INVALID_HANDLE_VALUE, out processAffinityMask, out systemAffinityMask) == 0)
          {
            SystemInfo._trueNumberOfProcessors = 1;
          }
          else
          {
            int num1 = 0;
            if (IntPtr.Size == 4)
            {
              uint num2 = (uint) (int) processAffinityMask;
              while ((int) num2 != 0)
              {
                if (((int) num2 & 1) == 1)
                  ++num1;
                num2 >>= 1;
              }
            }
            else
            {
              ulong num2 = (ulong) (long) processAffinityMask;
              while ((long) num2 != 0L)
              {
                if (((long) num2 & 1L) == 1L)
                  ++num1;
                num2 >>= 1;
              }
            }
            SystemInfo._trueNumberOfProcessors = num1;
          }
        }
      }
      return SystemInfo._trueNumberOfProcessors;
    }
}

Border Radius of Table is not working

<div class="leads-search-table">
                    <div class="row col-md-6 col-md-offset-2 custyle">
                    <table class="table custab bordered">
                    <thead>

                        <tr>
                            <th>ID</th>
                            <th>Title</th>
                            <th>Parent ID</th>
                            <th class="text-center">Action</th>
                        </tr>
                    </thead>
                            <tr>
                                <td>1</td>
                                <td>News</td>
                                <td>News Cate</td>
                                <td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
                            </tr>
                            <tr>
                                <td>2</td>
                                <td>Products</td>
                                <td>Main Products</td>
                                <td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
                            </tr>
                            <tr>
                                <td>3</td>
                                <td>Blogs</td>
                                <td>Parent Blogs</td>
                                <td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
                            </tr>
                    </table>
                    </div>
                </div>

Css

.custab{
    border: 1px solid #ccc;
    margin: 5% 0;
    transition: 0.5s;
    background-color: #fff;
    -webkit-border-radius:4px;
    border-radius: 4px;
    border-collapse: separate;
}

Why is JavaFX is not included in OpenJDK 8 on Ubuntu Wily (15.10)?

According to the packages list in Ubuntu Wily Xenial Bionic there is a package named openjfx. This should be a candidate for what you're looking for:

JavaFX/OpenJFX 8 - Rich client application platform for Java

You can install it via:

sudo apt-get install openjfx

It provides the following JAR files to the OpenJDK installation on Ubuntu systems:

/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/jfxrt.jar
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/jfxswt.jar
/usr/lib/jvm/java-8-openjdk-amd64/lib/ant-javafx.jar
/usr/lib/jvm/java-8-openjdk-amd64/lib/javafx-mx.jar

If you want to have sources available, for example for debugging, you can additionally install:

sudo apt-get install openjfx-source

Draw in Canvas by finger, Android

tutorial to draw line use Bitmap, Canvas, and Paint class. draw-line-on-finger-touch and androiddraw

here one simple class to draw line using canvas as show below.

    public class TestLineView extends View {

    private Paint paint;
    private PointF startPoint, endPoint;
    private boolean isDrawing;

    public TestLineView(Context context)
    {
        super(context);
        init();
    }

    private void init()
    {
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStyle(Style.STROKE);
        paint.setStrokeWidth(2);
        paint.setAntiAlias(true);
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        if(isDrawing)
        {
            canvas.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y, paint);
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                startPoint = new PointF(event.getX(), event.getY());
                endPoint = new PointF();
                isDrawing = true;
                break;
            case MotionEvent.ACTION_MOVE:
                if(isDrawing)
                {
                    endPoint.x = event.getX();
                    endPoint.y = event.getY();
                    invalidate();
                }
                break;
            case MotionEvent.ACTION_UP:
                if(isDrawing)
                {
                    endPoint.x = event.getX();
                    endPoint.y = event.getY();
                    isDrawing = false;
                    invalidate();
                }
                break;
            default:
                break;
        }
        return true;
    }
}

The response content cannot be parsed because the Internet Explorer engine is not available, or

In your invoke web request just use the parameter -UseBasicParsing

e.g. in your script (line 2) you should use:

$rss = Invoke-WebRequest -UseBasicParsing

According to the documentation, this parameter is necessary on systems where IE isn't installed or configured.

Uses the response object for HTML content without Document Object Model (DOM) parsing. This parameter is required when Internet Explorer is not installed on the computers, such as on a Server Core installation of a Windows Server operating system.

nginx - read custom header from upstream server

Use $http_MY_CUSTOM_HEADER

You can write some-thing like

set my_header $http_MY_CUSTOM_HEADER;
if($my_header != 'some-value') {
#do some thing;
}

How to change dataframe column names in pyspark?

I use this one:

from pyspark.sql.functions import col
df.select(['vin',col('timeStamp').alias('Date')]).show()

Remove pattern from string with gsub

The following code works on your example :

gsub(".*_", "", a)

Static variables in C++

A static variable declared in a header file outside of the class would be file-scoped in every .c file which includes the header. That means separate copy of a variable with same name is accessible in each of the .c files where you include the header file.

A static class variable on the other hand is class-scoped and the same static variable is available to every compilation unit that includes the header containing the class with static variable.

<input type="file"> limit selectable files by extensions

NOTE: This answer is from 2011. It was a really good answer back then, but as of 2015, native HTML properties are supported by most browsers, so there's (usually) no need to implement such custom logic in JS. See Edi's answer and the docs.


Before the file is uploaded, you can check the file's extension using Javascript, and prevent the form being submitted if it doesn't match. The name of the file to be uploaded is stored in the "value" field of the form element.

Here's a simple example that only allows files that end in ".gif" to be uploaded:

<script type="text/javascript">
    function checkFile() {
        var fileElement = document.getElementById("uploadFile");
        var fileExtension = "";
        if (fileElement.value.lastIndexOf(".") > 0) {
            fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
        }
        if (fileExtension.toLowerCase() == "gif") {
            return true;
        }
        else {
            alert("You must select a GIF file for upload");
            return false;
        }
    }
</script>

<form action="upload.aspx" enctype="multipart/form-data" onsubmit="return checkFile();">
    <input name="uploadFile" id="uploadFile" type="file" />

    <input type="submit" />
</form>

However, this method is not foolproof. Sean Haddy is correct that you always want to check on the server side, because users can defeat your Javascript checking by turning off javascript, or editing your code after it arrives in their browser. Definitely check server-side in addition to the client-side check. Also I recommend checking for size server-side too, so that users don't crash your server with a 2 GB file (there's no way that I know of to check file size on the client side without using Flash or a Java applet or something).

However, checking client side before hand using the method I've given here is still useful, because it can prevent mistakes and is a minor deterrent to non-serious mischief.

Get a random boolean in python?

You could use the Faker library, it's mainly used for testing, but is capable of providing a variety of fake data.

Install: https://pypi.org/project/Faker/

>>> from faker import Faker
>>> fake = Faker()
>>> fake.pybool()
True

web.xml is missing and <failOnMissingWebXml> is set to true

If you already have web.xml under /src/main/webapp/WEB-INF but you still get error "web.xml is missing and is set to true", you could check if you have included /src/main/webapp in your project source.

Here are the steps you can follow:

  1. You can check this by right clicking your project, and open its Properties dialogue, and then "Deployment Assembly", where you can add Folder /src/main/webapp. Save the setting, and then,
  2. Go to Eclipse menu Project -> Clean... and clean the project, and the error should go away.

(I verified this with Eclipse Mars)

clear javascript console in Google Chrome

I think this is no longer available due to 'security issues'.

console.log(console) from code gives:

Console
memory: MemoryInfo
profiles: Array[0]
__proto__: Console

From outside of code, _commandLineAPI is available. Kind of annoying because sometimes I want to just log and not see the old output.

JFrame: How to disable window resizing?

Just in case somebody didn't understand the 6th time around:

setResizable(false);

Android Dialog: Removing title bar

if you are using a custom view then remeber to request window feature before adding content view like this

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(view);
dialog.show();

How do I get the max and min values from a set of numbers entered?

here you need to skip int 0 like following:

val = s.nextInt();
  if ((val < min) && (val!=0)) {
      min = val;
  }

Font size relative to the user's screen resolution?

<script>
function getFontsByScreenWidth(actuallFontSize, maxScreenWidth){
     return (actualFontSize / maxScreenWidth) * window.innerWidth;
}

// Example:
fontSize = 18;
maxScreenWidth = 1080;
fontSize = getFontsByScreenWidth(fontSize, maxScreenWidth)

</script>

I hope this will help. I am using this formula for my Phase game.

Bootstrap 3 Glyphicons are not working

In my case I was getting a 404 for glyphicons-halflings-regular.woff, and non visible glyphicons on mobile browsers.

Looks like there is some confusion about the MIME type for woff, more than one MIME type being accepted by different browsers, but the W3C says:

application/font-woff

Edit: After testing the following MIME type for woff works on all browsers currently:

application/x-font-woff

Edit: Latest version of Bootstrap at this time (3.3.5) uses .woff2 fonts with the same initial result as .woff, the W3C still defining the spec but at the moment the MIME type seems to be:

application/font-woff2

ReferenceError: event is not defined error in Firefox

It is because you forgot to pass in event into the click function:

$('.menuOption').on('click', function (e) { // <-- the "e" for event

    e.preventDefault(); // now it'll work

    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();
});

On a side note, e is more commonly used as opposed to the word event since Event is a global variable in most browsers.

How do I open a second window from the first window in WPF?

Write your code in window1.

private void Button_Click(object sender, RoutedEventArgs e)
{
    window2 win2 = new window2();
    win2.Show();
}

Simple way to copy or clone a DataRow?

But to make sure that your new row is accessible in the new table, you need to close the table:

DataTable destination = new DataTable(source.TableName);
destination = source.Clone();
DataRow sourceRow = source.Rows[0];
destination.ImportRow(sourceRow);

AngularJS: How to run additional code after AngularJS has rendered a template?

In some scenarios where you update a service and redirect to a new view(page) and then your directive gets loaded before your services are updated then you can use $rootScope.$broadcast if your $watch or $timeout fails

View

<service-history log="log" data-ng-repeat="log in requiedData"></service-history>

Controller

app.controller("MyController",['$scope','$rootScope', function($scope, $rootScope) {

   $scope.$on('$viewContentLoaded', function () {
       SomeSerive.getHistory().then(function(data) {
           $scope.requiedData = data;
           $rootScope.$broadcast("history-updation");
       });
  });

}]);

Directive

app.directive("serviceHistory", function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
           log: '='
        },
        link: function($scope, element, attrs) {
            function updateHistory() {
               if(log) {
                   //do something
               }
            }
            $rootScope.$on("history-updation", updateHistory);
        }
   };
});

how to save DOMPDF generated content to file?

I have just used dompdf and the code was a little different but it worked.

Here it is:

require_once("./pdf/dompdf_config.inc.php");
$files = glob("./pdf/include/*.php");
foreach($files as $file) include_once($file);

$html =
      '<html><body>'.
      '<p>Put your html here, or generate it with your favourite '.
      'templating system.</p>'.
      '</body></html>';

    $dompdf = new DOMPDF();
    $dompdf->load_html($html);
    $dompdf->render();
    $output = $dompdf->output();
    file_put_contents('Brochure.pdf', $output);

Only difference here is that all of the files in the include directory are included.

Other than that my only suggestion would be to specify a full directory path for writing the file rather than just the filename.

What is a bus error?

My reason for bus error on Mac OS X was that I tried to allocate about 1Mb on the stack. This worked well in one thread, but when using openMP this drives to bus error, because Mac OS X has very limited stack size for non-main threads.

How to iterate for loop in reverse order in swift?

Xcode 6 beta 4 added two functions to iterate on ranges with a step other than one: stride(from: to: by:), which is used with exclusive ranges and stride(from: through: by:), which is used with inclusive ranges.

To iterate on a range in reverse order, they can be used as below:

for index in stride(from: 5, to: 1, by: -1) {
    print(index)
}
//prints 5, 4, 3, 2

for index in stride(from: 5, through: 1, by: -1) {
    print(index)
}
//prints 5, 4, 3, 2, 1

Note that neither of those is a Range member function. They are global functions that return either a StrideTo or a StrideThrough struct, which are defined differently from the Range struct.

A previous version of this answer used the by() member function of the Range struct, which was removed in beta 4. If you want to see how that worked, check the edit history.

Alternative to itoa() for converting integer to string C++?

int number = 123;

stringstream = s;

s << number;

cout << ss.str() << endl;

How to convert comma separated string into numeric array in javascript

You can split and convert like

 var strVale = "130,235,342,124 ";
 var intValArray=strVale.split(',');
 for(var i=0;i<intValArray.length;i++{
     intValArray[i]=parseInt(intValArray[i]);
}

Now you can use intValArray in you logic.

How to give environmental variable path for file appender in configuration file in log4j

Since you are using unix you can use a path like this.

  /home/Production/modulename/logs/message.log

path should start with /

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS

For anyone looking for a UI option using IIS Manager.

  1. Open the Website in IIS Manager
  2. Go To Request Filtering and open the Request Filtering Window.
  3. Go to Verbs Tab and Add HTTP Verbs to "Allow Verb..." or "Deny Verb...". This allow to add the HTTP Verbs in the "Deny Verb.." Collection.

Request Filtering Window in IIS Manager Request Filtering Window in IIS Manager

Add Verb... or Deny Verb... enter image description here

How to launch jQuery Fancybox on page load?

Window.load (as opposed to document.ready()) appears to the be the trick used in the JSFiddler onload demos of Fancybox 2.0:

$(window).load(function()
{
    $.fancybox("test");
});

Bare in mind you may be using document.ready() elsewhere, and IE9 gets upset with the load order of the two. This leaves you with two options: change everything to window.load or use a setTimer().

Difference between uint32 and uint32_t

uint32_t is standard, uint32 is not. That is, if you include <inttypes.h> or <stdint.h>, you will get a definition of uint32_t. uint32 is a typedef in some local code base, but you should not expect it to exist unless you define it yourself. And defining it yourself is a bad idea.

How to upgrade all Python packages with pip

Windows version after consulting the excellent documentation for FOR by Rob van der Woude:

for /F "delims===" %i in ('pip freeze -l') do pip install -U %i

Accept function as parameter in PHP

PHP VERSION >= 5.3.0

Example 1: basic

function test($test_param, $my_function) {
    return $my_function($test_param);
}

test("param", function($param) {
    echo $param;
}); //will echo "param"

Example 2: std object

$obj = new stdClass();
$obj->test = function ($test_param, $my_function) {
    return $my_function($test_param);
};

$test = $obj->test;
$test("param", function($param) {
    echo $param;
});

Example 3: non static class call

class obj{
    public function test($test_param, $my_function) {
        return $my_function($test_param);
    }
}

$obj = new obj();
$obj->test("param", function($param) {
    echo $param;
});

Example 4: static class call

class obj {
    public static function test($test_param, $my_function) {
        return $my_function($test_param);
    }
}

obj::test("param", function($param) {
    echo $param;
});

Swift - Split string over multiple lines

I tried several ways but found an even better solution: Just use a "Text View" element. It's text shows up multiple lines automatically! Found here: UITextField multiple lines

select2 onchange event only works once

This is what I am using:

$("#search_code").live('change', function(){
  alert(this.value)
});

For latest jQuery users, this one should work:

$(document.body).on("change","#search_code",function(){
 alert(this.value);
});

$(document).ready equivalent without jQuery

Here is the smallest code snippet to test DOM ready which works across all browsers (even IE 8):

r(function(){
    alert('DOM Ready!');
});
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}

See this answer.

How do I format my oracle queries so the columns don't wrap?

set WRAP OFF
set PAGESIZE 0

Try using those settings.

Getting an "ambiguous redirect" error

One other thing that can cause "ambiguous redirect" is \t \n \r in the variable name you are writing too

Maybe not \n\r? But err on the side of caution

Try this

echo "a" > ${output_name//[$'\t\n\r']}

I got hit with this one while parsing HTML, Tabs \t at the beginning of the line.

How to squash all git commits into one?

To squash using grafts

Add a file .git/info/grafts, put there the commit hash you want to become your root

git log will now start from that commit

To make it 'real' run git filter-branch

Division of integers in Java

In Java
Integer/Integer = Integer
Integer/Double = Double//Either of numerator or denominator must be floating point number
1/10 = 0
1.0/10 = 0.1
1/10.0 = 0.1

Just type cast either of them.

How to calculate md5 hash of a file using javascript

The following snippet shows an example, which can archive a throughput of 400 MB/s while reading and hashing the file.

It is using a library called hash-wasm, which is based on WebAssembly and calculates the hash faster than js-only libraries. As of 2020, all modern browsers support WebAssembly.

_x000D_
_x000D_
const chunkSize = 64 * 1024 * 1024;
const fileReader = new FileReader();
let hasher = null;

function hashChunk(chunk) {
  return new Promise((resolve, reject) => {
    fileReader.onload = async(e) => {
      const view = new Uint8Array(e.target.result);
      hasher.update(view);
      resolve();
    };

    fileReader.readAsArrayBuffer(chunk);
  });
}

const readFile = async(file) => {
  if (hasher) {
    hasher.init();
  } else {
    hasher = await hashwasm.createMD5();
  }

  const chunkNumber = Math.floor(file.size / chunkSize);

  for (let i = 0; i <= chunkNumber; i++) {
    const chunk = file.slice(
      chunkSize * i,
      Math.min(chunkSize * (i + 1), file.size)
    );
    await hashChunk(chunk);
  }

  const hash = hasher.digest();
  return Promise.resolve(hash);
};

const fileSelector = document.getElementById("file-input");
const resultElement = document.getElementById("result");

fileSelector.addEventListener("change", async(event) => {
  const file = event.target.files[0];

  resultElement.innerHTML = "Loading...";
  const start = Date.now();
  const hash = await readFile(file);
  const end = Date.now();
  const duration = end - start;
  const fileSizeMB = file.size / 1024 / 1024;
  const throughput = fileSizeMB / (duration / 1000);
  resultElement.innerHTML = `
    Hash: ${hash}<br>
    Duration: ${duration} ms<br>
    Throughput: ${throughput.toFixed(2)} MB/s
  `;
});
_x000D_
<script src="https://cdn.jsdelivr.net/npm/hash-wasm"></script>
<!-- defines the global `hashwasm` variable -->

<input type="file" id="file-input">
<div id="result"></div>
_x000D_
_x000D_
_x000D_

When to use an interface instead of an abstract class and vice versa?

OK, having just "grokked" this myself - here it is in layman's terms (feel free to correct me if I am wrong) - I know this topic is oooooold, but someone else might stumble across it one day...

Abstract classes allow you to create a blueprint, and allow you to additionally CONSTRUCT (implement) properties and methods you want ALL its descendants to possess.

An interface on the other hand only allows you to declare that you want properties and/or methods with a given name to exist in all classes that implement it - but doesn't specify how you should implement it. Also, a class can implement MANY interfaces, but can only extend ONE Abstract class. An Interface is more of a high level architectural tool (which becomes clearer if you start to grasp design patterns) - an Abstract has a foot in both camps and can perform some of the dirty work too.

Why use one over the other? The former allows for a more concrete definition of descendants - the latter allows for greater polymorphism. This last point is important to the end user/coder, who can utilise this information to implement the A.P.I(nterface) in a variety of combinations/shapes to suit their needs.

I think this was the "lightbulb" moment for me - think about interfaces less from the author's perpective and more from that of any coder coming later in the chain who is adding implementation to a project, or extending an API.

WCF named pipe minimal example

Check out my highly simplified Echo example: It is designed to use basic HTTP communication, but it can easily be modified to use named pipes by editing the app.config files for the client and server. Make the following changes:

Edit the server's app.config file, removing or commenting out the http baseAddress entry and adding a new baseAddress entry for the named pipe (called net.pipe). Also, if you don't intend on using HTTP for a communication protocol, make sure the serviceMetadata and serviceDebug is either commented out or deleted:

<configuration>
    <system.serviceModel>
        <services>
            <service name="com.aschneider.examples.wcf.services.EchoService">
                <host>
                    <baseAddresses>
                        <add baseAddress="net.pipe://localhost/EchoService"/>
                    </baseAddresses>
                </host>
            </service>
        </services>
        <behaviors>
            <serviceBehaviors></serviceBehaviors>
        </behaviors>
    </system.serviceModel>
</configuration>

Edit the client's app.config file so that the basicHttpBinding is either commented out or deleted and a netNamedPipeBinding entry is added. You will also need to change the endpoint entry to use the pipe:

<configuration>
    <system.serviceModel>
        <bindings>
            <netNamedPipeBinding>
                <binding name="NetNamedPipeBinding_IEchoService"/>
            </netNamedPipeBinding>
        </bindings>
        <client>
            <endpoint address              = "net.pipe://localhost/EchoService"
                      binding              = "netNamedPipeBinding"
                      bindingConfiguration = "NetNamedPipeBinding_IEchoService"
                      contract             = "EchoServiceReference.IEchoService"
                      name                 = "NetNamedPipeBinding_IEchoService"/>
        </client>
    </system.serviceModel>
</configuration>

The above example will only run with named pipes, but nothing is stopping you from using multiple protocols to run your service. AFAIK, you should be able to have a server run a service using both named pipes and HTTP (as well as other protocols).

Also, the binding in the client's app.config file is highly simplified. There are many different parameters you can adjust, aside from just specifying the baseAddress...

Registry key Error: Java version has value '1.8', but '1.7' is required

You have to define your jdk folder in variable JAVA_HOME, add %JAVA_HOME% to your variable path

Delete or change name of your java.exe, javaw.exe and javaws in your folder system32

execute cmd.exe, java -version now take the new version that you define in JAVA_HOME.

Are PHP Variables passed by value or by reference?

Actually both methods are valid but it depends upon your requirement. Passing values by reference often makes your script slow. So it's better to pass variables by value considering time of execution. Also the code flow is more consistent when you pass variables by value.

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

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

Two important pieces that are needed are:

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

Export pictures from excel file into jpg using VBA

Dim filepath as string
Sheets("Sheet 1").ChartObjects("Chart 1").Chart.Export filepath & "Name.jpg"

Slimmed down the code to the absolute minimum if needed.

Xcode/Simulator: How to run older iOS version?

To add previous iOS simulator to Xcode 4.2, you need old xcode_3.2.6_and_ios_sdk_4.3.dmg (or similar version) installer file and do as following:

  • Mount the xcode_3.2.6_and_ios_sdk_4.3.dmg file
  • Open mounting disk image and choose menu: Go->Go to Folder...
  • Type /Volumes/Xcode and iOS SDK/Packages/ then click Go. There are many packages and find to iPhoneSimulatorSDK(version).pkg
  • Double click to install package you want to add and wait for installer displays.
  • In Installer click Continue and choose destination, Choose folder...
  • Explorer shows and select Developer folder and click Choose
  • Install and repeat with other simulator as you need.
  • Restart Xcode.

Now there are a list of your installed simulator.

How do I check what version of Python is running my script?

From the command line (note the capital 'V'):

python -V

This is documented in 'man python'.

From IPython console

!python -V

Why do I get "Cannot redirect after HTTP headers have been sent" when I call Response.Redirect()?

You can also use below mentioned code

Response.Write("<script type='text/javascript'>"); Response.Write("window.location = '" + redirect url + "'</script>");Response.Flush();

Delete sql rows where IDs do not have a match from another table

DELETE FROM blob
WHERE NOT EXISTS (
    SELECT *
    FROM files
    WHERE id=blob.id
)

How to get function parameter names/values dynamically?

Whatever the solution, it must not break on wierd functions, whose toString() looks just as wierd:

function  (  A,  b
,c      ,d
){}

screenshot from console

Also, why use complex regular expressions? This can be done like:

function getArguments(f) {
    return f.toString().split(')',1)[0].replace(/\s/g,'').substr(9).split(',');
}

This works everywhere with every function, and the only regex is whitespace removal that doesn't even process the whole string due to the .split trick.

jquery ajax get responsetext from http url

in jquery ajax functions, the success callback signature is:

function (data, textStatus) {
  // data could be xmlDoc, jsonObj, html, text, etc...
  this; // the options for this ajax request
}

depending on the data type you've asked, using the 'dataType' parameter, you'll get the 'data' argument.

from the docs:

dataType (String) Default: Intelligent Guess (xml or html). The type of data that you're expecting back from the server. If none is specified, jQuery will intelligently pass either responseXML or responseText to your success callback, based on the MIME type of the response.

The available types (and the result passed as the first argument to your success callback) are:

"xml": Returns a XML document that can be processed via jQuery.

"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.

"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching unless option "cache" is used. Note: This will turn POSTs into GETs for remote-domain requests.

"json": Evaluates the response as JSON and returns a JavaScript Object.

"jsonp": Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback. (Added in jQuery 1.2)

"text": A plain text string.

see http://docs.jquery.com/Ajax/jQuery.ajax#options

Show dialog from fragment?

I must cautiously doubt the previously accepted answer that using a DialogFragment is the best option. The intended (primary) purpose of the DialogFragment seems to be to display fragments that are dialogs themselves, not to display fragments that have dialogs to display.

I believe that using the fragment's activity to mediate between the dialog and the fragment is the preferable option.

Is recursion ever faster than looping?

Consider what absolutely must be done for each, iteration and recursion.

  • iteration: a jump to beginning of loop
  • recursion: a jump to beginning of called function

You see that there is not much room for differences here.

(I assume recursion being a tail-call and compiler being aware of that optimization).

How to add a “readonly” attribute to an <input>?

Readonly is an attribute as defined in html, so treat it like one.

You need to have something like readonly="readonly" in the object you are working with if you want it not to be editable. And if you want it to be editable again you won't have something like readonly='' (this is not standard if I understood correctly). You really need to remove the attribute as a whole.

As such, while using jquery adding it and removing it is what makes sense.

Set something readonly:

$("#someId").attr('readonly', 'readonly');

Remove readonly:

$("#someId").removeAttr('readonly');

This was the only alternative that really worked for me. Hope it helps!

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Create patch or diff file from git repository and apply it to another different git repository

you can apply two commands

  1. git diff --patch > mypatch.patch // to generate the patch
  2. git apply mypatch.patch // to apply the patch

Best C# API to create PDF

My work uses Winnovative's PDF generator (We've used it mainly to convert HTML to PDF, but you can generate it other ways as well)

Can I use library that used android support with Androidx projects.

If your project is not AndroidX (mean Appcompat) and got this error, try to downgrade dependencies versions that triggers this error, in my case play-services-location ("implementation 'com.google.android.gms:play-services-location:17.0.0'") , I solved the problem by downgrading to com.google.android.gms:play-services-location:16.0.0'

Relationship between hashCode and equals method in Java

The problem you will have is with collections where unicity of elements is calculated according to both .equals() and .hashCode(), for instance keys in a HashMap.

As its name implies, it relies on hash tables, and hash buckets are a function of the object's .hashCode().

If you have two objects which are .equals(), but have different hash codes, you lose!

The part of the contract here which is important is: objects which are .equals() MUST have the same .hashCode().

This is all documented in the javadoc for Object. And Joshua Bloch says you must do it in Effective Java. Enough said.

Laravel Password & Password_Confirmation Validation

Try doing it this way, it worked for me:

$this->validate($request, [
'name' => 'required|min:3|max:50',
'email' => 'email',
'vat_number' => 'max:13',
'password' => 'min:6|required_with:password_confirmation|same:password_confirmation',
'password_confirmation' => 'min:6'
]);`

Seems like the rule always has the validation on the first input among the pair...

How to pick a new color for each plotted line within a figure in matplotlib?

matplotlib 1.5+

You can use axes.set_prop_cycle (example).

matplotlib 1.0-1.4

You can use axes.set_color_cycle (example).

matplotlib 0.x

You can use Axes.set_default_color_cycle.

How should I store GUID in MySQL tables?

char(36) would be a good choice. Also MySQL's UUID() function can be used which returns a 36-character text format (hex with hyphens) which can be used for retrievals of such IDs from the db.

Closing JFrame with button click

You can use super.dispose() method which is more similar to close operation.

How to Correctly handle Weak Self in Swift Blocks with Arguments

As of swift 4.2 we can do:

_ = { [weak self] value in
    guard let self = self else { return }
    print(self) // will never be nil
}()

HTML img align="middle" doesn't align an image

You don't need align="center" and float:left. Remove both of these. margin: 0 auto is sufficient.

check if "it's a number" function in Oracle

Note that regexp or function approaches are several times slower than plain sql condition.

So some heuristic workarounds with limited applicability make sence for huge scans.

There is a solution for cases when you know for sure that non-numeric values would contain some alphabetic letters:

select case when upper(dummy)=lower(dummy) then '~numeric' else '~alpabetic' end from dual

And if you know some letter would be always present in non-numeric cases:

select case when instr(dummy, 'X')>0 then '~alpabetic' else '~numeric' end from dual

When numeric cases would always contain zero:

select case when instr(dummy, '0')=0 then '~alpabetic' else '~numeric' end from dual

Visual Studio debugging/loading very slow

Open the solution folder in windows explorer, close the visual studio, delete .suo file from windows explorer.

Now open the project in visual studio, hopefully debugger will attached/detached fastly.

Getting a slice of keys from a map

For example,

package main

func main() {
    mymap := make(map[int]string)
    keys := make([]int, 0, len(mymap))
    for k := range mymap {
        keys = append(keys, k)
    }
}

To be efficient in Go, it's important to minimize memory allocations.

How to parse float with two decimal places in javascript?

I've got other solution.

You can use round() to do that instead toFixed()

var twoPlacedFloat = parseFloat(yourString).round(2)

How do I remove a specific element from a JSONArray?

In case if someone returns with the same question for Android platform, you cannot use the inbuilt remove() method if you are targeting for Android API-18 or less. The remove() method is added on API level 19. Thus, the best possible thing to do is to extend the JSONArray to create a compatible override for the remove() method.

public class MJSONArray extends JSONArray {

    @Override
    public Object remove(int index) {

        JSONArray output = new JSONArray();     
        int len = this.length(); 
        for (int i = 0; i < len; i++)   {
            if (i != index) {
                try {
                    output.put(this.get(i));
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }
        } 
        return output;
        //return this; If you need the input array in case of a failed attempt to remove an item.
     }
}

EDIT As Daniel pointed out, handling an error silently is bad style. Code improved.

How to convert InputStream to FileInputStream

Use ClassLoader#getResource() instead if its URI represents a valid local disk file system path.

URL resource = classLoader.getResource("resource.ext");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
// ...

If it doesn't (e.g. JAR), then your best bet is to copy it into a temporary file.

Path temp = Files.createTempFile("resource-", ".ext");
Files.copy(classLoader.getResourceAsStream("resource.ext"), temp, StandardCopyOption.REPLACE_EXISTING);
FileInputStream input = new FileInputStream(temp.toFile());
// ...

That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStream instead of InputStream. If you can, just fix the API to ask for an InputStream instead. If it's a 3rd party one, by all means report it as a bug. I'd in this specific case also put question marks around the remainder of that API.

How to hash a string into 8 digits?

Yes, you can use the built-in hashlib module or the built-in hash function. Then, chop-off the last eight digits using modulo operations or string slicing operations on the integer form of the hash:

>>> s = 'she sells sea shells by the sea shore'

>>> # Use hashlib
>>> import hashlib
>>> int(hashlib.sha1(s.encode("utf-8")).hexdigest(), 16) % (10 ** 8)
58097614L

>>> # Use hash()
>>> abs(hash(s)) % (10 ** 8)
82148974

How can I get System variable value in Java?

Have you tried rebooting since you set the environment variable?

It appears that Windows keeps it's environment variable in some sort of cache, and rebooting is one method to refresh it. I'm not sure but there may be a different method, but if you are not going to be changing your variable value too often this may be good enough.

Mime type for WOFF fonts?

I have had the same problem, font/opentype worked for me

Rethrowing exceptions in Java without losing the stack trace

I was just having a similar situation in which my code potentially throws a number of different exceptions that I just wanted to rethrow. The solution described above was not working for me, because Eclipse told me that throw e; leads to an unhandeled exception, so I just did this:

try
{
...
} catch (NoSuchMethodException | SecurityException | IllegalAccessException e) {                    
    throw new RuntimeException(e.getClass().getName() + ": " + e.getMessage() + "\n" + e.getStackTrace().toString());
}

Worked for me....:)

Skip first entry in for loop in python?

for item in do_not_use_list_as_a_name[1:-1]:
    #...do whatever

remove kernel on jupyter notebook

In jupyter notebook run:

!echo y | jupyter kernelspec uninstall unwanted-kernel 

In anaconda prompt run:

jupyter kernelspec uninstall unwanted-kernel

Simple VBA selection: Selecting 5 cells to the right of the active cell

This copies the 5 cells to the right of the activecell. If you have a range selected, the active cell is the top left cell in the range.

Sub Copy5CellsToRight()
    ActiveCell.Offset(, 1).Resize(1, 5).Copy
End Sub

If you want to include the activecell in the range that gets copied, you don't need the offset:

Sub ExtendAndCopy5CellsToRight()
    ActiveCell.Resize(1, 6).Copy
End Sub

Note that you don't need to select before copying.

Event for Handling the Focus of the EditText

when in kotlin it will look like this :

editText.setOnFocusChangeListener { view, hasFocus ->
        if (hasFocus) toast("focused") else toast("focuse lose")
    }

How to get current user in asp.net core

Have another way of getting current user in Asp.NET Core - and I think I saw it somewhere here, on SO ^^

// Stores UserManager
private readonly UserManager<ApplicationUser> _manager; 

// Inject UserManager using dependency injection.
// Works only if you choose "Individual user accounts" during project creation.
public DemoController(UserManager<ApplicationUser> manager)  
{  
    _manager = manager;  
}

// You can also just take part after return and use it in async methods.
private async Task<ApplicationUser> GetCurrentUser()  
{  
    return await _manager.GetUserAsync(HttpContext.User);  
}  

// Generic demo method.
public async Task DemoMethod()  
{  
    var user = await GetCurrentUser(); 
    string userEmail = user.Email; // Here you gets user email 
    string userId = user.Id;
}  

That code goes to controller named DemoController. Won't work without both await (won't compile) ;)

ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file

For windows 10 you need to path C:\Program Files\Java\jre1.8.0_161\bin

restart command and open

How do I restrict a float value to only two places after the decimal point in C?

Use float roundf(float x).

"The round functions round their argument to the nearest integer value in floating-point format, rounding halfway cases away from zero, regardless of the current rounding direction." C11dr §7.12.9.5

#include <math.h>
float y = roundf(x * 100.0f) / 100.0f; 

Depending on your float implementation, numbers that may appear to be half-way are not. as floating-point is typically base-2 oriented. Further, precisely rounding to the nearest 0.01 on all "half-way" cases is most challenging.

void r100(const char *s) {
  float x, y;
  sscanf(s, "%f", &x);
  y = round(x*100.0)/100.0;
  printf("%6s %.12e %.12e\n", s, x, y);
}

int main(void) {
  r100("1.115");
  r100("1.125");
  r100("1.135");
  return 0;
}

 1.115 1.115000009537e+00 1.120000004768e+00  
 1.125 1.125000000000e+00 1.129999995232e+00
 1.135 1.134999990463e+00 1.139999985695e+00

Although "1.115" is "half-way" between 1.11 and 1.12, when converted to float, the value is 1.115000009537... and is no longer "half-way", but closer to 1.12 and rounds to the closest float of 1.120000004768...

"1.125" is "half-way" between 1.12 and 1.13, when converted to float, the value is exactly 1.125 and is "half-way". It rounds toward 1.13 due to ties to even rule and rounds to the closest float of 1.129999995232...

Although "1.135" is "half-way" between 1.13 and 1.14, when converted to float, the value is 1.134999990463... and is no longer "half-way", but closer to 1.13 and rounds to the closest float of 1.129999995232...

If code used

y = roundf(x*100.0f)/100.0f;

Although "1.135" is "half-way" between 1.13 and 1.14, when converted to float, the value is 1.134999990463... and is no longer "half-way", but closer to 1.13 but incorrectly rounds to float of 1.139999985695... due to the more limited precision of float vs. double. This incorrect value may be viewed as correct, depending on coding goals.

How to set upload_max_filesize in .htaccess?

If you are getting 500 - Internal server error that means you don't have permission to set these values by .htaccess. You have to contact your web server providers and ask to set AllowOverride Options for your host or to put these lines in their virtual host configuration file.

fatal error: Python.h: No such file or directory

On Ubuntu, I was running Python 3 and I had to install

sudo apt-get install python3-dev

If you want to use a version of Python that is not linked to python3, install the associated python3.x-dev package. For example:

sudo apt-get install python3.5-dev

Best way to disable button in Twitter's Bootstrap

You just need the $('button').prop('disabled', true); part, the button will automatically take the disabled class.

TSQL DATETIME ISO 8601

For ISO 8601 format for Datetime & Datetime2, below is the recommendation from SQL Server. It does not support basic ISO 8601 format for datetime(yyyyMMddThhmmss).

DateTime

YYYY-MM-DDThh:mm:ss[.mmm]

YYYYMMDD[ hh:mm:ss[.mmm]]

Examples:

  1. 2004-05-23T14:25:10

  2. 2004-05-23T14:25:10.487

Datetime2

YYYY-MM-DDThh:mm:ss[.nnnnnnn]

YYYY-MM-DDThh:mm:ss[.nnnnnnn] Examples:

  1. 2004-05-23T14:25:10

  2. 2004-05-23T14:25:10.8849926

You can convert them using 126 option

--Datetime

DECLARE @table Table(ExtendedDate DATETIME, BasicDate Datetime)

DECLARE @ExtendedDate VARCHAR(30) = '2020-07-01T08:39:17' , @BasicDate VARCHAR(30) = '2009-01-23T10:53:21.000'

INSERT INTO @table(ExtendedDate, BasicDate)
SELECT convert(datetime,@ExtendedDate,126) ,convert(datetime,@BasicDate,126)

SELECT * FROM @table
go

-- Datetime2

DECLARE @table Table(ExtendedDate DATETIME2, BasicDate Datetime2)

DECLARE @ExtendedDate VARCHAR(30) = '2000-01-14T13:42:00.0000000' , @BasicDate VARCHAR(30) = '2009-01-23T10:53:21.0000000'

INSERT INTO @table(ExtendedDate, BasicDate)
SELECT convert(datetime2,@ExtendedDate,126) ,convert(datetime2,@BasicDate,126)

SELECT * FROM @table
go

Datetime

+-------------------------+-------------------------+
|      ExtendedDate       |        BasicDate        |
+-------------------------+-------------------------+
| 2020-07-01 08:39:17.000 | 2009-01-23 10:53:21.000 |
+-------------------------+-------------------------+

Datetime2


+-----------------------------+-----------------------------+
|        ExtendedDate         |          BasicDate          |
+-----------------------------+-----------------------------+
| 2000-01-14 13:42:00.0000000 | 2009-01-23 10:53:21.0000000 |
+-----------------------------+-----------------------------+

jQuery function after .append

Cleanest way is to do it step by step. Use an each funciton to itterate through each element. As soon as that element is appended, pass it to a subsequent function to process that element.

    function processAppended(el){
        //process appended element
    }

    var remove = '<a href="#">remove</a>' ;
    $('li').each(function(){
        $(this).append(remove);   
        processAppended(this);    
    });?

What are the different NameID format used for?

It is just a hint for the Service Provider on what to expect from the NameID returned by the Identity Provider. It can be:

  1. unspecified
  2. emailAddress – e.g. [email protected]
  3. X509SubjectName – e.g. CN=john,O=Company Ltd.,C=US
  4. WindowsDomainQualifiedName – e.g. CompanyDomain\John
  5. kerberos– e.g. john@realm
  6. entity – this one in used to identify entities that provide SAML-based services and looks like a URI
  7. persistent – this is an opaque service-specific identifier which must include a pseudo-random value and must not be traceable to the actual user, so this is a privacy feature.
  8. transient – opaque identifier which should be treated as temporary.

How to count the frequency of the elements in an unordered list?

I am quite late, but this will also work, and will help others:

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
freq_list = []
a_l = list(set(a))

for x in a_l:
    freq_list.append(a.count(x))


print 'Freq',freq_list
print 'number',a_l

will produce this..

Freq  [4, 4, 2, 1, 2]
number[1, 2, 3, 4, 5]

How to check edittext's text is email address or not?

/**
 * method is used for checking valid email id format.
 * 
 * @param email
 * @return boolean true for valid false for invalid
 */
public static boolean isEmailValid(String email) {
    String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(email);
    return matcher.matches();
}

Pass your edit text string in this function .

for right email verification you need server side authentication


Note there is now a built-in method in Android, see answers below.

Regex Email validation

I found nice document on MSDN for it.

How to: Verify that Strings Are in Valid Email Format http://msdn.microsoft.com/en-us/library/01escwtf.aspx (check out that this code also supports the use of non-ASCII characters for Internet domain names.)

There are 2 implementation, for .Net 2.0/3.0 and for .Net 3.5 and higher.
the 2.0/3.0 version is:

bool IsValidEmail(string strIn)
{
    // Return true if strIn is in valid e-mail format.
    return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); 
}

My tests over this method give:

Invalid: @majjf.com
Invalid: A@b@[email protected]
Invalid: Abc.example.com
Valid: [email protected]
Valid: [email protected]
Invalid: js*@proseware.com
Invalid: [email protected]
Valid: [email protected]
Valid: [email protected]
Invalid: ma@@jjf.com
Invalid: ma@jjf.
Invalid: [email protected]
Invalid: [email protected]
Invalid: ma_@jjf
Invalid: ma_@jjf.
Valid: [email protected]
Invalid: -------
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Invalid: [email protected]
Valid: j_9@[129.126.118.1]
Valid: [email protected]
Invalid: js#[email protected]
Invalid: [email protected]
Invalid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Invalid: [email protected]
Invalid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]

Error while inserting date - Incorrect date value:

You need to convert the date to YYYY-MM-DD in order to insert it as a MySQL date using the default configuration.

One way to do that is STR_TO_DATE():

insert into your_table (...)
values (...,str_to_date('07-25-2012','%m-%d-%Y'),...);

Iterating over all the keys of a map

Is there a way to get a list of all the keys in a Go language map?

ks := reflect.ValueOf(m).MapKeys()

how do I iterate over all the keys?

Use the accepted answer:

for k, _ := range m { ... }

Array versus List<T>: When to use which?

Arrays should be used in preference to List when the immutability of the collection itself is part of the contract between the client & provider code (not necessarily immutability of the items within the collection) AND when IEnumerable is not suitable.

For example,

var str = "This is a string";
var strChars = str.ToCharArray();  // returns array

It is clear that modification of "strChars" will not mutate the original "str" object, irrespective implementation-level knowledge of "str"'s underlying type.

But suppose that

var str = "This is a string";
var strChars = str.ToCharList();  // returns List<char>
strChars.Insert(0, 'X');

In this case, it's not clear from that code-snippet alone if the insert method will or will not mutate the original "str" object. It requires implementation level knowledge of String to make that determination, which breaks Design by Contract approach. In the case of String, it's not a big deal, but it can be a big deal in almost every other case. Setting the List to read-only does help but results in run-time errors, not compile-time.

SQL Server - inner join when updating

UPDATE R 
SET R.status = '0' 
FROM dbo.ProductReviews AS R
INNER JOIN dbo.products AS P 
       ON R.pid = P.id 
WHERE R.id = '17190' 
  AND P.shopkeeper = '89137';

How to find duplicate records in PostgreSQL

In order to make it easier I assume that you wish to apply a unique constraint only for column year and the primary key is a column named id.

In order to find duplicate values you should run,

SELECT year, COUNT(id)
FROM YOUR_TABLE
GROUP BY year
HAVING COUNT(id) > 1
ORDER BY COUNT(id);

Using the sql statement above you get a table which contains all the duplicate years in your table. In order to delete all the duplicates except of the the latest duplicate entry you should use the above sql statement.

DELETE
FROM YOUR_TABLE A USING YOUR_TABLE_AGAIN B
WHERE A.year=B.year AND A.id<B.id;

Where does Android app package gets installed on phone

The package it-self is located under /data/app/com.company.appname-xxx.apk.

/data/app/com.company.appname is only a directory created to store files like native libs, cache, ecc...

You can retrieve the package installation path with the Context.getPackageCodePath() function call.

Plot bar graph from Pandas DataFrame

To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:

ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)

What you tried was df['V1','V2'] this will raise a KeyError as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]].

import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()

enter image description here

subquery in FROM must have an alias

add an ALIAS on the subquery,

SELECT  COUNT(made_only_recharge) AS made_only_recharge
FROM    
    (
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER = '0130'
        EXCEPT
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER != '0130'
    ) AS derivedTable                           -- <<== HERE

How to extract public key using OpenSSL?

If your looking how to copy an Amazon AWS .pem keypair into a different region do the following:

openssl rsa -in .ssh/amazon-aws.pem -pubout > .ssh/amazon-aws.pub

Then

aws ec2 import-key-pair --key-name amazon-aws --public-key-material '$(cat .ssh/amazon-aws.pub)' --region us-west-2

Twitter Bootstrap Multilevel Dropdown Menu

I just added class="span2" to the <li> for the dropdown items and that worked.

Generate MD5 hash string with T-SQL

None of the other answers worked for me. Note that SQL Server will give different results if you pass in a hard-coded string versus feed it from a column in your result set. Below is the magic that worked for me to give a perfect match between SQL Server and MySql

select LOWER(CONVERT(VARCHAR(32), HashBytes('MD5', CONVERT(varchar, EmailAddress)), 2)) from ...

Is there a TRY CATCH command in Bash

Is there a TRY CATCH command in Bash?

No.

Bash doesn't have as many luxuries as one can find in many programming languages.

There is no try/catch in bash; however, one can achieve similar behavior using && or ||.

Using ||:

if command1 fails then command2 runs as follows

command1 || command2

Similarly, using &&, command2 will run if command1 is successful

The closest approximation of try/catch is as follows

{ # try

    command1 &&
    #save your output

} || { # catch
    # save log for exception 
}

Also bash contains some error handling mechanisms, as well

set -e

it stops your script if any simple command fails.

And also why not if...else. It is your best friend.

The module was expected to contain an assembly manifest

In my case, I was using InstallUtil.exe which was causing an error. To install the .Net Core service in window best way to use sc command.

More information here Exe installation throwing error The module was expected to contain an assembly manifest .Net Core

How to fill in proxy information in cntlm config file?

Update your user, domain, and proxy information in cntlm.ini, then test your proxy with this command (run in your Cntlm installation folder):

cntlm -c cntlm.ini -I -M http://google.ro

It will ask for your password, and hopefully print your required authentication information, which must be saved in your cntlm.ini

Sample cntlm.ini:

Username            user
Domain              domain

# provide actual value if autodetection fails
# Workstation         pc-name

Proxy               my_proxy_server.com:80
NoProxy             127.0.0.*, 192.168.*

Listen              127.0.0.1:54321
Listen              192.168.1.42:8080
Gateway             no

SOCKS5Proxy         5000
# provide socks auth info if you want it
# SOCKS5User          socks-user:socks-password

# printed authentication info from the previous step
Auth            NTLMv2
PassNTLMv2      98D6986BCFA9886E41698C1686B58A09

Note: on linux the config file is cntlm.conf

"date(): It is not safe to rely on the system's timezone settings..."

This issue has been bugging me for SOME time as im trying to inject a "createbucket.php" script into composer and i keep being told my time-zone is incorrect.

In the end the only thing that fixed the issue was to: $ sudo nano /etc/php.ini

Search for timezone

[Date]
; Defines the default timezone used by the date functions
; http://www.php.net/manual/en/datetime.configuration.php#ini.date.timezone
date.timezone = UTC

Ensure you remove the ;

Then finally

$ sudo service httpd restart

And you'll be good to go :)

Does Index of Array Exist

Assuming you also want to check if the item is not null

if (array.Length > 25 && array[25] != null)
{
    //it exists
}

Check if string is in a pandas dataframe

I bumped into the same problem, I used:

if "Mel" in a["Names"].values:
    print("Yep")

But this solution may be slower since internally pandas create a list from a Series.

jQuery toggle animation

I dont think adding dual functions inside the toggle function works for a registered click event (Unless I'm missing something)

For example:

$('.btnName').click(function() {
 top.$('#panel').toggle(function() {
   $(this).animate({ 
     // style change
   }, 500);
   },
   function() {
   $(this).animate({ 
     // style change back
   }, 500);
 });

Compare two data.frames to find the rows in data.frame 1 that are not present in data.frame 2

I wrote a package (https://github.com/alexsanjoseph/compareDF) since I had the same issue.

  > df1 <- data.frame(a = 1:5, b=letters[1:5], row = 1:5)
  > df2 <- data.frame(a = 1:3, b=letters[1:3], row = 1:3)
  > df_compare = compare_df(df1, df2, "row")

  > df_compare$comparison_df
    row chng_type a b
  1   4         + 4 d
  2   5         + 5 e

A more complicated example:

library(compareDF)
df1 = data.frame(id1 = c("Mazda RX4", "Mazda RX4 Wag", "Datsun 710",
                         "Hornet 4 Drive", "Duster 360", "Merc 240D"),
                 id2 = c("Maz", "Maz", "Dat", "Hor", "Dus", "Mer"),
                 hp = c(110, 110, 181, 110, 245, 62),
                 cyl = c(6, 6, 4, 6, 8, 4),
                 qsec = c(16.46, 17.02, 33.00, 19.44, 15.84, 20.00))

df2 = data.frame(id1 = c("Mazda RX4", "Mazda RX4 Wag", "Datsun 710",
                         "Hornet 4 Drive", " Hornet Sportabout", "Valiant"),
                 id2 = c("Maz", "Maz", "Dat", "Hor", "Dus", "Val"),
                 hp = c(110, 110, 93, 110, 175, 105),
                 cyl = c(6, 6, 4, 6, 8, 6),
                 qsec = c(16.46, 17.02, 18.61, 19.44, 17.02, 20.22))

> df_compare$comparison_df
    grp chng_type                id1 id2  hp cyl  qsec
  1   1         -  Hornet Sportabout Dus 175   8 17.02
  2   2         +         Datsun 710 Dat 181   4 33.00
  3   2         -         Datsun 710 Dat  93   4 18.61
  4   3         +         Duster 360 Dus 245   8 15.84
  5   7         +          Merc 240D Mer  62   4 20.00
  6   8         -            Valiant Val 105   6 20.22

The package also has an html_output command for quick checking

df_compare$html_output enter image description here

PHP MySQL Google Chart JSON - Complete Example

use this, it realy works:

data.addColumn no of your key, you can add more columns or remove

<?php
$con=mysql_connect("localhost","USername","Password") or die("Failed to connect with database!!!!");
mysql_select_db("Database Name", $con); 
// The Chart table contain two fields: Weekly_task and percentage
//this example will display a pie chart.if u need other charts such as Bar chart, u will need to change little bit to make work with bar chart and others charts
$sth = mysql_query("SELECT * FROM chart");

while($r = mysql_fetch_assoc($sth)) {
$arr2=array_keys($r);
$arr1=array_values($r);

}

for($i=0;$i<count($arr1);$i++)
{
    $chart_array[$i]=array((string)$arr2[$i],intval($arr1[$i]));
}
echo "<pre>";
$data=json_encode($chart_array);
?>

<html>
  <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">

    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    function drawChart() {

      // Create our data table out of JSON data loaded from server.
     var data = new google.visualization.DataTable();
        data.addColumn("string", "YEAR");
        data.addColumn("number", "NO of record");

        data.addRows(<?php $data ?>);

        ]); 
      var options = {
           title: 'My Weekly Plan',
          is3D: 'true',
          width: 800,
          height: 600
        };
      // Instantiate and draw our chart, passing in some options.
      //do not forget to check ur div ID
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
    </script>
  </head>

  <body>
    <!--Div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

How to make a UILabel clickable?

As described in the above solution you should enable the user interaction first and add the tap gesture

this code has been tested using

Swift4 - Xcode 9.2

yourlabel.isUserInteractionEnabled = true
yourlabel.addGestureRecognizer(UITapGestureRecognizer(){
                //TODO 
            })

Your password does not satisfy the current policy requirements

For MySQL 8*

SET GLOBAL validate_password.policy=LOW

Reference Link to explain about policy - Click Here

Offline Speech Recognition In Android (JellyBean)

Google did quietly enable offline recognition in that Search update, but there is (as yet) no API or additional parameters available within the SpeechRecognizer class. {See Edit at the bottom of this post} The functionality is available with no additional coding, however the user’s device will need to be configured correctly for it to begin working and this is where the problem lies and I would imagine why a lot of developers assume they are ‘missing something’.

Also, Google have restricted certain Jelly Bean devices from using the offline recognition due to hardware constraints. Which devices this applies to is not documented, in fact, nothing is documented, so configuring the capabilities for the user has proved to be a matter of trial and error (for them). It works for some straight away – For those that it doesn't, this is the ‘guide’ I supply them with.

  1. Make sure the default Android Voice Recogniser is set to Google not Samsung/Vlingo
  2. Uninstall any offline recognition files you already have installed from the Google Voice Search Settings
  3. Go to your Android Application Settings and see if you can uninstall the updates for the Google Search and Google Voice Search applications.
  4. If you can't do the above, go to the Play Store see if you have the option there.
  5. Reboot (if you achieved 2, 3 or 4)
  6. Update Google Search and Google Voice Search from the Play Store (if you achieved 3 or 4 or if an update is available anyway).
  7. Reboot (if you achieved 6)
  8. Install English UK offline language files
  9. Reboot
  10. Use utter! with a connection
  11. Switch to aeroplane mode and give it a try
  12. Once it is working, the offline recognition of other languages, such as English US should start working too.

EDIT: Temporarily changing the device locale to English UK also seems to kickstart this to work for some.

Some users reported they still had to reboot a number of times before it would begin working, but they all get there eventually, often inexplicably to what was the trigger, the key to which are inside the Google Search APK, so not in the public domain or part of AOSP.

From what I can establish, Google tests the availability of a connection prior to deciding whether to use offline or online recognition. If a connection is available initially but is lost prior to the response, Google will supply a connection error, it won’t fall-back to offline. As a side note, if a request for the network synthesised voice has been made, there is no error supplied it if fails – You get silence.

The Google Search update enabled no additional features in Google Now and in fact if you try to use it with no internet connection, it will error. I mention this as I wondered if the ability would be withdrawn as quietly as it appeared and therefore shouldn't be relied upon in production.

If you intend to start using the SpeechRecognizer class, be warned, there is a pretty major bug associated with it, which require your own implementation to handle.

Not being able to specifically request offline = true, makes controlling this feature impossible without manipulating the data connection. Rubbish. You’ll get hundreds of user emails asking you why you haven’t enabled something so simple!

EDIT: Since API level 23 a new parameter has been added EXTRA_PREFER_OFFLINE which the Google recognition service does appear to adhere to.

Hope the above helps.