Programs & Examples On #Qtcpserver

QTcpServer is a Qt class embedding a TCP-based server.

Python syntax for "if a or b or c but not all of them"

When every given bool is True, or when every given bool is False...
they all are equal to each other!

So, we just need to find two elements which evaluates to different bools
to know that there is at least one True and at least one False.

My short solution:

not bool(a)==bool(b)==bool(c)

I belive it short-circuits, cause AFAIK a==b==c equals a==b and b==c.

My generalized solution:

def _any_but_not_all(first, iterable): #doing dirty work
    bool_first=bool(first)
    for x in iterable:
        if bool(x) is not bool_first:
            return True
    return False

def any_but_not_all(arg, *args): #takes any amount of args convertable to bool
    return _any_but_not_all(arg, args)

def v_any_but_not_all(iterable): #takes iterable or iterator
    iterator=iter(iterable)
    return _any_but_not_all(next(iterator), iterator)

I wrote also some code dealing with multiple iterables, but I deleted it from here because I think it's pointless. It's however still available here.

Difference between scaling horizontally and vertically for databases

Traditional relational databases were designed as client/server database systems. They can be scaled horizontally but the process to do so tends to be complex and error prone. NewSQL databases like NuoDB are memory-centric distributed database systems designed to scale out horizontally while maintaining the SQL/ACID properties of traditional RDBMS.

For more information on NuoDB, read their technical white paper.

iptables LOG and DROP in one rule

Although already over a year old, I stumbled across this question a couple of times on other Google search and I believe I can improve on the previous answer for the benefit of others.

Short answer is you cannot combine both action in one line, but you can create a chain that does what you want and then call it in a one liner.

Let's create a chain to log and accept:

iptables -N LOG_ACCEPT

And let's populate its rules:

iptables -A LOG_ACCEPT -j LOG --log-prefix "INPUT:ACCEPT:" --log-level 6
iptables -A LOG_ACCEPT -j ACCEPT

Now let's create a chain to log and drop:

iptables -N LOG_DROP

And let's populate its rules:

iptables -A LOG_DROP -j LOG --log-prefix "INPUT:DROP: " --log-level 6
iptables -A LOG_DROP -j DROP

Now you can do all actions in one go by jumping (-j) to you custom chains instead of the default LOG / ACCEPT / REJECT / DROP:

iptables -A <your_chain_here> <your_conditions_here> -j LOG_ACCEPT
iptables -A <your_chain_here> <your_conditions_here> -j LOG_DROP

tomcat - CATALINA_BASE and CATALINA_HOME variables

I can't say I know the best practice, but here's my perspective.

Are you using these variables for anything?

Personally, I haven't needed to change neither, on Linux nor Windows, in environments varying from development to production. Unless you are doing something particular that relies on them, chances are you could leave them alone.

catalina.sh sets the variables that Tomcat needs to work out of the box. It also says that CATALINA_BASE is optional:

#   CATALINA_HOME   May point at your Catalina "build" directory.
#
#   CATALINA_BASE   (Optional) Base directory for resolving dynamic portions
#                   of a Catalina installation.  If not present, resolves to
#                   the same directory that CATALINA_HOME points to.

I'm pretty sure you'll find out whether or not your setup works when you start your server.

(HTML) Download a PDF file instead of opening them in browser when clicked

I needed to do this for files created with dynamic names in a particular folder and served by IIS.

This worked for me:

  • In IIS, go that folder and double click HTTP Response Headers.
  • Add a new header with the following info:

    Name: content-disposition Value: attachment

(from: http://forums.iis.net/t/1175103.aspx?add+CustomHeaders+only+for+certain+file+types+)

T-SQL Substring - Last 3 Characters

SELECT RIGHT(column, 3)

That's all you need.

You can also do LEFT() in the same way.

Bear in mind if you are using this in a WHERE clause that the RIGHT() can't use any indexes.

SeekBar and media player in android

The below code worked for me.

I've created a method for seekbar

@Override
public void onPrepared(MediaPlayer mediaPlayer) {
    mp.start();
     getDurationTimer();
    getSeekBarStatus();


}
//Creating duration time method
public void getDurationTimer(){
    final long minutes=(mSongDuration/1000)/60;
    final int seconds= (int) ((mSongDuration/1000)%60);
    SongMaxLength.setText(minutes+ ":"+seconds);


}



 //creating a method for seekBar progress
public void getSeekBarStatus(){

    new Thread(new Runnable() {

        @Override
        public void run() {
            // mp is your MediaPlayer
            // progress is your ProgressBar

            int currentPosition = 0;
            int total = mp.getDuration();
            seekBar.setMax(total);
            while (mp != null && currentPosition < total) {
                try {
                    Thread.sleep(1000);
                    currentPosition = mp.getCurrentPosition();
                } catch (InterruptedException e) {
                    return;
                }
                seekBar.setProgress(currentPosition);

            }
        }
    }).start();





    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        int progress=0;

        @Override
        public void onProgressChanged(final SeekBar seekBar, int ProgressValue, boolean fromUser) {
            if (fromUser) {
                mp.seekTo(ProgressValue);//if user drags the seekbar, it gets the position and updates in textView.
            }
            final long mMinutes=(ProgressValue/1000)/60;//converting into minutes
            final int mSeconds=((ProgressValue/1000)%60);//converting into seconds
            SongProgress.setText(mMinutes+":"+mSeconds);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });
}

SongProgress and SongMaxLength are the TextView to show song duration and song length.

SQL - HAVING vs. WHERE

First we should know the order of execution of Clauses i.e FROM > WHERE > GROUP BY > HAVING > DISTINCT > SELECT > ORDER BY. Since WHERE Clause gets executed before GROUP BY Clause the records cannot be filtered by applying WHERE to a GROUP BY applied records.

"HAVING is same as the WHERE clause but is applied on grouped records".

first the WHERE clause fetches the records based on the condition then the GROUP BY clause groups them accordingly and then the HAVING clause fetches the group records based on the having condition.

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

Install opencv for Python 3.3

Whether or not you install opencv3 manually or from Gohlke's whl package, I found the need to create/edit the file cv.py in site_packages as follows to make compatable with old code:

import cv2 as cv

run a python script in terminal without the python command

Add the following line to the beginning script1.py

#!/usr/bin/env python

and then make the script executable:

$ chmod +x script1.py

If the script resides in a directory that appears in your PATH variable, you can simply type

$ script1.py

Otherwise, you'll need to provide the full path (either absolute or relative). This includes the current working directory, which should not be in your PATH.

$ ./script1.py

Transposing a 2D-array in JavaScript

You can achieve this without loops by using the following.

It looks very elegant and it does not require any dependencies such as jQuery of Underscore.js.

function transpose(matrix) {  
    return zeroFill(getMatrixWidth(matrix)).map(function(r, i) {
        return zeroFill(matrix.length).map(function(c, j) {
            return matrix[j][i];
        });
    });
}

function getMatrixWidth(matrix) {
    return matrix.reduce(function (result, row) {
        return Math.max(result, row.length);
    }, 0);
}

function zeroFill(n) {
    return new Array(n+1).join('0').split('').map(Number);
}

Minified

function transpose(m){return zeroFill(m.reduce(function(m,r){return Math.max(m,r.length)},0)).map(function(r,i){return zeroFill(m.length).map(function(c,j){return m[j][i]})})}function zeroFill(n){return new Array(n+1).join("0").split("").map(Number)}

Here is a demo I threw together. Notice the lack of loops :-)

_x000D_
_x000D_
// Create a 5 row, by 9 column matrix._x000D_
var m = CoordinateMatrix(5, 9);_x000D_
_x000D_
// Make the matrix an irregular shape._x000D_
m[2] = m[2].slice(0, 5);_x000D_
m[4].pop();_x000D_
_x000D_
// Transpose and print the matrix._x000D_
println(formatMatrix(transpose(m)));_x000D_
_x000D_
function Matrix(rows, cols, defaultVal) {_x000D_
    return AbstractMatrix(rows, cols, function(r, i) {_x000D_
        return arrayFill(cols, defaultVal);_x000D_
    });_x000D_
}_x000D_
function ZeroMatrix(rows, cols) {_x000D_
    return AbstractMatrix(rows, cols, function(r, i) {_x000D_
        return zeroFill(cols);_x000D_
    });_x000D_
}_x000D_
function CoordinateMatrix(rows, cols) {_x000D_
    return AbstractMatrix(rows, cols, function(r, i) {_x000D_
        return zeroFill(cols).map(function(c, j) {_x000D_
            return [i, j];_x000D_
        });_x000D_
    });_x000D_
}_x000D_
function AbstractMatrix(rows, cols, rowFn) {_x000D_
    return zeroFill(rows).map(function(r, i) {_x000D_
        return rowFn(r, i);_x000D_
    });_x000D_
}_x000D_
/** Matrix functions. */_x000D_
function formatMatrix(matrix) {_x000D_
    return matrix.reduce(function (result, row) {_x000D_
        return result + row.join('\t') + '\n';_x000D_
    }, '');_x000D_
}_x000D_
function copy(matrix) {  _x000D_
    return zeroFill(matrix.length).map(function(r, i) {_x000D_
        return zeroFill(getMatrixWidth(matrix)).map(function(c, j) {_x000D_
            return matrix[i][j];_x000D_
        });_x000D_
    });_x000D_
}_x000D_
function transpose(matrix) {  _x000D_
    return zeroFill(getMatrixWidth(matrix)).map(function(r, i) {_x000D_
        return zeroFill(matrix.length).map(function(c, j) {_x000D_
            return matrix[j][i];_x000D_
        });_x000D_
    });_x000D_
}_x000D_
function getMatrixWidth(matrix) {_x000D_
    return matrix.reduce(function (result, row) {_x000D_
        return Math.max(result, row.length);_x000D_
    }, 0);_x000D_
}_x000D_
/** Array fill functions. */_x000D_
function zeroFill(n) {_x000D_
  return new Array(n+1).join('0').split('').map(Number);_x000D_
}_x000D_
function arrayFill(n, defaultValue) {_x000D_
    return zeroFill(n).map(function(value) {_x000D_
        return defaultValue || value;_x000D_
    });_x000D_
}_x000D_
/** Print functions. */_x000D_
function print(str) {_x000D_
    str = Array.isArray(str) ? str.join(' ') : str;_x000D_
    return document.getElementById('out').innerHTML += str || '';_x000D_
}_x000D_
function println(str) {_x000D_
    print.call(null, [].slice.call(arguments, 0).concat(['<br />']));_x000D_
}
_x000D_
#out {_x000D_
    white-space: pre;_x000D_
}
_x000D_
<div id="out"></div>
_x000D_
_x000D_
_x000D_

Programmatically open new pages on Tabs

You can't directly control this, because it's an option controlled by Internet Explorer users.

Opening pages using Window.open with a different window name will open in a new browser window like a popup, OR open in a new tab, if the user configured the browser to do so.

In which case do you use the JPA @JoinTable annotation?

It's the only solution to map a ManyToMany association : you need a join table between the two entities tables to map the association.

It's also used for OneToMany (usually unidirectional) associations when you don't want to add a foreign key in the table of the many side and thus keep it independent of the one side.

Search for @JoinTable in the hibernate documentation for explanations and examples.

AWS ssh access 'Permission denied (publickey)' issue

use...

# chmod 400 ec2-keypair.pem

don't use the 600 permission otherwise you might overwrite your key accidently.

SSH to Vagrant box in Windows?

A good alternative to PuTTY is the Mintty terminal emulator. It has more configurable options than PuTTY.

AngularJs - ng-model in a SELECT

You can also put the item with the default value selected out of the ng-repeat like follow :

<div ng-app="app" ng-controller="myCtrl">
    <select class="form-control" ng-change="unitChanged()" ng-model="data.unit">
        <option value="yourDefaultValue">Default one</option>
        <option ng-selected="data.unit == item.id" ng-repeat="item in units" ng-value="item.id">{{item.label}}</option>
    </select>
</div>

and don't forget the value atribute if you leave it blank you will have the same issue.

How to format dateTime in django template?

This is exactly what you want. Try this:

{{ wpis.entry.lastChangeDate|date:'Y-m-d H:i' }}

How to compare two dates in Objective-C

If you make both dates NSDates you can use NSDate's compare: method:

NSComparisonResult result = [Date2 compare:Date1];

if(result==NSOrderedAscending)
    NSLog(@"Date1 is in the future");
else if(result==NSOrderedDescending)
    NSLog(@"Date1 is in the past");
else
    NSLog(@"Both dates are the same");

You can take a look at the docs here.

gdb: how to print the current line or find the current line number?

All the answers above are correct, What I prefer is to use tui mode (ctrl+X A or 'tui enable') which shows your location and the function in a separate window which is very helpful for the users. Hope that helps too.

