Programs & Examples On #Church encoding

In mathematics, Church encoding is a means of representing data and operators in the lambda calculus. The Church numerals are a representation of the natural numbers using lambda notation. The method is named for Alonzo Church, who first encoded data in the lambda calculus this way.

Instantly detect client disconnection from server socket

This worked for me, the key is you need a separate thread to analyze the socket state with polling. doing it in the same thread as the socket fails detection.

//open or receive a server socket - TODO your code here
socket = new Socket(....);

//enable the keep alive so we can detect closure
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

//create a thread that checks every 5 seconds if the socket is still connected. TODO add your thread starting code
void MonitorSocketsForClosureWorker() {
    DateTime nextCheckTime = DateTime.Now.AddSeconds(5);

    while (!exitSystem) {
        if (nextCheckTime < DateTime.Now) {
            try {
                if (socket!=null) {
                    if(socket.Poll(5000, SelectMode.SelectRead) && socket.Available == 0) {
                        //socket not connected, close it if it's still running
                        socket.Close();
                        socket = null;    
                    } else {
                        //socket still connected
                    }    
               }
           } catch {
               socket.Close();
            } finally {
                nextCheckTime = DateTime.Now.AddSeconds(5);
            }
        }
        Thread.Sleep(1000);
    }
}

How to fix SSL certificate error when running Npm on Windows?

This problem was fixed for me by using http version of repository:

npm config set registry http://registry.npmjs.org/

Search all tables, all columns for a specific value SQL Server

I've just updated my blog post to correct the error in the script that you were having Jeff, you can see the updated script here: Search all fields in SQL Server Database

As requested, here's the script in case you want it but I'd recommend reviewing the blog post as I do update it from time to time

DECLARE @SearchStr nvarchar(100)
SET @SearchStr = '## YOUR STRING HERE ##'
 
 
-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Updated and tested by Tim Gaunt
-- http://www.thesitedoctor.co.uk
-- http://blogs.thesitedoctor.co.uk/tim/2010/02/19/Search+Every+Table+And+Field+In+A+SQL+Server+Database+Updated.aspx
-- Tested on: SQL Server 7.0, SQL Server 2000, SQL Server 2005 and SQL Server 2010
-- Date modified: 03rd March 2011 19:00 GMT
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
 
SET NOCOUNT ON
 
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
 
WHILE @TableName IS NOT NULL
 
BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM     INFORMATION_SCHEMA.TABLES
        WHERE         TABLE_TYPE = 'BASE TABLE'
            AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND    OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )
 
    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
         
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM     INFORMATION_SCHEMA.COLUMNS
            WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                AND    QUOTENAME(COLUMN_NAME) > @ColumnName
        )
 
        IF @ColumnName IS NOT NULL
         
        BEGIN
            INSERT INTO #Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END   
END
 
SELECT ColumnName, ColumnValue FROM #Results
 
DROP TABLE #Results

Possible to make labels appear when hovering over a point in matplotlib?

mpld3 solve it for me. EDIT (CODE ADDED):

import matplotlib.pyplot as plt
import numpy as np
import mpld3

fig, ax = plt.subplots(subplot_kw=dict(axisbg='#EEEEEE'))
N = 100

scatter = ax.scatter(np.random.normal(size=N),
                 np.random.normal(size=N),
                 c=np.random.random(size=N),
                 s=1000 * np.random.random(size=N),
                 alpha=0.3,
                 cmap=plt.cm.jet)
ax.grid(color='white', linestyle='solid')

ax.set_title("Scatter Plot (with tooltips!)", size=20)

labels = ['point {0}'.format(i + 1) for i in range(N)]
tooltip = mpld3.plugins.PointLabelTooltip(scatter, labels=labels)
mpld3.plugins.connect(fig, tooltip)

mpld3.show()

You can check this example

How to play CSS3 transitions in a loop?

If you want to take advantage of the 60FPS smoothness that the "transform" property offers, you can combine the two:

@keyframes changewidth {
  from {
    transform: scaleX(1);
  }

  to {
    transform: scaleX(2);
  }
}

div {
  animation-duration: 0.1s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

More explanation on why transform offers smoother transitions here: https://medium.com/outsystems-experts/how-to-achieve-60-fps-animations-with-css3-db7b98610108

How do I change UIView Size?

Assigning questionFrame.frame.size.height= screenSize.height * 0.30 will not reflect anything in the view. because it is a get-only property. If you want to change the frame of questionFrame you can use the below code.

questionFrame.frame = CGRect(x: 0, y: 0, width: 0, height: screenSize.height * 0.70)

Session timeout in ASP.NET

Are you using Forms authentication?

Forms authentication uses it own value for timeout (30 min. by default). A forms authentication timeout will send the user to the login page with the session still active. This may look like the behavior your app gives when session times out making it easy to confuse one with the other.

<system.web>
    <authentication mode="Forms">
          <forms timeout="50"/>
    </authentication>

    <sessionState timeout="60"  />
</system.web>

Setting the forms timeout to something less than the session timeout can give the user a window in which to log back in without losing any session data.

assembly to compare two numbers

The basic technique (on most modern systems) is to subtract the two numbers and then to check the sign bit of the result, i.e. see if the result is greater than/equal to/less than zero. In the assembly code instead of getting the result directly (into a register), you normally just branch depending on the state:

; Compare r1 and r2
    CMP $r1, $r2
    JLT lessthan
greater_or_equal:
    ; print "r1 >= r2" somehow
    JMP l1
lessthan:
    ; print "r1 < r2" somehow
l1:

get current page from url

Try this:

path.Substring(path.LastIndexOf("/");

Retrieving the COM class factory for component failed

I have Done the Following Things in IIS 8.5 (Windows Server 2012 R2)Server and its Worked in My Case Without Restart:

  1. Selecting The Application Pool That Connected to The Application in IIS

  2. And Right Click --> Advanced Settings --> Process Model --> Select Local System Instead of Recommended ApplicationPoolIdentity

  3. And Make Sure C:\Windows\SysWOW64\config\systemprofile\desktop Have Enough Access For Users.

  4. Refresh the Website Link that Connected With this Pool


enter image description here

How to set index.html as root file in Nginx?

For me, the try_files directive in the (currently most voted) answer https://stackoverflow.com/a/11957896/608359 led to rewrite cycles,

*173 rewrite or internal redirection cycle while internally redirecting

I had better luck with the index directive. Note that I used a forward slash before the name, which might or might not be what you want.

server {
  listen 443 ssl;
  server_name example.com;

  root /home/dclo/example;
  index /index.html;
  error_page 404 /index.html;

  # ... ssl configuration
}

In this case, I wanted all paths to lead to /index.html, including when returning a 404.

How to get the parents of a Python class?

The FASTEST way, to see all parents, and IN ORDER, just use the built in __mro__

i.e. repr(YOUR_CLASS.__mro__)


>>>
>>>
>>> import getpass
>>> getpass.GetPassWarning.__mro__

outputs, IN ORDER


(<class 'getpass.GetPassWarning'>, <type 'exceptions.UserWarning'>,
<type 'exceptions.Warning'>, <type 'exceptions.Exception'>, 
<type 'exceptions.BaseException'>, <type 'object'>)
>>>

There you have it. The "best" answer right now, has 182 votes (as I am typing this) but this is SO much simpler than some convoluted for loop, looking into bases one class at a time, not to mention when a class extends TWO or more parent classes. Importing and using inspect just clouds the scope unnecessarily. It honestly is a shame people don't know to just use the built-ins

I Hope this Helps!

Javascript checkbox onChange

try

totalCost.value = checkbox.checked ? 10 : calculate();

_x000D_
_x000D_
function change(checkbox) {_x000D_
  totalCost.value = checkbox.checked ? 10 : calculate();_x000D_
}_x000D_
_x000D_
function calculate() {_x000D_
  return other.value*2;_x000D_
}
_x000D_
input { display: block}
_x000D_
Checkbox: <input type="checkbox" onclick="change(this)"/>_x000D_
Total cost: <input id="totalCost" type="number" value=5 />_x000D_
Other: <input id="other" type="number" value=7 />
_x000D_
_x000D_
_x000D_

Spring - download response as a file

It's working for me :

  • Spring controller : DownloadController.java

    package com.mycompany.myapp.controller;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.io.IOUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.mycompany.myapp.exception.TechnicalException;
    
    
    @RestController
    public class DownloadController {
    
        private final Logger log = LoggerFactory.getLogger(DownloadController.class);
    
        @RequestMapping(value = "/download", method = RequestMethod.GET)
        public void download(@RequestParam ("name") String name, final HttpServletRequest request, final HttpServletResponse response) throws TechnicalException {
            log.trace("name : {}", name);
    
            File file = new File ("src/main/resources/" + name);
            log.trace("Write response...");
            try (InputStream fileInputStream = new FileInputStream(file);
                    OutputStream output = response.getOutputStream();) {
    
                response.reset();
    
                response.setContentType("application/octet-stream");
                response.setContentLength((int) (file.length()));
    
                response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
    
                IOUtils.copyLarge(fileInputStream, output);
                output.flush();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
    
        }
    
    }
    
  • AngularJs Service : download.service.js

    (function() {
        'use strict';
    
        var downloadModule = angular.module('components.donwload', []);
    
        downloadModule.factory('downloadService', ['$q', '$timeout', '$window',
            function($q, $timeout, $window) {
                return {
                    download: function(name) {
    
                        var defer = $q.defer();
    
                        $timeout(function() {
                                $window.location = 'download?name=' + name;
    
                            }, 1000)
                            .then(function() {
                                defer.resolve('success');
                            }, function() {
                                defer.reject('error');
                            });
                        return defer.promise;
                    }
                };
            }
        ]);
    })();
    
  • AngularJs config : app.js

    (function() {
        'use strict';
    
        var myApp = angular.module('myApp', ['components.donwload']);
       /* myApp.config([function () {
    
        }]);
        myApp.run([function () {
    
        }]);*/
    
    
    })();
    
  • AngularJs controller : download.controller.js

    (function() {
        'use strict';
    
        angular.module('myApp')
            .controller('DownloadSampleCtrl', ['downloadService', function(downloadService) {
                this.download = function(fileName) {
                    downloadService.download(fileName)
                        .then(function(success) {
                            console.log('success : ' + success);
                        }, function(error) {
                            console.log('error : ' + error);
                        });
                };
            }]);
    })();
    
  • index.html

    <!DOCTYPE html>
    <html ng-app="myApp">
    
    <head>
        <title>My App</title>
        <link rel="stylesheet" href="bower_components/normalize.css/normalize.css" />
        <link rel="stylesheet" href="assets/styles/main.css" />
        <link rel="icon" href="favicon.ico">
    </head>
    
    <body>
        <div ng-controller="DownloadSampleCtrl as ctrl">
            <button ng-click="ctrl.download('fileName.txt')">Download</button>
        </div>
    
        <script src="bower_components/angular/angular.min.js"></script>
    
        <!-- App config -->
        <script src="scripts/app/app.js"></script>
        <!-- Download Feature -->
        <script src="scripts/app/download/download.controller.js"></script>
        <!-- Components -->
        <script src="scripts/components/download/download.service.js"></script>
    </body>
    
    </html>
    

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

I had the same problem. I removed virtual device and run app on my phone - worked well. To remove virtual device: Click icon "AVD Manager" in Android Studio, select virtual device and in context menu click "Delete". Then turn on on the phone "Developer mode". Connect phone via USB to the laptop.

Is there a better way to do optional function parameters in JavaScript?

I am used to seeing a few basic variations on handling optional variables. Sometimes, the relaxed versions are useful.

function foo(a, b, c) {
  a = a || "default";   // Matches 0, "", null, undefined, NaN, false.
  a || (a = "default"); // Matches 0, "", null, undefined, NaN, false.

  if (b == null) { b = "default"; } // Matches null, undefined.

  if (typeof c === "undefined") { c = "default"; } // Matches undefined.
}

The falsy default used with variable a is, for example, used extensively in Backbone.js.

Get the Last Inserted Id Using Laravel Eloquent

Using Eloquent Model

use App\Company;

public function saveDetailsCompany(Request $request)
{

$createcompany=Company::create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);

// Last Inserted Row ID

echo $createcompany->id;

}

Using Query Builder

$createcompany=DB::table('company')->create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);

echo $createcompany->id;

For more methods to get Last Inserted Row id in Laravel : http://phpnotebook.com/95-laravel/127-3-methods-to-get-last-inserted-row-id-in-laravel

The type or namespace name 'Objects' does not exist in the namespace 'System.Data'

Upgraded from EF5 to EF6 nuget a while back and kept encountering this issue. I'd temp fix it by updating the generated code to reference System.Data.Entity.Core.Objects, but after generation it would be changed back again (as expected since its generated).

This solved the problem for good:

http://msdn.microsoft.com/en-us/data/upgradeef6

If you have any models created with the EF Designer, you will need to update the code generation templates to generate EF6 compatible code. Note: There are currently only EF 6.x DbContext Generator templates available for Visual Studio 2012 and 2013.

  1. Delete existing code-generation templates. These files will typically be named <edmx_file_name>.tt and <edmx_file_name>.Context.tt and be nested under your edmx file in Solution Explorer. You can select the templates in Solution Explorer and press the Del key to delete them.
    Note: In Web Site projects the templates will not be nested under your edmx file, but listed alongside it in Solution Explorer.
    Note: In VB.NET projects you will need to enable 'Show All Files' to be able to see the nested template files.
  2. Add the appropriate EF 6.x code generation template. Open your model in the EF Designer, right-click on the design surface and select Add Code Generation Item...
    • If you are using the DbContext API (recommended) then EF 6.x DbContext Generator will be available under the Data tab.
      Note: If you are using Visual Studio 2012, you will need to install the EF 6 Tools to have this template. See Get Entity Framework for details.
    • If you are using the ObjectContext API then you will need to select the Online tab and search for EF 6.x EntityObject Generator.
  3. If you applied any customizations to the code generation templates you will need to re-apply them to the updated templates.

Connect to Amazon EC2 file directory using Filezilla and SFTP

I've created a video tutorial for this. Just check:

Connect to Amazon EC2 file directory using FileZilla and SFTP, Video Tutorial

Summary of above video tutorial:

  1. Edit (Preferences) > Settings > Connection > SFTP, Click "Add key file”
  2. Browse to the location of your .pem file and select it.
  3. A message box will appear asking your permission to convert the file into ppk format. Click Yes, then give the file a name and store it somewhere.
  4. If the new file is shown in the list of Keyfiles, then continue to the next step. If not, then click "Add keyfile..." and select the converted file.
  5. File > Site Manager Add a new site with the following parameters:

    Host: Your public DNS name of your EC2 instance, or the public IP address of the server.

    Protocol: SFTP

    Logon Type: Normal

    User: From the docs: "For Amazon Linux, the default user name is ec2-user. For RHEL5, the user name is often root but might be ec2-user. For Ubuntu, the user name is ubuntu. For SUSE Linux, the user name is root. For Debian, the user name is admin. Otherwise, check with your AMI provider."

    Press Connect Button - If saving of passwords has been disabled, you will be prompted that the logon type will be changed to 'Ask for password'. Say 'OK' and when connecting, at the password prompt push 'OK' without entering a password to proceed past the dialog.

    Note: FileZilla automatically figures out which key to use. You do not need to specify the key after importing it as described above.

If you use Cyberduck follow this.

Check this post if you have any permission issues.

jQuery Validate Required Select

I don't know how was the plugin the time the question was asked (2010), but I faced the same problem today and solved it this way:

  1. Give your select tag a name attribute. For example in this case

    <select name="myselect">

  2. Instead of working with the attribute value="default" in the tag option, disable the default option or set value="" as suggested by Andrew Coats

    <option disabled="disabled">Choose...</option>

    or

    <option value="">Choose...</option>

  3. Set the plugin validation rule

    $( "#YOUR_FORM_ID" ).validate({ rules: { myselect: { required: true } } });

    or

    <select name="myselect" class="required">

Obs: Andrew Coats' solution works only if you have just one select in your form. If you want his solution to work with more than one select add a name attribute to your select.

Hope it helps! :)

