Programs & Examples On #Ruby gnome2

Where is the IIS Express configuration / metabase file found?

For Visual Studio 2019 (v16.2.4) I was only able to find this file here:

C:\Users\\Documents\IISExpress\config\applicationhost.config applicationhost.config

Hope this helps as I wasn't able to find the .vs folder location as mentioned in the above suggestions.

M_PI works with math.h but not with cmath in Visual Studio

As suggested by user7860670, right-click on the project, select properties, navigate to C/C++ -> Preprocessor and add _USE_MATH_DEFINES to the Preprocessor Definitions.

That's what worked for me.

How can I check if a string contains a character in C#?

It will be hard to work in C# without knowing how to work with strings and booleans. But anyway:

        String str = "ABC";
        if (str.Contains('A'))
        { 
            //...
        }

        if (str.Contains("AB"))
        { 
            //...
        }

Simulation of CONNECT BY PRIOR of Oracle in SQL Server

The SQL standard way to implement recursive queries, as implemented e.g. by IBM DB2 and SQL Server, is the WITH clause. See this article for one example of translating a CONNECT BY into a WITH (technically a recursive CTE) -- the example is for DB2 but I believe it will work on SQL Server as well.

Edit: apparently the original querant requires a specific example, here's one from the IBM site whose URL I already gave. Given a table:

CREATE TABLE emp(empid  INTEGER NOT NULL PRIMARY KEY,
                 name   VARCHAR(10),
                 salary DECIMAL(9, 2),
                 mgrid  INTEGER);

where mgrid references an employee's manager's empid, the task is, get the names of everybody who reports directly or indirectly to Joan. In Oracle, that's a simple CONNECT:

SELECT name 
  FROM emp
  START WITH name = 'Joan'
  CONNECT BY PRIOR empid = mgrid

In SQL Server, IBM DB2, or PostgreSQL 8.4 (as well as in the SQL standard, for what that's worth;-), the perfectly equivalent solution is instead a recursive query (more complex syntax, but, actually, even more power and flexibility):

WITH n(empid, name) AS 
   (SELECT empid, name 
    FROM emp
    WHERE name = 'Joan'
        UNION ALL
    SELECT nplus1.empid, nplus1.name 
    FROM emp as nplus1, n
    WHERE n.empid = nplus1.mgrid)
SELECT name FROM n

Oracle's START WITH clause becomes the first nested SELECT, the base case of the recursion, to be UNIONed with the recursive part which is just another SELECT.

SQL Server's specific flavor of WITH is of course documented on MSDN, which also gives guidelines and limitations for using this keyword, as well as several examples.

failed to push some refs to [email protected]

Make sure you’re pushing the right branch. I wasn’t on master and kept wondering why it was complaining :P

Opacity of background-color, but not the text

I use an alpha-transparent PNG for that:

div.semi-transparent {
  background: url('semi-transparent.png');
}

For IE6, you'd need to use a PNG fix (1, 2), though.

Change Default branch in gitlab

in the GitLab Enterprise Edition 12.2.0-pre you have to use following: Setting ? Repository ? Default Branch ( expand it) and change the default branch Here

How to detect pressing Enter on keyboard using jQuery?

I spent sometime coming up with this solution i hope it helps someone.

$(document).ready(function(){

  $('#loginforms').keypress(function(e) {
    if (e.which == 13) {
    //e.preventDefault();
    alert('login pressed');
    }
  });

 $('#signupforms').keypress(function(e) {
    if (e.which == 13) {
      //e.preventDefault();
      alert('register');
    }
  });

});

Using relative URL in CSS file, what location is it relative to?

Try using:

body {
  background-attachment: fixed;
  background-image: url(./Images/bg4.jpg);
}

Images being folder holding the picture that you want to post.

How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

If you find yourself doing things like this regularly it may be worth investigating the object-oriented interface to matplotlib. In your case:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(5)
y = np.exp(x)
fig1, ax1 = plt.subplots()
ax1.plot(x, y)
ax1.set_title("Axis 1 title")
ax1.set_xlabel("X-label for axis 1")

z = np.sin(x)
fig2, (ax2, ax3) = plt.subplots(nrows=2, ncols=1) # two axes on figure
ax2.plot(x, z)
ax3.plot(x, -z)

w = np.cos(x)
ax1.plot(x, w) # can continue plotting on the first axis

It is a little more verbose but it's much clearer and easier to keep track of, especially with several figures each with multiple subplots.

Deleting queues in RabbitMQ

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
               'localhost'))
channel = connection.channel()

channel.queue_delete(queue='queue-name')

connection.close()

Install pika package as follows

$ sudo pip install pika==0.9.8

The installation depends on pip and git-core packages, you may need to install them first.

On Ubuntu:

$ sudo apt-get install python-pip git-core

On Debian:

$ sudo apt-get install python-setuptools git-core
$ sudo easy_install pip

On Windows: To install easy_install, run the MS Windows Installer for setuptools

> easy_install pip
> pip install pika==0.9.8

ImportError: No module named - Python

For the Python module import to work, you must have "src" in your path, not "gen_py/lib".

When processing an import like import gen_py.lib, it looks for a module gen_py, then looks for a submodule lib.

As the module gen_py won't be in "../gen_py/lib" (it'll be in ".."), the path you added will do nothing to help the import process.

Depending on where you're running it from, try adding the relative path to the "src" folder. Perhaps it's sys.path.append('..'). You might also have success running the script while inside the src folder directly, via relative paths like python main/MyServer.py

How do I merge a specific commit from one branch into another in Git?

SOURCE: https://git-scm.com/book/en/v2/Distributed-Git-Maintaining-a-Project#Integrating-Contributed-Work

The other way to move introduced work from one branch to another is to cherry-pick it. A cherry-pick in Git is like a rebase for a single commit. It takes the patch that was introduced in a commit and tries to reapply it on the branch you’re currently on. This is useful if you have a number of commits on a topic branch and you want to integrate only one of them, or if you only have one commit on a topic branch and you’d prefer to cherry-pick it rather than run rebase. For example, suppose you have a project that looks like this:

enter image description here

If you want to pull commit e43a6 into your master branch, you can run

$ git cherry-pick e43a6
Finished one cherry-pick.
[master]: created a0a41a9: "More friendly message when locking the index fails."
 3 files changed, 17 insertions(+), 3 deletions(-)

This pulls the same change introduced in e43a6, but you get a new commit SHA-1 value, because the date applied is different. Now your history looks like this:

enter image description here

Now you can remove your topic branch and drop the commits you didn’t want to pull in.

Using .htaccess to make all .html pages to run as .php files?

I'm using PHP7.1 running in my Raspberry Pi 3.

In the file /etc/apache2/mods-enabled/php7.1.conf I added at the end:

AddType application/x-httpd-php .html .htm .png .jpg .gif

Choosing a jQuery datagrid plugin?

The three most used and well supported jQuery grid plugins today are SlickGrid, jqGrid and DataTables. See http://wiki.jqueryui.com/Grid-OtherGrids for more info.

Declaring an enum within a class

If you are creating a code library, then I would use namespace. However, you can still only have one Color enum inside that namespace. If you need an enum that might use a common name, but might have different constants for different classes, use your approach.

How do you clear the console screen in C?

For portability, try this:

#ifdef _WIN32
#include <conio.h>
#else
#include <stdio.h>
#define clrscr() printf("\e[1;1H\e[2J")
#endif

Then simply call clrscr(). On Windows, it will use conio.h's clrscr(), and on Linux, it will use ANSI escape codes.

If you really want to do it "properly", you can eliminate the middlemen (conio, printf, etc.) and do it with just the low-level system tools (prepare for a massive code-dump):

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

void ClearScreen()
{
  HANDLE                     hStdOut;
  CONSOLE_SCREEN_BUFFER_INFO csbi;
  DWORD                      count;
  DWORD                      cellCount;
  COORD                      homeCoords = { 0, 0 };

  hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
  if (hStdOut == INVALID_HANDLE_VALUE) return;

  /* Get the number of cells in the current buffer */
  if (!GetConsoleScreenBufferInfo( hStdOut, &csbi )) return;
  cellCount = csbi.dwSize.X *csbi.dwSize.Y;

  /* Fill the entire buffer with spaces */
  if (!FillConsoleOutputCharacter(
    hStdOut,
    (TCHAR) ' ',
    cellCount,
    homeCoords,
    &count
    )) return;

  /* Fill the entire buffer with the current colors and attributes */
  if (!FillConsoleOutputAttribute(
    hStdOut,
    csbi.wAttributes,
    cellCount,
    homeCoords,
    &count
    )) return;

  /* Move the cursor home */
  SetConsoleCursorPosition( hStdOut, homeCoords );
}

#else // !_WIN32
#include <unistd.h>
#include <term.h>

void ClearScreen()
{
  if (!cur_term)
  {
     int result;
     setupterm( NULL, STDOUT_FILENO, &result );
     if (result <= 0) return;
  }

   putp( tigetstr( "clear" ) );
}
#endif

strdup() - what does it do in C?

No point repeating the other answers, but please note that strdup() can do anything it wants from a C perspective, since it is not part of any C standard. It is however defined by POSIX.1-2001.

Bootstrap 4 - Responsive cards in card-columns

I realize this question was posted a while ago; nonetheless, Bootstrap v4.0 has card layout support out of the box. You can find the documentation here: Bootstrap Card Layouts.

I've gotten back into using Bootstrap for a recent project that relies heavily on the card layout UI. I've found success with the following implementation across the standard breakpoints:

_x000D_
_x000D_
<link href="https://unpkg.com/[email protected]/css/tachyons.min.css" rel="stylesheet"/>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="flex justify-center" id="cars" v-cloak>_x000D_
    <!-- RELEVANT MARKUP BEGINS HERE -->_x000D_
    <div class="container mh0 w-100">_x000D_
        <div class="page-header text-center mb5">_x000D_
            <h1 class="avenir text-primary mb-0">Cars</h1>_x000D_
            <p class="text-secondary">Add and manage your cars for sale.</p>_x000D_
            <div class="header-button">_x000D_
                <button class="btn btn-outline-primary" @click="clickOpenAddCarModalButton">Add a car for sale</button>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="container pa0 flex justify-center">_x000D_
            <div class="listings card-columns">_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

After trying both the Bootstrap .card-group and .card-deck card layout classes with quirky results at best across the standard breakpoints, I finally decided to give the .card-columns class a shot. And it worked!

Your results may vary, but .card-columns seems to be the most stable implementation here.

jQuery pass more parameters into callback

You can use a closure of JavaScript:

function wrapper( var1, var2,....) // put here your variables
{
  return function( data, status)
  {
     //Handle here results of call
  }
};

and when you can do:

$.post("someurl.php",data,wrapper(var1, var2, etc...),"html");

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

After trying EVERY solution google came up with on stack overflow, I found what my particular problem was. I had edited my hosts file a long time ago to allow me to access my localhost from my virtualbox.

Removing this entry solved it for me, along with the correct installation of mongoDB from the link given in the above solution, and including the correct promise handling code:

mongoose.connect('mongodb://localhost/testdb').then(() => {
console.log("Connected to Database");
}).catch((err) => {
    console.log("Not Connected to Database ERROR! ", err);
});

CURL alternative in Python

import requests

url = 'https://example.tld/'
auth = ('username', 'password')

r = requests.get(url, auth=auth)
print r.content

This is the simplest I've been able to get it.

Importing CSV data using PHP/MySQL

letsay $infile = a.csv //file needs to be imported.

class blah
{
 static public function readJobsFromFile($file)
{            
    if (($handle = fopen($file, "r")) === FALSE) 
    {
        echo "readJobsFromFile: Failed to open file [$file]\n";
        die;
    }

    $header=true;
    $index=0;
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) 
    {
        // ignore header
        if ($header == true)
        {
            $header = false;
            continue;
        }

        if ($data[0] == '' && $data[1] == '' ) //u have oly 2 fields
        {
            echo "readJobsFromFile: No more input entries\n";
            break;                        
        }            


        $a      = trim($data[0]);
        $b   = trim($data[1]);                 





        if (check_if_exists("SELECT count(*) FROM Db_table WHERE a='$a' AND b='$b'") === true)
        {

                $index++;
            continue;    
        }            

        $sql = "INSERT INTO DB_table SET a='$a' , b='$b' ";
        @mysql_query($sql) or die("readJobsFromFile: " . mysql_error());            
        $index++;
    }

    fclose($handle);        
    return $index; //no. of fields in database.
} 
function
check_if_exists($sql)
{
$result = mysql_query($sql) or die("$sql --" . mysql_error());
if (!$result) {
    $message  = 'check_if_exists::Invalid query: ' . mysql_error() . "\n";
    $message .= 'Query: ' . $sql;
    die($message);
}

$row = mysql_fetch_assoc ($result);
$count = $row['count(*)'];
if ($count > 0)
    return true;
return false;
}

$infile=a.csv; 
blah::readJobsFromFile($infile);
}

hope this helps.

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

I had a similar issue, I was sending a POST request (using RESTClient plugin for Firefox) with data in the request body and was receiving the same message.

In my case this happened because I was trying to use HTTPS protocol in a local tomcat instance where HTTPS was not configured.

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

The number of results can (theoretically) be greater than the range of an integer. I would refactor the code and work with the returned long value instead.

Spring JSON request getting 406 (not Acceptable)

There is another case where this status will be returned: if the Jackson mapper cannot figure out how to serialize your bean. For example, if you have two accessor methods for the same boolean property, isFoo() and getFoo().