Invoking a jQuery function after .each() has completed

I'm using something like this:

$.when(
           $.each(yourArray, function (key, value) {
                // Do Something in loop here
            })
          ).then(function () {
               // After loop ends.
          });

Get week number (in the year) from a date PHP

Just as a suggestion:

<?php echo date("W", strtotime("2012-10-18")); ?>

Might be a little simpler than all that lot.

Other things you could do:

<?php echo date("Weeknumber: W", strtotime("2012-10-18 01:00:00")); ?>
<?php echo date("Weeknumber: W", strtotime($MY_DATE)); ?>

Python convert tuple to string

This works:

''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))

It will produce:

'abcdgxre'

You can also use a delimiter like a comma to produce:

'a,b,c,d,g,x,r,e'

By using:

','.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))

MySql sum elements of a column

Try this:

select sum(a), sum(b), sum(c)
from your_table

AttributeError: 'str' object has no attribute 'strftime'

You should use datetime object, not str.

>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'

To get the datetime object from the string, use datetime.datetime.strptime:

>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'

Write bytes to file

This example reads 6 bytes into a byte array and writes it to another byte array. It does an XOR operation with the bytes so that the result written to the file is the same as the original starting values. The file is always 6 bytes in size, since it writes at position 0.

using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
        byte[] b1 = { 1, 2, 4, 8, 16, 32 };
        byte[] b2 = new byte[6];
        byte[] b3 = new byte[6];
        byte[] b4 = new byte[6];

        FileStream f1;
        f1 = new FileStream("test.txt", FileMode.Create, FileAccess.Write);

        // write the byte array into a new file
        f1.Write(b1, 0, 6);
        f1.Close();

        // read the byte array
        f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Read);

        f1.Read(b2, 0, 6);
        f1.Close();

        // make changes to the byte array
        for (int i = 1; i < b2.Length; i++)
        {
            b2[i] = (byte)(b2[i] ^ (byte)10); //xor 10
        }

        f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Write);
        // write the new byte array into the file
        f1.Write(b2, 0, 6);
        f1.Close();

        f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Read);

        // read the byte array
        f1.Read(b3, 0, 6);
        f1.Close();

        // make changes to the byte array
        for (int i = 1; i < b3.Length; i++)
        {
            b4[i] = (byte)(b3[i] ^ (byte)10); //xor 10
        }

        f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Write);

        // b4 will have the same values as b1
        f1.Write(b4, 0, 6);
        f1.Close();
        }
    }
}

How to enable MySQL Query Log?

I had to drop and recreate the general log at one point. During the recreation, character sets got messed up and I ended up having this error in the logs:

[ERROR] Incorrect definition of table mysql.general_log: expected the type of column 'user_host' at position 1 to have character set 'utf8' but found character set 'latin1'

So if the standard answer of "check to make sure logging is on" doesn't work for you, check to make sure your fields have the right character set.

node.js http 'get' request with query string parameters

Check out the request module.

It's more full featured than node's built-in http client.

var request = require('request');

var propertiesObject = { field1:'test1', field2:'test2' };

request({url:url, qs:propertiesObject}, function(err, response, body) {
  if(err) { console.log(err); return; }
  console.log("Get response: " + response.statusCode);
});

"use database_name" command in PostgreSQL

In pgAdmin you can also use

SET search_path TO your_db_name;

How to convert Windows end of line in Unix end of line (CR/LF to LF)

Go back to Windows, tell Eclipse to change the encoding to UTF-8, then back to Unix and run d2u on the files.

Setting log level of message at runtime in slf4j

The method I use is to import the ch.qos.logback modules and then type-cast the slf4j Logger instance to a ch.qos.logback.classic.Logger. This instance includes a setLevel() method.

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;

Logger levelSet = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);

// Now you can set the desired logging-level
levelSet.setLevel( Level.OFF );

To find out the possible Logging-levels, you can explode the ch.qos.logback class to see all the possible values for Level:

prompt$ javap -cp logback-classic-1.2.3.jar ch.qos.logback.classic.Level

The results are the following:

{
   // ...skipping
   public static final ch.qos.logback.classic.Level OFF;
   public static final ch.qos.logback.classic.Level ERROR;
   public static final ch.qos.logback.classic.Level WARN;
   public static final ch.qos.logback.classic.Level INFO;
   public static final ch.qos.logback.classic.Level DEBUG;
   public static final ch.qos.logback.classic.Level TRACE;
   public static final ch.qos.logback.classic.Level ALL;
}

How to link to a <div> on another page?

Take a look at anchor tags. You can create an anchor with

<div id="anchor-name">Heading Text</div>

and refer to it later with

<a href="http://server/page.html#anchor-name">Link text</a>

How to access List elements

Tried list[:][0] to show all first member of each list inside list is not working. Result is unknowingly will same as list[0][:]

So i use list comprehension like this:

[i[0] for i in list] which return first element value for each list inside list.

How to restore a SQL Server 2012 database to SQL Server 2008 R2?

Right click on your database and select Tasks -> Generate Scripts

Select things you want to restore or just let the complete database be selected by default.

Now click Next -> Click Advanced and Choose 'Script for Server Version' to the 'ssms version' you want to restore like 2008 or 2008 R2 or other.

also, select 'type of data to script' to 'Schema and Data'

Finally execute this .sql file on destination ssms and Change Database Name in first Line Use Database

if database is not there then create one and if you get error with executing the script execute the script from alter keyword to complete bottom.

How do I make a div full screen?

<div id="placeholder" style="position:absolute; top:0; right:0; bottom:0; left:0;"></div>

How to perform a for loop on each character in a string in Bash?

It is also possible to split the string into a character array using fold and then iterate over this array:

for char in `echo "??????" | fold -w1`; do
    echo $char
done

How to replace all spaces in a string

var result = replaceSpace.replace(/ /g, ";");

Here, / /g is a regex (regular expression). The flag g means global. It causes all matches to be replaced.

How do I convert a Swift Array to a String?

Create extension for an Array:

extension Array {

    var string: String? {

        do {

            let data = try JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted])

            return String(data: data, encoding: .utf8)

        } catch {

            return nil
        }
    }
}

php execute a background process

If you need to just do something in background without the PHP page waiting for it to complete, you could use another (background) PHP script that is "invoked" with wget command. This background PHP script will be executed with privileges, of course, as any other PHP script on your system.

Here is an example on Windows using wget from gnuwin32 packages.

The background code (file test-proc-bg.php) as an exmple ...

sleep(5);   // some delay
file_put_contents('test.txt', date('Y-m-d/H:i:s.u')); // writes time in a file

The foreground script, the one invoking ...

$proc_command = "wget.exe http://localhost/test-proc-bg.php -q -O - -b";
$proc = popen($proc_command, "r");
pclose($proc);

You must use the popen/pclose for this to work properly.

The wget options:

-q    keeps wget quiet.
-O -  outputs to stdout.
-b    works on background

How to close current tab in a browser window?

You can use window.close() to close browser tab.

Smooth scroll without the use of jQuery

I've made an example without jQuery here : http://codepen.io/sorinnn/pen/ovzdq

/**
    by Nemes Ioan Sorin - not an jQuery big fan 
    therefore this script is for those who love the old clean coding style  
    @id = the id of the element who need to bring  into view

    Note : this demo scrolls about 12.700 pixels from Link1 to Link3
*/
(function()
{
      window.setTimeout = window.setTimeout; //
})();

      var smoothScr = {
      iterr : 30, // set timeout miliseconds ..decreased with 1ms for each iteration
        tm : null, //timeout local variable
      stopShow: function()
      {
        clearTimeout(this.tm); // stopp the timeout
        this.iterr = 30; // reset milisec iterator to original value
      },
      getRealTop : function (el) // helper function instead of jQuery
      {
        var elm = el; 
        var realTop = 0;
        do
        {
          realTop += elm.offsetTop;
          elm = elm.offsetParent;
        }
        while(elm);
        return realTop;
      },
      getPageScroll : function()  // helper function instead of jQuery
      {
        var pgYoff = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
        return pgYoff;
      },
      anim : function (id) // the main func
      {
        this.stopShow(); // for click on another button or link
        var eOff, pOff, tOff, scrVal, pos, dir, step;

        eOff = document.getElementById(id).offsetTop; // element offsetTop

        tOff =  this.getRealTop(document.getElementById(id).parentNode); // terminus point 

        pOff = this.getPageScroll(); // page offsetTop

        if (pOff === null || isNaN(pOff) || pOff === 'undefined') pOff = 0;

        scrVal = eOff - pOff; // actual scroll value;

        if (scrVal > tOff) 
        {
          pos = (eOff - tOff - pOff); 
          dir = 1;
        }
        if (scrVal < tOff)
        {
          pos = (pOff + tOff) - eOff;
          dir = -1; 
        }
        if(scrVal !== tOff) 
        {
          step = ~~((pos / 4) +1) * dir;

          if(this.iterr > 1) this.iterr -= 1; 
          else this.itter = 0; // decrease the timeout timer value but not below 0
          window.scrollBy(0, step);
          this.tm = window.setTimeout(function()
          {
             smoothScr.anim(id);  
          }, this.iterr); 
        }  
        if(scrVal === tOff) 
        { 
          this.stopShow(); // reset function values
          return;
        }
    }
 }

Escaping special characters in Java Regular Expressions

use

pattern.compile("\"");
String s= p.toString()+"yourcontent"+p.toString();

will give result as yourcontent as is

How to make a <div> always full screen?

This is the trick I use. Good for responsive designs. Works perfectly when user tries to mess with browser resizing.

<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style type="text/css">
        #container {
            position: absolute;
            width: 100%;
            min-height: 100%;
            left: 0;
            top: 0;
        }
    </style>
</head>

<body>
    <div id="container">some content</div>
</body>

Why is the time complexity of both DFS and BFS O( V + E )

Time complexity is O(E+V) instead of O(2E+V) because if the time complexity is n^2+2n+7 then it is written as O(n^2).

Hence, O(2E+V) is written as O(E+V)

because difference between n^2 and n matters but not between n and 2n.

How to change icon on Google map marker

Manish, Eden after your suggestion: here is the code. But still showing the red(Default) icon.

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

<script type="text/javascript">
var markers = [
            {
            "title": 'This is title',
            "lat": '-37.801578',
            "lng": '145.060508',
        "icon": 'http://maps.gstatic.com/mapfiles/ridefinder-images/mm_20_green.png',
            "description": 'Vikash Rathee. <br/><a href="http://www.pricingindia.in/pincode.aspx">Pin Code by City</a>'
        }
];
</script>
<script type="text/javascript">
    window.onload = function () {
        var mapOptions = {
            center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
            zoom: 10,
            flat: true,
            styles: [ { "stylers": [ { "hue": "#4bd6bf" }, { "gamma": "1.58" } ] } ],
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var infoWindow = new google.maps.InfoWindow();
        var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
        for (i = 0; i < markers.length; i++) {
            var data = markers[i]
            var myLatlng = new google.maps.LatLng(data.lat, data.lng);
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
        icon: markers[i][3],
                title: data.title
            });
            (function (marker, data) {
                google.maps.event.addListener(marker, "click", function (e) {
                    infoWindow.setContent(data.description);
                    infoWindow.open(map, marker);
                });
            })(marker, data);
        }
    }
</script>


<div id="dvMap" style="width: 100%; height: 100%">
</div>

How do I pass a command line argument while starting up GDB in Linux?

Once gdb starts, you can run the program using "r args".

So if you are running your code by:

$ executablefile arg1 arg2 arg3 

Debug it on gdb by:

$ gdb executablefile  
(gdb) r arg1 arg2 arg3

Java for loop multiple variables