how to delete all cookies of my website in php

<?php
      parse_str(http_build_query($_COOKIE),$arr);
      foreach ($arr as $k=>$v) {
        setCookie("$k","",1000,"/");
      }

Show hide fragment in android

the answers here are correct and i liked @Jyo the Whiff idea of a show and hide fragment implementation except the way he has it currently would hide the fragment on the first run so i added a slight change in that i added the isAdded check and show the fragment if its not already

public void showHideCardPreview(int id) {
    FragmentManager fm = getSupportFragmentManager();
    Bundle b = new Bundle();
    b.putInt(Constants.CARD, id);
    cardPreviewFragment.setArguments(b);
    FragmentTransaction ft = fm.beginTransaction()
        .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
    if (!cardPreviewFragment.isAdded()){
        ft.add(R.id.full_screen_container, cardPreviewFragment);
        ft.show(cardPreviewFragment);
    } else {
        if (cardPreviewFragment.isHidden()) {
            Log.d(TAG,"++++++++++++++++++++ show");
            ft.show(cardPreviewFragment);
        } else {
            Log.d(TAG,"++++++++++++++++++++ hide");
            ft.hide(cardPreviewFragment);
        }
    }

    ft.commit();
} 

AngularJs: Reload page

My solution to avoid the infinite loop was to create another state which have made the redirection:

$stateProvider.state('app.admin.main', {
    url: '/admin/main',
    authenticate: 'admin',
    controller: ($state, $window) => {
      $state.go('app.admin.overview').then(() => {
        $window.location.reload();
      });
    }
  });

remove space between paragraph and unordered list

I ended up using a definition list with an unordered list inside it. It solves the issue of the unwanted space above the list without needing to change every paragraph tag.

<dl><dt>Text</dt>
<dd><ul><li>First item</li>
<li>Second item</li></ul></dd></dl>

What exactly does the .join() method do?

list = ["my", "name", "is", "kourosh"]   
" ".join(list)

If this is an input, using the JOIN method, we can add the distance between the words and also convert the list to the string.

This is Python output

'my name is kourosh'

jQuery toggle animation

onmouseover="$('.play-detail').stop().animate({'height': '84px'},'300');" 

onmouseout="$('.play-detail').stop().animate({'height': '44px'},'300');"

Just put two stops -- one onmouseover and one onmouseout.

How is the default max Java heap size determined?

Finally!

As of Java 8u191 you now have the options:

-XX:InitialRAMPercentage
-XX:MaxRAMPercentage
-XX:MinRAMPercentage

that can be used to size the heap as a percentage of the usable physical RAM. (which is same as the RAM installed less what the kernel uses).

See Release Notes for Java8 u191 for more information. Note that the options are mentioned under a Docker heading but in fact they apply whether you are in Docker environment or in a traditional environment.

The default value for MaxRAMPercentage is 25%. This is extremely conservative.

My own rule: If your host is more or less dedicated to running the given java application, then you can without problems increase dramatically. If you are on Linux, only running standard daemons and have installed RAM from somewhere around 1 Gb and up then I wouldn't hesitate to use 75% for the JVM's heap. Again, remember that this is 75% of the RAM available, not the RAM installed. What is left is the other user land processes that may be running on the host and the other types of memory that the JVM needs (eg for stack). All together, this will typically fit nicely in the 25% that is left. Obviously, with even more installed RAM the 75% is a safer and safer bet. (I wish the JDK folks had implemented an option where you could specify a ladder)

Setting the MaxRAMPercentage option look like this:

java -XX:MaxRAMPercentage=75.0  ....

Note that these percentage values are of 'double' type and therefore you must specify them with a decimal dot. You get a somewhat odd error if you use "75" instead of "75.0".

What does <T> denote in C#

It is a Generic Type Parameter.

A generic type parameter allows you to specify an arbitrary type T to a method at compile-time, without specifying a concrete type in the method or class declaration.

For example:

public T[] Reverse<T>(T[] array)
{
    var result = new T[array.Length];
    int j=0;
    for(int i=array.Length - 1; i>= 0; i--)
    {
        result[j] = array[i];
        j++;
    }
    return result;
}

reverses the elements in an array. The key point here is that the array elements can be of any type, and the function will still work. You specify the type in the method call; type safety is still guaranteed.

So, to reverse an array of strings:

string[] array = new string[] { "1", "2", "3", "4", "5" };
var result = reverse(array);

Will produce a string array in result of { "5", "4", "3", "2", "1" }

This has the same effect as if you had called an ordinary (non-generic) method that looks like this:

public string[] Reverse(string[] array)
{
    var result = new string[array.Length];
    int j=0;
    for(int i=array.Length - 1; i >= 0; i--)
    {
        result[j] = array[i];
        j++;
    }
    return result;
}

The compiler sees that array contains strings, so it returns an array of strings. Type string is substituted for the T type parameter.


Generic type parameters can also be used to create generic classes. In the example you gave of a SampleCollection<T>, the T is a placeholder for an arbitrary type; it means that SampleCollection can represent a collection of objects, the type of which you specify when you create the collection.

So:

var collection = new SampleCollection<string>();

creates a collection that can hold strings. The Reverse method illustrated above, in a somewhat different form, can be used to reverse the collection's members.

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

I got this with data driven tests using:

Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)

The problem is the above driver only is 32 bit. I had switched visual studio testsettings file to 64 bit to test a 64-bit-only application.

Switching back to 32 bit in the testsettings file fixed the issue.

using a test settings file

Apply a function to every row of a matrix or a data frame

Here is a short example of applying a function to each row of a matrix. (Here, the function applied normalizes every row to 1.)

Note: The result from the apply() had to be transposed using t() to get the same layout as the input matrix A.

A <- matrix(c(
  0, 1, 1, 2,
  0, 0, 1, 3,
  0, 0, 1, 3
), nrow = 3, byrow = TRUE)

t(apply(A, 1, function(x) x / sum(x) ))

Result:

     [,1] [,2] [,3] [,4]
[1,]    0 0.25 0.25 0.50
[2,]    0 0.00 0.25 0.75
[3,]    0 0.00 0.25 0.75

shell-script headers (#!/bin/sh vs #!/bin/csh)

This is known as a Shebang:

http://en.wikipedia.org/wiki/Shebang_(Unix)

#!interpreter [optional-arg]

A shebang is only relevant when a script has the execute permission (e.g. chmod u+x script.sh).

When a shell executes the script it will use the specified interpreter.

Example:

#!/bin/bash
# file: foo.sh
echo 1

$ chmod u+x foo.sh
$ ./foo.sh
  1

No more data to read from socket error

This is a very low-level exception, which is ORA-17410.

It may happen for several reasons:

  1. A temporary problem with networking.

  2. Wrong JDBC driver version.

  3. Some issues with a special data structure (on database side).

  4. Database bug.

In my case, it was a bug we hit on the database, which needs to be patched.

Getting Textarea Value with jQuery

It can be done at easily like as:

     <a id="send-thoughts" href="">Click</a>
     <textarea id="message"></textarea>

        $("a#send-thoughts").click(function() {
            var thought = $("#message").val();
            alert(thought);
        });

Using UPDATE in stored procedure with optional parameters

   UPDATE tbl_ClientNotes
    SET 
      ordering=ISNULL@ordering,ordering), 
      title=isnull(@title,title), 
      content=isnull(@content,content)
    WHERE id=@id

I think I remember seeing before that if you are updating to the same value SQL Server will actually recognize this and won't do an unnecessary write.

How to install "make" in ubuntu?

I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.

To answer the question in the header: To install make in ubuntu you have to install build-essentials

sudo apt-get install build-essential

How to fix a header on scroll

Coop's answer is excellent.
However it depends on jQuery, here is a version that has no dependencies:

HTML

<div id="sticky" class="sticky"></div>

CSS

.sticky {
  width: 100%
}

.fixed {
  position: fixed;
  top:0;
}

JS
(This uses eyelidlessness's answer for finding offsets in Vanilla JS.)

function findOffset(element) {
  var top = 0, left = 0;

  do {
    top += element.offsetTop  || 0;
    left += element.offsetLeft || 0;
    element = element.offsetParent;
  } while(element);

  return {
    top: top,
    left: left
  };
}

window.onload = function () {
  var stickyHeader = document.getElementById('sticky');
  var headerOffset = findOffset(stickyHeader);

  window.onscroll = function() {
    // body.scrollTop is deprecated and no longer available on Firefox
    var bodyScrollTop = document.documentElement.scrollTop || document.body.scrollTop;

    if (bodyScrollTop > headerOffset.top) {
      stickyHeader.classList.add('fixed');
    } else {
      stickyHeader.classList.remove('fixed');
    }
  };
};

Example

https://jsbin.com/walabebita/edit?html,css,js,output

How to get access to HTTP header information in Spring MVC REST controller?

You can use the @RequestHeader annotation with HttpHeaders method parameter to gain access to all request headers:

@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers) {
    // Use headers to get the information about all the request headers
    long contentLength = headers.getContentLength();
    // ...
    StreamSource source = new StreamSource(new StringReader(body));
    YourObject obj = (YourObject) jaxb2Mashaller.unmarshal(source);
    // ...
}

Depend on a branch or tag using a git URL in a package.json?

If you want to use devel or feature branch, or you haven’t published a certain package to the NPM registry, or you can’t because it’s a private module, then you can point to a git:// URI instead of a version number in your package.json:

"dependencies": {
   "public": "git://github.com/user/repo.git#ref",
   "private": "git+ssh://[email protected]:user/repo.git#ref"
}

The #ref portion is optional, and it can be a branch (like master), tag (like 0.0.1) or a partial or full commit id.

conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I think the best way to work with dates between C# and SQL is, of course, use parametrized queries, and always work with DateTime objects on C# and the ToString() formating options it provides.

You better execute set datetime <format> (here you have the set dateformat explanation on MSDN) before working with dates on SQL Server so you don't get in trouble, like for example set datetime ymd. You only need to do it once per connection because it mantains the format while open, so a good practice would be to do it just after openning the connection to the database.
Then, you can always work with 'yyyy-MM-dd HH:mm:ss:ffff' formats.

To pass the DateTime object to your parametrized query you can use DateTime.ToString('yyyy-MM-dd HH:mm:ss:ffff').

For parsing weird formatted dates on C# you can use DateTime.ParseExact() method, where you have the option to specify exactly what the input format is: DateTime.ParseExact(<some date string>, 'dd/MM-yyyy',CultureInfo.InvariantCulture). Here you have the DateTime.ParseExact() explanation on MSDN)

How to update values using pymongo?

Something I did recently, hope it helps. I have a list of dictionaries and wanted to add a value to some existing documents.

for item in my_list:
    my_collection.update({"_id" : item[key] }, {"$set" : {"New_col_name" :item[value]}})

How to find if div with specific id exists in jQuery?

if($("#id").length) /*exists*/

if(!$("#id").length) /*doesn't exist*/

Angular CLI - Please add a @NgModule annotation when using latest

In my case, I created a new ChildComponent in Parentcomponent whereas both in the same module but Parent is registered in a shared module so I created ChildComponent using CLI which registered Child in the current module but my parent was registered in the shared module.

So register the ChildComponent in Shared Module manually.

How to define two fields "unique" as couple

Django 2.2+

Using the constraints features UniqueConstraint is preferred over unique_together.

From the Django documentation for unique_together:

Use UniqueConstraint with the constraints option instead.
UniqueConstraint provides more functionality than unique_together.
unique_together may be deprecated in the future.

For example:

class Volume(models.Model):
    id = models.AutoField(primary_key=True)
    journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name="Journal")
    volume_number = models.CharField('Volume Number', max_length=100)
    comments = models.TextField('Comments', max_length=4000, blank=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['journal_id', 'volume_number'], name='name of constraint')
        ]

How to check if a file exists before creating a new file

Assuming it is OK that the operation is not atomic, you can do:

if (std::ifstream(name))
{
     std::cout << "File already exists" << std::endl;
     return false;
}
std::ofstream file(name);
if (!file)
{
     std::cout << "File could not be created" << std::endl;
     return false;
}
... 

Note that this doesn't work if you run multiple threads trying to create the same file, and certainly will not prevent a second process from "interfering" with the file creation because you have TOCTUI problems. [We first check if the file exists, and then create it - but someone else could have created it in between the check and the creation - if that's critical, you will need to do something else, which isn't portable].

