Programs & Examples On #Subscribe


Angular 2: How to call a function after get a response from subscribe

You can add a callback function to your list of get_category(...) parameters.


 get_categories(number, callback){ url, body, {headers: headers, withCredentials:true})
      response => { = response.json();

      }, error => {


And then you can just call get_category(...) like this:

this.get_category(1, name_of_function);

Angular 2 - Checking for server errors from subscribe

As stated in the relevant RxJS documentation, the .subscribe() method can take a third argument that is called on completion if there are no errors.

For reference:

  1. [onNext] (Function): Function to invoke for each element in the observable sequence.
  2. [onError] (Function): Function to invoke upon exceptional termination of the observable sequence.
  3. [onCompleted] (Function): Function to invoke upon graceful termination of the observable sequence.

Therefore you can handle your routing logic in the onCompleted callback since it will be called upon graceful termination (which implies that there won't be any errors when it is called).

      result => {
        // Handle result
      error => {
        this.errors = error;
      () => {
        // 'onCompleted' callback.
        // No errors, route to new page here

As a side note, there is also a .finally() method which is called on completion regardless of the success/failure of the call. This may be helpful in scenarios where you always want to execute certain logic after an HTTP request regardless of the result (i.e., for logging purposes or for some UI interaction such as showing a modal).


Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.

For instance, here is a basic example:

import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/finally';

// ...

    .finally(() => {
      // Execute after graceful or exceptionally termination
      console.log('Handle logging logic...');
    .subscribe (
      result => {
        // Handle result
      error => {
        this.errors = error;
      () => {
        // No errors, route to new page

get dictionary value by key

I use a similar method to dasblinkenlight's in a function to return a single key value from a Cookie containing a JSON array loaded into a Dictionary as follows:

    /// <summary>
    /// Gets a single key Value from a Json filled cookie with 'cookiename','key' 
    /// </summary>
    public static string GetSpecialCookieKeyVal(string _CookieName, string _key)
        Dictionary<string, string> dictCookie =
        JsonConvert.DeserializeObject<Dictionary<string, string>>

        string value;
        if (dictCookie.TryGetValue( _key, out value))
            return value;
            return "0";


Where "MyCookinator.Get()" is another simple Cookie function getting an http cookie overall value.

View/edit ID3 data for MP3 files

TagLib Sharp is pretty popular.

As a side note, if you wanted to take a quick and dirty peek at doing it yourself.. here is a C# snippet I found to read an mp3's tag info.

class MusicID3Tag


    public byte[] TAGID = new byte[3];      //  3
    public byte[] Title = new byte[30];     //  30
    public byte[] Artist = new byte[30];    //  30 
    public byte[] Album = new byte[30];     //  30 
    public byte[] Year = new byte[4];       //  4 
    public byte[] Comment = new byte[30];   //  30 
    public byte[] Genre = new byte[1];      //  1


string filePath = @"C:\Documents and Settings\All Users\Documents\My Music\Sample Music\041105.mp3";

        using (FileStream fs = File.OpenRead(filePath))
            if (fs.Length >= 128)
                MusicID3Tag tag = new MusicID3Tag();
                fs.Seek(-128, SeekOrigin.End);
                fs.Read(tag.TAGID, 0, tag.TAGID.Length);
                fs.Read(tag.Title, 0, tag.Title.Length);
                fs.Read(tag.Artist, 0, tag.Artist.Length);
                fs.Read(tag.Album, 0, tag.Album.Length);
                fs.Read(tag.Year, 0, tag.Year.Length);
                fs.Read(tag.Comment, 0, tag.Comment.Length);
                fs.Read(tag.Genre, 0, tag.Genre.Length);
                string theTAGID = Encoding.Default.GetString(tag.TAGID);

                if (theTAGID.Equals("TAG"))
                    string Title = Encoding.Default.GetString(tag.Title);
                    string Artist = Encoding.Default.GetString(tag.Artist);
                    string Album = Encoding.Default.GetString(tag.Album);
                    string Year = Encoding.Default.GetString(tag.Year);
                    string Comment = Encoding.Default.GetString(tag.Comment);
                    string Genre = Encoding.Default.GetString(tag.Genre);


What does void mean in C, C++, and C#?

Basically it means "nothing" or "no type"

There are 3 basic ways that void is used:

  1. Function argument: int myFunc(void) -- the function takes nothing.

  2. Function return value: void myFunc(int) -- the function returns nothing

  3. Generic data pointer: void* data -- 'data' is a pointer to data of unknown type, and cannot be dereferenced

Note: the void in a function argument is optional in C++, so int myFunc() is exactly the same as int myFunc(void), and it is left out completely in C#. It is always required for a return value.

How to subtract X days from a date using Java calendar?

Anson's answer will work fine for the simple case, but if you're going to do any more complex date calculations I'd recommend checking out Joda Time. It will make your life much easier.

FYI in Joda Time you could do

DateTime dt = new DateTime();
DateTime fiveDaysEarlier = dt.minusDays(5);

A Parser-blocking, cross-origin script is invoked via document.write - how to circumvent it?

@niutech I was having the similar issue which is caused by Rocket Loader Module by Cloudflare. Just disable it for the website and it will sort out all your related issues.

CSS to line break before/after a particular `inline-block` item

Maybe it's is completely possible with only CSS but I prefer to avoid "float" as much as I can because it interferes with it's parent's height.

If you are using jQuery, you can create a simple `wrapN` plugin that is similar to `wrapAll` except it only wraps "N" elements and then breaks and wraps the next "N" elements using a loop. Then set your wrappers class to `display: block;`.

(function ($) {
    $.fn.wrapN = function (wrapper, n, start) {
        if (wrapper === undefined || n === undefined) return false;
        if (start === undefined) start = 0;
        for (var i = start; i < $(this).size(); i += n)
           $(this).slice(i, i + n).wrapAll(wrapper);
        return this;

$(document).ready(function () {
    $("li").wrapN("<span class='break' />", 3);

Here is a JSFiddle of the finished product:

How to replace a whole line with sed?

If you would like to use awk then this would work too

awk -F= '{$2="xxx";print}' OFS="\=" filename

How to sum all column values in multi-dimensional array?

Here's a version where the array keys may not be the same for both arrays, but you want them all to be there in the final array.

function array_add_by_key( $array1, $array2 ) {
    foreach ( $array2 as $k => $a ) {
        if ( array_key_exists( $k, $array1 ) ) {
            $array1[$k] += $a;
        } else {
            $array1[$k] = $a;
    return $array1;

How can I find the method that called the current method?

We can improve on Mr Assad's code (the current accepted answer) just a little bit by instantiating only the frame we actually need rather than the entire stack:

new StackFrame(1).GetMethod().Name;

This might perform a little better, though in all likelihood it still has to use the full stack to create that single frame. Also, it still has the same caveats that Alex Lyman pointed out (optimizer/native code might corrupt the results). Finally, you might want to check to be sure that new StackFrame(1) or .GetFrame(1) don't return null, as unlikely as that possibility might seem.

See this related question: Can you use reflection to find the name of the currently executing method?

What is the difference between jQuery: text() and html() ?

Strange that no-one mentioned the Cross Site scripting prevention benefit of .text() over .html() (Although others have just mentioned that .text() escapes the data).

It's always recommended to use .text() when you want to update data in DOM which is just data / text for the user to see.

.html() should be mostly used to get the HTML content within a div.

ORA-12505, TNS:listener does not currently know of SID given in connect descriptor

I found some reasons for this exception.they are

1)The name of the database XE by the url will be"jdbc:oracle:thin:@localhost:1521:XE".

2)Make sure that OracleServiceXE,OracleXETNSListener is will be in Control Panel\All Control Panel Items\Administrative Tools\Services

SQL Server 2000: How to exit a stored procedure?

This works over here.

ALTER PROCEDURE dbo.Archive_Session
    @SessionGUID int
        PRINT 'before raiserror'
        RAISERROR('this is a raised error', 18, 1)
        IF @@Error != 0 
        PRINT 'before return'
        RETURN -1
        PRINT 'after return'

EXECUTE dbo.Archive_Session @SessionGUID = 1


before raiserror
Msg 50000, Level 18, State 1, Procedure Archive_Session, Line 7
this is a raised error

MYSQL Sum Query with IF Condition

Try with a CASE in this way :

    WHEN PaymentType = "credit card" 
    THEN TotalAmount 
    ELSE 0 
END) AS CreditCardTotal,

Should give what you are looking for ...

How to encode URL to avoid special characters in Java?

URL construction is tricky because different parts of the URL have different rules for what characters are allowed: for example, the plus sign is reserved in the query component of a URL because it represents a space, but in the path component of the URL, a plus sign has no special meaning and spaces are encoded as "%20".

RFC 2396 explains (in section 2.4.2) that a complete URL is always in its encoded form: you take the strings for the individual components (scheme, authority, path, etc.), encode each according to its own rules, and then combine them into the complete URL string. Trying to build a complete unencoded URL string and then encode it separately leads to subtle bugs, like spaces in the path being incorrectly changed to plus signs (which an RFC-compliant server will interpret as real plus signs, not encoded spaces).

In Java, the correct way to build a URL is with the URI class. Use one of the multi-argument constructors that takes the URL components as separate strings, and it'll escape each component correctly according to that component's rules. The toASCIIString() method gives you a properly-escaped and encoded string that you can send to a server. To decode a URL, construct a URI object using the single-string constructor and then use the accessor methods (such as getPath()) to retrieve the decoded components.

Don't use the URLEncoder class! Despite the name, that class actually does HTML form encoding, not URL encoding. It's not correct to concatenate unencoded strings to make an "unencoded" URL and then pass it through a URLEncoder. Doing so will result in problems (particularly the aforementioned one regarding spaces and plus signs in the path).

How to store phone numbers on MySQL databases?

I would suggest a varchar for the phone number (since phone numbers are known to have leading 0s which are important to keep) and having the phone number in two fields:

Country Code and phone number i.e. for 004477789787 you could store CountryCode=44 and phone number=77789787

however it could be very application specific. If for example you will only store US numbers and want to keep the capability of quickly performing queries like "Get all the numbers from a specific area" then you can further split the phone number field (and drop the country code field as it would be redundant)

I don't think there is a general right and wrong way to do this. It really depends on the demands.

Auto start node.js server on boot

If you are using Linux, macOS or Windows pm2 is your friend. It's a process manager that handle clusters very well.

You install it:

npm install -g pm2

Start a cluster of, for example, 3 processes:

 pm2 start app.js -i 3

And make pm2 starts them at boot:

 pm2 startup

It has an API, an even a monitor interface:


Go to github and read the instructions. It's easy to use and very handy. Best thing ever since forever.

How to serve .html files with Spring

You can still continue to use the same View resolver but set the suffix to empty.

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
    p:prefix="/WEB-INF/jsp/" p:suffix="" />

Now your code can choose to return either index.html or index.jsp as shown in below sample -

@RequestMapping(value="jsp", method = RequestMethod.GET )
public String startJsp(){
    return "/test.jsp";

@RequestMapping(value="html", method = RequestMethod.GET )
public String startHtml(){
    return "/test.html";

SQL Server : How to test if a string has only digit characters

Solution: where some_column NOT LIKE '%[^0-9]%' Is correct.

Just one important note: Add validation for when the string column = '' (empty string). This scenario will return that '' is a valid number as well.

how to make password textbox value visible when hover an icon

Try This :

In HTML and JS :

// Convert Password Field To Text On Hover._x000D_
  var passField = $('input[type=password]');_x000D_
  $('.show-pass').hover(function() {_x000D_
      passField.attr('type', 'text');_x000D_
  }, function() {_x000D_
    passField.attr('type', 'password');_x000D_
<script src=""></script>_x000D_
<link href="" rel="stylesheet"/>_x000D_
<!-- An Input PassWord Field With Eye Font-Awesome Class -->_x000D_
<input type="password" placeholder="Type Password">_x000D_
      <i class="show-pass fa fa-eye fa-lg"></i>

Sending and receiving data over a network using TcpClient

Be warned - this is a very old and cumbersome "solution".

By the way, you can use serialization technology to send strings, numbers or any objects which are support serialization (most of .NET data-storing classes & structs are [Serializable]). There, you should at first send Int32-length in four bytes to the stream and then send binary-serialized (System.Runtime.Serialization.Formatters.Binary.BinaryFormatter) data into it.

On the other side or the connection (on both sides actually) you definetly should have a byte[] buffer which u will append and trim-left at runtime when data is coming.

Something like that I am using:

namespace System.Net.Sockets
    public class TcpConnection : IDisposable
        public event EvHandler<TcpConnection, DataArrivedEventArgs> DataArrive = delegate { };
        public event EvHandler<TcpConnection> Drop = delegate { };

        private const int IntSize = 4;
        private const int BufferSize = 8 * 1024;

        private static readonly SynchronizationContext _syncContext = SynchronizationContext.Current;
        private readonly TcpClient _tcpClient;
        private readonly object _droppedRoot = new object();
        private bool _dropped;
        private byte[] _incomingData = new byte[0];
        private Nullable<int> _objectDataLength;

        public TcpClient TcpClient { get { return _tcpClient; } }
        public bool Dropped { get { return _dropped; } }

        private void DropConnection()
            lock (_droppedRoot)
                if (Dropped)

                _dropped = true;

            _syncContext.Post(delegate { Drop(this); }, null);

        public void SendData(PCmds pCmd) { SendDataInternal(new object[] { pCmd }); }
        public void SendData(PCmds pCmd, object[] datas)
            SendDataInternal(new object[] { pCmd }.Append(datas));
        private void SendDataInternal(object data)
            if (Dropped)

            byte[] bytedata;

            using (MemoryStream ms = new MemoryStream())
                BinaryFormatter bf = new BinaryFormatter();

                try { bf.Serialize(ms, data); }
                catch { return; }

                bytedata = ms.ToArray();

                lock (_tcpClient)
                    TcpClient.Client.BeginSend(BitConverter.GetBytes(bytedata.Length), 0, IntSize, SocketFlags.None, EndSend, null);
                    TcpClient.Client.BeginSend(bytedata, 0, bytedata.Length, SocketFlags.None, EndSend, null);
            catch { DropConnection(); }
        private void EndSend(IAsyncResult ar)
            try { TcpClient.Client.EndSend(ar); }
            catch { }

        public TcpConnection(TcpClient tcpClient)
            _tcpClient = tcpClient;

        private void StartReceive()
            byte[] buffer = new byte[BufferSize];

                _tcpClient.Client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, DataReceived, buffer);
            catch { DropConnection(); }

        private void DataReceived(IAsyncResult ar)
            if (Dropped)

            int dataRead;

            try { dataRead = TcpClient.Client.EndReceive(ar); }

            if (dataRead == 0)

            byte[] byteData = ar.AsyncState as byte[];
            _incomingData = _incomingData.Append(byteData.Take(dataRead).ToArray());
            bool exitWhile = false;

            while (exitWhile)
                exitWhile = true;

                if (_objectDataLength.HasValue)
                    if (_incomingData.Length >= _objectDataLength.Value)
                        object data;
                        BinaryFormatter bf = new BinaryFormatter();

                        using (MemoryStream ms = new MemoryStream(_incomingData, 0, _objectDataLength.Value))
                            try { data = bf.Deserialize(ms); }

                        _syncContext.Post(delegate(object T)
                            try { DataArrive(this, new DataArrivedEventArgs(T)); }
                            catch { DropConnection(); }
                        }, data);

                        _incomingData = _incomingData.TrimLeft(_objectDataLength.Value);
                        _objectDataLength = null;
                        exitWhile = false;
                    if (_incomingData.Length >= IntSize)
                        _objectDataLength = BitConverter.ToInt32(_incomingData.TakeLeft(IntSize), 0);
                        _incomingData = _incomingData.TrimLeft(IntSize);
                        exitWhile = false;

        public void Dispose() { DropConnection(); }

That is just an example, you should edit it for your use.

URLEncoder not able to translate space character

Although quite old, nevertheless a quick response:

Spring provides UriUtils - with this you can specify how to encoded and which part is it related from an URI, e.g.


I use them cause we already using Spring, i.e. no additonal library is required!

Python: How to create a unique file name?

You can use the datetime module

import datetime
uniq_filename = str( + '_' + str(':', '.')

Note that: I am using replace since the colons are not allowed in filenames in many operating systems.

That's it, this will give you a unique filename every single time.

What is the difference between docker-compose ports vs expose


  1. Activates the container to listen for specified port(s) from the world outside of the docker(can be same host machine or a different machine) AND also accessible world inside docker.
  2. More than one port can be specified (that's is why ports not port)

enter image description here


  1. Activates container to listen for a specific port only from the world inside of docker AND not accessible world outside of the docker.
  2. More than one port can be specified

enter image description here

How to set the From email address for mailx command?

On macOS Sierra, creating ~/.mailrc with smtp setup did the trick:

set smtp-use-starttls
set smtp=smtp://
set smtp-auth=login
set [email protected]
set smtp-auth-password=yourpass

Then to send mail from CLI:

echo "your message" | mail -s "your subject" [email protected]

MySQL Error: : 'Access denied for user 'root'@'localhost'

In your MySQL workbench, you can go to the left sidebar, under Management select "Users and Privileges", click root under User Accounts, the in the right section click tab "Account Limits" to increase the max queries, updates, etc, and then click tab "Administrative Roles" and check the boxes to give the account access. Hope that helps!

How to iterate through two lists in parallel?

You should use 'zip' function. Here is an example how your own zip function can look like

def custom_zip(seq1, seq2):
    it1 = iter(seq1)
    it2 = iter(seq2)
    while True:
        yield next(it1), next(it2)

Rails how to run rake task




Cannot find Microsoft.Office.Interop Visual Studio

If you have installed latest Visual studio and want to To locate library of Microsoft.Office.Interop.Outlook or any other Microsoft.Office.Interop library then you should look into below 2 folders:

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA\Office14

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA\Office15

Please note that folder could be C:\Program Files\

How to load a controller from another controller in codeigniter?

I came here because I needed to create a {{ render() }} function in Twig, to simulate Symfony2's behaviour. Rendering controllers from view is really cool to display independant widgets or ajax-reloadable stuffs.

Even if you're not a Twig user, you can still take this helper and use it as you want in your views to render a controller, using <?php echo twig_render('welcome/index', $param1, $param2, $_); ?>. This will echo everything your controller outputted.

Here it is:



if (!function_exists('twig_render'))

    function twig_render()
        $args = func_get_args();
        $route = array_shift($args);
        $controller = APPPATH . 'controllers/' . substr($route, 0, strrpos($route, '/'));

        $explode = explode('/', $route);
        if (count($explode) < 2)
            show_error("twig_render: A twig route is made from format: path/to/controller/action.");

        if (!is_file($controller . '.php'))
            show_error("twig_render: Controller not found: {$controller}");
        if (!is_readable($controller . '.php'))
            show_error("twig_render: Controller not readable: {$controller}");
        require_once($controller . '.php');

        $class = ucfirst(reset(array_slice($explode, count($explode) - 2, 1)));
        if (!class_exists($class))
            show_error("twig_render: Controller file exists, but class not found inside: {$class}");

        $object = new $class();
        if (!($object instanceof CI_Controller))
            show_error("twig_render: Class {$class} is not an instance of CI_Controller");

        $method = $explode[count($explode) - 1];
        if (!method_exists($object, $method))
            show_error("twig_render: Controller method not found: {$method}");

        if (!is_callable(array($object, $method)))
            show_error("twig_render: Controller method not visible: {$method}");

        call_user_func_array(array($object, $method), $args);

        $ci = &get_instance();
        return $ci->output->get_output();


Specific for Twig users (adapt this code to your Twig implementation):


$this->_twig_env->addFunction('render', new Twig_Function_Function('twig_render'));


{{ render('welcome/index', param1, param2, ...) }}

React: Expected an assignment or function call and instead saw an expression

You are not returning anything, at least from your snippet and comment.

const def = (props) => { <div></div> };

This is not returning anything, you are wrapping the body of the arrow function with curly braces but there is no return value.

const def = (props) => { return (<div></div>); }; OR const def = (props) => <div></div>;

These two solutions on the other hand are returning a valid React component. Keep also in mind that inside your jsx (as mentioned by @Adam) you can't have if ... else ... but only ternary operators.

make: Nothing to be done for `all'

When you just give make, it makes the first rule in your makefile, i.e "all". You have specified that "all" depends on "hello", which depends on main.o, factorial.o and hello.o. So 'make' tries to see if those files are present.

If they are present, 'make' sees if their dependencies, e.g. main.o has a dependency main.c, have changed. If they have changed, make rebuilds them, else skips the rule. Similarly it recursively goes on building the files that have changed and finally runs the top most command, "all" in your case to give you a executable, 'hello' in your case.

If they are not present, make blindly builds everything under the rule.

Coming to your problem, it isn't an error but 'make' is saying that every dependency in your makefile is up to date and it doesn't need to make anything!

I want to exception handle 'list index out of range.'

for i in range (1, len(list))
        print (list[i])

    except ValueError:
        print("Error Value.")
    except indexError:
        print("Erorr index")
    except :
        print('error ')

find vs find_by vs where

Both #2s in your lists are being deprecated. You can still use find(params[:id]) though.

Generally, where() works in most situations.

Here's a great post:

Using DISTINCT along with GROUP BY in SQL Server

Perhaps not in the context that you have it, but you could use


You would use this to return different levels of aggregation returned in a single row. The use case would be for when a single grouping would not suffice all of the aggregates needed.

align textbox and text/labels in html?

I have found better option,

<style type="text/css">
    .form {
        margin: 0 auto;
        width: 210px;
    .form label{
        display: inline-block;
        text-align: right;
        float: left;
    .form input{
        display: inline-block;
        text-align: left;
        float: right;

Demo here:

Oracle comparing timestamp with date

You can truncate the date part:

select * from table1 where trunc(field1) = to_date('2012-01-01', 'YYYY-MM-DD')

The trouble with this approach is that any index on field1 wouldn't be used due to the function call.

Alternatively (and more index friendly)

select * from table1 
 where field1 >= to_timestamp('2012-01-01', 'YYYY-MM-DD') 
   and field1 < to_timestamp('2012-01-02', 'YYYY-MM-DD')

Starting with Zend Tutorial - Zend_DB_Adapter throws Exception: "SQLSTATE[HY000] [2002] No such file or directory"

It looks like mysql service is either not working or stopped. you can start it by using below command (in Ubuntu):

service mysql start

It should work! If you are using any other operating system than Ubuntu then use appropriate way to start mysql

Find provisioning profile in Xcode 5

It is not exactly for Xcode5 but this question links people who want to check where are provisioning profiles:
Following documentation

  1. Choose Xcode > Preferences.
  2. Click Accounts at the top of the window.
  3. Select the team you want to view, and click View Details. enter image description here In the dialog that appears, view your signing identities and provisioning profiles. If a Create button appears next to a certificate, it hasn’t been created yet. If a Download button appears next to a provisioning profile, it’s not on your Mac. enter image description here

Ten you can start context menu on each profile and click "Show in Finder" or "Move to Trash".

Export table data from one SQL Server to another

It can be done through "Import/Export Data..." in SQL Server Management Studio

Imitating a blink tag with CSS3 animations

Please find below solution for your code.

@keyframes blink {_x000D_
  50% {_x000D_
    color: transparent;_x000D_
.loader__dot {_x000D_
  animation: 1s blink infinite;_x000D_
.loader__dot:nth-child(2) {_x000D_
  animation-delay: 250ms;_x000D_
.loader__dot:nth-child(3) {_x000D_
  animation-delay: 500ms;_x000D_
Loading <span class="loader__dot">.</span><span class="loader__dot">.</span><span class="loader__dot">.</span>

How to fix Array indexOf() in JavaScript for Internet Explorer browsers

With the Underscore.js

var arr=['a','a1','b'] _.filter(arr, function(a){ return a.indexOf('a') > -1; })

Amazon S3 upload file and get URL

For AWS SDK 2+

String key = "filePath";
String bucketName = "bucketName";
PutObjectResponse response = s3Client
            .putObject(PutObjectRequest.builder().bucket(bucketName ).key(key).build(), RequestBody.fromFile(file));
 GetUrlRequest request = GetUrlRequest.builder().bucket(bucketName ).key(key).build();
 String url = s3Client.utilities().getUrl(request).toExternalForm();

#1071 - Specified key was too long; max key length is 767 bytes

We encountered this issue when trying to add a UNIQUE index to a VARCHAR(255) field using utf8mb4. While the problem is outlined well here already, I wanted to add some practical advice for how we figured this out and solved it.

When using utf8mb4, characters count as 4 bytes, whereas under utf8, they could as 3 bytes. InnoDB databases have a limit that indexes can only contain 767 bytes. So when using utf8, you can store 255 characters (767/3 = 255), but using utf8mb4, you can only store 191 characters (767/4 = 191).

You're absolutely able to add regular indexes for VARCHAR(255) fields using utf8mb4, but what happens is the index size is truncated at 191 characters automatically - like unique_key here:

Sequel Pro screenshot showing index truncated at 191 characters

This is fine, because regular indexes are just used to help MySQL search through your data more quickly. The whole field doesn't need to be indexed.

So, why does MySQL truncate the index automatically for regular indexes, but throw an explicit error when trying to do it for unique indexes? Well, for MySQL to be able to figure out if the value being inserted or updated already exists, it needs to actually index the whole value and not just part of it.

At the end of the day, if you want to have a unique index on a field, the entire contents of the field must fit into the index. For utf8mb4, this means reducing your VARCHAR field lengths to 191 characters or less. If you don't need utf8mb4 for that table or field, you can drop it back to utf8 and be able to keep your 255 length fields.

Get a UTC timestamp

"... that are independent of their timezone"

var timezone =  d.getTimezoneOffset() // difference in minutes from GMT

how to delete the content of text file without deleting itself

using : New Java 7 NIO library, try

        if(!Files.exists(filePath.getParent())) {
        if(!Files.exists(filePath)) {
        // Empty the file content
        writer = Files.newBufferedWriter(filePath);

The above code checks if Directoty exist if not creates the directory, checks if file exists is yes it writes empty string and flushes the buffer, in the end yo get the writer pointing to empty file

Adding iOS UITableView HeaderView (not section header)

In Swift:

override func viewDidLoad() {

    // We set the table view header.
    let cellTableViewHeader = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewHeaderCustomCellIdentifier) as! UITableViewCell
    cellTableViewHeader.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewHeaderCustomCellIdentifier]!)
    self.tableView.tableHeaderView = cellTableViewHeader

    // We set the table view footer, just know that it will also remove extra cells from tableview.
    let cellTableViewFooter = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewFooterCustomCellIdentifier) as! UITableViewCell
    cellTableViewFooter.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewFooterCustomCellIdentifier]!)
    self.tableView.tableFooterView = cellTableViewFooter

ProgressDialog spinning circle

I was using View.INVISIBLE and View.VISIBLE and the ProgressBar would slowly flash instead of constantly being visible, switched to View.GONE and View.VISIBLE and it works perfectly

Accessing Objects in JSON Array (JavaScript)

You can loop the array with a for loop and the object properties with for-in loops.

for (var i=0; i<result.length; i++)
    for (var name in result[i]) {
        console.log("Item name: "+name);
        console.log("Source: "+result[i][name].sourceUuid);
        console.log("Target: "+result[i][name].targetUuid);

How to check if function exists in JavaScript?

This will verify if the function exists, if so it will be executed

me.onChange && me.onChange(str);

Thus the error TypeError: me.onChange is not a function is prevent.

How to get data by SqlDataReader.GetValue by column name

Log.WriteLine("Value of CompanyName column:" + thisReader["CompanyName"]); 

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

The Singleton:

package com.domain.packagename;

import android.content.Context;

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

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

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

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

    public Context getApplicationContext() {
        return context;


Initialize the Singleton in your Application subclass:

package com.domain.packagename;


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

    public void onCreate() {

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

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

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


    android:name=".mApplication" <!-- This is the important line -->

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

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

Finding the index of elements based on a condition using python list comprehension

For me it works well:

>>> import numpy as np
>>> a = np.array([1, 2, 3, 1, 2, 3])
>>> np.where(a > 2)[0]
[2 5]

What does the function then() mean in JavaScript?

The traditional way to deal with asynchronous calls in JavaScript has been with callbacks. Say we had to make three calls to the server, one after the other, to set up our application. With callbacks, the code might look something like the following (assuming a xhrGET function to make the server call):

// Fetch some server configuration
    xhrGET('/api/server-config', function(config) {
        // Fetch the user information, if he's logged in
        xhrGET('/api/' + config.USER_END_POINT, function(user) {
            // Fetch the items for the user
            xhrGET('/api/' + + '/items', function(items) {
                // Actually display the items here

In this example, we first fetch the server configuration. Then based on that, we fetch information about the current user, and then finally get the list of items for the current user. Each xhrGET call takes a callback function that is executed when the server responds.

Now of course the more levels of nesting we have, the harder the code is to read, debug, maintain, upgrade, and basically work with. This is generally known as callback hell. Also, if we needed to handle errors, we need to possibly pass in another function to each xhrGET call to tell it what it needs to do in case of an error. If we wanted to have just one common error handler, that is not possible.

The Promise API was designed to solve this nesting problem and the problem of error handling.

The Promise API proposes the following:

  1. Each asynchronous task will return a promise object.
  2. Each promise object will have a then function that can take two arguments, a success handler and an error handler.
  3. The success or the error handler in the then function will be called only once, after the asynchronous task finishes.
  4. The then function will also return a promise, to allow chaining multiple calls.
  5. Each handler (success or error) can return a value, which will be passed to the next function as an argument, in the chain of promises.
  6. If a handler returns a promise (makes another asynchronous request), then the next handler (success or error) will be called only after that request is finished.

So the previous example code might translate to something like the following, using promises and the $http service(in AngularJs):

    function(configResponse) {
        return $http.get('/api/' +;
    function(userResponse) {
        return $http.get('/api/' + + '/items');
    function(itemResponse) {
        // Display items here
    function(error) {
        // Common error handling

Propagating Success and Error

Chaining promises is a very powerful technique that allows us to accomplish a lot of functionality, like having a service make a server call, do some postprocessing of the data, and then return the processed data to the controller. But when we work with promise chains, there are a few things we need to keep in mind.

Consider the following hypothetical promise chain with three promises, P1, P2, and P3. Each promise has a success handler and an error handler, so S1 and E1 for P1, S2 and E2 for P2, and S3 and E3 for P3:

  .then(S1, E1) //P1
  .then(S2, E2) //P2
  .then(S3, E3) //P3

In the normal flow of things, where there are no errors, the application would flow through S1, S2, and finally, S3. But in real life, things are never that smooth. P1 might encounter an error, or P2 might encounter an error, triggering E1 or E2.

Consider the following cases:

• We receive a successful response from the server in P1, but the data returned is not correct, or there is no data available on the server (think empty array). In such a case, for the next promise P2, it should trigger the error handler E2.

• We receive an error for promise P2, triggering E2. But inside the handler, we have data from the cache, ensuring that the application can load as normal. In that case, we might want to ensure that after E2, S3 is called.

So each time we write a success or an error handler, we need to make a call—given our current function, is this promise a success or a failure for the next handler in the promise chain?

If we want to trigger the success handler for the next promise in the chain, we can just return a value from the success or the error handler

If, on the other hand, we want to trigger the error handler for the next promise in the chain, we can do that using a deferred object and calling its reject() method

Now What is deferred object?

Deferred objects in jQuery represents a unit of work that will be completed later, typically asynchronously. Once the unit of work completes, the deferred object can be set to resolved or failed.

A deferred object contains a promise object. Via the promise object you can specify what is to happen when the unit of work completes. You do so by setting callback functions on the promise object.

Deferred objects in Jquery :

Deferred objects in AngularJs :$q

Change the Arrow buttons in Slick slider

Content property of pseudo element :before accepts images too. In slick-theme.css change:

// change_x000D_
$slick-prev-character: "?" !default; _x000D_
// to_x000D_
$slick-prev-character: url('image-prev.png');_x000D_
// and _x000D_
$slick-next-character: "?" !default;_x000D_
// to _x000D_
$slick-next-character: url('image-next.jpg');

or directly change the content property on slick-prev:before and slick-next:before

.slick-prev {_x000D_
    left: -25px;_x000D_
    [dir="rtl"] & {_x000D_
        left: auto;_x000D_
        right: -25px;_x000D_
    &:before {_x000D_
        content: url('image-prev.jpg'); // <<<<<<<<_x000D_
        [dir="rtl"] & {_x000D_
            content: url('image-next.jpg'); // <<<<<<<<_x000D_
.slick-next {_x000D_
    right: -25px;_x000D_
    [dir="rtl"] & {_x000D_
        left: -25px;_x000D_
        right: auto;_x000D_
    &:before {_x000D_
        content: url('image-next.jpg'); // <<<<<<<<_x000D_
        [dir="rtl"] & {_x000D_
            content: url('image-prev.jpg'); // <<<<<<<<_x000D_

Check if a Bash array contains a value

My version of the regular expressions technique that's been suggested already:

values=(foo bar)

[[ "${values[@]/#/X-}" =~ "X-${requestedValue}" ]] || echo "Unsupported value"

What's happening here is that you're expanding the entire array of supported values into words and prepending a specific string, "X-" in this case, to each of them, and doing the same to the requested value. If this one is indeed contained in the array, then the resulting string will at most match one of the resulting tokens, or none at all in the contrary. In the latter case the || operator triggers and you know you're dealing with an unsupported value. Prior to all of that the requested value is stripped of all leading and trailing whitespace through standard shell string manipulation.

It's clean and elegant, I believe, though I'm not too sure of how performant it may be if your array of supported values is particularly large.

How to convert binary string value to decimal

Test it

import java.util.Scanner;
public class BinaryToDecimal{

public static void main(String[] args) {

    Scanner input = new Scanner(;
    int binaryNumber = 0;
    int counter = 0;
    int number = 0;

    System.out.print("Input binary number: ");
    binaryNumber = input.nextInt();

    //it's going to stop when the binaryNumber/10 is less than 0
    //binaryNumber = 11/10. The result value is 1 when you do the next
    //operation 1/10 . The result value is 0     

    while(binaryNumber != 0)
        //Obtaining the remainder of the division and multiplying it 
        //with the number raised to two

        //adding it up with the previous result

        number += ((binaryNumber % 10)) * Math.pow(2,counter);

        binaryNumber /= 10;  //removing one digit from the binary number

        //Increasing counter 2^0, 2^1, 2^2, 2^3.....

    System.out.println("Decimal number : " + number);



How to center align the ActionBar title in Android?

Best and easiest way, specifically for those who just want text view with gravity center without any xml layout.

AppCompatTextView mTitleTextView = new AppCompatTextView(getApplicationContext());
        ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.CENTER;
        actionBar.setCustomView(mTitleTextView, layoutParams);
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_HOME_AS_UP);

How to post JSON to PHP with curl

I believe you are getting an empty array because PHP is expecting the posted data to be in a Querystring format (key=value&key1=value1).

Try changing your curl request to:

curl -i -X POST -d 'json={"screencast":{"subject":"tools"}}'  \

and see if that helps any.

git add, commit and push commands in one?

Building off of @Gavin's answer:

Making lazygit a function instead of an alias allows you to pass it an argument. I have added the following to my .bashrc (or .bash_profile if Mac):

function lazygit() {
    git add .
    git commit -a -m "$1"
    git push

This allows you to provide a commit message, such as

lazygit "My commit msg"

You could of course beef this up even more by accepting even more arguments, such as which remote place to push to, or which branch.

PostgreSQL unnest() with element number

If the order of element is not important, you can

  id, elem, row_number() over (partition by id) as nr
from (
      unnest(string_to_array(elements, ',')) AS elem
  from myTable
) a

When to use StringBuilder in Java

Some compilers may not replace any string concatenations with StringBuilder equivalents. Be sure to consider which compilers your source will use before relying on compile time optimizations.

How to send json data in POST request using C#

This works for me.

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new 

    string json = new JavaScriptSerializer().Serialize(new
                    Username = "myusername",
                    Password = "password"

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

random.seed(): What does it do?

random.seed(a, version) in python is used to initialize the pseudo-random number generator (PRNG).

PRNG is algorithm that generates sequence of numbers approximating the properties of random numbers. These random numbers can be reproduced using the seed value. So, if you provide seed value, PRNG starts from an arbitrary starting state using a seed.

Argument a is the seed value. If the a value is None, then by default, current system time is used.

and version is An integer specifying how to convert the a parameter into a integer. Default value is 2.

import random
random.randint(1, 10) #this gives output of 1
# 1

If you want the same random number to be reproduced then provide the same seed again

random.randint(1, 10) # this will give the same output of 1
# 1

If you don't provide the seed, then it generate different number and not 1 as before

random.randint(1, 10) # this gives 7 without providing seed
# 7

If you provide different seed than before, then it will give you a different random number

random.randint(1, 10) # this gives you 5 not 1
# 5

So, in summary, if you want the same random number to be reproduced, provide the seed. Specifically, the same seed.

Ways to circumvent the same-origin policy

Personally, window.postMessage is the most reliable way that I've found for modern browsers. You do have to do a slight bit more work to make sure you're not leaving yourself open to XSS attacks, but it's a reasonable tradeoff.

There are also several plugins for the popular Javascript toolkits out there that wrap window.postMessage that provide similar functionality to older browsers using the other methods discussed above.

ASP.NET Core - Swashbuckle not creating swagger.json file

You must conform to 2 rules:

  1. Decorate all actions with explicit Http Methods like[HttpGet("xxx")],[HttpPost("xxx")] or ... instead of [Route("xxx")].
  2. Decorate public methods in controllers with [NonAction] Attribute.

Note that http://localhost:XXXX/swagger/ page requests for http://localhost:XXXX/swagger/v1/swagger.json file, but an Exception will occur from Swagger if you wouldn't conform above rules.

How do you express binary literals in Python?

How do you express binary literals in Python?

They're not "binary" literals, but rather, "integer literals". You can express integer literals with a binary format with a 0 followed by a B or b followed by a series of zeros and ones, for example:

>>> 0b0010101010
>>> 0B010101

From the Python 3 docs, these are the ways of providing integer literals in Python:

Integer literals are described by the following lexical definitions:

integer      ::=  decinteger | bininteger | octinteger | hexinteger
decinteger   ::=  nonzerodigit (["_"] digit)* | "0"+ (["_"] "0")*
bininteger   ::=  "0" ("b" | "B") (["_"] bindigit)+
octinteger   ::=  "0" ("o" | "O") (["_"] octdigit)+
hexinteger   ::=  "0" ("x" | "X") (["_"] hexdigit)+
nonzerodigit ::=  "1"..."9"
digit        ::=  "0"..."9"
bindigit     ::=  "0" | "1"
octdigit     ::=  "0"..."7"
hexdigit     ::=  digit | "a"..."f" | "A"..."F"

There is no limit for the length of integer literals apart from what can be stored in available memory.

Note that leading zeros in a non-zero decimal number are not allowed. This is for disambiguation with C-style octal literals, which Python used before version 3.0.

Some examples of integer literals:

7     2147483647                        0o177    0b100110111
3     79228162514264337593543950336     0o377    0xdeadbeef
      100_000_000_000                   0b_1110_0101

Changed in version 3.6: Underscores are now allowed for grouping purposes in literals.

Other ways of expressing binary:

You can have the zeros and ones in a string object which can be manipulated (although you should probably just do bitwise operations on the integer in most cases) - just pass int the string of zeros and ones and the base you are converting from (2):

>>> int('010101', 2)

You can optionally have the 0b or 0B prefix:

>>> int('0b0010101010', 2)

If you pass it 0 as the base, it will assume base 10 if the string doesn't specify with a prefix:

>>> int('10101', 0)
>>> int('0b10101', 0)

Converting from int back to human readable binary:

You can pass an integer to bin to see the string representation of a binary literal:

>>> bin(21)

And you can combine bin and int to go back and forth:

>>> bin(int('010101', 2))

You can use a format specification as well, if you want to have minimum width with preceding zeros:

>>> format(int('010101', 2), '{fill}{width}b'.format(width=10, fill=0))
>>> format(int('010101', 2), '010b')

The name 'ViewBag' does not exist in the current context

I had this problem after changing the Application's Default namespace in the Properties dialog.

The ./Views/Web.Config contained a reference to the old namespace

How to make Google Fonts work in IE?

While Yi Jiang's solution may work, I don't believe abandoning the Google Web Font API is the right answer here. We serve a local jQuery file when it's not properly loaded from the CDN, right?

<script src="//"></script>
<script>window.jQuery || document.write('<script src="/js/jquery-1.9.0.min.js"><\/script>')</script>

So why wouldn't we do the same for fonts, specifically for < IE9?

<link href=',400italic,700' rel='stylesheet' type='text/css'>
<!--[if lt IE 9]><link href='/css/fonts.css' rel='stylesheet' type='text/css'><![endif]-->

Here's my process when using custom fonts:

  1. Download the font's ZIP folder from Google, and use Font Squirrel's @font-face Generator to create the local web font.
  2. Create a fonts.css file that calls the newly created, locally hosted font files (only linking to the file if < IE9, as shown above). NOTE: The @font-face Generator creates this file for you.

    @font-face {
      font-family: 'cardoitalic';
      src: url('cardo-italic-webfont.eot');
      src: url('cardo-italic-webfont.eot?#iefix') format('embedded-opentype'),
        url('cardo-italic-webfont.woff') format('woff'),
        url('cardo-italic-webfont.ttf') format('truetype'),
        url('cardo-italic-webfont.svg#cardoitalic') format('svg');
      font-weight: normal;
      font-style: normal;
    @font-face {
      font-family: 'cardobold';
      src: url('cardo-bold-webfont.eot');
      src: url('cardo-bold-webfont.eot?#iefix') format('embedded-opentype'),
        url('cardo-bold-webfont.woff') format('woff'),
        url('cardo-bold-webfont.ttf') format('truetype'),
        url('cardo-bold-webfont.svg#cardobold') format('svg');
      font-weight: normal;
      font-style: normal;
    @font-face {
      font-family: 'cardoregular';
      src: url('cardo-regular-webfont.eot');
      src: url('cardo-regular-webfont.eot?#iefix') format('embedded-opentype'),
         url('cardo-regular-webfont.woff') format('woff'),
         url('cardo-regular-webfont.ttf') format('truetype'),
         url('cardo-regular-webfont.svg#cardoregular') format('svg');
      font-weight: normal;
      font-style: normal;
  3. Using IE conditional classes in your main stylesheet to avoide faux weights and styles, your font styles might look like this:

    .lt-ie9 h1{
    .lt-ie9 h2{
    .lt-ie9 strong,
    .lt-ie9 b{

Sure, it's a little extra work, but haven't we come to expect this from IE? Besides, it becomes second-nature after awhile.

Convert hex string to int

It's simply too big for an int (which is 4 bytes and signed).


Long.parseLong("AA0F245C", 16);

Alter a MySQL column to be AUTO_INCREMENT

As you are redefining the column again, you have to specify the datatype again and add auto_increment to it as it's a part of datatype.


Android: long click on a button -> perform actions

To get both functions working for a clickable image that will respond to both short and long clicks, I tried the following that seems to work perfectly:

    image = (ImageView) findViewById(;
    image.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

    image.setOnLongClickListener(new View.OnLongClickListener() {
    public boolean onLongClick(View v) {
        return true;

//Then the functions that are called:

 public void shortclick()
 Toast.makeText(this, "Why did you do that? That hurts!!!", Toast.LENGTH_LONG).show();


 public void longclick()
 Toast.makeText(this, "Why did you do that? That REALLY hurts!!!", Toast.LENGTH_LONG).show();


It seems that the easy way of declaring the item in XML as clickable and then defining a function to call on the click only applies to short clicks - you must have a listener to differentiate between short and long clicks.

Java : Sort integer array without using Arrays.sort()

class Sort 
    public static void main(String[] args) 
    System.out.println("Enter the range");
    java.util.Scanner sc=new java.util.Scanner(;
    int n=sc.nextInt();
    int arr[]=new int[n];
    System.out.println("Enter the array values");
    for(int i=0;i<=n-1;i++)

    System.out.println("Before sorting array values are");
     for(int i=0;i<=n-1;i++)
    for(int pass=1;pass<=n;pass++)
    for(int i=0;i<=n-1;i++)
        int temp;


    System.out.println("After sorting array values are");
       for(int i=0;i<=n-1;i++)


jquery smooth scroll to an anchor?

jQuery.scrollTo will do everything you want and more!

You can pass it all kinds of different things:

  • A raw number
  • A string('44', '100px', '+=30px', etc )
  • A DOM element (logically, child of the scrollable element)
  • A selector, that will be relative to the scrollable element
  • The string 'max' to scroll to the end.
  • A string specifying a percentage to scroll to that part of the container (f.e: 50% goes to * to the middle).
  • A hash { top:x, left:y }, x and y can be any kind of number/string like above.

Histogram with Logarithmic Scale and custom breaks

Here's a pretty ggplot2 solution:

library(scales)  # makes pretty labels on the x-axis


ggplot(mydata,aes(x = V3)) + 
  geom_histogram(breaks = log10(breaks)) + 
    breaks = breaks,
    labels = scales::trans_format("log10", scales::math_format(10^.x))

Note that to set the breaks in geom_histogram, they had to be transformed to work with scale_x_log10

How to resize a VirtualBox vmdk file

You can use Vmware player to resize a vmdk. This removes the round trip conversion (noted in other posts) if you want to keep it in vmdk format. Just make sure that when you add the vmdk into vmware, don't click upgrade format when prompted, keep the current one in case VirtualBox doesn't accept it.

git rebase: "error: cannot stat 'file': Permission denied"

I agree with the above "Close Visual Studio" answers.

However, an additional step I had to do even after I'd closed Visual Studio was to manually kill the "devenv.exe" Visual Studio process in Task Explorer. After I had done this I was able to again run in gitbash:

git pull

and the "cannot stat filename" error disappeared. It is perhaps due to a Visual Studio extension keeping the process open for longer even after closing.

How to get a random number between a float range?

random.uniform(a, b) appears to be what your looking for. From the docs:

Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.

See here.

Easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)?

In addition to the native versions, but you may want to try BitNami MAMP Stacks (disclaimer, I am one of the developers). They are completely free, all-in-one bundles of Apache, MySQL, PHP and a several other third-party libraries and utilities that are useful when developing locally. In particular, they are completely self-contained so you can have several one installed at the same time, with different versions of Apache and MySQL and they will not interfere with each other. You can get them from or directly from the Mac OS X app store

Optional args in MATLAB functions

A simple way of doing this is via nargin (N arguments in). The downside is you have to make sure that your argument list and the nargin checks match.

It is worth remembering that all inputs are optional, but the functions will exit with an error if it calls a variable which is not set. The following example sets defaults for b and c. Will exit if a is not present.

function [ output_args ] = input_example( a, b, c )
if nargin < 1
  error('input_example :  a is a required input')

if nargin < 2
  b = 20

if nargin < 3
  c = 30

<div> cannot appear as a descendant of <p>

The warning appears only because the demo code has:

function TabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
      hidden={value !== index}
      {value === index && (
        <Box p={3}>  // <==NOTE P TAG HERE

Changing it like this takes care of it:

function TabPanel(props) {
    const {children, value, index, classes, ...other} = props;

    return (
            hidden={value !== index}
            {value === index && (
                    <Box>   // <== P TAG REMOVED

SQL Server FOR EACH Loop

Off course an old question. But I have a simple solution where no need of Looping, CTE, Table variables etc.

DECLARE @MyVar datetime = '1/1/2010'    

FROM master.dbo.spt_values 

Note : spt_values is a Mircrosoft's undocumented table. It has numbers for every type. Its not suggestible to use as it can be removed in any new versions of sql server without prior information, since it is undocumented. But we can use it as quick workaround in some scenario's like above.

Plotting a 3d cube, a sphere and a vector in Matplotlib

It is a little complicated, but you can draw all the objects by the following code:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations

fig = plt.figure()
ax = fig.gca(projection='3d')

# draw cube
r = [-1, 1]
for s, e in combinations(np.array(list(product(r, r, r))), 2):
    if np.sum(np.abs(s-e)) == r[1]-r[0]:
        ax.plot3D(*zip(s, e), color="b")

# draw sphere
u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
ax.plot_wireframe(x, y, z, color="r")

# draw a point
ax.scatter([0], [0], [0], color="g", s=100)

# draw a vector
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d

class Arrow3D(FancyArrowPatch):

    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
        FancyArrowPatch.draw(self, renderer)

a = Arrow3D([0, 1], [0, 1], [0, 1], mutation_scale=20,
            lw=1, arrowstyle="-|>", color="k")


Soft keyboard open and close listener in an activity in Android

This is not working as desired...

... have seen many use size calculations to check ...

I wanted to determine if it was open or not and I found isAcceptingText()

so this really does not answer the question as it does not address opening or closing rather more like is open or closed so it is related code that may help others in various scenarios...

in an activity

    if (((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).isAcceptingText()) {
        Log.d(TAG,"Software Keyboard was shown");
    } else {
        Log.d(TAG,"Software Keyboard was not shown");

in a fragment

    if (((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).isAcceptingText()) {
        Log.d(TAG,"Software Keyboard was shown");
    } else {
        Log.d(TAG,"Software Keyboard was not shown");


Mocha / Chai not catching thrown errors

As this answer says, you can also just wrap your code in an anonymous function like this:

}).to.throw('Property does not exist in model schema.');

Version of Apache installed on a Debian machine

dlocate -s apache2 | grep '^Version:'

jQuery add text to span within a div

You can use append or prepend

The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend()).

$("#tagscloud span").append(second);
$("#tagscloud span").append(third);
$("#tagscloud span").prepend(first);

How to check if smtp is working from commandline (Linux)

Syntax for establishing a raw network connection using telnet is this:

telnet {domain_name} {port_number}

So telnet to your smtp server like

telnet 25

And copy and paste the below

mail from:<[email protected]>
rcpt to:<[email protected]>
From: [email protected]
Subject: test mail from command line

this is test number 1
sent from linux box

Note : Do not forgot the "." at the end which represents the end of the message. The "quit" line exits ends the session.

Which version of MVC am I using?

In Solution Explorer open packages.config and find Microsoft.AspNet.MVC:

package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net461"

From the above we can see it's an Asp.Net MVC 5.2.3 Version.

Moreover packages.config file also helps us to track all the installed packages with their respective versions.

How to remove an iOS app from the App Store

I just changed availability date to a future date. After doing that, I received following message -

You have selected an Available Date in the future. This will remove your currently live version from the App Store until the new date. Changing Available Date affects all versions of the application, both Ready For Sale and In Review.

Which means that the app is removed and no longer available.

Inserting records into a MySQL table using Java

This should work for any table, instead of hard-coding the columns.

//Source details_x000D_
    String sourceUrl = "jdbc:oracle:thin:@//server:1521/db";_x000D_
    String sourceUserName = "src";_x000D_
    String sourcePassword = "***";_x000D_
    // Destination details_x000D_
    String destinationUserName = "dest";_x000D_
    String destinationPassword = "***";_x000D_
    String destinationUrl = "jdbc:mysql://server:3306/db";_x000D_
    Connection srcConnection = getSourceConnection(sourceUrl, sourceUserName, sourcePassword);_x000D_
    Connection destConnection = getDestinationConnection(destinationUrl, destinationUserName, destinationPassword);_x000D_
    PreparedStatement sourceStatement = srcConnection.prepareStatement("SELECT *  FROM src_table ");_x000D_
    ResultSet rs = sourceStatement.executeQuery();_x000D_
    rs.setFetchSize(1000); // not needed_x000D_
    ResultSetMetaData meta = rs.getMetaData();_x000D_
    List<String> columns = new ArrayList<>();_x000D_
    for (int i = 1; i <= meta.getColumnCount(); i++)_x000D_
    try (PreparedStatement destStatement = destConnection.prepareStatement(_x000D_
            "INSERT INTO dest_table ("_x000D_
                    +", "))_x000D_
                    + ") VALUES ("_x000D_
                    + -> "?").collect(Collectors.joining(", "))_x000D_
                    + ")"_x000D_
        int count = 0;_x000D_
        while ( {_x000D_
            for (int i = 1; i <= meta.getColumnCount(); i++) {_x000D_
                destStatement.setObject(i, rs.getObject(i));_x000D_
        destStatement.executeBatch(); // you will see all the rows in dest once this statement is executed_x000D_
        System.out.println("done " + count);_x000D_

How to fully clean bin and obj folders within Visual Studio?

Just an addendum to all the fine answers above in case someone doesn't realize how easy it is in VB/C# to automate the entire process down to the zip archive.

So you just grab a simple Forms app from the templates (if you don't already have a housekeeping app) and add a button to it and then ClickOnce install it to your desktop without worrying about special settings or much of anything. This is all the code you need to attach to the button:

Imports System.IO.Compression

Private Sub btnArchive_Click(sender As Object, e As EventArgs) Handles btnArchive.Click
    Dim src As String = "C:\Project"
    Dim dest As String = Path.Combine("D:\Archive", "Stub" & Now.ToString("yyyyMMddHHmmss") & ".zip")
    If IsProjectOpen() Then 'You don't want Visual Studio holding a lock on anything while you're deleting folders
        MsgBox("Close projects first, (expletive deleted)", vbOKOnly)
        Exit Sub
    End If
    If MsgBox("Are you sure you want to delete bin and obj folders?", vbOKCancel) = DialogResult.Cancel Then Exit Sub
    If ClearBinAndObj(src) Then ZipFile.CreateFromDirectory(src, dest)
End Sub

Public Function ClearBinAndObj(targetDir As String) As Boolean
    Dim dirstodelete As New List(Of String)
    For Each d As String In My.Computer.FileSystem.GetDirectories(targetDir, FileIO.SearchOption.SearchAllSubDirectories, "bin")
    For Each d As String In My.Computer.FileSystem.GetDirectories(targetDir, FileIO.SearchOption.SearchAllSubDirectories, "obj")
    For Each d In dirstodelete
            Directory.Delete(d, True)
        Catch ex As Exception
            If MsgBox("Error: " & ex.Message & " - OK to continue?", vbOKCancel) = MsgBoxResult.Cancel Then Return False
        End Try
    Return True
End Function

Public Function IsProjectOpen()
    For Each clsProcess As Process In Process.GetProcesses()
        If clsProcess.ProcessName.Equals("devenv") Then Return True
    Return False
End Function

One thing to remember is that file system deletes can go wrong easily. One of my favorites was when I realized that I couldn't delete a folder because it contained items created by Visual Studio while running with elevated privileges (so that I could debug a service).

I needed to manually give permission or, I suppose, run the app with elevated privileges also. Either way, I think there is some value in using an interactive GUI-based approach over a script, specially since this is likely something that is done at the end of a long day and you don't want to find out later that your backup doesn't actually exist...

How to set specific Java version to Maven

On windows

If you do not want to change your JAVA_HOME variable inside the system variables.

Edit your mvn.bat file and add a line like this

set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_45\jre

This can be done after @REM ==== START VALIDATION ==== like mentionned by @Jonathan

On Mac (& Linux ?)

If you do not want to change your JAVA_HOME variable inside your ~/.bashrc or ~/.bash_profile

you can create a ~/.mavenrc file and redefine your JAVA_HOME using the java_home tool

export JAVA_HOME=`/usr/libexec/java_home -v 1.7.0_45`

Sanity Check

You can verify that everything is working fine by executing the following commands. The jdk version should be different.

mvn -version


java -version

Nested JSON objects - do I have to use arrays for everything?

You have too many redundant nested arrays inside your jSON data, but it is possible to retrieve the information. Though like others have said you might want to clean it up.

use each() wrap within another each() until the last array.

for[0].stuff[0].onetype[0] in jQuery you could do the following:


$.each(, function(index0, v) {
    $.each(v, function (index1, w) {
        $.each(w, function (index2, x) {



How do you remove Subversion control for a folder?

On Linux the command is:

svn delete --keep-local file_name

jQuery find and replace string

Below is the code I used to replace some text, with colored text. It's simple, took the text and replace it within an HTML tag. It works for each words in that class tags.

    //highlight_words('going', this);
    var high = 'going';
    high = high.replace(/\W/g, '');
    var str = high.split(" ");
    var text = $(this).text();
    text = text.replace(str, "<span style='color: blue'>"+str+"</span>");

Trying to handle "back" navigation button action in iOS

Set the UINavigationControllerDelegate and implement this delegate func (Swift):

func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
    if viewController is <target class> {
        //if the only way to get back - back button was pressed

Oracle Partition - Error ORA14400 - inserted partition key does not map to any partition

For this issue need to add the partition for date column values, If last partition 20201231245959, then inserting the 20210110245959 values, this issue will occurs.

For that need to add the 2021 partition into that table


How to upload a file in Django?

I must say I find the documentation at django confusing. Also for the simplest example why are forms being mentioned? The example I got to work in the is :-

for key, file in request.FILES.items():
    path =
    dest = open(path, 'w')
    if file.multiple_chunks:
        for c in file.chunks():

The html file looks like the code below, though this example only uploads one file and the code to save the files handles many :-

<form action="/upload_file/" method="post" enctype="multipart/form-data">{% csrf_token %}
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />

These examples are not my code, they have been optained from two other examples I found. I am a relative beginner to django so it is very likely I am missing some key point.

Executing a shell script from a PHP script

It's a simple problem. When you are running from terminal, you are running the php file from terminal as a privileged user. When you go to the php from your web browser, the php script is being run as the web server user which does not have permissions to execute files in your home directory. In Ubuntu, the www-data user is the apache web server user. If you're on ubuntu you would have to do the following: chown yourusername:www-data /home/testuser/testscript chmod g+x /home/testuser/testscript

what the above does is transfers user ownership of the file to you, and gives the webserver group ownership of it. the next command gives the group executable permission to the file. Now the next time you go ahead and do it from the browser, it should work.

Form Submission without page refresh

<!-- index.php -->
    <!DOCTYPE html>
        <script src=""></script>
    <form id="myForm">
        <input type="text" name="fname" id="fname"/>
        <input type="submit" name="click" value="button" />

                    method: 'POST',
                    url: 'submit.php',
                    dataType: "json",
                    contentType: "application/json",
                    data : $('#myForm').serialize(),
                    success: function(data){
                    error: function(xhr, desc, err){
<!-- submit.php -->
$value ="call";
header('Content-Type: application/json');
echo json_encode($value);

foreach with index

You can do the following

foreach (var it in someCollection.Select((x, i) => new { Value = x, Index = i }) )
   if (it.Index > SomeNumber) //      

This will create an anonymous type value for every entry in the collection. It will have two properties

  • Value: with the original value in the collection
  • Index: with the index within the collection

bash export command

Follow These step to Remove " bash export command not found." Terminal open error fix>>>>>>

open terminal and type : root@someone:~# nano ~/.bashrc

After Loading nano: remove the all 'export PATH = ...........................' lines and press ctrl+o to save file and press ctrl+e to exit.

Now the Terminal opening error will be fixed.........

jQuery set checkbox checked

"checked" attribute 'ticks' the checkbox as soon as it exists. So to check/uncheck a checkbox you have to set/unset the attribute.

For checking the box:

$('#myCheckbox').attr('checked', 'checked');

For unchecking the box:


For testing the checked status:

if ($('#myCheckbox').is(':checked'))

Hope it helps...

Is it possible to use a div as content for Twitter's Popover

All of these answers miss a very important aspect!

By using .html or innerHtml or outerHtml you are not actually using the referenced element. You are using a copy of the element's html. This has some serious draw backs.

  1. You can't use any ids because the ids will be duplicated.
  2. If you load the contents every time that the popover is shown you will lose all of the user's input.

What you want to do is load the object itself into the popover.


<h1> Test </h1>

<div><button id="target">click me</button></div>

<!-- This will be the contents of our popover -->
<div class='_content' id='blah'>
<h1>Extra Stuff</h1>
<input type='number' placeholder='number'/>


$(document).ready(function() {

    // We don't want to see the popover contents until the user clicks the target.
    // If you don't hide 'blah' first it will be visible outside of the popover.

    // Initialize our popover
        content: $('#blah'), // set the content to be the 'blah' div
        placement: 'bottom',
        html: true
    // The popover contents will not be set until the popover is shown.  Since we don't 
    // want to see the popover when the page loads, we will show it then hide it.

    // Now that the popover's content is the 'blah' dive we can make it visisble again.


Eclipse: Syntax Error, parameterized types are only if source level is 1.5

Do the following..

Right-click on your project--> select properties-----> select Java Compilers

You wills see this window

Image for reference

Now check the checkbox ---> enable project specific settings.

Now set the compiler compliance level to 1.6

Apply then Ok

now clean your project and you are good to go

How do you read a CSV file and display the results in a grid in Visual Basic 2010?

Do the following:

Dim dataTable1 As New DataTable
                dataTable1.Columns.Add("No. DOC")

For Each line As String In System.IO.File.ReadAllLines(objetos.url)

How to convert JSON data into a Python object


With Python3, you can do it in one line, using SimpleNamespace and object_hook:

import json
from types import SimpleNamespace

data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'

# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(data, object_hook=lambda d: SimpleNamespace(**d))

OLD ANSWER (Python2)

In Python2, you can do it in one line, using namedtuple and object_hook (but it's very slow with many nested objects):

import json
from collections import namedtuple

data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'

# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))

or, to reuse this easily:

def _json_object_hook(d): return namedtuple('X', d.keys())(*d.values())
def json2obj(data): return json.loads(data, object_hook=_json_object_hook)

x = json2obj(data)

If you want it to handle keys that aren't good attribute names, check out namedtuple's rename parameter.

What is default list styling (CSS)?

I think this is actually what you're looking for:

.my_container ul
    list-style: initial;
    margin: initial;
    padding: 0 0 0 40px;

.my_container li
    display: list-item;

Most simple code to populate JTable from ResultSet

I think this is the Easiest way to populate a table with ResultSet with a method like

FillTable(MyTable, "select * Customers;");

And a very simple method can be made as

public void FillTable(JTable table, String Query)
        Statement stat = conn.createStatement();
        ResultSet rs = stat.executeQuery(Query);

        //To remove previously added rows
        while(table.getRowCount() > 0) 
            ((DefaultTableModel) table.getModel()).removeRow(0);
        int columns = rs.getMetaData().getColumnCount();
            Object[] row = new Object[columns];
            for (int i = 1; i <= columns; i++)
                row[i - 1] = rs.getObject(i);
            ((DefaultTableModel) table.getModel()).insertRow(rs.getRow()-1,row);

    catch(InstantiationException | IllegalAccessException | SQLException e)

Jquery Ajax beforeSend and success,error & complete

Maybe you can try the following :

var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
    type: 'POST',
    url: url,
    data: data,
    beforeSend: function() {
        // setting a timeout
    success: function(data) {
        if (append) {
        } else {
    error: function(xhr) { // if error occured
        alert("Error occured.please try again");
        $(placeholder).append(xhr.statusText + xhr.responseText);
    complete: function() {
        if (i <= 0) {
    dataType: 'html'

This way, if the beforeSend statement is called before the complete statement i will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.

I cannot test it, let me know if it works or not.

JavaScript error (Uncaught SyntaxError: Unexpected end of input)

Formatting your code a bit, you have only closed the inner hover function. You have not closed the outer parts, marked below:

$(// missing closing)
 function() { // missing closing }
        function() {
            $("#mewlyDiagnosed").animate({'height': '237px', 'top': "-75px"});
        function() {
            $("#mewlyDiagnosed").animate({'height': '162px', 'top': "0px"});

Rails: call another controller action from a controller

To use one controller from another, do this:

def action_that_calls_one_from_another_controller
  controller_you_want =
  controller_you_want.request = request
  controller_you_want.response = response

Write a file in external storage in Android

Supplemental Answer

After writing to external storage, some file managers don't see the file right away. This can be confusing if a user thinks they copied something to the SD card, but then can't find it there. So after you copy the file, run the following code to notify file managers of its presence.

        new String[]{myFile.getAbsolutePath()},

See the documentation and this answer for more.

Install specific branch from github using Npm

you can give git pattern as version, yarn and npm are clever enough to resolve from a git repo.

yarn add any-package@user-name/repo-name#branch-name

or for npm

npm install --save any-package@user-name/repo-name#branch-name

What is python's site-packages directory?

site-packages is just the location where Python installs its modules.

No need to "find it", python knows where to find it by itself, this location is always part of the PYTHONPATH (sys.path).

Programmatically you can find it this way:

import sys
site_packages = next(p for p in sys.path if 'site-packages' in p)
print site_packages


Is it a good practice to use try-except-else in Python?

OP, YOU ARE CORRECT. The else after try/except in Python is ugly. it leads to another flow-control object where none is needed:

    x = blah()
    print "failed at blah()"
    print "just succeeded with blah"

A totally clear equivalent is:

    x = blah()
    print "just succeeded with blah"
    print "failed at blah()"

This is far clearer than an else clause. The else after try/except is not frequently written, so it takes a moment to figure what the implications are.

Just because you CAN do a thing, doesn't mean you SHOULD do a thing.

Lots of features have been added to languages because someone thought it might come in handy. Trouble is, the more features, the less clear and obvious things are because people don't usually use those bells and whistles.

Just my 5 cents here. I have to come along behind and clean up a lot of code written by 1st-year out of college developers who think they're smart and want to write code in some uber-tight, uber-efficient way when that just makes it a mess to try and read / modify later. I vote for readability every day and twice on Sundays.

Creating Accordion Table with Bootstrap

In the accepted answer you get annoying spacing between the visible rows when the expandable row is hidden. You can get rid of that by adding this to css:

.collapse-row.collapsed + tr {
     display: none;

'+' is adjacent sibling selector, so if you want your expandable row to be the next row, this selects the next tr following tr named collapse-row.

Here is updated fiddle:

Java: Convert String to TimeStamp

can you try it once...

String dob="your date String";
String dobis=null;
final DateFormat df = new SimpleDateFormat("yyyy-MMM-dd");
final Calendar c = Calendar.getInstance();
try {
    if(dob!=null && !dob.isEmpty() && dob != "")
    int month=c.get(Calendar.MONTH);


Session variables in ASP.NET MVC

Great answers from the guys but I would caution you against always relying on the Session. It is quick and easy to do so, and of course would work but would not be great in all cicrumstances.

For example if you run into a scenario where your hosting doesn't allow session use, or if you are on a web farm, or in the example of a shared SharePoint application.

If you wanted a different solution you could look at using an IOC Container such as Castle Windsor, creating a provider class as a wrapper and then keeping one instance of your class using the per request or session lifestyle depending on your requirements.

The IOC would ensure that the same instance is returned each time.

More complicated yes, if you need a simple solution just use the session.

Here are some implementation examples below out of interest.

Using this method you could create a provider class along the lines of:

public class CustomClassProvider : ICustomClassProvider
    public CustomClassProvider(CustomClass customClass)
        CustomClass = customClass;

    public string CustomClass { get; private set; }

And register it something like:

public void Install(IWindsorContainer container, IConfigurationStore store)
                () => new CustomClassProvider(new CustomClass())).LifestylePerWebRequest());

Pandas create empty DataFrame with only column names

df.to_html() has a columns parameter.

Just pass the columns into the to_html() method.


How can the size of an input text box be defined in HTML?

Try this

<input type="text" style="font-size:18pt;height:420px;width:200px;">

Or else

 <input type="text" id="txtbox">

with the css:


Difference between "module.exports" and "exports" in the CommonJs Module System

As all answers posted above are well explained, I want to add something which I faced today.

When you export something using exports then you have to use it with variable. Like,


exports.a = 5;

In another file


const A = require("./File1.js");

and using module.exports


module.exports.a = 5;

In File2.js

const A = require("./File1.js");

and default module.exports


module.exports = 5;

in File2.js

const A = require("./File2.js");

Unix: How to delete files listed in a file

In case somebody prefers sed and removing without wildcard expansion:

sed -e "s/^\(.*\)$/rm -f -- \'\1\'/" deletelist.txt | /bin/sh

Reminder: use absolute pathnames in the file or make sure you are in the right directory.

And for completeness the same with awk:

awk '{printf "rm -f -- '\''%s'\''\n",$1}' deletelist.txt | /bin/sh

Wildcard expansion will work if the single quotes are remove, but this is dangerous in case the filename contains spaces. This would need to add quotes around the wildcards.

How to print Unicode character in C++?

I needed to show the string in UI as well as save that to an xml configuration file. The above specified format is good for string in c++, I would add we can have the xml compatible string for the special character by replacing "\u" by "&#x" and adding a ";" at the end.

For example : C++ : "\u0444" --> XML : "&#x0444;"

Call angularjs function using jquery/javascript

Your plunker is firing off


Before anything is rendered.

You can verify that by wrapping it in a timeout

setTimeout(function() {
}, 1000);

You also need to acutally add an ID to your div.

<div ng-app='MyModule' ng-controller="MyController" id="MyController">

What is the role of the package-lock.json?

package-lock.json is written to when a numerical value in a property such as the "version" property, or a dependency property is changed in package.json.

If these numerical values in package.json and package-lock.json match, package-lock.json is read from.

If these numerical values in package.json and package-lock.json do not match, package-lock.json is written to with those new values, and new modifiers such as the caret and tilde if they are present. But it is the numeral that is triggering the change to package-lock.json.

To see what I mean, do the following. Using package.json without package-lock.json, run npm install with:

  "name": "test",
  "version": "1.0.0",
  "devDependencies": {
    "sinon": "7.2.2"

package-lock.json will now have:

"sinon": {
  "version": "7.2.2",

Now copy/paste both files to a new directory. Change package.json to (only adding caret):

  "name": "test",
  "version": "1.0.0",
  "devDependencies": {
    "sinon": "^7.2.2"

run npm install. If there were no package-lock.json file, [email protected] would be installed. npm install is reading from package-lock.json and installing 7.2.2.

Now change package.json to:

  "name": "test",
  "version": "1.0.0",
  "devDependencies": {
    "sinon": "^7.3.0"

run npm install. package-lock.json has been written to, and will now show:

"sinon": {
  "version": "^7.3.0",

Google Chrome default opening position and size

Maybe a little late, but I found an easier way to set the defaults! You have to right-click on the right of your tab and choose "size", then click on your window, and it should keep it as the default size.

IEnumerable vs List - What to Use? How do they work?

A class that implement IEnumerable allows you to use the foreach syntax.

Basically it has a method to get the next item in the collection. It doesn't need the whole collection to be in memory and doesn't know how many items are in it, foreach just keeps getting the next item until it runs out.

This can be very useful in certain circumstances, for instance in a massive database table you don't want to copy the entire thing into memory before you start processing the rows.

Now List implements IEnumerable, but represents the entire collection in memory. If you have an IEnumerable and you call .ToList() you create a new list with the contents of the enumeration in memory.

Your linq expression returns an enumeration, and by default the expression executes when you iterate through using the foreach. An IEnumerable linq statement executes when you iterate the foreach, but you can force it to iterate sooner using .ToList().

Here's what I mean:

var things = 
    from item in BigDatabaseCall()
    where ....
    select item;

// this will iterate through the entire linq statement:
int count = things.Count();

// this will stop after iterating the first one, but will execute the linq again
bool hasAnyRecs = things.Any();

// this will execute the linq statement *again*
foreach( var thing in things ) ...

// this will copy the results to a list in memory
var list = things.ToList()

// this won't iterate through again, the list knows how many items are in it
int count2 = list.Count();

// this won't execute the linq statement - we have it copied to the list
foreach( var thing in list ) ...

Using ng-click vs bind within link function of Angular Directive

I think it is fine because I've seen many people doing this way.

If you are just defining the event handler within the directive, you do not have to define it on the scope, though. Following would be fine.

myApp.directive('clickme', function() {
  return function(scope, element, attrs) {
    var clickingCallback = function() {
    element.bind('click', clickingCallback);

How to use an environment variable inside a quoted string in Bash

The following script works for me for multiple values of $COLUMNS. I wonder if you are not setting COLUMNS prior to this call?

svn diff $@ --diff-cmd /usr/bin/diff -x "-y -w -p -W $COLUMNS"

Can you echo $COLUMNS inside your script to see if it set correctly?

How to refresh token with Google API client?

You need to save the access token to file or database as a json string during the initial authorization request, and set the access type to offline $client->setAccessType("offline")

Then, during subsequent api requests, grab the access token from your file or db and pass it to the client:

$accessToken = json_decode($row['token'], true);

Now you need to check if the token has expired:

if ($client->isAccessTokenExpired()) {
    // access token has expired, use the refresh token to obtain a new one
    // save the new token to file or db
    // ...json_encode($client->getAccessToken())

The fetchAccessTokenWithRefreshToken() function will do the work for you and provide a new access token, save it back to your file or database.

Accessing bash command line args $@ vs $*

The difference appears when the special parameters are quoted. Let me illustrate the differences:

$ set -- "arg  1" "arg  2" "arg  3"

$ for word in $*; do echo "$word"; done

$ for word in $@; do echo "$word"; done

$ for word in "$*"; do echo "$word"; done
arg  1 arg  2 arg  3

$ for word in "$@"; do echo "$word"; done
arg  1
arg  2
arg  3

one further example on the importance of quoting: note there are 2 spaces between "arg" and the number, but if I fail to quote $word:

$ for word in "$@"; do echo $word; done
arg 1
arg 2
arg 3

and in bash, "$@" is the "default" list to iterate over:

$ for word; do echo "$word"; done
arg  1
arg  2
arg  3

Understanding Popen.communicate

.communicate() writes input (there is no input in this case so it just closes subprocess' stdin to indicate to the subprocess that there is no more input), reads all output, and waits for the subprocess to exit.

The exception EOFError is raised in the child process by raw_input() (it expected data but got EOF (no data)). hangs forever because it tries to read all output from the child at the same time as the child waits for input (raw_input()) that causes a deadlock.

To avoid the deadlock you need to read/write asynchronously (e.g., by using threads or select) or to know exactly when and how much to read/write, for example:

from subprocess import PIPE, Popen

p = Popen(["python", "-u", ""], stdin=PIPE, stdout=PIPE, bufsize=1)
print p.stdout.readline(), # read the first line
for i in range(10): # repeat several times to show that it works
    print >>p.stdin, i # write input
    p.stdin.flush() # not necessary in this case
    print p.stdout.readline(), # read output

print p.communicate("n\n")[0], # signal the child to exit,
                               # read the rest of the output, 
                               # wait for the child to exit

Note: it is a very fragile code if read/write are not in sync; it deadlocks.

Beware of block-buffering issue (here it is solved by using "-u" flag that turns off buffering for stdin, stdout in the child).

bufsize=1 makes the pipes line-buffered on the parent side.

Regular Expression For Duplicate Words

The below expression should work correctly to find any number of consecutive words. The matching can be case insensitive.

String regex = "\\b(\\w+)(\\s+\\1\\b)*";
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);

Matcher m = p.matcher(input);

// Check for subsequences of input that match the compiled pattern
while (m.find()) {
     input = input.replaceAll(,;

Sample Input : Goodbye goodbye GooDbYe

Sample Output : Goodbye


The regex expression:

\b : Start of a word boundary

\w+ : Any number of word characters

(\s+\1\b)* : Any number of space followed by word which matches the previous word and ends the word boundary. Whole thing wrapped in * helps to find more than one repetitions.

Grouping : : Shall contain the matched group in above case Goodbye goodbye GooDbYe : Shall contain the first word of the matched pattern in above case Goodbye

Replace method shall replace all consecutive matched words with the first instance of the word.

Better techniques for trimming leading zeros in SQL Server?

This might help

SELECT ABS(column_name) FROM [db].[schema].[table]

Close popup window

An old tip...

var daddy = window.self;
daddy.opener = window.self;

HTML Table cell background image alignment

use like this your inline css

<td width="178" rowspan="3" valign="top" 
align="right" background="images/left.jpg" 
style="background-repeat:background-position: right top;">

java.lang.OutOfMemoryError: Java heap space in Maven

The chances are that the problem is in one of the unit tests that you've asked Maven to run.

As such, fiddling with the heap size is the wrong approach. Instead, you should be looking at the unit test that has caused the OOME, and trying to figure out if it is the fault of the unit test or the code that it is testing.

Start by looking at the stack trace. If there isn't one, run mvn ... test again with the -e option.

GROUP BY having MAX date

There's no need to group in that subquery... a where clause would suffice:

SELECT * FROM tblpm n
WHERE date_updated=(SELECT MAX(date_updated)
    FROM tblpm WHERE control_number=n.control_number)

Also, do you have an index on the 'date_updated' column? That would certainly help.


Look this example.

CREATE TABLE [dbo].#TestTable(
    [id] [int] NOT NULL,
    [create_date] [date] NOT NULL,
    [info1] [varchar](50) NOT NULL,
    [info2] [varchar](50) NOT NULL,

Insert some data

INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (1, '1/1/09', 'Blue', 'Green')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (1, '1/2/09', 'Red', 'Yellow')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (1, '1/3/09', 'Orange', 'Purple')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (2, '1/1/09', 'Yellow', 'Blue')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (2, '1/5/09', 'Blue', 'Orange')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (3, '1/2/09', 'Green', 'Purple')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (3, '1/8/09', 'Red', 'Blue')

Repeat same Values for 1

INSERT INTO dbo.#TestTable (id, create_date, info1, info2) VALUES (1, '1/1/09', 'Blue', 'Green')

Look All

SELECT * FROM #TestTable

Look your results

FROM #TestTable

Need to understand the different

Write string to text file and ensure it always overwrites the existing content.

If your code doesn't require the file to be truncated first, you can use the FileMode.OpenOrCreate to open the filestream, which will create the file if it doesn't exist or open it if it does. You can use the stream to point at the front and start overwriting the existing file?

I'm assuming your using a streams here, there are other ways to write a file.

How to include css files in Vue 2

If you want to append this css file to header you can do it using mounted() function of the vue file. See the example.
Note: Assume you can access the css file as http://www.yoursite/assets/styles/vendor.css in the browser.

mounted() {
        let style = document.createElement('link');
        style.type = "text/css";
        style.rel = "stylesheet";
        style.href = '/assets/styles/vendor.css';

How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

Although not directly applicable to this question, because it wants some information for the user, google brought me here when I wanted to run my .bat file elevated from task scheduler.

The simplest approach was to create a shortcut to the .bat file, because for a shortcut you can set Run as administrator directly from the advanced properties.

Running the shortcut from task scheduler, runs the .bat file elevated.

Disabling swap files creation in vim

here are my personal ~/.vimrc backup settings

" backup to ~/.tmp 
set backup 
set backupdir=~/.vim-tmp,~/.tmp,~/tmp,/var/tmp,/tmp 
set backupskip=/tmp/*,/private/tmp/* 
set directory=~/.vim-tmp,~/.tmp,~/tmp,/var/tmp,/tmp 
set writebackup

How to give credentials in a batch script that copies files to a network location?

You can also map the share to a local drive as follows:

net use X: "\\servername\share" /user:morgan password

How to show the last queries executed on MySQL?

You can do the flowing thing for monitoring mysql query logs.

Open mysql configuration file my.cnf

sudo nano /etc/mysql/my.cnf

Search following lines under a [mysqld] heading and uncomment these lines to enable log

general_log_file        = /var/log/mysql/mysql.log
general_log             = 1

Restart your mysql server for reflect changes

sudo service mysql start

Monitor mysql server log with following command in terminal

tail -f /var/log/mysql/mysql.log

What's the best way to determine which version of Oracle client I'm running?

In Windows -> use Command Promt:

tnsping localhost

It show the version and if is installed 32 o 64 bit client, for example:

TNS Ping Utility for 64-bit Windows: Version - Production on 03-MAR-2015 16:47:26


How to find MySQL process list and to kill those processes?

select GROUP_CONCAT(stat SEPARATOR ' ') from (select concat('KILL ',id,';') as stat from information_schema.processlist) as stats;

Then copy and paste the result back into the terminal. Something like:

KILL 2871; KILL 2879; KILL 2874; KILL 2872; KILL 2866;

Commands out of sync; you can't run this command now

I think the problem is that you're making a new connection in the function, and then not closing it at the end. Why don't you try passing in the existing connection and re-using it?

Another possibility is that you're returning out of the middle of a while loop fetching. You never complete that outer fetch.

How to save an HTML5 Canvas as an image on a server?

Here is an example of how to achieve what you need:

  1. Draw something (taken from canvas tutorial)

<canvas id="myCanvas" width="578" height="200"></canvas>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  // begin custom shape
  context.moveTo(170, 80);
  context.bezierCurveTo(130, 100, 130, 150, 230, 150);
  context.bezierCurveTo(250, 180, 320, 180, 340, 150);
  context.bezierCurveTo(420, 150, 420, 120, 390, 100);
  context.bezierCurveTo(430, 40, 370, 30, 340, 50);
  context.bezierCurveTo(320, 5, 250, 20, 250, 50);
  context.bezierCurveTo(200, 5, 150, 20, 170, 80);

  // complete custom shape
  context.lineWidth = 5;
  context.fillStyle = '#8ED6FF';
  context.strokeStyle = 'blue';

  1. Convert canvas image to URL format (base64)

    var dataURL = canvas.toDataURL();

  2. Send it to your server via Ajax

      type: "POST",
      url: "script.php",
      data: { 
         imgBase64: dataURL
    }).done(function(o) {
      // If you want the file to be visible in the browser 
      // - please modify the callback in javascript. All you
      // need is to return the url to the file, you just saved 
      // and than put the image in your browser.

  1. Save base64 on your server as an image (here is how to do this in PHP, the same ideas is in every language. Server side in PHP can be found here):

How to append rows to an R data frame

Lets take a vector 'point' which has numbers from 1 to 5

point = c(1,2,3,4,5)

if we want to append a number 6 anywhere inside the vector then below command may come handy

i) Vectors

new_var = append(point, 6 ,after = length(point))

ii) columns of a table

new_var = append(point, 6 ,after = length(mtcars$mpg))

The command append takes three arguments:

  1. the vector/column to be modified.
  2. value to be included in the modified vector.
  3. a subscript, after which the values are to be appended.

simple...!! Apologies in case of any...!

How to set up gradle and android studio to do release build?

No need to update gradle for making release application in Android studio.If you were eclipse user then it will be so easy for you. If you are new then follow the steps

1: Go to the "Build" at the toolbar section. 2: Choose "Generate Signed APK..." option. enter image description here

3:fill opened form and go next 4 :if you already have .keystore or .jks then choose that file enter your password and alias name and respective password. 5: Or don't have .keystore or .jks file then click on Create new... button as shown on pic 1 then fill the form.enter image description here

Above process was to make build manually. If You want android studio to automatically Signing Your App

In Android Studio, you can configure your project to sign your release APK automatically during the build process:

On the project browser, right click on your app and select Open Module Settings. On the Project Structure window, select your app's module under Modules. Click on the Signing tab. Select your keystore file, enter a name for this signing configuration (as you may create more than one), and enter the required information. enter image description here Figure 4. Create a signing configuration in Android Studio.

Click on the Build Types tab. Select the release build. Under Signing Config, select the signing configuration you just created. enter image description here Figure 5. Select a signing configuration in Android Studio.

4:Most Important thing that make debuggable=false at gradle.

    buildTypes {
        release {
           minifyEnabled false
          proguardFiles getDefaultProguardFile('proguard-  android.txt'), 'proguard-rules.txt'
        debuggable false
        jniDebuggable false
        renderscriptDebuggable false
        zipAlignEnabled true

visit for more in info

get basic SQL Server table structure information

sp_help will give you a whole bunch of information about a table including the columns, keys and constraints. For example, running

exec sp_help 'Address' 

will give you information about Address.

How do I set the focus to the first input element in an HTML form independent from the id?

without jquery, e.g. with regular javascript:

document.querySelector('form input:not([type=hidden])').focus()

works on Safari but not Chrome 75 (april 2019)

sqlplus statement from command line

Just be aware that on Unix/Linux your username/password can be seen by anyone that can run "ps -ef" command if you place it directly on the command line . Could be a big security issue (or turn into a big security issue).

I usually recommend creating a file or using here document so you can protect the username/password from being viewed with "ps -ef" command in Unix/Linux. If the username/password is contained in a script file or sql file you can protect using appropriate user/group read permissions. Then you can keep the user/pass inside the file like this in a shell script:

sqlplus -s /nolog <<EOF
connect user/pass
select blah;

Error: More than one module matches. Use skip-import option to skip importing the component into the closest module

I was getting below error when trying to create a new component under a folder.

error: More than one module matches. Use skip-import option to skip importing the component into the closest module.

I have used below command and new component got created successfully under a folder.

 ng g c folderName/my_newComponent ---module ../app

How to have Ellipsis effect on Text

        flexDirection: 'row',
        padding: 10,
  <Text numberOfLines={5} style={{flex:1}}>
       This is a very long text that will overflow on a small device This is a very 
       long text that will overflow on a small deviceThis is a very long text that 
       will overflow on a small deviceThis is a very long text that will overflow 
       on a small device

Illegal string offset Warning PHP

A little bit late to the question, but for others who are searching: I got this error by initializing with a wrong value (type):

$varName = '';
$varName["x"] = "test"; // causes: Illegal string offset

The right way is:

 $varName = array();
 $varName["x"] = "test"; // works

how to change the default positioning of modal in bootstrap?

I get a better result setting this class:

.modal-dialog {
  position: absolute;
  top: 50px;
  right: 100px;
  bottom: 0;
  left: 0;
  z-index: 10040;
  overflow: auto;
  overflow-y: auto;

With bootstrap 3.3.7.

(all credits to msnfreaky for the idea...)

Emulating a do-while loop in Bash

This implementation:

  • Has no code duplication
  • Doesn't require extra functions()
  • Doesn't depend on the return value of code in the "while" section of the loop:
while $do || conditions; do
  # your code ...

It works with a read loop, too, skipping the first read:

while $do || read foo; do

  # your code ...
  echo $foo

How to count how many values per level in a given factor?

In case I just want to know how many unique factor levels exist in the data, I use:


How to return result of a SELECT inside a function in PostgreSQL?

Hi please check the below link


CREATE FUNCTION sum_n_product_with_tab (x int)
RETURNS TABLE(sum int, product int) AS $$
    SELECT $1 + tab.y, $1 * tab.y FROM tab;

Convert date from String to Date format in Dataframes

Use to_date with Java SimpleDateFormat.



  SELECT TO_DATE(CAST(UNIX_TIMESTAMP('08/26/2016', 'MM/dd/yyyy') AS TIMESTAMP)) AS newdate"""

|        dt|

How to symbolicate crash log Xcode?

You can refer this one too, I have written step by step procedure of Manual Crash Re-Symbolication.

Crash Re-Symbolication


Move all the above files (, MyApp-dSYM.dSYM and MyApp-Crash-log.crash) into a Folder with a convenient name wherever you can go using Terminal easily.

For me, Desktop is the most easily reachable place ;) So, I have moved these three files into a folder MyApp at Desktop.


Now its turn of Finder, Go to the path from following whichever is applicable for your XCODE version.

Use this command to find the symbolicatecrash script file,
find /Applications/ -name symbolicatecrash

Xcode 8, Xcode 9, Xcode 11 /Applications/

Xcode 7.3 /Applications/

XCode 7 /Applications/

Xcode 6 /Applications/

Lower then Xcode 6 Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks/DTDeviceKitBase.framework/Versions/A/Resources

Or Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks/DTDeviceKit.framework/Versions/A/Resources


Add the found symbolicatecrash script file's directory to $PATH env variable like this: sudo vim /etc/paths.d/Xcode-symbolicatecrash and paste the script file's directory and save the file. When opening a new terminal, you can call symbolicatecrash at any folder as commands located in /usr/bin.


Copy symbolicatecrash file from this location, and paste it to the Desktop/MyApp (Wait… Don’t blindly follow me, I am pasting sybolicatecrash file in folder MyApp, one that you created in step one at your favorite location, having three files.)


Open Terminal, and CD to the MyApp Folder.

cd Desktop/MyApp — Press Enter
export DEVELOPER_DIR=$(xcode-select --print-path)

Press Enter

./symbolicatecrash -v MyApp-Crash-log.crash MyApp.dSYM

Press Enter

That’s it !! Symbolicated logs are on your terminal… now what are you waiting for? Now simply, Find out the Error and resolve it ;)

Happy Coding !!!

How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?

For those looking to do this in dask. I could not find a similar option in dask but if I simply do this in same notebook for pandas it works for dask too.

import pandas as pd
import dask.dataframe as dd
pd.set_option('display.max_colwidth', -1) # This will set the no truncate for pandas as well as for dask. Not sure how it does for dask though. but it works

train_data = dd.read_csv('./data/train.csv')    

PHP: If internet explorer 6, 7, 8 , or 9

You can do this via parsing the user-agent header:

Be wary that this is not very reliable and can be trivially spoofed.

No Such Element Exception?

I had run into the same issue while I was dealing with large dataset. One thing I've noticed was the NoSuchElementException is thrown when the Scanner reaches the endOfFile, where it is not going to affect our data.

Here, I've placed my code in try block and catch block handles the exception. You can also leave it empty, if you don't want to perform any task.

For the above question, because you are using both in the condition and in the while loop you can handle the exception as

    try{; //stack trace error here
       }catch(NoSuchElementException e) {  }

This worked perfectly for me, if there are any corner cases for my approach, do let me know through comments.

Python non-greedy regexes

Do you want it to match "(b)"? Do as Zitrax and Paolo have suggested. Do you want it to match "b"? Do

>>> x = "a (b) c (d) e"
>>>"\((.*?)\)", x).group(1)

Is there a way to automatically generate getters and setters in Eclipse?

Right click-> generate getters and setters does the job well but if you want to create a keyboard shortcut in eclipse in windows, you can follow the following steps:

  1. Go to Window > Preferences
  2. Go to General > Keys
  3. List for "Quick Assist - Create getter/setter for field"
  4. In the "Binding" textfield below, hold the desired keys (in my case, I use ALT + SHIFT + G)
  5. Hit Apply and Ok
  6. Now in your Java editor, select the field you want to create getter/setter methods for and press the shortcut you setup in Step 4. Hit ok in this window to create the methods.

Hope this helps!

MySQL Trigger after update only if row has changed

I cant comment, so just beware, that if your column supports NULL values, OLD.x<>NEW.x isnt enough, because


returns 0 as same as


So it will not track changes FROM and TO NULL

The correct way in this scenario is


Printing pointers in C

change line:

char s[] = "asd";


char *s = "asd";

and things will get more clear

How can I delete one element from an array by value

Compiling all the different options for delete in ruby

delete - Deletes matching elements by value. If more than one value matches it will remove all. If you don't care about the number of occurrence or sure about single occurrence, use this method.

a = [2, 6, 3, 5, 3, 7]
a.delete(3)  # returns 3
puts a       # return [2, 6, 5, 7]

delete_at - Deletes element at given index. If you know the index use this method.

# continuing from the above example
a.delete_at(2) # returns 5
puts a         # returns [2, 6, 7]

delete_if - Deletes every element for which block is true. This will modify the array. Array changes instantly as the block is called.

b = [1, 2, 5, 4, 9, 10, 11]
b.delete_if {|n| n >= 10}.  # returns [1, 2, 5, 4, 9]

reject - This will return new array with the elements for which the given block is false. The ordering is maintained with this.

c = [1, 2, 5, 4, 9, 10, 11]
c.reject {|n| n >= 10}.  # returns [1, 2, 5, 4, 9]

reject! - same as delete_if. Array may not change instantly as the block is called.

If you want to delete multiple values from array, the best option is as bellow.

a = [2, 3, 7, 4, 6, 21, 13]
b = [7, 21]
a = a - b    # a - [2, 3, 4, 6, 13]

1030 Got error 28 from storage engine

If you want to use the tokudb plugin This can happen if you have less than 5% (by default) of free space.

see the option: tokudb_fs_reserve_percent

Maximum packet size for a TCP connection

There're no packets in TCP API.

There're packets in underlying protocols often, like when TCP is done over IP, which you have no interest in, because they have nothing to do with the user except for very delicate performance optimizations which you are probably not interested in (according to the question's formulation).

If you ask what is a maximum number of bytes you can send() in one API call, then this is implementation and settings dependent. You would usually call send() for chunks of up to several kilobytes, and be always ready for the system to refuse to accept it totally or partially, in which case you will have to manually manage splitting into smaller chunks to feed your data into the TCP send() API.

What is the best way to find the users home directory in Java?

Others have answered the question before me but a useful program to print out all available properties is:

for (Map.Entry<?,?> e : System.getProperties().entrySet()) {
    System.out.println(String.format("%s = %s", e.getKey(), e.getValue())); 

super() in Java

Yes, super() (lowercase) calls a constructor of the parent class. You can include arguments: super(foo, bar)

There is also a super keyword, that you can use in methods to invoke a method of the superclass

A quick google for "Java super" results in this



This will contain a 'non-empty' value if the request was sent through HTTPS

PHP Server Variables

How to get mouse position in jQuery without mouse-events?

I don't believe there's a way to query the mouse position, but you can use a mousemove handler that just stores the information away, so you can query the stored information.

jQuery(function($) {
    var currentMousePos = { x: -1, y: -1 };
    $(document).mousemove(function(event) {
        currentMousePos.x = event.pageX;
        currentMousePos.y = event.pageY;

    // ELSEWHERE, your code that needs to know the mouse position without an event
    if (currentMousePos.x < 10) {
        // ....

But almost all code, other than setTimeout code and such, runs in response to an event, and most events provide the mouse position. So your code that needs to know where the mouse is probably already has access to that information...

html select option separator

You could use the em dash "—". It has no visible spaces between each character.
(In some fonts!)


<option value="—————————————" disabled>—————————————</option>

Or in XHTML:

<option value="—————————————" disabled="disabled">—————————————</option>

How to check if string input is a number?

while True:
    b1=input('Type a number:')
    except ValueError:
        print ('"%(a1)s" is not a number. Try again.' %{'a1':b1})       
        print ('You typed "{}".'.format(a1))

This makes a loop to check whether input is an integer or not, result would look like below:

>>> %Run
Type a number:d
"d" is not a number. Try again.
Type a number:
>>> %Run
Type a number:4
You typed 4.

How can I get the "network" time, (from the "Automatic" setting called "Use network-provided values"), NOT the time on the phone?

the time signal is not built into network antennas: you have to use the NTP protocol in order to retrieve the time on a ntp server. there are plenty of ntp clients, available as standalone executables or libraries.

the gps signal does indeed include a precise time signal, which is available with any "fix".

however, if nor the network, nor the gps are available, your only choice is to resort on the time of the phone... your best solution would be to use a system wide setting to synchronize automatically the phone time to the gps or ntp time, then always use the time of the phone.

note that the phone time, if synchronized regularly, should not differ much from the gps or ntp time. also note that forcing a user to synchronize its time may be intrusive, you 'd better ask your user if he accepts synchronizing. at last, are you sure you absolutely need a time that precise ?

How to test web service using command line curl

In addition to existing answers it is often desired to format the REST output (typically JSON and XML lacks indentation). Try this:

$ curl  | xmllint --format -
$ curl | python -mjson.tool

Tested on Ubuntu 11.0.4/11.10.

Another issue is the desired content type. Twitter uses .xml/.json extension, but more idiomatic REST would require Accept header:

$ curl -H "Accept: application/json"

Allow all remote connections, MySQL

Also you need to disable below line in configuration file: bind-address =

When should I use Lazy<T>?

You typically use it when you want to instantiate something the first time its actually used. This delays the cost of creating it till if/when it's needed instead of always incurring the cost.

Usually this is preferable when the object may or may not be used and the cost of constructing it is non-trivial.

Appending HTML string to the DOM

Quick Hack:


Use Cases:

1: Save as .html file and run in chrome or firefox or edge. (IE wont work)

2: Use in

In Action:

Broken down with comments:


//: The message "QUICK_HACK" 
//: wrapped in a header #1 tag.
var text = "<h1>QUICK_HACK</h1>";

//: It's a quick hack, so I don't
//: care where it goes on the document,
//: just as long as I can see it.
//: Since I am doing this quick hack in
//: an empty file or scratchpad, 
//: it should be visible.
var child = document.children[0];

//: Set the html content of your child
//: to the message you want to see on screen.
child.innerHTML = text;


Reason Why I posted: has two must haves:

  1. No autocomplete
  2. Vertical monitor friendly

But doesn't show console.log messages. Came here looking for a quick solution. I just want to see the results of a few lines of scratchpad code, the other solutions are too much work.

Python Socket Receive Large Amount of Data

You can use it as: data = recvall(sock)

def recvall(sock):
    BUFF_SIZE = 4096 # 4 KiB
    data = b''
    while True:
        part = sock.recv(BUFF_SIZE)
        data += part
        if len(part) < BUFF_SIZE:
            # either 0 or end of data
    return data

Test if remote TCP port is open from a shell script

I needed short script which was run in cron and hasn't output. I solve my trouble using nmap

open=`nmap -p $PORT $SERVER | grep "$PORT" | grep open`
if [ -z "$open" ]; then
  echo "Connection to $SERVER on port $PORT failed"
  exit 1
  echo "Connection to $SERVER on port $PORT succeeded"
  exit 0

To run it You should install nmap because it is not default installed package.

How to view the assembly behind the code using Visual C++?

In Visual C++ the project options under, Output Files I believe has an option for outputing the ASM listing with source code. So you will see the C/C++ source code and the resulting ASM all in the same file.

Lua String replace


name = "^aH^ai"
name = name:gsub("%^a", "")

See also:

Invalid column name sql error

You have to use '"+texbox1.Text+"','"+texbox2.Text+"','"+texbox3.Text+"'

Instead of "+texbox1.Text+","+texbox2.Text+","+texbox3.Text+"

Notice the extra single quotes.

Copy file from source directory to binary directory using CMake

I would suggest TARGET_FILE_DIR if you want the file to be copied to the same folder as your .exe file.

$ Directory of main file (.exe, .so.1.2, .a).


In VS, this cmake script will copy input.txt to the same file as your final exe, no matter it's debug or release.

Using curl POST with variables defined in bash script functions

Solution tested with and inline bash script
1. For variables without spaces in it i.e. 1:
Simply add ' before and after $variable when replacing desired string

for i in {1..3}; do \
  curl -X POST -H "Content-Type: application/json" -d \
    '{"number":"'$i'"}' ""; \

2. For input with spaces:
Wrap variable with additional " i.e. "el a":

declare -a arr=("el a" "el b" "el c"); for i in "${arr[@]}"; do \
  curl -X POST -H "Content-Type: application/json" -d \
    '{"elem":"'"$i"'"}' ""; \

Wow works :)

What are the correct version numbers for C#?

C# language version history:

These are the versions of C# known about at the time of this writing:

In response to the OP's question:

What are the correct version numbers for C#? What came out when? Why can't I find any answers about C# 3.5?

There is no such thing as C# 3.5 - the cause of confusion here is that the C# 3.0 is present in .NET 3.5. The language and framework are versioned independently, however - as is the CLR, which is at version 2.0 for .NET 2.0 through 3.5, .NET 4 introducing CLR 4.0, service packs notwithstanding. The CLR in .NET 4.5 has various improvements, but the versioning is unclear: in some places it may be referred to as CLR 4.5 (this MSDN page used to refer to it that way, for example), but the Environment.Version property still reports

As of May 3, 2017, the C# Language Team created a history of C# versions and features on their GitHub repository: Features Added in C# Language Versions. There is also a page that tracks upcoming and recently implemented language features.

vertical-align image in div

If you have a fixed height in your container, you can set line-height to be the same as height, and it will center vertically. Then just add text-align to center horizontally.

Here's an example:


Your code should look like this:

.img_thumb {
    float: left;
    height: 120px;
    margin-bottom: 5px;
    margin-left: 9px;
    position: relative;
    width: 147px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 3px;

.img_thumb img {
    vertical-align: middle;

The images will always be centered horizontally and vertically, no matter what their size is. Here's 2 more examples with images with different dimensions:


It's now 2016 (the future!) and looks like a few things are changing (finally!!).

Back in 2014, Microsoft announced that it will stop supporting IE8 in all versions of Windows and will encourage all users to update to IE11 or Edge. Well, this is supposed to happen next Tuesday (12th January).

Why does this matter? With the announced death of IE8, we can finally start using CSS3 magic.

With that being said, here's an updated way of aligning elements, both horizontally and vertically:

.container {
    position: relative;

.container .element {
   position: absolute;
   left: 50%;
   top: 50%;
   transform: translate(-50%, -50%);

Using this transform: translate(); method, you don't even need to have a fixed height in your container, it's fully dynamic. Your element has fixed height or width? Your container as well? No? It doesn't matter, it will always be centered because all centering properties are fixed on the child, it's independent from the parent. Thank you CSS3.

If you only need to center in one dimension, you can use translateY or translateX. Just try it for a while and you'll see how it works. Also, try to change the values of the translate, you will find it useful for a bunch of different situations.

Here, have a new fiddle:

For more information on transform, here's a good resource.

Happy coding.

Finding smallest value in an array most efficiently

You need too loop through the array, remembering the smallest value you've seen so far. Like this:

int smallest = INT_MAX;
for (int i = 0; i < array_length; i++) {
    if (array[i] < smallest) {
        smallest = array[i];

Round up value to nearest whole number in SQL UPDATE

You could use the ceiling function; this portion of SQL code :

select ceiling(45.01), ceiling(45.49), ceiling(45.99);

will get you "46" each time.

For your update, so, I'd say :

Update product SET price = ceiling(45.01)

BTW : On MySQL, ceil is an alias to ceiling ; not sure about other DB systems, so you might have to use one or the other, depending on the DB you are using...

Quoting the documentation :


Returns the smallest integer value not less than X.

And the given example :

mysql> SELECT CEILING(1.23);
        -> 2
mysql> SELECT CEILING(-1.23);
        -> -1

PHP How to find the time elapsed since a date time?

If you use the php Datetime class you could use:

function time_ago(Datetime $date) {
  $time_ago = '';

  $diff = $date->diff(new Datetime('now'));

  if (($t = $diff->format("%m")) > 0)
    $time_ago = $t . ' months';
  else if (($t = $diff->format("%d")) > 0)
    $time_ago = $t . ' days';
  else if (($t = $diff->format("%H")) > 0)
    $time_ago = $t . ' hours';
    $time_ago = 'minutes';

  return $time_ago . ' ago (' . $date->format('M j, Y') . ')';

How to efficiently change image attribute "src" from relative URL to absolute using jQuery?

The replace method in Javascript returns a value, and does not act upon the existing string object. See:

In your example, you will have to do

$(this).attr("src", $(this).attr("src").replace(...))