Instead of this : for(int a = 0, b = 1; a<cards.length-1; b=a+1; a++;){

It should be

for(int a = 0, b = 1; a<cards.length()-1; b=a+1, a++){
                                     ^         ^    ^  
                                     |         |    |  
                                     |         |    |  
            -------------------------------------------Note the changes
           |                    
           v                                                  |
   if(rank==cards.substring(a,b){                             |
-------------------------------------------------------------                                  
|
v
System.out.println(c); //capital S in system

How can I count the number of children?

Try to get using:

var count = $("ul > li").size();
alert(count);

Save multiple sheets to .pdf

I recommend adding the following line after the export to PDF:

ThisWorkbook.Sheets("Sheet1").Select

(where eg. Sheet1 is the single sheet you want to be active afterwards)

Leaving multiple sheets in a selected state may cause problems executing some code. (eg. unprotect doesn't function properly when multiple sheets are actively selected.)

How to resolve a Java Rounding Double issue

To control the precision of floating point arithmetic, you should use java.math.BigDecimal. Read The need for BigDecimal by John Zukowski for more information.

Given your example, the last line would be as following using BigDecimal.

import java.math.BigDecimal;

BigDecimal premium = BigDecimal.valueOf("1586.6");
BigDecimal netToCompany = BigDecimal.valueOf("708.75");
BigDecimal commission = premium.subtract(netToCompany);
System.out.println(commission + " = " + premium + " - " + netToCompany);

This results in the following output.

877.85 = 1586.6 - 708.75

Set style for TextView programmatically

Parameter int defStyleAttr does not specifies the style. From the Android documentation:

defStyleAttr - An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults.

To setup the style in View constructor we have 2 possible solutions:

  1. With use of ContextThemeWrapper:

    ContextThemeWrapper wrappedContext = new ContextThemeWrapper(yourContext, R.style.your_style);
    TextView textView = new TextView(wrappedContext, null, 0);
    
  2. With four-argument constructor (available starting from LOLLIPOP):

    TextView textView = new TextView(yourContext, null, 0, R.style.your_style);
    

Key thing for both solutions - defStyleAttr parameter should be 0 to apply our style to the view.

org.hibernate.MappingException: Unknown entity: annotations.Users

The Hibernate configuration file must define the entity classes:

<mapping class="annotations.Users"/>

Or you must explicitly add the class to the configuration using

configuration.addClass(annotations.Users.class)
// Read mappings as a application resourceName
 // addResource is for add hbml.xml files in case of declarative approach
configuration.addResource("myFile.hbm.xml");  // not hibernateAnnotations.cfg.xml

Code snippet or shortcut to create a constructor in Visual Studio

If you want to see the list of all available snippets:

Press Ctrl + K and then X.

Download files from server php

Here is the code that will not download courpt files

$filename = "myfile.jpg";
$file = "/uploads/images/".$filename;

header('Content-type: application/octet-stream');
header("Content-Type: ".mime_content_type($file));
header("Content-Disposition: attachment; filename=".$filename);
while (ob_get_level()) {
    ob_end_clean();
}
readfile($file);

I have included mime_content_type which will return content type of file .

To prevent from corrupt file download i have added ob_get_level() and ob_end_clean();

The application may be doing too much work on its main thread

I had the same problem. Android Emulator worked perfectly on Android < 6.0. When I used emulator Nexus 5 (Android 6.0), the app worked very slow with I/Choreographer: Skipped frames in the logs.

So, I solved this problem by changing in Manifest file hardwareAccelerated option to true like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <application android:hardwareAccelerated="true">
        ...
    </application>
</manifest>

Detect change to ngModel on a select tag (Angular 2)

I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"

in my .html

<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">

then in my component.ts

reSearch(newValue: string) {
    //this.searchText would equal the new value
    //handle my filtering with the new value
}

How to run a C# application at Windows startup?

I did not find any of the above code worked. Maybe that's because my app is running .NET 3.5. I don't know. The following code worked perfectly for me. I got this from a senior level .NET app developer on my team.

Write(Microsoft.Win32.Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\", "WordWatcher", "\"" + Application.ExecutablePath.ToString() + "\"");
public bool Write(RegistryKey baseKey, string keyPath, string KeyName, object Value)
{
    try
    {
        // Setting 
        RegistryKey rk = baseKey;
        // I have to use CreateSubKey 
        // (create or open it if already exits), 
        // 'cause OpenSubKey open a subKey as read-only 
        RegistryKey sk1 = rk.CreateSubKey(keyPath);
        // Save the value 
        sk1.SetValue(KeyName.ToUpper(), Value);

        return true;
    }
    catch (Exception e)
    {
        // an error! 
        MessageBox.Show(e.Message, "Writing registry " + KeyName.ToUpper());
        return false;
    }
}

Import Error: No module named numpy

You can simply use

pip install numpy

Or for python3, use

pip3 install numpy

SQL JOIN and different types of JOINs

I have created an illustration that explains better than words, in my opinion: SQL Join table of explanation

jQuery object equality

First order your object based on key using this function

function sortObject(o) {
    return Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {});
}

Then, compare the stringified version of your object, using this funtion

function isEqualObject(a,b){
    return JSON.stringify(sortObject(a)) == JSON.stringify(sortObject(b));
}

Here is an example

Assuming objects keys are ordered differently and are of the same values

var obj1 = {"hello":"hi","world":"earth"}
var obj2 = {"world":"earth","hello":"hi"}

isEqualObject(obj1,obj2);//returns true

Subtracting time.Duration from time in Go

Try AddDate:

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()

    fmt.Println("now:", now)

    then := now.AddDate(0, -1, 0)

    fmt.Println("then:", then)
}

Produces:

now: 2009-11-10 23:00:00 +0000 UTC
then: 2009-10-10 23:00:00 +0000 UTC

Playground: http://play.golang.org/p/QChq02kisT

OS X: equivalent of Linux's wget

Use curl;

curl http://127.0.0.1:8000 -o index.html

Apache SSL Configuration Error (SSL Connection Error)

I was getting the same error in chrome (and different one in Firefox, IE). Also in error.log i was getting [error] [client cli.ent.ip.add] Invalid method in request \x16\x03 Following the instructions form this site I changed my configuration FROM:

<VirtualHost subdomain.domain.com:443>

   ServerAdmin [email protected]
   ServerName subdomain.domain.com

   SSLEngine On
   SSLCertificateFile conf/ssl/ssl.crt
   SSLCertificateKeyFile conf/ssl/ssl.key
</VirtualHost>

TO:

<VirtualHost _default_:443>

   ServerAdmin [email protected]
   ServerName subdomain.domain.com

   SSLEngine On
   SSLCertificateFile conf/ssl/ssl.crt
   SSLCertificateKeyFile conf/ssl/ssl.key
</VirtualHost>

Now it's working fine :)

Capturing "Delete" Keypress with jQuery

You shouldn't use the keypress event, but the keyup or keydown event because the keypress event is intended for real (printable) characters. keydown is handled at a lower level so it will capture all nonprinting keys like delete and enter.

Match multiline text using regular expression

The multiline flag tells regex to match the pattern to each line as opposed to the entire string for your purposes a wild card will suffice.

node.js Error: connect ECONNREFUSED; response from server

I got this error because my AdonisJS server was not running before I ran the test. Running the server first fixed it.

'uint32_t' identifier not found error

I have the same error and it fixed it including in the file the following

#include <stdint.h>

at the beginning of your file.

How to remove leading zeros from alphanumeric text?

A clear way without any need of regExp and any external libraries.

public static String trimLeadingZeros(String source) {
    for (int i = 0; i < source.length(); ++i) {
        char c = source.charAt(i);
        if (c != '0') {
            return source.substring(i);
        }
    }
    return ""; // or return "0";
}

Skipping error in for-loop

Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction() function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!

How to install a .ipa file into my iPhone?

You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.

Getting the number of filled cells in a column (VBA)

You may also use:

UsedRange.Rows.Count

How to add a Try/Catch to SQL Stored Procedure

Create Proc[usp_mquestions]  
( 
 @title  nvarchar(500),   --0
 @tags  nvarchar(max),   --1
 @category  nvarchar(200),   --2
 @ispoll  char(1),   --3
 @descriptions  nvarchar(max),   --4
)              
 AS  
 BEGIN TRY




BEGIN
DECLARE @message varchar(1000); 
DECLARE @tempid bigint; 

IF((SELECT count(id) from  [xyz] WHERE title=@title)>0)
BEGIN
SELECT 'record already existed.';
END
ELSE
BEGIN               


if @id=0 
begin 
select @tempid =id from [xyz] where id=@id;

if @tempid is null 
BEGIN 
        INSERT INTO xyz
        (entrydate,updatedate)
        VALUES
        (GETDATE(),GETDATE())

        SET @tempid=@@IDENTITY;
 END 
END 
ELSE 
BEGIN 
set @tempid=@id 
END 
if @tempid>0 
BEGIN 

    -- Updation of table begin--


UPDATE  tab_questions
set title=@title, --0 
 tags=@tags, --1 
 category=@category, --2 
 ispoll=@ispoll, --3 
 descriptions=@descriptions, --4 
 status=@status, --5

WHERE id=@tempid ; --9 ;


IF @id=0 
BEGIN 
SET @message= 'success:Record added successfully:'+ convert(varchar(10), @tempid)
END 
ELSE 
BEGIN 
SET @message= 'success:Record updated successfully.:'+ convert(varchar(10), @tempid)

END 
END 
ELSE 
BEGIN 
SET @message= 'failed:invalid request:'+convert(varchar(10), @tempid)
END 

END
END

END TRY
BEGIN CATCH
    SET @message='failed:'+ ERROR_MESSAGE();
END CATCH
SELECT @message;

Remove spaces from a string in VB.NET

This will remove spaces only, matches the SQL functionality of rtrim(ltrim(myString))

Dim charstotrim() As Char = {" "c}
myString = myString .Trim(charstotrim) 

The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication

To diagnose this problem, run the service under the Visual Studio debugger. Use the menu: Debug|Exceptions and indicate that you want to break when an Exception is thrown.

The original exception thrown will have a much better error message than "..it is in the Faulted state."

For example I was getting this exception from ServiceHost.Open(), but when I caught the original exception at the time it was thrown, the error message was:

Service 'MyServiceName' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.

Fixing the spelling error in App.config solved the problem.

How to change the button color when it is active using bootstrap?

HTML--

<div class="col-sm-12" id="my_styles">
   <button type="submit" class="btn btn-warning" id="1">Button1</button>
   <button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>

css--

.active{
         background:red;
    }
 button.btn:active{
     background:red;
 }

jQuery--

jQuery("#my_styles .btn").click(function(){
    jQuery("#my_styles .btn").removeClass('active');
    jQuery(this).toggleClass('active'); 

});

view the live demo on jsfiddle

How do I exit the Vim editor?

If you want to quit without saving in Vim and have Vim return a non-zero exit code, you can use :cq.

I use this all the time because I can't be bothered to pinky shift for !. I often pipe things to Vim which don't need to be saved in a file. We also have an odd SVN wrapper at work which must be exited with a non-zero value in order to abort a checkin.

Jackson serialization: ignore empty values (or null)

Code bellow may help if you want to exclude boolean type from serialization either:

@JsonInclude(JsonInclude.Include.NON_ABSENT)

How to serialize SqlAlchemy result to JSON?

Flask-JsonTools package has an implementation of JsonSerializableBase Base class for your models.

Usage:

from sqlalchemy.ext.declarative import declarative_base
from flask.ext.jsontools import JsonSerializableBase

Base = declarative_base(cls=(JsonSerializableBase,))

class User(Base):
    #...

Now the User model is magically serializable.

If your framework is not Flask, you can just grab the code

Omitting the first line from any Linux command output

Pipe it to awk:

awk '{if(NR>1)print}'

or sed

sed -n '1!p'

What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

Okay, the .NET 2.0 answers:

If you don't need to clone the values, you can use the constructor overload to Dictionary which takes an existing IDictionary. (You can specify the comparer as the existing dictionary's comparer, too.)

If you do need to clone the values, you can use something like this:

public static Dictionary<TKey, TValue> CloneDictionaryCloningValues<TKey, TValue>
   (Dictionary<TKey, TValue> original) where TValue : ICloneable
{
    Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>(original.Count,
                                                            original.Comparer);
    foreach (KeyValuePair<TKey, TValue> entry in original)
    {
        ret.Add(entry.Key, (TValue) entry.Value.Clone());
    }
    return ret;
}

That relies on TValue.Clone() being a suitably deep clone as well, of course.

how to get curl to output only http response body (json) and no other headers etc

#!/bin/bash

req=$(curl -s -X GET http://host:8080/some/resource -H "Accept: application/json") 2>&1
echo "${req}"

Passing a varchar full of comma delimited values to a SQL Server IN function

Thanks, for your function I Used IT........................ This is my EXAMPLE

**UPDATE [RD].[PurchaseOrderHeader]
SET     [DispatchCycleNumber] ='10'
 WHERE  OrderNumber in(select * FROM XA.fn_SplitOrderIDs(@InvoiceNumberList))**


CREATE FUNCTION [XA].[fn_SplitOrderIDs]
(
    @OrderList varchar(500)
)
RETURNS 
@ParsedList table
(
    OrderID int
)
AS
BEGIN
    DECLARE @OrderID varchar(10), @Pos int

    SET @OrderList = LTRIM(RTRIM(@OrderList))+ ','
    SET @Pos = CHARINDEX(',', @OrderList, 1)

    IF REPLACE(@OrderList, ',', '') <> ''
    BEGIN
        WHILE @Pos > 0
        BEGIN
                SET @OrderID = LTRIM(RTRIM(LEFT(@OrderList, @Pos - 1)))
                IF @OrderID <> ''
                BEGIN
                        INSERT INTO @ParsedList (OrderID) 
                        VALUES (CAST(@OrderID AS int)) --Use Appropriate conversion
                END
                SET @OrderList = RIGHT(@OrderList, LEN(@OrderList) - @Pos)
                SET @Pos = CHARINDEX(',', @OrderList, 1)

        END
    END 
    RETURN
END

Download file of any type in Asp.Net MVC using FileResult?

The MVC framework supports this natively. The System.Web.MVC.Controller.File controller provides methods to return a file by name/stream/array.

For example using a virtual path to the file you could do the following.

return File(virtualFilePath, System.Net.Mime.MediaTypeNames.Application.Octet,  Path.GetFileName(virtualFilePath));

Table cell widths - fixing width, wrapping/truncating long words

<style type="text/css">
td { word-wrap: break-word;max-width:50px; }            
</style>

'No JUnit tests found' in Eclipse

I think you have created your test classes outside the src folder. You can solve above problem by two way:

  1. Add your package name in java build path->source

  2. Move your package/class in src folder

I have the same problem and solved in this way both solutions working fine.

ImportError: Couldn't import Django

I think the best way to use django is with virtualenv it's safe and you can install many apps in virtualenv which does not affect any outer space of the system vitualenv uses the default version of python which is same as in your system to install virtualenv

sudo pip install virtualenv

or for python3

sudo pip3 install virtualenv

and then in your dir

mkdir ~/newproject

cd ~/newproject

Now, create a virtual environment within the project directory by typing

virtualenv newenv

To install packages into the isolated environment, you must activate it by typing:

source newenv/bin/activate

now install here with

pip install django

You can verify the installation by typing:

django-admin --version

To leave your virtual environment, you need to issue the deactivate command from anywhere on the system:

deactivate

How do I delete specific characters from a particular String in Java?

Note that the word boundaries also depend on the Locale. I think the best way to do it using standard java.text.BreakIterator. Here is an example from the java.sun.com tutorial.

import java.text.BreakIterator;
import java.util.Locale;

public static void main(String[] args) {
    String text = "\n" +
            "\n" +
            "For example I'm extracting a text String from a text file and I need those words to form an array. However, when I do all that some words end with comma (,) or a full stop (.) or even have brackets attached to them (which is all perfectly normal).\n" +
            "\n" +
            "What I want to do is to get rid of those characters. I've been trying to do that using those predefined String methods in Java but I just can't get around it.\n" +
            "\n" +
            "Every help appreciated. Thanx";
    BreakIterator wordIterator = BreakIterator.getWordInstance(Locale.getDefault());
    extractWords(text, wordIterator);
}

static void extractWords(String target, BreakIterator wordIterator) {
    wordIterator.setText(target);
    int start = wordIterator.first();
    int end = wordIterator.next();

    while (end != BreakIterator.DONE) {
        String word = target.substring(start, end);
        if (Character.isLetterOrDigit(word.charAt(0))) {
            System.out.println(word);
        }
        start = end;
        end = wordIterator.next();
    }
}

Source: http://java.sun.com/docs/books/tutorial/i18n/text/word.html

Combining two Series into a DataFrame in pandas

If I may answer this.

The fundamentals behind converting series to data frame is to understand that

1. At conceptual level, every column in data frame is a series.

2. And, every column name is a key name that maps to a series.

If you keep above two concepts in mind, you can think of many ways to convert series to data frame. One easy solution will be like this:

Create two series here

import pandas as pd

series_1 = pd.Series(list(range(10)))

series_2 = pd.Series(list(range(20,30)))

Create an empty data frame with just desired column names

df = pd.DataFrame(columns = ['Column_name#1', 'Column_name#1'])

Put series value inside data frame using mapping concept

df['Column_name#1'] = series_1

df['Column_name#2'] = series_2

Check results now

df.head(5)

How to count rows with SELECT COUNT(*) with SQLAlchemy?

I managed to render the following SELECT with SQLAlchemy on both layers.

SELECT count(*) AS count_1
FROM "table"

Usage from the SQL Expression layer

from sqlalchemy import select, func, Integer, Table, Column, MetaData

metadata = MetaData()

table = Table("table", metadata,
              Column('primary_key', Integer),
              Column('other_column', Integer)  # just to illustrate
             )   

print select([func.count()]).select_from(table)

Usage from the ORM layer

You just subclass Query (you have probably anyway) and provide a specialized count() method, like this one.

from sqlalchemy.sql.expression import func

class BaseQuery(Query):
    def count_star(self):
        count_query = (self.statement.with_only_columns([func.count()])
                       .order_by(None))
        return self.session.execute(count_query).scalar()

Please note that order_by(None) resets the ordering of the query, which is irrelevant to the counting.

Using this method you can have a count(*) on any ORM Query, that will honor all the filter andjoin conditions already specified.

RegEx to exclude a specific string constant

Try this regular expression:

^(.{0,2}|([^A]..|A[^B].|AB[^C])|.{4,})$

It describes three cases:

  1. less than three arbitrary character
  2. exactly three characters, while either
    • the first is not A, or
    • the first is A but the second is not B, or
    • the first is A, the second B but the third is not C
  3. more than three arbitrary characters

Laravel: Using try...catch with DB::transaction()

You could wrapping the transaction over try..catch or even reverse them, here my example code I used to in laravel 5,, if you look deep inside DB:transaction() in Illuminate\Database\Connection that the same like you write manual transaction.

Laravel Transaction

public function transaction(Closure $callback)
    {
        $this->beginTransaction();

        try {
            $result = $callback($this);

            $this->commit();
        }

        catch (Exception $e) {
            $this->rollBack();

            throw $e;
        } catch (Throwable $e) {
            $this->rollBack();

            throw $e;
        }

        return $result;
    }

so you could write your code like this, and handle your exception like throw message back into your form via flash or redirect to another page. REMEMBER return inside closure is returned in transaction() so if you return redirect()->back() it won't redirect immediately, because the it returned at variable which handle the transaction.

Wrap Transaction

$result = DB::transaction(function () use ($request, $message) {
   try{

      // execute query 1
      // execute query 2
      // ..

      return redirect(route('account.article'));

   } catch (\Exception $e) {
       return redirect()->back()->withErrors(['error' => $e->getMessage()]);
    }
 });

// redirect the page
return $result;

then the alternative is throw boolean variable and handle redirect outside transaction function or if your need to retrieve why transaction failed you can get it from $e->getMessage() inside catch(Exception $e){...}

How to find the maximum value in an array?

Iterate over the Array. First initialize the maximum value to the first element of the array and then for each element optimize it if the element under consideration is greater.

What is the most efficient way to loop through dataframes with pandas?

The newest versions of pandas now include a built-in function for iterating over rows.

for index, row in df.iterrows():

    # do some logic here

Or, if you want it faster use itertuples()

But, unutbu's suggestion to use numpy functions to avoid iterating over rows will produce the fastest code.

The server encountered an internal error or misconfiguration and was unable to complete your request

You should look for the error in the file error_log in the log directory. Maybe there are differences between your local and server configuration (db user/password etc.etc.)

usually the log file is in

/var/log/apache2/error.log

or

/var/log/httpd/error.log

How to set the project name/group/version, plus {source,target} compatibility in the same file?

I found the solution to a similar problem. I am using Gradle 1.11 (as April, 2014). The project name can be changed directly in settings.gradle file as following:

  rootProject.name='YourNewName'

This takes care of uploading to repository (Artifactory w/ its plugin for me) with the correct artifactId.

Django: multiple models in one template using forms

This really isn't too hard to implement with ModelForms. So lets say you have Forms A, B, and C. You print out each of the forms and the page and now you need to handle the POST.

if request.POST():
    a_valid = formA.is_valid()
    b_valid = formB.is_valid()
    c_valid = formC.is_valid()
    # we do this since 'and' short circuits and we want to check to whole page for form errors
    if a_valid and b_valid and c_valid:
        a = formA.save()
        b = formB.save(commit=False)
        c = formC.save(commit=False)
        b.foreignkeytoA = a
        b.save()
        c.foreignkeytoB = b
        c.save()

Here are the docs for custom validation.

How to delete a file or folder?

Python syntax to delete a file

import os
os.remove("/tmp/<file_name>.txt")

Or

import os
os.unlink("/tmp/<file_name>.txt")

Or

pathlib Library for Python version >= 3.4

file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()

Path.unlink(missing_ok=False)

Unlink method used to remove the file or the symbolik link.

If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist.
If missing_ok is true, FileNotFoundError exceptions will be ignored (same behavior as the POSIX rm -f command).
Changed in version 3.8: The missing_ok parameter was added.

Best practice

  1. First, check whether the file or folder exists or not then only delete that file. This can be achieved in two ways :
    a. os.path.isfile("/path/to/file")
    b. Use exception handling.

EXAMPLE for os.path.isfile

#!/usr/bin/python
import os
myfile="/tmp/foo.txt"

## If file exists, delete it ##
if os.path.isfile(myfile):
    os.remove(myfile)
else:    ## Show an error ##
    print("Error: %s file not found" % myfile)

Exception Handling

#!/usr/bin/python
import os

## Get input ##
myfile= raw_input("Enter file name to delete: ")

## Try to delete the file ##
try:
    os.remove(myfile)
except OSError as e:  ## if failed, report it back to the user ##
    print ("Error: %s - %s." % (e.filename, e.strerror))

RESPECTIVE OUTPUT

Enter file name to delete : demo.txt
Error: demo.txt - No such file or directory.

Enter file name to delete : rrr.txt
Error: rrr.txt - Operation not permitted.

Enter file name to delete : foo.txt

Python syntax to delete a folder

shutil.rmtree()

Example for shutil.rmtree()

#!/usr/bin/python
import os
import sys
import shutil

# Get directory name
mydir= raw_input("Enter directory name: ")

## Try to remove tree; if failed show an error using try...except on screen
try:
    shutil.rmtree(mydir)
except OSError as e:
    print ("Error: %s - %s." % (e.filename, e.strerror))

CSS grid wrapping

You want either auto-fit or auto-fill inside the repeat() function:

grid-template-columns: repeat(auto-fit, 186px);

The difference between the two becomes apparent if you also use a minmax() to allow for flexible column sizes:

grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));

This allows your columns to flex in size, ranging from 186 pixels to equal-width columns stretching across the full width of the container. auto-fill will create as many columns as will fit in the width. If, say, five columns fit, even though you have only four grid items, there will be a fifth empty column:

Enter image description here

Using auto-fit instead will prevent empty columns, stretching yours further if necessary:

Enter image description here

How to increase the clickable area of a <a> tag button?

Big thanks to the contributors to the answers here, it pointed me in the right direction.

For the Bootstrap4 users out there, this worked for me. Sets the a link (tap target) to correct size to pass the Lighthouse Site Audit on mobiles.

    <span class="small">
         <a class="d-inline position-relative p-3 m-n3" style="z-index: 1;" href="/AdvancedSearch" title="Advanced Site Search using extra optional filters">Advanced Site Search</a>
    </span>

Cross browser method to fit a child div to its parent's width

If you put position:relative; on the outer element, the inner element will place itself according to this one. Then a width:auto; on the inner element will be the same as the width of the outer.

What are good message queue options for nodejs?

you could use redis with the lightning fast node_redis client. It even has built-in pubsub semantics.

Find the files that have been changed in last 24 hours

For others who land here in the future (including myself), add a -name option to find specific file types, for instance: find /var -name "*.php" -mtime -1 -ls

T-SQL split string

I have developed a double Splitter (Takes two split characters) as requested Here. Could be of some value in this thread seeing its the most referenced for queries relating to string splitting.

CREATE FUNCTION uft_DoubleSplitter 
(   
    -- Add the parameters for the function here
    @String VARCHAR(4000), 
    @Splitter1 CHAR,
    @Splitter2 CHAR
)
RETURNS @Result TABLE (Id INT,MId INT,SValue VARCHAR(4000))
AS
BEGIN
DECLARE @FResult TABLE(Id INT IDENTITY(1, 1),
                   SValue VARCHAR(4000))
DECLARE @SResult TABLE(Id INT IDENTITY(1, 1),
                   MId INT,
                   SValue VARCHAR(4000))
SET @String = @String+@Splitter1

WHILE CHARINDEX(@Splitter1, @String) > 0
    BEGIN
       DECLARE @WorkingString VARCHAR(4000) = NULL

       SET @WorkingString = SUBSTRING(@String, 1, CHARINDEX(@Splitter1, @String) - 1)
       --Print @workingString

       INSERT INTO @FResult
       SELECT CASE
            WHEN @WorkingString = '' THEN NULL
            ELSE @WorkingString
            END

       SET @String = SUBSTRING(@String, LEN(@WorkingString) + 2, LEN(@String))

    END
IF ISNULL(@Splitter2, '') != ''
    BEGIN
       DECLARE @OStartLoop INT
       DECLARE @OEndLoop INT

       SELECT @OStartLoop = MIN(Id),
            @OEndLoop = MAX(Id)
       FROM @FResult

       WHILE @OStartLoop <= @OEndLoop
          BEGIN
             DECLARE @iString VARCHAR(4000)
             DECLARE @iMId INT

             SELECT @iString = SValue+@Splitter2,
                   @iMId = Id
             FROM @FResult
             WHERE Id = @OStartLoop

             WHILE CHARINDEX(@Splitter2, @iString) > 0
                BEGIN
                    DECLARE @iWorkingString VARCHAR(4000) = NULL

                    SET @IWorkingString = SUBSTRING(@iString, 1, CHARINDEX(@Splitter2, @iString) - 1)

                    INSERT INTO @SResult
                    SELECT @iMId,
                         CASE
                         WHEN @iWorkingString = '' THEN NULL
                         ELSE @iWorkingString
                         END

                    SET @iString = SUBSTRING(@iString, LEN(@iWorkingString) + 2, LEN(@iString))

                END

             SET @OStartLoop = @OStartLoop + 1
          END
       INSERT INTO @Result
       SELECT MId AS PrimarySplitID,
            ROW_NUMBER() OVER (PARTITION BY MId ORDER BY Mid, Id) AS SecondarySplitID ,
            SValue
       FROM @SResult
    END
ELSE
    BEGIN
       INSERT INTO @Result
       SELECT Id AS PrimarySplitID,
            NULL AS SecondarySplitID,
            SValue
       FROM @FResult
    END
RETURN

Usage:

--FirstSplit
SELECT * FROM uft_DoubleSplitter('ValueA=ValueB=ValueC=ValueD==ValueE&ValueA=ValueB=ValueC===ValueE&ValueA=ValueB==ValueD===','&',NULL)

--Second Split
SELECT * FROM uft_DoubleSplitter('ValueA=ValueB=ValueC=ValueD==ValueE&ValueA=ValueB=ValueC===ValueE&ValueA=ValueB==ValueD===','&','=')

Possible Usage (Get second value of each split):

SELECT fn.SValue
FROM uft_DoubleSplitter('ValueA=ValueB=ValueC=ValueD==ValueE&ValueA=ValueB=ValueC===ValueE&ValueA=ValueB==ValueD===', '&', '=')AS fn
WHERE fn.mid = 2

Firebase TIMESTAMP to date and Time

For those looking for the Firebase Firestore equivalent. It's

firebase.firestore.FieldValue.serverTimestamp()

e.g.

firebase.firestore().collection("cities").add({
    createdAt: firebase.firestore.FieldValue.serverTimestamp(),
    name: "Tokyo",
    country: "Japan"
})
.then(function(docRef) {
    console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
    console.error("Error adding document: ", error);
});

Docs

Editing the git commit message in GitHub

You need to git push -f assuming that nobody has pulled the other commit before. Beware, you're changing history.

Postgres: check if array field contains value?

This should work:

select * from mytable where 'Journal'=ANY(pub_types);

i.e. the syntax is <value> = ANY ( <array> ). Also notice that string literals in postresql are written with single quotes.

How can I find the dimensions of a matrix in Python?

If you are using NumPy arrays, shape can be used. For example

  >>> a = numpy.array([[[1,2,3],[1,2,3]],[[12,3,4],[2,1,3]]])
  >>> a
  array([[[ 1,  2,  3],
         [ 1,  2,  3]],

         [[12,  3,  4],
         [ 2,  1,  3]]])
 >>> a.shape
 (2, 2, 3)

Installed SSL certificate in certificate store, but it's not in IIS certificate list

This can happen if you e.g. generate a new certificate request after having your old certificate request approved. The new request will cause IIS to delete the private key associated with your first certificate request, and hence when you import the (now signed) certificate associated with your first request, it will not have a private key associated with it. Since it doesn't have a private key, it can't be used for SSL binding and will not appear in the IIS manager.

You may be able to restore the private key, since it is stored more than one place on your computer:

  1. Start -> mmc.exe -> Add snap-in -> Certificates -> Computer account. Verify that the installed certificate appears in the "Personal/Certificates" tab. If not, import it. A missing private key is visualized by the icon next to the certificate not containing a key icon.
  2. Open the certificate (.cer) file from disk by double-clicking on it. In the Details tab, note the serial number.
  3. Start -> cmd.exe. Type "certutil -repairstore my (serialnumberhere)". The serial number should have no spaces. Could be 8 or more digits.

If the certutil command returns with "-repairstore command completed successfully", the private key of your certificate was most likely recovered. You can verify this by going to the MMC certificate list and hitting F5 -- if successful, your certificate will now have a small key in its icon. You will then be able to select your certificate from IIS.

If this fails, your private key is no longer available and you need to send a new certificate signing request to the signing authority.

Get Windows version in a batch file

These one-line commands have been tested on Windows XP, Server 2012, 7 and 10 (thank you Mad Tom Vane).

Extract version x.y in a cmd console

for /f "tokens=4-7 delims=[.] " %i in ('ver') do @(if %i==Version (echo %j.%k) else (echo %i.%j))

Extract the full version x.y.z

for /f "tokens=4-7 delims=[.] " %i in ('ver') do @(if %i==Version (echo %j.%k.%l) else (echo %i.%j.%k))

In a batch script use %% instead of single %

@echo off
for /f "tokens=4-7 delims=[.] " %%i in ('ver') do (if %%i==Version (set v=%%j.%%k) else (set v=%%i.%%j))
echo %v%

Version is not always consistent to brand name number

Be aware that the extracted version number does not always corresponds to the Windows name release. See below an extract from the full list of Microsoft Windows versions.

10.0   Windows 10
6.3   Windows Server 2012
6.3   Windows 8.1   /!\
6.2   Windows 8   /!\
6.1   Windows 7   /!\
6.0   Windows Vista
5.2   Windows XP x64
5.1   Windows XP
5.0   Windows 2000
4.10   Windows 98

Please also up-vote answers from Agent Gibbs and peterbh as my answer is inspired from their ideas.

What does \0 stand for?

In C, \0 denotes a character with value zero. The following are identical:

char a = 0;
char b = '\0';

The utility of this escape sequence is greater inside string literals, which are arrays of characters:

char arr[] = "abc\0def\0ghi\0";

(Note that this array has two zero characters at the end, since string literals include a hidden, implicit terminal zero.)

Show a number to two decimal places

$number = sprintf('%0.2f', $numbers); // 520.89898989 -> 520.89

This will give you 2 number after decimal.

Setting up FTP on Amazon Cloud Server

In case you have ufw enabled, remember add ftp:

> sudo ufw allow ftp

It took me 2 days to realise that I enabled ufw.

Running Composer returns: "Could not open input file: composer.phar"

You can do

curl -sS https://getcomposer.org/installer | php

The -sS flag meaning don't show progress, do show errors

and then

php composer.phar install

from: How do I get cURL to not show the progress bar?

https://packagist.org/

How to use greater than operator with date?

Try this.

SELECT * FROM la_schedule WHERE `start_date` > '2012-11-18';

UICollectionView spacing margins

For adding margins to specified cells, you can use this custom flow layout. https://github.com/voyages-sncf-technologies/VSCollectionViewCellInsetFlowLayout/

extension ViewController : VSCollectionViewDelegateCellInsetFlowLayout 
{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForItemAt indexPath: IndexPath) -> UIEdgeInsets {
        if indexPath.item == 0 {
            return UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)
        }
        return UIEdgeInsets.zero
    }
}