A further problem is if you have permissions such as the file is not readable (so we can't open it for read) but is writeable, it will overwrite the file.

In MOST cases, neither of these things matter, because all you care about is telling someone that "you already have a file like that" (or something like that) in a "best effort" approach.

"Cross origin requests are only supported for HTTP." error when loading a local file

Easy solution for whom using VS Code

I've been getting this error for a while. Most of the answers works. But I found a different solution. If you don't want to deal with node.js or any other solution in here and you are working with an HTML file (calling functions from another js file or fetch json api's) try to use Live Server extension.

It allows you to open a live server easily. And because of it creates localhost server, the problem is resolving. You can simply start the localhost by open a HTML file and right-click on the editor and click on Open with Live Server.

It basically load the files using http://localhost/index.html instead of using file://....

EDIT

It is not necessary to have a .html file. You can start the Live Server with shortcuts.

Hit (alt+L, alt+O) to Open the Server and (alt+L, alt+C) to Stop the server. [On MAC, cmd+L, cmd+O and cmd+L, cmd+C]

Hope it will help someone :)

Role/Purpose of ContextLoaderListener in Spring?

ContextLoaderListener is optional. Just to make a point here: you can boot up a Spring application without ever configuring ContextLoaderListener, just a basic minimum web.xml with DispatcherServlet.

Here is what it would look like:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
    xsi:schemaLocation="
        http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
    id="WebApp_ID" 
    version="2.5">
  <display-name>Some Minimal Webapp</display-name>
  <welcome-file-list>   
    <welcome-file>index.jsp</welcome-file>    
  </welcome-file-list>

  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>
      org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

Create a file called dispatcher-servlet.xml and store it under WEB-INF. Since we mentioned index.jsp in welcome list, add this file under WEB-INF.

dispatcher-servlet.xml

In the dispatcher-servlet.xml define your beans:

<?xml version="1.0" encoding="UTF-8"?>
<beans 
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd     
        http://www.springframework.org/schema/context     
        http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="bean1">
      ...
    </bean>
    <bean id="bean2">
      ...
    </bean>         

    <context:component-scan base-package="com.example" />
    <!-- Import your other configuration files too -->
    <import resource="other-configs.xml"/>
    <import resource="some-other-config.xml"/>

    <!-- View Resolver -->
    <bean 
        id="viewResolver" 
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
      <property 
          name="viewClass" 
          value="org.springframework.web.servlet.view.JstlView" />
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
    </bean>
</beans>

jQuery - Sticky header that shrinks when scrolling down

This should be what you are looking for using jQuery.

$(function(){
  $('#header_nav').data('size','big');
});

$(window).scroll(function(){
  if($(document).scrollTop() > 0)
{
    if($('#header_nav').data('size') == 'big')
    {
        $('#header_nav').data('size','small');
        $('#header_nav').stop().animate({
            height:'40px'
        },600);
    }
}
else
  {
    if($('#header_nav').data('size') == 'small')
      {
        $('#header_nav').data('size','big');
        $('#header_nav').stop().animate({
            height:'100px'
        },600);
      }  
  }
});

Demonstration: http://jsfiddle.net/jezzipin/JJ8Jc/

How to get current route in react-router 2.0.0-rc5

You could use the 'isActive' prop like so:

const { router } = this.context;
if (router.isActive('/login')) {
    router.push('/');
}

isActive will return a true or false.

Tested with react-router 2.7

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

In addition to the above mentioned answers: I wanted to start a job with a simple parameter passed to a second pipeline and found the answer on http://web.archive.org/web/20160209062101/https://dzone.com/refcardz/continuous-delivery-with-jenkins-workflow

So i used:

stage ('Starting ART job') {
    build job: 'RunArtInTest', parameters: [[$class: 'StringParameterValue', name: 'systemname', value: systemname]]
}

Eclipse: How to build an executable jar with external jar?

How to include the jars of your project into your runnable jar:

I'm using Eclipse Version: 3.7.2 running on Ubuntu 12.10. I'll also show you how to make the build.xml so you can do the ant jar from command line and create your jar with other imported jars extracted into it.

Basically you ask Eclipse to construct the build.xml that imports your libraries into your jar for you.

  1. Fire up Eclipse and make a new Java project, make a new package 'mypackage', add your main class: Runner Put this code in there.

    enter image description here

  2. Now include the mysql-connector-java-5.1.28-bin.jar from Oracle which enables us to write Java to connect to the MySQL database. Do this by right clicking the project -> properties -> java build path -> Add External Jar -> pick mysql-connector-java-5.1.28-bin.jar.

  3. Run the program within eclipse, it should run, and tell you that the username/password is invalid which means Eclipse is properly configured with the jar.

  4. In Eclipse go to File -> Export -> Java -> Runnable Jar File. You will see this dialog:

    enter image description here

    Make sure to set up the 'save as ant script' checkbox. That is what makes it so you can use the commandline to do an ant jar later.

  5. Then go to the terminal and look at the ant script:

    enter image description here

So you see, I ran the jar and it didn't error out because it found the included mysql-connector-java-5.1.28-bin.jar embedded inside Hello.jar.

Look inside Hello.jar: vi Hello.jar and you will see many references to com/mysql/jdbc/stuff.class

To do ant jar on the commandline to do all this automatically: Rename buildant.xml to build.xml, and change the target name from create_run_jar to jar.

Then, from within MyProject you type ant jar and boom. You've got your jar inside MyProject. And you can invoke it using java -jar Hello.jar and it all works.

Regex match everything after question mark?

Try this:

\?(.*)

The parentheses are a capturing group that you can use to extract the part of the string you are interested in.

If the string can contain new lines you may have to use the "dot all" modifier to allow the dot to match the new line character. Whether or not you have to do this, and how to do this, depends on the language you are using. It appears that you forgot to mention the programming language you are using in your question.

Another alternative that you can use if your language supports fixed width lookbehind assertions is:

(?<=\?).*

Convert a secure string to plain text

You may also use PSCredential.GetNetworkCredential() :

$SecurePassword = Get-Content C:\Users\tmarsh\Documents\securePassword.txt | ConvertTo-SecureString
$UnsecurePassword = (New-Object PSCredential "user",$SecurePassword).GetNetworkCredential().Password

How do I output the results of a HiveQL query to CSV?

hive  --outputformat=csv2 -e "select * from yourtable" > my_file.csv

or

hive  --outputformat=csv2 -e "select * from yourtable" > [your_path]/file_name.csv

For tsv, just change csv to tsv in the above queries and run your queries

How to get JSON object from Razor Model object in javascript

After use codevar json = @Html.Raw(Json.Encode(@Model.CollegeInformationlist));

You need use JSON.parse(JSON.stringify(json));

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

you can use the keyword 'In' and pass the List argument. e.g : findByInventoryIdIn

 List<AttributeHistory> findByValueIn(List<String> values);

Git commit with no commit message

I found the simplest solution:

git commit -am'save'

That's all,you will work around git commit message stuff.

you can even save that commend to a bash or other stuff to make it more simple.

Our team members always write those messages,but almost no one will see those message again.

Commit message is a time-kill stuff at least in our team,so we ignore it.

Doing a join across two databases with different collations on SQL Server and getting an error

You can use the collate clause in a query (I can't find my example right now, so my syntax is probably wrong - I hope it points you in the right direction)

select sone_field collate SQL_Latin1_General_CP850_CI_AI
  from table_1
    inner join table_2
      on (table_1.field collate SQL_Latin1_General_CP850_CI_AI = table_2.field)
  where whatever

mysqli_real_connect(): (HY000/2002): No such file or directory

Try just

sudo service mysql restart

It worked for me

Why SQL Server throws Arithmetic overflow error converting int to data type numeric?

Numeric defines the TOTAL number of digits, and then the number after the decimal.

A numeric(3,2) can only hold up to 9.99.

How to install a specific version of Node on Ubuntu?

NVM (Node Version manager)

https://github.com/nvm-sh/nvm

Advantages:

  • allows you to use multiple versions of Node and without sudo

  • is analogous to Ruby RVM and Python Virtualenv, widely considered best practice in Ruby and Python communities

  • downloads a pre-compiled binary where possible, and if not it downloads the source and compiles one for you

Tested in Ubuntu 17.10:

curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | sh
source ~/.nvm/nvm.sh
nvm install 0.9.0
nvm install 0.9.9
nvm use 0.9.0
node --version
#v0.9.0
nvm use 0.9.9
node --version
#v0.9.9

For the particular case of the most recent long term support version (recommended if you can choose):

nvm install --lts
nvm use --lts
npm --version
npm install --global vaca
vaca

Since the sourcing has to be done for every new shell, the install script hacks adds some auto sourcing to the end of your .barshrc. That works, but I prefer to remove the auto-added one and add my own:

f="$HOME/.nvm/nvm.sh"
if [ -r "$f" ]; then
  . "$f" &>'/dev/null'
  nvm use --lts &>'/dev/null'
fi

With this setup, you get for example:

which node

gives:

/home/ciro/.nvm/versions/node/v0.9.0/bin/node

and:

which vaca

gives:

/home/ciro/.nvm/versions/node/v0.9.0/bin/vaca

and if we want to use the globally installed module:

npm link vaca
node -e 'console.log(require.resolve("vaca"))'

gives:

/home/ciro/.nvm/versions/node/v0.9.0/lib/node_modules/vaca/index.js

so we see that everything is completely contained inside the specific node version.

Cannot create Maven Project in eclipse

Same problem here, solved.

I will explain the problem and the solution, to help others.

My software is:

Windows 7
Eclipse 4.4.1 (Luna SR1)
m2e 1.5.0.20140606-0033
    (from eclipse repository: http://download.eclipse.org/releases/luna)

And I'm accessing internet through a proxy.

My problem was the same:

  • Just installed m2e, went to menu: File > New > Other > Maven > Maven project > Next > Next.
  • Selected "Catalog: All catalogs" and "Filter: maven-archetype-quickstart", then clicked on the search result, then on button Next.
  • Then entered "Group Id: test_gr" and "Artifact Id: test_art", then clicked on Finish button.
  • Got the "Could not resolve archetype..." error.

After a lot of try-and-error, and reading a lot of pages, I've finally found a solution to fix it. Some important points of the solution:

  • It uses the default (embedded) Maven installation (3.2.1/1.5.0.20140605-2032) that comes with m2e.
  • So no aditional (external) Maven installation is required.
  • No special m2e config is required.

The solution is:

  • Open eclipse.
  • Restore m2e original preferences (if you changed any of them): Click on menu: Window > Preferences > Maven > Restore defaults. Do the same for all tree items under "Maven" item: Archetypes, Discovery, Errors/Warnings, Instalation, Lifecycle Mappings, Templates, User Interface, User Settings. Click on "OK" button.
  • Copy (for example to a notepad window) the path of the user settings file. To see the path, click again on menu: Window > Preferences > Maven > User Settings, and the path is at the "User settings" textbox. You will have to write the path manually, since it is not posible to copy-and-paste. After coping the path to the notepad, don't close the Preferences window.
  • At the Preferences window that is already open, click on the "open file" link. Close the Preferences window, and you will see the "settings.xml" file already openned in a Eclipse editor.
  • The editor will have 2 tabs at the bottom: "Design" and "Source". Click on "Source" tab. You will see all the source code (xml).
  • Delete all the source code: Click on the code, press control+a, press "del".
  • Copy the following code to the editor (and customize the uppercased values):
<settings>
  <proxies>
   <proxy>
      <active>true</active>
      <protocol>http</protocol>
      <host>YOUR.PROXY.IP.OR.NAME</host>
      <port>YOUR PROXY PORT</port>
      <username>YOUR PROXY USERNAME (OR EMPTY IF NOT REQUIRED)</username>
      <password>YOUR PROXY PASSWORD (OR EMPTY IF NOT REQUIRED)</password>
      <nonProxyHosts>YOUR PROXY EXCLUSION HOST LIST (OR EMPTY)</nonProxyHosts>
    </proxy>
  </proxies>
</settings>
  • Save the file: control+s.
  • Exit Eclipse: Menu File > Exit.
  • Open in a Windows Explorer the path you copied (without the filename, just the path of directories).
  • You will probaly see the xml file ("settings.xml") and a directoy ("repository"). Remove the directoy ("repository"): Right click > Delete > Yes.
  • Start Eclipse.
  • Now you will be able to create a maven project: File > New > Other > Maven > Maven project > Next > Next, select "Catalog: All catalogs" and "Filter: maven-archetype-quickstart", click on the search result, then on button Next, enter "Group Id: test_gr" and "Artifact Id: test_art", click on Finish button.

Finally, I would like to give a suggestion to m2e developers, to make config easier. After installing m2e from the internet (from a repository), m2e should check if Eclipse is using a proxy (Preferences > General > Network Connections). If Eclipse is using a proxy, the m2e should show a dialog to the user:

m2e has detected that Eclipse is using a proxy to access to the internet.
Would you like me to create a User settings file (settings.xml) for the embedded 
Maven software?

[ Yes ] [ No ]

If the user clicks on Yes, then m2e should create automatically the "settings.xml" file by copying proxy values from Eclipse preferences.

multiple figure in latex with captions

Below is an example of multiple figures that I used recently in Latex. You need to call these packages

\usepackage{graphicx}
\usepackage{subfig})


\begin{figure}[H]%

    \centering

    \subfloat[Row1]{{\includegraphics[scale=.36]{1.png} }}%

    \subfloat[Row2]{{\includegraphics[scale=.36]{2.png} }}%

    \subfloat[Row3]{{\includegraphics[scale=.36]{3.png} }}%
    \hfill
    \subfloat[Row4]{{\includegraphics[scale=0.37]{4.png} }}%

    \subfloat[Row5]{{\includegraphics[scale=0.37]{5.png} }}%

    \caption{Multiple figures in latex.}%

    \label{fig:MFL}%

\end{figure}

How to check if the docker engine and a docker container are running?

For OS X users (Mojave 10.14.3)

Here is what i use in my Bash script to test if Docker is running or not

# Check if docker is running
if ! docker info >/dev/null 2>&1; then
    echo "Docker does not seem to be running, run it first and retry"
    exit 1
fi

Getting the last revision number in SVN?

<?php
    $url = 'your repository here';
    $output = `svn info $url`;
    echo "<pre>$output</pre>";
?>

You can get the output in XML like so:

$output = `svn info $url --xml`;

If there is an error then the output will be directed to stderr. To capture stderr in your output use thusly:

$output = `svn info $url 2>&1`;

How to remove time portion of date in C# in DateTime object only?

Try this, if you use a DateTimeOffset, it will also take care of the timezone

date1 = date1.LocalDateTime.Date;

If you need to add hours, use this:

date1 = date1.LocalDateTime.Date;
date1 = date1.AddHours(23).AddMinutes(59).AddSeconds(59);

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

Add services.AddSingleton(); in your ConfigureServices method of Startup.cs file of your project.

public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        // To register interface with its concrite type
        services.AddSingleton<IEmployee, EmployeesMockup>();
    }

For More details please visit this URL : https://www.youtube.com/watch?v=aMjiiWtfj2M

for All methods (i.e. AddSingleton vs AddScoped vs AddTransient) Please visit this URL: https://www.youtube.com/watch?v=v6Nr7Zman_Y&list=PL6n9fhu94yhVkdrusLaQsfERmL_Jh4XmU&index=44)

How to check if a value is not null and not empty string in JS

If you truly want to confirm that a variable is not null and not an empty string specifically, you would write:

if(data !== null && data !== '') {
   // do something
}

Notice that I changed your code to check for type equality (!==|===).

If, however you just want to make sure, that a code will run only for "reasonable" values, then you can, as others have stated already, write:

if (data) {
  // do something
}

Since, in javascript, both null values, and empty strings, equals to false (i.e. null == false).

The difference between those 2 parts of code is that, for the first one, every value that is not specifically null or an empty string, will enter the if. But, on the second one, every true-ish value will enter the if: false, 0, null, undefined and empty strings, would not.

How to add fixed button to the bottom right of page

This will be helpful for the right bottom rounded button

HTML :

      <a class="fixedButton" href>
         <div class="roundedFixedBtn"><i class="fa fa-phone"></i></div>
      </a>
    

CSS:

       .fixedButton{
            position: fixed;
            bottom: 0px;
            right: 0px; 
            padding: 20px;
        }
        .roundedFixedBtn{
          height: 60px;
          line-height: 80px;  
          width: 60px;  
          font-size: 2em;
          font-weight: bold;
          border-radius: 50%;
          background-color: #4CAF50;
          color: white;
          text-align: center;
          cursor: pointer;
        }
    

Here is jsfiddle link http://jsfiddle.net/vpthcsx8/11/

Remove a prefix from a string

def remove_prefix(str, prefix):
    if str.startswith(prefix):
        return str[len(prefix):]
    else:
        return str

As an aside note, str is a bad name for a variable because it shadows the str type.

Unsuccessful append to an empty NumPy array

This error arise from the fact that you are trying to define an object of shape (0,) as an object of shape (2,). If you append what you want without forcing it to be equal to result[0] there is no any issue:

b = np.append([result[0]], [1,2])

But when you define result[0] = b you are equating objects of different shapes, and you can not do this. What are you trying to do?

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

I had the same error on IIS Express. In my case, I had two projects as startup projects.I changed properties of the solution to single startup project and ran it. then changed it to previous settings and ran the solution again and no error occurred again!

How to align LinearLayout at the center of its parent?

This worked for me.. adding empty view ..

<LinearLayout
       android:layout_width="match_parent"
        android:layout_height="wrap_content"
       android:layout_gravity="center_horizontal"
        android:orientation="horizontal"
         >
<View
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="1"
            />  
     <com.google.android.gms.ads.AdView

         android:id="@+id/adView"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"

         android:layout_gravity="center_horizontal"
         ads:adSize="BANNER"
         ads:adUnitId="@string/banner_ad_unit_id" >

    </com.google.android.gms.ads.AdView>
    <View
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="1"
            />  
    </LinearLayout>

What does %>% function mean in R?

My understanding after reading the link offered by G.Grothendieck is that %>% is an operator that pipes functions. This helps readability and productivity as it's easier to follow the flow of multiple functions through these pipes than going backwards when multiple function are nested.

Linq code to select one item

These are the preferred methods:

var item = Items.SingleOrDefault(x => x.Id == 123);

Or

var item = Items.Single(x => x.Id == 123);

How can I pass variable to ansible playbook in the command line?

For some reason none of the above Answers worked for me. As I need to pass several extra vars to my playbook in Ansbile 2.2.0, this is how I got it working (note the -e option before each var):

ansible-playbook site.yaml -i hostinv -e firstvar=false -e second_var=value2

Android get Current UTC time

see my answer here:

How can I get the current date and time in UTC or GMT in Java?

I've fully tested it by changing the timezones on the emulator

"No such file or directory" but it exists

I found my solution for my Ubuntu 18 here.

sudo dpkg --add-architecture i386

Then:

sudo apt-get update
sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386

How can I get a resource content from a static context?

The Singleton:

package com.domain.packagename;

import android.content.Context;

/**
 * Created by Versa on 10.09.15.
 */
public class ApplicationContextSingleton {
    private static PrefsContextSingleton mInstance;
    private Context context;

    public static ApplicationContextSingleton getInstance() {
        if (mInstance == null) mInstance = getSync();
        return mInstance;
    }

    private static synchronized ApplicationContextSingleton getSync() {
        if (mInstance == null) mInstance = new PrefsContextSingleton();
        return mInstance;
    }

    public void initialize(Context context) {
        this.context = context;
    }

    public Context getApplicationContext() {
        return context;
    }

}

Initialize the Singleton in your Application subclass:

package com.domain.packagename;

import android.app.Application;

/**
 * Created by Versa on 25.08.15.
 */
public class mApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        ApplicationContextSingleton.getInstance().initialize(this);
    }
}