What's happening is that Spring's MappingJackson2HttpMessageConverter calls Jackson's StdSerializerProvider to see if it can convert your object. At the bottom of the call chain, StdSerializerProvider._createAndCacheUntypedSerializer throws a JsonMappingException with an informative message. However, this exception is swallowed by StdSerializerProvider._createAndCacheUntypedSerializer, which tells Spring that it can't convert the object. Having run out of converters, Spring reports that it's not being given an Accept header that it can use, which of course is bogus when you're giving it */*.

There is a bug for this behavior, but it was closed as "cannot reproduce": the method that's being called doesn't declare that it can throw, so swallowing exceptions is apparently an appropriate solution (yes, that was sarcasm). Unfortunately, Jackson doesn't have any logging ... and there are a lot of comments in the codebase wishing it did, so I suspect this isn't the only hidden gotcha.

Asus Zenfone 5 not detected by computer

I had the same problem. I solved it the following way :

1. Go to Settings->Storage->Click the USB icon at top
2. Make sure that MTP is selected

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

I had this problem in VSCode, and the issue was that the file that I was looking at in the editor was not the same copy of the file that the project was building. I had cloned a repository for a C# library down into two locations, one which was open in the editor and one which was being linked by the project. If clean building isn't working for you, check that you are looking at the right copy of the file in the editor!

How to return a result from a VBA function

Just setting the return value to the function name is still not exactly the same as the Java (or other) return statement, because in java, return exits the function, like this:

public int test(int x) {
    if (x == 1) {
        return 1; // exits immediately
    }

    // still here? return 0 as default.
    return 0;
}

In VB, the exact equivalent takes two lines if you are not setting the return value at the end of your function. So, in VB the exact corollary would look like this:

Public Function test(ByVal x As Integer) As Integer
    If x = 1 Then
        test = 1 ' does not exit immediately. You must manually terminate...
        Exit Function ' to exit
    End If

    ' Still here? return 0 as default.
    test = 0
    ' no need for an Exit Function because we're about to exit anyway.
End Function 

Since this is the case, it's also nice to know that you can use the return variable like any other variable in the method. Like this:

Public Function test(ByVal x As Integer) As Integer

    test = x ' <-- set the return value

    If test <> 1 Then ' Test the currently set return value
        test = 0 ' Reset the return value to a *new* value
    End If

End Function 

Or, the extreme example of how the return variable works (but not necessarily a good example of how you should actually code)—the one that will keep you up at night:

Public Function test(ByVal x As Integer) As Integer

    test = x ' <-- set the return value

    If test > 0 Then

        ' RECURSIVE CALL...WITH THE RETURN VALUE AS AN ARGUMENT,
        ' AND THE RESULT RESETTING THE RETURN VALUE.
        test = test(test - 1)

    End If

End Function

Get JSF managed bean by name in any Servlet related class

I had same requirement.

I have used the below way to get it.

I had session scoped bean.

@ManagedBean(name="mb")
@SessionScopedpublic 
class ManagedBean {
     --------
}

I have used the below code in my servlet doPost() method.

ManagedBean mb = (ManagedBean) request.getSession().getAttribute("mb");

it solved my problem.

How to get full path of a file?

find $PWD -type f | grep "filename"

or

find $PWD -type f -name "*filename*"

What is the (function() { } )() construct in JavaScript?

This is an Immediately Invoked Function Expression in Javascript:

To understand IIFE in JS, lets break it down:

  1. Expression: Something that returns a value
    Example: Try out following in chrome console. These are expressions in JS.
a = 10 
output = 10 
(1+3) 
output = 4
  1. Function Expression:
    Example:
// Function Expression 
var greet = function(name){
   return 'Namaste' + ' ' + name;
}

greet('Santosh');

How function expression works:
- When JS engine runs for the first time (Execution Context - Create Phase), this function (on the right side of = above) does not get executed or stored in the memory. Variable 'greet' is assigned 'undefined' value by the JS engine.
- During execution (Execution Context - Execute phase), the funtion object is created on the fly (its not executed yet), gets assigned to 'greet' variable and it can be invoked using 'greet('somename')'.

3. Immediately Invoked Funtion Expression:

Example:

// IIFE
var greeting = function(name) {
    return 'Namaste' + ' ' + name;
}('Santosh')

console.log(greeting)  // Namaste Santosh. 

How IIFE works:
- Notice the '()' immediately after the function declaration. Every funtion object has a 'CODE' property attached to it which is callable. And we can call it (or invoke it) using '()' braces.
- So here, during the execution (Execution Context - Execute Phase), the function object is created and its executed at the same time - So now, the greeting variable, instead of having the funtion object, has its return value ( a string )

Typical usecase of IIFE in JS:

The following IIFE pattern is quite commonly used.

// IIFE 
// Spelling of Function was not correct , result into error
(function (name) {
   var greeting = 'Namaste';
   console.log(greeting + ' ' + name);
})('Santosh');
  • we are doing two things over here. a) Wrapping our function expression inside braces (). This goes to tell the syntax parser the whatever placed inside the () is an expression (function expression in this case) and is a valid code.
    b) We are invoking this funtion at the same time using the () at the end of it.

So this function gets created and executed at the same time (IIFE).

Important usecase for IIFE:

IIFE keeps our code safe.
- IIFE, being a function, has its own execution context, meaning all the variables created inside it are local to this function and are not shared with the global execution context.

Suppose I've another JS file (test1.js) used in my applicaiton along with iife.js (see below).

// test1.js

var greeting = 'Hello';

// iife.js
// Spelling of Function was not correct , result into error
(function (name) { 
   var greeting = 'Namaste';
   console.log(greeting + ' ' + name);
})('Santosh');

console.log(greeting)   // No collision happens here. It prints 'Hello'.

So IIFE helps us to write safe code where we are not colliding with the global objects unintentionally.

"No resource identifier found for attribute 'showAsAction' in package 'android'"

From answer that was removed due to being written in Spanish:

All of the above fixes may not work in android studio. If you are using ANDROID STUDIO please use the following fix.

Use

xmlns: compat = "http://schemas.android.com/tools"

on the menu label instead of

xmlns: compat = "http://schemas.android.com/apk/res-auto"

How to Pass data from child to parent component Angular

Register the EventEmitter in your child component as the @Output:

@Output() onDatePicked = new EventEmitter<any>();

Emit value on click:

public pickDate(date: any): void {
    this.onDatePicked.emit(date);
}

Listen for the events in your parent component's template:

<div>
    <calendar (onDatePicked)="doSomething($event)"></calendar>
</div>

and in the parent component:

public doSomething(date: any):void {
    console.log('Picked date: ', date);
}

It's also well explained in the official docs: Component interaction.

'IF' in 'SELECT' statement - choose output value based on column values

SELECT id, 
       IF(type = 'P', amount, amount * -1) as amount
FROM report

See http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html.

Additionally, you could handle when the condition is null. In the case of a null amount:

SELECT id, 
       IF(type = 'P', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount
FROM report

The part IFNULL(amount,0) means when amount is not null return amount else return 0.

What is the difference between LATERAL and a subquery in PostgreSQL?

Database table

Having the following blog database table storing the blogs hosted by our platform:

Blog table

And, we have two blogs currently hosted:

id created_on title url
1 2013-09-30 Vlad Mihalcea's Blog https://vladmihalcea.com
2 2017-01-22 Hypersistence https://hypersistence.io

Getting our report without using the SQL LATERAL JOIN

We need to build a report that extracts the following data from the blog table:

  • the blog id
  • the blog age, in years
  • the date for the next blog anniversary
  • the number of days remaining until the next anniversary.

If you're using PostgreSQL, then you have to execute the following SQL query:

SELECT
  b.id as blog_id,
  extract(
    YEAR FROM age(now(), b.created_on)
  ) AS age_in_years,
  date(
    created_on + (
      extract(YEAR FROM age(now(), b.created_on)) + 1
    ) * interval '1 year'
  ) AS next_anniversary,
  date(
    created_on + (
      extract(YEAR FROM age(now(), b.created_on)) + 1
    ) * interval '1 year'
  ) - date(now()) AS days_to_next_anniversary
FROM blog b
ORDER BY blog_id

As you can see, the age_in_years has to be defined three times because you need it when calculating the next_anniversary and days_to_next_anniversary values.

And, that's exactly where LATERAL JOIN can help us.

Getting the report using the SQL LATERAL JOIN

The following relational database systems support the LATERAL JOIN syntax:

  • Oracle since 12c
  • PostgreSQL since 9.3
  • MySQL since 8.0.14

SQL Server can emulate the LATERAL JOIN using CROSS APPLY and OUTER APPLY.

LATERAL JOIN allows us to reuse the age_in_years value and just pass it further when calculating the next_anniversary and days_to_next_anniversary values.

The previous query can be rewritten to use the LATERAL JOIN, as follows:

SELECT
  b.id as blog_id,
  age_in_years,
  date(
    created_on + (age_in_years + 1) * interval '1 year'
  ) AS next_anniversary,
  date(
    created_on + (age_in_years + 1) * interval '1 year'
  ) - date(now()) AS days_to_next_anniversary
FROM blog b
CROSS JOIN LATERAL (
  SELECT
    cast(
      extract(YEAR FROM age(now(), b.created_on)) AS int
    ) AS age_in_years
) AS t
ORDER BY blog_id

And, the age_in_years value can be calculated one and reused for the next_anniversary and days_to_next_anniversary computations:

blog_id age_in_years next_anniversary days_to_next_anniversary
1 7 2021-09-30 295
2 3 2021-01-22 44

Much better, right?

The age_in_years is calculated for every record of the blog table. So, it works like a correlated subquery, but the subquery records are joined with the primary table and, for this reason, we can reference the columns produced by the subquery.

In C#, what is the difference between public, private, protected, and having no access modifier?

Those access modifiers specify where your members are visible. You should probably read this up. Take the link given by IainMH as a starting point.

Static members are one per class and not one per instance.

semaphore implementation

Please check this out below sample code for semaphore implementation(Lock and unlock).

    #include<stdio.h>
    #include<stdlib.h>
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include<string.h>
    #include<malloc.h>
    #include <sys/sem.h>
    int main()
    {
            int key,share_id,num;
            char *data;
            int semid;
            struct sembuf sb={0,-1,0};
            key=ftok(".",'a');
            if(key == -1 ) {
                    printf("\n\n Initialization Falied of shared memory \n\n");
                    return 1;
            }
            share_id=shmget(key,1024,IPC_CREAT|0744);
            if(share_id == -1 ) {
                    printf("\n\n Error captured while share memory allocation\n\n");
                    return 1;
            }
            data=(char *)shmat(share_id,(void *)0,0);
            strcpy(data,"Testing string\n");
            if(!fork()) { //Child Porcess
                 sb.sem_op=-1; //Lock
                 semop(share_id,(struct sembuf *)&sb,1);

                 strncat(data,"feeding form child\n",20);

                 sb.sem_op=1;//Unlock
                 semop(share_id,(struct sembuf *)&sb,1);
                 _Exit(0);
            } else {     //Parent Process
              sb.sem_op=-1; //Lock
              semop(share_id,(struct sembuf *)&sb,1);

               strncat(data,"feeding form parent\n",20);

              sb.sem_op=1;//Unlock
              semop(share_id,(struct sembuf *)&sb,1);

            }
            return 0;
    }

MySQL: Can't create table (errno: 150)

usually, the mismatch between foreign key & primary key causes the error:150.

The foreign key must have the same datatype as the primary key. Also, if the primary key is unsigned then the foreign key must also be unsigned.

Is there a decorator to simply cache function return values?

I coded this simple decorator class to cache function responses. I find it VERY useful for my projects:

from datetime import datetime, timedelta 

class cached(object):
    def __init__(self, *args, **kwargs):
        self.cached_function_responses = {}
        self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=0))

    def __call__(self, func):
        def inner(*args, **kwargs):
            max_age = kwargs.get('max_age', self.default_max_age)
            if not max_age or func not in self.cached_function_responses or (datetime.now() - self.cached_function_responses[func]['fetch_time'] > max_age):
                if 'max_age' in kwargs: del kwargs['max_age']
                res = func(*args, **kwargs)
                self.cached_function_responses[func] = {'data': res, 'fetch_time': datetime.now()}
            return self.cached_function_responses[func]['data']
        return inner

The usage is straightforward:

import time

@cached
def myfunc(a):
    print "in func"
    return (a, datetime.now())

@cached(default_max_age = timedelta(seconds=6))
def cacheable_test(a):
    print "in cacheable test: "
    return (a, datetime.now())


print cacheable_test(1,max_age=timedelta(seconds=5))
print cacheable_test(2,max_age=timedelta(seconds=5))
time.sleep(7)
print cacheable_test(3,max_age=timedelta(seconds=5))

input() error - NameError: name '...' is not defined

You can change which python you're using with your IDE, if you've already downloaded python 3.x it shouldn't be too hard to switch. But your script works fine on python 3.x, I would just change

print ("your name is" + input_variable)

to

print ("your name is", input_variable)

Because with the comma it prints with a whitespace in between your name is and whatever the user inputted. AND: if you're using 2.7 just use raw_input instead of input.

how to fix java.lang.IndexOutOfBoundsException

Use if(index.length() < 0) for Integer

or

Use if(index.equals(null) for String

How to check if a date is greater than another in Java?

You need to use a SimpleDateFormat (dd-MM-yyyy will be the format) to parse the 2 input strings to Date objects and then use the Date#before(otherDate) (or) Date#after(otherDate) to compare them.

Try to implement the code yourself.

Can't include C++ headers like vector in Android NDK

This is what caused the problem in my case (CMakeLists.txt):

set (CMAKE_CXX_FLAGS "...some flags...")

It makes invisible all earlier defined include directories. After removing / refactoring this line everything works fine.

remove borders around html input

your code is look like this jsfiddle.net/NTkGZ/

try

border:none;

How to center the text in PHPExcel merged cell

if you want to align only this cells, you can do something like this:

    $style = array(
        'alignment' => array(
            'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
        )
    );

    $sheet->getStyle("A1:B1")->applyFromArray($style);

But, if you want to apply this style to all cells, try this:

    $style = array(
        'alignment' => array(
            'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
        )
    );

    $sheet->getDefaultStyle()->applyFromArray($style);

How do you connect localhost in the Android emulator?

Thanks to author of this blog: https://bigdata-etl.com/solved-how-to-connect-from-android-emulator-to-application-on-localhost/

Defining network security config in xml

<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
       <domain includeSubdomains="true">10.0.2.2</domain>
    </domain-config>
</network-security-config>

And setting it on AndroidManifest.xml

 <application
    android:networkSecurityConfig="@xml/network_security_config"
</application>

Solved issue for me!

Please refer: https://developer.android.com/training/articles/security-config

batch file Copy files with certain extensions from multiple directories into one directory

In a batch file solution

for /R c:\source %%f in (*.xml) do copy %%f x:\destination\

The code works as such;

for each file for in directory c:\source and subdirectories /R that match pattern (\*.xml) put the file name in variable %%f, then for each file do copy file copy %%f to destination x:\\destination\\

Just tested it here on my Windows XP computer and it worked like a treat for me. But I typed it into command prompt so I used the single %f variable name version, as described in the linked question above.

Android - Using Custom Font

Well, after seven years you can change whole app textView or what you want easily by using android.support libraries 26++.

E.g:

Create your font package app/src/res/font and move your font into it.

enter image description here

And in your app theme just add it as a fontFamily:

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
   . . . ...
    <item name="android:fontFamily">@font/demo</item>
</style>

Example for use with textView only:

<style name="fontTextView" parent="@android:style/Widget.TextView">
    <item name="android:fontFamily">monospace</item>
</style>

And add into your main theme:

<item name="android:textViewStyle">@style/fontTextView</item>

Currently it's worked on 8.1 until 4.1 API Jelly Bean And that's a wide range.

How to increase request timeout in IIS?

In IIS >= 7, a <webLimits> section has replaced ConnectionTimeout, HeaderWaitTimeout, MaxGlobalBandwidth, and MinFileBytesPerSec IIS 6 metabase settings.

Example Configuration:

<configuration>
   <system.applicationHost>
      <webLimits connectionTimeout="00:01:00"
         dynamicIdleThreshold="150"
         headerWaitTimeout="00:00:30"
         minBytesPerSecond="500"
      />
   </system.applicationHost>
</configuration>

For reference: more information regarding these settings in IIS can be found here. Also, I was unable to add this section to the web.config via the IIS manager's "configuration editor", though it did show up once I added it and searched the configuration.

Check if Key Exists in NameValueCollection

queryItems.AllKeys.Contains(key)

Be aware that key may not be unique and that the comparison is usually case sensitive. If you want to just get the value of the first matching key and not bothered about case then use this:

        public string GetQueryValue(string queryKey)
        {
            foreach (string key in QueryItems)
            {
                if(queryKey.Equals(key, StringComparison.OrdinalIgnoreCase))
                    return QueryItems.GetValues(key).First(); // There might be multiple keys of the same name, but just return the first match
            }
            return null;
        }

How do I read a specified line in a text file?

No unfortunately there is not. At the raw level files do not work on a line number basis. Instead they work at a position / offset basis. The root filesystem has no concept of lines. It's a concept added by higher level components.

So there is no way to tell the operating system, please open file at line blah. Instead you have to open the file and skip around counting new lines until you've passed the specified number. Then store the next set of bytes into an array until you hit the next new line.

How to use multiple conditions (With AND) in IIF expressions in ssrs

Here is an example that should give you some idea..

=IIF(First(Fields!Gender.Value,"vw_BrgyClearanceNew")="Female" and 
(First(Fields!CivilStatus.Value,"vw_BrgyClearanceNew")="Married"),false,true)

I think you have to identify the datasource name or the table name where your data is coming from.

How to keep a Python script output window open?

`import sys,traceback
sys.exc_info()[0]
traceback.format_exc()
print("Press Enter to exit ...")
input()`

simply write the above code after your actual code. for eg. am taking input from user and print on console hence my code will be look like this -->

`import sys,traceback
nam=input("enter your name:")
print("your name is:-{}".format(nam)) #here all my actual working is done
sys.exc_info()[0]
traceback.format_exc()
print("Press Enter to exit ...")
input()`

Perl - Multiple condition if statement without duplicating code?

if (   ($name eq "tom" and $password eq "123!")
    or ($name eq "frank" and $password eq "321!")) {

    print "You have gained access.";
}
else {
    print "Access denied!";
}

MySQL - Replace Character in Columns

If you have "something" and need 'something', use replace(col, "\"", "\'") and viceversa.

Can an ASP.NET MVC controller return an Image?

Look at ContentResult. This returns a string, but can be used to make your own BinaryResult-like class.

git push vs git push origin <branchname>

First, you need to create your branch locally

git checkout -b your_branch

After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it

git push -u origin your_branch

Your Teammates/colleagues can push to your branch by doing commits and then push explicitly

... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch 

What's "P=NP?", and why is it such a famous question?

There is not much I can add to the what and why of the P=?NP part of the question, but in regards to the proof. Not only would a proof be worth some extra credit, but it would solve one of the Millennium Problems. An interesting poll was recently conducted and the published results (PDF) are definitely worth reading in regards to the subject of a proof.

How to Get a Specific Column Value from a DataTable?

As per the title of the post I just needed to get all values from a specific column. Here is the code I used to achieve that.

    public static IEnumerable<T> ColumnValues<T>(this DataColumn self)
    {
        return self.Table.Select().Select(dr => (T)Convert.ChangeType(dr[self], typeof(T)));
    }

Closing Twitter Bootstrap Modal From Angular Controller

We can achieve the same without using angular-ui. This can be done using angular directives.

First add the directive to the modal.

<div class="modal fade" my-modal ....>...</div>

Create a new angular directive:

app.directive('myModal', function() {
   return {
     restrict: 'A',
     link: function(scope, element, attr) {
       scope.dismiss = function() {
           element.modal('hide');
       };
     }
   } 
});

Now call the dismiss() method from your controller.

app.controller('MyCtrl', function($scope, $http) {
    // You can call dismiss() here
    $scope.dismiss();
});

I am still in my early days with angular js. I know that we should not manipulate the DOM inside the controllers. So I have the DOM manipulation in the directive. I am not sure if this is equally bad. If I have a better alternative, I shall post it here.

The important thing to note is that we cannot simply use ng-hide or ng-show in the view to hide or show the modal. That simply hides the modal and not the modal backdrop. We have to call the modal() instance method to completely remove the modal.

jQuery - find child with a specific class

$(this).find(".bgHeaderH2").html();

or

$(this).find(".bgHeaderH2").text();

Why am I getting "Thread was being aborted" in ASP.NET?

If you spawn threads in Application_Start, they will still be executing in the application pool's AppDomain.

If an application is idle for some time (meaning that no requests are coming in), or certain other conditions are met, ASP.NET will recycle the entire AppDomain.

When that happens, any threads that you started from that AppDomain, including those from Application_Start, will be aborted.

Lots more on application pools and recycling in this question: What exactly is Appdomain recycling

If you are trying to run a long-running process within IIS/ASP.NET, the short answer is usually "Don't". That's what Windows Services are for.

Illegal mix of collations error in MySql

SELECT  username, AVG(rating) as TheAverage, COUNT(*) as TheCount
FROM    ratings
        WHERE month='Aug'
        AND username COLLATE latin1_general_ci IN
        (
        SELECT  username
        FROM    users
        WHERE   gender = 1
        )
GROUP BY
        username
HAVING
        TheCount > 4
ORDER BY
        TheAverage DESC, TheCount DESC;

Is there a shortcut to make a block comment in Xcode?

UPDATE: Xcode 8 Update

Now with xcode 8 you can do:

? + ? + /

Note: Below method will not work in xcode version => 8

Very simple steps to add Block Comment functionality to any editor of mac OS X

  1. Open Automator
  2. Choose Services
  3. Search Run Shell Script and double click it

Add the below applescript in textarea

awk 'BEGIN{print "/*"}{print $0}END{print "*/"}'