Changing datagridview cell color dynamically

This works for me

dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red;

convert a JavaScript string variable to decimal/money

Yes -- parseFloat.

parseFloat(document.getElementById(amtid4).innerHTML);

For formatting numbers, use toFixed:

var num = parseFloat(document.getElementById(amtid4).innerHTML).toFixed(2);

num is now a string with the number formatted with two decimal places.

Postgresql SELECT if string contains

In addition to the solution with 'aaaaaaaa' LIKE '%' || tag_name || '%' there are position (reversed order of args) and strpos.

SELECT id FROM TAG_TABLE WHERE strpos('aaaaaaaa', tag_name) > 0

Besides what is more efficient (LIKE looks less efficient, but an index might change things), there is a very minor issue with LIKE: tag_name of course should not contain % and especially _ (single char wildcard), to give no false positives.

How to ignore SSL certificate errors in Apache HttpClient 4.0

If you are using the fluent API, you need to set it up via the Executor:

Executor.unregisterScheme("https");
SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext,
                                  SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Executor.registerScheme(new Scheme("https", 443, sslSocketFactory));

... where sslContext is the SSLContext created as shown in the ZZ Coder's answer.

After that, you can do your http requests as:

String responseAsString = Request.Get("https://192.168.1.0/whatever.json")
                         .execute().getContent().asString();