If I´m not wrong, this gives you a hook to applicationContext everywhere, call it with ApplicationContextSingleton.getInstance.getApplicationContext(); You shouldn´t need to clear this at any point, as when application closes, this goes with it anyway.

Remember to update AndroidManifest.xml to use this Application subclass:

<?xml version="1.0" encoding="utf-8"?>

<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.domain.packagename"
    >

<application
    android:allowBackup="true"
    android:name=".mApplication" <!-- This is the important line -->
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    android:icon="@drawable/app_icon"
    >

Now you should be able to use ApplicationContextSingleton.getInstance().getApplicationContext().getResources() from anywhere, also the very few places where application subclasses can´t.

Please let me know if you see anything wrong here, thank you. :)

How can I read the contents of an URL with Python?

A solution with works with Python 2.X and Python 3.X makes use of the Python 2 and 3 compatibility library six:

from six.moves.urllib.request import urlopen
link = "http://www.somesite.com/details.pl?urn=2344"
response = urlopen(link)
content = response.read()
print(content)

Android WebView progress bar

here is the easiest way to add progress bar in android Web View.

Add a boolean field in your activity/fragment

private boolean isRedirected;

This boolean will prevent redirection of web pages cause of dead links.Now you can just pass your WebView object and web Url into this method.

private void startWebView(WebView webView,String url) {

    webView.setWebViewClient(new WebViewClient() {
        ProgressDialog progressDialog;

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            isRedirected = true;
            return false;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            isRedirected = false;
        }

        public void onLoadResource (WebView view, String url) {
            if (!isRedirected) {
                if (progressDialog == null) {
                    progressDialog = new ProgressDialog(SponceredDetailsActivity.this);
                    progressDialog.setMessage("Loading...");
                    progressDialog.show();
                }
            }

        }
        public void onPageFinished(WebView view, String url) {
            try{
                isRedirected=true;

                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }



            }catch(Exception exception){
                exception.printStackTrace();
            }
        }

    });

    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl(url);
}

Here when start loading it will call onPageStarted. Here i setting Boolean field is false. But when page load finish it will come to onPageFinished method and here Boolean field is set to true. Sometimes if url is dead it will redirected and it will come to onLoadResource() before onPageFinished method. For this reason it will not hiding the progress bar. To prevent this i am checking if (!isRedirected) in onLoadResource()

in onPageFinished() method before dismissing the Progress Dialog you can write your 10 second time delay code

That's it. Happy coding :)

How to find all occurrences of an element in a list

more_itertools.locate finds indices for all items that satisfy a condition.

from more_itertools import locate


list(locate([0, 1, 1, 0, 1, 0, 0]))
# [1, 2, 4]

list(locate(['a', 'b', 'c', 'b'], lambda x: x == 'b'))
# [1, 3]

more_itertools is a third-party library > pip install more_itertools.

Using an HTTP PROXY - Python

I encountered this on jython client. The server was only talking TLS and the client using SSL context.

javax.net.ssl.SSLContext.getInstance("SSL")

Once the client was to TLS, things started working.

How to reset a select element with jQuery

This does the trick, and works for any select.

$('#baba').val($(this).find('option:first').val());

Should I use window.navigate or document.location in JavaScript?

Late joining this conversation to shed light on a mildly interesting factoid for web-facing, analytics-aware websites. Passing the mic over to Michael Papworth:

https://github.com/michaelpapworth/jQuery.navigate

"When using website analytics, window.location is not sufficient due to the referer not being passed on the request. The plugin resolves this and allows for both aliased and parametrised URLs."

If one examines the code what it does is this:

   var methods = {
            'goTo': function (url) {
                // instead of using window.location to navigate away
                // we use an ephimeral link to click on and thus ensure
                // the referer (current url) is always passed on to the request
                $('<a></a>').attr("href", url)[0].click();
            },
            ...
   };

Neato!

Killing a process using Java

It might be a java interpreter defect, but java on HPUX does not do a kill -9, but only a kill -TERM.

I did a small test testDestroy.java:

ProcessBuilder pb = new ProcessBuilder(args);
Process process = pb.start();
Thread.sleep(1000);
process.destroy();
process.waitFor();

And the invocation:

$ tusc -f -p -s signal,kill -e /opt/java1.5/bin/java testDestroy sh -c 'trap "echo TERM" TERM; sleep 10'

dies after 10s (not killed after 1s as expected) and shows:

...
[19999]   Received signal 15, SIGTERM, in waitpid(), [caught], no siginfo
[19998] kill(19999, SIGTERM) ............................................................................. = 0
...

Doing the same on windows seems to kill the process fine even if signal is handled (but that might be due to windows not using signals to destroy).

Actually i found Java - Process.destroy() source code for Linux related thread and openjava implementation seems to use -TERM as well, which seems very wrong.

checking if number entered is a digit in jquery

there is a simpler way of checking if a variable is an integer. you can use $.isNumeric() function. e.g.

$.isNumeric( 10 );     // true

this will return true but if you put a string in place of the 10, you will get false.

I hope this works for you.

Android Viewpager as Image Slide Gallery

Hi if your are looking for simple android image sliding with circle indicator you can download the complete code from here http://javaant.com/viewpager-with-circle-indicator-in-android/#.VysQQRV96Hs . please check the live demo which will give the clear idea.

Change default date time format on a single database in SQL Server

You do realize that format has nothing to do with how SQL Server stores datetime, right?

You can use set dateformat for each session. There is no setting for database only.

If you use parameters for data insert or update or where filtering you won't have any problems with that.

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

To Enable WiFi:

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);

To Disable WiFi:

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);

Note: To access with WiFi state, we have to add following permissions inside the AndroidManifest.xml file:

android.permission.ACCESS_WIFI_STATE
android.permission.UPDATE_DEVICE_STATS 
android.permission.CHANGE_WIFI_STATE

JUnit Testing private variables?

If you create your test classes in a seperate folder which you then add to your build path,

Then you could make the test class an inner class of the class under test by using package correctly to set the namespace. This gives it access to private fields and methods.

But dont forget to remove the folder from the build path for your release build.

How can I mock an ES6 module import using Jest?

You have to mock the module and set the spy by yourself:

import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency', () => ({
  doSomething: jest.fn()
}))

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    myModule(2);
    expect(dependency.doSomething).toBeCalledWith(4);
  });
});

Replacing Pandas or Numpy Nan with a None to use with MysqlDB

Another addition: be careful when replacing multiples and converting the type of the column back from object to float. If you want to be certain that your None's won't flip back to np.NaN's apply @andy-hayden's suggestion with using pd.where. Illustration of how replace can still go 'wrong':

In [1]: import pandas as pd

In [2]: import numpy as np

In [3]: df = pd.DataFrame({"a": [1, np.NAN, np.inf]})

In [4]: df
Out[4]:
     a
0  1.0
1  NaN
2  inf

In [5]: df.replace({np.NAN: None})
Out[5]:
      a
0     1
1  None
2   inf

In [6]: df.replace({np.NAN: None, np.inf: None})
Out[6]:
     a
0  1.0
1  NaN
2  NaN

In [7]: df.where((pd.notnull(df)), None).replace({np.inf: None})
Out[7]:
     a
0  1.0
1  NaN
2  NaN

How to subtract one month using moment.js?

For substracting in moment.js:

moment().subtract(1, 'months').format('MMM YYYY');

Documentation:

http://momentjs.com/docs/#/manipulating/subtract/

Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).

  moment().subtract('seconds', 1); // Deprecated in 2.8.0
  moment().subtract(1, 'seconds');

As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.

  moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
  moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8

How to display the first few characters of a string in Python?

If you want first 2 letters and last 2 letters of a string then you can use the following code: name = "India" name[0:2]="In" names[-2:]="ia"

Convert RGB to Black & White in OpenCV

AFAIK, you have to convert it to grayscale and then threshold it to binary.

1. Read the image as a grayscale image If you're reading the RGB image from disk, then you can directly read it as a grayscale image, like this:

// C
IplImage* im_gray = cvLoadImage("image.jpg",CV_LOAD_IMAGE_GRAYSCALE);

// C++ (OpenCV 2.0)
Mat im_gray = imread("image.jpg",CV_LOAD_IMAGE_GRAYSCALE);

2. Convert an RGB image im_rgb into a grayscale image: Otherwise, you'll have to convert the previously obtained RGB image into a grayscale image

// C
IplImage *im_rgb  = cvLoadImage("image.jpg");
IplImage *im_gray = cvCreateImage(cvGetSize(im_rgb),IPL_DEPTH_8U,1);
cvCvtColor(im_rgb,im_gray,CV_RGB2GRAY);

// C++
Mat im_rgb  = imread("image.jpg");
Mat im_gray;
cvtColor(im_rgb,im_gray,CV_RGB2GRAY);

3. Convert to binary You can use adaptive thresholding or fixed-level thresholding to convert your grayscale image to a binary image.

E.g. in C you can do the following (you can also do the same in C++ with Mat and the corresponding functions):

// C
IplImage* im_bw = cvCreateImage(cvGetSize(im_gray),IPL_DEPTH_8U,1);
cvThreshold(im_gray, im_bw, 128, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);

// C++
Mat img_bw = im_gray > 128;

In the above example, 128 is the threshold.

4. Save to disk

// C
cvSaveImage("image_bw.jpg",img_bw);

// C++
imwrite("image_bw.jpg", img_bw);

How to make rectangular image appear circular with CSS

I presume that your problem with background-image is that it would be inefficient with a source for each image inside a stylesheet. My suggestion is to set the source inline:

<div style = 'background-image: url(image.gif)'></div>

div {
    background-repeat: no-repeat;
    background-position: 50%;
    border-radius: 50%;
    width: 100px;
    height: 100px;
}

Fiddle

Execution failed for task ':app:compileDebugAidl': aidl is missing

I am working with sdk 23.1.0 and gradle 1.3.1. I created a new project edited nothing and got the aidl error. I went into my project gradle file and changed tool to 22.0.1 instead of 23.1.0 and it worked:

   compileSdkVersion 23
   buildToolsVersion "22.0.1" //"23.1.0"

Find files in a folder using Java

What you want is File.listFiles(FileNameFilter filter).

That will give you a list of the files in the directory you want that match a certain filter.

The code will look similar to:

// your directory
File f = new File("C:\\example");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.startsWith("temp") && name.endsWith("txt");
    }
});

How to set max and min value for Y axis

With 1.1.1, I used the following to fix the scale between 0.0 and 1.0:

var options = {
    scaleOverride: true,
    scaleStartValue: 0,
    scaleSteps: 10,
    scaleStepWidth: 0.1
}

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

Follow below steps:

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

  2. Replace the @RestController with @Controller

  3. Remove if you are using any view resolvers.

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

  5. Include the below dependencies:

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

Allow 2 decimal places in <input type="number">

Step 1: Hook your HTML number input box to an onchange event

myHTMLNumberInput.onchange = setTwoNumberDecimal;

or in the HTML code

<input type="number" onchange="setTwoNumberDecimal" min="0" max="10" step="0.25" value="0.00" />

Step 2: Write the setTwoDecimalPlace method

function setTwoNumberDecimal(event) {
    this.value = parseFloat(this.value).toFixed(2);
}

You can alter the number of decimal places by varying the value passed into the toFixed() method. See MDN docs.

toFixed(2); // 2 decimal places
toFixed(4); // 4 decimal places
toFixed(0); // integer

Truncate to three decimals in Python

I develop a good solution, I know there is much If statements, but It works! (Its only for <1 numbers)

def truncate(number, digits) -> float:
    startCounting = False
    if number < 1:
      number_str = str('{:.20f}'.format(number))
      resp = ''
      count_digits = 0
      for i in range(0, len(number_str)):
        if number_str[i] != '0' and number_str[i] != '.' and number_str[i] != ',':
          startCounting = True
        if startCounting:
          count_digits = count_digits + 1
        resp = resp + number_str[i]
        if count_digits == digits:
            break
      return resp
    else:
      return number

How can I start InternetExplorerDriver using Selenium WebDriver

1---Enable protected mode for all zones You need to enable protected mode for all zones from Internet Options -> Security tab. To enable protected mode for all zones

Open Internet Explorer browser.
Go to menu Tools -> Internet Options.
Click on Security tab.
Select Internet from "Select a zone to view or change security settings" and Select(check) check box "Enable Protected Mode" from In the "Security level for this zone" block .
Apply same thing for all other 3 zones -> Local Internet, Trusted Sites and Restricted Sites

