Programs & Examples On #Jboss esb

Docker container not starting (docker start)

What I need is to use Docker with MariaDb on different port /3301/ on my Ubuntu machine because I already had MySql installed and running on 3306.

To do this after half day searching did it using:

docker run -it -d -p 3301:3306 -v ~/mdbdata/mariaDb:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root --name mariaDb mariadb

This pulls the image with latest MariaDb, creates container called mariaDb, and run mysql on port 3301. All data of which is located in home directory in /mdbdata/mariaDb.

To login in mysql after that can use:

mysql -u root -proot -h -P3301

Used sources are:

The answer of Iarks in this article /using -it -d was the key :) /




Good luck all!

How to count the number of files in a directory using Python

one liner and recursive:

def count_files(path):
    return sum([len(files) for _, _, files in os.walk(path)])


How to solve "The directory is not empty" error when running rmdir command in a batch script?

As @gfullam stated in a comment to @BoffinbraiN's answer, the <dir> you are deleting itself might not be the one which contains files: there might be subdirectories in <dir> that get a "The directory is not empty" message and the only solution then would be to recursively iterate over the directories, manually deleting all their containing files... I ended up deciding to use a port of rm from UNIX. rm.exe comes with Git Bash, MinGW, Cygwin, GnuWin32 and others. You just need to have its parent directory in your PATH and then execute as you would in a UNIX system.

Batch script example:

set PATH=C:\cygwin64\bin;%PATH%
rm -rf "C:\<dir>"

Python logging: use milliseconds in time format

tl;dr for folks looking here for an ISO formatted date:

instead of using something like '%Y-%m-%d %H:%M:%S.%03d%z', create your own class as @unutbu indicated. Here's one for iso date format:

import logging
from time import gmtime, strftime

class ISOFormatter(logging.Formatter):
    def formatTime(self, record, datefmt=None):
        t = strftime("%Y-%m-%dT%H:%M:%S", gmtime(record.created))
        z = strftime("%z",gmtime(record.created))
        s = "%s.%03d%s" % (t, record.msecs,z)        
        return s

logger = logging.getLogger(__name__)

console = logging.StreamHandler()

formatter = ISOFormatter(fmt='%(asctime)s - %(module)s - %(levelname)s - %(message)s')

logger.debug('Jackdaws love my big sphinx of quartz.')
#2020-10-23T17:25:48.310-0800 - <stdin> - DEBUG - Jackdaws love my big sphinx of quartz.

How to catch a specific SqlException error?

With MS SQL 2008, we can list supported error messages in the table sys.messages

SELECT * FROM sys.messages

R data formats: RData, Rda, Rds etc

Rda is just a short name for RData. You can just save(), load(), attach(), etc. just like you do with RData.

Rds stores a single R object. Yet, beyond that simple explanation, there are several differences from a "standard" storage. Probably this R-manual Link to readRDS() function clarifies such distinctions sufficiently.

So, answering your questions:

  • The difference is not about the compression, but serialization (See this page)
  • Like shown in the manual page, you may wanna use it to restore a certain object with a different name, for instance.
  • You may readRDS() and save(), or load() and saveRDS() selectively.

Error "can't load package: package my_prog: found packages my_prog and main"

Make sure that your package is installed in your $GOPATH directory or already inside your workspace/package.

For example: if your $GOPATH = "c:\go", make sure that the package inside C:\Go\src\pkgName

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

Pycharm/Python OpenCV and CV2 install error

How about try some different mirrors? If you are in China, I highly recommend you try:

sudo pip install --index opencv-contrib-python

If not, just replace the url address to some other mirrors you like! Good luck.

Show current assembly instruction in GDB

If you want the next few instructions to display automatically while stepping through the program you can use the display command as follows -

display /3i $pc

The above will display 3 instructions whenever a breakpoint is hit or when you single step the program.

More details at the blog entry here.

Could not autowire field:RestTemplate in Spring boot application

Depending on what technologies you're using and what versions will influence how you define a RestTemplate in your @Configuration class.

Spring >= 4 without Spring Boot

Simply define an @Bean:

public RestTemplate restTemplate() {
    return new RestTemplate();

Spring Boot <= 1.3

No need to define one, Spring Boot automatically defines one for you.

Spring Boot >= 1.4

Spring Boot no longer automatically defines a RestTemplate but instead defines a RestTemplateBuilder allowing you more control over the RestTemplate that gets created. You can inject the RestTemplateBuilder as an argument in your @Bean method to create a RestTemplate:

public RestTemplate restTemplate(RestTemplateBuilder builder) {
   // Do any additional configuration here

Using it in your class

private RestTemplate restTemplate;


Count number of lines in a git repository

git diff --stat 4b825dc642cb6eb9a060e54bf8d69288fbee4904

This shows the differences from the empty tree to your current working tree. Which happens to count all lines in your current working tree.

To get the numbers in your current working tree, do this:

git diff --shortstat `git hash-object -t tree /dev/null`

It will give you a string like 1770 files changed, 166776 insertions(+).

how to add json library

AFAIK the json module was added in version 2.6, see here. I'm guessing you can update your python installation to the latest stable 2.6 from this page.

How can I auto increment the C# assembly version via our CI platform (Hudson)?

This is a simpler mechanism. It simply involves the addition of a Windows Batch command task build step before the MSBuild step and the use of a simple find and replace program (FART).

The Batch Step

fart --svn -r AssemblyInfo.cs "[assembly: AssemblyVersion(\"\")]" "[assembly: AssemblyVersion(\"1.0.%BUILD_NUMBER%.%SVN_REVISION%\")]"
if %ERRORLEVEL%==0 exit /b 1
fart --svn -r AssemblyInfo.cs "[assembly: AssemblyFileVersion(\"\")]" "[assembly: AssemblyFileVersion(\"1.0.%BUILD_NUMBER%.%SVN_REVISION%\")]"
if %ERRORLEVEL%==0 exit /b 1
exit /b 0

If you are using source control other than svn change the --svn option for the appropriate one for your scm environment.

Download Fart

What's the best way to break from nested loops in JavaScript?

Quite simple:

var a = [1, 2, 3];
var b = [4, 5, 6];
var breakCheck1 = false;

for (var i in a) {
    for (var j in b) {
        breakCheck1 = true;
    if (breakCheck1) break;

Run .jar from batch-file

If you want a batch file to run a jar file, make a blank file called runjava.bat with the contents:

java -jar "C:\myjarfile.jar"

Error: Local workspace file ('angular.json') could not be found

Just run ng update @angular/cli in your console. You might find some vulnerabilities after running the command (if using npm), but then just runnpm audit fix in the console to fix them. This command will scan the project for any vulnerabilities and it will also fix compatibility issues by installing updates to these dependencies. If you do not wish to auto fix these vulnerabilities immediately, you can perform a Dry Run: by running npm audit fix --dry-run -json in the console. This will give you an idea of what the command npm audit fix will do, in the form of json in the console.

Angular @ViewChild() error: Expected 2 arguments, but got 1

Angular 8

In Angular 8, ViewChild has another param

@ViewChild('nameInput', {static: false}) component : Component

You can read more about it here and here

Angular 9 & Angular 10

In Angular 9 default value is static: false, so doesn't need to provide param unless you want to use {static: true}

How to read data from java properties file using Spring Boot

You can use @PropertySource to externalize your configuration to a properties file. There is number of way to do get properties:

1. Assign the property values to fields by using @Value with PropertySourcesPlaceholderConfigurer to resolve ${} in @Value:

public class ApplicationConfiguration {

    private String gMapReportUrl;

    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();


2. Get the property values by using Environment:

public class ApplicationConfiguration {

    private Environment env;

    public void foo() {


Hope this can help

Is it not possible to stringify an Error using JSON.stringify?

JSON.stringify(err, Object.getOwnPropertyNames(err))

seems to work

[from a comment by /u/ub3rgeek on /r/javascript] and felixfbecker's comment below

IIS7 URL Redirection from root to sub directory

Here it is. Add this code to your web.config file:

            <rule name="Root Hit Redirect" stopProcessing="true">
                <match url="^$" />
                <action type="Redirect" url="/menu_1/MainScreen.aspx" />

It will do 301 Permanent Redirect (URL will be changed in browser). If you want to have such "redirect" to be invisible (rewrite, internal redirect), then use this rule (the only difference is that "Redirect" has been replaced by "Rewrite"):

            <rule name="Root Hit Redirect" stopProcessing="true">
                <match url="^$" />
                <action type="Rewrite" url="/menu_1/MainScreen.aspx" />

Why are arrays of references illegal?

This is an interesting discussion. Clearly arrays of refs are outright illegal, but IMHO the reason why is not so simple as saying 'they are not objects' or 'they have no size'. I'd point out that arrays themselves are not full-fledged objects in C/C++ - if you object to that, try instantiating some stl template classes using an array as a 'class' template parameter, and see what happens. You can't return them, assign them, pass them as parameters. ( an array param is treated as a pointer). But it is legal to make arrays of arrays. References do have a size that the compiler can and must calculate - you can't sizeof() a reference, but you can make a struct containing nothing but references. It will have a size sufficient to contain all the pointers which implement the references. You can't instantiate such a struct without initializing all the members:

struct mys {
 int & a;
 int & b;
 int & c;
int ivar1, ivar2, arr[200];
mys my_refs = { ivar1, ivar2, arr[12] };

my_refs.a += 3  ;  // add 3 to ivar1

In fact you can add this line to the struct definition

struct mys {
 int & operator[]( int i ) { return i==0?a : i==1? b : c; }

...and now I have something which looks a LOT like an array of refs:

int ivar1, ivar2, arr[200];
mys my_refs = { ivar1, ivar2, arr[12] };

my_refs[1] = my_refs[2]  ;  // copy arr[12] to ivar2
&my_refs[0];               // gives &my_refs.a == &ivar1

Now, this is not a real array, it's an operator overload; it won't do things that arrays normally do like sizeof(arr)/sizeof(arr[0]), for instance. But it does exactly what I want an array of references to do, with perfectly legal C++. Except (a) it's a pain to set up for more than 3 or 4 elements, and (b) it's doing a calculation using a bunch of ?: which could be done using indexing (not with normal C-pointer-calculation-semantics indexing, but indexing nonetheless). I'd like to see a very limited 'array of reference' type which can actually do this. I.e. an array of references would not be treated as a general array of things which are references, but rather it would be a new 'array-of-reference' thing which effectively maps to an internally generated class similar to the one above (but which you unfortunately can't make with templates).

this would probably work, if you don't mind this kind of nasty: recast '*this' as an array of int *'s and return a reference made from one: (not recommended, but it shows how the proper 'array' would work):

 int & operator[]( int i ) { return *(reinterpret_cast<int**>(this)[i]); }

Replace "\\" with "\" in a string in C#

You can simply do a replace in your string like


how to get the ipaddress of a virtual box running on local machine

Login to virtual machine use below command to check ip address. (anyone will work)

  1. ifconfig
  2. ip addr show

If you used NAT for your virtual machine settings(your machine ip will be, then you have to use port forwarding to connect to machine. IP address will be

If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

How do I get the current location of an iframe?


You can't access cross-domain iframe location at all.

Checkbox value true/false

To return true or false depending on whether a checkbox is checked or not, I use this in JQuery

let checkState = $("#checkboxId").is(":checked") ? "true" : "false";

how to read all files inside particular folder

If you are looking to copy all the text files in one folder to merge and copy to another folder, you can do this to achieve that:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace HowToCopyTextFiles
  class Program
    static void Main(string[] args)
      string mydocpath=Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);     
      StringBuilder sb = new StringBuilder();
      foreach (string txtName in Directory.GetFiles(@"D:\Links","*.txt"))
        using (StreamReader sr = new StreamReader(txtName))
          sb.AppendLine("= = = = = =");
      using (StreamWriter outfile=new StreamWriter(mydocpath + @"\AllTxtFiles.txt"))

How to filter multiple values (OR operation) in angularJS

Here is the implementation of custom filter, which will filter the data using array of values.It will support multiple key object with both array and single value of keys. As mentioned inangularJS API AngularJS filter Doc supports multiple key filter with single value, but below custom filter will support same feature as angularJS and also supports array of values and combination of both array and single value of keys.Please find the code snippet below,

myApp.filter('filterMultiple',['$filter',function ($filter) {
return function (items, keyObj) {
    var filterObj = {
        applyFilter : function(obj,key){
            var fData = [];
            if (this.filteredData.length == 0)
                this.filteredData =;
            if (obj){
                var fObj = {};
                if (!angular.isArray(obj)){
                    fObj[key] = obj;
                    fData = fData.concat($filter('filter')(this.filteredData,fObj));
                } else if (angular.isArray(obj)){
                    if (obj.length > 0){
                        for (var i=0;i<obj.length;i++){
                            if (angular.isDefined(obj[i])){
                                fObj[key] = obj[i];
                                fData = fData.concat($filter('filter')(this.filteredData,fObj));    

                if (fData.length > 0){
                    this.filteredData = fData;
    if (keyObj){
    return filterObj.filteredData;


arrayOfObjectswithKeys | filterMultiple:{key1:['value1','value2','value3',...etc],key2:'value4',key3:[value5,value6,...etc]}

Here is a fiddle example with implementation of above "filterMutiple" custom filter. :::Fiddle Example:::

Python truncate a long string

Even shorter :

info = data[:75] + (data[75:] and '..')

PyCharm error: 'No Module' when trying to import own module (python script)

I was getting the error with "Add source roots to PYTHONPATH" as well. My problem was that I had two folders with the same name, like project/subproject1/thing/src and project/subproject2/thing/src and I had both of them marked as source root. When I renamed one of the "thing" folders to "thing1" (any unique name), it worked.

Maybe if PyCharm automatically adds selected source roots, it doesn't use the full path and hence mixes up folders with the same name.

C# ASP.NET Send Email via TLS

TLS (Transport Level Security) is the slightly broader term that has replaced SSL (Secure Sockets Layer) in securing HTTP communications. So what you are being asked to do is enable SSL.

How to draw an overlay on a SurfaceView used by Camera on Android?

Try calling setWillNotDraw(false) from surfaceCreated:

public void surfaceCreated(SurfaceHolder holder) {
    try {
    } catch (Exception e) {
        Log.d(TAG,"Surface not created");

protected void onDraw(Canvas canvas) {

    canvas.drawRect(area, rectanglePaint);
    Log.w(this.getClass().getName(), "On Draw Called");

and calling invalidate from onTouchEvent:

public boolean onTouch(View v, MotionEvent event) {

    return true;

OSX -bash: composer: command not found

On Mac OS X, for anyone having:

-bash: /usr/local/bin/composer: Permission denied

problem, while trying to move downloaded composer.phar using:

mv composer.phar /usr/local/bin/composer

this is the cause:

System Integrity Protection

and this is the solution:

  1. Reboot in recovery mode: restart you mac and hold down cmd+R.
  2. Open the terminal once recovery mode has started via Utilities>Terminal via the bar at the top.
  3. Type in csrutil disable and hit enter. You should see a msg returned saying that:

    the System Integrity Protection is off.

  4. Restart the computer as normal and then go set up composer. I had to put it in /usr/bin and NOT /usr/local/bin because for some reason it just didn't work there.
  5. Go back to recovery mode and enable System Integrity Protector by typing csrutil enable
  6. Come back in normal boot up and check that composer works. It did for me.

The above 6 steps are copied from here, so all the credit belongs to the user Vasheer there.

SQL Format as of Round off removing decimals

check the round function and how does the length argument works. It controls the behaviour of the precision of the result

How to print the contents of RDD?

If you want to view the content of a RDD, one way is to use collect():


That's not a good idea, though, when the RDD has billions of lines. Use take() to take just a few to print out:



At first glance your original attempt seems pretty close. I'm assuming that clockDate is a DateTime fields so try this:

IF (NOT EXISTS(SELECT * FROM Clock WHERE cast(clockDate as date) = '08/10/2012') 
    AND userName = 'test') 
    INSERT INTO Clock(clockDate, userName, breakOut) 
    VALUES(GetDate(), 'test', GetDate()) 
    UPDATE Clock 
    SET breakOut = GetDate()
    WHERE Cast(clockDate AS Date) = '08/10/2012' AND userName = 'test'

Note that getdate gives you the current date. If you are trying to compare to a date (without the time) you need to cast or the time element will cause the compare to fail.

If clockDate is NOT datetime field (just date), then the SQL engine will do it for you - no need to cast on a set/insert statement.

IF (NOT EXISTS(SELECT * FROM Clock WHERE clockDate = '08/10/2012') 
    AND userName = 'test') 
    INSERT INTO Clock(clockDate, userName, breakOut) 
    VALUES(GetDate(), 'test', GetDate()) 
    UPDATE Clock 
    SET breakOut = GetDate()
    WHERE clockDate = '08/10/2012' AND userName = 'test'

As others have pointed out, the merge statement is another way to tackle this same logic. However, in some cases, especially with large data sets, the merge statement can be prohibitively slow, causing a lot of tran log activity. So knowing how to logic it out as shown above is still a valid technique.

OPENSSL file_get_contents(): Failed to enable crypto

Had same problem - it was somewhere in the ca certificate, so I used the ca bundle used for curl, and it worked. You can download the curl ca bundle here:

For encryption and security issues see this helpful article:

Here is the example:

    $url = '';
    $cn_match = '';

    $data = array (     
        'apikey' => '[example api key here]',               
        'limit' => intval($limit),
        'offset' => intval($offset)

    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',                
            'content' => http_build_query($data)                
        , 'ssl' => array(
            'verify_peer' => true,
            'cafile' => [path to file] . "cacert.pem",
            'ciphers' => 'HIGH:TLSv1.2:TLSv1.1:TLSv1.0:!SSLv3:!SSLv2',
            'CN_match' => $cn_match,
            'disable_compression' => true,

    $context  = stream_context_create($options);
    $response = file_get_contents($url, false, $context);

Hope that helps

How to determine the version of android SDK installed in computer?

Type in android list target into your command line to see what android API you are using.

Repair all tables in one go

from command line you can use:

mysqlcheck -A --auto-repair

Best way to call a JSON WebService from a .NET Console

I use HttpWebRequest to GET from the web service, which returns me a JSON string. It looks something like this for a GET:

// Returns JSON string
string GET(string url) 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    try {
        WebResponse response = request.GetResponse();
        using (Stream responseStream = response.GetResponseStream()) {
            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
            return reader.ReadToEnd();
    catch (WebException ex) {
        WebResponse errorResponse = ex.Response;
        using (Stream responseStream = errorResponse.GetResponseStream())
            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
            String errorText = reader.ReadToEnd();
            // log errorText

I then use JSON.Net to dynamically parse the string. Alternatively, you can generate the C# class statically from sample JSON output using this codeplex tool:

POST looks like this:

// POST a JSON string
void POST(string url, string jsonContent) 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";

    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
    Byte[] byteArray = encoding.GetBytes(jsonContent);

    request.ContentLength = byteArray.Length;
    request.ContentType = @"application/json";

    using (Stream dataStream = request.GetRequestStream()) {
        dataStream.Write(byteArray, 0, byteArray.Length);
    long length = 0;
    try {
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
            length = response.ContentLength;
    catch (WebException ex) {
        // Log exception and throw as for GET example above

I use code like this in automated tests of our web service.

Unable to run Java code with Intellij IDEA

Last resort option when nothing else seems to work: close and reopen IntelliJ.

My issue was with reverting a Git commit, which happened to change the Java SDK configured for the Project to a no longer installed version of the JDK. But fixing that back still didn't allow me to run the program. Restarting IntelliJ fixed this

Intermediate language used in scalac?

The nearest equivalents would be icode and bcode as used by scalac, view Miguel Garcia's site on the Scalac optimiser for more information, here:

You might also consider Java bytecode itself to be your intermediate representation, given that bytecode is the ultimate output of scalac.

Or perhaps the true intermediate is something that the JIT produces before it finally outputs native instructions?

Ultimately though... There's no single place that you can point at an claim "there's the intermediate!". Scalac works in phases that successively change the abstract syntax tree, every single phase produces a new intermediate. The whole thing is like an onion, and it's very hard to try and pick out one layer as somehow being more significant than any other.

Laravel 4: Redirect to a given url

You can use different types of redirect method in laravel -

return redirect()->intended('');


return redirect()->to('');


use Illuminate\Support\Facades\Redirect;

return Redirect::to('/')->with(['type' => 'error','message' => 'Your message'])->withInput(Input::except('password'));


return redirect('/')->with(Auth::logout());


return redirect()->route('user.profile', ['step' => $step, 'id' => $id]);

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

Double.parseDouble(String) will return a primitive double type. Double.valueOf(String) will return a wrapper object of type Double.

So, for e.g.:

double d = Double.parseDouble("1");

Double d = Double.valueOf("1");

Moreover, valueOf(...) is an overloaded method. It has two variants:

  1. Double valueOf(String s)
  2. Double valueOf(double d)

Whereas parseDouble is a single method with the following signature:

  1. double parseDouble(String s)

php, mysql - Too many connections to database error

If you are reaching the mac connection limit go to /etc/my.cnf and under the [mysqld] section add max_connections = 500

and restart MySQL.

Using Lato fonts in my css (@font-face)

Well, you're missing the letter 'd' in url("~/fonts/Lato-Bol.ttf"); - but assuming that's not it, I would open up your page with developer tools in Chrome and make sure there's no errors loading any of the files (you would probably see an issue in the JavaScript console, or you can check the Network tab and see if anything is red).

(I don't see anything obviously wrong with the code you have posted above)

Other things to check: 1) Are you including your CSS file in your html above the lines where you are trying to use the font-family style? 2) What do you see in the CSS panel in the developer tools for that div? Is font-family: lato crossed out?

How to create a HTML Cancel button that redirects to a URL

Just put type="button"

<button type="button"><b>Cancel</b></button>

Because your button is inside a form it is taking default value as submit and type="cancel" doesn't exist.

Notice: Trying to get property of non-object error

This is because $pjs is an one-element-array of objects, so first you should access the array element, which is an object and then access its attributes.

echo $pjs[0]->player_name;

Actually dump result that you pasted tells it very clearly.

Two onClick actions one button

Try it:

<input type="button" value="Dont show this again! " onClick="fbLikeDump();WriteCookie();" />

Or also

function clickEvent(){
<input type="button" value="Dont show this again! " onClick="clickEvent();" />

Is there a way to automatically build the package.json file for Node.js projects

First off, run

npm init

...will ask you a few questions (read this first) about your project/package and then generate a package.json file for you.

Then, once you have a package.json file, use

npm install <pkg> --save


npm install <pkg> --save-dev install a dependency and automatically append it to your package.json's dependencies list.

(Note: You may need to manually tweak the version ranges for your dependencies.)

how to get data from selected row from datagridview

To get the cell value, you need to read it directly from DataGridView1 using e.RowIndex and e.ColumnIndex properties.


Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
   Dim value As Object = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value

   If IsDBNull(value) Then 
      TextBox1.Text = "" ' blank if dbnull values
      TextBox1.Text = CType(value, String)
   End If
End Sub

Default value in Go's method

No, the powers that be at Google chose not to support that.!topic/golang-nuts/-5MCaivW0qQ

Sheet.getRange(1,1,1,12) what does the numbers in bracket specify?

Found these docu on the google docu pages:

  • row --- int --- top row of the range
  • column --- int--- leftmost column of the range
  • optNumRows --- int --- number of rows in the range.
  • optNumColumns --- int --- number of columns in the range

In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns


Using the example on the docu:

// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);

The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G

So you come to the range: C2:G8

An App ID with Identifier '' is not available. Please enter a different string

I was having the same issue after the Xcode 7.3 update and nothing worked. The fix is really simple, please follow the answer here, it worked for me:

How do I disable Git Credential Manager for Windows?

Another option I had to use with VSTS:

git config credential.modalprompt false --global

How to read all files in a folder from Java?

package com;


 * @author ?Mukesh
public class ListFiles {

     static File mainFolder = new File("D:\\Movies");

     public static void main(String[] args)
         ListFiles lf = new ListFiles();

         long fileSize = mainFolder.length();
             System.out.println("mainFolder size in bytes is: " + fileSize);
             System.out.println("File size in KB is : " + (double)fileSize/1024);
             System.out.println("File size in MB is :" + (double)fileSize/(1024*1024));
     public void getFiles(File f){
         File files[];
             files = f.listFiles();
             for (int i = 0; i < files.length; i++) {

Remove Item from ArrayList

Try it this way,

ArrayList<String> List_Of_Array = new ArrayList<String>();

int i[] = {5,3,1};

for (int j = 0; j < i.length; j++) {

PHP Regex to get youtube video ID?

if (preg_match('![?&]{1}v=([^&]+)!', $url . '&', $m))
    $video_id = $m[1];

Text Editor For Linux (Besides Vi)?

I love TextMate on OSX.

There is a kind of TextMate clone for Windows called simply "E" ( Its author promised that there will be a Linux version soon. Even if you already picked your favourite, TextMate (or E) is worth a look, simply because it is different.

I would say that there are mainly four different families of text editors:

  • classic menubar-based editors like WinEdit, Gedit or BBEdit
  • Emacs and its brethren XEmacs, Aquamacs etc.
  • VI / Vim / Cream and the like
  • TextMate and E

You can differenciate between these families by their different paradigms of usage:

  • Classic editors rely mainly on a menubar and some Ctrl-key shortcuts.
  • Emacs-style editing uses highly sophisticated keyboard commands like C-x-s and even whole words to evoke commands.
  • VI is modebased and is operated by single-key commands or whole words.
  • TextMate is based on Snippets and classic shortcuts.

Emacs and TextMate are also easily extensible by user-created scripts in Lisp (Emacs) or any other command-line-language (TextMate). (Classic editors and VI are also extendable, but the effort is usually considerably bigger)

I would recommend that everyone tried at least one good example of each of these families (if possible) and find out what suits them best.

OR operator in switch-case?

You cannot use || operators in between 2 case. But you can use multiple case values without using a break between them. The program will then jump to the respective case and then it will look for code to execute until it finds a "break". As a result these cases will share the same code.

    case 0: 
    case 1: 
        // do stuff for if case 0 || case 1 
    // other cases 

How to extract a single value from JSON response?

using json.loads will turn your data into a python dictionary.

Dictionaries values are accessed using ['key']

resp_str = {
  "name" : "ns1:timeSeriesResponseType",
  "declaredType" : "org.cuahsi.waterml.TimeSeriesResponseType",
  "scope" : "javax.xml.bind.JAXBElement$GlobalScope",
  "value" : {
    "queryInfo" : {
      "creationTime" : 1349724919000,
      "queryURL" : "",
      "criteria" : {
        "locationParam" : "[ALL:103232434]",
        "variableParam" : "[00060, 00065]"
      "note" : [ {
        "value" : "[ALL:103232434]",
        "title" : "filter:sites"
      }, {
        "value" : "[mode=LATEST, modifiedSince=null]",
        "title" : "filter:timeRange"
      }, {
        "value" : "sdas01",
        "title" : "server"
      } ]
  "nil" : false,
  "globalScope" : true,
  "typeSubstituted" : false

would translate into a python diction

resp_dict = json.loads(resp_str)

resp_dict['name'] # "ns1:timeSeriesResponseType"

resp_dict['value']['queryInfo']['creationTime'] # 1349724919000

What is bootstrapping?

I belong to the generation who flipped switches to enter a boot program. In the early 1980s, I worked on a microcomputer called Micro-78, developed by Electronics Corporation of India Ltd (ECIL). It was a sort of clone of Altair 8800. I distinctly remember what happens when a small boot program was entered using the toggle switches and executed by pressing a button. The program reads a second boot program contained in the 1st track of the floppy disk and overwrites it on itself in such a way that the second boot program starts executing to load a disk operating system. I think the term "bootstrap" refers to this process of the first boot program reading and overwriting the second boot program on itself, in a way "pulling itself up" with the additional functionality of the second boot program. That may be the origin of the original meaning of "the bootstrap program".

How to print a string multiple times?

So I take it if the user enters 2, you want the output to be something like:



To get that, you would need something like:

rows = 4
times_to_repeat = int(raw_input("How many times to repeat per row? ")

for i in range(rows):
    print "!" * times_to_repeat

That would result in:

How many times to repeat per row?
>> 4

I have not tested this, but it should run error free.

"Items collection must be empty before using ItemsSource."

Mine was with a datagrid Style. If you leave out the <DataGrid.RowStyle> tags around the Style you get that problem. Weird thing is it worked for a while like that. Here is the bad code.

 <DataGrid Name="DicsountScheduleItemsDataGrid"
                  ItemsSource="{Binding DiscountScheduleItems, Mode=OneWay}">
            <Style TargetType="DataGridRow">
                <Setter Property="IsSelected"
                        Value="{Binding IsSelected, Mode=TwoWay}" />

and the good

 <DataGrid Name="DicsountScheduleItemsDataGrid"
                  ItemsSource="{Binding DiscountScheduleItems, Mode=OneWay}">
            <Style TargetType="DataGridRow">
                <Setter Property="IsSelected"
                        Value="{Binding IsSelected, Mode=TwoWay}" />

Unable to read repository at

I had the same problem. Try to deactivate your Firewall (I had avast!), which worked for me.

(Sorry for my English I'm French :D)

Reducing the gap between a bullet and text in a list item

Here's yet another way.

  1. Add two divs to each li, one for the bullet, one for the text.
  2. Put a bullet character (or whatever you like, Unicode has plenty) in the bullet div. Put the text in the text div.
  3. Set each li to display:flex.


  • No extra bullet image to add.
  • No negative margins or anything, won't go outside of parent.
  • Works on any browser that supports flexbox.
  • Proper indentation of multiline items.
  • Use of bullet character means bullet will always be properly vertically aligned with text, no tweaks necessary.


  • Requires extra elements.

Also, if you don't want to hand code all the extra divs, you can just make a normal list and then run this function to transform it, passing your ul as the parameter:

function fixList (theList) {
  theList.find('li').each(function (_, li) {
    li = $(li);


li {_x000D_
  font-family: sans-serif;_x000D_
  list-style-type: none;_x000D_
  display: flex;_x000D_
li > div:first-child {_x000D_
  margin-right: 0.75ex; /* set to desired spacing */_x000D_
  <li><div>•</div><div>First list item.</div>_x000D_
  <li><div>•</div><div>Second list item.<br>It's on two lines.</div>_x000D_
  <li><div>•</div><div>Third <i>list</i> item.</div>_x000D_

Here's an example using the function:

function fixList (theList) {_x000D_
  $('li', theList).each(function (_, li) {_x000D_
    li = $(li);_x000D_
li {_x000D_
  font-family: sans-serif;_x000D_
  list-style-type: none;_x000D_
  display: flex;_x000D_
li > div:first-child {_x000D_
  margin-right: 0.75ex;_x000D_
<script src=""></script>_x000D_
  <li>First list item._x000D_
  <li>Second list item.<br>It's on two lines._x000D_
  <li>Third <i>list</i> item._x000D_

One line if statement not working

Both the shell and C one-line constructs work (ruby 1.9.3p429):

# Shell format
irb(main):022:0> true && "Yes" || "No"
=> "Yes"
irb(main):023:0> false && "Yes" || "No"
=> "No"

# C format
irb(main):024:0> true ? "Yes" : "No"
=> "Yes"
irb(main):025:0> false ? "Yes" : "No"
=> "No"

Twitter Bootstrap - add top space between rows

Bootstrap 3

If you need to separate rows in bootstrap, you can simply use .form-group. This adds 15px margin to the bottom of row.

In your case, to get margin top, you can add this class to previous .row element

<div class="row form-group">

/* From bootstrap.css */
.form-group {
        margin-bottom: 15px;

Bootstrap 4

You can use built-in spacing classes

<div class="row mt-3"></div>

The "t" in class name makes it apply only to "top" side, there are similar classes for bottom, left, right. The number defines space size.

using batch echo with special characters

Why not use single quote?

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


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

Shell script current directory?

As already mentioned, the location will be where the script was called from. If you wish to have the script reference it's installed location, it's quite simple. Below is a snippet that will print the PWD and the installed directory:

echo "Script executed from: ${PWD}"

BASEDIR=$(dirname $0)
echo "Script location: ${BASEDIR}"

You're weclome

Change image source in code behind - Wpf

None of the above solutions worked for me. But this did:

myImage.Source = new BitmapImage(new Uri(@"/Images/foo.png", UriKind.Relative));

Make a float only show two decimal places

Use NSNumberFormatter with maximumFractionDigits as below:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.maximumFractionDigits = 2;
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:12.345]]);

And you will get 12.35

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
 $('#cmd').click(function () {
        var doc = new jsPDF();
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){'sample-file.pdf'); }


and it will work.

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result

Try this query -

  CASE status
      WHEN 'New' THEN t2.expose_new
      WHEN 'Used' THEN t2.expose_used
  END as 'expose'
  `products` t1
JOIN manufacturers t2
  ON = t1.seller
  t1.seller = 4238

changing textbox border colour using javascript

Use CSS styles with CSS Classes instead


.error {
  border:2px solid red;

Now in Javascript

document.getElementById("fName").className = document.getElementById("fName").className + " error";  // this adds the error class

document.getElementById("fName").className = document.getElementById("fName").className.replace(" error", ""); // this removes the error class

The main reason I mention this is suppose you want to change the color of the errored element's border. If you choose your way you will may need to modify many places in code. If you choose my way you can simply edit the style sheet.

Most efficient way to reverse a numpy array

In order to have it working with negative numbers and a long list you can do the following:

b = numpy.flipud(numpy.array(a.split(),float))

Where flipud is for 1d arra

Adding up BigDecimals using Streams

This post already has a checked answer, but the answer doesn't filter for null values. The correct answer should prevent null values by using the Object::nonNull function as a predicate.

BigDecimal result =
    .filter(i -> (i.getUnit_price() != null) && (i.getQuantity != null))
    .reduce(BigDecimal.ZERO, BigDecimal::add);

This prevents null values from attempting to be summed as we reduce.

Capturing a form submit with jquery and .submit

Wrap the code in document ready and prevent the default submit action:

$(function() { //shorthand document.ready function
    $('#login_form').on('submit', function(e) { //use on if jQuery 1.7+
        e.preventDefault();  //prevent form from submitting
        var data = $("#login_form :input").serializeArray();
        console.log(data); //use the console for debugging, F12 in Chrome, not alerts

pip issue installing almost any library

Just uninstall and reinstall pip packages it will workout for you guys.

Mac os version: high Sierra 10.13.6

python version: 3.7

So I uninstalled the older pip and installed the newest version10.0.0 by entering this:

python3 -m pip uninstall pip setuptools

curl | python3

Now my problem was solved. If you are using the python2, you can substitute the python3 with python. I hope it also works for you.

Stacking DIVs on top of each other?

All the answers seem pretty old :) I'd prefer CSS grid for a better page layout (absolute divs can be overridden by other divs in the page.)

<div class="container">
  <div class="inner" style="background-color: white;"></div>
  <div class="inner" style="background-color: red;"></div>
  <div class="inner" style="background-color: green;"></div>
  <div class="inner" style="background-color: blue;"></div>
  <div class="inner" style="background-color: purple;"></div>
  <div class="inner no-display" style="background-color: black;"></div>

.container {
  width: 300px;
  height: 300px;
  margin: 0 auto;
  background-color: yellow;
  display: grid;
  place-items: center;

.inner {
  grid-area: inners;
  height: 100px;
  width: 100px;

.no-display {
  display: none;

Here's a working link

How to use struct timeval to get the execution time?

You have two typing errors in your code:

 struct timeval,

should be

 struct timeval

and after the printf() parenthesis you need a semicolon.

Also, depending on the compiler, so simple a cycle might just be optimized out, giving you a time of 0 microseconds whatever you do.

Finally, the time calculation is wrong. You only take into accounts the seconds, ignoring the microseconds. You need to get the difference between seconds, multiply by one million, then add "after" tv_usec and subtract "before" tv_usec. You gain nothing by casting an integer number of seconds to a float.

I'd suggest checking out the man page for struct timeval.

This is the code:

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

int main (int argc, char** argv) {
    struct timeval tvalBefore, tvalAfter;  // removed comma

    gettimeofday (&tvalBefore, NULL);
    int i =0;
    while ( i < 10000) {
        i ++;

    gettimeofday (&tvalAfter, NULL);

    // Changed format to long int (%ld), changed time calculation

    printf("Time in microseconds: %ld microseconds\n",
            ((tvalAfter.tv_sec - tvalBefore.tv_sec)*1000000L
           +tvalAfter.tv_usec) - tvalBefore.tv_usec
          ); // Added semicolon
    return 0;

How should I copy Strings in Java?

Strings are immutable objects so you can copy them just coping the reference to them, because the object referenced can't change ...

So you can copy as in your first example without any problem :

String s = "hello";
String backup_of_s = s;
s = "bye";

Iterating over arrays in Python 3

When you loop in an array like you did, your for variable(in this example i) is current element of your array.

For example if your ar is [1,5,10], the i value in each iteration is 1, 5, and 10. And because your array length is 3, the maximum index you can use is 2. so when i = 5 you get IndexError. You should change your code into something like this:

for i in ar:
    theSum = theSum + i

Or if you want to use indexes, you should create a range from 0 ro array length - 1.

for i in range(len(ar)):
    theSum = theSum + ar[i]

How to enable C++11 in Qt Creator?

If you are using an earlier version of QT (<5) try this

QMAKE_CXXFLAGS += -std=c++0x

Timing Delays in VBA

Access can always use the Excel procedure as long as the project has the Microsoft Excel XX.X object reference included:

Call Excel.Application.Wait(DateAdd("s",10,Now()))

Jquery change <p> text programmatically

Try the following, note that when user refreshes the page, the value is "Male" again, data should be stored on database.

<p id="pTest">Male</p>


SQL SERVER: Check if variable is null and then assign statement for Where Clause

Try the following:

if ((select VisitCount from PageImage where PID=@pid and PageNumber=5) is NULL)
    update PageImage
    set VisitCount=1
    where PID=@pid and PageNumber=@pageno
    update PageImage 
    set VisitCount=VisitCount+1
    where PID=@pid and PageNumber=@pageno

Cannot find java. Please use the --jdkhome switch

In my case, I had installed *ahem* OpenJDK, but the bin folder was full of symlinks to the bundled JRE and the actual JDK was nowhere to be found.

When I see a directory structure with bin and jre subdirectories I expect this to be the JDK installation, because JRE installations on Windows looked different. But in this case it was the JRE installation as found out by apt search. After installing openjdk-8-jre the simlinks were replaced and the directory structure otherwise stayed the same.

How can I loop through a C++ map of maps?


std::map< std::string, std::map<std::string, std::string> > m;
m["name1"]["value1"] = "data1";
m["name1"]["value2"] = "data2";
m["name2"]["value1"] = "data1";
m["name2"]["value2"] = "data2";
m["name3"]["value1"] = "data1";
m["name3"]["value2"] = "data2";

for (auto i : m)
    for (auto j : i.second)
        cout << i.first.c_str() << ":" << j.first.c_str() << ":" << j.second.c_str() << endl;



Best way to encode Degree Celsius symbol into web page?

Add a metatag to your header

<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

This expands the amount of characters you can use.

How to create empty data frame with column names specified in R?

Just create a data.frame with 0 length variables


nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))

## 'data.frame':    0 obs. of  3 variables:
##  $ x: num 
##  $ y: int 
##  $ z: Factor w/ 0 levels: 

or to create a data.frame with 5 columns named a,b,c,d,e

nodata <-,numeric(0), simplify = F), letters[1:5]))

How to log out user from web site using BASIC authentication?

I updated mthoring's solution for modern Chrome versions:

function logout(secUrl, redirUrl) {
    if (bowser.msie) {
        document.execCommand('ClearAuthenticationCache', 'false');
    } else if (bowser.gecko) {
            async: false,
            url: secUrl,
            type: 'GET',
            username: 'logout'
    } else if (bowser.webkit || {
        var xmlhttp = new XMLHttpRequest();\"GET\", secUrl, true);
        xmlhttp.setRequestHeader(\"Authorization\", \"Basic logout\");\
    } else {
        redirUrl = url.replace('http://', 'http://' + new Date().getTime() + '@');
    setTimeout(function () {
        window.location.href = redirUrl;
    }, 200);

How to download files using axios

My answer is a total hack- I just created a link that looks like a button and add the URL to that.

<a class="el-button"
  style="color: white; background-color: #58B7FF;"
  :download="<FILE NAME NERE>">
<i class="fa fa-file-excel-o"></i>&nbsp;Excel

I'm using the excellent VueJs hence the odd anotations, however, this solution is framework agnostic. The idea would work for any HTML based design.

How to correctly assign a new string value?

Think of strings as abstract objects, and char arrays as containers. The string can be any size but the container must be at least 1 more than the string length (to hold the null terminator).

C has very little syntactical support for strings. There are no string operators (only char-array and char-pointer operators). You can't assign strings.

But you can call functions to help achieve what you want.

The strncpy() function could be used here. For maximum safety I suggest following this pattern:

strncpy(, "Jane", 19);[19] = '\0'; //add null terminator just in case

Also have a look at the strncat() and memcpy() functions.

How to take input in an array + PYTHON?

If the number of elements in the array is not given, you can alternatively make use of list comprehension like:

str_arr = raw_input().split(' ') //will take in a string of numbers separated by a space
arr = [int(num) for num in str_arr]

How to find which version of TensorFlow is installed in my system?

Another variation, i guess :P

python3 -c 'print(__import__("tensorflow").__version__)'

Open application after clicking on Notification

See below code. I am using that and it is opening my HomeActivity.

    NotificationManager notificationManager = (NotificationManager) context
    Notification notification = new Notification(icon, message, when);

    Intent notificationIntent = new Intent(context, HomeActivity.class);

            | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent intent = PendingIntent.getActivity(context, 0,
            notificationIntent, 0);

    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(0, notification);

How to select id with max date group by category in PostgreSQL?

This is a perfect use-case for DISTINCT ON - a Postgres specific extension of the standard DISTINCT:

       id  -- , category, date  -- any other column (expression) from the same row
FROM   tbl
ORDER  BY category, date DESC;

Careful with descending sort order. If the column can be NULL, you may want to add NULLS LAST:

DISTINCT ON is simple and fast. Detailed explanation in this related answer:

For big tables with many rows per category consider an alternative approach:

CSS table td width - fixed, not flexible

This workaround worked for me...

<td style="white-space: normal; width:300px;">

Warning: Permanently added the RSA host key for IP address

I had similar problem. In git site after user clicking on clone or download button, while copying the cloned url there are 2 options to select ssh and https. I selected https url to clone and it worked.

dropping infinite values from dataframes in pandas?

Here is another method using .loc to replace inf with nan on a Series:

s.loc[(~np.isfinite(s)) & s.notnull()] = np.nan

So, in response to the original question:

df = pd.DataFrame(np.ones((3, 3)), columns=list('ABC'))

for i in range(3): 
    df.iat[i, i] = np.inf

          A         B         C
0       inf  1.000000  1.000000
1  1.000000       inf  1.000000
2  1.000000  1.000000       inf

A    inf
B    inf
C    inf
dtype: float64

df.apply(lambda s: s[np.isfinite(s)].dropna()).sum()
A    2
B    2
C    2
dtype: float64

Html.HiddenFor value property not getting set

Have you tried using a view model instead of ViewData? Strongly typed helpers that end with For and take a lambda expression cannot work with weakly typed structures such as ViewData.

Personally I don't use ViewData/ViewBag. I define view models and have my controller actions pass those view models to my views.

For example in your case I would define a view model:

public class MyViewModel
    [HiddenInput(DisplayValue = false)]
    public string CRN { get; set; }

have my controller action populate this view model:

public ActionResult Index()
    var model = new MyViewModel
        CRN = "foo bar"
    return View(model);

and then have my strongly typed view simply use an EditorFor helper:

@model MyViewModel
@Html.EditorFor(x => x.CRN)

which would generate me:

<input id="CRN" name="CRN" type="hidden" value="foo bar" />

in the resulting HTML.

How to get an array of unique values from an array containing duplicates in JavaScript?

    Array.prototype.unique =
    ( function ( _where ) {
      return function () {
        for (
          i1 = 0,
          i1 < this.length;
        ) {
          if ( ( dups = _where( this, this[i1] ) ).length > 1 ) {
            for (
              i2 = dups.length;
              this.splice( dups[i2], 1 )
        return this;
    } )(
      function ( arr, elem ) {
        var locs  = [];
        var tmpi  = arr.indexOf( elem, 0 );
        while (
          ( tmpi ^ -1 )
          && (
            locs.push( tmpi ),
            tmpi = arr.indexOf( elem, tmpi + 1 ), 1
        return locs;

What is the javascript filename naming convention?

There is no official, universal, convention for naming JavaScript files.

There are some various options:

  • scriptName.js
  • script-name.js
  • script_name.js

are all valid naming conventions, however I prefer the jQuery suggested naming convention (for jQuery plugins, although it works for any JS)

  • jquery.pluginname.js

The beauty to this naming convention is that it explicitly describes the global namespace pollution being added.

  • foo.js adds
  • adds

Because I left out versioning: it should come after the full name, preferably separated by a hyphen, with periods between major and minor versions:

  • foo-1.2.1.js
  • foo-1.2.2.js
  • ...
  • foo-2.1.24.js

Remove padding from columns in Bootstrap 3

You'd normally use .row to wrap two columns, not .col-md-12 - that's a column encasing another column. Afterall, .row doesn't have the extra margins and padding that a col-md-12 would bring and also discounts the space that a column would introduce with negative left & right margins.

<div class="container">
    <div class="row">
        <h2>OntoExplorer<span style="color:#b92429">.</span></h2>

        <div class="col-md-4 nopadding">
            <div class="widget">
                <div class="widget-header">
                <div class="widget-content">

        <div class="col-md-8 nopadding">
            <div class="widget">
                <div class="widget-header">
                <div class="widget-content">

if you really wanted to remove the padding/margins, add a class to filter out the margins/paddings for each child column.

.nopadding {
   padding: 0 !important;
   margin: 0 !important;

std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

They are not really same mutexes, lock_guard<muType> has nearly the same as std::mutex, with a difference that it's lifetime ends at the end of the scope (D-tor called) so a clear definition about these two mutexes :

lock_guard<muType> has a mechanism for owning a mutex for the duration of a scoped block.


unique_lock<muType> is a wrapper allowing deferred locking, time-constrained attempts at locking, recursive locking, transfer of lock ownership, and use with condition variables.

Here is an example implemetation :

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <chrono>

using namespace std::chrono;

class Product{


       Product(int data):mdata(data){


       bool isReady(){
       return flag;

       void showData(){


       void read(){


         std::lock_guard<std::mutex> guard(mmutex);

         flag = true;

         std::cout<<"Data is ready"<<std::endl;



       void task(){

       std::unique_lock<std::mutex> lock(mmutex);

       cvar.wait(lock, [&, this]() mutable throw() -> bool{ return this->isReady(); });




    std::condition_variable cvar;
    std::mutex mmutex;
    int mdata;
    bool flag = false;


int main(){

     int a = 0;
     Product product(a);

     std::thread reading(, &product);
     std::thread setting(product.task, &product);


    return 0;

In this example, i used the unique_lock<muType> with condition variable

proper way to logout from a session in PHP

Personally, I do the following:

setcookie(session_name(), '', 100);
$_SESSION = array();

That way, it kills the cookie, destroys all data stored internally, and destroys the current instance of the session information (which is ignored by session_destroy).

Cannot connect to MySQL Workbench on mac. Can't connect to MySQL server on '' (61) Mac Macintosh

brew services start mysql defualt set --bind-address= with /usr/local/Cellar/mysql/5.6.27/homebrew.mxcl.mysql.plist,so replace --bind-address= with --bind-address=* or --bind-address=

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

Invariant Violation: Objects are not valid as a React child

I'd like to add another solution to this list.


  • "react": "^16.2.0",
  • "react-dom": "^16.2.0",
  • "react-redux": "^5.0.6",
  • "react-scripts": "^1.0.17",
  • "redux": "^3.7.2"

I encountered the same error:

Uncaught Error: Objects are not valid as a React child (found: object with keys {XXXXX}). If you meant to render a collection of children, use an array instead.

This was my code:

let payload = {
      guess: this.userInput.value



  // let payload = {
  //   guess: this.userInput.value
  // };


The problem was occurring because the payload was sending the item as an object. When I removed the payload variable and put the userInput value into the dispatch everything started working as expected.

How to handle query parameters in angular 2

In Angular 6, I found this simpler way:

navigate(["/yourpage", { "someParamName": "paramValue"}]);

Then in the constructor or in ngInit you can directly use:

let value = this.route.snapshot.params.someParamName;

Biggest advantage to using ASP.Net MVC vs web forms

In webforms you could also render almost whole html by hand, except few tags like viewstate, eventvalidation and similar, which can be removed with PageAdapters. Nobody force you to use GridView or some other server side control that has bad html rendering output.

I would say that biggest advantage of MVC is SPEED!

Next is forced separation of concern. But it doesn't forbid you to put whole BL and DAL logic inside Controller/Action! It's just separation of view, which can be done also in webforms (MVP pattern for example). A lot of things that people mentions for mvc can be done in webforms, but with some additional effort.
Main difference is that request comes to controller, not view, and those two layers are separated, not connected via partial class like in webforms (aspx + code behind)

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on =
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

How do I add a Maven dependency in Eclipse?

I have faced the similar issue and fixed by copying the missing Jar files in to .M2 Path,

For example: if you see the error message as Missing artifact tws:axis-client:jar:8.7 then you have to download "axis-client-8.7.jar" file and paste the same in to below location will resolve the issue.

C:\Users\UsernameXXX.m2\repository\tws\axis-client\8.7(Paste axis-client-8.7.jar).

finally, right click on project->Maven->Update Project...Thats it.

happy coding.

How to increment an iterator by 2?

You could use the 'assignment by addition' operator

iter += 2;

How to make a div 100% height of the browser window

Try the following CSS:

html {
    min-height: 100%;
    margin: 0;
    padding: 0;

body {
    height: 100%;

#right {
    min-height: 100%;

HTTP Request in Kotlin

You can use kohttp library. It is a Kotlin DSL HTTP client. It supports the features of square.okhttp and provides a clear DSL for them. KoHttp async calls are powered by coroutines.

httpGet extension function

val response: Response = "".httpGet()

you can also use async call with coroutines

val response: Deferred<Response> = "".asyncHttpGet()

or DSL function for more complex requests

val response: Response = httpGet {
    host = ""
    path = "/search"
    param {
       "q" to "iphone"
       "safe" to "off"

You can find more details in docs

To get it with gradle use

implementation 'io.github.rybalkinsd:kohttp:0.12.0'

TypeError: 'str' object cannot be interpreted as an integer

You have to convert input x and y into int like below.


how to add values to an array of objects dynamically in javascript?

You have to instantiate the object first. The simplest way is:

var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++)  {
    data.push({label: lab[i], value: val[i]});

Or an other, less concise way, but closer to your original code:

for(var i=0; i<4; i++)  {
   data[i] = {};              // creates a new object
   data[i].label = lab[i];
   data[i].value = val[i];    

array() will not create a new array (unless you defined that function). Either Array() or new Array() or just [].

I recommend to read the MDN JavaScript Guide.

SQL Server: Get data for only the past year

I had a similar problem but the previous coder only provided the date in mm-yyyy format. My solution is simple but might prove helpful to some (I also wanted to be sure beginning and ending spaces were eliminated):

','')+'/01/'+RIGHT(RTRIM([MoYr]),4)) >=  DATEADD(year,-1,GETDATE())

script to map network drive

Tomalak's answer worked great for me (+1)

I only needed to make alter it slightly for my purposes, and I didn't need a password - it's for corporate domain:

Option Explicit
Dim l: l = "Z:"
Dim s: s = "\\\share"
Dim Network: Set Network = CreateObject("WScript.Network")
Dim CheckDrive: Set CheckDrive = Network.EnumNetworkDrives()
Dim DriveExists: DriveExists = False
Dim i

For i = 0 to CheckDrive.Count - 1
  If CheckDrive.Item(i) = l Then
    DriveExists = True
  End If

If DriveExists = False Then
  Network.MapNetworkDrive l, s, False
  MsgBox l + " Drive already mapped"
End If

Or if you want to disconnect the drive:

For i = 0 to CheckDrive.Count - 1
  If CheckDrive.Item(i) = l Then 
    WshNetwork.RemoveNetworkDrive CheckDrive.Item(i)
  End If

What's the difference between VARCHAR and CHAR?

CHAR is fixed length and VARCHAR is variable length. CHAR always uses the same amount of storage space per entry, while VARCHAR only uses the amount necessary to store the actual text.

change PATH permanently on Ubuntu

Try to add export PATH=$PATH:/home/me/play in ~/.bashrc file.

Calling a function of a module by using its name (a string)

getattr calls method by name from an object. But this object should be parent of calling class. The parent class can be got by super(self.__class__, self)

class Base:
    def call_base(func):
        """This does not work"""
        def new_func(self, *args, **kwargs):
            name = func.__name__
            getattr(super(self.__class__, self), name)(*args, **kwargs)
        return new_func

    def f(self, *args):
        print(f"BASE method invoked.")

    def g(self, *args):
        print(f"BASE method invoked.")

class Inherit(Base):
    def f(self, *args):
        """function body will be ignored by the decorator."""

    def g(self, *args):
        """function body will be ignored by the decorator."""

Inherit().f() # The goal is to print "BASE method invoked."

How can I create a link to a local file on a locally-run web page?

back to 2017:

use URL.createObjectURL( file ) to create local link to file system that user select;

don't forgot to free memory by using URL.revokeObjectURL()

VBA vlookup reference in different sheet

try this:

Dim ws as Worksheet

Set ws = Thisworkbook.Sheets("Sheet2")

With ws
    .Range("E2").Formula = "=VLOOKUP(D2,Sheet1!$A:$C,1,0)"
End With

End Sub

This just the simplified version of what you want.
No need to use Application if you will just output the answer in the Range("E2").

If you want to stick with your logic, declare the variables.
See below for example.

Sub Test()

Dim rng As Range
Dim ws1, ws2 As Worksheet
Dim MyStringVar1 As String

Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
Set rng = ws2.Range("D2")

With ws2
    On Error Resume Next 'add this because if value is not found, vlookup fails, you get 1004
    MyStringVar1 = Application.WorksheetFunction.VLookup(rng, ws1.Range("A1:C65536").Value, 1, False)
    On Error GoTo 0
    If MyStringVar1 = "" Then MsgBox "Item not found" Else MsgBox MyStringVar1
End With

End Sub

Hope this get's you started.

How to serialize an object into a string

Java8 approach, converting Object from/to String, inspired by answer from OscarRyz. For de-/encoding, java.util.Base64 is required and used.

import java.util.Base64;
import java.util.Optional;

final class ObjectHelper {

  private ObjectHelper() {}

  static Optional<String> convertToString(final Serializable object) {
    try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream(baos)) {
      return Optional.of(Base64.getEncoder().encodeToString(baos.toByteArray()));
    } catch (final IOException e) {
      return Optional.empty();

  static <T extends Serializable> Optional<T> convertFrom(final String objectAsString) {
    final byte[] data = Base64.getDecoder().decode(objectAsString);
    try (final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data))) {
      return Optional.of((T) ois.readObject());
    } catch (final IOException | ClassNotFoundException e) {
      return Optional.empty();

Laravel Rule Validation for Numbers

Laravel min and max validation do not work properly with a numeric rule validation. Instead of numeric, min and max, Laravel provided a rule digits_between.


CSS3 :unchecked pseudo-class

There is no :unchecked pseudo class however if you use the :checked pseudo class and the sibling selector you can differentiate between both states. I believe all of the latest browsers support the :checked pseudo class, you can find more info from this resource:

Your going to get better browser support with jquery... you can use a click function to detect when the click happens and if its checked or not, then you can add a class or remove a class as necessary...

What is a 'multi-part identifier' and why can't it be bound?

I found that I get these a lot when I try to abbreviate, such as:

Table1 t1, Table2 t2 
where t1.ID = t2.ID

Changing it to:

Table1, Table2 
where Table1.ID = Table2.ID

Makes the query work and not throw the error.

CSS text-overflow: ellipsis; not working?

I have been having this problem and I wanted a solution that could easily work with dynamic widths. The solution use css grid. This is how the code looks like:

// css 
      display: grid; 
      grid-template-columns: auto 1fr;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;


// html
<div class="parent">
  <div class="dynamic-width-child">
    iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii asdfhlhlafh;lshd;flhsd;lhfaaaaaaaaaaaaaaaaaaaa
  <div class="fixed-width-child">Why?-Zed</div>

Ansible: deploy on multiple hosts in the same time

As of Ansible 2.0 there seems to be an option called strategy on a playbook. When setting the strategy to free, the playbook plays tasks on each host without waiting to the others. See

It looks something like this (taken from the above link):

- hosts: all
  strategy: free

Please note that I didn't check this and I'm very new to Ansible. I was just curious about doing what you described and happened to come acroess this strategy thing.


It seems like this is not exactly what you're trying to do. Maybe "async tasks" is more appropriate as described here:

This includes specifying async and poll on a task. The following is taken from the 2nd link I mentioned:

- name: simulate long running op, allow to run for 45 sec, fire and forget
  command: /bin/sleep 15
  async: 45
  poll: 0

I guess you can specify longer async times if your task is lengthy. You can probably define your three concurrent task this way.

Chart creating dynamically. in .net, c#

You need to attach the Form1_Load handler to the Load event:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Diagnostics;

namespace WindowsFormsApplication6
    public partial class Form1 : Form
        public Form1()
            Load += Form1_Load;

        private void Form1_Load(object sender, EventArgs e)
            Random rnd = new Random();
            Chart mych = new Chart();
            mych.Height = 100;
            mych.Width = 100;
            mych.BackColor = SystemColors.Highlight;

            mych.Series["duck"].Enabled = true;
            mych.Visible = true;

            for (int q = 0; q < 10; q++)
                int first = rnd.Next(0, 10);
                int second = rnd.Next(0, 10);
                mych.Series["duck"].Points.AddXY(first, second);
                Debug.WriteLine(first + "  " + second);


How to format an inline code in Confluence?

By default Confluence renders monospaced text with transparent background. You can edit global CSS to add grey color. From Confluence manual:

  1. Choose the cog icon at top right of the screen, then choose Confluence Admin.
  2. Choose Stylesheet.
  3. Choose Edit.
  4. Paste your custom CSS into the text field.
  5. Choose Save.

Custom CSS for displaying grey background in monospaced blocks:

code {
    padding: 1px 5px 1px 5px; 
    font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
    background-color: #eeeeee;

If you're using Confluence OnDemand (cloud):

  1. Click the cog/gear in the bottom of the sidebar on the left
  2. Select Look and Feel
  3. Click the Sidebar, Header and Footer tab
  4. Paste your custom CSS into the Header field
  5. Wrap the code in a {style} block
  6. Save

Paste the following:

code {
    padding: 1px 5px 1px 5px; 
    font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
    background-color: #eeeeee;

After that you'll get nice and tidy stackoverflow-stylish inline code spans just by writing {{sometext}}.

Use SELECT inside an UPDATE query

Does this work? Untested but should get the point across.

SET Func_TaxRef = 
  SELECT Min(TAX.Tax_Code) AS MinOfTax_Code
  WHERE F1.Func_Pure <= [Tax_ToPrice]
    AND F1.Func_Year=[Tax_Year]
    AND F1.Func_ID = FUNCTIONS.Func_ID
  GROUP BY F1.Func_ID;

Basically for each row in FUNCTIONS, the subquery determines the minimum current tax code and sets FUNCTIONS.Func_TaxRef to that value. This is assuming that FUNCTIONS.Func_ID is a Primary or Unique key.

Sublime Text 2 - View whitespace characters

  1. open


  1. search

Preferences: Settings –> User

  1. just paste below codes

    "draw_white_space": "all",_x000D_
    "translate_tabs_to_spaces": true_x000D_

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

The same situation was with the previous versions. It's annoing that new versions libraries are always releasing before plugin, and it's impossible to use new version because is incompatible with old plugin. I don't know if plugin is now required (google docs sucks). I remember times when it wasn't. The only way is wait for new plugin version, or you can try to remove plugin dependencies, but as I said I'am not sure if gcm will work without it. What I know the main feature of 9.2.0 version is new Awareness API, if you didn't need it, you can use 9.0.0 version without any trouble.

catch specific HTTP error in python

Tims answer seems to me as misleading. Especially when urllib2 does not return expected code. For example this Error will be fatal (believe or not - it is not uncommon one when downloading urls):

AttributeError: 'URLError' object has no attribute 'code'

Fast, but maybe not the best solution would be code using nested try/except block:

import urllib2
    urllib2.urlopen("some url")
except urllib2.HTTPError, err:
        if err.code == 404:
            # Handle the error

More information to the topic of nested try/except blocks Are nested try/except blocks in python a good programming practice?

SQL query to get the deadlocks in SQL SERVER 2008

In order to capture deadlock graphs without using a trace (you don't need profiler necessarily), you can enable trace flag 1222. This will write deadlock information to the error log. However, the error log is textual, so you won't get nice deadlock graph pictures - you'll have to read the text of the deadlocks to figure it out.

I would set this as a startup trace flag (in which case you'll need to restart the service). However, you can run it only for the current running instance of the service (which won't require a restart, but which won't resume upon the next restart) using the following global trace flag command:

DBCC TRACEON(1222, -1);

A quick search yielded this tutorial:

Also note that if your system experiences a lot of deadlocks, this can really hammer your error log, and can become quite a lot of noise, drowning out other, important errors.

Have you considered third party monitoring tools? SQL Sentry Performance Advisor, for example, has a much nicer deadlock graph, showing you object / index names as well as the order in which the locks were taken. As a bonus, these are captured for you automatically on monitored servers without having to configure trace flags, run your own traces, etc.:

enter image description here

Disclaimer: I work for SQL Sentry.

How do I print the percent sign(%) in c

Use "%%". The man page describes this requirement:

% A '%' is written. No argument is converted. The complete conversion specification is '%%'.

JPA : How to convert a native query result set to POJO class collection

if you are using Spring, you can use org.springframework.jdbc.core.RowMapper

Here is an example:

public List query(String objectType, String namedQuery)
  String rowMapper = objectType + "RowMapper";
  // then by reflection you can instantiate and use. The RowMapper classes need to follow the naming specific convention to follow such implementation.

C# 30 Days From Todays Date

DateTime.AddDays does that:

DateTime expires = yourDate.AddDays(30);

Finding Variable Type in JavaScript

Use typeof:

> typeof "foo"
> typeof true
> typeof 42

So you can do:

if(typeof bar === 'number') {

Be careful though if you define these primitives with their object wrappers (which you should never do, use literals where ever possible):

> typeof new Boolean(false)
> typeof new String("foo")
> typeof new Number(42)

The type of an array is still object. Here you really need the instanceof operator.


Another interesting way is to examine the output of Object.prototype.toString:

"[object Array]"
>"foo bar")
"[object String]"
"[object Number]"
"[object Boolean]"
> String("foo bar"))
"[object String]"
"[object Null]"
"[object RegExp]"
"[object Undefined]"

With that you would not have to distinguish between primitive values and objects.

Swift apply .uppercaseString to only the first letter of a string

Including mutating and non mutating versions that are consistent with API guidelines.

Swift 3:

extension String {
    func capitalizingFirstLetter() -> String {
        let first = String(characters.prefix(1)).capitalized
        let other = String(characters.dropFirst())
        return first + other

    mutating func capitalizeFirstLetter() {
        self = self.capitalizingFirstLetter()

Swift 4:

extension String {
    func capitalizingFirstLetter() -> String {
      return prefix(1).uppercased() + self.lowercased().dropFirst()

    mutating func capitalizeFirstLetter() {
      self = self.capitalizingFirstLetter()

what does "dead beef" mean?

It was used as a pattern to store in memory as a series of hex bytes (0xde, 0xad, 0xbe, 0xef). You could see if memory was corrupted because of hardware failure, buffer overruns, etc.

Change the current directory from a Bash script

In light of the unreadability and overcomplication of answers, i believe this is what the requestor should do

  1. add that script to the PATH
  2. run the script as . scriptname

The . (dot) will make sure the script is not run in a child shell.

In C - check if a char exists in a char array

Assuming your input is a standard null-terminated C string, you want to use strchr:

#include <string.h>

char* foo = "abcdefghijkl";
if (strchr(foo, 'a') != NULL)
  // do stuff

If on the other hand your array is not null-terminated (i.e. just raw data), you'll need to use memchr and provide a size:

#include <string.h>

char foo[] = { 'a', 'b', 'c', 'd', 'e' }; // note last element isn't '\0'
if (memchr(foo, 'a', sizeof(foo)))
  // do stuff

How to Configure SSL for Amazon S3 bucket

It is not possible directly with S3, but you can create a Cloud Front distribution from you bucket. Then go to certificate manager and request a certificate. Amazon gives them for free. Ones you have successfully confirmed the certification, assign it to your Cloud Front distribution. Also remember to set the rule to re-direct http to https.

I'm hosting couple of static websites on Amazon S3, like my personal website to which I have assigned the SSL certificate as they have the Cloud Front distribution.

Spring Boot - inject map from application.yml

You can make it even simplier, if you want to avoid extra structures.

    key1: value1
    key2: value2
public class ServiceConfigurationProperties {

  @ConfigurationProperties(prefix = "service.mappings")
  public Map<String, String> serviceMappings() {
    return new HashMap<>();


And then use it as usual, for example with a constructor:

public class Foo {

  private final Map<String, String> serviceMappings;

  public Foo(Map<String, String> serviceMappings) {
    this.serviceMappings = serviceMappings;


os.path.dirname(__file__) returns empty

can be used also like that:


Insert text with single quotes in PostgreSQL

String literals

Escaping single quotes ' by doubling them up -> '' is the standard way and works of course:

'user's log'     -- incorrect syntax (unbalanced quote)
'user''s log'

In old versions or if you still run with standard_conforming_strings = off or, generally, if you prepend your string with E to declare Posix escape string syntax, you can also escape with the backslash \:

E'user\'s log'

Backslash itself is escaped with another backslash. But that's generally not preferable.
If you have to deal with many single quotes or multiple layers of escaping, you can avoid quoting hell in PostgreSQL with dollar-quoted strings:

'escape '' with '''''
$$escape ' with ''$$

To further avoid confusion among dollar-quotes, add a unique token to each pair:

$token$escape ' with ''$token$

Which can be nested any number of levels:

$token2$Inner string: $token1$escape ' with ''$token1$ is nested$token2$

Pay attention if the $ character should have special meaning in your client software. You may have to escape it in addition. This is not the case with standard PostgreSQL clients like psql or pgAdmin.

That is all very useful for writing plpgsql functions or ad-hoc SQL commands. It cannot alleviate the need to use prepared statements or some other method to safeguard against SQL injection in your application when user input is possible, though. @Craig's answer has more on that. More details:

Values inside Postgres

When dealing with values inside the database, there are a couple of useful functions to quote strings properly:

  • quote_literal() or quote_nullable() - the latter outputs the string NULL for null input. (There is also quote_ident() to double-quote strings where needed to get valid SQL identifiers.)
  • format() with the format specifier %L is equivalent to quote_nullable().
    Like: format('%L', string_var)
  • concat() or concat_ws() are typically no good for this purpose as those do not escape nested single quotes and backslashes.

How do I return multiple values from a function in C?

Option 1: Declare a struct with an int and string and return a struct variable.

struct foo {    
 int bar1;
 char bar2[MAX];

struct foo fun() {
 struct foo fooObj;
 return fooObj;

Option 2: You can pass one of the two via pointer and make changes to the actual parameter through the pointer and return the other as usual:

int fun(char **param) {
 int bar;
 return bar;


 char* fun(int *param) {
 char *str = /* malloc suitably.*/
 *param = /* some value */
 return str;

Option 3: Similar to the option 2. You can pass both via pointer and return nothing from the function:

void fun(char **param1,int *param2) {
 *param2 = /* some calculated value */

How to remove elements/nodes from angular.js array

Just a slight expansion on the 'angular' solution. I wanted to exclude an item based on it's numeric id, so the ! approach doesn't work. The more general solution which should work for { name: 'ted' } or { id: 42 } is:

mycollection = $filter('filter')(myCollection, { id: theId }, function (obj, test) { 
                                                             return obj !== test; });

Converting string to Date and DateTime

$d = new DateTime('10-16-2003');

$timestamp = $d->getTimestamp(); // Unix timestamp
$formatted_date = $d->format('Y-m-d'); // 2003-10-16

Edit: you can also pass a DateTimeZone to DateTime() constructor to ensure the creation of the date for the desired time zone, not the server default one.

How to randomize (shuffle) a JavaScript array?

Here's a JavaScript implementation of the Durstenfeld shuffle, an optimized version of Fisher-Yates:

/* Randomize array in-place using Durstenfeld shuffle algorithm */
function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;

It picks a random element for each original array element, and excludes it from the next draw, like picking randomly from a deck of cards.

This clever exclusion swaps the picked element with the current one, then picks the next random element from the remainder, looping backwards for optimal efficiency, ensuring the random pick is simplified (it can always start at 0), and thereby skipping the final element.

Algorithm runtime is O(n). Note that the shuffle is done in-place so if you don't want to modify the original array, first make a copy of it with .slice(0).

EDIT: Updating to ES6 / ECMAScript 2015

The new ES6 allows us to assign two variables at once. This is especially handy when we want to swap the values of two variables, as we can do it in one line of code. Here is a shorter form of the same function, using this feature.

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];

How to simulate POST request?

Simple way is to use curl from command-line, for example:

curl --data "$DATA" --request POST --header "Content-Type:application/x-www-form-urlencoded" | python -m json.tool

or here is example how to send raw POST request using Bash shell (JSON request):

exec 3<> /dev/tcp/

DATA='{"email": "[email protected]"}'
LEN=$(printf "$DATA" | wc -c)

cat >&3 << EOF
POST /api/retrieveInfo HTTP/1.1
User-Agent: Bash
Accept: */*
Content-Length: $LEN
Connection: close


# Read response.
while read line <&3; do
   echo $line

Detect click event inside iframe

In my case, I was trying to fire a custom event from the parent document, and receive it in the child iframe, so I had to do the following:

var event = new CustomEvent('marker-metrics', {
    detail: // extra payload data here
var iframe = document.getElementsByTagName('iframe');

and in the iframe document:

document.addEventListener('marker-metrics', (e) => {
  console.log('@@@@@', e.detail);

Where can I find the assembly System.Web.Extensions dll?

I had this problem myself. Most of the information I could find online was related to people having this problem with an ASP.NET web application. I was creating a Win Forms stand alone app so most of the advice wasn't helpful for me.

Turns out that the problem was that my project was set to use the ".NET 4 Framework Client Profile" as the target framework and the System.Web.Extensions reference was not in the list for adding. I changed the target to ".NET 4 Framework" and then the reference was available by the normal methods.

Here is what worked for me step by step:

  1. Right Click you project Select Properties
  2. Change your Target Framework to ".NET Framework 4"
  3. Do whatever you need to do to save the changes and close the preferences tab
  4. Right click on the References item in your Solution Explorer
  5. Choose Add Reference...
  6. In the .NET tab, scroll down to System.Web.Extensions and add it.

How can I format bytes a cell in Excel as KB, MB, GB etc?

The above formatting approach works but only for three levels. The above used KB, MB, and GB. Here I've expanded it to six. Right-click on the cell(s) and select Format Cells. Under the Number tab, select Custom. Then in the Type: box, put the following:

[<1000]##0.00"  B";[<1000000]##0.00," KB";##0.00,," MB"

Then select OK. This covers B, KB, and MB. Then, with the same cells selected, click Home ribbon, Conditional Formatting, New Rule. Select Format only cells that contain. Then below in the rule description, Format only cells with, Cell Value, greater than or equal to, 1000000000 (that's 9 zeros.) Then click on Format, Number tab, Custom, and in the Type: box, put the following:

[<1000000000000]##0.00,,," GB";[<1000000000000000]##0.00,,,," TB";#,##0.00,,,,," PB"

Select OK, and OK. This conditional formatting will take over only if the value is bigger than 1,000,000,000. And it will take care of the GB, TB, and PB ranges.

567.00  B
  5.67 KB
 56.70 KB
567.00 KB
  5.67 MB
 56.70 MB
567.00 MB
  5.67 GB
 56.70 GB
567.00 GB
  5.67 TB
 56.70 TB
567.00 TB
  5.67 PB
 56.70 PB

Anything bigger than PB will just show up as a bigger PB, e.g. 56,700 PB. You could add another conditional formatting to handle even bigger values, EB, and so on.

HttpListener Access Denied

You can start your application as administrator if you add Application Manifest to your project.

Just Add New Item to your project and select "Application Manifest File". Change the <requestedExecutionLevel> element to:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

Android Studio 3.0 Flavor Dimension Issue

After trying and reading carefully, I solved it myself. Solution is to add the following line in build.gradle.

flavorDimensions "versionCode"

android { 
       compileSdkVersion 24
       flavorDimensions "versionCode"

How to upgrade Git to latest version on macOS?

the simplest way I found so far is from git official website. It just computed dependencies and downloaded all of the required libraries/tools

The other major way is to install Git via MacPorts ( If you have MacPorts installed, install Git via

$ sudo port install git-core +svn +doc +bash_completion +gitweb

Laravel Eloquent inner join with multiple conditions

Because you did it in such a way that it thinks both are join conditions in your code given below:

public function scopeShops($query) {
    return $query->join('kg_shops', function($join)
        $join->on('', '=', 'kg_feeds.shop_id');
        $join->on('', '=', "1");

So,you should remove the second line:

return $query->join('kg_shops', function($join)
    $join->on('', '=', 'kg_feeds.shop_id');

Now, you should add a where clause and it should be like this:

return $query->join('kg_shops', function($join)
  $join->on('', '=', 'kg_feeds.shop_id')->where('', 1);

How to sort a collection by date in MongoDB?

With mongoose it's as simple as:

collection.find().sort('-date').exec(function(err, collectionItems) {
  // here's your code

Add custom header in HttpWebRequest

You can add values to the HttpWebRequest.Headers collection.

According to MSDN, it should be supported in windows phone:

Set style for TextView programmatically

The accepted answer was great solution for me. The only thing to add is about inflate() method.

In accepted answer all android:layout_* parameters will not be applied.

The reason is no way to adjust it, cause null was passed as ViewGroup parent.

You can use it like this:

View view = inflater.inflate(R.layout.view, parent, false);

and the parent is the ViewGroup, from where you like to adjust android:layout_*.

In this case, all relative properties will be set.

Hope it'll be useful for someone.

Having trouble setting working directory

Maybe it is the case that you have your path in couple of lines, you used enter to make it? If so, then part of you paths might look like that "/\nData/" instead of "/Data/", which causes the problem. Just set it to be in one line and issue is solved!

"cannot be used as a function error"

#include "header.h"

int estimatedPopulation (int currentPopulation, float growthRate)
    return currentPopulation + currentPopulation * growthRate  / 100;

Use dynamic variable names in `dplyr`

Another alternative: use {} inside quotation marks to easily create dynamic names. This is similar to other solutions but not exactly the same, and I find it easier.


iris <- as_tibble(iris)

multipetal <- function(df, n) {
  df <- mutate(df, "petal.{n}" := Petal.Width * n)  ## problem arises here

for(i in 2:5) {
  iris <- multipetal(df=iris, n=i)

I think this comes from dplyr 1.0.0 but not sure (I also have rlang 4.7.0 if it matters).

How to check if a value exists in an object using JavaScript

getValue = function (object, key) {
    return key.split(".").reduce(function (obj, val) {
        return (typeof obj == "undefined" || obj === null || obj === "") ? obj : (_.isString(obj[val]) ? obj[val].trim() : obj[val]);}, object);

var obj = {
   "a": "test1",
   "b": "test2"

Function called:

 getValue(obj, "a");

Javascript - object key->value

I use the following syntax:

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

get error:

 var name = "error"

get message:

 name = "message"

jquery how to use multiple ajax calls one after the end of the other

We can simply use

async: false 

This will do your need.

PHP array: count or sizeof?

I know this is old but just wanted to mention that I tried this with PHP 7.2:

//Creating array with 1 000 000 elements
$a = array();
for ($i = 0; $i < 1000000; ++$i)
    $a[] = 100;

$time = time();
for ($i = 0; $i < 1000000000; ++$i)
    $b = count($a);
print("1 000 000 000 iteration of count() took ".(time()-$time)." sec\n");

$time = time();
for ($i = 0; $i < 1000000000; ++$i)
    $b = sizeof($a);
print("1 000 000 000 iteration of sizeof() took ".(time()-$time)." sec\n");

and the result was:

1 000 000 000 iteration of count() took 414 sec
1 000 000 000 iteration of sizeof() took 1369 sec

So just use count().

CSS - center two images in css side by side

Flexbox can do this with just two css rules on a surrounding div.

    display: flex;_x000D_
    justify-content: center;_x000D_
<div class="social-media">_x000D_
<a href="mailto:[email protected]">_x000D_
<img class="fblogo" border="0" alt="Mail" src=""/></a>_x000D_
<a href="" target="_blank">_x000D_
<img class="fblogo" border="0" alt="Facebook" src=""/></a>_x000D_

CSS values using HTML5 data attribute

You can create with javascript some css-rules, which you can later use in your styles:

var addRule = (function (sheet) {
    if(!sheet) return;
    return function (selector, styles) {
        if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
        if (sheet.addRule) return sheet.addRule(selector, styles);
}(document.styleSheets[document.styleSheets.length - 1]));

var i = 101;
while (i--) {
    addRule("[data-width='" + i + "%']", "width:" + i + "%");

This creates 100 pseudo-selectors like this:

[data-width='1%'] { width: 1%; }
[data-width='2%'] { width: 2%; }
[data-width='3%'] { width: 3%; }
[data-width='100%'] { width: 100%; }

Note: This is a bit offtopic, and not really what you (or someone) wants, but maybe helpful.

How to get a List<string> collection of values from app.config in WPF?

You could have them semi-colon delimited in a single value, e.g.


<add key="paths" value="C:\test1;C:\test2;C:\test3" />


var paths = new List<string>(ConfigurationManager.AppSettings["paths"].Split(new char[] { ';' }));

Installing PG gem on OS X - failure to build native extension

If you are using Ubuntu try to install following lib file

sudo apt-get install libpq-dev

and then

gem install pg

worked for me.

Adding Text to DataGridView Row Header

Here's a little "coup de pouce"

Public Class DataGridViewRHEx
Inherits DataGridView

Protected Overrides Function CreateRowsInstance() As System.Windows.Forms.DataGridViewRowCollection
    Dim dgvRowCollec As DataGridViewRowCollection = MyBase.CreateRowsInstance()
    AddHandler dgvRowCollec.CollectionChanged, AddressOf dvgRCChanged
    Return dgvRowCollec
End Function

Private Sub dvgRCChanged(sender As Object, e As System.ComponentModel.CollectionChangeEventArgs)
    If e.Action = System.ComponentModel.CollectionChangeAction.Add Then
        Dim dgvRow As DataGridViewRow = e.Element
        dgvRow.DefaultHeaderCellType = GetType(DataGridViewRowHeaderCellEx)
    End If
End Sub
End Class


Public Class DataGridViewRowHeaderCellEx
Inherits DataGridViewRowHeaderCell

Protected Overrides Sub Paint(graphics As System.Drawing.Graphics, clipBounds As System.Drawing.Rectangle, cellBounds As System.Drawing.Rectangle, rowIndex As Integer, dataGridViewElementState As System.Windows.Forms.DataGridViewElementStates, value As Object, formattedValue As Object, errorText As String, cellStyle As System.Windows.Forms.DataGridViewCellStyle, advancedBorderStyle As System.Windows.Forms.DataGridViewAdvancedBorderStyle, paintParts As System.Windows.Forms.DataGridViewPaintParts)
    If Not Me.OwningRow.DataBoundItem Is Nothing Then
        If TypeOf Me.OwningRow.DataBoundItem Is DataRowView Then

        End If
    End If

    formattedValue = CStr(Me.DataGridView.Rows(rowIndex).Tag)
    MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts)
End Sub
End Class

Pandas - replacing column values

You can also try using apply with get method of dictionary, seems to be little faster than replace:

data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)

Testing with timeit:



The slowest run took 5.83 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 510 µs per loop

Using apply:

data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)


The slowest run took 5.92 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 331 µs per loop

Note: apply with dictionary should be used if all the possible values of the columns in the dataframe are defined in the dictionary else, it will have empty for those not defined in dictionary.

How to remove duplicate values from a multi-dimensional array in PHP

If "remove duplicates" means "remove duplicates, but let one there", a solution might be to apply the array_unique(...) on the "identifier column" first and then to remove in the original array all the keys, that have been removed from the column array:

$array = [
        'id' => '123',
        'foo' => 'aaa',
        'bar' => 'bbb'
        'id' => '123',
        'foo' => 'ccc',
        'bar' => 'ddd'
        'id' => '567',
        'foo' => 'eee',
        'bar' => 'fff'

$ids = array_column($array, 'id');
$ids = array_unique($ids);
$array = array_filter($array, function ($key, $value) use ($ids) {
    return in_array($value, array_keys($ids));

The result is:

    [0] => Array
            [id] => 123
            [foo] => aaa
            [bar] => bbb

    [2] => Array
            [id] => 567
            [foo] => eee
            [bar] => fff


How to hide reference counts in VS2013?

Another option is to use mouse, right click on "x reference". Context menu "CodeLens Options" will appear, saving all the navigation headache.

SSRS Query execution failed for dataset

I also had a very similar issue with a very similar error message. My issue was that the database could not be connected to. In our case, we have mirrored databases and the connection string did not specify the Failover Partner. So when the database couldn't connect, it never went to the mirror and was throwing this error. Once I specified the Failover Partner in the connection string for my datasource, it resolved the issue.

What can MATLAB do that R cannot do?

Short answer: no, of course not. While any set of mathematical software packages will have their overlaps, they will always have biases towards certain problem domains. These biases figure strongly in whether or not you want to use one of these packages.

An example of what MATLAB can do that R cannot is interface to real-time hardware for signal processing/acquisition and control. A Simulink model in MATLAB can be configured both to run in simulation on your machine before compiling the code to execute on a real system taking measured data as input and calculating appropriate outputs (what was before a simulation of a control system is now a fully functioning one). With the appropriate hardware board in your machine, you can run real-time control systems through a PC.

R, by contrast, seems firmly set in the role of statistics, where I'm sure it out-performs what MATLAB can do. Similarly, Mathematica is better than MATLAB at symbolic maths; Python is better than MATLAB at general programming; gnuplot is better than all of them at actually creating graphs (er, I assume); and so on.

HTTP Error 503. The service is unavailable. App pool stops on accessing website

I had a similar issue. I solved it by adding my user to the "Log on as a batch job" policy under "Local Security Policy" > "Local Policies" > "User Rights Assignment".

Is there a function to round a float in C or do I need to write my own?

There is a round() function, also fround(), which will round to the nearest integer expressed as a double. But that is not what you want.

I had the same problem and wrote this:

#include <math.h>

   double db_round(double value, int nsig)
/* ===============
** Rounds double <value> to <nsig> significant figures.  Always rounds
** away from zero, so -2.6 to 1 sig fig will become -3.0.
** <nsig> should be in the range 1 - 15

    double     a, b;
    long long  i;
    int        neg = 0;

    if(!value) return value;

    if(value < 0.0)
        value = -value;
        neg = 1;

    i = nsig - log10(value);

    if(i) a = pow(10.0, (double)i);
    else  a = 1.0;

    b = value * a;
    i = b + 0.5;
    value = i / a;

    return neg ? -value : value;

Increasing the timeout value in a WCF service

Different timeouts mean different things. When you're working on the client.. you're probably looking mostly at the SendTimeout - check this reference - wonderful and relevant explanation:

It says:

Brief summary of binding timeout knobs...

Client side:

SendTimeout is used to initialize the OperationTimeout, which governs the whole interaction for sending a message (including receiving a reply message in a request-reply case).  This timeout also applies when sending reply messages from a CallbackContract method.
OpenTimeout and CloseTimeout are used when opening and closing channels (when no explicit timeout value is passed).
ReceiveTimeout is not used.

Server side:

Send, Open, and Close Timeout same as on client (for Callbacks).
ReceiveTimeout is used by ServiceFramework layer to initialize the session-idle timeout.

Python List & for-each access (Find/Replace in built-in list)

Python is not Java, nor C/C++ -- you need to stop thinking that way to really utilize the power of Python.

Python does not have pass-by-value, nor pass-by-reference, but instead uses pass-by-name (or pass-by-object) -- in other words, nearly everything is bound to a name that you can then use (the two obvious exceptions being tuple- and list-indexing).

When you do spam = "green", you have bound the name spam to the string object "green"; if you then do eggs = spam you have not copied anything, you have not made reference pointers; you have simply bound another name, eggs, to the same object ("green" in this case). If you then bind spam to something else (spam = 3.14159) eggs will still be bound to "green".

When a for-loop executes, it takes the name you give it, and binds it in turn to each object in the iterable while running the loop; when you call a function, it takes the names in the function header and binds them to the arguments passed; reassigning a name is actually rebinding a name (it can take a while to absorb this -- it did for me, anyway).

With for-loops utilizing lists, there are two basic ways to assign back to the list:

for i, item in enumerate(some_list):
    some_list[i] = process(item)


new_list = []
for item in some_list:
some_list[:] = new_list

Notice the [:] on that last some_list -- it is causing a mutation of some_list's elements (setting the entire thing to new_list's elements) instead of rebinding the name some_list to new_list. Is this important? It depends! If you have other names besides some_list bound to the same list object, and you want them to see the updates, then you need to use the slicing method; if you don't, or if you do not want them to see the updates, then rebind -- some_list = new_list.

Understanding the Gemfile.lock file

in regards to the exclamation mark I just found out it's on gems fetched via :git, e.g.

gem "foo", :git => "[email protected]:company/foo.git"

Where is the Keytool application?

It is in path/to/jdk/bin. Make sure that $JAVA_HOME is defined, and $JAVA_HOME/bin is added to $PATH, or else the 'keytool' command won't be recognized when called.

How to indent/format a selection of code in Visual Studio Code with Ctrl + Shift + F

F1 → open Keyboard Shortcuts → search for 'Indent Line', and change keybinding to Tab.

Right click > "Change when expression" to editorHasSelection && editorTextFocus && !editorReadonly

It will allow you to indent line when something in that line is selected (multiple lines still work).

How can I view the allocation unit size of a NTFS partition in Vista?

Easiest way, confirmed on 2012r2.

  1. Go to "This PC"
  2. Right click on the Disk
  3. Click on Format

Under drop down "allocation unit size" will be the value of what the Allocation of the Unit size disk already is.

How to write :hover using inline style?

Not gonna happen with CSS only

Inline javascript

<a href='index.html' 
    Click Me

In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:

<a href=""
   style="{color: blue; background: white}  /* a+=0 b+=0 c+=0 */
      :visited {color: green}           /* a+=0 b+=1 c+=0 */
      :hover {background: yellow}       /* a+=0 b+=1 c+=0 */
      :visited:hover {color: purple}    /* a+=0 b+=2 c+=0 */

but it was never implemented in the release of the spec as far as I know.

How to decrypt hash stored by bcrypt

You can use the password_verify function with the PHP. It verifies that a password matches with the hash

password_verify ( string $password , string $hash ) : bool

more details:

CSS Font Border?

You could perhaps emulate a text-stroke, using the css text-shadow (or -webkit-text-shadow/-moz-text-shadow) and a very low blur:

  text-shadow: 0 0 2px #000; /* horizontal-offset vertical-offset 'blur' colour */
  -moz-text-shadow: 0 0 2px #000;
  -webkit-text-shadow: 0 0 2px #000;

But while this is more widely available than the -webkit-text-stroke property, I doubt that it's available to the majority of your users, but that might not be a problem (graceful degradation, and all that).

jQuery xml error ' No 'Access-Control-Allow-Origin' header is present on the requested resource.'

You won't be able to make an ajax call to from a file deployed at due to the same-origin policy.

As the source (aka origin) page and the target URL are at different domains ( and, your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary GET.

In a few words, the same-origin policy says that browsers should only allow ajax calls to services at the same domain of the HTML page.


A page at can only directly request services that are at, like If the service is hosted at another domain (say, the browser won't make the call directly (as you'd expect). Instead, it will try to make a CORS request.

To put it shortly, to perform a (CORS) request* across different domains, your browser:

  • Will include an Origin header in the original request (with the page's domain as value) and perform it as usual; and then
  • Only if the server response to that request contains the adequate headers (Access-Control-Allow-Origin is one of them) allowing the CORS request, the browse will complete the call (almost** exactly the way it would if the HTML page was at the same domain).
    • If the expected headers don't come, the browser simply gives up (like it did to you).

* The above depicts the steps in a simple request, such as a regular GET with no fancy headers. If the request is not simple (like a POST with application/json as content type), the browser will hold it a moment, and, before fulfilling it, will first send an OPTIONS request to the target URL. Like above, it only will continue if the response to this OPTIONS request contains the CORS headers. This OPTIONS call is known as preflight request.
** I'm saying almost because there are other differences between regular calls and CORS calls. An important one is that some headers, even if present in the response, will not be picked up by the browser if they aren't included in the Access-Control-Expose-Headers header.

How to fix it?

Was it just a typo? Sometimes the JavaScript code has just a typo in the target domain. Have you checked? If the page is at it will only make regular calls to! Other URLs, such as or even or are considered different domains by the browser! Yes, if the port is different, then it is a different domain!

Add the headers. The simplest way to enable CORS is by adding the necessary headers (as Access-Control-Allow-Origin) to the server's responses. (Each server/language has a way to do that - check some solutions here.)

Last resort: If you don't have server-side access to the service, you can also mirror it (through tools such as reverse proxies), and include all the necessary headers there.

document.getElementById(id).focus() is not working for firefox or chrome

Try using a timer:

var mnumber = document.getElementById('mobileno').value;
if (mnumber.length >=10) 
    alert("Mobile Number Should be in 10 digits only");
    document.getElementById('mobileno').value = "";
    window.setTimeout(function ()
    }, 0);
    return false;

A timer with a count of 0 will run when the thread becomes idle. If that doesn't help, try the code (with the timer) in the onblur event instead.

Why javascript getTime() is not a function?

dat1 and dat2 are Strings in JavaScript. There is no getTime function on the String prototype. I believe you want the Date.parse() function:

You would use it like this:

var date = Date.parse(dat1);

Python/BeautifulSoup - how to remove all tags from an element?

Code to simply get the contents as text instead of html:

'html_text' parameter is the string which you will pass in this function to get the text

from bs4 import BeautifulSoup

soup = BeautifulSoup(html_text, 'lxml')
text = soup.get_text()