apple script for block comment

  1. Save script as Block Comment

Add a keyboard shortcut

Open System Preference > Keyboard > Shortcuts, add new shortcut by clicking + and right the same name i.e. Block Comment as you given to applescript in the 4th step. Add your Keyboard Shortcut and click Add button.

New keyboard shortcut

Now you should be able to use block comment in Xcode or any other editor, select some text, use your shortcut key to block comment any line of code or right click, the context menu, and the name you gave to this script should show near the bottom.

Call a function after previous function is complete

you can do it like this

$.when(funtion1()).then(function(){
    funtion2();
})

How to get current screen width in CSS?

Use the CSS3 Viewport-percentage feature.

Viewport-Percentage Explanation

Assuming you want the body width size to be a ratio of the browser's view port. I added a border so you can see the body resize as you change your browser width or height. I used a ratio of 90% of the view-port size.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <title>Styles</title>_x000D_
_x000D_
    <style>_x000D_
        @media screen and (min-width: 480px) {_x000D_
            body {_x000D_
                background-color: skyblue;_x000D_
                width: 90vw;_x000D_
                height: 90vh;_x000D_
                border: groove black;_x000D_
            }_x000D_
_x000D_
            div#main {_x000D_
                font-size: 3vw;_x000D_
            }_x000D_
        }_x000D_
    </style>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
    <div id="main">_x000D_
        Viewport-Percentage Test_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How can I use grep to show just filenames on Linux?

For a simple file search you could use grep's -l and -r options:

grep -rl "mystring"

All the search is done by grep. Of course, if you need to select files on some other parameter, find is the correct solution:

find . -iname "*.php" -execdir grep -l "mystring" {} +

The execdir option builds each grep command per each directory, and concatenates filenames into only one command (+).

conditional Updating a list using LINQ

        li.Where(w => w.name == "di" )
          .Select(s => { s.age = 10; return s; })
          .ToList();

In Gradle, is there a better way to get Environment Variables?

Well; this works as well:

home = "$System.env.HOME"

It's not clear what you're aiming for.

Entity framework left join

If you prefer method call notation, you can force a left join using SelectMany combined with DefaultIfEmpty. At least on Entity Framework 6 hitting SQL Server. For example:

using(var ctx = new MyDatabaseContext())
{
    var data = ctx
    .MyTable1
    .SelectMany(a => ctx.MyTable2
      .Where(b => b.Id2 == a.Id1)
      .DefaultIfEmpty()
      .Select(b => new
      {
        a.Id1,
        a.Col1,
        Col2 = b == null ? (int?) null : b.Col2,
      }));
}

(Note that MyTable2.Col2 is a column of type int). The generated SQL will look like this:

SELECT 
    [Extent1].[Id1] AS [Id1], 
    [Extent1].[Col1] AS [Col1], 
    CASE WHEN ([Extent2].[Col2] IS NULL) THEN CAST(NULL AS int) ELSE  CAST( [Extent2].[Col2] AS int) END AS [Col2]
    FROM  [dbo].[MyTable1] AS [Extent1]
    LEFT OUTER JOIN [dbo].[MyTable2] AS [Extent2] ON [Extent2].[Id2] = [Extent1].[Id1]

How can I find the length of a number?

A way for integers without banal converting to string:

var num = 9999999999; // your number
var length = 1;
while (num >= 10) {
   num /= 10;
   length++;
}
alert(length);

Reading HTML content from a UIWebView

if you want to extract the contents of an already-loaded UIWebView, -stringByEvaluatingJavaScriptFromString. For example:

NSString  *html = [webView stringByEvaluatingJavaScriptFromString: @"document.body.innerHTML"];

How to use andWhere and orWhere in Doctrine?

Why not just

$q->where("a = 1");
$q->andWhere("b = 1 OR b = 2");
$q->andWhere("c = 1 OR d = 2");

EDIT: You can also use the Expr class (Doctrine2).

How can I keep Bootstrap popovers alive while being hovered?

I agree that the best way is to use the one given by: David Chase, Cu Ly, and others that the simplest way to do this is to use the container: $(this) property as follows:

$(selectorString).each(function () {
  var $this = $(this);
  $this.popover({
    html: true,
    placement: "top",
    container: $this,
    trigger: "hover",
    title: "Popover",
    content: "Hey, you hovered on element"
  });
});

I want to point out here that the popover in this case will inherit all properties of the current element. So, for example, if you do this for a .btn element(bootstrap), you won't be able to select text inside the popover. Just wanted to record that since I spent quite some time banging my head on this.

how can I debug a jar at runtime?

Even though it is a runnable jar, you can still run it from a console -- open a terminal window, navigate to the directory containing the jar, and enter "java -jar yourJar.jar". It will run in that terminal window, and sysout and syserr output will appear there, including stack traces from uncaught exceptions. Be sure to have your debug set to true when you compile. And good luck.


Just thought of something else -- if you're on Win7, it often has permission problems with user applications writing files to specific directories. Make sure the directory to which you are writing your output file is one for which you have permissions.

In a future project, if it's big enough, you can use one of the standard logging facilities for 'debug' output; then it will be easy(ier) to redirect it to a file instead of depending on having a console. But for a smaller job like this, this should be fine.

Keep the order of the JSON keys during JSON conversion to CSV

Underscore-java keeps orders for elements while reading json. I am the maintainer of the project.