This setting will resolve error related to "Protected Mode settings are not the same for all zones.

2-- Set IE browser's zoom level 100%

Open Internet Explorer browser.
Go to menu View -> Zoom -> Select 100%

Autowiring two beans implementing same interface - how to set default bean to autowire?

For Spring 2.5, there's no @Primary. The only way is to use @Qualifier.

How to use not contains() in xpath?

I need to select every production with a category that doesn't contain "Business"

Although I upvoted @Arran's answer as correct, I would also add this... Strictly interpreted, the OP's specification would be implemented as

//production[category[not(contains(., 'Business'))]]

rather than

//production[not(contains(category, 'Business'))]

The latter selects every production whose first category child doesn't contain "Business". The two XPath expressions will behave differently when a production has no category children, or more than one.

It doesn't make any difference in practice as long as every <production> has exactly one <category> child, as in your short example XML. Whether you can always count on that being true or not, depends on various factors, such as whether you have a schema that enforces that constraint. Personally, I would go for the more robust option, since it doesn't "cost" much... assuming your requirement as stated in the question is really correct (as opposed to e.g. 'select every production that doesn't have a category that contains "Business"').

Upload a file to Amazon S3 with NodeJS

Upload CSV/Excel

const fs = require('fs');
const AWS = require('aws-sdk');

const s3 = new AWS.S3({
    accessKeyId: XXXXXXXXX,
    secretAccessKey: XXXXXXXXX
});

const absoluteFilePath = "C:\\Project\\test.xlsx";

const uploadFile = () => {
  fs.readFile(absoluteFilePath, (err, data) => {
     if (err) throw err;
     const params = {
         Bucket: 'testBucket', // pass your bucket name
         Key: 'folderName/key.xlsx', // file will be saved in <folderName> folder
         Body: data
     };
      s3.upload(params, function (s3Err, data) {
                    if (s3Err) throw s3Err
                    console.log(`File uploaded successfully at ${data.Location}`);
                    debugger;
                });
  });
};

uploadFile();

Maximum size for a SQL Server Query? IN clause? Is there a Better Approach

Per batch, 65536 * Network Packet Size which is 4k so 256 MB

However, IN will stop way before that but it's not precise.

You end up with memory errors but I can't recall the exact error. A huge IN will be inefficient anyway.

Edit: Remus reminded me: the error is about "stack size"

What determines the monitor my app runs on?

Important note: If you remember the position of your application and shutdown and then start up again at that position, keep in mind that the user's monitor configuration may have changed while your application was closed.

Laptop users, for example, frequently change their display configuration. When docked there may be a 2nd monitor that disappears when undocked. If the user closes an application that was running on the 2nd monitor and the re-opens the application when the monitor is disconnected, restoring the window to the previous coordinates will leave it completely off-screen.

To figure out how big the display really is, check out GetSystemMetrics.

DROP IF EXISTS VS DROP?

DROP TABLE IF EXISTS [table_name]

it first checks if the table exists, if it does it deletes the table while

DROP TABLE [table_name]

it deletes without checking, so if it doesn't exist it exits with an error

document.getelementbyId will return null if element is not defined?

console.log(document.getElementById('xx') ) evaluates to null.

document.getElementById('xx') !=null evaluates to false

You should use document.getElementById('xx') !== null as it is a stronger equality check.

jQuery function to open link in new window

Try adding return false; in your click callback like this -

$(document).ready(function() {
  $('.popup').click(function(event) {
      window.open($(this).attr("href"), "popupWindow", "width=600,height=600,scrollbars=yes");
      return false;
  });
});

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

Assuming the second window is defined as public partial class Window2 : Window, you can do it by:

Window2 win2 = new Window2();
win2.Show();

How Can I Truncate A String In jQuery?

From: jQuery text truncation (read more style)

Try this:

var title = "This is your title";

var shortText = jQuery.trim(title).substring(0, 10)
    .split(" ").slice(0, -1).join(" ") + "...";

And you can also use a plugin:

As a extension of String

String.prototype.trimToLength = function(m) {
  return (this.length > m) 
    ? jQuery.trim(this).substring(0, m).split(" ").slice(0, -1).join(" ") + "..."
    : this;
};

Use as

"This is your title".trimToLength(10);

Get Hours and Minutes (HH:MM) from date

Here is syntax for showing hours and minutes for a field coming out of a SELECT statement. In this example, the SQL field is named "UpdatedOnAt" and is a DateTime. Tested with MS SQL 2014.

SELECT Format(UpdatedOnAt ,'hh:mm') as UpdatedOnAt from MyTable

I like the format that shows the day of the week as a 3-letter abbreviation, and includes the seconds:

SELECT Format(UpdatedOnAt ,'ddd hh:mm:ss') as UpdatedOnAt from MyTable

The "as UpdatedOnAt" suffix is optional. It gives you a column heading equal tot he field you were selecting to begin with.

Connection string with relative path to the database file

   <?xml version="1.0"?>  
<configuration>  
  <appSettings>  
    <!--FailIfMissing=false -->  
    <add key="DbSQLite" value="data source=|DataDirectory|DB.db3;Pooling=true;FailIfMissing=false"/>  
  </appSettings>  
</configuration>  

Compare two date formats in javascript/jquery

As in your example, the fit_start_time is not later than the fit_end_time.

Try it the other way round:

var fit_start_time  = $("#fit_start_time").val(); //2013-09-5
var fit_end_time    = $("#fit_end_time").val(); //2013-09-10

if(Date.parse(fit_start_time) <= Date.parse(fit_end_time)){
    alert("Please select a different End Date.");
}

Update

Your code implies that you want to see the alert with the current variables you have. If this is the case then the above code is correct. If you're intention (as per the implication of the alert message) is to make sure their fit_start_time variable is a date that is before the fit_end_time, then your original code is fine, but the data you're getting from the jQuery .val() methods is not parsing correctly. It would help if you gave us the actual HTML which the selector is sniffing at.

Nodemailer with Gmail and NodeJS

For me is working this way, using port and security (I had issues to send emails from gmail using PHP without security settings)

I hope will help someone.

var sendEmail = function(somedata){
  var smtpConfig = {
    host: 'smtp.gmail.com',
    port: 465,
    secure: true, // use SSL, 
                  // you can try with TLS, but port is then 587
    auth: {
      user: '***@gmail.com', // Your email id
      pass: '****' // Your password
    }
  };

  var transporter = nodemailer.createTransport(smtpConfig);
  // replace hardcoded options with data passed (somedata)
  var mailOptions = {
    from: '[email protected]', // sender address
    to: '[email protected]', // list of receivers
    subject: 'Test email', // Subject line
    text: 'this is some text', //, // plaintext body
    html: '<b>Hello world ?</b>' // You can choose to send an HTML body instead
  }

  transporter.sendMail(mailOptions, function(error, info){
    if(error){
      return false;
    }else{
      console.log('Message sent: ' + info.response);
      return true;
    };
  });
}

exports.contact = function(req, res){
   // call sendEmail function and do something with it
   sendEmail(somedata);
}

all the config are listed here (including examples)

Why does multiplication repeats the number several times?

I think you're confused about types here. You'll only get that result if you're multiplying a string. Start the interpreter and try this:

>>> print "1" * 9
111111111
>>> print 1 * 9
9
>>> print int("1") * 9
9

So make sure the first operand is an integer (and not a string), and it will work.

fatal: git-write-tree: error building trees

I used:

 git reset --hard

I lost some changes, but this is ok.

How to convert data.frame column from Factor to numeric

breast$class <- as.numeric(as.character(breast$class))

If you have many columns to convert to numeric

indx <- sapply(breast, is.factor)
breast[indx] <- lapply(breast[indx], function(x) as.numeric(as.character(x)))

Another option is to use stringsAsFactors=FALSE while reading the file using read.table or read.csv

Just in case, other options to create/change columns

 breast[,'class'] <- as.numeric(as.character(breast[,'class']))

or

 breast <- transform(breast, class=as.numeric(as.character(breast)))

What is 'Currying'?

Currying is a transformation that can be applied to functions to allow them to take one less argument than previously.

For example, in F# you can define a function thus:-

let f x y z = x + y + z

Here function f takes parameters x, y and z and sums them together so:-

f 1 2 3

Returns 6.

From our definition we can can therefore define the curry function for f:-

let curry f = fun x -> f x

Where 'fun x -> f x' is a lambda function equivilent to x => f(x) in C#. This function inputs the function you wish to curry and returns a function which takes a single argument and returns the specified function with the first argument set to the input argument.

Using our previous example we can obtain a curry of f thus:-

let curryf = curry f

We can then do the following:-

let f1 = curryf 1

Which provides us with a function f1 which is equivilent to f1 y z = 1 + y + z. This means we can do the following:-

f1 2 3

Which returns 6.

This process is often confused with 'partial function application' which can be defined thus:-

let papply f x = f x

Though we can extend it to more than one parameter, i.e.:-

let papply2 f x y = f x y
let papply3 f x y z = f x y z
etc.

A partial application will take the function and parameter(s) and return a function that requires one or more less parameters, and as the previous two examples show is implemented directly in the standard F# function definition so we could achieve the previous result thus:-

let f1 = f 1
f1 2 3

Which will return a result of 6.

In conclusion:-

The difference between currying and partial function application is that:-

Currying takes a function and provides a new function accepting a single argument, and returning the specified function with its first argument set to that argument. This allows us to represent functions with multiple parameters as a series of single argument functions. Example:-

let f x y z = x + y + z
let curryf = curry f
let f1 = curryf 1
let f2 = curryf 2
f1 2 3
6
f2 1 3
6

Partial function application is more direct - it takes a function and one or more arguments and returns a function with the first n arguments set to the n arguments specified. Example:-

let f x y z = x + y + z
let f1 = f 1
let f2 = f 2
f1 2 3
6
f2 1 3
6

converting drawable resource image into bitmap

In res/drawable folder,

1. Create a new Drawable Resources.

2. Input file name.

A new file will be created inside the res/drawable folder.

Replace this code inside the newly created file and replace ic_action_back with your drawable file name.

<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/ic_action_back"
    android:tint="@color/color_primary_text" />

Now, you can use it with Resource ID, R.id.filename.

How can I disable mod_security in .htaccess file?

In .htaccess file at site root directory edit following line:

_x000D_
_x000D_
<ifmodule mod_security.c>_x000D_
_x000D_
SecFilterEngine Off_x000D_
SecFilterScanPOST Off_x000D_
_x000D_
</ifmodule>_x000D_
_x000D_
<IfModule mod_rewrite.c>_x000D_
RewriteEngine On_x000D_
RewriteBase /_x000D_
RewriteCond %{REQUEST_FILENAME} !-f_x000D_
RewriteCond %{REQUEST_FILENAME} !-d_x000D_
RewriteRule . /index.php [L]_x000D_
</IfModule>
_x000D_
_x000D_
_x000D_

Just keep the mod_security rules like SecFilterEngine and parts apart from each other. Its works for apache server

MySQL error 1241: Operand should contain 1 column(s)

Syntax error, remove the ( ) from select.

insert into table2 (name, subject, student_id, result)
select name, subject, student_id, result
from table1;

Where are include files stored - Ubuntu Linux, GCC

gcc is a rich and complex "orchestrating" program that calls many other programs to perform its duties. For the specific purpose of seeing where #include "goo" and #include <zap> will search on your system, I recommend:

$ touch a.c
$ gcc -v -E a.c
 ...
#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/gcc/i686-apple-darwin9/4.0.1/include
 /usr/include
 /System/Library/Frameworks (framework directory)
 /Library/Frameworks (framework directory)
End of search list.
# 1 "a.c"

This is one way to see the search lists for included files, including (if any) directories into which #include "..." will look but #include <...> won't. This specific list I'm showing is actually on Mac OS X (aka Darwin) but the commands I recommend will show you the search lists (as well as interesting configuration details that I've replaced with ... here;-) on any system on which gcc runs properly.

Combine [NgStyle] With Condition (if..else)

You can use this as follows:

<div [style.background-image]="value ? 'url(' + imgLink + ')' : 'url(' + defaultLink + ')'"></div>

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

Bart Kiers, your regex has a couple issues. The best way to do that is this:

(.*[a-z].*)       // For lower cases
(.*[A-Z].*)       // For upper cases
(.*\d.*)          // For digits

In this way you are searching no matter if at the beginning, at the end or at the middle. In your have I have a lot of troubles with complex passwords.

Javascript Date Validation ( DD/MM/YYYY) & Age Checking

It is two problems - is the slashes the right places and is it a valid date. I would suggest you catch input changes and put the slashes in yourself. (annoying for the user)

The interesting problem is whether they put in a valid date and I would suggest exploiting how flexible js is:

_x000D_
_x000D_
function isValidDate(str) {_x000D_
  var newdate = new Date();_x000D_
  var yyyy = 2000 + Number(str.substr(4, 2));_x000D_
  var mm = Number(str.substr(2, 2)) - 1;_x000D_
  var dd = Number(str.substr(0, 2));_x000D_
  newdate.setFullYear(yyyy);_x000D_
  newdate.setMonth(mm);_x000D_
  newdate.setDate(dd);_x000D_
  return dd == newdate.getDate() && mm == newdate.getMonth() && yyyy == newdate.getFullYear();_x000D_
}_x000D_
console.log(isValidDate('jk'));//false_x000D_
console.log(isValidDate('290215'));//false_x000D_
console.log(isValidDate('290216'));//true_x000D_
console.log(isValidDate('292216'));//false
_x000D_
_x000D_
_x000D_

Cannot Resolve Collation Conflict

The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.

When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.

Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:

http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database

Update Collation of all fields in database on the fly

http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx

If you need to have different collation on two objects or can't change collations - you can still JOIN between them using COLLATE command, and choosing the collation you want for join.

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS 

or using default database collation:

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT

Angular 4 - get input value

HTML Component

<input type="text" [formControl]="txtValue">

TS Component

public txtValue = new FormControl('', { validators:[Validators.required] });

We can use this method to save using API. LearnersModules is the module file on our Angular files SaveSampleExams is the service file is one function method.

>  this.service.SaveSampleExams(LearnersModules).subscribe(
>             (data) => {
>               this.dataSaved = true;
>               LearnersModules.txtValue = this.txtValue.value; 
>              });

How do I connect to a MySQL Database in Python?

Try using MySQLdb. MySQLdb only supports Python 2.

There is a how to page here: http://www.kitebird.com/articles/pydbapi.html


From the page:

# server_version.py - retrieve and display database server version

import MySQLdb

conn = MySQLdb.connect (host = "localhost",
                        user = "testuser",
                        passwd = "testpass",
                        db = "test")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()

What is the difference between Promises and Observables?

Both Promises and Observables help us dealing with asynchronous operations. They can call certain callbacks when these asynchronous operations are done.

Angular uses Observables which is from RxJS instead of promises for dealing with HTTP

Below are some important differences in promises & Observables.

difference between Promises and Observables

Remove json element

Try this following

var myJSONObject ={"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
console.log(myJSONObject);
console.log(myJSONObject.ircEvent);
delete myJSONObject.ircEvent 
delete myJSONObject.regex 
console.log(myJSONObject);

how to check for datatype in node js- specifically for integer

If you want to know if "1" ou 1 can be casted to a number, you can use this code :

if (isNaN(i*1)) {
     console.log('i is not a number'); 
}

Google Maps API: open url by clicking on marker

the previous answers didn't work out for me well. I had persisting problems by setting the marker. So i changed the code slightly.

   <!DOCTYPE html>
   <html>
   <head>
     <meta http-equiv="content-type" content="text/html; charset=ANSI" />
     <title>Google Maps Multiple Markers</title>
     <script src="http://maps.google.com/maps/api/js?sensor=false"
      type="text/javascript"></script>
   </head>
   <body>
     <div id="map" style="width: 1500px; height: 1000px;"></div>

     <script type="text/javascript">
       var locations = [
         ['Goettingen',  51.54128040000001,  9.915803500000038, 'http://www.google.de'],
         ['Kassel', 51.31271139999999,  9.479746100000057,0, 'http://www.stackoverflow.com'],
         ['Witzenhausen', 51.33996819999999,  9.855564299999969,0, 'www.http://developer.mozilla.org.de']

 ];

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 10,
 center: new google.maps.LatLng(51.54376, 9.910419999999931),
 mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();

var marker, i;

for (i = 0; i < locations.length; i++) {
  marker = new google.maps.Marker({
   position: new google.maps.LatLng(locations[i][1], locations[i][2]),
   map: map,
   url: locations[i][4]
  });

 google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
   return function() {
     infowindow.setContent(locations[i][0]);
     infowindow.open(map, marker);
   }
 })(marker, i));

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
   return function() {
     infowindow.setContent(locations[i][0]);
     infowindow.open(map, marker);
     window.location.href = this.url;
   }
 })(marker, i));

    }

     </script>
   </body>
   </html>

