Programs & Examples On #Vmime

Jquery-How to grey out the background while showing the loading icon over it

I reworked the example you provided in the js fiddle :

Step 1 :

I renamed your container div to overlay, as semantically this div is not a container, but an overlay. I also placed the loader div as a child of this overlay div.

The resulting html is :

<div class="overlay">
    <div id="loading-img"></div>

<div class="content">
    <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea velit provident sint aliquid eos omnis aperiam officia architecto error incidunt nemo obcaecati adipisci doloremque dicta neque placeat natus beatae cupiditate minima ipsam quaerat explicabo non reiciendis qui sit. ...</div>
    <button id="button">Submit</button>

The css of the overlay is the following

.overlay {
    background: #e9e9e9;  <- I left your 'gray' background
    display: none;        <- Not displayed by default
    position: absolute;   <- This and the following properties will
    top: 0;                  make the overlay, the element will expand
    right: 0;                so as to cover the whole body of the page
    bottom: 0;
    left: 0;
    opacity: 0.5;

Step 2 :

I added some dummy text so as to have something to overlay.

Step 3 :

Then, in the click handler we just need to show the overlay :

$("#button").click(function () {

Fast way to get the min/max values among properties of object

You can also try with Object.values

const points = { Neel: 100, Veer: 89, Shubham: 78, Vikash: 67 };_x000D_
const vals = Object.values(points);_x000D_
const max = Math.max(...vals);_x000D_
const min = Math.min(...vals);_x000D_

C# how to wait for a webpage to finish loading before continuing

Try the DocumentCompleted Event

webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);

void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    webBrowser.Document.GetElementById("product").SetAttribute("value", product);
    webBrowser.Document.GetElementById("version").SetAttribute("value", version);

Using "&times" word in html changes to ×

You need to escape:

<div class="test">&amp;times</div>

And then read the value using text() to get the unescaped value:

alert($(".test").text()); // outputs: &times

How to use range-based for() loop with std::map?

Each element of the container is a map<K, V>::value_type, which is a typedef for std::pair<const K, V>. Consequently, in C++17 or higher, you can write

for (auto& [key, value]: myMap) {
    std::cout << key << " has value " << value << std::endl;

or as

for (const auto& [key, value]: myMap) {
    std::cout << key << " has value " << value << std::endl;

if you don't plan on modifying the values.

In C++11 and C++14, you can use enhanced for loops to extract out each pair on its own, then manually extract the keys and values:

for (const auto& kv : myMap) {
    std::cout << kv.first << " has value " << kv.second << std::endl;

You could also consider marking the kv variable const if you want a read-only view of the values.

Using Sockets to send and receive data

the easiest way to do this is to wrap your sockets in ObjectInput/OutputStreams and send serialized java objects. you can create classes which contain the relevant data, and then you don't need to worry about the nitty gritty details of handling binary protocols. just make sure that you flush your object streams after you write each object "message".

How do I set specific environment variables when debugging in Visual Studio?

If you can't use bat files to set up your environment, then your only likely option is to set up a system wide environment variable. You can find these by doing

  1. Right click "My Computer"
  2. Select properties
  3. Select the "advanced" tab
  4. Click the "environment variables" button
  5. In the "System variables" section, add the new environment variable that you desire
  6. "Ok" all the way out to accept your changes

I don't know if you'd have to restart visual studio, but seems unlikely. HTH

What is the default database path for MongoDB?

I have version 2.0.7 installed on Ubuntu and it defaulted to /var/lib/mongodb/ and that is also what was placed into my /etc/mongodb.conf file.

How do I check that multiple keys are in a dict in a single pass?

Using sets:

if set(("foo", "bar")).issubset(foo):
    #do stuff


if set(("foo", "bar")) <= set(foo):
    #do stuff

Get element of JS object with an index


------- or ----------


will get you 'B'

how to check the dtype of a column in python pandas

I know this is a bit of an old thread but with pandas 19.02, you can do:


How to return history of validation loss in Keras

Actually, you can also do it with the iteration method. Because sometimes we might need to use the iteration method instead of the built-in epochs method to visualize the training results after each iteration.

history = [] #Creating a empty list for holding the loss later
for iteration in range(1, 3):
    print('-' * 50)
    print('Iteration', iteration)
    result =, y, batch_size=128, nb_epoch=1) #Obtaining the loss after each training
    history.append(result.history['loss']) #Now append the loss after the training to the list.
    start_index = random.randint(0, len(text) - maxlen - 1)

This way allows you to get the loss you want while maintaining your iteration method.

How do I show a "Loading . . . please wait" message in Winforms for a long loading form?

You should create a background thread to to create and populate the form. This will allow your foreground thread to show the loading message.

Twitter Bootstrap alert message close and open again

All of the above solutions use external libraries, either angular or jQuery, and an old version of Bootstrap. So, here is Charles Wyke-Smith's solution in pure JavaScript, applied to Bootstrap 4. Yes, Bootstrap requires jQuery for its own modal and alerts code, but not everyone writes their own code with jQuery any more.

Here is the html of the alert:

<div id="myAlert" style="display: none;" 
    class="alert alert-success alert-dismissible fade show">
    <button type="button" class="close" data-hide="alert">&times;</button>
    <strong>Success!</strong> You did it!

Note that initially the alert is hidden (style="display: none;"), and instead of the standard data-dismiss="alert", we have here used data-hide="alert".

Here is the JavaScript to show the alert and override the close button:

var myAlert = document.getElementById('myAlert');
// Show the alert box = 'block';
// Override Bootstrap's standard close action
myAlert.querySelector('button[data-hide]').addEventListener('click', function() { = 'none';

If you wish to hide or show the alert programmatically elsewhere in the code, just do = 'none'; or = 'block';.

How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4

Here I'm basically wrapping a button in a link. The advantage is that you can post to different action methods in the same form.

<a href="Controller/ActionMethod">
    <input type="button" value="Click Me" />

Adding parameters:

<a href="Controller/ActionMethod?userName=ted">
    <input type="button" value="Click Me" />

Adding parameters from a non-enumerated Model:

<a href="Controller/[email protected]">
    <input type="button" value="Click Me" />

You can do the same for an enumerated Model too. You would just have to reference a single entity first. Happy Coding!

firestore: PERMISSION_DENIED: Missing or insufficient permissions

I also had the "Missing or insufficient permissions" error after specifying security rules. Turns out that the the rules are not recursive by default! i.e. if you wrote a rule like

match /users/{userId} {
  allow read, write: if request.auth != null && request.auth.uid == userId;

The rule will not apply to any subcollections under /users/{userId}. This was the reason for my error.

I fixed it by specifying the rule as:

match /users/{userId}/{document=**} {
  allow read, write: if request.auth != null && request.auth.uid == userId;

Read more at the relevant section of the documentation.

OnClick Send To Ajax

<textarea name='Status'> </textarea>
<input type='button' value='Status Update'>

You have few problems with your code like using . for concatenation

Try this -

$(function () {
    $('input').on('click', function () {
        var Status = $(this).val();
            url: 'Ajax/StatusUpdate.php',
            data: {
                text: $("textarea[name=Status]").val(),
                Status: Status
            dataType : 'json'

How to append elements into a dictionary in Swift?

If your dictionary is Int to String you can do simply:

dict[3] = "efg"

If you mean adding elements to the value of the dictionary a possible solution:

var dict = Dictionary<String, Array<Int>>()

dict["key"]! += [1]

How can I setup & run PhantomJS on Ubuntu?

For PhantomJS version above 1.5, consider this (verbatim copy of the build instructions on the phantom website):

For Ubuntu Linux (tested on a barebone install of Ubuntu 10.04 Lucid Lynx and Ubuntu 11.04 Natty Narwhal):

sudo apt-get install build-essential chrpath git-core libssl-dev libfontconfig1-dev
git clone git://
cd phantomjs
git checkout 1.7

Submit HTML form on self page

In 2013, with all the HTML5 stuff, you can just omit the 'action' attribute to self-submit a form


Actually, the Form Submission subsection of the current HTML5 draft does not allow action="" (empty attribute). It is against the specification.

From this other Stack Overflow answer.

How to read/write from/to file using Go?

New Way

Starting with Go 1.16, use os.ReadFile to load the file to memory, use os.WriteFile to write to a file from memory.

Be careful with the os.ReadFile because it reads the whole file into memory.

package main

import "os"

func main() {
    b, err := os.ReadFile("input.txt")
    if err != nil {

    // `data` contains everything your file does
    // This writes it to the Standard Out

    // You can also write it to a file as a whole
    err = os.WriteFile("destination.txt", b, 0644)
    if err != nil {

C program to check little vs. big endian

The following will do.

unsigned int x = 1;
printf ("%d", (int) (((char *)&x)[0]));

And setting &x to char * will enable you to access the individual bytes of the integer, and the ordering of bytes will depend on the endianness of the system.

Rounding float in Ruby

When displaying, you can use (for example)

>> '%.2f' % 2.3465
=> "2.35"

If you want to store it rounded, you can use

>> (2.3465*100).round / 100.0
=> 2.35

How do I convert a number to a numeric, comma-separated formatted string?

For SQL Server 2012, or later, an easier solution is to use FORMAT ()Documentation.

SELECT Format(1234567.8, '##,##0') 

Results in: 1,234,568

Proxy setting for R

On Windows 7 I solved this by going into my environment settings (try this link for how) and adding user variables http_proxy and https_proxy with my proxy details.

C++ - How to append a char to char*?

The function name does not reflect the semantic of the function. In fact you do not append a character. You create a new character array that contains the original array plus the given character. So if you indeed need a function that appends a character to a character array I would write it the following way

bool AppendCharToCharArray( char *array, size_t n, char c )
    size_t sz = std::strlen( array );

    if ( sz + 1 < n ) 
        array[sz] = c;
        array[sz + 1] = '\0';

    return ( sz + 1 < n );

If you need a function that will contain a copy of the original array plus the given character then it could look the following way

char * CharArrayPlusChar( const char *array, char c )
    size_t sz = std::strlen( array );
    char *s = new char[sz + 2];

    std::strcpy( s, array );
    s[sz] = c;
    s[sz + 1] = '\0';

    return ( s );

Import mysql DB with XAMPP in command LINE

I think the OP's problem was not escaping the slashes. on windows a path like: "c:\user\folderss\myscript.sql" should in the command line be written like either:




therefore "\u" from "c:\user" was interpreted as a command.

see: for more info

How to get current SIM card number in Android?

You have everything right, but the problem is with getLine1Number() function.

getLine1Number()- this method returns the phone number string for line 1, i.e the MSISDN for a GSM phone. Return null if it is unavailable.

this method works only for few cell phone but not all phones.

So, if you need to perform operations according to the sim(other than calling), then you should use getSimSerialNumber(). It is always unique, valid and it always exists.

Struct memory layout in C

You can start by reading the data structure alignment wikipedia article to get a better understanding of data alignment.

From the wikipedia article:

Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.

From 6.54.8 Structure-Packing Pragmas of the GCC documentation:

For compatibility with Microsoft Windows compilers, GCC supports a set of #pragma directives which change the maximum alignment of members of structures (other than zero-width bitfields), unions, and classes subsequently defined. The n value below always is required to be a small power of two and specifies the new alignment in bytes.

  1. #pragma pack(n) simply sets the new alignment.
  2. #pragma pack() sets the alignment to the one that was in effect when compilation started (see also command line option -fpack-struct[=] see Code Gen Options).
  3. #pragma pack(push[,n]) pushes the current alignment setting on an internal stack and then optionally sets the new alignment.
  4. #pragma pack(pop) restores the alignment setting to the one saved at the top of the internal stack (and removes that stack entry). Note that #pragma pack([n]) does not influence this internal stack; thus it is possible to have #pragma pack(push) followed by multiple #pragma pack(n) instances and finalized by a single #pragma pack(pop).

Some targets, e.g. i386 and powerpc, support the ms_struct #pragma which lays out a structure as the documented __attribute__ ((ms_struct)).

  1. #pragma ms_struct on turns on the layout for structures declared.
  2. #pragma ms_struct off turns off the layout for structures declared.
  3. #pragma ms_struct reset goes back to the default layout.

How to create a md5 hash of a string in C?

As other answers have mentioned, the following calls will compute the hash:

MD5Context md5;
MD5Update(&md5, data, datalen);
MD5Final(digest, &md5);

The purpose of splitting it up into that many functions is to let you stream large datasets.

For example, if you're hashing a 10GB file and it doesn't fit into ram, here's how you would go about doing it. You would read the file in smaller chunks and call MD5Update on them.

MD5Context md5;

fread(/* Read a block into data. */)
MD5Update(&md5, data, datalen);

fread(/* Read the next block into data. */)
MD5Update(&md5, data, datalen);

fread(/* Read the next block into data. */)
MD5Update(&md5, data, datalen);


//  Now finish to get the final hash value.
MD5Final(digest, &md5);

Can I call a constructor from another constructor (do constructor chaining) in C++?

If I understand your question correctly, you're asking if you can call multiple constructors in C++?

If that's what you're looking for, then no - that is not possible.

You certainly can have multiple constructors, each with unique argument signatures, and then call the one you want when you instantiate a new object.

You can even have one constructor with defaulted arguments on the end.

But you may not have multiple constructors, and then call each of them separately.

Using an IF Statement in a MySQL SELECT query

The IF/THEN/ELSE construct you are using is only valid in stored procedures and functions. Your query will need to be restructured because you can't use the IF() function to control the flow of the WHERE clause like this.

The IF() function that can be used in queries is primarily meant to be used in the SELECT portion of the query for selecting different data based on certain conditions, not so much to be used in the WHERE portion of the query:

SELECT IF(JQ.COURSE_ID=0, 'Some Result If True', 'Some Result If False'), OTHER_COLUMNS
FROM ...

Can I use wget to check , but not download

If you are in a directory where only root have access to write in system. Then you can directly use wget using a standard user account. So it will hit the url but because of having no write permission file won't be saved.. This method is working fine for me as i am using this method for a cronjob. Thanks.


postgreSQL - psql \i : how to execute script in a given path

Try this, I work myself to do so

\i 'somedir\\script2.sql'

Eclipse error: indirectly referenced from required .class files?

Since you give us very little details, most likely what you did, which is an incredibly easy mistake to make, is that instead of heading to

Build Path > Configure Build Path > Projects

and adding your additional project folder from there, instead you went to

Build Path > Configure Build Path > Libraries

and added your project folder from there instead.

This is most definitely the case if your code is all correct, but upon automatically reorganizing imports via the ctrl+space shortcut , instead of your import statements referring to com.your.additionalproject, your references all point to

Note the bin. Meaning that you -are- indirectly referring to your class by treating your other project folder structure as a library, making your IDE doing all the wokr of finding the exactly binary class you're referring to.

To correct this, remove the folder from the Libraries, and instead add it under the Projects tab, and reorganize your imports. Your project should work fine.

Initializing C# auto-properties

Update - the answer below was written before C# 6 came along. In C# 6 you can write:

public class Foo
    public string Bar { get; set; } = "bar";

You can also write read-only automatically-implemented properties, which are only writable in the constructor (but can also be given a default initial value):

public class Foo
    public string Bar { get; }

    public Foo(string bar)
        Bar = bar;

It's unfortunate that there's no way of doing this right now. You have to set the value in the constructor. (Using constructor chaining can help to avoid duplication.)

Automatically implemented properties are handy right now, but could certainly be nicer. I don't find myself wanting this sort of initialization as often as a read-only automatically implemented property which could only be set in the constructor and would be backed by a read-only field.

This hasn't happened up until and including C# 5, but is being planned for C# 6 - both in terms of allowing initialization at the point of declaration, and allowing for read-only automatically implemented properties to be initialized in a constructor body.

How to convert number to words in java

I think this may help you...programme is very simple and works fine

import java.util.*;

public class NumberToWord

    public void pw(int n, String ch)
        String one[] = {

        " ", " one", " two", " three", " four", " five", " six", " seven",
                " eight", " Nine", " ten", " eleven", " twelve", " thirteen",
                " fourteen", "fifteen", " sixteen", " seventeen", " eighteen",
                " nineteen" };
        String ten[] = { " ", " ", " twenty", " thirty", " forty", " fifty",
                " sixty", "seventy", " eighty", " ninety" };
        if (n > 19) {
            System.out.print(ten[n / 10] + " " + one[n % 10]);
        } else {
        if (n > 0)

    public static void main(String[] args)

        int n = 0;
        Scanner s = new Scanner(;
        System.out.print("Enter an integer number: ");
        n = s.nextInt();
        if (n <= 0)
            System.out.print("Enter numbers greater than 0");
            NumberToWord a = new NumberToWord();
            System.out.print("After conversion number in words is :");
   / 1000000000), " Hundred");
   / 10000000) % 100, " crore");
   / 100000) % 100), " lakh");
   / 1000) % 100), " thousand");
   / 100) % 10), " hundred");
   % 100), " ");

C# Copy a file to another location with a different name

StreamReader reader = new StreamReader(Oldfilepath);
string fileContent = reader.ReadToEnd();

StreamWriter writer = new StreamWriter(NewFilePath);

Run a PostgreSQL .sql file using command line arguments

You should do it like this:

\i path_to_sql_file


Enter image description here

Remove header and footer from window.print()

avoiding the top and bottom margin will solve your problem

@media print {
     @page {
        margin-left: 0.5in;
        margin-right: 0.5in;
        margin-top: 0;
        margin-bottom: 0;

Default values and initialization in Java

In the first code sample, a is a main method local variable. Method local variables need to be initialized before using them.

In the second code sample, a is class member variable, hence it will be initialized to the default value.

Get jQuery version from inspecting the jQuery object

FYI, for the cases where your page is loading with other javascript libraries like mootools that are conflicting with the $ symbol, you can use jQuery instead.

For instance, jQuery.fn.jquery or jQuery().jquery would work just fine:

screen shot for checking jQuery version

Error inflating when extending a class

In my case, I copied my class from somewhere else and didn't notice right away that it was an abstract class. You can't inflate abstract classes.

Importing JSON into an Eclipse project

Download the json jar from here. This will solve your problem.

See full command of running/stopped container in Docker

Moving Dylan's comment into a full-blown answer because TOO USEFUL:

docker run --rm -v /var/run/docker.sock:/var/run/docker.sock assaflavie/runlike YOUR-CONTAINER

What does it do? Runs inside a container, gets you the complete docker run command, then removes the container for you.

Multiple separate IF conditions in SQL Server

Maybe this is a bit redundant, but no one appeared to have mentioned this as a solution.

As a beginner in SQL I find that when using a BEGIN and END SSMS usually adds a squiggly line with incorrect syntax near 'END' to END, simply because there's no content in between yet. If you're just setting up BEGIN and END to get started and add the actual query later, then simply add a bogus PRINT statement so SSMS stops bothering you.

For example:

IF (1=1)

The following will indeed set you on the wrong track, thinking you made a syntax error which in this case just means you still need to add content in between BEGIN and END:

IF (1=1)

Programmatically generate video or animated GIF in Python?

I understand you asked about converting images to a gif; however, if the original format is MP4, you could use FFmpeg:

ffmpeg -i input.mp4 output.gif

'mvn' is not recognized as an internal or external command,

Make sure you have your maven bin directory in the path and the JAVA_HOME property set

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

I wrote an article of when to use an abstract class and when to use an interface. There is a lot more of a difference between them other than "one IS-A... and one CAN-DO...". To me, those are canned answers. I mention a few reasons when to use either of them. Hope it helps.

How to define a variable in a Dockerfile?

To my knowledge, only ENV allows that, as mentioned in "Environment replacement"

Environment variables (declared with the ENV statement) can also be used in certain instructions as variables to be interpreted by the Dockerfile.

They have to be environment variables in order to be redeclared in each new containers created for each line of the Dockerfile by docker build.

In other words, those variables aren't interpreted directly in a Dockerfile, but in a container created for a Dockerfile line, hence the use of environment variable.

This day, I use both ARG (docker 1.10+, and docker build --build-arg var=value) and ENV.
Using ARG alone means your variable is visible at build time, not at runtime.

My Dockerfile usually has:

ARG var
ENV var=${var}

In your case, ARG is enough: I use it typically for setting http_proxy variable, that docker build needs for accessing internet at build time.

How to change navbar/container width? Bootstrap 3

Container widths will drop down to 940 pixels for viewports less than 992 pixels. If you really don’t want containers larger than 940 pixels wide, then go to the Bootstrap customize page, and set @container-lg-desktop to either @container-desktop or hard-coded 940px.

Example: Communication between Activity and Service using Messaging

Seems to me you could've saved some memory by declaring your activity with "implements Handler.Callback"

How do I jump to a closing bracket in Visual Studio Code?

For those with a non-US keyboard:

File > Preferences > Keyboard Shortcuts. 
(Code > Preferences > Keyboard Shortcuts on Mac)

shows the current key bindings. See also here:

How to handle errors with boto3?

Following @armod's update about exceptions being added right on client objects. I'll show how you can see all exceptions defined for your client class.

Exceptions are generated dynamically when you create your client with session.create_client() or boto3.client(). Internally it calls method botocore.errorfactory.ClientExceptionsFactory._create_client_exceptions() and fills client.exceptions field with constructed exception classes.

All class names are available in client.exceptions._code_to_exception dictionary, so you can list all types with following snippet:

client = boto3.client('s3')

for ex_code in client.exceptions._code_to_exception:

Hope it helps.

How can I write data attributes using Angular?

Use attribute binding syntax instead

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    []="section.value">{{ section.text }}</li>  


<ol class="viewer-nav"><li *ngFor="let section of sections""{{section.value}}">{{ section.text }}</li>  

See also :

Python OpenCV2 (cv2) wrapper to get image size?

I'm afraid there is no "better" way to get this size, however it's not that much pain.

Of course your code should be safe for both binary/mono images as well as multi-channel ones, but the principal dimensions of the image always come first in the numpy array's shape. If you opt for readability, or don't want to bother typing this, you can wrap it up in a function, and give it a name you like, e.g. cv_size:

import numpy as np
import cv2

# ...

def cv_size(img):
    return tuple(img.shape[1::-1])

If you're on a terminal / ipython, you can also express it with a lambda:

>>> cv_size = lambda img: tuple(img.shape[1::-1])
>>> cv_size(img)
(640, 480)

Writing functions with def is not fun while working interactively.


Originally I thought that using [:2] was OK, but the numpy shape is (height, width[, depth]), and we need (width, height), as e.g. cv2.resize expects, so - we must use [1::-1]. Even less memorable than [:2]. And who remembers reverse slicing anyway?

Check if all values in list are greater than a certain number

You could do the following:

def Lists():

    my_list1 = [30,34,56]
    my_list2 = [29,500,43]

    for element in my_list1:
        print(element >= 30)

    for element in my_list2:
        print(element >= 30)


This will return the values that are greater than 30 as True, and the values that are smaller as false.

Fastest check if row exists in PostgreSQL

INSERT INTO target( userid, rightid, count )
  SELECT userid, rightid, count 
  FROM batch
    SELECT * FROM target t2, batch b2
    WHERE t2.userid = b2.userid
    -- ... other keyfields ...

BTW: if you want the whole batch to fail in case of a duplicate, then (given a primary key constraint)

INSERT INTO target( userid, rightid, count )
SELECT userid, rightid, count 
FROM batch

will do exactly what you want: either it succeeds, or it fails.

How to navigate through textfields (Next / Done Buttons)

 -(BOOL)textFieldShouldReturn:(UITextField *)textField
   [[self.view viewWithTag:textField.tag+1] becomeFirstResponder];
   return YES;

Return HTML content as a string, given URL. Javascript Function

you need to return when the readystate==4 e.g.

function httpGet(theUrl)
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
            return xmlhttp.responseText;
    }"GET", theUrl, false );

PHP function ssh2_connect is not working

For WHM Panel

Menu > Server Configuration > Terminal:

yum install libssh2-devel -y

Menu > Software > Module Installers

  1. PHP PECL Manage Click
  2. ssh2 Install Now Click

Menu > Restart Services > HTTP Server (Apache)

Are you sure you wish to restart this service?


ssh2_connect() Work!

How to allow http content within an iframe on a https site

You will always get warnings of blocked content in most browsers when trying to display non secure content on an https page. This is tricky if you want to embed stuff from other sites that aren't behind ssl. You can turn off the warnings or remove the blocking in your own browser but for other visitors it's a problem.

One way to do it is to load the content server side and save the images and other things to your server and display them from https.

You can also try using a service like and get the content through them. They have support for getting the content behind https.

What programming language does facebook use?

Facebook uses the LAMP stack, so if you want to get a career with them you're going to want to focus on that. In addition they often have C++ and/or Java listed in their requirements as well.

One of the postings includes the following requirements:

  • Expertise with C++ and/or Java
  • Knowledge of Perl or PHP or Python
  • Knowledge of relational databases and SQL, preferably MySQL and Oracle


  • Expertise in PHP, JavaScript, and CSS.


  • Knowledge of Perl or PHP or Python
  • Knowledge of relational databases and
  • SQL, preferably MySQL Knowledge of
  • web technologies: XHTML, JavaScript Experience with C, C++ a plus


Also, do any other social networking sites use the same language?

Some other companys that use PHP/LAMP Stack:

Passing variable number of arguments around

Variadic Functions can be dangerous. Here's a safer trick:

   void func(type* values) {
        while(*values) {
            x = *values++;
            /* do whatever with x */


OpenCV - DLL missing, but it's not?

Just copy the .dll files to C:\windows\system32\

Apache Name Virtual Host with SSL

Apache doesn't support SSL on name-based virtual host, only on IP based Virtual Hosts.

Source: Apache 2.2 SSL FAQ question Why is it not possible to use Name-Based Virtual Hosting to identify different SSL virtual hosts?

Unlike SSL, the TLS specification allows for name-based hosts (SNI as mentioned by someone else), but Apache doesn't yet support this feature. It supposedly will in a future release when compiled against openssl 0.9.8.

Also, mod_gnutls claims to support SNI, but I've never actually tried it.

How to decompile a whole Jar file?

Note: This solution only works for Mac and *nix users.

I also tried to find Jad with no luck. My quick solution was to download MacJad that contains jad. Once you downloaded it you can find jad in [where-you-downloaded-macjad]/MacJAD/Contents/Resources/jad.

Registering for Push Notifications in Xcode 8/Swift 3.0?

Heads up, you should be using the main thread for this action.

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
        if granted {
            DispatchQueue.main.async(execute: {

Flask example with POST

Before actually answering your question:

Parameters in a URL (e.g. key=listOfUsers/user1) are GET parameters and you shouldn't be using them for POST requests. A quick explanation of the difference between GET and POST can be found here.

In your case, to make use of REST principles, you should probably have:


Then, on each URL, you can define the behaviour of different HTTP methods (GET, POST, PUT, DELETE). For example, on /users/<user_id>, you want the following:

GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id> 

So, in your example, you want do a POST to /users/user_1 with the POST data being "John". Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.

Now, the answer to your question: Below is a basic semi-pseudocode of how you can achieve what I mentioned above:

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
    if request.method == 'GET':
        """return the information for <user_id>"""
    if request.method == 'POST':
        """modify/update the information for <user_id>"""
        # you can use <user_id>, which is a str but could
        # changed to be int or whatever you want, along
        # with your lxml knowledge to make the required
        # changes
        data = request.form # a multidict containing POST data
    if request.method == 'DELETE':
        """delete user with ID <user_id>"""
        # POST Error 405 Method Not Allowed

There are a lot of other things to consider like the POST request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.

Thanks and I hope this is helpful. Please do let me know if I have gotten something wrong.

Press Enter to move to next control

This may help:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
    // Detect the KeyEventArg's key enumerated constant.
    if (e.KeyCode == Keys.Enter)
        MessageBox.Show("You pressed enter! Good job!");

HTML text input allow only numeric input

If you want to suggest to the device (maybe a mobile phone) between alpha or numeric you can use <input type="number">.

How to insert a character in a string at a certain position?

In most use-cases, using a StringBuilder (as already answered) is a good way to do this. However, if performance matters, this may be a good alternative.

 * Insert the 'insert' String at the index 'position' into the 'target' String.
 * ````
 * insertAt("AC", 0, "") -> "AC"
 * insertAt("AC", 1, "xxx") -> "AxxxC"
 * insertAt("AB", 2, "C") -> "ABC
 * ````
public static String insertAt(final String target, final int position, final String insert) {
    final int targetLen = target.length();
    if (position < 0 || position > targetLen) {
        throw new IllegalArgumentException("position=" + position);
    if (insert.isEmpty()) {
        return target;
    if (position == 0) {
        return insert.concat(target);
    } else if (position == targetLen) {
        return target.concat(insert);
    final int insertLen = insert.length();
    final char[] buffer = new char[targetLen + insertLen];
    target.getChars(0, position, buffer, 0);
    insert.getChars(0, insertLen, buffer, position);
    target.getChars(position, targetLen, buffer, position + insertLen);
    return new String(buffer);

Convert int to char in java

It seems like you are looking for the Character.forDigit method:

final int RADIX = 10;
int i = 4;
char ch = Character.forDigit(i, RADIX);
System.out.println(ch); // Prints '4'

There is also a method that can convert from a char back to an int:

int i2 = Character.digit(ch, RADIX);
System.out.println(i2); // Prints '4'

Note that by changing the RADIX you can also support hexadecimal (radix 16) and any radix up to 36 (or Character.MAX_RADIX as it is also known as).

Insert auto increment primary key to existing table

suppose you don't have column for auto increment like id, no, then you can add using following query:


If you've column, then alter to auto increment using following query:

 ALTER TABLE table_name MODIFY column_name datatype(length) AUTO_INCREMENT PRIMARY KEY

Convert String to java.util.Date

You should set a TimeZone in your DateFormat, otherwise it will use the default one (depending on the settings of the computer).

Clearing input in vuejs form

Assuming that you have a form that is huge or simply you do not want to reset each form field one by one, you can reset all the fields of the form by iterating through the fields one by one

var self = this;
Object.keys(,index) {[key] = '';

The above will reset all fields of the given object to empty string. Let's say there are one or two fields that you selectively want to set to a specific value in that case inside the above block you can easily put a condition based on field name

if(key === "country")[key] = 'Canada';
else[key] = ''; 

Or if you want to reset the field based on type and you have boolean and other field types in that case

if(typeof[key] === "string")[key] = ''; 
else if (typeof[key] === "boolean")[key] = false; 

For more type info see here

A basic vuejs template and script sample would look as follow

    <form @submit.prevent="onSubmit">
      <input type="text" class="input" placeholder="User first name" v-model="data.form.firstName">
      <input type="text" class="input" placeholder="User last name" v-model="data.form.lastName">
      <input type="text" class="input" placeholder="User phone" v-model="">
      <input type="submit" class="button is-info" value="Add">
      <input type="button" class="button is-warning" @click="resetForm()" value="Reset Form">

See ow the @submit.prevent="onSubmit" is used in the form element. That would by default, prevent the form submission and call the onSubmit function.

Let's assume we have the following for the above

  export default {
    data() {
      return {
        data: {
          form: {
            firstName: '',
            lastName: '',
            phone: ''
    methods: {
      onSubmit: function() {
        console.log('Make API request.')
        this.resetForm(); //clear form automatically after successful request
      resetForm() {
        console.log('Reseting the form')
        var self = this; //you need this because *this* will refer to Object.keys below`

        //Iterate through each object field, key is name of the object field`
        Object.keys(,index) {
[key] = '';

You can call the resetForm from anywhere and it will reset your form fields.

Vue 'export default' vs 'new Vue'

When you declare:

new Vue({
    el: '#app',
    data () {
      return {}

That is typically your root Vue instance that the rest of the application descends from. This hangs off the root element declared in an html document, for example:

    <div id="app"></div>

The other syntax is declaring a component which can be registered and reused later. For example, if you create a single file component like:

// my-component.js
export default {
    name: 'my-component',
    data () {
      return {}

You can later import this and use it like:

// another-component.js
  import myComponent from 'my-component'
  export default {
    components: {
    data () {
      return {}

Also, be sure to declare your data properties as functions, otherwise they are not going to be reactive.

When to use std::size_t?

size_t is an unsigned type that can hold maximum integer value for your architecture, so it is protected from integer overflows due to sign (signed int 0x7FFFFFFF incremented by 1 will give you -1) or short size (unsigned short int 0xFFFF incremented by 1 will give you 0).

It is mainly used in array indexing/loops/address arithmetic and so on. Functions like memset() and alike accept size_t only, because theoretically you may have a block of memory of size 2^32-1 (on 32bit platform).

For such simple loops don't bother and use just int.

How to make a smooth image rotation in Android?

No matter what I tried, I couldn't get this to work right using code (and setRotation) for smooth rotation animation. What I ended up doing was making the degree changes so small, that the small pauses are unnoticeable. If you don't need to do too many rotations, the time to execute this loop is negligible. The effect is a smooth rotation:

        float lastDegree = 0.0f;
        float increment = 4.0f;
        long moveDuration = 10;
        for(int a = 0; a < 150; a++)
            rAnim = new RotateAnimation(lastDegree, (increment * (float)a),  Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            rAnim.setStartOffset(moveDuration * a);
            lastDegree = (increment * (float)a);
            ((AnimationSet) animation).addAnimation(rAnim);

Xcode 6 Bug: Unknown class in Interface Builder file

On me it happend because my project was called with "ä,ü,ö"

How to figure out the SMTP server host?

You can use the dig/host command to look up the MX records to see which mail server is handling mails for this domain.

On Linux you can do it as following for example:

$ host has address has address has address mail is handled by 10 mail is handled by 10 mail is handled by 10 mail is handled by 100 mail is handled by 10 mail is handled by 100

(as you can see, google has quite a lot of mail servers)

If you are working with windows, you might use nslookup (?) or try some web tool (e.g. that one) to display the same information.

Although that will only tell you the mail server for that domain. All other settings which are required can't be gathered that way. You might have to ask the provider.

Opening database file from within SQLite command-line shell

The same way you do it in other db system, you can use the name of the db for identifying double named tables. unique tablenames can used directly.

select * from ttt.table_name;

or if table name in all attached databases is unique

select * from my_unique_table_name;

But I think the of of sqlite-shell is only for manual lookup or manual data manipulation and therefor this way is more inconsequential

normally you would use sqlite-command-line in a script

IF...THEN...ELSE using XML

Faced with a similar problem sometime ago, I decided to go for a generalized "switch ... case ... break ... default" type solution together with an arm-style instruction set with conditional execution. A custom interpreter using a nesting stack was used to parse these "programs". This solution completely avoids id's or labels. All my XML language elements or "instructions" support a "condition" attribute which if not present or if it evaluates to true then the element's instruction is executed. If there is an "exit" attribute evaluating to true and the condition is also true, then the following group of elements/instructions at the same nesting level will neither be evaluated nor executed and the execution will continue with the next element/instruction at the parent level. If there is no "exit" or it evaluates to false, then the program will proceed with the next element/instruction. For example you can write this type of program (it will be useful to provide a noop "statement" and a mechanism/instruction to assign values and/or expressions to "variables" will prove very handy):

    <ins-11 condition="expr-a" exit="true">
        <ins-111 />
    <ins-12 condition="expr-b" exit="true" />
    <ins-13 condition="expr-c" />

If expr-a is true then the execution sequence will be:


if expr-a is false and expr-b is true then it will be:


If both expr-a and expr-b are false then we'll have:

ins-13 (only if expr-c evaluates to true)

PS. I used "exit" instead of "break" because I used "break" to implement "breakpoints". Such programs are very hard to debug without some kind of breakpointing/tracing mechanism.

PS2. Because I had similar date-time conditions as your example along with the other types of conditions, I also implemented two special attributes: "from" and "until", that also had to evaluate to true if present, just like "condition", and which used special fast date-time checking logic.

How to download a file from my server using SSH (using PuTTY on Windows)

If your server have a http service you can compress your directory and download the compressed file.


tar -zcvf archive-name.tar.gz -C directory-name .

Download throught your browser:


If you don't have direct access to the server ip, do a ssh tunnel throught putty, and forward the 80 port in some local port, and you can download the file.

Force flushing of output to a file while bash script is still running

Buffering of output depends on how your program /homedir/MyScript is implemented. If you find that output is getting buffered, you have to force it in your implementation. For example, use sys.stdout.flush() if it's a python program or use fflush(stdout) if it's a C program.

React native text going off my screen, refusing to wrap. What to do?

<SafeAreaView style={{flex:1}}>
        <View style={{alignItems:'center'}}>
            <Text style={{ textAlign:'center' }}>
                    This code will make your text centered even when there is a line-break

toBe(true) vs toBeTruthy() vs toBeTrue()

What I do when I wonder something like the question asked here is go to the source.


expect().toBe() is defined as:

function toBe() {
  return {
    compare: function(actual, expected) {
      return {
        pass: actual === expected

It performs its test with === which means that when used as expect(foo).toBe(true), it will pass only if foo actually has the value true. Truthy values won't make the test pass.


expect().toBeTruthy() is defined as:

function toBeTruthy() {
  return {
    compare: function(actual) {
      return {
        pass: !!actual

Type coercion

A value is truthy if the coercion of this value to a boolean yields the value true. The operation !! tests for truthiness by coercing the value passed to expect to a boolean. Note that contrarily to what the currently accepted answer implies, == true is not a correct test for truthiness. You'll get funny things like

> "hello" == true
> "" == true
> [] == true
> [1, 2, 3] == true

Whereas using !! yields:

> !!"hello"
> !!""
> !![1, 2, 3]
> !![] 

(Yes, empty or not, an array is truthy.)


expect().toBeTrue() is part of Jasmine-Matchers (which is registered on npm as jasmine-expect after a later project registered jasmine-matchers first).

expect().toBeTrue() is defined as:

function toBeTrue(actual) {
  return actual === true ||
    is(actual, 'Boolean') &&

The difference with expect().toBeTrue() and expect().toBe(true) is that expect().toBeTrue() tests whether it is dealing with a Boolean object. expect(new Boolean(true)).toBe(true) would fail whereas expect(new Boolean(true)).toBeTrue() would pass. This is because of this funny thing:

> new Boolean(true) === true
> new Boolean(true) === false

At least it is truthy:

> !!new Boolean(true)

Which is best suited for use with elem.isDisplayed()?

Ultimately Protractor hands off this request to Selenium. The documentation states that the value produced by .isDisplayed() is a promise that resolves to a boolean. I would take it at face value and use .toBeTrue() or .toBe(true). If I found a case where the implementation returns truthy/falsy values, I would file a bug report.

Proper use cases for Android UserManager.isUserAGoat()?

Complementing the @djechlin answer (good answer by the way!), this function call could be also used as dummy code to hold a breakpoint in an IDE when you want to stop in some specific iteration or a particular recursive call, for example:

enter image description here

isUserAGoat() could be used instead of a dummy variable declaration that will be shown in the IDE as a warning and, in Eclipse particular case, will clog the breakpoint mark, making it difficult to enable/disable it. If the method is used as a convention, all the invocations could be later filtered by some script (during commit phase maybe?).

enter image description here

Google guys are heavy Eclipse users (they provide several of their projects as Eclipse plugins: Android SDK, GAE, etc), so the @djechlin answer and this complementary answer make a lot of sense (at least for me).

Django error - matching query does not exist

Maybe you have no Comments record with such primary key, then you should use this code:

    comment = Comment.objects.get(pk=comment_id)
except Comment.DoesNotExist:
    comment = None

SQL Insert Query Using C#

private void button1_Click(object sender, EventArgs e)
        String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (@txtitemid,@txtitemname,@txtitemdesc,@txtitemqty)";
            using (SqlCommand command = new SqlCommand(query, con))

                command.Parameters.AddWithValue("@txtitemid", txtitemid.Text);
                command.Parameters.AddWithValue("@txtitemname", txtitemname.Text);
                command.Parameters.AddWithValue("@txtitemdesc", txtitemdesc.Text);
                command.Parameters.AddWithValue("@txtitemqty", txtitemqty.Text);

                int result = command.ExecuteNonQuery();

                // Check Error
                if (result < 0)

                MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        catch (Exception ex)

In git how is fetch different than pull and how is merge different than rebase?

fetch vs pull

fetch will download any changes from the remote* branch, updating your repository data, but leaving your local* branch unchanged.

pull will perform a fetch and additionally merge the changes into your local branch.

What's the difference? pull updates you local branch with changes from the pulled branch. A fetch does not advance your local branch.

merge vs rebase

Given the following history:

          C---D---E local
    A---B---F---G remote

merge joins two development histories together. It does this by replaying the changes that occurred on your local branch after it diverged on top of the remote branch, and record the result in a new commit. This operation preserves the ancestry of each commit.

The effect of a merge will be:

          C---D---E local
         /         \
    A---B---F---G---H remote

rebase will take commits that exist in your local branch and re-apply them on top of the remote branch. This operation re-writes the ancestors of your local commits.

The effect of a rebase will be:

                  C'--D'--E' local
    A---B---F---G remote

What's the difference? A merge does not change the ancestry of commits. A rebase rewrites the ancestry of your local commits.

* This explanation assumes that the current branch is a local branch, and that the branch specified as the argument to fetch, pull, merge, or rebase is a remote branch. This is the usual case. pull, for example, will download any changes from the specified branch, update your repository and merge the changes into the current branch.

Bootstrap Collapse not Collapsing

I had this problem and the problem was bootstrap.js wasn't load in Yii2 framework.First check is jquery loaded in inspect and then check bootstrap.js is loaded?If you used any tooltip Popper.js is needed before bootsrap.js.

Merging dictionaries in C#

I know this is an old question, but since we now have LINQ you can do it in a single line like this

Dictionary<T1,T2> merged;
Dictionary<T1,T2> mergee;
mergee.ToList().ForEach(kvp => merged.Add(kvp.Key, kvp.Value));


mergee.ToList().ForEach(kvp => merged.Append(kvp));

String replacement in Objective-C

It also posible string replacement with stringByReplacingCharactersInRange:withString:

for (int i = 0; i < card.length - 4; i++) {

    if (![[card substringWithRange:NSMakeRange(i, 1)] isEqual:@" "]) {

        NSRange range = NSMakeRange(i, 1);
        card = [card stringByReplacingCharactersInRange:range withString:@"*"];


} //out: **** **** **** 1234

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

  1. I had the same problem, and I used the UTF-8 coding for both of my files as follows:

    add @charset "UTF-8"; in CSS file and <meta charset="UTF-8"> under <head> tag in HTML file. and it worked for me.

    it makes the same encoding for both the files i.e HTML and CSS.

    You can also do the same for "UTF-16" encoding.

  2. If it is still not working check for the <link type="text/css" rel="stylesheet" href="style.css"/> under <head> tag in HTML File where you should mention type="text/css"

How to terminate a process in vbscript

Dim shll : Set shll = CreateObject("WScript.Shell")
Set Rt = shll.Exec("Notepad") : wscript.sleep 4000 : Rt.Terminate

Run the process with .Exec.

Then wait for 4 seconds.

After that kill this process.

What does ':' (colon) do in JavaScript?

You guys are forgetting that the colon is also used in the ternary operator (though I don't know if jquery uses it for this purpose).

the ternary operator is an expression form (expressions return a value) of an if/then statement. it's used like this:

var result = (condition) ? (value1) : (value2) ;

A ternary operator could also be used to produce side effects just like if/then, but this is profoundly bad practice.

How to get the employees with their managers

Perhaps your subquery (SELECT ename FROM EMP WHERE empno = mgr) thinks, give me the employee records that are their own managers! (i.e., where the empno of a row is the same as the mgr of the same row.)

have you considered perhaps rewriting this to use an inner (self) join? (I'm asking, becuase i'm not even sure if the following will work or not.)

SELECT t1.ename, t1.empno, t2.ename as MANAGER, t1.mgr
from emp as t1
inner join emp t2 ON t1.mgr = t2.empno
order by t1.empno;

Spring Boot @Value Properties

I´d like to mention, that I used spring boot version 1.4.0 and since this version you can only write:

public class MongoConnection {

private String mongoHost;

private int mongoPort;

private String mongoDB;

Then inject class whenever you want.


From nowadays I would use @ConfigurationProperties because you are able to inject property values in your POJOs. Keep hierarchical sort above your properties. Moreover, you can put validations above POJOs attributes and so on. Take a look at the link

Remove All Event Listeners of Specific Type

You cant remove a single event, but all? at once? just do

document.body.innerHTML = document.body.innerHTML

Usage of the backtick character (`) in JavaScript

Backticks enclose template literals, previously known as template strings. Template literals are string literals that allow embedded expressions and string interpolation features.

Template literals have expressions embedded in placeholders, denoted by the dollar sign and curly brackets around an expression, i.e. ${expression}. The placeholder / expressions get passed to a function. The default function just concatenates the string.

To escape a backtick, put a backslash before it:

`\`` === '`'; => true

Use backticks to more easily write multi-line string:

console.log(`string text line 1
string text line 2`);


console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);

vs. vanilla JavaScript:

console.log('string text line 1\n' +
'string text line 2');


console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');

Escape sequences:

  • Unicode escapes started by \u, for example \u00A9
  • Unicode code point escapes indicated by \u{}, for example \u{2F804}
  • Hexadecimal escapes started by \x, for example \xA9
  • Octal literal escapes started by \ and (a) digit(s), for example \251

How to scroll to an element inside a div?

You need to get the top offset of the element you'd like to scroll into view, relative to its parent (the scrolling div container):

var myElement = document.getElementById('element_within_div');
var topPos = myElement.offsetTop;

The variable topPos is now set to the distance between the top of the scrolling div and the element you wish to have visible (in pixels).

Now we tell the div to scroll to that position using scrollTop:

document.getElementById('scrolling_div').scrollTop = topPos;

If you're using the prototype JS framework, you'd do the same thing like this:

var posArray = $('element_within_div').positionedOffset();
$('scrolling_div').scrollTop = posArray[1];

Again, this will scroll the div so that the element you wish to see is exactly at the top (or if that's not possible, scrolled as far down as it can so it's visible).

How to place and center text in an SVG rectangle

If you are creating the SVG programmatically you can simplify it and do something like this:

      <rect x={x} y={y} width={width} height={height} />
          x={x + width / 2}
          y={y + height / 2}

What is the question mark for in a Typescript parameter name

The ? in the parameters is to denote an optional parameter. The Typescript compiler does not require this parameter to be filled in. See the code example below for more details:

// baz: number | undefined means: the second argument baz can be a number or undefined

// = undefined, is default parameter syntax, 
// if the parameter is not filled in it will default to undefined

// Although default JS behaviour is to set every non filled in argument to undefined 
// we need this default argument so that the typescript compiler
// doesn't require the second argument to be filled in
function fn1 (bar: string, baz: number | undefined = undefined) {
    // do stuff

// All the above code can be simplified using the ? operator after the parameter
// In other words fn1 and fn2 are equivalent in behaviour
function fn2 (bar: string, baz?: number) {
    // do stuff

fn2('foo', 3); // works
fn2('foo'); // works

// Compile time error: Expected 1-2 arguments, but got 0
// An argument for 'bar' was not provided.

fn1('foo', 3); // works
fn1('foo'); // works

// Compile time error: Expected 1-2 arguments, but got 0
// An argument for 'bar' was not provided.

How to get the current branch name in Git?

if you run in Jenkins, you can use GIT_BRANCH variable as appears here:

The git plugin sets several environment variables you can use in your scripts:

GIT_COMMIT - SHA of the current

GIT_BRANCH - Name of the branch currently being used, e.g. "master" or "origin/foo"

GIT_PREVIOUS_COMMIT - SHA of the previous built commit from the same branch (the current SHA on first build in branch)

GIT_URL - Repository remote URL

GIT_URL_N - Repository remote URLs when there are more than 1 remotes, e.g. GIT_URL_1, GIT_URL_2

GIT_AUTHOR_EMAIL - Committer/Author Email

GIT_COMMITTER_EMAIL - Committer/Author Email

Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave

If you have issues with the xcode-select --install command; e.g. I kept getting a network problem timeout, then try downloading the dmg at (Command line tools OS X 10.11) for Xcode 7.1

Adding to the classpath on OSX

If you want to make a certain set of JAR files (or .class files) available to every Java application on the machine, then your best bet is to add those files to /Library/Java/Extensions.

Or, if you want to do it for every Java application, but only when your Mac OS X account runs them, then use ~/Library/Java/Extensions instead.

EDIT: If you want to do this only for a particular application, as Thorbjørn asked, then you will need to tell us more about how the application is packaged.

Set bootstrap modal body height by percentage

This should work for everyone, any screen resolutions:

.modal-body {
    max-height: calc(100vh - 143px);
    overflow-y: auto; }

First, count your modal header and footer height, in my case I have H4 heading so I have them on 141px, already counted default modal margin in 20px(top+bottom).

So that subtract 141px is the max-height for my modal height, for the better result there are both border top and bottom by 1px, for this, 143px will work perfectly.

In some case of styling you may like to use overflow-y: auto; instead of overflow-y: scroll;, try it.

Try it, and you get the best result in both computer or mobile devices. If you have a heading larger than H4, recount it see how much px you would like to subtract.

If you don't know what I am telling, just change the number of 143px, see what is the best result for your case.

Last, I'd suggest have it an inline CSS.

Detect application heap size in Android

This returns max heap size in bytes:


I was using ActivityManager.getMemoryClass() but on CyanogenMod 7 (I didn't test it elsewhere) it returns wrong value if the user sets heap size manually.

NUnit Unit tests not showing in Test Explorer with Test Adapter installed

I started a new solution with a test project in it, and compared it against my original, problem project. The original, for some reason, had an app.config in it. I excluded that file from the project and saw my tests reappear in the test explorer.

Docker error: invalid reference format: repository name must be lowercase

In my case was the -e before the parameters for mysql docker

docker run --name mysql-standalone -e MYSQL_ROOT_PASSWORD=hello -e MYSQL_DATABASE=hello -e MYSQL_USER=hello -e MYSQL_PASSWORD=hello -d mysql:5.6

Check also if there are missing whitespaces

how to create and call scalar function in sql server 2008

Your Call works if it were a Table Valued Function. Since its a scalar function, you need to call it like:

SELECT dbo.fn_HomePageSlider(9, 3025) AS MyResult

cancelling a handler.postdelayed process

I do this to post a delayed runnable:

myHandler.postDelayed(myRunnable, SPLASH_DISPLAY_LENGTH); 

And this to remove it: myHandler.removeCallbacks(myRunnable);

Returning a pointer to a vector element in c++

Return the address of the thing pointed to by the iterator:


Edit: To clear up some confusion:

vector <int> vec;          // a global vector of ints

void f() {
   vec.push_back( 1 );    // add to the global vector
   vector <int>::iterator it = vec.begin();
   * it = 2;              // change what was 1 to 2
   int * p = &(*it);      // get pointer to first element
   * p = 3;               // change what was 2 to 3

No need for vectors of pointers or dynamic allocation.

ClientAbortException: Connection reset by peer: socket write error

Your log indicates ClientAbortException, which occurs when your HTTP client drops the connection with the server and this happened before server could close the server socket Connection.

How to print HTML content on click of a button, but not the page?

@media print {
print me
<h1 class="noPrint">
no print
<button onclick="window.print();" class="noPrint">
Print Me

I came across another elegant solution for this:

Place your printable part inside a div with an id like this:

<div id="printableArea">
      <h1>Print me</h1>

<input type="button" onclick="printDiv('printableArea')" value="print a div!" />

Now let's create a really simple javascript:

function printDiv(divName) {
     var printContents = document.getElementById(divName).innerHTML;
     var originalContents = document.body.innerHTML;

     document.body.innerHTML = printContents;


     document.body.innerHTML = originalContents;

SOURCE : SO Answer

Recommended add-ons/plugins for Microsoft Visual Studio

A lot of the mentioned Addins are used by me on a regular basis. Here are just a few I I estimate, too:

All three are free and highly recommended (by me).

How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?


 <script type="text/javascript">


<select id="gender" selected="selected">
    <option value="1">Male</option>
    <option value="2">Female</option>

Click Here More Details

Not Equal to This OR That in Lua

x ~= 0 or 1 is the same as ((x ~= 0) or 1)

x ~=(0 or 1) is the same as (x ~= 0).

try something like this instead.

function isNot0Or1(x)
    return (x ~= 0 and x ~= 1)

print( isNot0Or1(-1) == true )
print( isNot0Or1(0) == false )
print( isNot0Or1(1) == false )

Pass a reference to DOM object with ng-click

While you do the following, technically speaking:

<button ng-click="doSomething($event)"></button>
// In controller:
$scope.doSomething = function($event) {
  //reference to the button that triggered the function:

This is probably something you don't want to do as AngularJS philosophy is to focus on model manipulation and let AngularJS do the rendering (based on hints from the declarative UI). Manipulating DOM elements and attributes from a controller is a big no-no in AngularJS world.

You might check this answer for more info:

Fast Linux file count for a large number of files

The fastest way on Linux (the question is tagged as Linux), is to use a direct system call. Here's a little program that counts files (only, no directories) in a directory. You can count millions of files and it is around 2.5 times faster than "ls -f" and around 1.3-1.5 times faster than Christopher Schultz's answer.

#define _GNU_SOURCE
#include <dirent.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/syscall.h>

#define BUF_SIZE 4096

struct linux_dirent {
    long d_ino;
    off_t d_off;
    unsigned short d_reclen;
    char d_name[];

int countDir(char *dir) {

    int fd, nread, bpos, numFiles = 0;
    char d_type, buf[BUF_SIZE];
    struct linux_dirent *dirEntry;

    fd = open(dir, O_RDONLY | O_DIRECTORY);
    if (fd == -1) {
        puts("open directory error");
    while (1) {
        nread = syscall(SYS_getdents, fd, buf, BUF_SIZE);
        if (nread == -1) {
            puts("getdents error");
        if (nread == 0) {

        for (bpos = 0; bpos < nread;) {
            dirEntry = (struct linux_dirent *) (buf + bpos);
            d_type = *(buf + bpos + dirEntry->d_reclen - 1);
            if (d_type == DT_REG) {
                // Increase counter
            bpos += dirEntry->d_reclen;

    return numFiles;

int main(int argc, char **argv) {

    if (argc != 2) {
        puts("Pass directory as parameter");
        return 2;
    printf("Number of files in %s: %d\n", argv[1], countDir(argv[1]));
    return 0;

PS: It is not recursive, but you could modify it to achieve that.

Javascript, Time and Date: Getting the current minute, hour, day, week, month, year of a given millisecond time

Here is another method to get date

new Date().getDate()          // Get the day as a number (1-31)
new Date().getDay()           // Get the weekday as a number (0-6)
new Date().getFullYear()      // Get the four digit year (yyyy)
new Date().getHours()         // Get the hour (0-23)
new Date().getMilliseconds()  // Get the milliseconds (0-999)
new Date().getMinutes()       // Get the minutes (0-59)
new Date().getMonth()         // Get the month (0-11)
new Date().getSeconds()       // Get the seconds (0-59)
new Date().getTime()          // Get the time (milliseconds since January 1, 1970)

How to load Spring Application Context

I am using in the way and it is working for me.

public static void main(String[] args) {
    new CarpoolDBAppTest();


public CarpoolDBAppTest(){
    ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
    Student stud = (Student) context.getBean("yourBeanId");

Here Student is my classm you will get the class matching yourBeanId.

Now work on that object with whatever operation you want to do.

How to run or debug php on Visual Studio Code (VSCode)

Debugging PHP with VSCode using the vscode-php-debug extension

VSCode can now support debugging PHP projects through the marketplace extension vscode-php-debug.

This extension uses XDebug in the background, and allows you to use breakpoints, watches, stack traces and the like:

Screenshot: PHP Debugging in VSCode using vscode-php-debug extension

Installation is straightforward from within VSCode: Summon the command line with F1 and then type ext install php-debug

How to render a DateTime object in a Twig template

You can use date filter:

{{ game.gameDate|date("m/d/Y") }}

Unable to Git-push master to Github - 'origin' does not appear to be a git repository / permission denied

One possibility that the above answers don't address is that you may not have an ssh access from your shell. That is, you may be in a network (some college networks do this) where ssh service is blocked.In that case you will not only be able to get github services but also any other ssh services. You can test if this is the problem by trying to use any other ssh service.This was the case with me.

Get remote registry value

If you need user's SID and browse remote HKEY_USERS folder, you can follow this script :

<# Replace following with yours and userAccountName with remote username #>
$userLogin = New-Object System.Security.Principal.NTAccount(““,”userAccountName“)
$userSID = $userLogin.Translate([System.Security.Principal.SecurityIdentifier])

<# We will open HKEY_USERS and with accurate user’s SID from remoteComputer #>
$remoteRegistry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(‘Users’,”remoteComputer“)

<# We will then retrieve LocalName value from Control Panel / International subkeys #>

$key = $userSID.value+”\Control Panel\International”
$openKey = $remoteRegistry.OpenSubKey($key)

<# We can now retrieve any values #>

$localName = $openKey.GetValue(‘LocaleName’)

Source :

how to increase sqlplus column output length?

On Linux try these:

set wrap off
set trimout ON
set trimspool on
set serveroutput on
set pagesize 0
set long 20000000
set longchunksize 20000000
set linesize 4000

CSS3 Spin Animation

To use CSS3 Animation you must also define the actual animation keyframes (which you named spin)

Read for more info

Once you've configured the animation's timing, you need to define the appearance of the animation. This is done by establishing two or more keyframes using the @keyframes at-rule. Each keyframe describes how the animated element should render at a given time during the animation sequence.

Demo at

@-moz-keyframes spin {
    from { -moz-transform: rotate(0deg); }
    to { -moz-transform: rotate(360deg); }
@-webkit-keyframes spin {
    from { -webkit-transform: rotate(0deg); }
    to { -webkit-transform: rotate(360deg); }
@keyframes spin {
    from {transform:rotate(0deg);}
    to {transform:rotate(360deg);}

Cannot find the declaration of element 'beans'

This error of Cannot find the declaration of element 'beans' but for a whole different reason

It turs out my internet connection was not very reliable, so i decided to check first for this url

Once I saw that the xsd was open succesfully I clean the Eclipse(IDE) project and the error was gone

If you try this steps and still get the error then check the Spring version so that it matches as mentioned by another answer

<beans xmlns="" 

Replace [MAYOR.MINOR] on the last line with whatever major.minor Spring version that you are using

For Spring 4.0

For Sprint 3.1 spring-beans-3.1.xsd

All the contexts are available here

SQLSTATE[42S22]: Column not found: 1054 Unknown column - Laravel

You don't have a field named user_email in the members table ... as for why, I'm not sure as the code "looks" like it should try to join on different fields

Does the Auth::attempt method perform a join of the schema? Run grep -Rl 'class Auth' /path/to/framework and find where the attempt method is and what it does.

React-Router: No Not Found Route?

In newer versions of react-router you want to wrap the routes in a Switch which only renders the first matched component. Otherwise you would see multiple components rendered.

For example:

import React from 'react';
import ReactDOM from 'react-dom';
import {
  BrowserRouter as Router,
} from 'react-router-dom';

import App from './app/App';
import Welcome from './app/Welcome';
import NotFound from './app/NotFound';

const Root = () => (
  <Router history={browserHistory}>
      <Route exact path="/" component={App}/>
      <Route path="/welcome" component={Welcome}/>
      <Route component={NotFound}/>


Google maps API V3 - multiple markers on exact same spot

@Ignatius most excellent answer, updated to work with v2.0.7 of MarkerClustererPlus.

  1. Add a prototype click method in the MarkerClusterer class, like so - we will override this later in the map initialize() function:

    // BEGIN MODIFICATION (around line 715)
    MarkerClusterer.prototype.onClick = function() { 
        return true; 
  2. In the ClusterIcon class, add the following code AFTER the click/clusterclick trigger:

    // EXISTING CODE (around line 143)
    google.maps.event.trigger(mc, "click", cClusterIcon.cluster_);
    google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name
    var zoom = mc.getMap().getZoom();
    // Trying to pull this dynamically made the more zoomed in clusters not render
    // when then kind of made this useless. -NNC @ BNB
    // var maxZoom = mc.getMaxZoom();
    var maxZoom = 15;
    // if we have reached the maxZoom and there is more than 1 marker in this cluster
    // use our onClick method to popup a list of options
    if (zoom >= maxZoom && cClusterIcon.cluster_.markers_.length > 1) {
        return mc.onClick(cClusterIcon);
  3. Then, in your initialize() function where you initialize the map and declare your MarkerClusterer object:

    markerCluster = new MarkerClusterer(map, markers);
    // onClick OVERRIDE
    markerCluster.onClick = function(clickedClusterIcon) { 
      return multiChoice(clickedClusterIcon.cluster_); 

    Where multiChoice() is YOUR (yet to be written) function to popup an InfoWindow with a list of options to select from. Note that the markerClusterer object is passed to your function, because you will need this to determine how many markers there are in that cluster. For example:

    function multiChoice(clickedCluster) {
      if (clickedCluster.getMarkers().length > 1)
        // var markers = clickedCluster.getMarkers();
        // do something creative!
        return false;
      return true;

How to export html table to excel using javascript

Only works in Mozilla, Chrome and Safari..

$(function() {
  $('button').click(function() {
    var url = 'data:application/,' + encodeURIComponent($('#tableWrap').html())
    location.href = url
    return false
<script src=""></script>

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

How to print a list with integers without the brackets, commas and no quotes?

Something like this should do it:

for element in list_:

How to implement the Java comparable interface?

Implement Comparable<Animal> interface in your class and provide implementation of int compareTo(Animal other) method in your class.See This Post

How to get rid of the "No bootable medium found!" error in Virtual Box?

Follow the steps below:

1) Select your VM Instance. Go to Settings->Storage

2) Under the storage tree select the default image or "Empty"(which ever is present)

3) Under the attributes frame, click on the CD image and select "Choose a virtual CD/DVD disk file"

4) Browse and select the image file(iso or what ever format) from the system

5) Select OK.

Abishek's solution is correct. But the highlighted area in 2nd image could be misleading.

Calling a javascript function recursively

Using Named Function Expressions:

You can give a function expression a name that is actually private and is only visible from inside of the function ifself:

var factorial = function myself (n) {
    if (n <= 1) {
        return 1;
    return n * myself(n-1);
typeof myself === 'undefined'

Here myself is visible only inside of the function itself.

You can use this private name to call the function recursively.

See 13. Function Definition of the ECMAScript 5 spec:

The Identifier in a FunctionExpression can be referenced from inside the FunctionExpression's FunctionBody to allow the function to call itself recursively. However, unlike in a FunctionDeclaration, the Identifier in a FunctionExpression cannot be referenced from and does not affect the scope enclosing the FunctionExpression.

Please note that Internet Explorer up to version 8 doesn't behave correctly as the name is actually visible in the enclosing variable environment, and it references a duplicate of the actual function (see patrick dw's comment below).

Using arguments.callee:

Alternatively you could use arguments.callee to refer to the current function:

var factorial = function (n) {
    if (n <= 1) {
        return 1;
    return n * arguments.callee(n-1);

The 5th edition of ECMAScript forbids use of arguments.callee() in strict mode, however:

(From MDN): In normal code arguments.callee refers to the enclosing function. This use case is weak: simply name the enclosing function! Moreover, arguments.callee substantially hinders optimizations like inlining functions, because it must be made possible to provide a reference to the un-inlined function if arguments.callee is accessed. arguments.callee for strict mode functions is a non-deletable property which throws when set or retrieved.

Capturing mobile phone traffic on Wireshark

Another option which has not been suggested here is to run the app you want to monitor in the Android emulator from the Android SDK. You can then easily capture the traffic with wireshark on the same machine.

This was the easiest option for me.

Fix columns in horizontal scrolling

Solved using JavaScript + jQuery! I just need similar solution to my project but current solution with HTML and CSS is not ok for me because there is issue with column height + I need more then one column to be fixed. So I create simple javascript solution using jQuery

You can try it here

All you need is setup home many columsn will be fixed in data-count-fixed-columns parameter

<table class="table" data-count-fixed-columns="2" cellpadding="0" cellspacing="0">

and run js function


JavaScript Extending Class

For traditional extending you can simply write superclass as constructor function, and then apply this constructor for your inherited class.

     function AbstractClass() {
      this.superclass_method = function(message) {
          // do something

     function Child() {
         // Now Child will have superclass_method()

Example on angularjs:

    this._constructor = function() {
      this.scream = function(message) {
          message = message + " by " + this.get_mouth();

      this.get_mouth = function(){
        return 'abstract mouth';
  ['noisyThing', function(noisyThing){
    this.meow = function() {
    this.get_mouth = function(){
      return 'fluffy mouth';
  ['noisyThing', function(noisyThing){
    this.twit = function() {

can't access mysql from command line mac

I'm using OS X 10.10, open the shell, type

export PATH=$PATH:/usr/local/mysql/bin

it works temporary.if you use Command+T to open a new tab ,mysql command will not work anymore.

We need to create a .bash_profile file to make it work each time you open a new tab.

nano ~/.bash_profile

add the following line to the file.

# Set architecture flags
export ARCHFLAGS="-arch x86_64"
# Ensure user-installed binaries take precedence
export PATH=/usr/local/mysql/bin:$PATH
# Load .bashrc if it exists
test -f ~/.bashrc && source ~/.bashrc

Save the file, then open a new shell tab, it works like a charm..

by the way, why not try

pip install -U mycli

it's a tool way better than the mysqlcli.. A command line client for MySQL that can do auto-completion and syntax highlighting

How to open a txt file and read numbers in Java

Read file, parse each line into an integer and store into a list:

List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;

try {
    reader = new BufferedReader(new FileReader(file));
    String text = null;

    while ((text = reader.readLine()) != null) {
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
    try {
        if (reader != null) {
    } catch (IOException e) {

//print out the list

Remove URL parameters without refreshing page

In jquery use <

window.location.href =  window.location.href.split("?")[0]

How to sort a file in-place

To sort file in place, try:

echo "$(sort your_file)" > your_file

As explained in other answers, you cannot directly redirect the output back to the input file. But you can evaluate the sort command first and then redirect it back to the original file. In this way you can implement in-place sort.

Similarly, you can also apply this trick to other command like paste to implement row-wise appending.

How to get the version of ionic framework?

ionic -v

Ionic CLI update available: 5.2.4 ? 5.2.5
Run npm i -g ionic to update

find: missing argument to -exec

For anyone else having issues when using GNU find binary in a Windows command prompt. The semicolon needs to be escaped with ^

find.exe . -name "*.rm" -exec ffmpeg -i {} -sameq {}.mp3 ^;

How can I retrieve Id of inserted entity using Entity framework?

All answers are very well suited for their own scenarios, what i did different is that i assigned the int PK directly from object (TEntity) that Add() returned to an int variable like this;

using (Entities entities = new Entities())
      int employeeId = entities.Employee.Add(new Employee
                            EmployeeName = employeeComplexModel.EmployeeName,
                            EmployeeCreatedDate = DateTime.Now,
                            EmployeeUpdatedDate = DateTime.Now,
                            EmployeeStatus = true

      //...use id for other work

so instead of creating an entire new object, you just take what you want :)

EDIT For Mr. @GertArnold :

enter image description here

How to add composite primary key to table

The ALTER TABLE statement presented by Chris should work, but first you need to declare the columns NOT NULL. All parts of a primary key need to be NOT NULL.

How To Remove Outline Border From Input Button

To avoid the problem caused when you change the outline property on a focus, is tho give a visual effect when the user Tab on the input button or click on it.

In this case is a submit type, but you can apply to a type="button" too.

input[type="submit"]:focus {_x000D_
    outline: none !important;_x000D_
    background-color: rgb(208, 192, 74);_x000D_

Android selector & text color

In order to make it work on selection in a list view use the following code:

<selector xmlns:android="">
    <item android:state_pressed="true" android:color="#fff"/>
    <item android:state_activated="true" android:color="#fff"/>
    <item android:color="#000" />

Apparently the key is state_activated="true" state.

indexOf Case Sensitive?

Had the same problem. I tried regular expression and the apache StringUtils.indexOfIgnoreCase-Method, but both were pretty slow... So I wrote an short method myself...:

public static int indexOfIgnoreCase(final String chkstr, final String searchStr, int i) {
    if (chkstr != null && searchStr != null && i > -1) {
          int serchStrLength = searchStr.length();
          char[] searchCharLc = new char[serchStrLength];
          char[] searchCharUc = new char[serchStrLength];
          searchStr.toUpperCase().getChars(0, serchStrLength, searchCharUc, 0);
          searchStr.toLowerCase().getChars(0, serchStrLength, searchCharLc, 0);
          int j = 0;
          for (int checkStrLength = chkstr.length(); i < checkStrLength; i++) {
                char charAt = chkstr.charAt(i);
                if (charAt == searchCharLc[j] || charAt == searchCharUc[j]) {
                     if (++j == serchStrLength) {
                           return i - j + 1;
                } else { // faster than: else if (j != 0) {
                         i = i - j;
                         j = 0;
        return -1;

According to my tests its much faster... (at least if your searchString is rather short). if you have any suggestions for improvement or bugs it would be nice to let me know... (since I use this code in an application ;-)

How to find rows that have a value that contains a lowercase letter

SELECT * FROM my_table WHERE my_column = 'my string'
COLLATE Latin1_General_CS_AS

This would make a case sensitive search.


As stated in kouton's comment here and tormuto's comment here whosoever faces problem with the below collation

COLLATE Latin1_General_CS_AS

should first check the default collation for their SQL server, their respective database and the column in question; and pass in the default collation with the query expression. List of collations can be found here.

Read/Parse text file line by line in VBA

You Can use this code to read line by line in text file and You could also check about the first character is "*" then you can leave that..

Public Sub Test()

    Dim ReadData as String

    Open "C:\satheesh\myfile\file.txt" For Input As #1

    Do Until EOF(1) 
       Line Input #1, ReadData 'Adding Line to read the whole line, not only first 128 positions
    If Not Left(ReadData, 1) = "*" then
       '' you can write the variable ReadData into the database or file
    End If 


    Close #1

End Sub

What is the default access specifier in Java?

The default visibility (no keyword) is package which means that it will be available to every class that is located in the same package.

Interesting side note is that protected doesn't limit visibility to the subclasses but also to the other classes in the same package

Reading a key from the Web.Config using ConfigurationManager

Try using the WebConfigurationManager class instead. For example:

string userName = WebConfigurationManager.AppSettings["PFUserName"]

session handling in jquery

In my opinion you should not load and use plugins you don't have to. This particular jQuery plugin doesn't give you anything since directly using the JavaScript sessionStorage object is exactly the same level of complexity. Nor, does the plugin provide some easier way to interact with other jQuery functionality. In addition the practice of using a plugin discourages a deep understanding of how something works. sessionStorage should be used only if its understood. If its understood, then using the jQuery plugin is actually MORE effort.

Consider using sessionStorage directly:

How to convert java.util.Date to java.sql.Date?

I was trying the following coding that worked fine.

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate);

Why is it that "No HTTP resource was found that matches the request URI" here?

Try this mate, you can chuck it in the body like so...

    public bool SampleCall([FromBody]JObject data)
        var firstName = data["firstName"].ToString();
        var lastName= data["lastName"].ToString();
        var email = data["email"].ToString();
        var obj= data["toLastName"].ToObject<SomeObject>();

        return _someService.DoYourBiz(firstName, lastName, email, obj);

How to get text of an element in Selenium WebDriver, without including child element text?

In the HTML which you have shared:

<div id="a">This is some
   <div id="b">text</div>

The text This is some is within a text node. To depict the text node in a structured way:

<div id="a">
    This is some
   <div id="b">text</div>

This Usecase

To extract and print the text This is some from the text node using Selenium's client you have 2 ways as follows:

  • Using splitlines(): You can identify the parent element i.e. <div id="a">, extract the innerHTML and then use splitlines() as follows:

    • using xpath:

    • using xpath:

  • Using execute_script(): You can also use the execute_script() method which can synchronously execute JavaScript in the current window/frame as follows:

    • using xpath and firstChild:

      parent_element = driver.find_element_by_xpath("//div[@id='a']")
      print(driver.execute_script('return arguments[0].firstChild.textContent;', parent_element).strip())
    • using xpath and childNodes[n]:

      parent_element = driver.find_element_by_xpath("//div[@id='a']")
      print(driver.execute_script('return arguments[0].childNodes[1].textContent;', parent_element).strip())

Setting Django up to use MySQL

If you are using python3.x then Run below command

pip install mysqlclient

Then change like

'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'DB',
     'USER': 'username',
    'PASSWORD': 'passwd',

How do I get my Python program to sleep for 50 milliseconds?

There is a module called 'time' which can help you. I know two ways:

  1. sleep

    Sleep (reference) asks the program to wait, and then to do the rest of the code.

    There are two ways to use sleep:

    import time # Import whole time module
    print("0.00 seconds")
    time.sleep(0.05) # 50 milliseconds... make sure you put time. if you import time!
    print("0.05 seconds")

    The second way doesn't import the whole module, but it just sleep.

    from time import sleep # Just the sleep function from module time
    print("0.00 sec")
    sleep(0.05) # Don't put time. this time, as it will be confused. You did
                # not import the whole module
    print("0.05 sec")
  2. Using time since Unix time.

    This way is useful if you need a loop to be running. But this one is slightly more complex.

    time_not_passed = True
    from time import time # You can import the whole module like last time. Just don't forget the time. before to signal it.
    init_time = time() # Or time.time() if whole module imported
    print("0.00 secs")
    while True: # Init loop
        if init_time + 0.05 <= time() and time_not_passed: # Time not passed variable is important as we want this to run once. !!! time.time() if whole module imported :O
            print("0.05 secs")
            time_not_passed = False

How to find out what group a given user has?

Below is the script which is integrated into ansible and generating dashboard in CSV format.



HOSTNAME=`hostname -s`

for i in `cat /etc/passwd| grep -vE "nologin|shutd|hal|sync|root|false"|awk -F':' '{print$1}' | sed 's/[[:space:]]/,/g'`; do groups $i; done|sed s/\:/\,/g|tr -d ' '|sed -e "s/^/$HOSTNAME,/"> /tmp/"$HOSTNAME"_inventory.txt

sudo cat /etc/sudoers| grep -v "^#"|awk '{print $1}'|grep -v Defaults|sed '/^$/d;s/[[:blank:]]//g'>/tmp/"$HOSTNAME"_sudo.txt

paste -d , /tmp/"$HOSTNAME"_inventory.txt /tmp/"$HOSTNAME"_sudo.txt|sed 's/,[[:blank:]]*$//g' >/tmp/"$HOSTNAME"_inventory_users.txt

My output stored in below text files.

cat /tmp/ANSIBLENODE_sudo.txt
cat /tmp/ANSIBLENODE_inventory.txt
cat /tmp/ANSIBLENODE_inventory_users.txt

Two models in one view in ASP MVC 3

I hope you find it helpfull !!

i use ViewBag For Project and Model for task so in this way i am using two model in single view and in controller i defined viewbag's value or data

List<tblproject> Plist = new List<tblproject>();_x000D_
            Plist = ps.getmanagerproject(c, id);_x000D_
            ViewBag.projectList = Plist.Select(x => new SelectListItem_x000D_
                Value = x.ProjectId.ToString(),_x000D_
                Text = x.Title_x000D_

and in view tbltask and projectlist are my two diff models


IEnumerable<SelectListItem> plist = ViewBag.projectList;

} @model List

Python: Removing spaces from list objects

replace() does not operate in-place, you need to assign its result to something. Also, for a more concise syntax, you could supplant your for loop with a one-liner: hello_no_spaces = map(lambda x: x.replace(' ', ''), hello)

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

How do I get the picture size with PIL?

Here's how you get the image size from the given URL in Python 3:

from PIL import Image
import urllib.request
from io import BytesIO

file = BytesIO(urllib.request.urlopen('').read())
im =
width, height = im.size

How to iterate over the file in python

Just use for x in f: ..., this gives you line after line, is much shorter and readable (partly because it automatically stops when the file ends) and also saves you the rstrip call because the trailing newline is already stipped.

The error is caused by the exit condition, which can never be true: Even if the file is exhausted, readline will return an empty string, not None. Also note that you could still run into trouble with empty lines, e.g. at the end of the file. Adding if line.strip() == "": continue makes the code ignore blank lines, which is propably a good thing anyway.

How to fix "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" error?

Try this one -

       ID, Salt, password, BannedEndDate
     , (
          SELECT COUNT(1)
          FROM dbo.LoginFails l
          WHERE l.UserName = u.UserName
               AND IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "'
      ) AS cnt
FROM dbo.Users u
WHERE u.UserName = '" + LoginModel.Username + "'"

Webpack not excluding node_modules

This worked for me:

exclude: [/bower_components/, /node_modules/]


A array of automatically applied loaders.

Each item can have these properties:

test: A condition that must be met

exclude: A condition that must not be met

include: A condition that must be met

loader: A string of "!" separated loaders

loaders: A array of loaders as string

A condition can be a RegExp, an absolute path start, or an array of one of these combined with "and".


ASP.Net MVC: Calling a method from a view

You can implement a static formatting method or an HTML helper, then use this syntaxe :

@using class_of_method_namespace
// HTML page here

or in case of HTML Helper


How to `wget` a list of URLs in a text file?

If you also want to preserve the original file name, try with:

wget --content-disposition --trust-server-names -i list_of_urls.txt

Splitting applicationContext to multiple files

Mike Nereson has this to say on his blog at:

There are a couple of ways to do this.

1. web.xml contextConfigLocation

Your first option is to load them all into your Web application context via the ContextConfigLocation element. You’re already going to have your primary applicationContext here, assuming you’re writing a web application. All you need to do is put some white space between the declaration of the next context.

      <param-name> contextConfigLocation </param-name>


The above uses carriage returns. Alternatively, yo could just put in a space.

      <param-name> contextConfigLocation </param-name>
      <param-value> applicationContext1.xml applicationContext2.xml </param-value>

      <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class>

2. applicationContext.xml import resource

Your other option is to just add your primary applicationContext.xml to the web.xml and then use import statements in that primary context.

In applicationContext.xml you might have…

  <!-- hibernate configuration and mappings -->
  <import resource="applicationContext-hibernate.xml"/>

  <!-- ldap -->
  <import resource="applicationContext-ldap.xml"/>

  <!-- aspects -->
  <import resource="applicationContext-aspects.xml"/>

Which strategy should you use?

1. I always prefer to load up via web.xml.

Because , this allows me to keep all contexts isolated from each other. With tests, we can load just the contexts that we need to run those tests. This makes development more modular too as components stay loosely coupled, so that in the future I can extract a package or vertical layer and move it to its own module.

2. If you are loading contexts into a non-web application, I would use the import resource.

In Bash, how do I add a string after each line in a file?

Sed is a little ugly, you could do it elegantly like so:

hendry@i7 tmp$ cat foo 
hendry@i7 tmp$ for i in `cat foo`; do echo ${i}bar; done

Inner join vs Where

They should be exactly the same. However, as a coding practice, I would rather see the Join. It clearly articulates your intent,

contenteditable change events

Consider using MutationObserver. These observers are designed to react to changes in the DOM, and as a performant replacement to Mutation Events.


  • Fires when any change occurs, which is difficult to achieve by listening to key events as suggested by other answers. For example, all of these work well: drag & drop, italicizing, copy/cut/paste through context menu.
  • Designed with performance in mind.
  • Simple, straightforward code. It's a lot easier to understand and debug code that listens to one event rather than code that listens to 10 events.
  • Google has an excellent mutation summary library which makes using MutationObservers very easy.


  • Requires a very recent version of Firefox (14.0+), Chrome (18+), or IE (11+).
  • New API to understand
  • Not a lot of information available yet on best practices or case studies

Learn more:

  • I wrote a little snippet to compare using MutationObserers to handling a variety of events. I used balupton's code since his answer has the most upvotes.
  • Mozilla has an excellent page on the API
  • Take a look at the MutationSummary library

Allow click on twitter bootstrap dropdown toggle link?

Since there is not really an answer that works (selected answer disables dropdown), or overrides using javascript, here goes.

This is all html and css fix (uses two <a> tags):

<ul class="nav">
 <li class="dropdown dropdown-li">
    <a class="dropdown-link" href="">Dropdown</a>
    <a class="dropdown-caret dropdown-toggle"><b class="caret"></b></a>
    <ul class="dropdown-menu">
        <li><a href="#">Link 1</a></li>
        <li><a href="#">Link 2</a></li>

Now here's the CSS you need.

.dropdown-li {
    display:inline-block !important;
.dropdown-link {
    display:inline-block !important; 
    padding-right:4px !important;
.dropdown-caret {
    display:inline-block !important; 
    padding-left:4px !important;

Assuming you will want the both <a> tags to highlight on hover of either one, you will also need to override bootstrap, you might play around with the following:

.nav > li:hover {
    background-color: #f67a47; /*hover background color*/
.nav > li:hover > a {
    color: white; /*hover text color*/
.nav > li:hover > ul > a {
    color: black; /*dropdown item text color*/

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

You can take the SelectedItem and cast it back to your class and access its properties.


Edit You can try using DataTextField and DataValueField, I used it with DataSource.

ComboBox_Servers.DataTextField = "Text";
ComboBox_Servers.DataValueField = "Value";

Pretty-print a Map in Java

Look at the code for HashMap#toString() and AbstractMap#toString() in the OpenJDK sources:

class java.util.HashMap.Entry<K,V> implements Map.Entry<K,V> {
       public final String toString() {
           return getKey() + "=" + getValue();
 class java.util.AbstractMap<K,V> {
     public String toString() {
         Iterator<Entry<K,V>> i = entrySet().iterator();
         if (! i.hasNext())
            return "{}";

        StringBuilder sb = new StringBuilder();
        for (;;) {
            Entry<K,V> e =;
            K key = e.getKey();
            V value = e.getValue();
            sb.append(key   == this ? "(this Map)" : key);
            sb.append(value == this ? "(this Map)" : value);
            if (! i.hasNext())
                return sb.append('}').toString();
            sb.append(", ");

So if the guys from OpenJDK did not find a more elegant way to do this, there is none :-)

What are the advantages of NumPy over regular Python lists?

NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented.

For example, you could read your cube directly from a file into an array:

x = numpy.fromfile(file=open("data"), dtype=float).reshape((100, 100, 100))

Sum along the second dimension:

s = x.sum(axis=1)

Find which cells are above a threshold:

(x > 0.5).nonzero()

Remove every even-indexed slice along the third dimension:

x[:, :, ::2]

Also, many useful libraries work with NumPy arrays. For example, statistical analysis and visualization libraries.

Even if you don't have performance problems, learning NumPy is worth the effort.

Handling 'Sequence has no elements' Exception

I had the same issue, i realized i had deleted the default image that was in the folder just update the media missing, on the specific file

How can I use Html.Action?

You should look at the documentation for the Action method; it's explained well. For your case, this should work:

@Html.Action("GetOptions", new { pk="00", rk="00" });

The controllerName parameter will default to the controller from which Html.Action is being invoked. So if you're trying to invoke an action from another controller, you'll have to specify the controller name like so:

@Html.Action("GetOptions", "ControllerName", new { pk="00", rk="00" });

How to use if statements in LESS

There is a way to use guards for individual (or multiple) attributes.

@debug: true;

header {
    /* guard for attribute */
    & when (@debug = true) {
        background-color: yellow;
    /* guard for nested class */
    #title when (@debug = true) {
        background-color: orange;

/* guard for class */
article when (@debug = true) {
    background-color: red;

/* and when debug is off: */
article when not (@debug = true) {
    background-color: green;

...and with Less 1.7; compiles to:

header {
    background-color: yellow;
header #title {
    background-color: orange;
article {
    background-color: red;

Must issue a STARTTLS command first

You are probably attempting to use Gmail's servers on port 25 to deliver mail to a third party over an unauthenticated connection. Gmail doesn't let you do this, because then anybody could use Gmail's servers to send mail to anybody else. This is called an open relay and was a common enabler of spam in the early days. Open relays are no longer acceptable on the Internet.

You will need to ask your SMTP client to connect to Gmail using an authenticated connection, probably on port 587.

How to get first and last day of week in Oracle?


select TRUNC(sysdate, 'iw') AS iso_week_start_date,
       TRUNC(sysdate, 'iw') + 7 - 1/86400 AS iso_week_end_date
from dual;


TRUNC (sysdate, 'mm') AS month_start_date,
LAST_DAY (TRUNC (sysdate, 'mm')) + 1 - 1/86400 AS month_end_date
from dual;

How do I create sql query for searching partial matches?

First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).

If your data is not large, you can do

SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'

using OR if you have multiple keywords.

Dataset - Vehicle make/model/year (free)

How about Freebase? I think they have an API available, too.

"Active Directory Users and Computers" MMC snap-in for Windows 7?

I'm not allowed to use Turn Windows features on or off, but running all of these commands in an elevated command prompt (Run as Administrator) finally got Active Directory Users and Computers to show up under Administrative Tools on the start menu:

dism /online /enable-feature /featurename:RemoteServerAdministrationTools
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS-SnapIns
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS-AdministrativeCenter
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS-NIS
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-LDS
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-Powershell

I had downloaded and installed the RSAT (Windows 7 Link, Windows Vista Link) before running these commands.

It's quite likely that this is more than you features than you actually need, but at least it's not too few.

Recommended website resolution (width and height)?

I target the 1024 pixel monitors (but don't use 100% of that space). I've given up on those with 800x600. I'd rather punish the few with outdated hardware by making them scroll if they need to, versus punishing everyone with new equipment by wasting space.

I suppose it depends on your audience, and the nature of you app though.

How to update the value stored in Dictionary in C#?

Here is a way to update by an index much like foo[x] = 9 where x is a key and 9 is the value

var views = new Dictionary<string, bool>();

foreach (var g in grantMasks)
    string m = g.ToString();
    for (int i = 0; i <= m.Length; i++)
        views[views.ElementAt(i).Key] = m[i].Equals('1') ? true : false;

Write a formula in an Excel Cell using VBA

I don't know why, but if you use

(...)Formula = "=SUM(D2,E2)"

(',' instead of ';'), it works.

If you step through your sub in the VB script editor (F8), you can add Range("F2").Formula to the watch window and see what the formular looks like from a VB point of view. It seems that the formular shown in Excel itself is sometimes different from the formular that VB sees...

When are static variables initialized?

static variable

  • It is a variable which belongs to the class and not to object(instance)
  • Static variables are initialized only once , at the start of the execution(when the Classloader load the class for the first time) .
  • These variables will be initialized first, before the initialization of any instance variables
  • A single copy to be shared by all instances of the class
  • A static variable can be accessed directly by the class name and doesn’t need any object

How can I shuffle the lines of a text file on the Unix command line or in a shell script?

A simple and intuitive way would be to use shuf.


Assume words.txt as:


To shuffle the lines, do:

$ shuf words.txt

which would throws the shuffled lines to standard output; So, you've to pipe it to an output file like:

$ shuf words.txt > shuffled_words.txt

One such shuffle run could yield:


method in class cannot be applied to given types

generateNumbers() expects a parameter and you aren't passing one in!

generateNumbers() also returns after it has set the first random number - seems to be some confusion about what it is trying to do.