String json = "{\n"
      + "    \"items\":\n"
      + "    [\n"
      + "        {\n"
      + "            \"WR\":\"qwe\",\n"
      + "            \"QU\":\"asd\",\n"
      + "            \"QA\":\"end\",\n"
      + "            \"WO\":\"hasd\",\n"
      + "            \"NO\":\"qwer\"\n"
      + "        }\n"
      + "    ]\n"
      + "}";
System.out.println(U.fromJson(json));

// {items=[{WR=qwe, QU=asd, QA=end, WO=hasd, NO=qwer}]}

convert '1' to '0001' in JavaScript

Just to demonstrate the flexibility of javascript: you can use a oneliner for this

function padLeft(nr, n, str){
    return Array(n-String(nr).length+1).join(str||'0')+nr;
}
//or as a Number prototype method:
Number.prototype.padLeft = function (n,str){
    return Array(n-String(this).length+1).join(str||'0')+this;
}
//examples
console.log(padLeft(23,5));       //=> '00023'
console.log((23).padLeft(5));     //=> '00023'
console.log((23).padLeft(5,' ')); //=> '   23'
console.log(padLeft(23,5,'>>'));  //=> '>>>>>>23'

If you want to use this for negative numbers also:

Number.prototype.padLeft = function (n,str) {
    return (this < 0 ? '-' : '') + 
            Array(n-String(Math.abs(this)).length+1)
             .join(str||'0') + 
           (Math.abs(this));
}
console.log((-23).padLeft(5));     //=> '-00023'

Alternative if you don't want to use Array:

number.prototype.padLeft = function (len,chr) {
 var self = Math.abs(this)+'';
 return (this<0 && '-' || '')+
         (String(Math.pow( 10, (len || 2)-self.length))
           .slice(1).replace(/0/g,chr||'0') + self);
}

Angular JS break ForEach

break isn't possible to achieve in angular forEach, we need to modify forEach to do that.

$scope.myuser = [{name: "Ravi"}, {name: "Bhushan"}, {name: "Thakur"}];  
                angular.forEach($scope.myuser, function(name){
                  if(name == "Bhushan") {
                    alert(name);
                    return forEach.break(); 
                    //break() is a function that returns an immutable object,e.g. an empty string
                  }
                });

Variable length (Dynamic) Arrays in Java

You can't change the size of an array. You can, however, create a new array with the right size and copy the data from the old array to the new.

But your best option is to use IntList from jacarta commons. (here)