This way worked out for me! You can create Google Maps routing links from your Datebase to to use it as an interactive routing map.

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

You can use Oracle.ManagedDataAccess.dll instead (download from Oracle), include that dll in you project bin dir, add reference to that dll in the project. In code, "using Oracle.MangedDataAccess.Client". Deploy project to server as usual. No need install Oracle Client on server. No need to add assembly info in web.config.

jquery getting post action url

Try this ocde;;

var formAction = $("#signup").attr('action');

How do I block comment in Jupyter notebook?

Fn + Cmd + / in Safari browser on MacOS

Apache: client denied by server configuration

This code worked for me..

 <Location />
Allow from all
Order Deny,Allow
</Location> 

Hope this helps others

Apache - MySQL Service detected with wrong path. / Ports already in use

hello i have had same problem an i did the steps with tommer and the problem solved thank you

note :

you don't have to go to that like just do this ;

1)-- Edit your “my.ini” file in c:\xampp\mysql\bin\ Change all default 3306 port entries to a new value 3308

2)--edit your “php.ini” in c:\xampp\php and replace 3306 by 3308

3)--Create the service entry - in Windows command line type

sc.exe create "mysqlweb" binPath= "C:\xampp\mysql\bin\mysqld.exe --defaults-file=c:\xampp\mysql\bin\my.ini mysqlweb"

4)--Open Windows Services and set Startup Type: Automatic, Start the service

Should I use scipy.pi, numpy.pi, or math.pi?

One thing to note is that not all libraries will use the same meaning for pi, of course, so it never hurts to know what you're using. For example, the symbolic math library Sympy's representation of pi is not the same as math and numpy:

import math
import numpy
import scipy
import sympy

print(math.pi == numpy.pi)
> True
print(math.pi == scipy.pi)
> True
print(math.pi == sympy.pi)
> False

Complete list of reasons why a css file might not be working

If your URL is working and loads the file correctly, and you've said that adding the correct

<link rel="stylesheet" type="text/css" href="yourlink.css">

code doesn't fix it, then the only other problem is that's it's an error in the actual .css file. And to advise you on that, we'd need to see the file.

What you can do though is write one basic <div> tag into your HTML, add in a basic CSS rule into your existing file, then see if you can influence this tag with your new CSS rule.

Check whether an input string contains a number in javascript

It's not bulletproof by any means, but it worked for my purposes and maybe it will help someone.

var value = $('input').val();
 if(parseInt(value)) {
  console.log(value+" is a number.");
 }
 else {
  console.log(value+" is NaN.");
 }

Setting Custom ActionBar Title from Fragment

In your MainActivity, under onCreate:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

And in your fragment activity under onResume:

getActivity().setTitle(R.string.app_name_science);

Optional:- if they show warning of null reference

Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);


Objects.requireNonNull(getActivity()).setTitle(R.string.app_name_science);

Not connecting to SQL Server over VPN

Make sure SQL Server is enabled for TCP/IP (someone may have disabled it)?

This will also help you to check/verify the port number the SQL instance is using (in case someone changed it from the default of port 1433).

Obviously port 1433 (or whatever port SQL is listening on) needs to be unblocked by any firewalls between your machine and the box SQL is running on.

To check SQL's network configuration (requires SQL Server Client Tools installed): Start -> Programs -> SQL Server 200x -> Configuration Tools -> SQL Server Configuration Manager

Connect to the machine you need then expand the Tree Item (LHS) "SQL Server Network Configuration", then pick instance. You should have four options - Shared Memory, Named Pipes, TCP/IP and VIA. You can check that TCP/IP is enabled in the RHS window.

If you double click TCP/IP and hit the "Advanced" tab, you can also view the Port number.

Other thoughts.. Are you using SQL Authentication or Windows (Domain) authentication?

  • If SQL Authentication (which I assume you are using given you said username and password), are you sure the SQL instance you're connecting to has mixed mode authentication enabled? If not, you have to connect as Administrator and change the default security settings to allow SQL authentication.

  • If Windows Authentication, could your network be using Kerberos potentially? One would think the VPN credentials would be used for the handshake. I'd check your account has appropriate login rights.

Disable scrolling on `<input type=number>`

While trying to solve this for myself, I noticed that it's actually possible to retain the scrolling of the page and focus of the input while disabling number changes by attempting to re-fire the caught event on the parent element of the <input type="number"/> on which it was caught, simply like this:

e.target.parentElement.dispatchEvent(e);

However, this causes an error in browser console, and is probably not guaranteed to work everywhere (I only tested on Firefox), since it is intentionally invalid code.

Another solution which works nicely at least on Firefox and Chromium is to temporarily make the <input> element readOnly, like this:

function handleScroll(e) {
  if (e.target.tagName.toLowerCase() === 'input'
    && (e.target.type === 'number')
    && (e.target === document.activeElement)
    && !e.target.readOnly
  ) {
      e.target.readOnly = true;
      setTimeout(function(el){ el.readOnly = false; }, 0, e.target);
  }
}
document.addEventListener('wheel', function(e){ handleScroll(e); });

One side effect that I've noticed is that it may cause the field to flicker for a split-second if you have different styling for readOnly fields, but for my case at least, this doesn't seem to be an issue.

Similarly, (as explained in James' answer) instead of modifying the readOnly property, you can blur() the field and then focus() it back, but again, depending on styles in use, some flickering might occur.

Alternatively, as mentioned in other comments here, you can just call preventDefault() on the event instead. Assuming that you only handle wheel events on number inputs which are in focus and under the mouse cursor (that's what the three conditions above signify), negative impact on user experience would be close to none.

“Unable to find manifest signing certificate in the certificate store” - even when add new key

Try this: Right click on your project -> Go to properties -> Click signing which is left side of the screen -> Uncheck the Sign the click once manifests -> Save & Build

What is the default boolean value in C#?

The default value is indeed false.

However you can't use a local variable is it's not been assigned first.

You can use the default keyword to verify:

bool foo = default(bool);
if (!foo) { Console.WriteLine("Default is false"); }

Quicksort with Python

def quicksort(items):
    if not len(items) > 1:
        return items
    items, pivot = partition(items)
    return quicksort(items[:pivot]) + [items[pivot]] + quicksort(items[pivot + 1:])


def partition(items):
    i = 1
    pivot = 0
    for j in range(1, len(items)):
        if items[j] <= items[pivot]:
            items[i], items[j] = items[j], items[i]
            i += 1
    items[i - 1], items[pivot] = items[pivot], items[i - 1]
    return items, i - 1

Get bitcoin historical data

In case, you would like to collect bitstamp trade data form their websocket in higher resolution over longer time period you could use script log_bitstamp_trades.py below.

The script uses python websocket-client and pusher_client_python libraries, so install them.

#!/usr/bin/python

import pusherclient
import time
import logging
import sys
import datetime
import signal
import os

logging.basicConfig()
log_file_fd = None

def sigint_and_sigterm_handler(signal, frame):
    global log_file_fd
    log_file_fd.close()
    sys.exit(0)


class BitstampLogger:

    def __init__(self, log_file_path, log_file_reload_path, pusher_key, channel, event):
        self.channel = channel
        self.event = event
        self.log_file_fd = open(log_file_path, "a")
        self.log_file_reload_path = log_file_reload_path
        self.pusher = pusherclient.Pusher(pusher_key)
        self.pusher.connection.logger.setLevel(logging.WARNING)
        self.pusher.connection.bind('pusher:connection_established', self.connect_handler)
        self.pusher.connect()

    def callback(self, data):
        utc_timestamp = time.mktime(datetime.datetime.utcnow().timetuple())
        line = str(utc_timestamp) + " " + data + "\n"
        if os.path.exists(self.log_file_reload_path):
            os.remove(self.log_file_reload_path)
            self.log_file_fd.close()
            self.log_file_fd = open(log_file_path, "a")
        self.log_file_fd.write(line)

    def connect_handler(self, data):
        channel = self.pusher.subscribe(self.channel)
        channel.bind(self.event, self.callback)


def main(log_file_path, log_file_reload_path):
    global log_file_fd
    bitstamp_logger = BitstampLogger(
        log_file_path,
        log_file_reload_path,
        "de504dc5763aeef9ff52",
        "live_trades",
        "trade")
    log_file_fd = bitstamp_logger.log_file_fd
    signal.signal(signal.SIGINT, sigint_and_sigterm_handler)
    signal.signal(signal.SIGTERM, sigint_and_sigterm_handler)
    while True:
        time.sleep(1)


if __name__ == '__main__':
    log_file_path = sys.argv[1]
    log_file_reload_path = sys.argv[2]
    main(log_file_path, log_file_reload_path

and logrotate file config

/mnt/data/bitstamp_logs/bitstamp-trade.log
{
    rotate 10000000000
    minsize 10M
    copytruncate
    missingok
    compress
    postrotate
        touch /mnt/data/bitstamp_logs/reload_log > /dev/null
    endscript
}

then you can run it on background

nohup ./log_bitstamp_trades.py /mnt/data/bitstamp_logs/bitstamp-trade.log /mnt/data/bitstamp_logs/reload_log &

Difference between spring @Controller and @RestController annotation

THE new @RestController annotation in Spring4+, which marks the class as a controller where every method returns a domain object instead of a view. It’s shorthand for @Controller and @ResponseBody rolled together.

How to fill DataTable with SQL Table

You can make method which return the datatable of given sql query:

public DataTable GetDataTable()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
conn.Open();
string query = "SELECT * FROM [EventOne] ";

SqlCommand cmd = new SqlCommand(query, conn);

DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
    a.Fill(t1);
}
return t1;
}

and now can be used like this:

table = GetDataTable();

Send push to Android by C# using FCM (Firebase Cloud Messaging)

Here's the code for server side firebase cloud request from C# / Asp.net.
Please note that your client side should have same topic.
e.g.

FirebaseMessaging.getInstance().subscribeToTopic("news");

public String SendNotificationFromFirebaseCloud()
{
    var result = "-1";
    var webAddr = "https://fcm.googleapis.com/fcm/send";

    var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Headers.Add("Authorization:key=" + YOUR_FIREBASE_SERVER_KEY);
    httpWebRequest.Method = "POST";

    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = "{\"to\": \"/topics/news\",\"data\": {\"message\": \"This is a Firebase Cloud Messaging Topic Message!\",}}";


        streamWriter.Write(json);
        streamWriter.Flush();
    }

    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        result = streamReader.ReadToEnd();
    }

    return result;
}

Where does Internet Explorer store saved passwords?

I found the answer. IE stores passwords in two different locations based on the password type:

  • Http-Auth: %APPDATA%\Microsoft\Credentials, in encrypted files
  • Form-based: HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IntelliForms\Storage2, encrypted with the url

From a very good page on NirSoft.com:

Starting from version 7.0 of Internet Explorer, Microsoft completely changed the way that passwords are saved. In previous versions (4.0 - 6.0), all passwords were saved in a special location in the Registry known as the "Protected Storage". In version 7.0 of Internet Explorer, passwords are saved in different locations, depending on the type of password. Each type of passwords has some limitations in password recovery:

  • AutoComplete Passwords: These passwords are saved in the following location in the Registry: HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IntelliForms\Storage2 The passwords are encrypted with the URL of the Web sites that asked for the passwords, and thus they can only be recovered if the URLs are stored in the history file. If you clear the history file, IE PassView won't be able to recover the passwords until you visit again the Web sites that asked for the passwords. Alternatively, you can add a list of URLs of Web sites that requires user name/password into the Web sites file (see below).

  • HTTP Authentication Passwords: These passwords are stored in the Credentials file under Documents and Settings\Application Data\Microsoft\Credentials, together with login passwords of LAN computers and other passwords. Due to security limitations, IE PassView can recover these passwords only if you have administrator rights.

In my particular case it answers the question of where; and I decided that I don't want to duplicate that. I'll continue to use CredRead/CredWrite, where the user can manage their passwords from within an established UI system in Windows.

Easiest way to convert int to string in C++

It would be easier using stringstreams:

#include <sstream>

int x = 42;          // The integer
string str;          // The string
ostringstream temp;  // 'temp' as in temporary
temp << x;
str = temp.str();    // str is 'temp' as string

Or make a function:

#include <sstream>

string IntToString(int a)
{
    ostringstream temp;
    temp << a;
    return temp.str();
}

How to join multiple collections with $lookup in mongodb

You can actually chain multiple $lookup stages. Based on the names of the collections shared by profesor79, you can do this :

db.sivaUserInfo.aggregate([
    {
        $lookup: {
           from: "sivaUserRole",
           localField: "userId",
           foreignField: "userId",
           as: "userRole"
        }
    },
    {
        $unwind: "$userRole"
    },
    {
        $lookup: {
            from: "sivaUserInfo",
            localField: "userId",
            foreignField: "userId",
            as: "userInfo"
        }
    },
    {
        $unwind: "$userInfo"
    }
])

This will return the following structure :

{
    "_id" : ObjectId("56d82612b63f1c31cf906003"),
    "userId" : "AD",
    "phone" : "0000000000",
    "userRole" : {
        "_id" : ObjectId("56d82612b63f1c31cf906003"),
        "userId" : "AD",
        "role" : "admin"
    },
    "userInfo" : {
        "_id" : ObjectId("56d82612b63f1c31cf906003"),
        "userId" : "AD",
        "phone" : "0000000000"
    }
}

Maybe this could be considered an anti-pattern because MongoDB wasn't meant to be relational but it is useful.