Note: tested with HttpClient 4.2

Meaning of numbers in "col-md-4"," col-xs-1", "col-lg-2" in Bootstrap

From Twitter Bootstrap documentation:

  • small grid (= 768px) = .col-sm-*,
  • medium grid (= 992px) = .col-md-*,
  • large grid (= 1200px) = .col-lg-*.

to Read More...

The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception

This is an old, but still relevant question, and while the answers here are helpful no one answer fully addressed both of the OP's questions.

1. Do I have to install ODP.NET and Oracle client on the computer that I want to run my application?

YES - if you are using ODP.NET, Unmanaged. This is the version that you typically install when you choose "Oracle Data Provider for .NET" in the Oracle Client installer (for example). You Download this from Oracle (just google it: Oracle URLs change often).

But If you are using ODP.NET, Managed (and you probably want to use this one this instead) then No, you only need to install (or deploy) ODP.NET, Managed with the app, not the full Oracle Client. See below for details.

2. If yes, is there other way that I don't have to install them but still can run my application?

Yes, there is at least one way. And it is the Managed port of ODP.NET.

Unfortunately the usual workarounds, including ODBC, Microsoft's Oracle Provider for .NET (yes, that old, deprecated one), and the ODP.NET, Unmanaged DLL all require the Oracle client to be installed. It wasn't until our friends at Oracle gave us a nice little (~5MB) DLL that is also Managed. This means no more having to depoy 32-bit and 64-bit versions to go with 32-bit and 64-bit Oracle clients! And no more issues with assembly binding where you build against 10.0.2.1 (or whatever) but your customers install a range of clients from 9i all the way to 12c, including the 'g' ones in the middle) because you can just ship it with your app, and manage it via nuget.

But if you use ODP.NET, Managed which is available as a nuget package, then you do not need to install the Oracle Client. You only need the ODP.NET, Managed DLL. And if you were previously using the ODP.NET, Unmanaged DLL, it is very easy to switch: simply change all your references to the Managed ODP.NET (.csproj files in csharp, etc.), and then change any using statements, for example: using Oracle.DataAccess.Client becomes using Oracle.ManagedDataAccess.Client and that's it! (Unless you were supposedly using some of the more advanced DB management features in the full client that are exposed in the ODP.NET, Unmanaged, which I have not done myself, so good luck with that..). And also nuke all of those annoying assemblyBindingRedirect nodes from your app.config/web.config files and never sweat that junk again!

References:

Troubleshooting:

That error typically means ODP.NET was found OK, but Oracle client was not found or not installed. This could also occur when the architecture doesn't match (32-bit Oracle client is installed, but trying to use 64-bit Unmanaged ODP.NET, or vice versa). This can also happen due to permissions issues and path issues and other problems with the app domain (your web app or your EXE or whatever) not being able to find the Oracle DLLs to actually communicate with Oracle over the network (the ODP.NET Unmanaged DLLs are basically just wrappers for this that hook into ADO and stuff).

Common solutions I have found to this problem:

App is 64-bit?

  • Install 64-bit Oracle Client (32-bit one wont work)

App is 32-bit?

  • Install 32-bit Oracle Client (64-bit one wont work)

Oracle Client is already installed for the correct architecture?

  • Verify your environment PATH and ORACLE_HOME variables, make sure Oracle can be found (newer versions may use Registry instead)
  • Verify the ORACLE_HOME and settings in the Registry (And remember: Registry is either 32-bit or 64-bit, so make sure you check the one that matches your app!)
  • Verify permissions on the ORACLE_HOME folder. If you don't know where this is, check the Registry. I have seen cases where ASP.NET app worker process was using Network Service user and for some reason installing 32-bit and 64-bit clients side by side resulted in the permissions being removed from the first client for the Authorized Users group.. fixing perms on the home folder fixed this.
  • As always, it is handy to Use SysInternals Process Monitor to find out what file is missing or can't be read.

How do I convert a Django QuerySet into list of dicts?

Type Cast to List

    job_reports = JobReport.objects.filter(job_id=job_id, status=1).values('id', 'name')

    json.dumps(list(job_reports))

SCCM 2012 application install "Failed" in client Software Center