It works just like a List but takes less space and is more efficient than that, because it stores int's instead of storing wrapper objects over int's (that's what the Integer class is).

Eclipse interface icons very small on high resolution screen in Windows 8.1

For anyone seeing this after upgrading their Windows 10 (post April 2018 update), the DPI Scaling Override setting has moved into a dedicated window:

enter image description here

enter image description here

missing private key in the distribution certificate on keychain

To add on to others' answers, if you don't have access to that private key anymore it's fairly simple to get back up and running:

  1. revoke your active certificate in the provisioning portal
  2. create new developer certificate (keychain access/.../request for csr...etc.)
  3. download and install a new certificate
  4. create a new provisioning profile for existing app id (on provisioning portal)
  5. download and install new provisioning profile and in the build, settings set the appropriate code signing identities

Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?

This is an old post but maybe this could help people to complete the CORS problem. To complete the basic authorization problem you should avoid authorization for OPTIONS requests in your server. This is an Apache configuration example. Just add something like this in your VirtualHost or Location.

<LimitExcept OPTIONS>
    AuthType Basic
    AuthName <AUTH_NAME>
    Require valid-user
    AuthUserFile <FILE_PATH>
</LimitExcept>

How can I sort a std::map first by value, then by key?

EDIT: The other two answers make a good point. I'm assuming that you want to order them into some other structure, or in order to print them out.

"Best" can mean a number of different things. Do you mean "easiest," "fastest," "most efficient," "least code," "most readable?"

The most obvious approach is to loop through twice. On the first pass, order the values:

if(current_value > examined_value)
{
    current_value = examined_value
    (and then swap them, however you like)
}

Then on the second pass, alphabetize the words, but only if their values match.

if(current_value == examined_value)
{
    (alphabetize the two)
}

Strictly speaking, this is a "bubble sort" which is slow because every time you make a swap, you have to start over. One "pass" is finished when you get through the whole list without making any swaps.

There are other sorting algorithms, but the principle would be the same: order by value, then alphabetize.

What is "android:allowBackup"?

This is not explicitly mentioned, but based on the following docs, I think it is implied that an app needs to declare and implement a BackupAgent in order for data backup to work, even in the case when allowBackup is set to true (which is the default value).

http://developer.android.com/reference/android/R.attr.html#allowBackup http://developer.android.com/reference/android/app/backup/BackupManager.html http://developer.android.com/guide/topics/data/backup.html

Colorizing text in the console with C++

Assuming you're talking about a Windows console window, look up the console functions in the MSDN Library documentation.

Otherwise, or more generally, it depends on the console. Colors are not supported by the C++ library. But a library for console handling may/will support colors. E.g. google "ncurses colors".

For connected serial terminals and terminal emulators you can control things by outputting "escape sequences". These typically start with ASCII 27 (the escape character in ASCII). There is an ANSI standard and a lot of custom schemes.

Centering a div block without the width

Slight variation on Mike M. Lin's answer

If you add overflow: auto; ( or hidden ) to div.product_container, then you don't need div.clear.

This is derived from this article -> http://www.quirksmode.org/css/clearing.html

Here is modified HTML:

<div class="product_container">
    <div class="outer-center">
        <div class="product inner-center">
        </div>
    </div>
</div>

And here is modified CSS:

.product_container {
  overflow: auto;
  /* width property only required if you want to support IE6 */
  width: 100%;
}

.outer-center {
  float: right;
  right: 50%;
  position: relative;
}

.inner-center {
  float: right;
  right: -50%;
  position: relative;
}

The reason, why it's better without div.clear (apart that it feels wrong to have an empty element) is Firefox'es overzealous margin assignment.

If, for example, you have this html:

<div class="product_container">
    <div class="outer-center">
        <div class="product inner-center">
        </div>
    </div>
    <div style="clear: both;"></div>
</div>
<p style="margin-top: 11px;">Some text</p>

then, in Firefox (8.0 at the point of writing), you will see 11px margin before product_container. What's worse, is that you will get a vertical scroll bar for the whole page, even if the content fits nicely into the screen dimensions.

Execute curl command within a Python script

You can use below code snippet

import shlex
import subprocess
import json

def call_curl(curl):
    args = shlex.split(curl)
    process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()
    return json.loads(stdout.decode('utf-8'))


if __name__ == '__main__':
    curl = '''curl - X
    POST - d
    '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}'
    http: // localhost: 8080 / firewall / rules / 0000000000000001 '''
    output = call_curl(curl)
    print(output)

Get city name using geolocation

Another approach to this is to use my service, http://ipinfo.io, which returns the city, region and country name based on the user's current IP address. Here's a simple example:

$.get("http://ipinfo.io", function(response) {
    console.log(response.city, response.country);
}, "jsonp");

Here's a more detailed JSFiddle example that also prints out the full response information, so you can see all of the available details: http://jsfiddle.net/zK5FN/2/

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

How do I set the default page of my application in IIS7?

Karan has posted the answer but that didn't work for me. So, I am posting what worked for me. If that didn't work then user can try this

<configuration> 
    <system.webServer> 
        <defaultDocument enabled="true"> 
            <files> 
                <add value="myFile.aspx" /> 
            </files> 
        </defaultDocument> 
    </system.webServer>
</configuration> 

How can I create a text box for a note in markdown?

Another solution is to use CSS adjacency and use h4 (or higher):

#### note

This is the note content
h4 {
  display: none; /* hide */
}

h4 + p {
  /* style the note however you want */
}

How to run DOS/CMD/Command Prompt commands from VB.NET?

You could try this method:

Public Class MyUtilities
    Shared Sub RunCommandCom(command as String, arguments as String, permanent as Boolean) 
        Dim p as Process = new Process() 
        Dim pi as ProcessStartInfo = new ProcessStartInfo() 
        pi.Arguments = " " + if(permanent = true, "/K" , "/C") + " " + command + " " + arguments 
        pi.FileName = "cmd.exe" 
        p.StartInfo = pi 
        p.Start() 
    End Sub
End Class

call, for example, in this way:

MyUtilities.RunCommandCom("DIR", "/W", true)

EDIT: For the multiple command on one line the key are the & | && and || command connectors

  • A & B → execute command A, then execute command B.
  • A | B → execute command A, and redirect all it's output into the input of command B.
  • A && B → execute command A, evaluate the errorlevel after running Command A, and if the exit code (errorlevel) is 0, only then execute command B.
  • A || B → execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute command B.

How to get the number of characters in a std::string?

for an actual string object:

yourstring.length();

or

yourstring.size();

PostgreSQL next value of the sequences?

If your are not in a session you can just nextval('you_sequence_name') and it's just fine.

Mosaic Grid gallery with dynamic sized images

I think you can try "Google Grid Gallery", it based on aforementioned Masonry with some additions, like styles and viewer.

Javascript switch vs. if...else if...else

Pointy's answer suggests the use of an object literal as an alternative to switch or if/else. I like this approach too, but the code in the answer creates a new map object every time the dispatch function is called:

function dispatch(funCode) {
  var map = {
    'explode': function() {
      prepExplosive();
      if (flammable()) issueWarning();
      doExplode();
    },

    'hibernate': function() {
      if (status() == 'sleeping') return;
      // ... I can't keep making this stuff up
    },
    // ...
  };

  var thisFun = map[funCode];
  if (thisFun) thisFun();
}

If map contains a large number of entries, this can create significant overhead. It's better to set up the action map only once and then use the already-created map each time, for example:

var actions = {
    'explode': function() {
        prepExplosive();
        if( flammable() ) issueWarning();
        doExplode();
    },

    'hibernate': function() {
        if( status() == 'sleeping' ) return;
        // ... I can't keep making this stuff up
    },
    // ...
};

function dispatch( name ) {
    var action = actions[name];
    if( action ) action();
}

How to break out of while loop in Python?

Walrus operator (assignment expressions added to python 3.8) and while-loop-else-clause can do it more pythonic:

myScore = 0
while ans := input("Roll...").lower() == "r":
    # ... do something
else:
    print("Now I'll see if I can break your score...")

How to get a index value from foreach loop in jstl

I face Similar problem now I understand we have some more option : varStatus="loop", Here will be loop will variable which will hold the index of lop.

It can use for use to read for Zeor base index or 1 one base index.

${loop.count}` it will give 1 starting base index.

${loop.index} it will give 0 base index as normal Index of array start from 0.

For Example :

<c:forEach var="currentImage" items="${cityBannerImages}" varStatus="loop">
<picture>
   <source srcset="${currentImage}" media="(min-width: 1000px)"></source>
   <source srcset="${cityMobileImages[loop.count]}" media="(min-width:600px)"></source>
   <img srcset="${cityMobileImages[loop.count]}" alt=""></img>
</picture>
</c:forEach>

For more Info please refer this link

Laravel 5.2 redirect back with success message

You can use laravel MessageBag to add our own messages to existing messages.

To use MessageBag you need to use:

use Illuminate\Support\MessageBag;

In the controller:

MessageBag $message_bag

$message_bag->add('message', trans('auth.confirmation-success'));

return redirect('login')->withSuccess($message_bag);

Hope it will help some one.

  • Adi

Show dialog from fragment?

 public void showAlert(){


     AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
     LayoutInflater inflater = getActivity().getLayoutInflater();
     View alertDialogView = inflater.inflate(R.layout.test_dialog, null);
     alertDialog.setView(alertDialogView);

     TextView textDialog = (TextView) alertDialogView.findViewById(R.id.text_testDialogMsg);
     textDialog.setText(questionMissing);

     alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
             dialog.cancel();
         }
     });
     alertDialog.show();

}

where .test_dialog is of xml custom

How to create cross-domain request?

In my experience the plugins worked with http but not with the latest httpClient. Also, configuring the CORS respsonse headers on the server wasn't really an option. So, I created a proxy.conf.json file to act as a proxy server.

Read more about this here: https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

below is my prox.conf.json file

{
  "/posts": {
    "target": "https://example.com",
    "secure": true,
    "pathRewrite": {
    "^/posts": ""
  },
    "changeOrigin": true
  }
}

I placed the proxy.conf.json file right next the the package.json file in the same directory

then I modified the start command in the package.json file like below

"start": "ng serve --proxy-config proxy.conf.json"

now, the http call from my app component is as follows

return this._http.get('/posts/pictures?method=GetPictures')
.subscribe((returnedStuff) => {
  console.log(returnedStuff);
});

Lastly to run my app, I'd have to use npm start or ng serve --proxy-config proxy.conf.json

Align the form to the center in Bootstrap 4

You need to use the various Bootstrap 4 centering methods...

  • Use text-center for inline elements.
  • Use justify-content-center for flexbox elements (ie; form-inline)

https://codeply.com/go/Am5LvvjTxC

Also, to offset the column, the col-sm-* must be contained within a .row, and the .row must be in a container...

<section id="cover">
    <div id="cover-caption">
        <div id="container" class="container">
            <div class="row">
                <div class="col-sm-10 offset-sm-1 text-center">
                    <h1 class="display-3">Welcome to Bootstrap 4</h1>
                    <div class="info-form">
                        <form action="" class="form-inline justify-content-center">
                            <div class="form-group">
                                <label class="sr-only">Name</label>
                                <input type="text" class="form-control" placeholder="Jane Doe">
                            </div>
                            <div class="form-group">
                                <label class="sr-only">Email</label>
                                <input type="text" class="form-control" placeholder="[email protected]">
                            </div>
                            <button type="submit" class="btn btn-success ">okay, go!</button>
                        </form>
                    </div>
                    <br>

                    <a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">?</a>
                </div>
            </div>
        </div>
    </div>
</section>

How Can I Resolve:"can not open 'git-upload-pack' " error in eclipse?

......../info/refs?service=git-upload-pack not found: did you run git update-server-info on the server?

For me the issue was a password issue. I run Keychain and deleted Github passwords. I run the pull command after that and it asked me for username and password. After that it worked ok.

Inconsistent Accessibility: Parameter type is less accessible than method

Make the class public.

class NewClass
{

}

is the same as:

internal class NewClass
{

}

so the class has to be public

go to character in vim

:goto 21490 will take you to the 21490th byte in the buffer.

Yum fails with - There are no enabled repos.

ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.

But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:

sudo apt-get install libstdc++.i686

Configuring ObjectMapper in Spring

It may be because I'm using Spring 3.1 (instead of Spring 3.0.5 as your question specified), but Steve Eastwood's answer didn't work for me. This solution works for Spring 3.1:

In your spring xml context:

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
        <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
            <property name="objectMapper" ref="jacksonObjectMapper" />
        </bean>        
    </mvc:message-converters>
</mvc:annotation-driven>

<bean id="jacksonObjectMapper" class="de.Company.backend.web.CompanyObjectMapper" />

Uncaught TypeError: Cannot read property 'msie' of undefined - jQuery tools

Use like blow

i use this command and solve

"Uncaught TypeError: Cannot read property 'msie' of undefined" Error

if (/1\.(0|1|2)\.(0|1|2)/.test($.fn.jquery) || /^1.1/.test($.fn.jquery)) {
    return;
}

Compare objects in Angular

I know it's kinda late answer but I just lost about half an hour debugging cause of this, It might save someone some time.

BE MINDFUL, If you use angular.equals() on objects that have property obj.$something (property name starts with $) those properties will get ignored in comparison.

Example:

var obj1 = {
  $key0: "A",
  key1: "value1",
  key2: "value2",
  key3: {a: "aa", b: "bb"}
}

var obj2 = {
  $key0: "B"
  key2: "value2",
  key1: "value1",
  key3: {a: "aa", b: "bb"}
}

angular.equals(obj1, obj2) //<--- would return TRUE (despite it's not true)

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

Android: I lost my android key store, what should I do?

Brute Force is the only way!

Here is a script that helped me out:

https://code.google.com/p/android-keystore-password-recover/wiki/HowTo

Using a list of 5-10 possible words from memory, it recovered my password in <1 sec.

Vue v-on:click does not work on component

As mentioned by Chris Fritz (Vue.js Core Team Emeriti) in VueCONF US 2019

if we had Kia enter .native and then the root element of the base input changed from an input to a label suddenly this component is broken and it's not obvious and in fact, you might not even catch it right away unless you have a really good test. Instead by avoiding the use of the .native modifier which I currently consider an anti-pattern will be removed in Vue 3 you'll be able to explicitly define that the parent might care about which element listeners are added to...

With Vue 2

Using $listeners:

So, if you are using Vue 2 a better option to resolve this issue would be to use a fully transparent wrapper logic. For this Vue provides a $listeners property containing an object of listeners being used on the component. For example:

{
  focus: function (event) { /* ... */ }
  input: function (value) { /* ... */ },
}

and then we just need to add v-on="$listeners" to the test component like:

Test.vue (child component)

<template>
  <div v-on="$listeners">
    click here
  </div>
</template>

Now the <test> component is a fully transparent wrapper, meaning it can be used exactly like a normal <div> element: all the listeners will work, without the .native modifier.

Demo:

_x000D_
_x000D_
Vue.component('test', {_x000D_
  template: `_x000D_
    <div class="child" v-on="$listeners">_x000D_
      Click here_x000D_
    </div>`_x000D_
})_x000D_
_x000D_
new Vue({_x000D_
  el: "#myApp",_x000D_
  data: {},_x000D_
  methods: {_x000D_
    testFunction: function(event) {_x000D_
      console.log('test clicked')_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
div.child{border:5px dotted orange; padding:20px;}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>_x000D_
<div id="myApp">_x000D_
  <test @click="testFunction"></test>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using $emit method:

We can also use $emit method for this purpose, which helps us to listen to child components events in parent component. For this, we first need to emit a custom event from child component like:

Test.vue (child component)

<test @click="$emit('my-event')"></test>

Important: Always use kebab-case for event names. For more information and demo regading this point please check out this answer: VueJS passing computed value from component to parent.

Now, we just need to listen to this emitted custom event in parent component like:

App.vue

<test @my-event="testFunction"></test>

So, basically instead of v-on:click or the shorthand @click we will simply use v-on:my-event or just @my-event.

Demo:

_x000D_
_x000D_
Vue.component('test', {_x000D_
  template: `_x000D_
    <div class="child" @click="$emit('my-event')">_x000D_
      Click here_x000D_
    </div>`_x000D_
})_x000D_
_x000D_
new Vue({_x000D_
  el: "#myApp",_x000D_
  data: {},_x000D_
  methods: {_x000D_
    testFunction: function(event) {_x000D_
      console.log('test clicked')_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
div.child{border:5px dotted orange; padding:20px;}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>_x000D_
<div id="myApp">_x000D_
  <test @my-event="testFunction"></test>_x000D_
</div>
_x000D_
_x000D_
_x000D_


With Vue 3

Using v-bind="$attrs":

Vue 3 is going to make our life much easier in many ways. One of the examples for it is that it will help us to create a simpler transparent wrapper with very less config by just using v-bind="$attrs". By using this on child components not only our listener will work directly from the parent but also any other attribute will also work just like it a normal <div> only.

So, with respect to this question, we will not need to update anything in Vue 3 and your code will still work fine as <div> is the root element here and it will automatically listen to all child events.

Demo #1:

_x000D_
_x000D_
const { createApp } = Vue;_x000D_
_x000D_
const Test = {_x000D_
  template: `_x000D_
    <div class="child">_x000D_
      Click here_x000D_
    </div>`_x000D_
};_x000D_
_x000D_
const App = {_x000D_
  components: { Test },_x000D_
  setup() {_x000D_
    const testFunction = event => {_x000D_
      console.log("test clicked");_x000D_
    };_x000D_
    return { testFunction };_x000D_
  }_x000D_
};_x000D_
_x000D_
createApp(App).mount("#myApp");
_x000D_
div.child{border:5px dotted orange; padding:20px;}
_x000D_
<script src="//unpkg.com/vue@next"></script>_x000D_
<div id="myApp">_x000D_
  <test v-on:click="testFunction"></test>_x000D_
</div>
_x000D_
_x000D_
_x000D_

But for complex components with nested elements where we need to apply attributes and events to main <input /> instead of the parent label we can simply use v-bind="$attrs"

Demo #2:

_x000D_
_x000D_
const { createApp } = Vue;_x000D_
_x000D_
const BaseInput = {_x000D_
  props: ['label', 'value'],_x000D_
  template: `_x000D_
    <label>_x000D_
      {{ label }}_x000D_
      <input v-bind="$attrs">_x000D_
    </label>`_x000D_
};_x000D_
_x000D_
const App = {_x000D_
  components: { BaseInput },_x000D_
  setup() {_x000D_
    const search = event => {_x000D_
      console.clear();_x000D_
      console.log("Searching...", event.target.value);_x000D_
    };_x000D_
    return { search };_x000D_
  }_x000D_
};_x000D_
_x000D_
createApp(App).mount("#myApp");
_x000D_
input{padding:8px;}
_x000D_
<script src="//unpkg.com/vue@next"></script>_x000D_
<div id="myApp">_x000D_
  <base-input _x000D_
    label="Search: "_x000D_
    placeholder="Search"_x000D_
    @keyup="search">_x000D_
  </base-input><br/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Find which version of package is installed with pip

In question, it is not mentioned which OS user is using (Windows/Linux/Mac)

As there are couple of answers which will work flawlessly on Mac and Linux.

Below command can be used in case the user is trying to find the version of a python package on windows.

In PowerShell use below command :

pip list | findstr <PackageName>

Example:- pip list | findstr requests

Output : requests 2.18.4

How to log Apache CXF Soap Request and Soap Response using Log4j?

This worked for me.

Setup log4j as normal. Then use this code:

    // LOGGING 
    LoggingOutInterceptor loi = new LoggingOutInterceptor(); 
    loi.setPrettyLogging(true); 
    LoggingInInterceptor lii = new LoggingInInterceptor(); 
    lii.setPrettyLogging(true); 

    org.apache.cxf.endpoint.Client client = org.apache.cxf.frontend.ClientProxy.getClient(isalesService); 
    org.apache.cxf.endpoint.Endpoint cxfEndpoint = client.getEndpoint(); 

    cxfEndpoint.getOutInterceptors().add(loi); 
    cxfEndpoint.getInInterceptors().add(lii);

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

Even when you asked finally for the opposite, to reform 0s and 1s into Trues and Falses, however, I post an answer about how to transform falses and trues into ones and zeros (1s and 0s), for a whole dataframe, in a single line.

Example given

df <- structure(list(p1_1 = c(TRUE, FALSE, FALSE, NA, TRUE, FALSE, 
                NA), p1_2 = c(FALSE, TRUE, FALSE, NA, FALSE, NA, 
                TRUE), p1_3 = c(TRUE, 
                TRUE, FALSE, NA, NA, FALSE, TRUE), p1_4 = c(FALSE, NA, 
                FALSE,  FALSE, TRUE, FALSE, NA), p1_5 = c(TRUE, NA, 
                FALSE, TRUE, FALSE, NA, TRUE), p1_6 = c(TRUE, NA, 
                FALSE, TRUE, FALSE, NA, TRUE), p1_7 = c(TRUE, NA, 
                FALSE, TRUE, NA, FALSE, TRUE), p1_8 = c(FALSE, 
                FALSE, NA, FALSE, TRUE, FALSE, NA), p1_9 = c(TRUE, 
                FALSE,  NA, FALSE, FALSE, NA, TRUE), p1_10 = c(TRUE, 
                FALSE, NA, FALSE, FALSE, NA, TRUE), p1_11 = c(FALSE, 
                FALSE, NA, FALSE, NA, FALSE, TRUE)), .Names = 
                c("p1_1", "p1_2", "p1_3", "p1_4", "p1_5", "p1_6", 
                "p1_7", "p1_8", "p1_9", "p1_10", "p1_11"), row.names = 
                 c(NA, -7L), class = "data.frame")

   p1_1  p1_2  p1_3  p1_4  p1_5  p1_6  p1_7  p1_8  p1_9 p1_10 p1_11
1  TRUE FALSE  TRUE FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE FALSE
2 FALSE  TRUE  TRUE    NA    NA    NA    NA FALSE FALSE FALSE FALSE
3 FALSE FALSE FALSE FALSE FALSE FALSE FALSE    NA    NA    NA    NA
4    NA    NA    NA FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE
5  TRUE FALSE    NA  TRUE FALSE FALSE    NA  TRUE FALSE FALSE    NA
6 FALSE    NA FALSE FALSE    NA    NA FALSE FALSE    NA    NA FALSE
7    NA  TRUE  TRUE    NA  TRUE  TRUE  TRUE    NA  TRUE  TRUE  TRUE

Then by running that: df * 1 all Falses and Trues are trasnformed into 1s and 0s. At least, this was happen in the R version that I have (R version 3.4.4 (2018-03-15) ).

> df*1
  p1_1 p1_2 p1_3 p1_4 p1_5 p1_6 p1_7 p1_8 p1_9 p1_10 p1_11
1    1    0    1    0    1    1    1    0    1     1     0
2    0    1    1   NA   NA   NA   NA    0    0     0     0
3    0    0    0    0    0    0    0   NA   NA    NA    NA
4   NA   NA   NA    0    1    1    1    0    0     0     0
5    1    0   NA    1    0    0   NA    1    0     0    NA
6    0   NA    0    0   NA   NA    0    0   NA    NA     0
7   NA    1    1   NA    1    1    1   NA    1     1     1

I do not know if it a total "safe" command, under all different conditions / dfs.

Seeing the console's output in Visual Studio 2010?

System.Diagnostics.Debug.WriteLine() will work, but you have to be looking in the right place for the output. In Visual Studio 2010, on the menu bar, click Debug -> Windows -> Output. Now, at the bottom of the screen docked next to your error list, there should be an output tab. Click it and double check it's showing output from the debug stream on the dropdown list.

P.S.: I think the output window shows on a fresh install, but I can't remember. If it doesn't, or if you closed it by accident, follow these instructions.

Java Security: Illegal key size or default parameters?

Default JDK supports encryption only through 128 bit keys becuase of American restrictions. So to support encryption from 256 bit long key we have to replace local_policy.jar and US_export_policy.jars in $JAVA_HOME/java-8-oracle/jre/lib/security folder otherwise it will give:

java.security.InvalidKeyException: Illegal key size or default

PHP display image BLOB from MySQL

Try Like this.

For Inserting into DB

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
//you keep your column name setting for insertion. I keep image type Blob.
$query = "INSERT INTO products (id,image) VALUES('','$image')";  
$qry = mysqli_query($db, $query);

For Accessing image From Blob

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';

Hope It will help you.

Thanks.

How to detect Adblock on my website?

You don't need an extra HTTP request , you may simply calculate the height of a fake add.

By the way, here is a full list matching the elements that adblockers avoid rendering.

_x000D_
_x000D_
window.adBlockRunning = function() {
    return (getComputedStyle(document.getElementById("detect"))["display"] == "none") ? true : false;
  }()

console.log(window.adBlockRunning);
_x000D_
#detect {
  height: 1px;
  width: 1px;
  position: absolute;
  left: -999em;
  top: -999em
}
_x000D_
<div id="detect" class="ads ad adsbox doubleclick ad-placement carbon-ads"></div>
_x000D_
_x000D_
_x000D_

AngularJS - Building a dynamic table based on a json

TGrid is another option that people don't usually find in a google search. If the other grids you find don't suit your needs, you can give it a try, its free

CSS On hover show another element

we just can show same label div on hovering like this

<style>
#b {
    display: none;
}

#content:hover~#b{
    display: block;
}

</style>

How to auto-reload files in Node.js?

Use this:

function reload_config(file) {
  if (!(this instanceof reload_config))
    return new reload_config(file);
  var self = this;

  self.path = path.resolve(file);

  fs.watchFile(file, function(curr, prev) {
    delete require.cache[self.path];
    _.extend(self, require(file));
  });

  _.extend(self, require(file));
}

All you have to do now is:

var config = reload_config("./config");

And config will automatically get reloaded :)

LINQ's Distinct() on a particular property

Please give a try with below code.

var Item = GetAll().GroupBy(x => x .Id).ToList();

.NET code to send ZPL to Zebra printers

VB Version (using port 9100 - tested on Zebra ZM400)

Sub PrintZPL(ByVal pIP As String, ByVal psZPL As String)
    Dim lAddress As Net.IPEndPoint
    Dim lSocket As System.Net.Sockets.Socket = Nothing
    Dim lNetStream As System.Net.Sockets.NetworkStream = Nothing
    Dim lBytes As Byte()

    Try
        lAddress = New Net.IPEndPoint(Net.IPAddress.Parse(pIP), 9100)
        lSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, _                       ProtocolType.Tcp)
        lSocket.Connect(lAddress)
        lNetStream = New NetworkStream(lSocket)

        lBytes = System.Text.Encoding.ASCII.GetBytes(psZPL)
        lNetStream.Write(lBytes, 0, lBytes.Length)
    Catch ex As Exception When Not App.Debugging
        Msgbox ex.message & vbnewline & ex.tostring
    Finally
        If Not lNetStream Is Nothing Then
            lNetStream.Close()
        End If
        If Not lSocket Is Nothing Then
            lSocket.Close()
        End If
    End Try
End Sub

Deploying my application at the root in Tomcat

You have a couple of options:

  1. Remove the out-of-the-box ROOT/ directory from tomcat and rename your war file to ROOT.war before deploying it.

  2. Deploy your war as (from your example) war_name.war and configure the context root in conf/server.xml to use your war file :

    <Context path="" docBase="war_name" debug="0" reloadable="true"></Context>
    

The first one is easier, but a little more kludgy. The second one is probably the more elegant way to do it.

Multiple inputs with same name through POST in php

Eric answer is correct, but the problem is the fields are not grouped. Imagine you have multiple streets and cities which belong together:

<h1>First Address</h1>
<input name="street[]" value="Hauptstr" />
<input name="city[]" value="Berlin"  />

<h2>Second Address</h2>
<input name="street[]" value="Wallstreet" />
<input name="city[]" value="New York" />

The outcome would be

$POST = [ 'street' => [ 'Hauptstr', 'Wallstreet'], 
          'city' => [ 'Berlin' , 'New York'] ];

To group them by address, I would rather recommend to use what Eric also mentioned in the comment section:

<h1>First Address</h1>
<input name="address[1][street]" value="Hauptstr" />
<input name="address[1][city]" value="Berlin"  />

<h2>Second Address</h2>
<input name="address[2][street]" value="Wallstreet" />
<input name="address[2][city]" value="New York" />

The outcome would be

$POST = [ 'address' => [ 
                 1 => ['street' => 'Hauptstr', 'city' => 'Berlin'],
                 2 => ['street' => 'Wallstreet', 'city' => 'New York'],
              ]
        ]

"java.lang.OutOfMemoryError : unable to create new native Thread"

I would recommend to also look at the Thread Stack Size and see if you get more threads created. The default Thread Stack Size for JRockit 1.5/1.6 is 1 MB for 64-bit VM on Linux OS. 32K threads will require a significant amount of physical and virtual memory to honor this requirement.

Try to reduce the Stack Size to 512 KB as a starting point and see if it helps creating more threads for your application. I also recommend to explore horizontal scaling e.g. splitting your application processing across more physical or virtual machines.

When using a 64-bit VM, the true limit will depend on the OS physical and virtual memory availability and OS tuning parameters such as ulimitc. I also recommend the following article as a reference:

OutOfMemoryError: unable to create new native thread – Problem Demystified

Reinitialize Slick js after successful ajax call

$('#slick-slider').slick('refresh'); //Working for slick 1.8.1

How to stop a JavaScript for loop?

I know this is a bit old, but instead of looping through the array with a for loop, it would be much easier to use the method <array>.indexOf(<element>[, fromIndex])

It loops through an array, finding and returning the first index of a value. If the value is not contained in the array, it returns -1.

<array> is the array to look through, <element> is the value you are looking for, and [fromIndex] is the index to start from (defaults to 0).

I hope this helps reduce the size of your code!

INSERT INTO @TABLE EXEC @query with SQL Server 2000

N.B. - this question and answer relate to the 2000 version of SQL Server. In later versions, the restriction on INSERT INTO @table_variable ... EXEC ... were lifted and so it doesn't apply for those later versions.


You'll have to switch to a temp table:

CREATE TABLE #tmp (code varchar(50), mount money)
DECLARE @q nvarchar(4000)
SET @q = 'SELECT coa_code, amount FROM T_Ledger_detail'

INSERT INTO  #tmp (code, mount)
EXEC sp_executesql (@q)

SELECT * from #tmp

From the documentation:

A table variable behaves like a local variable. It has a well-defined scope, which is the function, stored procedure, or batch in which it is declared.

Within its scope, a table variable may be used like a regular table. It may be applied anywhere a table or table expression is used in SELECT, INSERT, UPDATE, and DELETE statements. However, table may not be used in the following statements:

INSERT INTO table_variable EXEC stored_procedure

SELECT select_list INTO table_variable statements.

onCreateOptionsMenu inside Fragments

Your already have the autogenerated file res/menu/menu.xml defining action_settings.

In your MainActivity.java have the following methods:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch (id) {
        case R.id.action_settings:
            // do stuff, like showing settings fragment
            return true;
    }

    return super.onOptionsItemSelected(item); // important line
}

In the onCreateView() method of your Fragment call:

setHasOptionsMenu(true); 

and also add these 2 methods:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.fragment_menu, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch (id) {
        case R.id.action_1:
            // do stuff
            return true;

        case R.id.action_2:
            // do more stuff
            return true;
    }

    return false;
}

Finally, add the new file res/menu/fragment_menu.xml defining action_1 and action_2.

This way when your app displays the Fragment, its menu will contain 3 entries:

  • action_1 from res/menu/fragment_menu.xml
  • action_2 from res/menu/fragment_menu.xml
  • action_settings from res/menu/menu.xml

'if' in prolog?

You should read Learn Prolog Now! Chapter 10.2 Using Cut. This provides an example:

max(X,Y,Z) :- X =< Y,!, Y = Z.

to be said,

Z is equal to Y IF ! is true (which it always is) AND X is <= Y.

How to install lxml on Ubuntu

Since you're on Ubuntu, don't bother with those source packages. Just install those development packages using apt-get.

apt-get install libxml2-dev libxslt1-dev python-dev

If you're happy with a possibly older version of lxml altogether though, you could try

apt-get install python-lxml

and be done with it. :)

Get a list of numbers as input from the user

num = int(input('Size of elements : '))
arr = list()

for i in range(num) :
  ele  = int(input())
  arr.append(ele)

print(arr)

Disable Drag and Drop on HTML elements?

This is a fiddle I always use with my Web applications:

$('body').on('dragstart drop', function(e){
    e.preventDefault();
    return false;
});

It will prevent anything on your app being dragged and dropped. Depending on tour needs, you can replace body selector with any container that childrens should not be dragged.

Convert list to array in Java

This is works. Kind of.

public static Object[] toArray(List<?> a) {
    Object[] arr = new Object[a.size()];
    for (int i = 0; i < a.size(); i++)
        arr[i] = a.get(i);
    return arr;
}

Then the main method.

public static void main(String[] args) {
    List<String> list = new ArrayList<String>() {{
        add("hello");
        add("world");
    }};
    Object[] arr = toArray(list);
    System.out.println(arr[0]);
}

Resize font-size according to div size

In regards to your code, see @Coulton. You'll need to use JavaScript.

Checkout either FitText (it does work in IE, they just ballsed their site somehow) or BigText.

FitText will allow you to scale some text in relation to the container it is in, while BigText is more about resizing different sections of text to be the same width within the container.

BigText will set your string to exactly the width of the container, whereas FitText is less pixel perfect. It starts by setting the font-size at 1/10th of the container element's width. It doesn't work very well with all fonts by default, but it has a setting which allows you to decrease or increase the 'power' of the re-size. It also allows you to set a min and max font-size. It will take a bit of fiddling to get working the first time, but does work great.

http://marabeas.io <- playing with it currently here. As far as I understand, BigText wouldn't work in my context at all.

For those of you using Angularjs, here's an Angular version of FitText I've made.


Here's a LESS mixin you can use to make @humanityANDpeace's solution a little more pretty:

@mqIterations: 19;
.fontResize(@i) when (@i > 0) {
    @media all and (min-width: 100px * @i) { body { font-size:0.2em * @i; } }
    .fontResize((@i - 1));
}
.fontResize(@mqIterations);

And an SCSS version thanks to @NIXin!

$mqIterations: 19;
@mixin fontResize($iterations) { 
    $i: 1; 
    @while $i <= $iterations { 
        @media all and (min-width: 100px * $i) { body { font-size:0.2em * $i; } } 
        $i: $i + 1; 
    }
} 
@include fontResize($mqIterations);

std::string length() and size() member functions

length of string ==how many bits that string having, size==size of those bits, In strings both are same if the editor allocates size of character is 1 byte

Difference between string and StringBuilder in C#

From the StringBuilder Class documentation:

The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

What's the best practice for primary keys in tables?

Natural versus artificial keys to me is a matter of how much of the business logic you want in your database. Social Security number (SSN) is a great example.

"Each client in my database will, and must, have an SSN." Bam, done, make it the primary key and be done with it. Just remember when your business rule changes you're burned.

I don't like natural keys myself, due to my experience with changing business rules. But if your sure it won't change, it might prevent a few critical joins.

ISO time (ISO 8601) in Python

I've developed this function:

def iso_8601_format(dt):
    """YYYY-MM-DDThh:mm:ssTZD (1997-07-16T19:20:30-03:00)"""

    if dt is None:
        return ""

    fmt_datetime = dt.strftime('%Y-%m-%dT%H:%M:%S')
    tz = dt.utcoffset()
    if tz is None:
        fmt_timezone = "+00:00"
    else:
        fmt_timezone = str.format('{0:+06.2f}', float(tz.total_seconds() / 3600))

    return fmt_datetime + fmt_timezone

In Java, how do I call a base class's method from the overriding method in a derived class?

I am pretty sure that you can do it using Java Reflection mechanism. It is not as straightforward as using super but it gives you more power.

class A
{
    public void myMethod()
    { /* ... */ }
}

class B extends A
{
    public void myMethod()
    {
        super.myMethod(); // calling parent method
    }
}

How to convert Nvarchar column to INT

Your CAST() looks correct.

Your CONVERT() is not correct. You are quoting the column as a string. You will want something like

CONVERT(INT, A.my_NvarcharColumn)

** notice without the quotes **

The only other reason why this could fail is if you have a non-numeric character in the field value or if it's out of range.

You can try something like the following to verify it's numeric and return a NULL if it's not:

SELECT
 CASE
  WHEN ISNUMERIC(A.my_NvarcharColumn) = 1 THEN CONVERT(INT, A.my_NvarcharColumn)
  ELSE NULL
 END AS my_NvarcharColumn

oracle plsql: how to parse XML and insert into table

You can load an XML document into an XMLType, then query it, e.g.:

DECLARE
  x XMLType := XMLType(
    '<?xml version="1.0" ?> 
<person>
   <row>
       <name>Tom</name>
       <Address>
           <State>California</State>
           <City>Los angeles</City>
       </Address>
   </row>
   <row>
       <name>Jim</name>
       <Address>
           <State>California</State>
           <City>Los angeles</City>
       </Address>
   </row>
</person>');
BEGIN
  FOR r IN (
    SELECT ExtractValue(Value(p),'/row/name/text()') as name
          ,ExtractValue(Value(p),'/row/Address/State/text()') as state
          ,ExtractValue(Value(p),'/row/Address/City/text()') as city
    FROM   TABLE(XMLSequence(Extract(x,'/person/row'))) p
    ) LOOP
    -- do whatever you want with r.name, r.state, r.city
  END LOOP;
END;

How to pass data from 2nd activity to 1st activity when pressed back? - android

TL;DR Use Activity.startActivityForResult

Long answer:

You should start by reading the Android developer documentation. Specifically the topic of your question is covered in the Starting Activities and Getting Results section of the Activity documentation.

As for example code, the Android SDK provides good examples. Also, other answers here give you short snippets of sample code to use.

However, if you are looking for alternatives, read this SO question. This is a good discussion on how to use startActivityForResults with fragments, as well as couple othe approaches for passing data between activities.

Convert HH:MM:SS string to seconds only in javascript

This is the most clear, easy to understand solution:

_x000D_
_x000D_
function convertDurationtoSeconds(duration){
    const [hours, minutes, seconds] = duration.split(':');
    return Number(hours) * 60 * 60 + Number(minutes) * 60 + Number(seconds);
};

const input = '01:30:45';
const output = convertDurationtoSeconds(input);
console.log(`${input} is ${output} in seconds`);
_x000D_
_x000D_
_x000D_

Link to reload current page

Just add target="_blank" and the link will open a new page keeping the original page.

Javascript change font color

Html code

<div id="coloredBy">
    Colored By Santa
</div>

javascript code

document.getElementById("coloredBy").style.color = colorCode; // red or #ffffff

I think this is very easy to use

php return 500 error but no error log

For Symfony projects, be sure to check files in the project'es app/logs

More details available on this post :
How to debug 500 Error in Symfony 2

Btw, other frameworks or CMS share this kind of behaviour.

Why is Dictionary preferred over Hashtable in C#?

Notice that the documentation says: "the Dictionary<(Of <(TKey, TValue>)>) class is implemented as a hash table", not "the Dictionary<(Of <(TKey, TValue>)>) class is implemented as a HashTable"

Dictionary is NOT implemented as a HashTable, but it is implemented following the concept of a hash table. The implementation is unrelated to the HashTable class because of the use of Generics, although internally Microsoft could have used the same code and replaced the symbols of type Object with TKey and TValue.

In .NET 1.0 Generics did not exist; this is where the HashTable and ArrayList originally began.

SQLite select where empty?

Maybe you mean

select x
from some_table
where some_column is null or some_column = ''

but I can't tell since you didn't really ask a question.

ReferenceError: document is not defined (in plain JavaScript)

try: window.document......

var body = window.document.getElementsByTagName("body")[0];

opening html from google drive

A lot of the solutions offered here do not seem to work anymore. I'm currently on a chromebook and wanted to view an HTML5 banner. This seems impossible now through Google Drive or other apps (as mentioned in previous comments).

The method I ended up using to view the HTML5 was the following:

  1. Open Google Adwords (create a free account if you dont have one)
  2. Click on Ads in the top panel
  3. Click on "+AD" and choose image ad
  4. Choose "upload an ad"
  5. Drag and drop your zip file into the area
  6. Click on Preview
  7. Voila, you will see your HTML5 banners in their full beauty

There may well an easier way, but this way is pretty good too. Hope it helps and worked well for me.

Simple VBA selection: Selecting 5 cells to the right of the active cell

This example selects a new Range of Cells defined by the current cell to a cell 5 to the right.

Note that .Offset takes arguments of Offset(row, columns) and can be quite useful.


Sub testForStackOverflow()
    Range(ActiveCell, ActiveCell.Offset(0, 5)).Copy
End Sub

How to write lists inside a markdown table?

another solution , you can add <br> tag to your table

    |Method name| Behavior |
    |--|--|
    | OnAwakeLogicController(); | Its called when MainLogicController is loaded into the memory , its also hold the following actions :- <br> 1. Checking Audio Settings <br>2. Initializing Level Controller|

enter image description here

Div 100% height works on Firefox but not in IE

You might have to put one or both of:

html { height:100%; }

or

body { height:100%; }

EDIT: Whoops, didn't notice they were floated. You just need to float the container.

python - find index position in list based of partial string

spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"]

index=spell_list.index("Annual")
print(index)

Is there a Python equivalent of the C# null-coalescing operator?

Here's a function that will return the first argument that isn't None:

def coalesce(*arg):
  return reduce(lambda x, y: x if x is not None else y, arg)

# Prints "banana"
print coalesce(None, "banana", "phone", None)

reduce() might needlessly iterate over all the arguments even if the first argument is not None, so you can also use this version:

def coalesce(*arg):
  for el in arg:
    if el is not None:
      return el
  return None

Boxplot show the value of mean

First, you can calculate the group means with aggregate:

means <- aggregate(weight ~  group, PlantGrowth, mean)

This dataset can be used with geom_text:

library(ggplot2)
ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() +
  stat_summary(fun.y=mean, colour="darkred", geom="point", 
               shape=18, size=3,show_guide = FALSE) + 
  geom_text(data = means, aes(label = weight, y = weight + 0.08))

Here, + 0.08 is used to place the label above the point representing the mean.

enter image description here


An alternative version without ggplot2:

means <- aggregate(weight ~  group, PlantGrowth, mean)

boxplot(weight ~ group, PlantGrowth)
points(1:3, means$weight, col = "red")
text(1:3, means$weight + 0.08, labels = means$weight)

enter image description here

Recommended date format for REST GET API

REST doesn't have a recommended date format. Really it boils down to what works best for your end user and your system. Personally, I would want to stick to a standard like you have for ISO 8601 (url encoded).

If not having ugly URI is a concern (e.g. not including the url encoded version of :, -, in you URI) and (human) addressability is not as important, you could also consider epoch time (e.g. http://example.com/start/1331162374). The URL looks a little cleaner, but you certainly lose readability.

The /2012/03/07 is another format you see a lot. You could expand upon that I suppose. If you go this route, just make sure you're either always in GMT time (and make that clear in your documentation) or you might also want to include some sort of timezone indicator.

Ultimately it boils down to what works for your API and your end user. Your API should work for you, not you for it ;-).

Convert normal date to unix timestamp

You should check out the moment.js api, it is very easy to use and has lots of built in features.

I think for your problem, you could use something like this:

var unixTimestamp = moment('2012.08.10', 'YYYY.MM.DD').unix();

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

You need to add a metadata exchange (mex) endpoint to your service:

<services>
   <service name="MyService.MyService" behaviorConfiguration="metadataBehavior">
      <endpoint 
          address="http://localhost/MyService.svc" 
          binding="customBinding" bindingConfiguration="jsonpBinding" 
          behaviorConfiguration="MyService.MyService"
          contract="MyService.IMyService"/>
      <endpoint 
          address="mex" 
          binding="mexHttpBinding" 
          contract="IMetadataExchange"/>
   </service>
</services>

Now, you should be able to get metadata for your service

Update: ok, so you're just launching this from Visual Studio - in that case, it will be hosted in Cassini, the built-in web server. That beast however only supports HTTP - you're not using that protocol in your binding...

Also, since you're hosting this in Cassini, the address of your service will be dictated by Cassini - you don't get to define anything.

So my suggestion would be:

  • try to use http binding (just now for testing)
  • get this to work
  • once you know it works, change it to your custom binding and host it in IIS

So I would change the config to:

<behaviors>
   <serviceBehaviors>
      <behavior name="metadataBehavior">
         <serviceMetadata httpGetEnabled="true" />
      </behavior>
   </serviceBehaviors>
</behaviors>
<services>
   <service name="MyService.MyService" behaviorConfiguration="metadataBehavior">
      <endpoint 
          address=""   <!-- don't put anything here - Cassini will determine address -->
          binding="basicHttpBinding" 
          contract="MyService.IMyService"/>
      <endpoint 
          address="mex" 
          binding="mexHttpBinding" 
          contract="IMetadataExchange"/>
   </service>
</services>

Once you have that, try to do a View in Browser on your SVC file in your Visual Studio solution - if that doesn't work, you still have a major problem of some sort.

If it works - now you can press F5 in VS and your service should come up, and using the WCF Test Client app, you should be able to get your service metadata from a) the address that Cassini started your service on, or b) the mex address (Cassini's address + /mex)

Responsive table handling in Twitter Bootstrap

Bootstrap 3 now has Responsive tables out of the box. Hooray! :)

You can check it here: https://getbootstrap.com/docs/3.3/css/#tables-responsive

Add a <div class="table-responsive"> surrounding your table and you should be good to go:

<div class="table-responsive">
  <table class="table">
    ...
  </table>
</div>

To make it work on all layouts you can do this:

.table-responsive
{
    overflow-x: auto;
}

Find duplicate values in R

Here's a data.table solution that will list the duplicates along with the number of duplications (will be 1 if there are 2 copies, and so on - you can adjust that to suit your needs):

library(data.table)
dt = data.table(vocabulary)

dt[duplicated(id), cbind(.SD[1], number = .N), by = id]

React - Preventing Form Submission

Make sure you put the onSubmit attribute on the form not the button in case you have a from.

<form onSubmit={e => e.preventDefault()}>
    <button onClick={this.handleClick}>Click Me</button>
</form>

Make sure to change the button onClick attribute to your custom function.

How to set a value for a selectize.js input?

This works for me:

var $select = $("#my_input").selectize();
var selectize = $select[0].selectize;
selectize.setValue(selectize.search("My Default Value").items[0].id);

but you have to be really really sure that you only have one match.

Update: As this solution works perfect, in-order to make it working even if there are multiple select elements on page I have updated the answer:

Following way we can initialize:

$('select').each(function (idx) {
    var selectizeInput = $(this).selectize(options);
    $(this).data('selectize', selectizeInput[0].selectize);
});

Setting value pragmatically post initialization:

var selectElement = $('#unique_selector').eq(0);
var selectize = selectElement.data('selectize');
if (!!selectize) selectize.setValue("My Default Value");

Running JAR file on Windows

Besides all of the other suggestions, there is one other thing you need to consider. Is your helloworld.jar a console program? If it is, then I don't believe you'll be able to make it into a double-clickable jar file. Console programs use the regular cmd.exe shell window for their input and output. Usually the jar "launcher" is bound to javaw.exe which doesn't create a command-shell window.

How do I display images from Google Drive on a website?

Use the 'Get Link' option in Google Drive to get the URL.

Use <img> tag in HTML and paste the link in there.

Change Open? in the URL to uc?.

What does the CSS rule "clear: both" do?

I won't be explaining how the floats work here (in detail), as this question generally focuses on Why use clear: both; OR what does clear: both; exactly do...

I'll keep this answer simple, and to the point, and will explain to you graphically why clear: both; is required or what it does...

Generally designers float the elements, left or to the right, which creates an empty space on the other side which allows other elements to take up the remaining space.

Why do they float elements?

Elements are floated when the designer needs 2 block level elements side by side. For example say we want to design a basic website which has a layout like below...

enter image description here

Live Example of the demo image.

Code For Demo

_x000D_
_x000D_
/*  CSS:  */_x000D_
_x000D_
* { /* Not related to floats / clear both, used it for demo purpose only */_x000D_
    box-sizing: border-box;_x000D_
    -moz-box-sizing: border-box;_x000D_
    -webkit-box-sizing: border-box;_x000D_
}_x000D_
_x000D_
header, footer {_x000D_
    border: 5px solid #000;_x000D_
    height: 100px;_x000D_
}_x000D_
_x000D_
aside {_x000D_
    float: left;_x000D_
    width: 30%;_x000D_
    border: 5px solid #000;_x000D_
    height: 300px;_x000D_
}_x000D_
_x000D_
section {_x000D_
    float: left;_x000D_
    width: 70%;_x000D_
    border: 5px solid #000;_x000D_
    height: 300px;_x000D_
}_x000D_
_x000D_
.clear {_x000D_
    clear: both;_x000D_
}
_x000D_
<!-- HTML -->_x000D_
<header>_x000D_
    Header_x000D_
</header>_x000D_
<aside>_x000D_
    Aside (Floated Left)_x000D_
</aside>_x000D_
<section>_x000D_
    Content (Floated Left, Can Be Floated To Right As Well)_x000D_
</section>_x000D_
<!-- Clearing Floating Elements-->_x000D_
<div class="clear"></div>_x000D_
<footer>_x000D_
    Footer_x000D_
</footer>
_x000D_
_x000D_
_x000D_

Note: You might have to add header, footer, aside, section (and other HTML5 elements) as display: block; in your stylesheet for explicitly mentioning that the elements are block level elements.

Explanation:

I have a basic layout, 1 header, 1 side bar, 1 content area and 1 footer.

No floats for header, next comes the aside tag which I'll be using for my website sidebar, so I'll be floating the element to left.

Note: By default, block level element takes up document 100% width, but when floated left or right, it will resize according to the content it holds.

  1. Normal Behavior Of Block Level Element
  2. Floated Behavior Of Block Level Element

So as you note, the left floated div leaves the space to its right unused, which will allow the div after it to shift in the remaining space.

  1. div's will render one after the other if they are NOT floated
  2. div will shift beside each other if floated left or right

Ok, so this is how block level elements behave when floated left or right, so now why is clear: both; required and why?

So if you note in the layout demo - in case you forgot, here it is..

I am using a class called .clear and it holds a property called clear with a value of both. So lets see why it needs both.

I've floated aside and section elements to the left, so assume a scenario, where we have a pool, where header is solid land, aside and section are floating in the pool and footer is solid land again, something like this..

Floated View

So the blue water has no idea what the area of the floated elements are, they can be bigger than the pool or smaller, so here comes a common issue which troubles 90% of CSS beginners: why the background of a container element is not stretched when it holds floated elements. It's because the container element is a POOL here and the POOL has no idea how many objects are floating, or what the length or breadth of the floated elements are, so it simply won't stretch.

  1. Normal Flow Of The Document
  2. Sections Floated To Left
  3. Cleared Floated Elements To Stretch Background Color Of The Container

(Refer [Clearfix] section of this answer for neat way to do this. I am using an empty div example intentionally for explanation purpose)

I've provided 3 examples above, 1st is the normal document flow where red background will just render as expected since the container doesn't hold any floated objects.

In the second example, when the object is floated to left, the container element (POOL) won't know the dimensions of the floated elements and hence it won't stretch to the floated elements height.

enter image description here

After using clear: both;, the container element will be stretched to its floated element dimensions.

enter image description here

Another reason the clear: both; is used is to prevent the element to shift up in the remaining space.

Say you want 2 elements side by side and another element below them... So you will float 2 elements to left and you want the other below them.

  1. div Floated left resulting in section moving into remaining space
  2. Floated div cleared so that the section tag will render below the floated divs

1st Example

enter image description here


2nd Example

enter image description here

Last but not the least, the footer tag will be rendered after floated elements as I've used the clear class before declaring my footer tags, which ensures that all the floated elements (left/right) are cleared up to that point.


Clearfix

Coming to clearfix which is related to floats. As already specified by @Elky, the way we are clearing these floats is not a clean way to do it as we are using an empty div element which is not a div element is meant for. Hence here comes the clearfix.

Think of it as a virtual element which will create an empty element for you before your parent element ends. This will self clear your wrapper element holding floated elements. This element won't exist in your DOM literally but will do the job.

To self clear any wrapper element having floated elements, we can use

.wrapper_having_floated_elements:after {  /* Imaginary class name */
  content: "";
  clear: both;
  display: table;
}

Note the :after pseudo element used by me for that class. That will create a virtual element for the wrapper element just before it closes itself. If we look in the dom you can see how it shows up in the Document tree.

Clearfix

So if you see, it is rendered after the floated child div where we clear the floats which is nothing but equivalent to have an empty div element with clear: both; property which we are using for this too. Now why display: table; and content is out of this answers scope but you can learn more about pseudo element here.

Note that this will also work in IE8 as IE8 supports :after pseudo.


Original Answer:

Most of the developers float their content left or right on their pages, probably divs holding logo, sidebar, content etc., these divs are floated left or right, leaving the rest of the space unused and hence if you place other containers, it will float too in the remaining space, so in order to prevent that clear: both; is used, it clears all the elements floated left or right.

Demonstration:

------------------ ----------------------------------
div1(Floated Left) Other div takes up the space here
------------------ ----------------------------------

Now what if you want to make the other div render below div1, so you'll use clear: both; so it will ensure you clear all floats, left or right

------------------
div1(Floated Left)
------------------
<div style="clear: both;"><!--This <div> acts as a separator--></div>
----------------------------------
Other div renders here now
----------------------------------

"undefined" function declared in another file?

If your source folder is structured /go/src/blog (assuming the name of your source folder is blog).

  1. cd /go/src/blog ... (cd inside the folder that has your package)
  2. go install
  3. blog

That should run all of your files at the same time, instead of you having to list the files manually or "bashing" a method on the command line.

jQuery events .load(), .ready(), .unload()

window load will wait for all resources to be loaded.

document ready waits for the document to be initialized.

unload well, waits till the document is being unloaded.

the order is: document ready, window load, ... ... ... ... window unload.

always use document ready unless you need to wait for your images to load.

shorthand for document ready:

$(function(){
    // yay!
});

How can I merge the columns from two tables into one output?

Specifying the columns on your query should do the trick:

select a.col1, b.col2, a.col3, b.col4, a.category_id 
from items_a a, items_b b 
where a.category_id = b.category_id

should do the trick with regards to picking the columns you want.

To get around the fact that some data is only in items_a and some data is only in items_b, you would be able to do:

select 
  coalesce(a.col1, b.col1) as col1, 
  coalesce(a.col2, b.col2) as col2,
  coalesce(a.col3, b.col3) as col3,
  a.category_id
from items_a a, items_b b
where a.category_id = b.category_id

The coalesce function will return the first non-null value, so for each row if col1 is non null, it'll use that, otherwise it'll get the value from col2, etc.

pass **kwargs argument to another function with **kwargs

For #2 args will be only a formal parameter with dict value, but not a keyword type parameter.

If you want to pass a keyword type parameter into a keyword argument You need to specific ** before your dictionary, which means **args

check this out for more detail on using **kw

http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

jquery to validate phone number

I tried the below solution and it work fine for me.

/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/

Tried below phone format:

  • +(123) 456 7899
  • (123) 456 7899
  • (123).456.7899
  • (123)-456-7899
  • 123-456-7899
  • 123 456 7899
  • 1234567899

Is there a way to crack the password on an Excel VBA Project?

In the event that your block of CMG="XXXX"\r\nDPB="XXXXX"\r\nGC="XXXXXX" in your 'known password' file is shorter than the existing block in the 'unknown password' file, pad your hex strings with trailing zeros to reach the correct length.

e.g.

CMG="xxxxxx"\r\nDPB="xxxxxxxx"\r\nGC="xxxxxxxxxx"

in the unknown password file, should be set to

CMG="XXXX00"\r\nDPB="XXXXX000"\r\nGC="XXXXXX0000" to preserve file length.

I have also had this working with .XLA (97/2003 format) files in office 2007.

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

On CentOS Linux, Python3.6, I edited this file (make a backup copy first)

/usr/lib/python3.6/site-packages/certifi/cacert.pem

to the end of the file, I added my public certificate from my .pem file. you should be able to obtain the .pem file from your ssl certificate provider.

Can you do a partial checkout with Subversion?

Or do a non-recursive checkout of /trunk, then just do a manual update on the 3 directories you need.

Python memory usage of numpy arrays

The field nbytes will give you the size in bytes of all the elements of the array in a numpy.array:

size_in_bytes = my_numpy_array.nbytes

Notice that this does not measures "non-element attributes of the array object" so the actual size in bytes can be a few bytes larger than this.

Enter key press behaves like a Tab in Javascript

You can use my code below, tested in Mozilla, IE, and Chrome

   // Use to act like tab using enter key
    $.fn.enterkeytab=function(){
         $(this).on('keydown', 'input, select,', function(e) {
        var self = $(this)
          , form = self.parents('form:eq(0)')
          , focusable
          , next
          ;
            if (e.keyCode == 13) {
                focusable = form.find('input,a,select,button').filter(':visible');
                next = focusable.eq(focusable.index(this)+1);
                if (next.length) {
                    next.focus();
                } else {
                    alert("wd");
                    //form.submit();
                }
                return false;
            }
        });

    }

How to Use?

$("#form").enterkeytab(); // enter key tab

Is there a way to change the spacing between legend items in ggplot2?

From Koshke's work on ggplot2 and his blog (Koshke's blog)

... + theme(legend.key.height=unit(3,"line")) # Change 3 to X
... + theme(legend.key.width=unit(3,"line")) # Change 3 to X

Type theme_get() in the console to see other editable legend attributes.

How to change owner of PostgreSql database?

Frank Heikens answer will only update database ownership. Often, you also want to update ownership of contained objects (including tables). Starting with Postgres 8.2, REASSIGN OWNED is available to simplify this task.

IMPORTANT EDIT!

Never use REASSIGN OWNED when the original role is postgres, this could damage your entire DB instance. The command will update all objects with a new owner, including system resources (postgres0, postgres1, etc.)


First, connect to admin database and update DB ownership:

psql
postgres=# REASSIGN OWNED BY old_name TO new_name;

This is a global equivalent of ALTER DATABASE command provided in Frank's answer, but instead of updating a particular DB, it change ownership of all DBs owned by 'old_name'.

The next step is to update tables ownership for each database:

psql old_name_db
old_name_db=# REASSIGN OWNED BY old_name TO new_name;

This must be performed on each DB owned by 'old_name'. The command will update ownership of all tables in the DB.

Twitter bootstrap hide element on small devices

On small device : 4 columns x 3 (= 12) ==> col-sm-3

On extra small : 3 columns x 4 (= 12) ==> col-xs-4

 <footer class="row">
        <nav class="col-xs-4 col-sm-3">
            <ul class="list-unstyled">
            <li>Text 1</li>
            <li>Text 2</li>
            <li>Text 3</li>
            </ul>
        </nav>
        <nav class="col-xs-4 col-sm-3">
            <ul class="list-unstyled">
            <li>Text 4</li>
            <li>Text 5</li>
            <li>Text 6</li>
            </ul>
        </nav>
        <nav class="col-xs-4 col-sm-3">
            <ul class="list-unstyled">
            <li>Text 7</li>
            <li>Text 8</li>
            <li>Text 9</li>
            </ul>
        </nav>
        <nav class="hidden-xs col-sm-3">
            <ul class="list-unstyled">
            <li>Text 10</li>
            <li>Text 11</li>
            <li>Text 12</li>
            </ul>
        </nav>
    </footer>

As you say, hidden-xs is not enough, you have to combine xs and sm class.


Here is links to the official doc about available responsive classes and about the grid system.

Have in head :

  • 1 row = 12 cols
  • For XtraSmall device : col-xs-__
  • For SMall device : col-sm-__
  • For MeDium Device: col-md-__
  • For LarGe Device : col-lg-__
  • Make visible only (hidden on other) : visible-md (just visible in medium [not in lg xs or sm])
  • Make hidden only (visible on other) : hidden-xs (just hidden in XtraSmall)

Trim spaces from start and end of string

var word = " testWord ";   //add here word or space and test

var x = $.trim(word);

if(x.length > 0)
    alert('word');
else
    alert('spaces');

What is the best way to search the Long datatype within an Oracle database?

You can use this example without using temp table:

DECLARE

  l_var VARCHAR2(32767); -- max length

BEGIN

FOR rec IN (SELECT ID, LONG_COLUMN FROM TABLE_WITH_LONG_COLUMN) LOOP
  l_var := rec.LONG_COLUMN;
  IF l_var LIKE '%350%' THEN -- is there '350' string?
    dbms_output.put_line('ID:' || rec.ID || ' COLUMN:' || rec.LONG_COLUMN);
  END IF;
END LOOP;

END;

Of course there is a problem if LONG has more than 32K characters.

How do I access ViewBag from JS

You can achieve the solution, by doing this:

JavaScript:

var myValue = document.getElementById("@(ViewBag.CC)").value;

or if you want to use jQuery, then:

jQuery

var myValue = $('#' + '@(ViewBag.CC)').val();

How to delete/truncate tables from Hadoop-Hive?

Use the following to delete all the tables in a linux environment.

hive -e 'show tables' | xargs -I '{}' hive -e 'drop table {}'

Sum across multiple columns with dplyr

Using reduce() from purrr is slightly faster than rowSums and definately faster than apply, since you avoid iterating over all the rows and just take advantage of the vectorized operations:

library(purrr)
library(dplyr)
iris %>% mutate(Petal = reduce(select(., starts_with("Petal")), `+`))

See this for timings

JFrame Exit on close Java

this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

this worked for me in case of Class Extends Frame

How to append text to a text file in C++?

You could use an fstream and open it with the std::ios::app flag. Have a look at the code below and it should clear your head.

...
fstream f("filename.ext", f.out | f.app);
f << "any";
f << "text";
f << "written";
f << "wll";
f << "be append";
...

You can find more information about the open modes here and about fstreams here.

Get last record of a table in Postgres

Use the following

SELECT timestamp, value, card 
FROM my_table 
ORDER BY timestamp DESC 
LIMIT 1

PostgreSQL: days/months/years between two dates

Here is a complete example with output. psql (10.1, server 9.5.10).

You get 58, not some value less than 30.
Remove age() function, solved the problem that previous post mentioned.

drop table t;
create table t(
    d1 date
);

insert into t values(current_date - interval '58 day');

select d1
, current_timestamp - d1::timestamp date_diff
, date_part('day', current_timestamp - d1::timestamp)
from t;

     d1     |        date_diff        | date_part
------------+-------------------------+-----------
 2018-05-21 | 58 days 21:41:07.992731 |        58

Using Image control in WPF to display System.Drawing.Bitmap

I wrote a program with wpf and used Database for showing images and this is my code:

SqlConnection con = new SqlConnection(@"Data Source=HITMAN-PC\MYSQL;
                                      Initial Catalog=Payam;
                                      Integrated Security=True");

SqlDataAdapter da = new SqlDataAdapter("select * from news", con);

DataTable dt = new DataTable();
da.Fill(dt);

string adress = dt.Rows[i]["ImgLink"].ToString();
ImageSource imgsr = new BitmapImage(new Uri(adress));
PnlImg.Source = imgsr;

Locating child nodes of WebElements in selenium

For Finding All the ChildNodes you can use the below Snippet

List<WebElement> childs = MyCurrentWebElement.findElements(By.xpath("./child::*"));

        for (WebElement e  : childs)
        {
            System.out.println(e.getTagName());
        }

Note that this will give all the Child Nodes at same level -> Like if you have structure like this :

<Html> 
<body> 
 <div> ---suppose this is current WebElement 
   <a>
   <a>
      <img>
          <a>
      <img>
   <a>

It will give me tag names of 3 anchor tags here only . If you want all the child Elements recursively , you can replace the above code with MyCurrentWebElement.findElements(By.xpath(".//*"));

Hope That Helps !!

Could not establish secure channel for SSL/TLS with authority '*'

Yes an Untrusted certificate can cause this. Look at the certificate path for the webservice by opening the websservice in a browser and use the browser tools to look at the certificate path. You may need to install one or more intermediate certificates onto the computer calling the webservice. In the browser you may see "Certificate errors" with an option to "Install Certificate" when you investigate further - this could be the certificate you missing.

My particular problem was a Geotrust Geotrust DV SSL CA intermediate certificate missing following an upgrade to their root server in July 2010 https://knowledge.geotrust.com/support/knowledge-base/index?page=content&id=AR1422

(2020 update deadlink preserved here: https://web.archive.org/web/20140724085537/https://knowledge.geotrust.com/support/knowledge-base/index?page=content&id=AR1422 )

Removing character in list of strings

mylist = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
print mylist
j=0
for i in mylist:
    mylist[j]=i.rstrip("8")
    j+=1
print mylist

Why use Select Top 100 Percent?

The error says it all...

Msg 1033, Level 15, State 1, Procedure TestView, Line 5 The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

Don't use TOP 100 PERCENT, use TOP n, where N is a number

The TOP 100 PERCENT (for reasons I don't know) is ignored by SQL Server VIEW (post 2012 versions), but I think MS kept it for syntax reasons. TOP n is better and will work inside a view and sort it the way you want when a view is used initially, but be careful.