Converting HTML to PDF using PHP?

If you wish to create a pdf from php, pdflib will help you (as some others suggested).

Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.

So, the options I know are:

DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.

HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.

Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:

wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.

htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.

Add a auto increment primary key to existing table in oracle

Say your table is called t1 and your primary-key is called id
First, create the sequence:

create sequence t1_seq start with 1 increment by 1 nomaxvalue; 

Then create a trigger that increments upon insert:

create trigger t1_trigger
before insert on t1
for each row
   begin
     select t1_seq.nextval into :new.id from dual;
   end;

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

How to run Gulp tasks sequentially one after the other

Simply make coffee depend on clean, and develop depend on coffee:

gulp.task('coffee', ['clean'], function(){...});
gulp.task('develop', ['coffee'], function(){...});

Dispatch is now serial: cleancoffeedevelop. Note that clean's implementation and coffee's implementation must accept a callback, "so the engine knows when it'll be done":

gulp.task('clean', function(callback){
  del(['dist/*'], callback);
});

In conclusion, below is a simple gulp pattern for a synchronous clean followed by asynchronous build dependencies:

//build sub-tasks
gulp.task('bar', ['clean'], function(){...});
gulp.task('foo', ['clean'], function(){...});
gulp.task('baz', ['clean'], function(){...});
...

//main build task
gulp.task('build', ['foo', 'baz', 'bar', ...], function(){...})

Gulp is smart enough to run clean exactly once per build, no matter how many of build's dependencies depend on clean. As written above, clean is a synchronization barrier, then all of build's dependencies run in parallel, then build runs.

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

Really the format can be quite simple - sometimes there's no need to predefine a temp table - it will be created from results of the select.

Select FieldA...FieldN 
into #MyTempTable 
from MyTable

So unless you want different types or are very strict on definition, keep things simple. Note also that any temporary table created inside a stored procedure is automatically dropped when the stored procedure finishes executing. If stored procedure A creates a temp table and calls stored procedure B, then B will be able to use the temporary table that A created.

However, it's generally considered good coding practice to explicitly drop every temporary table you create anyway.

Why I got " cannot be resolved to a type" error?

for some reason, my.demo.service has the same level as src/ in eclise project explorer view. After I move my.demo.service under src/, it is fine. Seems I should not create new package in "Project Explorer" view in Eclipse...

But thank you for your response:)

ASP.Net which user account running Web Service on IIS 7?

I had a ton of trouble with this and then found a great solution:

Create a file in a text editor called whoami.php with the below code as it's content, save the file and upload it to public_html (or whatever you root of your webserver directory is named). It should output a useful string that you can use to track down the user the webserver is running as, my output was "php is running as user: nt authority\iusr" which allowed me to track down the permissions I needed to modify to the user "IUSR".

<?php
  // outputs the username that owns the running php/httpd process
  // (on a system with the "whoami" executable in the path)
  echo 'php is running as user: ' . exec('whoami');
?>

PowerShell try/catch/finally

-ErrorAction Stop is changing things for you. Try adding this and see what you get:

Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception" 
$error[0]
}

How to send JSON instead of a query string with $.ajax?

While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!

Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:

 var data = {USER : localProfile,  
        INSTANCE : "HTHACKNEY",  
        PAGE : $('select[name="PAGE"]').val(), 
        TITLE : $("input[name='TITLE']").val(), 
        HTML : html,
        STARTDATE : $("input[name='STARTDATE']").val(), 
        ENDDATE : $("input[name='ENDDATE']").val(),
        ARCHIVE : $("input[name='ARCHIVE']").val(), 
        ACTIVE : $("input[name='ACTIVE']").val(), 
        URGENT : $("input[name='URGENT']").val(), 
        AUTHLST :  authStr};
        //console.log(data);
       $.ajax({
            type: "POST",
           url:   "http://www.domian.com/webservicepgm?callback=?",
           data:  data,
           dataType:'jsonp'
       }).
       done(function(data){
         //handle data.WHATEVER
       });

Simplest way to download and unzip files in Node.js cross-platform?

I was looking forward this for a long time, and found no simple working example, but based on these answers I created the downloadAndUnzip() function.

The usage is quite simple:

downloadAndUnzip('http://your-domain.com/archive.zip', 'yourfile.xml')
    .then(function (data) {
        console.log(data); // unzipped content of yourfile.xml in root of archive.zip
    })
    .catch(function (err) {
        console.error(err);
    });

And here is the declaration:

var AdmZip = require('adm-zip');
var request = require('request');

var downloadAndUnzip = function (url, fileName) {

    /**
     * Download a file
     * 
     * @param url
     */
    var download = function (url) {
        return new Promise(function (resolve, reject) {
            request({
                url: url,
                method: 'GET',
                encoding: null
            }, function (err, response, body) {
                if (err) {
                    return reject(err);
                }
                resolve(body);
            });
        });
    };

    /**
     * Unzip a Buffer
     * 
     * @param buffer
     * @returns {Promise}
     */
    var unzip = function (buffer) {
        return new Promise(function (resolve, reject) {

            var resolved = false;

            var zip = new AdmZip(buffer);
            var zipEntries = zip.getEntries(); // an array of ZipEntry records

            zipEntries.forEach(function (zipEntry) {
                if (zipEntry.entryName == fileName) {
                    resolved = true;
                    resolve(zipEntry.getData().toString('utf8'));
                }
            });

            if (!resolved) {
                reject(new Error('No file found in archive: ' + fileName));
            }
        });
    };


    return download(url)
        .then(unzip);
};

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.List<string>

I think the answers are below

List<string> aa = (from char c in source
                    select c.ToString() ).ToList();

List<string> aa2 = (from char c1 in source
                    from char c2 in source
                    select string.Concat(c1, ".", c2)).ToList();

How to create a box when mouse over text in pure CSS?

You can easily make this CSS Tool Tip through simple code :-

    <!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
a.info{
    position:relative; /*this is the key*/
    color:#000;
    top:100px;
    left:50px;
    text-decoration:none;
    text-align:center;
  }



a.info span{display: none}

a.info:hover span{ /*the span will display just on :hover state*/
    display:block;
    position:absolute;
    top:-60px;
    width:15em;
    border:5px solid #0cf;
    background-color:#cff; color:#000;
    text-align: center;
    padding:10px;
  }

  a.info:hover span:after{ /*the span will display just on :hover state*/
    content:'';
    position:absolute;
    bottom:-11px;
    width:10px;
    height:10px;
    border-bottom:5px solid #0cf;
    border-right:5px solid #0cf;
    background:#cff;
    left:50%;
    margin-left:-5px;
    -moz-transform:rotate(45deg);
    -webkit-transform:rotate(45deg);
    transform:rotate(45deg);
  }


</style>
</head>
<body>
<a href="#" class="info">Shailender Arora <span>TOOLTIP</span></a>
  </div>
</body>
</html>

http://jsbin.com/ebucoz/25/edit

Variably modified array at file scope

It is also possible to use enumeration.

typedef enum {
    typeNo1 = 1,
    typeNo2,
    typeNo3,
    typeNo4,
    NumOfTypes = typeNo4
}  TypeOfSomething;

How to create JSON object Node.js

What I believe you're looking for is a way to work with arrays as object values:

var o = {} // empty Object
var key = 'Orientation Sensor';
o[key] = []; // empty Array, which you can push() values into


var data = {
    sampleTime: '1450632410296',
    data: '76.36731:3.4651554:0.5665419'
};
var data2 = {
    sampleTime: '1450632410296',
    data: '78.15431:0.5247617:-0.20050584'
};
o[key].push(data);
o[key].push(data2);

This is standard JavaScript and not something NodeJS specific. In order to serialize it to a JSON string you can use the native JSON.stringify:

JSON.stringify(o);
//> '{"Orientation Sensor":[{"sampleTime":"1450632410296","data":"76.36731:3.4651554:0.5665419"},{"sampleTime":"1450632410296","data":"78.15431:0.5247617:-0.20050584"}]}'

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

Spring Boot: Is it possible to use external application.properties files in arbitrary directories with a fat jar?

This may be coming in Late but I think I figured out a better way to load external configurations especially when you run your spring-boot app using java jar myapp.war instead of @PropertySource("classpath:some.properties")

The configuration would be loaded form the root of the project or from the location the war/jar file is being run from

public class Application implements EnvironmentAware {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void setEnvironment(Environment environment) {
        //Set up Relative path of Configuration directory/folder, should be at the root of the project or the same folder where the jar/war is placed or being run from
        String configFolder = "config";
        //All static property file names here
        List<String> propertyFiles = Arrays.asList("application.properties","server.properties");
        //This is also useful for appending the profile names
        Arrays.asList(environment.getActiveProfiles()).stream().forEach(environmentName -> propertyFiles.add(String.format("application-%s.properties", environmentName))); 
        for (String configFileName : propertyFiles) {
            File configFile = new File(configFolder, configFileName);
            LOGGER.info("\n\n\n\n");
            LOGGER.info(String.format("looking for configuration %s from %s", configFileName, configFolder));
            FileSystemResource springResource = new FileSystemResource(configFile);
            LOGGER.log(Level.INFO, "Config file : {0}", (configFile.exists() ? "FOund" : "Not Found"));
            if (configFile.exists()) {
                try {
                    LOGGER.info(String.format("Loading configuration file %s", configFileName));
                    PropertiesFactoryBean pfb = new PropertiesFactoryBean();
                    pfb.setFileEncoding("UTF-8");
                    pfb.setLocation(springResource);
                    pfb.afterPropertiesSet();
                    Properties properties = pfb.getObject();
                    PropertiesPropertySource externalConfig = new PropertiesPropertySource("externalConfig", properties);
                    ((ConfigurableEnvironment) environment).getPropertySources().addFirst(externalConfig);
                } catch (IOException ex) {
                    LOGGER.log(Level.SEVERE, null, ex);
                }
            } else {
                LOGGER.info(String.format("Cannot find Configuration file %s... \n\n\n\n", configFileName));

            }

        }
    }

}

Hope it helps.

MongoDB: Is it possible to make a case-insensitive query?

These have been tested for string searches

{'_id': /.*CM.*/}               ||find _id where _id contains   ->CM
{'_id': /^CM/}                  ||find _id where _id starts     ->CM
{'_id': /CM$/}                  ||find _id where _id ends       ->CM

{'_id': /.*UcM075237.*/i}       ||find _id where _id contains   ->UcM075237, ignore upper/lower case
{'_id': /^UcM075237/i}          ||find _id where _id starts     ->UcM075237, ignore upper/lower case
{'_id': /UcM075237$/i}          ||find _id where _id ends       ->UcM075237, ignore upper/lower case

How to secure MongoDB with username and password

The best practice to connect to mongoDB as follow:

  1. After initial installation,

    use admin

  2. Then run the following script to create admin user

    db.createUser(
     {
         user: "YourUserName",
         pwd: "YourPassword",
         roles: [
                   { role: "userAdminAnyDatabase", db: "admin" },
                   { role: "readWriteAnyDatabase", db: "admin" },
                   { role: "dbAdminAnyDatabase", db: "admin" },
                   { role: "clusterAdmin", db: "admin" }
                ]
     })

the following script will create the admin user for the DB.

  1. log into the db.admin using

    mongo -u YourUserName -p YourPassword admin

  2. After login, you can create N number of the database with same admin credential or different by repeating the 1 to 3.

This allows you to create different user and password for the different collection you creating in the MongoDB

Gradle Build Android Project "Could not resolve all dependencies" error

Go to wherever you installed Android Studio (for me it's under C:\Users\username\AppData\Local\Android\android-studio\) and open sdk\tools, then run android.bat. From here, update and download any missing build-tools and make sure you update the Android Support Repository and Android Support Library under Extras. Restart Android Studio after the SDK Manager finishes.

It seems that Android Studio completely ignores any installed Android SDK files and keeps a copy of its own. After running an update, everything compiled successfully for me using compile com.android.support:appcompat-v7:18.0.+

Duplicate headers received from server

For me the issue was about a comma not in the filename but as below: -

Response.ok(streamingOutput,MediaType.APPLICATION_OCTET_STREAM_TYPE).header("content-disposition", "attachment, filename=your_file_name").build();

I accidentally put a comma after attachment. Got it resolved by replacing comma with a semicolon.

When to catch java.lang.Error?

Very rarely.

I'd say only at the top level of a thread in order to ATTEMPT to issue a message with the reason for a thread dying.

If you are in a framework that does this sort of thing for you, leave it to the framework.

Accessing JPEG EXIF rotation data in JavaScript on the client side

Firefox 26 supports image-orientation: from-image: images are displayed portrait or landscape, depending on EXIF data. (See sethfowler.org/blog/2013/09/13/new-in-firefox-26-css-image-orientation.)

There is also a bug to implement this in Chrome.

Beware that this property is only supported by Firefox and is likely to be deprecated.

Where are the recorded macros stored in Notepad++?

You can find the shortcuts.xml in AppData\Roaming\Notepad++\ path only when using the default settings. If you have backup configured, you can find and set the path in Preferences -> Backup -> Backup path.

When these settings are applied, files in AppData directory won't be used.

Initialize a byte array to a certain value, other than the default null?

Use this to create the array in the first place:

byte[] array = Enumerable.Repeat((byte)0x20, <number of elements>).ToArray();

Replace <number of elements> with the desired array size.

Solving "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection" InvalidOperationException

The CosisEntities class is your DbContext. When you create a context in a using block, you're defining the boundaries for your data-oriented operation.

In your code, you're trying to emit the result of a query from a method and then end the context within the method. The operation you pass the result to then tries to access the entities in order to populate the grid view. Somewhere in the process of binding to the grid, a lazy-loaded property is being accessed and Entity Framework is trying to perform a lookup to obtain the values. It fails, because the associated context has already ended.

You have two problems:

  1. You're lazy-loading entities when you bind to the grid. This means that you're doing lots of separate query operations to SQL Server, which are going to slow everything down. You can fix this issue by either making the related properties eager-loaded by default, or asking Entity Framework to include them in the results of this query by using the Include extension method.

  2. You're ending your context prematurely: a DbContext should be available throughout the unit of work being performed, only disposing it when you're done with the work at hand. In the case of ASP.NET, a unit of work is typically the HTTP request being handled.

Get full query string in C# ASP.NET

This should work fine for you.

Write this code in the Page_Load event of the page.

string ID = Request.QueryString["id"].ToString();
Response.Redirect("http://www.example.com/rendernews.php?id=" + ID);

How do Mockito matchers work?

Mockito matchers are static methods and calls to those methods, which stand in for arguments during calls to when and verify.

Hamcrest matchers (archived version) (or Hamcrest-style matchers) are stateless, general-purpose object instances that implement Matcher<T> and expose a method matches(T) that returns true if the object matches the Matcher's criteria. They are intended to be free of side effects, and are generally used in assertions such as the one below.

/* Mockito */  verify(foo).setPowerLevel(gt(9000));
/* Hamcrest */ assertThat(foo.getPowerLevel(), is(greaterThan(9000)));

Mockito matchers exist, separate from Hamcrest-style matchers, so that descriptions of matching expressions fit directly into method invocations: Mockito matchers return T where Hamcrest matcher methods return Matcher objects (of type Matcher<T>).

Mockito matchers are invoked through static methods such as eq, any, gt, and startsWith on org.mockito.Matchers and org.mockito.AdditionalMatchers. There are also adapters, which have changed across Mockito versions:

  • For Mockito 1.x, Matchers featured some calls (such as intThat or argThat) are Mockito matchers that directly accept Hamcrest matchers as parameters. ArgumentMatcher<T> extended org.hamcrest.Matcher<T>, which was used in the internal Hamcrest representation and was a Hamcrest matcher base class instead of any sort of Mockito matcher.
  • For Mockito 2.0+, Mockito no longer has a direct dependency on Hamcrest. Matchers calls phrased as intThat or argThat wrap ArgumentMatcher<T> objects that no longer implement org.hamcrest.Matcher<T> but are used in similar ways. Hamcrest adapters such as argThat and intThat are still available, but have moved to MockitoHamcrest instead.

Regardless of whether the matchers are Hamcrest or simply Hamcrest-style, they can be adapted like so:

/* Mockito matcher intThat adapting Hamcrest-style matcher is(greaterThan(...)) */
verify(foo).setPowerLevel(intThat(is(greaterThan(9000))));

In the above statement: foo.setPowerLevel is a method that accepts an int. is(greaterThan(9000)) returns a Matcher<Integer>, which wouldn't work as a setPowerLevel argument. The Mockito matcher intThat wraps that Hamcrest-style Matcher and returns an int so it can appear as an argument; Mockito matchers like gt(9000) would wrap that entire expression into a single call, as in the first line of example code.

What matchers do/return

when(foo.quux(3, 5)).thenReturn(true);

When not using argument matchers, Mockito records your argument values and compares them with their equals methods.

when(foo.quux(eq(3), eq(5))).thenReturn(true);    // same as above
when(foo.quux(anyInt(), gt(5))).thenReturn(true); // this one's different

When you call a matcher like any or gt (greater than), Mockito stores a matcher object that causes Mockito to skip that equality check and apply your match of choice. In the case of argumentCaptor.capture() it stores a matcher that saves its argument instead for later inspection.

Matchers return dummy values such as zero, empty collections, or null. Mockito tries to return a safe, appropriate dummy value, like 0 for anyInt() or any(Integer.class) or an empty List<String> for anyListOf(String.class). Because of type erasure, though, Mockito lacks type information to return any value but null for any() or argThat(...), which can cause a NullPointerException if trying to "auto-unbox" a null primitive value.

Matchers like eq and gt take parameter values; ideally, these values should be computed before the stubbing/verification starts. Calling a mock in the middle of mocking another call can interfere with stubbing.

Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt()) or thenReturn(any(Foo.class)) in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.