The execmgr.log will show the commandline and ccmcache folder used for installation. Typically, required apps don't show on appenforce.log and some clients will have outdated appenforce or no ppenforce.log files. execmgr.log also shows required hidden uninstall actions as well.

You may want to save the blog link. I still reference it from time to time.

Regular expression for 10 digit number without any special characters

An example of how to implement it:

public bool ValidateSocialSecNumber(string socialSecNumber)
{
    //Accepts only 10 digits, no more no less. (Like Mike's answer)
    Regex pattern = new Regex(@"(?<!\d)\d{10}(?!\d)");

    if(pattern.isMatch(socialSecNumber))
    {
        //Do something
        return true;
    }
    else
    {
        return false;
    }
}

You could've also done it in another way by e.g. using Match and then wrapping a try-catch block around the pattern matching. However, if a wrong input is given quite often, it's quite expensive to throw an exception. Thus, I prefer the above way, in simple cases at least.

Javascript Uncaught TypeError: Cannot read property '0' of undefined

The error is here:

hasLetter("a",words[]);

You are passing the first item of words, instead of the array.

Instead, pass the array to the function:

hasLetter("a",words);

Problem solved!


Here's a breakdown of what the problem was:

I'm guessing in your browser (chrome throws a different error), words[] == words[0], so when you call hasLetter("a",words[]);, you are actually calling hasLetter("a",words[0]);. So, in essence, you are passing the first item of words to your function, not the array as a whole.

Of course, because words is just an empty array, words[0] is undefined. Therefore, your function call is actually:

hasLetter("a", undefined);

which means that, when you try to access d[ascii], you are actually trying to access undefined[0], hence the error.

Java error: Comparison method violates its general contract

It might also be an OpenJDK bug... (not in this case but it is the same error)

If somebody like me stumbles upon this answer regarding the

java.lang.IllegalArgumentException: Comparison method violates its general contract!

then it might also be a bug in the Java-Version. I have a compareTo running since several years now in some applications. But suddenly it stopped working and throws the error after all compares were done (i compare 6 Attributes before returning "0").

Now I just found this Bugreport of OpenJDK:

Get SELECT's value and text in jQuery

<select id="ddlViewBy">
    <option value="value">text</option>
</select>

JQuery

var txt = $("#ddlViewBy option:selected").text();
var val = $("#ddlViewBy option:selected").val();

JS Fiddle DEMO

How can I get the count of milliseconds since midnight for the current?

In Java 8 you can simply do

ZonedDateTime.now().toInstant().toEpochMilli()

returns : the number of milliseconds since the epoch of 1970-01-01T00:00:00Z

how to enable sqlite3 for php?

The accepted answer is not complete without the remainder of instructions (paraphrased below) from the forum thread linked to:

cd /etc/php5/conf.d

cat > sqlite3.ini
# configuration for php SQLite3 module
extension=sqlite3.so
^D

sudo /etc/init.d/apache2 restart

Settings to Windows Firewall to allow Docker for Windows to share drive

As stated in one other answer Docker doesn't play nice with a VPN. If you're using Nordvpn you have to disable "Invisibility on LAN" and probably "Internet Kill Switch".

If you've done so it should work even with the VPN active.

NordVPN Client

JOptionPane Input to int

This because the input that the user inserts into the JOptionPane is a String and it is stored and returned as a String.

Java cannot convert between strings and number by itself, you have to use specific functions, just use:

int ans = Integer.parseInt(JOptionPane.showInputDialog(...))

How to add title to seaborn boxplot

For a single boxplot:

import seaborn as sb
sb.boxplot(data=Array).set_title('Title')

For more boxplot in the same plot:

import seaborn as sb
sb.boxplot(data=ArrayofArray).set_title('Title')

e.g.

import seaborn as sb
myarray=[78.195229, 59.104538, 19.884109, 25.941648, 72.234825, 82.313911]
sb.boxplot(data=myarray).set_title('myTitle')

Is there a replacement for unistd.h for Windows (Visual C)?

No, IIRC there is no getopt() on Windows.

Boost, however, has the program_options library... which works okay. It will seem like overkill at first, but it isn't terrible, especially considering it can handle setting program options in configuration files and environment variables in addition to command line options.

Cannot find control with name: formControlName in angular reactive form

You should specify formGroupName for nested controls

<div class="panel panel-default" formGroupName="address"> <== add this
    <div class="panel-heading">Contact Info</div>

Plunker Example

Disable autocomplete via CSS

There are 3 ways to that, i mention them in order of being the better way...

1-HTML way:

<input type="text" autocomplete="false" />

2-Javascript way:

document.getElementById("input-id").getAttribute("autocomplete") = "off";

3-jQuery way:

$('input').attr('autocomplete','off');

Execute script after specific delay using JavaScript

You need to use setTimeout and pass it a callback function. The reason you can't use sleep in javascript is because you'd block the entire page from doing anything in the meantime. Not a good plan. Use Javascript's event model and stay happy. Don't fight it!

Resizable table columns with jQuery

I have tried several solutions today, the one working best for me is Jo-Geek/jQuery-ResizableColumns. Is is very simple, yet it handles tables placed in flex containers, which many of the other ones fail with.

<table class="resizable">
</table>
$('table.resizable').resizableColumns();

_x000D_
_x000D_
$(function() {_x000D_
  $('table.resizable').resizableColumns();_x000D_
})
_x000D_
body {_x000D_
  margin: 0px;_x000D_
}_x000D_
_x000D_
table {_x000D_
  width: 100%;_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://jo-geek.github.io/jQuery-ResizableColumns/demo/resizableColumns.min.js"></script>_x000D_
<table class="resizable" border="true">_x000D_
  <thead>_x000D_
  <tr>_x000D_
    <th>col 1</th><th>col 2</th><th>col 3</th><th>col 4</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How do I convert ticks to minutes?

there are 600 million ticks per minute. ticksperminute

Generate an HTML Response in a Java Servlet

Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:

public void doGet(HttpServletRequest request,
       HttpServletResponse response)
       throws IOException, ServletException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   out.println("HTML from an external file:");     
   request.getRequestDispatcher("/pathToFile/fragment.html")
          .include(request, response); 
   out.close();
}

Git resolve conflict using --ours/--theirs for all files

In case anyone else is looking to simply overwrite everything from one branch (say master) with the contents of another, there's an easier way:

git merge origin/master --strategy=ours

Thanks to https://stackoverflow.com/a/1295232/560114

Or for the other way around, see Is there a "theirs" version of "git merge -s ours"?

How can I wrap or break long text/word in a fixed width span?

By default a span is an inline element... so that's not the default behavior.

You can make the span behave that way by adding display: block; to your CSS.

span {
    display: block;
    width: 100px;
}

How to know installed Oracle Client is 32 bit or 64 bit?

A simple way to find this out in Windows is to run SQLPlus from your Oracle homes's bin directory and then check Task Manager. If it is a 32-bit version of SQLPlus, you'll see a process on the Processes tab that looks like this:

sqlplus.exe *32

If it is 64-bit, the process will look like this:

sqlplus.exe

How do I import a specific version of a package using go get?

From Go 1.5 there's the "vendor experiment" that helps you manage dependencies. As of Go 1.6 this is no longer an experiment. Theres also some other options on the Go wiki..

Edit: as mentioned in this answer gopkg.in is a good option for pinning github-depdencies pre-1.5.

Object Required Error in excel VBA

In order to set the value of integer variable we simply assign the value to it. eg g1val = 0 where as set keyword is used to assign value to object.

Sub test()

Dim g1val, g2val As Integer

  g1val = 0
  g2val = 0

    For i = 3 To 18

     If g1val > Cells(33, i).Value Then
        g1val = g1val
    Else
       g1val = Cells(33, i).Value
     End If

    Next i

    For j = 32 To 57
        If g2val > Cells(31, j).Value Then
           g2val = g2val
        Else
          g2val = Cells(31, j).Value
        End If
    Next j

End Sub

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__)
logger.setLevel(logging.DEBUG)

console = logging.StreamHandler()
logger.addHandler(console)

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

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 install and run phpize

Hmm... actually i dont know how this solved it? But the following steps solved it for me:

find / -name 'config.m4'

Now look if the config.m4 is anywhere in a folder of that stuff you want to phpize. Go to that folder and run phpize directly in there.

Access parent URL from iframe

In chrome it is possible to use location.ancestorOrigins It will return all parent urls

Is it possible to create a 'link to a folder' in a SharePoint document library?

The simplest way is to use the following pattern:

http://[server]/[site]/[ListName]/[Folder]/[SubFolder]

To place a shortcut to a document library:

  1. Upload it as *.url file. However, by default, this file type is not allowed.
  2. Go to you Document Library settings > Advanced Settings > Allow management of content types. Add the "Link to document" content type to a document library and paste the link

How to deep watch an array in angularjs?

_x000D_
_x000D_
$scope.changePass = function(data){_x000D_
    _x000D_
    if(data.txtNewConfirmPassword !== data.txtNewPassword){_x000D_
        $scope.confirmStatus = true;_x000D_
    }else{_x000D_
        $scope.confirmStatus = false;_x000D_
    }_x000D_
};
_x000D_
  <form class="list" name="myForm">_x000D_
      <label class="item item-input">        _x000D_
        <input type="password" placeholder="???????????????????" ng-model="data.txtCurrentPassword" maxlength="5" required>_x000D_
      </label>_x000D_
      <label class="item item-input">_x000D_
        <input type="password" placeholder="???????????????" ng-model="data.txtNewPassword" maxlength="5" ng-minlength="5" name="checknawPassword" ng-change="changePass(data)" required>_x000D_
      </label>_x000D_
      <label class="item item-input">_x000D_
        <input type="password" placeholder="????????????????????????" ng-model="data.txtNewConfirmPassword" maxlength="5" ng-minlength="5" name="checkConfirmPassword" ng-change="changePass(data)" required>_x000D_
      </label>      _x000D_
       <div class="spacer" style="width: 300px; height: 5px;"></div> _x000D_
      <span style="color:red" ng-show="myForm.checknawPassword.$error.minlength || myForm.checkConfirmPassword.$error.minlength">??????????????????? 5 ????</span><br>_x000D_
      <span ng-show="confirmStatus" style="color:red">?????????????????????</span>_x000D_
      <br>_x000D_
      <button class="button button-positive  button-block" ng-click="saveChangePass(data)" ng-disabled="myForm.$invalid || confirmStatus">???????</button>_x000D_
    </form>
_x000D_
_x000D_
_x000D_

How to import classes defined in __init__.py

Add something like this to lib/__init__.py

from .helperclass import Helper

now you can import it directly:

from lib import Helper

Redirecting to previous page after login? PHP

You can save a page using php, like this:

$_SESSION['current_page'] = $_SERVER['REQUEST_URI']

And return to the page with:

header("Location: ". $_SESSION['current_page'])

Floating Point Exception C++ Why and what is it?

for (i>0; i--;)

is probably wrong and should be

for (; i>0; i--)

instead. Note where I put the semicolons. The condition goes in the middle, not at the start.

How to sort Counter by value? - python

A rather nice addition to @MartijnPieters answer is to get back a dictionary sorted by occurrence since Collections.most_common only returns a tuple. I often couple this with a json output for handy log files:

from collections import Counter, OrderedDict

x = Counter({'a':5, 'b':3, 'c':7})
y = OrderedDict(x.most_common())

With the output:

OrderedDict([('c', 7), ('a', 5), ('b', 3)])
{
  "c": 7, 
  "a": 5, 
  "b": 3
}

Name attribute in @Entity and @Table

@Table's name attribute is the actual table name. @Entitiy's name is useful if you have two @Entity classes with the same name and you need a way to differentiate them when running queries.

Printing a char with printf

This is supposed to print the ASCII value of the character, as %d is the escape sequence for an integer. So the value given as argument of printf is taken as integer when printed.

char ch = 'a';
printf("%d", ch);

Same holds for printf("%d", '\0');, where the NULL character is interpreted as the 0 integer.

Finally, sizeof('\n') is 4 because in C, this notation for characters stands for the corresponding ASCII integer. So '\n' is the same as 10 as an integer.

It all depends on the interpretation you give to the bytes.

How to impose maxlength on textArea in HTML using JavaScript

Better Solution compared to trimming the value of the textarea.

$('textarea[maxlength]').live('keypress', function(e) {
    var maxlength = $(this).attr('maxlength');
    var val = $(this).val();

    if (val.length > maxlength) {
        return false;
    }
});

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

A lot depends on what kind of project it is. WTP's JSP support either expects the JSP files to be under the same folder that's the parent of the WEB-INF folder (src/web, which it will then treat as "/" to find TLDs), or to have project metadata set up to help it know where that root is (done for you in a Dynamic Web Project through Deployment Assembly). How are you referring to the TLD file, and where is the JSP file located?