Implementation details

Matchers are stored (as Hamcrest-style object matchers) in a stack contained in a class called ArgumentMatcherStorage. MockitoCore and Matchers each own a ThreadSafeMockingProgress instance, which statically contains a ThreadLocal holding MockingProgress instances. It's this MockingProgressImpl that holds a concrete ArgumentMatcherStorageImpl. Consequently, mock and matcher state is static but thread-scoped consistently between the Mockito and Matchers classes.

Most matcher calls only add to this stack, with an exception for matchers like and, or, and not. This perfectly corresponds to (and relies on) the evaluation order of Java, which evaluates arguments left-to-right before invoking a method:

when(foo.quux(anyInt(), and(gt(10), lt(20)))).thenReturn(true);
[6]      [5]  [1]       [4] [2]     [3]

This will:

  1. Add anyInt() to the stack.
  2. Add gt(10) to the stack.
  3. Add lt(20) to the stack.
  4. Remove gt(10) and lt(20) and add and(gt(10), lt(20)).
  5. Call foo.quux(0, 0), which (unless otherwise stubbed) returns the default value false. Internally Mockito marks quux(int, int) as the most recent call.
  6. Call when(false), which discards its argument and prepares to stub method quux(int, int) identified in 5. The only two valid states are with stack length 0 (equality) or 2 (matchers), and there are two matchers on the stack (steps 1 and 4), so Mockito stubs the method with an any() matcher for its first argument and and(gt(10), lt(20)) for its second argument and clears the stack.

This demonstrates a few rules:

  • Mockito can't tell the difference between quux(anyInt(), 0) and quux(0, anyInt()). They both look like a call to quux(0, 0) with one int matcher on the stack. Consequently, if you use one matcher, you have to match all arguments.

  • Call order isn't just important, it's what makes this all work. Extracting matchers to variables generally doesn't work, because it usually changes the call order. Extracting matchers to methods, however, works great.

    int between10And20 = and(gt(10), lt(20));
    /* BAD */ when(foo.quux(anyInt(), between10And20)).thenReturn(true);
    // Mockito sees the stack as the opposite: and(gt(10), lt(20)), anyInt().
    
    public static int anyIntBetween10And20() { return and(gt(10), lt(20)); }
    /* OK */  when(foo.quux(anyInt(), anyIntBetween10And20())).thenReturn(true);
    // The helper method calls the matcher methods in the right order.
    
  • The stack changes often enough that Mockito can't police it very carefully. It can only check the stack when you interact with Mockito or a mock, and has to accept matchers without knowing whether they're used immediately or abandoned accidentally. In theory, the stack should always be empty outside of a call to when or verify, but Mockito can't check that automatically. You can check manually with Mockito.validateMockitoUsage().

  • In a call to when, Mockito actually calls the method in question, which will throw an exception if you've stubbed the method to throw an exception (or require non-zero or non-null values). doReturn and doAnswer (etc) do not invoke the actual method and are often a useful alternative.

  • If you had called a mock method in the middle of stubbing (e.g. to calculate an answer for an eq matcher), Mockito would check the stack length against that call instead, and likely fail.

  • If you try to do something bad, like stubbing/verifying a final method, Mockito will call the real method and also leave extra matchers on the stack. The final method call may not throw an exception, but you may get an InvalidUseOfMatchersException from the stray matchers when you next interact with a mock.

Common problems

  • InvalidUseOfMatchersException:

    • Check that every single argument has exactly one matcher call, if you use matchers at all, and that you haven't used a matcher outside of a when or verify call. Matchers should never be used as stubbed return values or fields/variables.

    • Check that you're not calling a mock as a part of providing a matcher argument.

    • Check that you're not trying to stub/verify a final method with a matcher. It's a great way to leave a matcher on the stack, and unless your final method throws an exception, this might be the only time you realize the method you're mocking is final.

  • NullPointerException with primitive arguments: (Integer) any() returns null while any(Integer.class) returns 0; this can cause a NullPointerException if you're expecting an int instead of an Integer. In any case, prefer anyInt(), which will return zero and also skip the auto-boxing step.

  • NullPointerException or other exceptions: Calls to when(foo.bar(any())).thenReturn(baz) will actually call foo.bar(null), which you might have stubbed to throw an exception when receiving a null argument. Switching to doReturn(baz).when(foo).bar(any()) skips the stubbed behavior.

General troubleshooting

  • Use MockitoJUnitRunner, or explicitly call validateMockitoUsage in your tearDown or @After method (which the runner would do for you automatically). This will help determine whether you've misused matchers.

  • For debugging purposes, add calls to validateMockitoUsage in your code directly. This will throw if you have anything on the stack, which is a good warning of a bad symptom.

How to select only date from a DATETIME field in MySQL?

I solve this in my VB app with a simple tiny function (one line). Code taken out of a production app. The function looks like this:

Public Function MySQLDateTimeVar(inDate As Date, inTime As String) As String
Return "'" & inDate.ToString(format:="yyyy'-'MM'-'dd") & " " & inTime & "'"
End Function

Usage: Let's say I have DateTimePicker1 and DateTimePicker2 and the user must define a start date and an end date. No matter if the dates are the same. I need to query a DATETIME field using only the DATE. My query string is easily built like this:

Dim QueryString As String = "Select * From SOMETABLE Where SOMEDATETIMEFIELD BETWEEN " & MySQLDateTimeVar(DateTimePicker1.Value,"00:00:00") & " AND " & MySQLDateTimeVar(DateTimePicker2.Value,"23:59:59")

The function generates the correct MySQL DATETIME syntax for DATETIME fields in the query and the query returns all records on that DATE (or BETWEEN the DATES) correctly.

How to change an Android app's name?

I noticed there are some differences in how the app name can turn up in Lollipop devices. Before Lollipop, you can have different app names with this:

<application
    android:label="@string/app_name"> // appears in manage app info
    <activity
        android:name=".MainActivity"
        android:label="@string/action_bar_title"> // appears in actionbar title 
        <intent-filter android:label="@string/name_in_icon_launcher"> // appears in icon launcher
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
...

In Lollipop, it will be like this:

<application
    android:label="@string/name_in_manage_app_info">
    <activity
        android:name=".MainActivity"
        android:label="@string/name_in_actionbar_and_icon_launcher">
        <intent-filter android:label="@string/this_is_useless">
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

In Lollipop, android:label in intent-filter is basically useless, while actionbar title and icon launcher is identical. So, if you want a different title in actionbar, you have no choice but to set dynamically

getSupportActionBar().setTitle(R.string.app_name);

how to get current location in google map android

Please check the sample code for the Google Maps Android API v2. Using this will solve your problem.

private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        mMap.setMyLocationEnabled(true);
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
                @Override
                public void onMyLocationChange(Location arg0) {
                    mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
                }
            });
        }
    }
}

Call this function in onCreate function.

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

The SSL errors are often thrown by network management software such as Cyberroam.

To answer your question,

you will have to enter badidea into Chrome every time you visit a website.

You might at times have to enter it more than once, as the site may try to pull in various resources before load, hence causing multiple SSL errors

CSS 3 slide-in from left transition

You can use CSS3 transitions or maybe CSS3 animations to slide in an element.

For browser support: http://caniuse.com/

I made two quick examples just to show you how I mean.

CSS transition (on hover)

Demo One

Relevant Code

.wrapper:hover #slide {
    transition: 1s;
    left: 0;
}

In this case, Im just transitioning the position from left: -100px; to 0; with a 1s. duration. It's also possible to move the element using transform: translate();

CSS animation

Demo Two

#slide {
    position: absolute;
    left: -100px;
    width: 100px;
    height: 100px;
    background: blue;
    -webkit-animation: slide 0.5s forwards;
    -webkit-animation-delay: 2s;
    animation: slide 0.5s forwards;
    animation-delay: 2s;
}

@-webkit-keyframes slide {
    100% { left: 0; }
}

@keyframes slide {
    100% { left: 0; }
}

Same principle as above (Demo One), but the animation starts automatically after 2s, and in this case I've set animation-fill-mode to forwards, which will persist the end state, keeping the div visible when the animation ends.

Like I said, two quick example to show you how it could be done.

EDIT: For details regarding CSS Animations and Transitions see:

Animations

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations

Transitions

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions

Hope this helped.

How do I add options to a DropDownList using jQuery?

With the plugin: jQuery Selection Box. You can do this:

var myOptions = {
        "Value 1" : "Text 1",
        "Value 2" : "Text 2",
        "Value 3" : "Text 3"
    }
    $("#myselect2").addOption(myOptions, false); 

Meaning of @classmethod and @staticmethod for beginner?

Though classmethod and staticmethod are quite similar, there's a slight difference in usage for both entities: classmethod must have a reference to a class object as the first parameter, whereas staticmethod can have no parameters at all.

Example

class Date(object):

    def __init__(self, day=0, month=0, year=0):
        self.day = day
        self.month = month
        self.year = year

    @classmethod
    def from_string(cls, date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        date1 = cls(day, month, year)
        return date1

    @staticmethod
    def is_date_valid(date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        return day <= 31 and month <= 12 and year <= 3999

date2 = Date.from_string('11-09-2012')
is_date = Date.is_date_valid('11-09-2012')

Explanation

Let's assume an example of a class, dealing with date information (this will be our boilerplate):

class Date(object):

    def __init__(self, day=0, month=0, year=0):
        self.day = day
        self.month = month
        self.year = year

This class obviously could be used to store information about certain dates (without timezone information; let's assume all dates are presented in UTC).

Here we have __init__, a typical initializer of Python class instances, which receives arguments as a typical instancemethod, having the first non-optional argument (self) that holds a reference to a newly created instance.

Class Method

We have some tasks that can be nicely done using classmethods.

Let's assume that we want to create a lot of Date class instances having date information coming from an outer source encoded as a string with format 'dd-mm-yyyy'. Suppose we have to do this in different places in the source code of our project.

So what we must do here is:

  1. Parse a string to receive day, month and year as three integer variables or a 3-item tuple consisting of that variable.
  2. Instantiate Date by passing those values to the initialization call.

This will look like:

day, month, year = map(int, string_date.split('-'))
date1 = Date(day, month, year)

For this purpose, C++ can implement such a feature with overloading, but Python lacks this overloading. Instead, we can use classmethod. Let's create another "constructor".

    @classmethod
    def from_string(cls, date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        date1 = cls(day, month, year)
        return date1

date2 = Date.from_string('11-09-2012')

Let's look more carefully at the above implementation, and review what advantages we have here:

  1. We've implemented date string parsing in one place and it's reusable now.
  2. Encapsulation works fine here (if you think that you could implement string parsing as a single function elsewhere, this solution fits the OOP paradigm far better).
  3. cls is an object that holds the class itself, not an instance of the class. It's pretty cool because if we inherit our Date class, all children will have from_string defined also.

Static method

What about staticmethod? It's pretty similar to classmethod but doesn't take any obligatory parameters (like a class method or instance method does).

Let's look at the next use case.

We have a date string that we want to validate somehow. This task is also logically bound to the Date class we've used so far, but doesn't require instantiation of it.

Here is where staticmethod can be useful. Let's look at the next piece of code:

    @staticmethod
    def is_date_valid(date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        return day <= 31 and month <= 12 and year <= 3999

    # usage:
    is_date = Date.is_date_valid('11-09-2012')

So, as we can see from usage of staticmethod, we don't have any access to what the class is---it's basically just a function, called syntactically like a method, but without access to the object and its internals (fields and another methods), while classmethod does.

Why can't I make a vector of references?

boost::ptr_vector<int> will work.

Edit: was a suggestion to use std::vector< boost::ref<int> >, which will not work because you can't default-construct a boost::ref.

Python Script to convert Image into Byte array

with BytesIO() as output:
    from PIL import Image
    with Image.open(filename) as img:
        img.convert('RGB').save(output, 'BMP')                
    data = output.getvalue()[14:]

I just use this for add a image to clipboard in windows.

find -exec with multiple commands

find . -type d -exec sh -c "echo -n {}; echo -n ' x '; echo {}" \;

Same font except its weight seems different on different browsers

In order to best standardise your @font-face embedded fonts across browsers try including the below inside your @font-face declaration or on your body font styling:

speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
-webkit-font-smoothing: antialiased;

At present there looks to be no universal fix across all platforms and browser builds. As stated frequently all browsers/OS have different text rendering engines.

How to call multiple JavaScript functions in onclick event?

ES6 React

<MenuItem
  onClick={() => {
    this.props.toggleTheme();
    this.handleMenuClose();
  }}
>