And maybe I missed the original post to the Eclipse forums; the one I saw was posted a full day after this one.

convert NSDictionary to NSString

You can call [aDictionary description], or anywhere you would need a format string, just use %@ to stand in for the dictionary:

[NSString stringWithFormat:@"my dictionary is %@", aDictionary];

or

NSLog(@"My dictionary is %@", aDictionary);

What Java FTP client library should I use?

Check out Apache commons-net, which contains FTP utilities. Off the top of my head I'm not sure if it meets all of your requirements, but it's certainly free!

How to find text in a column and saving the row number where it is first found - Excel VBA

Dim FindRow as Range

Set FindRow = Range("A:A").Find(What:="ProjTemp", _' This is what you are searching for
                   After:=.Cells(.Cells.Count), _ ' This is saying after the last cell in the_
                                                  ' column i.e. the first
                   LookIn:=xlValues, _ ' this says look in the values of the cell not the formula
                   LookAt:=xlWhole, _ ' This look s for EXACT ENTIRE MATCH
                   SearchOrder:=xlByRows, _ 'This look down the column row by row 
                                            'Larger Ranges with multiple columns can be set to 
                                            ' look column by column then down 
                   MatchCase:=False) ' this says that the search is not case sensitive

If Not FindRow  Is Nothing Then ' if findrow is something (Prevents Errors)
    FirstRow = FindRow.Row      ' set FirstRow to the first time a match is found
End If

If you would like to get addition ones you can use:

Do Until FindRow Is Nothing
    Set FindRow = Range("A:A").FindNext(after:=FindRow)
    If FindRow.row = FirstRow Then
        Exit Do
    Else ' Do what you'd like with the additional rows here.

    End If
Loop

Wait until a process ends

Referring to the Microsoft example: [https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.enableraisingevents?view=netframework-4.8]

Best would be to set:

myProcess.EnableRaisingEvents = true;

otherwiese the Code will be blocked. Also no additional properties needed.

// Start a process and raise an event when done.
myProcess.StartInfo.FileName = fileName;
// Allows to raise event when the process is finished
myProcess.EnableRaisingEvents = true;
// Eventhandler wich fires when exited
myProcess.Exited += new EventHandler(myProcess_Exited);
// Starts the process
myProcess.Start();

// Handle Exited event and display process information.
private void myProcess_Exited(object sender, System.EventArgs e)
{
Console.WriteLine(
                  $"Exit time    : {myProcess.ExitTime}\n" +
                  $"Exit code    : {myProcess.ExitCode}\n" +
                  $"Elapsed time : {elapsedTime}");
}

SSL Error When installing rubygems, Unable to pull data from 'https://rubygems.org/

Make sure your system clock is correct

This exact error happened to me today on an Ubuntu virtual machine running on VirtualBox. I tried most of the solutions shown above before I noticed that I had resumed from a very old suspended state, and my clock was off by many days.

Updating the clock immediately fixed my issue. Here's the command I used in my case:

sudo service ntp stop && sudo ntpdate pool.ntp.org && sudo service ntp start

Laravel Eloquent update just if changes have been made

You can use getChanges() on Eloquent model even after persisting.

SQL selecting rows by most recent date with two unique columns

So this isn't what the requester was asking for but it is the answer to "SQL selecting rows by most recent date".

Modified from http://wiki.lessthandot.com/index.php/Returning_The_Maximum_Value_For_A_Row

SELECT t.chargeId, t.chargeType, t.serviceMonth FROM( 
    SELECT chargeId,MAX(serviceMonth) AS serviceMonth
    FROM invoice
    GROUP BY chargeId) x 
    JOIN invoice t ON x.chargeId =t.chargeId
    AND x.serviceMonth = t.serviceMonth

jQuery or Javascript - how to disable window scroll without overflow:hidden;

Following Glens idea, here it goes another possibility. It would allow you to scroll inside the div, but would prevent the body to scroll with it, when the div scroll ends. However, it seems to accumulate too many preventDefault if you scroll too much, and then it creates a lag if you want to scroll up. Does anybody have a suggestion to fix that?

    $(".scrollInsideThisDiv").bind("mouseover",function(){
       var bodyTop = document.body.scrollTop;
       $('body').on({
           'mousewheel': function(e) {
           if (document.body.scrollTop == bodyTop) return;
           e.preventDefault();
           e.stopPropagation();
           }
       });
    });
    $(".scrollInsideThisDiv").bind("mouseleave",function(){
          $('body').unbind("mousewheel");
    });

How to get the Power of some Integer in Swift language?

An Int-based pow function that computes the value directly via bit shift for base 2 in Swift 5:

func pow(base: Int, power: UInt) -> Int {
    if power == 0 { return 1 }
    // for base 2, use a bit shift to compute the value directly
    if base == 2 { return 2 << Int(power - 1) }
    // otherwise multiply base repeatedly to compute the value
    return repeatElement(base, count: Int(power)).reduce(1, *)
}

(Make sure the result is within the range of Int - this does not check for the out of bounds case)

how to implement login auth in node.js

@alessioalex answer is a perfect demo for fresh node user. But anyway, it's hard to write checkAuth middleware into all routes except login, so it's better to move the checkAuth from every route to one entry with app.use. For example:

function checkAuth(req, res, next) {
  // if logined or it's login request, then go next route
  if (isLogin || (req.path === '/login' && req.method === 'POST')) {
    next()
  } else {
    res.send('Not logged in yet.')
  }
}

app.use('/', checkAuth)

How to logout and redirect to login page using Laravel 5.4?

You can use the following in your controller:

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

How do I check/uncheck all checkboxes with a button using jQuery?

Try this:

$('.checkAll').on('click', function(e) {
     $('.cb-element').prop('checked', $(e.target).prop('checked'));
});

e is the event generated when you do click, and e.target is the element clicked (.checkAll), so you only have to put the property checked of elements with class .cb-element like that of element with class .checkAll`.

PS: Excuse my bad English!

Calling an API from SQL Server stored procedure

I worked so much, I hope my effort might help you out.

Just paste this into your SSMS and press F5:

Declare @Object as Int;
DECLARE @hr  int
Declare @json as table(Json_Table nvarchar(max))

Exec @hr=sp_OACreate 'MSXML2.ServerXMLHTTP.6.0', @Object OUT;
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
Exec @hr=sp_OAMethod @Object, 'open', NULL, 'get',
                 'http://overpass-api.de/api/interpreter?data=[out:json];area[name=%22Auckland%22]-%3E.a;(node(area.a)[amenity=cinema];way(area.a)[amenity=cinema];rel(area.a)[amenity=cinema];);out;', --Your Web Service Url (invoked)
                 'false'
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
Exec @hr=sp_OAMethod @Object, 'send'
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
Exec @hr=sp_OAMethod @Object, 'responseText', @json OUTPUT
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object

INSERT into @json (Json_Table) exec sp_OAGetProperty @Object, 'responseText'
-- select the JSON string
select * from @json
-- Parse the JSON string
SELECT * FROM OPENJSON((select * from @json), N'$.elements')
WITH (   
      [type] nvarchar(max) N'$.type'   ,
      [id]   nvarchar(max) N'$.id',
      [lat]   nvarchar(max) N'$.lat',
      [lon]   nvarchar(max) N'$.lon',
      [amenity]   nvarchar(max) N'$.tags.amenity',
      [name]   nvarchar(max) N'$.tags.name'     
)
EXEC sp_OADestroy @Object

This query will give you 3 results:

1. Catch the error in case something goes wrong (don't panic, it will always show you an error above 4000 characters because NVARCHAR(MAX) can only store till 4000 characters)

2. Put the JSON into a string (which is what we want)

3. BONUS: parse the JSON and nicely store the data into a table (how cool is that?)

enter image description here

Cannot open new Jupyter Notebook [Permission Denied]

Based on my experience on Ubuntu 18.04:

1. Check Jupyter installation

first of all make sure that you have installed and/or upgraded Jupyter-notebook (also for virtual-environment):

pip install --upgrade jupyter 

2. Change the Access Permissions (Use with Caution!)

then try to change the access permission for you

sudo chmod -R 777 ~/.local

where 777 is a three-digit representation of the access permission. In sense that each of the digits representing short format of the binary one (e.g. 7 for 111). So, 777 means that we set permission access to read, write and execute to 1 for all users (Owner, Group or Other)

Example.1

777 : 111 111 111

or

777 : rwx-rwx-rwx

Example.2

755 : 111 101 101

  • Owner: rwx=4+2+1=7
  • Group: r-x=4+0+1=5
  • Other: r-x=4+0+1=5

(More about chmod : File Permissions and attributes)

3. Run jupyter

afterwards run your jupyter notebook:

jupyter-notebook

Note: (These steps also solve your Visual-Studio code (VS-Code) problems regarding permissions while using ipython and jupyter for python-interactive-console.)

Dynamically adding properties to an ExpandoObject

i think this add new property in desired type without having to set a primitive value, like when property defined in class definition

var x = new ExpandoObject();
x.NewProp = default(string)

How do I remove the height style from a DIV using jQuery?

maybe something like

$('div#someDiv').css("height", "auto");

htaccess - How to force the client's browser to clear the cache?

Change the name of the .CSS file Load the page and then change the file again in the original name it works for me.

Parsing huge logfiles in Node.js - read in line-by-line

Apart from read the big file line by line, you also can read it chunk by chunk. For more refer to this article

var offset = 0;
var chunkSize = 2048;
var chunkBuffer = new Buffer(chunkSize);
var fp = fs.openSync('filepath', 'r');
var bytesRead = 0;
while(bytesRead = fs.readSync(fp, chunkBuffer, 0, chunkSize, offset)) {
    offset += bytesRead;
    var str = chunkBuffer.slice(0, bytesRead).toString();
    var arr = str.split('\n');

    if(bytesRead = chunkSize) {
        // the last item of the arr may be not a full line, leave it to the next chunk
        offset -= arr.pop().length;
    }
    lines.push(arr);
}
console.log(lines);

Counting repeated characters in a string in Python

This is the shortest, most practical I can comeup with without importing extra modules.

text = "hello cruel world. This is a sample text"
d = dict.fromkeys(text, 0)
for c in text: d[c] += 1

print d['a'] would output 2

And it's also fast.

Can I execute a function after setState is finished updating?

setState(updater[, callback]) is an async function:

https://facebook.github.io/react/docs/react-component.html#setstate

You can execute a function after setState is finishing using the second param callback like:

this.setState({
    someState: obj
}, () => {
    this.afterSetStateFinished();
});

The same can be done with hooks in React functional component:

https://github.com/the-road-to-learn-react/use-state-with-callback#usage

Look at useStateWithCallbackLazy:

import { useStateWithCallbackLazy } from 'use-state-with-callback';

const [count, setCount] = useStateWithCallbackLazy(0);

setCount(count + 1, () => {
   afterSetCountFinished();
});

vertical-align image in div

Old question but nowadays CSS3 makes vertical alignment really simple!

Just add to the <div> this css:

display:flex;
align-items:center;
justify-content:center;

JSFiddle demo

Live Example:

_x000D_
_x000D_
.img_thumb {_x000D_
    float: left;_x000D_
    height: 120px;_x000D_
    margin-bottom: 5px;_x000D_
    margin-left: 9px;_x000D_
    position: relative;_x000D_
    width: 147px;_x000D_
    background-color: rgba(0, 0, 0, 0.5);_x000D_
    border-radius: 3px;_x000D_
    display:flex;_x000D_
    align-items:center;_x000D_
    justify-content:center;_x000D_
}
_x000D_
<div class="img_thumb">_x000D_
    <a class="images_class" href="http://i.imgur.com/2FMLuSn.jpg" rel="images">_x000D_
       <img src="http://i.imgur.com/2FMLuSn.jpg" title="img_title" alt="img_alt" />_x000D_
    </a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CAML query with nested ANDs and ORs for multiple fields

You can try U2U Query Builder http://www.u2u.net/res/Tools/CamlQueryBuilder.aspx you can use their API U2U.SharePoint.CAML.Server.dll and U2U.SharePoint.CAML.Client.dll

I didn't use them but I'm sure it will help you achieving your task.

How to convert index of a pandas dataframe into a column?

For MultiIndex you can extract its subindex using

df['si_name'] = R.index.get_level_values('si_name') 

where si_name is the name of the subindex.

Mocking python function based on input arguments

If side_effect_func is a function then whatever that function returns is what calls to the mock return. The side_effect_func function is called with the same arguments as the mock. This allows you to vary the return value of the call dynamically, based on the input:

>>> def side_effect_func(value):
...     return value + 1
...
>>> m = MagicMock(side_effect=side_effect_func)
>>> m(1)
2
>>> m(2)
3
>>> m.mock_calls
[call(1), call(2)]

http://www.voidspace.org.uk/python/mock/mock.html#calling

Using lodash to compare jagged arrays (items existence without order)

We can use _.difference function to see if there is any difference or not.

function isSame(arrayOne, arrayTwo) {
   var a = _.uniq(arrayOne),
   b = _.uniq(arrayTwo);
   return a.length === b.length && 
          _.isEmpty(_.difference(b.sort(), a.sort()));
}

// examples
console.log(isSame([1, 2, 3], [1, 2, 3])); // true
console.log(isSame([1, 2, 4], [1, 2, 3])); // false
console.log(isSame([1, 2], [2, 3, 1])); // false
console.log(isSame([2, 3, 1], [1, 2])); // false

// Test cases pointed by Mariano Desanze, Thanks.
console.log(isSame([1, 2, 3], [1, 2, 2])); // false
console.log(isSame([1, 2, 2], [1, 2, 2])); // true
console.log(isSame([1, 2, 2], [1, 2, 3])); // false

I hope this will help you.

Adding example link at StackBlitz

Using multiprocessing.Process with a maximum number of simultaneous processes

I think Semaphore is what you are looking for, it will block the main process after counting down to 0. Sample code:

from multiprocessing import Process
from multiprocessing import Semaphore
import time

def f(name, sema):
    print('process {} starting doing business'.format(name))
    # simulate a time-consuming task by sleeping
    time.sleep(5)
    # `release` will add 1 to `sema`, allowing other 
    # processes blocked on it to continue
    sema.release()

if __name__ == '__main__':
    concurrency = 20
    total_task_num = 1000
    sema = Semaphore(concurrency)
    all_processes = []
    for i in range(total_task_num):
        # once 20 processes are running, the following `acquire` call
        # will block the main process since `sema` has been reduced
        # to 0. This loop will continue only after one or more 
        # previously created processes complete.
        sema.acquire()
        p = Process(target=f, args=(i, sema))
        all_processes.append(p)
        p.start()

    # inside main process, wait for all processes to finish
    for p in all_processes:
        p.join()

The following code is more structured since it acquires and releases sema in the same function. However, it will consume too much resources if total_task_num is very large:

from multiprocessing import Process
from multiprocessing import Semaphore
import time

def f(name, sema):
    print('process {} starting doing business'.format(name))
    # `sema` is acquired and released in the same
    # block of code here, making code more readable,
    # but may lead to problem.
    sema.acquire()
    time.sleep(5)
    sema.release()

if __name__ == '__main__':
    concurrency = 20
    total_task_num = 1000
    sema = Semaphore(concurrency)
    all_processes = []
    for i in range(total_task_num):
        p = Process(target=f, args=(i, sema))
        all_processes.append(p)
        # the following line won't block after 20 processes
        # have been created and running, instead it will carry 
        # on until all 1000 processes are created.
        p.start()

    # inside main process, wait for all processes to finish
    for p in all_processes:
        p.join()

The above code will create total_task_num processes but only concurrency processes will be running while other processes are blocked, consuming precious system resources.

RegEx for matching "A-Z, a-z, 0-9, _" and "."

Maybe, you need to specify more exactly what didn't work and in what environment you are.

As to the claim that the dot is special in a charackter class, this is not true in every programming environment. For example the following perl script

use warnings;
use strict;

my $str = '!!!.###';
$str =~ s/[A-Za-z_.]/X/g;
print "$str\n";

produces

!!!X###

What is the purpose of the word 'self'?

Let’s take a simple vector class:

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

We want to have a method which calculates the length. What would it look like if we wanted to define it inside the class?

    def length(self):
        return math.sqrt(self.x ** 2 + self.y ** 2)

What should it look like when we were to define it as a global method/function?

def length_global(vector):
    return math.sqrt(vector.x ** 2 + vector.y ** 2)

So the whole structure stays the same. How can me make use of this? If we assume for a moment that we hadn’t written a length method for our Vector class, we could do this:

Vector.length_new = length_global
v = Vector(3, 4)
print(v.length_new()) # 5.0

This works because the first parameter of length_global, can be re-used as the self parameter in length_new. This would not be possible without an explicit self.


Another way of understanding the need for the explicit self is to see where Python adds some syntactical sugar. When you keep in mind, that basically, a call like

v_instance.length()

is internally transformed to

Vector.length(v_instance)

it is easy to see where the self fits in. You don't actually write instance methods in Python; what you write is class methods which must take an instance as a first parameter. And therefore, you’ll have to place the instance parameter somewhere explicitly.

Batch not-equal (inequality) operator

I know this is quite out of date, but this might still be useful for those coming late to the party. (EDIT: updated since this still gets traffic and @Goozak has pointed out in the comments that my original analysis of the sample was incorrect as well.)

I pulled this from the example code in your link:

IF !%1==! GOTO VIEWDATA
REM  IF NO COMMAND-LINE ARG...
FIND "%1" C:\BOZO\BOOKLIST.TXT
GOTO EXIT0
REM  PRINT LINE WITH STRING MATCH, THEN EXIT.

:VIEWDATA
TYPE C:\BOZO\BOOKLIST.TXT | MORE
REM  SHOW ENTIRE FILE, 1 PAGE AT A TIME.

:EXIT0

!%1==! is simply an idiomatic use of == intended to verify that the thing on the left, that contains your variable, is different from the thing on the right, that does not. The ! in this case is just a character placeholder. It could be anything. If %1 has content, then the equality will be false, if it does not you'll just be comparing ! to ! and it will be true.

!==! is not an operator, so writing "asdf" !==! "fdas" is pretty nonsensical.

The suggestion to use if not "asdf" == "fdas" is definitely the way to go.

Setting the Textbox read only property to true using JavaScript

You can try

document.getElementById("textboxid").readOnly = true;

How do I automatically resize an image for a mobile site?

Your css with doesn't have any effect as the outer element doesn't have a width defined (and body is missing as well).

A different approach is to deliver already scaled images. http://www.sencha.com/products/io/ for example delivers the image already scaled down depending on the viewing device.

Does VBA have Dictionary Structure?

VBA has the collection object:

    Dim c As Collection
    Set c = New Collection
    c.Add "Data1", "Key1"
    c.Add "Data2", "Key2"
    c.Add "Data3", "Key3"
    'Insert data via key into cell A1
    Range("A1").Value = c.Item("Key2")

The Collection object performs key-based lookups using a hash so it's quick.


You can use a Contains() function to check whether a particular collection contains a key:

Public Function Contains(col As Collection, key As Variant) As Boolean
    On Error Resume Next
    col(key) ' Just try it. If it fails, Err.Number will be nonzero.
    Contains = (Err.Number = 0)
    Err.Clear
End Function

Edit 24 June 2015: Shorter Contains() thanks to @TWiStErRob.

Edit 25 September 2015: Added Err.Clear() thanks to @scipilot.

github markdown colspan

Compromise minimum solution:

| One    | Two | Three | Four    | Five  | Six 
| -
| Span <td colspan=3>triple  <td colspan=2>double

So you can omit closing </td> for speed, ?r can leave for consistency.

Result from http://markdown-here.com/livedemo.html : markdown table with colspan

Works in Jupyter Markdown.

Update:

As of 2019 year all pipes in the second line are compulsory in Jupyter Markdown.

| One    | Two | Three | Four    | Five  | Six
|-|-|-|-|-|-
| Span <td colspan=3>triple  <td colspan=2>double

minimally:

One    | Two | Three | Four    | Five  | Six
-|||||-
Span <td colspan=3>triple  <td colspan=2>double

Install mysql-python (Windows)

For folks using Python 3.0+ (which should be everyone now):

Unfortunately, MySQL-Python 1.2.5 does not support Python 3.0+ yet (which is kinda unreasonable IMHO, Python 3+ has been out for a while). Reference : https://pypi.python.org/pypi/MySQL-python/1.2.5

So, my workaround is to use Oracle's MySQL connector. In settings.py, change DATABASE's 'ENGINE' field to: 'ENGINE': 'mysql.connector.django',

More info could be found in the last paragraph of the first answer to this question: Setting Django up to use MySQL

Hope this helps!!

Properties private set;

Or you can do

public class Person
{
    public Person(int id)
    {
         this.Id=id;
    }

    public string Name { get;  set; }
    public int Id { get; private set; }
    public int Age { get; set; }
}

How to find time complexity of an algorithm

Taken from here - Introduction to Time Complexity of an Algorithm

1. Introduction

In computer science, the time complexity of an algorithm quantifies the amount of time taken by an algorithm to run as a function of the length of the string representing the input.

2. Big O notation

The time complexity of an algorithm is commonly expressed using big O notation, which excludes coefficients and lower order terms. When expressed this way, the time complexity is said to be described asymptotically, i.e., as the input size goes to infinity.

For example, if the time required by an algorithm on all inputs of size n is at most 5n3 + 3n, the asymptotic time complexity is O(n3). More on that later.

Few more Examples:

  • 1 = O(n)
  • n = O(n2)
  • log(n) = O(n)
  • 2 n + 1 = O(n)

3. O(1) Constant Time:

An algorithm is said to run in constant time if it requires the same amount of time regardless of the input size.

Examples:

  • array: accessing any element
  • fixed-size stack: push and pop methods
  • fixed-size queue: enqueue and dequeue methods

4. O(n) Linear Time

An algorithm is said to run in linear time if its time execution is directly proportional to the input size, i.e. time grows linearly as input size increases.

Consider the following examples, below I am linearly searching for an element, this has a time complexity of O(n).

int find = 66;
var numbers = new int[] { 33, 435, 36, 37, 43, 45, 66, 656, 2232 };
for (int i = 0; i < numbers.Length - 1; i++)
{
    if(find == numbers[i])
    {
        return;
    }
}

More Examples:

  • Array: Linear Search, Traversing, Find minimum etc
  • ArrayList: contains method
  • Queue: contains method

5. O(log n) Logarithmic Time:

An algorithm is said to run in logarithmic time if its time execution is proportional to the logarithm of the input size.

Example: Binary Search

Recall the "twenty questions" game - the task is to guess the value of a hidden number in an interval. Each time you make a guess, you are told whether your guess is too high or too low. Twenty questions game implies a strategy that uses your guess number to halve the interval size. This is an example of the general problem-solving method known as binary search

6. O(n2) Quadratic Time

An algorithm is said to run in quadratic time if its time execution is proportional to the square of the input size.

Examples:

7. Some Useful links

Printing 2D array in matrix format

you can do like this also

        long[,] arr = new long[4, 4] { { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 }};

        for (int i = 0; i < arr.GetLength(0); i++)
        {
            for (int j = 0; j < arr.GetLength(1); j++)
            {
                Console.Write(arr[i,j]+" ");
            }
            Console.WriteLine();
        }

Get a resource using getResource()

if you are calling from static method, use :

TestGameTable.class.getClassLoader().getResource("dice.jpg");

How to set 00:00:00 using moment.js

You've not shown how you're creating the string 2016-01-12T23:00:00.000Z, but I assume via .format().

Anyway, .set() is using your local time zone, but the Z in the time string indicates zero time, otherwise known as UTC.

https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators

So I assume your local timezone is 23 hours from UTC?

saikumar's answer showed how to load the time in as UTC, but the other option is to use a .format() call that outputs using your local timezone, rather than UTC.

http://momentjs.com/docs/#/get-set/
http://momentjs.com/docs/#/displaying/format/

Multiple models in a view

Add this ModelCollection.cs to your Models

using System;
using System.Collections.Generic;

namespace ModelContainer
{
  public class ModelCollection
  {
   private Dictionary<Type, object> models = new Dictionary<Type, object>();

   public void AddModel<T>(T t)
   {
      models.Add(t.GetType(), t);
   }

   public T GetModel<T>()
   {
     return (T)models[typeof(T)];
   }
 }
}

Controller:

public class SampleController : Controller
{
  public ActionResult Index()
  {
    var model1 = new Model1();
    var model2 = new Model2();
    var model3 = new Model3();

    // Do something

    var modelCollection = new ModelCollection();
    modelCollection.AddModel(model1);
    modelCollection.AddModel(model2);
    modelCollection.AddModel(model3);
    return View(modelCollection);
  }
}

The View:

enter code here
@using Models
@model ModelCollection

@{
  ViewBag.Title = "Model1: " + ((Model.GetModel<Model1>()).Name);
}

<h2>Model2: @((Model.GetModel<Model2>()).Number</h2>

@((Model.GetModel<Model3>()).SomeProperty

How to shutdown my Jenkins safely?

  1. jenkinsUrl/safeRestart - Let you to wait for running JOBS to get complete and do a RESTART.
  2. jenkinsUrl/restart - Do a restart immediately without waiting for the jobs which are running currently.
  3. jenkinsUrl/exit - It stops/shutdown the JENKINS services
  4. jenkinsUrl/reload - To reload the configuration changes.