Programs & Examples On #Saxparser

SAX (Simple API for XML) is an event-based parser for XML documents.

What is the difference between SAX and DOM?

In practical: book.xml

<bookstore>
  <book category="cooking">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
</bookstore>
  • DOM presents the xml document as a the following tree-structure in memory.
  • DOM is W3C standard.
  • DOM parser works on Document Object Model.
  • DOM occupies more memory, preferred for small XML documents
  • DOM is Easy to navigate either forward or backward.

enter image description here


  • SAX presents the xml document as event based like start element:abc, end element:abc.
  • SAX is not W3C standard, it was developed by group of developers.
  • SAX does not use memory, preferred for large XML documents.
  • Backward navigation is not possible as it sequentially process the documents.
  • Event happens to a node/element and it gives all sub nodes(Latin nodus, ‘knot’).

This XML document, when passed through a SAX parser, will generate a sequence of events like the following:

start element: bookstore
start element: book with an attribute category equal to cooking
start element: title with an attribute lang equal to en
Text node, with data equal to Everyday Italian
....
end element: title
.....
end element: book
end element: bookstore

How do you create an asynchronous method in C#?

If you didn't want to use async/await inside your method, but still "decorate" it so as to be able to use the await keyword from outside, TaskCompletionSource.cs:

public static Task<T> RunAsync<T>(Func<T> function)
{ 
    if (function == null) throw new ArgumentNullException(“function”); 
    var tcs = new TaskCompletionSource<T>(); 
    ThreadPool.QueueUserWorkItem(_ =>          
    { 
        try 
        {  
           T result = function(); 
           tcs.SetResult(result);  
        } 
        catch(Exception exc) { tcs.SetException(exc); } 
   }); 
   return tcs.Task; 
}

From here and here

To support such a paradigm with Tasks, we need a way to retain the Task façade and the ability to refer to an arbitrary asynchronous operation as a Task, but to control the lifetime of that Task according to the rules of the underlying infrastructure that’s providing the asynchrony, and to do so in a manner that doesn’t cost significantly. This is the purpose of TaskCompletionSource.

I saw it's also used in the .NET source, e.g. WebClient.cs:

    [HostProtection(ExternalThreading = true)]
    [ComVisible(false)]
    public Task<string> UploadStringTaskAsync(Uri address, string method, string data)
    {
        // Create the task to be returned
        var tcs = new TaskCompletionSource<string>(address);

        // Setup the callback event handler
        UploadStringCompletedEventHandler handler = null;
        handler = (sender, e) => HandleCompletion(tcs, e, (args) => args.Result, handler, (webClient, completion) => webClient.UploadStringCompleted -= completion);
        this.UploadStringCompleted += handler;

        // Start the async operation.
        try { this.UploadStringAsync(address, method, data, tcs); }
        catch
        {
            this.UploadStringCompleted -= handler;
            throw;
        }

        // Return the task that represents the async operation
        return tcs.Task;
    }

Finally, I also found the following useful:

I get asked this question all the time. The implication is that there must be some thread somewhere that’s blocking on the I/O call to the external resource. So, asynchronous code frees up the request thread, but only at the expense of another thread elsewhere in the system, right? No, not at all.

To understand why asynchronous requests scale, I’ll trace a (simplified) example of an asynchronous I/O call. Let’s say a request needs to write to a file. The request thread calls the asynchronous write method. WriteAsync is implemented by the Base Class Library (BCL), and uses completion ports for its asynchronous I/O. So, the WriteAsync call is passed down to the OS as an asynchronous file write. The OS then communicates with the driver stack, passing along the data to write in an I/O request packet (IRP).

This is where things get interesting: If a device driver can’t handle an IRP immediately, it must handle it asynchronously. So, the driver tells the disk to start writing and returns a “pending” response to the OS. The OS passes that “pending” response to the BCL, and the BCL returns an incomplete task to the request-handling code. The request-handling code awaits the task, which returns an incomplete task from that method and so on. Finally, the request-handling code ends up returning an incomplete task to ASP.NET, and the request thread is freed to return to the thread pool.

Introduction to Async/Await on ASP.NET

If the target is to improve scalability (rather than responsiveness), it all relies on the existence of an external I/O that provides the opportunity to do that.

Should C# or C++ be chosen for learning Games Programming (consoles)?

If you want to be employed professionally as a game developer you need to know C/C++. End of story!

How do I decode a base64 encoded string?

The m000493 method seems to perform some kind of XOR encryption. This means that the same method can be used for both encrypting and decrypting the text. All you have to do is reverse m0001cd:

string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));

string result = m000493(p0, "_p0lizei.");
//    result == "gaia^unplugged^Ta..."

with return m0001cd(builder3.ToString()); changed to return builder3.ToString();.

Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio?

In SQL Management Studio you can:

  1. Right click on the result set grid, select 'Save Result As...' and save in.

  2. On a tool bar toggle 'Result to Text' button. This will prompt for file name on each query run.

If you need to automate it, use bcp tool.

Return array from function

At a minimum, change this:

function BlockID() {
    var IDs = new Array();
        images['s'] = "Images/Block_01.png";
        images['g'] = "Images/Block_02.png";
        images['C'] = "Images/Block_03.png";
        images['d'] = "Images/Block_04.png";
    return IDs;
}

To this:

function BlockID() {
    var IDs = new Object();
        IDs['s'] = "Images/Block_01.png";
        IDs['g'] = "Images/Block_02.png";
        IDs['C'] = "Images/Block_03.png";
        IDs['d'] = "Images/Block_04.png";
    return IDs;
}

There are a couple fixes to point out. First, images is not defined in your original function, so assigning property values to it will throw an error. We correct that by changing images to IDs. Second, you want to return an Object, not an Array. An object can be assigned property values akin to an associative array or hash -- an array cannot. So we change the declaration of var IDs = new Array(); to var IDs = new Object();.

After those changes your code will run fine, but it can be simplified further. You can use shorthand notation (i.e., object literal property value shorthand) to create the object and return it immediately:

function BlockID() {
    return {
            "s":"Images/Block_01.png"
            ,"g":"Images/Block_02.png"
            ,"C":"Images/Block_03.png"
            ,"d":"Images/Block_04.png"
    };
}

iPhone hide Navigation Bar only on first page

I would put the code in the viewWillAppear delegate on each view being shown:

Like this where you need to hide it:

- (void)viewWillAppear:(BOOL)animated
{
        [yourObject hideBar];
}

Like this where you need to show it:

- (void)viewWillAppear:(BOOL)animated
{
        [yourObject showBar];
}

Which is a better way to check if an array has more than one element?

if(is_array($arr) && count($arr) > 1)

Just to be sure that $arr is indeed an array.

sizeof is an alias of count, I prefer to use count because:

  1. 1 less character to type
  2. sizeof at a quick glance might mean a size of an array in terms of memory, too technical :(

How do I create a SQL table under a different schema?

Hit F4 and you'll get what you are looking for.

Managing jQuery plugin dependency in webpack

Add this to your plugins array in webpack.config.js

new webpack.ProvidePlugin({
    'window.jQuery': 'jquery',
    'window.$': 'jquery',
})

then require jquery normally

require('jquery');

If pain persists getting other scripts to see it, try explicitly placing it in the global context via (in the entry js)

window.$ = jQuery;

Close virtual keyboard on button press

You use this code in your button click event

// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {  
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

Javascript reduce on array of objects

In the first step, it will work fine as the value of a will be 1 and that of b will be 2 but as 2+1 will be returned and in the next step the value of b will be the return value from step 1 i.e 3 and so b.x will be undefined...and undefined + anyNumber will be NaN and that is why you are getting that result.

Instead you can try this by giving initial value as zero i.e

arr.reduce(function(a,b){return a + b.x},0);

How to sort an array of objects in Java?

With Java 8, you can use a reference method.

You could add compare method to your Book class

class Book {
     public static int compare(Book a, Book b)
     {
         return a.name.compareTo(b.name);
     }
}

And then you could do this :

Arrays.sort(books , Book::compare);

Here is the full example:

class Book {
    String name;
    String author;

    public Book(String name, String author) {
        this.name = name;
        this.author = author;
    }

    public static int compareBooks(Book a , Book b)
    {
        return a.name.compareTo(b.name);
    }

    @Override
    public String toString() {
        return "name : " + name + "\t" + "author : " + author;
    }


    public static void main(String[] args) {

        Book[] books = {
                new Book("Book 3" , "Author 1"),
                new Book("Book 2" , "Author 2"),
                new Book("Book 1" , "Author 3"),
                new Book("Book 4" , "Author 4")
        };

        Arrays.sort(books , Book::compareBooks);
        Arrays.asList(books).forEach(System.out::println);

    }
}

What is more efficient? Using pow to square or just multiply it with itself?

I tested the performance difference between x*x*... vs pow(x,i) for small i using this code:

#include <cstdlib>
#include <cmath>
#include <boost/date_time/posix_time/posix_time.hpp>

inline boost::posix_time::ptime now()
{
    return boost::posix_time::microsec_clock::local_time();
}

#define TEST(num, expression) \
double test##num(double b, long loops) \
{ \
    double x = 0.0; \
\
    boost::posix_time::ptime startTime = now(); \
    for (long i=0; i<loops; ++i) \
    { \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
    } \
    boost::posix_time::time_duration elapsed = now() - startTime; \
\
    std::cout << elapsed << " "; \
\
    return x; \
}

TEST(1, b)
TEST(2, b*b)
TEST(3, b*b*b)
TEST(4, b*b*b*b)
TEST(5, b*b*b*b*b)

template <int exponent>
double testpow(double base, long loops)
{
    double x = 0.0;

    boost::posix_time::ptime startTime = now();
    for (long i=0; i<loops; ++i)
    {
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
    }
    boost::posix_time::time_duration elapsed = now() - startTime;

    std::cout << elapsed << " ";

    return x;
}

int main()
{
    using std::cout;
    long loops = 100000000l;
    double x = 0.0;
    cout << "1 ";
    x += testpow<1>(rand(), loops);
    x += test1(rand(), loops);

    cout << "\n2 ";
    x += testpow<2>(rand(), loops);
    x += test2(rand(), loops);

    cout << "\n3 ";
    x += testpow<3>(rand(), loops);
    x += test3(rand(), loops);

    cout << "\n4 ";
    x += testpow<4>(rand(), loops);
    x += test4(rand(), loops);

    cout << "\n5 ";
    x += testpow<5>(rand(), loops);
    x += test5(rand(), loops);
    cout << "\n" << x << "\n";
}

Results are:

1 00:00:01.126008 00:00:01.128338 
2 00:00:01.125832 00:00:01.127227 
3 00:00:01.125563 00:00:01.126590 
4 00:00:01.126289 00:00:01.126086 
5 00:00:01.126570 00:00:01.125930 
2.45829e+54

Note that I accumulate the result of every pow calculation to make sure the compiler doesn't optimize it away.

If I use the std::pow(double, double) version, and loops = 1000000l, I get:

1 00:00:00.011339 00:00:00.011262 
2 00:00:00.011259 00:00:00.011254 
3 00:00:00.975658 00:00:00.011254 
4 00:00:00.976427 00:00:00.011254 
5 00:00:00.973029 00:00:00.011254 
2.45829e+52

This is on an Intel Core Duo running Ubuntu 9.10 64bit. Compiled using gcc 4.4.1 with -o2 optimization.

So in C, yes x*x*x will be faster than pow(x, 3), because there is no pow(double, int) overload. In C++, it will be the roughly same. (Assuming the methodology in my testing is correct.)


This is in response to the comment made by An Markm:

Even if a using namespace std directive was issued, if the second parameter to pow is an int, then the std::pow(double, int) overload from <cmath> will be called instead of ::pow(double, double) from <math.h>.

This test code confirms that behavior:

#include <iostream>

namespace foo
{

    double bar(double x, int i)
    {
        std::cout << "foo::bar\n";
        return x*i;
    }


}

double bar(double x, double y)
{
    std::cout << "::bar\n";
    return x*y;
}

using namespace foo;

int main()
{
    double a = bar(1.2, 3); // Prints "foo::bar"
    std::cout << a << "\n";
    return 0;
}

batch file to check 64bit or 32bit OS

PROCESSOR_ARCHITECTURE=x86

Will appear on Win32, and

PROCESSOR_ARCHITECTURE=AMD64

will appear for Win64.

If you are perversely running the 32-bit cmd.exe process then Windows presents two environment variables:

PROCESSOR_ARCHITECTURE=x86
PROCESSOR_ARCHITEW6432=AMD64

How to read multiple text files into a single RDD?

There is a straight forward clean solution available. Use the wholeTextFiles() method. This will take a directory and forms a key value pair. The returned RDD will be a pair RDD. Find below the description from Spark docs:

SparkContext.wholeTextFiles lets you read a directory containing multiple small text files, and returns each of them as (filename, content) pairs. This is in contrast with textFile, which would return one record per line in each file

When should the xlsm or xlsb formats be used?

.xlsx loads 4 times longer than .xlsb and saves 2 times longer and has 1.5 times a bigger file. I tested this on a generated worksheet with 10'000 rows * 1'000 columns = 10'000'000 (10^7) cells of simple chained =…+1 formulas:

?--------------------------------?
¦              ¦ .xlsx  ¦ .xlsb  ¦
¦--------------+--------+--------¦
¦ loading time ¦ 165s   ¦  43s   ¦
+--------------+--------+--------¦
¦ saving time  ¦ 115s   ¦  61s   ¦
+--------------+--------+--------¦
¦ file size    ¦  91 MB ¦  65 MB ¦
?--------------------------------?

(Hardware: Core2Duo 2.3 GHz, 4 GB RAM, 5.400 rpm SATA II HD; Windows 7, under somewhat heavy load from other processes.)

Beside this, there should be no differences. More precisely,

both formats support exactly the same feature set

cites this blog post from 2006-08-29. So maybe the info that .xlsb does not support Ribbon code is newer than the upper citation, but I figure that forum source of yours is just wrong. When cracking open the binary file, it seems to condensedly mimic the OOXML file structure 1-to-1: Blog article from 2006-08-07

How to get the mysql table columns data type?

Please use the below mysql query.

SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH 
FROM information_schema.columns 
WHERE table_schema = '<DATABASE NAME>' 
AND table_name = '<TABLE NAME>' 
AND COLUMN_NAME = '<COLOMN NAME>' 

MySql Query Result

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

Swing + SwingX + Miglayout is my combination of choice. Miglayout is so much simpler than Swings perceived 200 different layout managers and much more powerful. Also, it provides you with the ability to "debug" your layouts, which is especially handy when creating complex layouts.

How to make Bootstrap carousel slider use mobile left/right swipe

I needed to add this functionality to a project I was working on recently and adding jQuery Mobile just to solve this problem seemed like overkill, so I came up with a solution and put it on github: bcSwipe (Bootstrap Carousel Swipe).

It's a lightweight jQuery plugin (~600 bytes minified vs jQuery Mobile touch events at 8kb), and it's been tested on Android and iOS.

This is how you use it:

$('.carousel').bcSwipe({ threshold: 50 });

What is "X-Content-Type-Options=nosniff"?

A really simple explanation that I found useful: the nosniff response header is a way to keep a website more secure.

From Security Researcher, Scott Helme, here:

It prevents Google Chrome and Internet Explorer from trying to mime-sniff the content-type of a response away from the one being declared by the server.

Simple way to count character occurrences in a string

Well there are a bunch of different utilities for this, e.g. Apache Commons Lang String Utils

but in the end, it has to loop over the string to count the occurrences one way or another.

Note also that the countMatches method above has the following signature so will work for substrings as well.

public static int countMatches(String str, String sub)

The source for this is (from here):

public static int countMatches(String str, String sub) {
    if (isEmpty(str) || isEmpty(sub)) {
        return 0;
    }
    int count = 0;
    int idx = 0;
    while ((idx = str.indexOf(sub, idx)) != -1) {
        count++;
        idx += sub.length();
    }
    return count;
}

I was curious if they were iterating over the string or using Regex.

'numpy.float64' object is not iterable

numpy.linspace() gives you a one-dimensional NumPy array. For example:

>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.])

Therefore:

for index,point in my_array

cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:

>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])

Now you can do this:

>>> for x, y in two_d:
    print(x, y)

1 2
4 5

SQL 'LIKE' query using '%' where the search criteria contains '%'

If you want a % symbol in search_criteria to be treated as a literal character rather than as a wildcard, escape it to [%]

... where name like '%' + replace(search_criteria, '%', '[%]') + '%'

How to Position a table HTML?

As BalausC mentioned in a comment, you are probably looking for CSS (Cascading Style Sheets) not HTML attributes.

To position an element, a <table> in your case you want to use either padding or margins.

the difference between margins and paddings can be seen as the "box model":

box model image

Image from HTML Dog article on margins and padding http://www.htmldog.com/guides/cssbeginner/margins/.

I highly recommend the article above if you need to learn how to use CSS.

To move the table down and right I would use margins like so:

table{
    margin:25px 0 0 25px;
}

This is in shorthand so the margins are as follows:

margin: top right bottom left;

Printing integer variable and string on same line in SQL

Double check if you have set and initial value for int and decimal values to be printed.

This sample is printing an empty line

declare @Number INT
print 'The number is : ' + CONVERT(VARCHAR, @Number)

And this sample is printing -> The number is : 1

declare @Number INT = 1
print 'The number is : ' + CONVERT(VARCHAR, @Number)

Ignore 'Security Warning' running script from command line

It is very simple to do, open your PowerShell and write the following command if you have number of ps1 files. here you have to change the path with your path.

PS C:\Users> Get-ChildItem -Path "D:\downlod" -Recurse | Unblock-File

Create an application setup in visual studio 2013

Visual Studio 2013 now supports setup projects. Microsoft have shipped a Visual Studio extension to produce setup projects.

Visual Studio Installer Projects Extension

How do I prevent people from doing XSS in Spring MVC?

When you are trying to prevent XSS, it's important to think of the context. As an example how and what to escape is very different if you are ouputting data inside a variable in a javascript snippet as opposed to outputting data in an HTML tag or an HTML attribute.

I have an example of this here: http://erlend.oftedal.no/blog/?blogid=91

Also checkout the OWASP XSS Prevention Cheat Sheet: http://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet

So the short answer is, make sure you escape output like suggested by Tendayi Mawushe, but take special care when you are outputting data in HTML attributes or javascript.

SQL Server : export query as a .txt file

The BCP Utility can also be used in the form of a .bat file, but be cautious of escape sequences (ie quotes "" must be used in conjunction with ) and the appropriate tags.

.bat Example:

C:
bcp "\"YOUR_SERVER\".dbo.Proc" queryout C:\FilePath.txt -T -c -q
-- Add PAUSE here if you'd like to see the completed batch

-q MUST be used in the presence of quotations within the query itself.

BCP can also run Stored Procedures if necessary. Again, be cautious: Temporary Tables must be created prior to execution or else you should consider using Table Variables.

Use of "instanceof" in Java

Basically, you check if an object is an instance of a specific class. You normally use it, when you have a reference or parameter to an object that is of a super class or interface type and need to know whether the actual object has some other type (normally more concrete).

Example:

public void doSomething(Number param) {
  if( param instanceof Double) {
    System.out.println("param is a Double");
  }
  else if( param instanceof Integer) {
    System.out.println("param is an Integer");
  }

  if( param instanceof Comparable) {
    //subclasses of Number like Double etc. implement Comparable
    //other subclasses might not -> you could pass Number instances that don't implement that interface
    System.out.println("param is comparable"); 
  }
}

Note that if you have to use that operator very often it is generally a hint that your design has some flaws. So in a well designed application you should have to use that operator as little as possible (of course there are exceptions to that general rule).

How are environment variables used in Jenkins with Windows Batch Command?

I should this On Windows, environment variable expansion is %BUILD_NUMBER%

How to check if a URL exists or returns 404 with Java?

Based on the given answers and information in the question, this is the code you should use:

public static boolean doesURLExist(URL url) throws IOException
{
    // We want to check the current URL
    HttpURLConnection.setFollowRedirects(false);

    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

    // We don't need to get data
    httpURLConnection.setRequestMethod("HEAD");

    // Some websites don't like programmatic access so pretend to be a browser
    httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
    int responseCode = httpURLConnection.getResponseCode();

    // We only accept response code 200
    return responseCode == HttpURLConnection.HTTP_OK;
}

Of course tested and working.

Stored procedure - return identity as output parameter or scalar

Its all depend on your client data access-layer. Many ORM frameworks rely on explicitly querying the SCOPE_IDENTITY during the insert operation.

If you are in complete control over the data access layer then is arguably better to return SCOPE_IDENTITY() as an output parameter. Wrapping the return in a result set adds unnecessary meta data overhead to describe the result set, and complicates the code to process the requests result.

If you prefer a result set return, then again is arguable better to use the OUTPUT clause:

INSERT INTO  MyTable (col1, col2, col3)
OUTPUT INSERTED.id, col1, col2, col3
VALUES (@col1, @col2, @col3);

This way you can get the entire inserted row back, including default and computed columns, and you get a result set containing one row for each row inserted, this working correctly with set oriented batch inserts.

Overall, I can't see a single case when returning SCOPE_IDENTITY() as a result set would be a good practice.

How do I exit from a function?

Use the return keyword.

From MSDN:

The return statement terminates execution of the method in which it appears and returns control to the calling method. It can also return the value of the optional expression. If the method is of the type void, the return statement can be omitted.

So in your case, the usage would be:

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
    {
        return; //exit this event
    }
}

Java system properties and environment variables

I think the difference between the two boils down to access. Environment variables are accessible by any process and Java system properties are only accessible by the process they are added to.

Also as Bohemian stated, env variables are set in the OS (however they 'can' be set through Java) and system properties are passed as command line options or set via setProperty().

Quick way to clear all selections on a multiselect enabled <select> with jQuery?

$("#ddlMultiselect").val('').trigger("change");

for multi-select drop-down, it will clear displayed text.

mysql query result in php variable

Of course there is. Check out mysql_query, and mysql_fetch_row if you use MySQL.
Example from PHP manual:

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$row = mysql_fetch_row($result);

echo $row[0]; // 42
echo $row[1]; // the email value
?>

"echo -n" prints "-n"

When you go and write you shell script always put first line as #!/usr/bin/env bash . This shell doesn't omit or manipulate escape sequences. ex echo "This is first \n line" prints This is first \n line.

Adjusting and image Size to fit a div (bootstrap)

If any of you looking for Bootstrap-4. Here it is

<div class="row no-gutters">
    <div class="col-10">
        <img class="img-fluid" src="/resources/img1.jpg" alt="">
    </div>
</div>

Synchronous XMLHttpRequest warning and <script>

UPDATE: This has been fixed in jQuery 3.x. If you have no possibility to upgrade to any version above 3.0, you could use following snippet BUT be aware that now you will lose sync behaviour of script loading in the targeted content.

You could fix it, setting explicitly async option of xhr request to true:

$.ajaxPrefilter(function( options, original_Options, jqXHR ) {
    options.async = true;
});

jquery-ui-dialog - How to hook into dialog close event

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.

Because no one actually created an answer with using .on() instead of bind() i decided to create one.

$('div#dialog').on('dialogclose', function(event) {
     //custom logic fired after dialog is closed.  
});

asp.net mvc @Html.CheckBoxFor

Use this code:

@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
    @Html.HiddenFor(m => m.EmploymentType[i].Text)
    @Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "YourId" })
}

Write to CSV file and export it?

Here is a CSV action result I wrote that takes a DataTable and converts it into CSV. You can return this from your view and it will prompt the user to download the file. You should be able to convert this easily into a List compatible form or even just put your list into a DataTable.

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;

namespace Detectent.Analyze.ActionResults
{
    public class CSVResult : ActionResult
    {
        /// <summary>
        /// Converts the columns and rows from a data table into an Microsoft Excel compatible CSV file.
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="fileName">The full file name including the extension.</param>
        public CSVResult(DataTable dataTable, string fileName)
        {
            Table = dataTable;
            FileName = fileName;
        }

        public string FileName { get; protected set; }
        public DataTable Table { get; protected set; }




        public override void ExecuteResult(ControllerContext context)
        {
            StringBuilder csv = new StringBuilder(10 * Table.Rows.Count * Table.Columns.Count);

            for (int c = 0; c < Table.Columns.Count; c++)
            {
                if (c > 0)
                    csv.Append(",");
                DataColumn dc = Table.Columns[c];
                string columnTitleCleaned = CleanCSVString(dc.ColumnName);
                csv.Append(columnTitleCleaned);
            }
            csv.Append(Environment.NewLine);
            foreach (DataRow dr in Table.Rows)
            {
                StringBuilder csvRow = new StringBuilder();
                for(int c = 0; c < Table.Columns.Count; c++)
                {
                    if(c != 0)
                        csvRow.Append(",");

                    object columnValue = dr[c];
                    if (columnValue == null)
                        csvRow.Append("");
                    else
                    {
                        string columnStringValue = columnValue.ToString();


                        string cleanedColumnValue = CleanCSVString(columnStringValue);

                        if (columnValue.GetType() == typeof(string) && !columnStringValue.Contains(","))
                        {
                            cleanedColumnValue = "=" + cleanedColumnValue; // Prevents a number stored in a string from being shown as 8888E+24 in Excel. Example use is the AccountNum field in CI that looks like a number but is really a string.
                        }
                        csvRow.Append(cleanedColumnValue);
                    }
                }
                csv.AppendLine(csvRow.ToString());
            }

            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = "text/csv";
            response.AppendHeader("Content-Disposition", "attachment;filename=" + this.FileName);
            response.Write(csv.ToString());
        }

        protected string CleanCSVString(string input)
        {
            string output = "\"" + input.Replace("\"", "\"\"").Replace("\r\n", " ").Replace("\r", " ").Replace("\n", "") + "\"";
            return output;
        }
    }
}

How can I count the number of characters in a Bash variable

jcomeau@intrepid:~$ mystring="one two three four five"
jcomeau@intrepid:~$ echo "string length: ${#mystring}"
string length: 23

link Couting characters, words, lenght of the words and total lenght in a sentence

How can I select an element in a component template?

Mimimum example for quick usage:

import { Component, ElementRef, ViewChild} from '@angular/core';

@Component({
  selector: 'my-app',
  template:
  `
  <input #inputEl value="hithere">
  `,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild('inputEl') inputEl:ElementRef; 

  ngAfterViewInit() {
    console.log(this.inputEl);
  }
}
  1. Put a template reference variable on the DOM element of interest. In our example this is the #inputEl on the <input> tag.
  2. In our component class inject the DOM element via the @ViewChild decorator
  3. Access the element in the ngAfterViewInit lifecycle hook.

Note:

If you want to manipulate the DOM elements use the Renderer2 API instead of accessing the elements directly. Permitting direct access to the DOM can make your application more vulnerable to XSS attacks

Check if checkbox is NOT checked on click - jQuery

jQuery to check for checked? Really?

if(!this.checked) {

Don't use a bazooka to do a razor's job.

Does not contain a static 'main' method suitable for an entry point

If you are like me, then you might have started with a Class Library, and then switched this to a Console Application. If so, change this...

namespace ClassLibrary1
{
    public class Class1
    {
    }
}

To this...

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

Change the Arrow buttons in Slick slider

For changing the color

.slick-prev:before {
  color: some-color!important;
}
.slick-next:before {
  color: some-color!important;
}

Verify host key with pysftp

Hi We sort of had the same problem if I understand you well. So check what pysftp version you're using. If it's the latest one which is 0.2.9 downgrade to 0.2.8. Check this out. https://github.com/Yenthe666/auto_backup/issues/47

What is NODE_ENV and how to use it in Express?

NODE_ENV is an environment variable made popular by the express web server framework. When a node application is run, it can check the value of the environment variable and do different things based on the value. NODE_ENV specifically is used (by convention) to state whether a particular environment is a production or a development environment. A common use-case is running additional debugging or logging code if running in a development environment.

Accessing NODE_ENV

You can use the following code to access the environment variable yourself so that you can perform your own checks and logic:

var environment = process.env.NODE_ENV

Assume production if you don't recognise the value:

var isDevelopment = environment === 'development'

if (isDevelopment) {
  setUpMoreVerboseLogging()
}

You can alternatively using express' app.get('env') function, but note that this is NOT RECOMMENDED as it defaults to "development", which may result in development code being accidentally run in a production environment - it's much safer if your app throws an error if this important value is not set (or if preferred, defaults to production logic as above).

Be aware that if you haven't explicitly set NODE_ENV for your environment, it will be undefined if you access it from process.env, there is no default.

Setting NODE_ENV

How to actually set the environment variable varies from operating system to operating system, and also depends on your user setup.

If you want to set the environment variable as a one-off, you can do so from the command line:

  • linux & mac: export NODE_ENV=production
  • windows: $env:NODE_ENV = 'production'

In the long term, you should persist this so that it isn't unset if you reboot - rather than list all the possible methods to do this, I'll let you search how to do that yourself!

Convention has dictated that there are two 'main' values you should use for NODE_ENV, either production or development, all lowercase. There's nothing to stop you from using other values, (test, for example, if you wish to use some different logic when running automated tests), but be aware that if you are using third-party modules, they may explicitly compare with 'production' or 'development' to determine what to do, so there may be side effects that aren't immediately obvious.

Finally, note that it's a really bad idea to try to set NODE_ENV from within a node application itself - if you do, it will only be applied to the process from which it was set, so things probably won't work like you'd expect them to. Don't do it - you'll regret it.

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

Syntax errors is not checked easily in external servers, just runtime errors.

What I do? Just like you, I use

ini_set('display_errors', 'On');
error_reporting(E_ALL);

However, before run I check syntax errors in a PHP file using an online PHP syntax checker.

The best, IMHO is PHP Code Checker

I copy all the source code, paste inside the main box and click the Analyze button.

It is not the most practical method, but the 2 procedures are complementary and it solves the problem completely

How to remove youtube branding after embedding video in web page?

It turns out this is either a poorly documented, intentionally misleading, or undocumented interaction between the "controls" param and the "modestbranding" param. There is no way to remove YouTube's logo from an embedded YouTube video, at least while the video controls are exposed. All you get to do is choose how and when you want the logo to appear. Here are the details:

If controls = 1 and modestbranding = 1, then the YouTube logo is bigger, is on the video still image as a grayscale watermark in the lower right, and shows when the play controls are exposed as a big gray scale watermark in the lower right. example: <iframe width="560" height="315" src="https://www.youtube.com/embed/Z6ytvzNlmRo?rel=0&amp;controls=1&amp&amp;showinfo=0&amp;modestbranding=1" frameborder="0"></iframe>

If controls = 1 and modestbranding = 0 (our change here), then the YouTube logo is smaller, is not on the video still image as a grayscale watermark in the lower right, and shows only when the controls are exposed as a white icon in the lower right. example: <iframe width="560" height="315" src="https://www.youtube.com/embed/Z6ytvzNlmRo?rel=0&amp;controls=1&amp&amp;showinfo=0&amp;modestbranding=0" frameborder="0"></iframe>

If controls = 0, then the modestbranding param is ignored and the YouTube logo is bigger, is on the video still image as a grayscale watermark in the lower right, the watermark appears on hover of a playing video, and the watermark appears in the lower right of any paused video. example: <iframe width="560" height="315" src="https://www.youtube.com/embed/Z6ytvzNlmRo?rel=0&amp;controls=0&amp&amp;showinfo=0&amp;modestbranding=1" frameborder="0"></iframe>

Number input type that takes only integers?

The integer input would mean that it can only take positive numbers, 0 and negative numbers too. This is how I have been able to achieve this using Javascript keypress.

<input type="number" (keypress)="keypress($event, $event.target.value)" >

keypress(evt, value){
  
    if (evt.charCode >= 48 && evt.charCode <= 57 || (value=="" && evt.charCode == 45))       
    {  
      return true;
    }
    return false;
}

The given code won't allow user to enter alphabets nor decimal on runtime, just positive and negative integer values.

Choosing bootstrap vs material design

As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).

On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.

  1. Bootstrap = responsive page
  2. AngularJS = MVC
  3. Material Design = great UI/UX

You can check awesome material design components for AngularJS:

https://material.angularjs.org


enter image description here

Demo: https://material.angularjs.org/latest/demo/ enter image description here

Hot to get all form elements values using jQuery?

jQuery has very helpful function called serialize.

Demo: http://jsfiddle.net/55xnJ/2/

//Just type:
$("#preview_form").serialize();

//to get result:
single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Use this in your my.ini under

[mysqldump]
    user=root
    password=anything

difference between css height : 100% vs height : auto

A height of 100% for is, presumably, the height of your browser's inner window, because that is the height of its parent, the page. An auto height will be the minimum height of necessary to contain .

How to get name of calling function/method in PHP?

My favourite way, in one line!

debug_backtrace()[1]['function'];

You can use it like this:

echo 'The calling function: ' . debug_backtrace()[1]['function'];

Note that this is only compatible with versions of PHP released within the last year. But it's a good idea to keep your PHP up to date anyway for security reasons.

How to set a cookie to expire in 1 hour in Javascript?

Code :

var now = new Date();
var time = now.getTime();
time += 3600 * 1000;
now.setTime(time);
document.cookie = 
'username=' + value + 
'; expires=' + now.toUTCString() + 
'; path=/';

Redirect output of mongo query to a csv file

Mongo's in-built export is working fine, unless you want to any data manipulation like format date, covert data types etc.

Following command works as charm.

    mongoexport -h localhost -d databse -c collection --type=csv 
    --fields erpNum,orderId,time,status 
    -q '{"time":{"$gt":1438275600000}, "status":{"$ne" :"Cancelled"}}' 
    --out report.csv

Java - get the current class name?

Here is a Android variant, but same principle can be used in plain Java too.

private static final String TAG = YourClass.class.getSimpleName();
private static final String TAG = YourClass.class.getName();

Vim 80 column layout concerns

Newer versions of vim allow a :set numberwidth=x value, which sets the width of the line number display. I don't really use folding etc, so I wouldn't know about that though. Drawing a thin vertical line is beyond the abilities of a console application though. GVim may allow this (I don't use it, so can't comment there).

Jquery how to find an Object by attribute in an Array

One more solution:

function firstOrNull(array, expr) {
  for (var i = 0; i < array.length; i++) {
    if (expr(array[i]))
      return array[i];
    }
  return null;
}

Using: firstOrNull([{ a: 1, b: 2 }, { a: 3, b: 3 }], function(item) { return item.a === 3; });

This function don't executes for each element from the array (it's valuable for large arrays)

Java: Rotating Images

This is how you can do it. This code assumes the existance of a buffered image called 'image' (like your comment says)

// The required drawing location
int drawLocationX = 300;
int drawLocationY = 300;

// Rotation information

double rotationRequired = Math.toRadians (45);
double locationX = image.getWidth() / 2;
double locationY = image.getHeight() / 2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);

// Drawing the rotated image at the required drawing locations
g2d.drawImage(op.filter(image, null), drawLocationX, drawLocationY, null);

get the margin size of an element with jquery

The CSS tag 'margin' is actually a shorthand for the four separate margin values, top/left/bottom/right. Use css('marginTop'), etc. - note they will have 'px' on the end if you have specified them that way.

Use parseInt() around the result to turn it in to the number value.

NB. As noted by Omaty, the order of the shorthand 'margin' tag is: top right bottom left - the above list was not written in a way intended to be the list order, just a list of that specified in the tag.

How to create a list of objects?

In Python, the name of the class refers to the class instance. Consider:

class A: pass
class B: pass
class C: pass

lst = [A, B, C]

# instantiate second class
b_instance = lst[1]()
print b_instance

How to convert JSON object to JavaScript array?

You can insert object items to an array as this

_x000D_
_x000D_
let obj = {_x000D_
  '1st': {_x000D_
    name: 'stackoverflow'_x000D_
  },_x000D_
  '2nd': {_x000D_
    name: 'stackexchange'_x000D_
  }_x000D_
};_x000D_
 _x000D_
 let wholeArray = Object.keys(obj).map(key => obj[key]);_x000D_
 _x000D_
 console.log(wholeArray);
_x000D_
_x000D_
_x000D_

Django, creating a custom 500/404 error page

If all you need is to show custom pages which have some fancy error messages for your site when DEBUG = False, then add two templates named 404.html and 500.html in your templates directory and it will automatically pick up this custom pages when a 404 or 500 is raised.

What is the $? (dollar question mark) variable in shell scripting?

$? is the result (exit code) of the last executed command.

Get UserDetails object from Security Context in Spring MVC controller

Let Spring 3 injection take care of this.

Thanks to tsunade21 the easiest way is:

 @RequestMapping(method = RequestMethod.GET)   
 public ModelAndView anyMethodNameGoesHere(Principal principal) {
        final String loggedInUserName = principal.getName();

 }

Use a content script to access the page context variables and functions

If you wish to inject pure function, instead of text, you can use this method:

_x000D_
_x000D_
function inject(){_x000D_
    document.body.style.backgroundColor = 'blue';_x000D_
}_x000D_
_x000D_
// this includes the function as text and the barentheses make it run itself._x000D_
var actualCode = "("+inject+")()"; _x000D_
_x000D_
document.documentElement.setAttribute('onreset', actualCode);_x000D_
document.documentElement.dispatchEvent(new CustomEvent('reset'));_x000D_
document.documentElement.removeAttribute('onreset');
_x000D_
_x000D_
_x000D_

And you can pass parameters (unfortunatelly no objects and arrays can be stringifyed) to the functions. Add it into the baretheses, like so:

_x000D_
_x000D_
function inject(color){_x000D_
    document.body.style.backgroundColor = color;_x000D_
}_x000D_
_x000D_
// this includes the function as text and the barentheses make it run itself._x000D_
var color = 'yellow';_x000D_
var actualCode = "("+inject+")("+color+")"; 
_x000D_
_x000D_
_x000D_

Check if string contains a value in array

You can concatenate the array values with implode and a separator of | and then use preg_match to search for the value.

Here is the solution I came up with ...

$emails = array('@gmail', '@hotmail', '@outlook', '@live', '@msn', '@yahoo', '@ymail', '@aol');
$emails = implode('|', $emails);

if(!preg_match("/$emails/i", $email)){
 // do something
}

How to build a query string for a URL in C#?

Just wanted to throw in my 2 cents:

public static class HttpClientExt
{
    public static Uri AddQueryParams(this Uri uri, string query)
    {
        var ub = new UriBuilder(uri);
        ub.Query = string.IsNullOrEmpty(uri.Query) ? query : string.Join("&", uri.Query.Substring(1), query);
        return ub.Uri;
    }

    public static Uri AddQueryParams(this Uri uri, IEnumerable<string> query)
    {
        return uri.AddQueryParams(string.Join("&", query));
    } 

    public static Uri AddQueryParams(this Uri uri, string key, string value)
    {
        return uri.AddQueryParams(string.Join("=", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value)));
    }

    public static Uri AddQueryParams(this Uri uri, params KeyValuePair<string,string>[] kvps)
    {
        return uri.AddQueryParams(kvps.Select(kvp => string.Join("=", HttpUtility.UrlEncode(kvp.Key), HttpUtility.UrlEncode(kvp.Value))));
    }

    public static Uri AddQueryParams(this Uri uri, IDictionary<string, string> kvps)
    {
        return uri.AddQueryParams(kvps.Select(kvp => string.Join("=", HttpUtility.UrlEncode(kvp.Key), HttpUtility.UrlEncode(kvp.Value))));
    }

    public static Uri AddQueryParams(this Uri uri, NameValueCollection nvc)
    {
        return uri.AddQueryParams(nvc.AllKeys.SelectMany(nvc.GetValues, (key, value) => string.Join("=", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value))));
    }
}

The docs say that uri.Query will start with a ? if it's non-empty and you should trim it off if you're going to modify it.

Note that HttpUtility.UrlEncode is found in System.Web.

Usage:

var uri = new Uri("https://api.del.icio.us/v1/posts/suggest").AddQueryParam("url","http://stackoverflow.com")

Unable to compile simple Java 10 / Java 11 project with Maven

Boosting your maven-compiler-plugin to 3.8.0 seems to be necessary but not sufficient. If you're still having problems, you should also make sure your JAVA_HOME environment variable is set to Java 10 (or 11) if you're running from the command line. (The error message you get won't tell you this.) Or if you're running from an IDE, you need to make sure it is set to run maven with your current JDK.

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

Using Javascript

I created a working demo that shows how to use the Google Maps API Directions Service in Javascript through a

  • DirectionsService object to send and receive direction requests
  • DirectionsRenderer object to render the returned route on the map

_x000D_
_x000D_
function initMap() {_x000D_
  var pointA = new google.maps.LatLng(51.7519, -1.2578),_x000D_
    pointB = new google.maps.LatLng(50.8429, -0.1313),_x000D_
    myOptions = {_x000D_
      zoom: 7,_x000D_
      center: pointA_x000D_
    },_x000D_
    map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),_x000D_
    // Instantiate a directions service._x000D_
    directionsService = new google.maps.DirectionsService,_x000D_
    directionsDisplay = new google.maps.DirectionsRenderer({_x000D_
      map: map_x000D_
    }),_x000D_
    markerA = new google.maps.Marker({_x000D_
      position: pointA,_x000D_
      title: "point A",_x000D_
      label: "A",_x000D_
      map: map_x000D_
    }),_x000D_
    markerB = new google.maps.Marker({_x000D_
      position: pointB,_x000D_
      title: "point B",_x000D_
      label: "B",_x000D_
      map: map_x000D_
    });_x000D_
_x000D_
  // get route from A to B_x000D_
  calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB);_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB) {_x000D_
  directionsService.route({_x000D_
    origin: pointA,_x000D_
    destination: pointB,_x000D_
    travelMode: google.maps.TravelMode.DRIVING_x000D_
  }, function(response, status) {_x000D_
    if (status == google.maps.DirectionsStatus.OK) {_x000D_
      directionsDisplay.setDirections(response);_x000D_
    } else {_x000D_
      window.alert('Directions request failed due to ' + status);_x000D_
    }_x000D_
  });_x000D_
}_x000D_
_x000D_
initMap();
_x000D_
    html,_x000D_
    body {_x000D_
      height: 100%;_x000D_
      margin: 0;_x000D_
      padding: 0;_x000D_
    }_x000D_
    #map-canvas {_x000D_
      height: 100%;_x000D_
      width: 100%;_x000D_
    }
_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>_x000D_
_x000D_
<div id="map-canvas"></div>
_x000D_
_x000D_
_x000D_

Also on Jsfiddle: http://jsfiddle.net/user2314737/u9no8te4/

Using Google Maps Web Services

You can use the Web Services using an API_KEY issuing a request like this:

https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key=API_KEY

An API_KEY can be obtained in the Google Developer Console with a quota of 2,500 free requests/day.

A request can return JSON or XML results that can be used to draw a path on a map.

Official documentation for Web Services using the Google Maps Directions API are here

How to get the text of the selected value of a dropdown list?

$("#select_id").find("option:selected").text();

It is helpful if your control is on Server side. In .NET it looks like:

$('#<%= dropdownID.ClientID %>').find("option:selected").text();

How to convert a String into an ArrayList?

If you are importing or you have an array (of type string) in your code and you have to convert it into arraylist (offcourse string) then use of collections is better. like this:

String array1[] = getIntent().getExtras().getStringArray("key1"); or String array1[] = ... then

List allEds = new ArrayList(); Collections.addAll(allEds, array1);

Calling Scalar-valued Functions in SQL

You are using an inline table value function. Therefore you must use Select * From function. If you want to use select function() you must use a scalar function.

https://msdn.microsoft.com/fr-fr/library/ms186755%28v=sql.120%29.aspx

Loop through an array of strings in Bash?

Single line looping,

 declare -a listOfNames=('db_a' 'db_b' 'db_c')
 for databaseName in ${listOfNames[@]}; do echo $databaseName; done;

you will get an output like this,

db_a
db_b
db_c

Maximum size of an Array in Javascript

I have built a performance framework that manipulates and graphs millions of datasets, and even then, the javascript calculation latency was on order of tens of milliseconds. Unless you're worried about going over the array size limit, I don't think you have much to worry about.

Add a new line to a text file in MS-DOS

Use the following:

echo (text here) >> (name here).txt

Ex. echo my name is jeff >> test.txt

test.txt

my name is jeff

You can use it in a script too.

Use Mockito to mock some methods but not others

According to docs :

Foo mock = mock(Foo.class, CALLS_REAL_METHODS);

// this calls the real implementation of Foo.getSomething()
value = mock.getSomething();

when(mock.getSomething()).thenReturn(fakeValue);

// now fakeValue is returned
value = mock.getSomething();

Bind event to right mouse click

Just use the event-handler. Something like this should work:

$('.js-my-element').bind('contextmenu', function(e) {
     e.preventDefault();
     alert('The eventhandler will make sure, that the contextmenu dosn&#39;t appear.');
});

What type of hash does WordPress use?

Start phpMyAdmin and access wp_users from your wordpress instance. Edit record and select user_pass function to match MD5. Write the string that will be your new password in VALUE. Click, GO. Go to your wordpress website and enter your new password. Back to phpMyAdmin you will see that WP changed the HASH to something like $P$B... enjoy!

adding .css file to ejs

You can use this

     var fs = require('fs');
     var myCss = {
         style : fs.readFileSync('./style.css','utf8');
     };

     app.get('/', function(req, res){
       res.render('index.ejs', {
       title: 'My Site',
       myCss: myCss
      });
     });

put this on template

   <%- myCss.style %>

just build style.css

  <style>
    body { 
     background-color: #D8D8D8;
     color: #444;
   }
  </style>

I try this for some custom css. It works for me

How to get the real and total length of char * (char array)?

This may sound Evil™ and I haven't tested it, but how about initializing all values in an array at allocation to '\0' and then using strlen() ? This would give you your so-called real value since it would stop counting at the first '\0' it encounters.

Well, now that I think about it though, please don't Ever™ do this. Unless, you want to land in a pile of dirty memory.

Also, for the allocated memory or the total memory you may use the following functions if your environment provides them:

What does !important mean in CSS?

It means, essentially, what it says; that 'this is important, ignore subsequent rules, and any usual specificity issues, apply this rule!'

In normal use a rule defined in an external stylesheet is overruled by a style defined in the head of the document, which, in turn, is overruled by an in-line style within the element itself (assuming equal specificity of the selectors). Defining a rule with the !important 'attribute' (?) discards the normal concerns as regards the 'later' rule overriding the 'earlier' ones.

Also, ordinarily, a more specific rule will override a less-specific rule. So:

a {
    /* css */
}

Is normally overruled by:

body div #elementID ul li a {
    /* css */
}

As the latter selector is more specific (and it doesn't, normally, matter where the more-specific selector is found (in the head or the external stylesheet) it will still override the less-specific selector (in-line style attributes will always override the 'more-', or the 'less-', specific selector as it's always more specific.

If, however, you add !important to the less-specific selector's CSS declaration, it will have priority.

Using !important has its purposes (though I struggle to think of them), but it's much like using a nuclear explosion to stop the foxes killing your chickens; yes, the foxes will be killed, but so will the chickens. And the neighbourhood.

It also makes debugging your CSS a nightmare (from personal, empirical, experience).

How to get the current time in Google spreadsheet using script editor?

use the JavaScript Date() object. There are a number of ways to get the time, date, timestamps, etc from the object. (Reference)

function myFunction() {
  var d = new Date();
  var timeStamp = d.getTime();  // Number of ms since Jan 1, 1970

  // OR:

  var currentTime = d.toLocaleTimeString(); // "12:35 PM", for instance
}

ReactJs: What should the PropTypes be for this.props.children?

Try a custom propTypes :

 const  childrenPropTypeLogic = (props, propName, componentName) => {
          const prop = props[propName];
          return React.Children
                   .toArray(prop)
                   .find(child => child.type !== 'div') && new Error(`${componentName} only accepts "div" elements`);
 };


static propTypes = {

   children : childrenPropTypeLogic

}

Fiddle

_x000D_
_x000D_
const {Component, PropTypes} = React;_x000D_
_x000D_
 const  childrenPropTypeLogic = (props, propName, componentName) => {_x000D_
             var error;_x000D_
          var prop = props[propName];_x000D_
    _x000D_
          React.Children.forEach(prop, function (child) {_x000D_
            if (child.type !== 'div') {_x000D_
              error = new Error(_x000D_
                '`' + componentName + '` only accepts children of type `div`.'_x000D_
              );_x000D_
            }_x000D_
          });_x000D_
    _x000D_
          return error;_x000D_
    };_x000D_
    _x000D_
  _x000D_
_x000D_
class ContainerComponent extends Component {_x000D_
  static propTypes = {_x000D_
    children: childrenPropTypeLogic,_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <div>_x000D_
        {this.props.children}_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
class App extends Component {_x000D_
   render(){_x000D_
    return (_x000D_
    <ContainerComponent>_x000D_
        <div>1</div>_x000D_
        <div>2</div>_x000D_
      </ContainerComponent>_x000D_
    )_x000D_
   }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App /> , document.querySelector('section'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<section />
_x000D_
_x000D_
_x000D_

Allow anonymous authentication for a single folder in web.config?

Use <location> configuration tag, and <allow users="?"/> to allow anonymous only or <allow users="*"/> for all:

<configuration>
   <location path="Path/To/Public/Folder">
      <system.web>
         <authorization>
            <allow users="?"/>
         </authorization>
      </system.web>
   </location>
</configuration>

How do I capture SIGINT in Python?

Register your handler with signal.signal like this:

#!/usr/bin/env python
import signal
import sys

def signal_handler(sig, frame):
    print('You pressed Ctrl+C!')
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()

Code adapted from here.

More documentation on signal can be found here.  

Angular 2 filter/search list

try this html code

<md-input #myInput placeholder="Item name..." [(ngModel)]="name"></md-input>

<div *ngFor="let item of filteredItems | search: name">
   {{item.name}}
</div>

use search pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'search'
})
export class SearchPipe implements PipeTransform {

  transform(value: any, args?: any): any {

    if(!value)return null;
    if(!args)return value;

    args = args.toLowerCase();

    return value.filter(function(item){
        return JSON.stringify(item).toLowerCase().includes(args);
    });
}

}

Android saving file to external storage

You need a permission for this

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

and method:

public boolean saveImageOnExternalData(String filePath, byte[] fileData) {

    boolean isFileSaved = false;
    try {
        File f = new File(filePath);
        if (f.exists())
            f.delete();
        f.createNewFile();
        FileOutputStream fos = new FileOutputStream(f);
        fos.write(fileData);
        fos.flush();
        fos.close();
        isFileSaved = true;
        // File Saved
    } catch (FileNotFoundException e) {
        System.out.println("FileNotFoundException");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("IOException");
        e.printStackTrace();
    }
    return isFileSaved;
    // File Not Saved
}

Java generics: multiple generic parameters?

You can follow one of the below approaches:

1) Basic, single type :

//One type
public static <T> void fill(List <T> list, T val) {

    for(int i=0; i<list.size(); i++){
        list.set(i, val);
    }

}

2) Multiple Types :

// multiple types as parameters
public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) {

    return val1+" "+val2;

}

3) Below will raise compiler error as 'T3 is not in the listing of generic types that are used in function declaration part.

//Raised compilation error
public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) {
    return 0;
}

Correct : Compiles fine

public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) {
    return 0;
}

Sample Class Code :

package generics.basics;

import java.util.ArrayList;
import java.util.List;

public class GenericMethods {

/*
 Declare the generic type parameter T in this method. 

 After the qualifiers public and static, you put <T> and 
 then followed it by return type, method name, and its parameters.

 Observe : type of val is 'T' and not '<T>'

 * */
//One type
public static <T> void fill(List <T> list, T val) {

    for(int i=0; i<list.size(); i++){
        list.set(i, val);
    }

}

// multiple types as parameters
public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) {

    return val1+" "+val2;

}

/*// Q: To audience -> will this compile ? 
 * 
 * public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) {

    return 0;

}*/

 public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) {

    return null;

}

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    list.add(10);
    list.add(20);
    System.out.println(list.toString());
    fill(list, 100);
    System.out.println(list.toString());

    List<String> Strlist = new ArrayList<>();
    Strlist.add("Chirag");
    Strlist.add("Nayak");
    System.out.println(Strlist.toString());
    fill(Strlist, "GOOD BOY");
    System.out.println(Strlist.toString());


    System.out.println(multipleTypeArgument("Chirag", 100));
    System.out.println(multipleTypeArgument(100,"Nayak"));

}

}

// class definition ends

Sample Output:

[10, 20]
[100, 100]
[Chirag, Nayak]
[GOOD BOY, GOOD BOY]
Chirag 100
100 Nayak

Setting environment variable in react-native?

The specific method used to set environment variables will vary by CI service, build approach, platform and tools you're using.

If you're using Buddybuild for CI to build an app and manage environment variables, and you need access to config from JS, create a env.js.example with keys (with empty string values) for check-in to source control, and use Buddybuild to produce an env.js file at build time in the post-clone step, hiding the file contents from the build logs, like so:

#!/usr/bin/env bash

ENVJS_FILE="$BUDDYBUILD_WORKSPACE/env.js"

# Echo what's happening to the build logs
echo Creating environment config file

# Create `env.js` file in project root
touch $ENVJS_FILE

# Write environment config to file, hiding from build logs
tee $ENVJS_FILE > /dev/null <<EOF
module.exports = {
  AUTH0_CLIENT_ID: '$AUTH0_CLIENT_ID',
  AUTH0_DOMAIN: '$AUTH0_DOMAIN'
}
EOF

Tip: Don't forget to add env.js to .gitignore so config and secrets aren't checked into source control accidentally during development.

You can then manage how the file gets written using the Buddybuild variables like BUDDYBUILD_VARIANTS, for instance, to gain greater control over how your config is produced at build time.

Can Flask have optional URL parameters?

I know this post is really old but I worked on a package that does this called flask_optional_routes. The code is located at: https://github.com/sudouser2010/flask_optional_routes.

from flask import Flask

from flask_optional_routes import OptionalRoutes


app = Flask(__name__)
optional = OptionalRoutes(app)

@optional.routes('/<user_id>/<user_name>?/')
def foobar(user_id, user_name=None):
    return 'it worked!'

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)

MySQL: Curdate() vs Now()

Just for the fun of it:

CURDATE() = DATE(NOW())

Or

NOW() = CONCAT(CURDATE(), ' ', CURTIME())

Difference between HashMap, LinkedHashMap and TreeMap

I prefer visual presentation:

+------------------------------------------------------------------------------+
¦   Property   ¦       HashMap       ¦      TreeMap      ¦     LinkedHashMap   ¦
¦--------------+---------------------+-------------------+---------------------¦
¦ Iteration    ¦  no guarantee order ¦ sorted according  ¦                     ¦
¦   Order      ¦ will remain constant¦ to the natural    ¦    insertion-order  ¦
¦              ¦      over time      ¦    ordering       ¦                     ¦
¦--------------+---------------------+-------------------+---------------------¦
¦  Get/put     ¦                     ¦                   ¦                     ¦
¦   remove     ¦         O(1)        ¦      O(log(n))    ¦         O(1)        ¦
¦ containsKey  ¦                     ¦                   ¦                     ¦
¦--------------+---------------------+-------------------+---------------------¦
¦              ¦                     ¦   NavigableMap    ¦                     ¦
¦  Interfaces  ¦         Map         ¦       Map         ¦         Map         ¦
¦              ¦                     ¦    SortedMap      ¦                     ¦
¦--------------+---------------------+-------------------+---------------------¦
¦              ¦                     ¦                   ¦                     ¦
¦     Null     ¦       allowed       ¦    only values    ¦       allowed       ¦
¦ values/keys  ¦                     ¦                   ¦                     ¦
¦--------------+---------------------------------------------------------------¦
¦              ¦   Fail-fast behavior of an iterator cannot be guaranteed      ¦
¦   Fail-fast  ¦ impossible to make any hard guarantees in the presence of     ¦
¦   behavior   ¦           unsynchronized concurrent modification              ¦
¦--------------+---------------------------------------------------------------¦
¦              ¦                     ¦                   ¦                     ¦
¦Implementation¦      buckets        ¦   Red-Black Tree  ¦    double-linked    ¦
¦              ¦                     ¦                   ¦       buckets       ¦
¦--------------+---------------------------------------------------------------¦
¦      Is      ¦                                                               ¦
¦ synchronized ¦              implementation is not synchronized               ¦
+------------------------------------------------------------------------------+

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

I ran into this issue with my desktop application ('Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine). I did not have the option to build as a 32 bit app. Hoping this would help others in the same situation.

I did the following and the issue went away:

  1. Installed the 64 bit version of Microsoft Access Database Engine 2010 Redistributable, as suggested by neo

  2. Changed my provider to Microsoft.ACE.OLEDB.12.0

CSS Box Shadow Bottom Only

Try this

-moz-box-shadow:0 5px 5px rgba(182, 182, 182, 0.75);
-webkit-box-shadow: 0 5px 5px rgba(182, 182, 182, 0.75);
box-shadow: 0 5px 5px rgba(182, 182, 182, 0.75);

You can see it in http://jsfiddle.net/wJ7qp/

Set value of textarea in jQuery

I've used $(textarea).val/html/text(any_str_var) all worked for me. If you want to be sure that your variable as a string is added to the textarea, you can always concat like so:

$(textarea).val(unknown_var + '')

.val() method is definitely used on textarea - see: https://api.jquery.com/val/

.html() can be used to get or set the contents of any element - see: https://api.jquery.com/html/#html2

.text() is the same as .html except this can be used to set XML content: see - https://api.jquery.com/text/#text-text

You can also read more about how each act upon special characters with each of those links.

Only read selected columns

You could also use JDBC to achieve this. Let's create a sample csv file.

write.table(x=mtcars, file="mtcars.csv", sep=",", row.names=F, col.names=T) # create example csv file

Download and save the the CSV JDBC driver from this link: http://sourceforge.net/projects/csvjdbc/files/latest/download

> library(RJDBC)

> path.to.jdbc.driver <- "jdbc//csvjdbc-1.0-18.jar"
> drv <- JDBC("org.relique.jdbc.csv.CsvDriver", path.to.jdbc.driver)
> conn <- dbConnect(drv, sprintf("jdbc:relique:csv:%s", getwd()))

> head(dbGetQuery(conn, "select * from mtcars"), 3)
   mpg cyl disp  hp drat    wt  qsec vs am gear carb
1   21   6  160 110  3.9  2.62 16.46  0  1    4    4
2   21   6  160 110  3.9 2.875 17.02  0  1    4    4
3 22.8   4  108  93 3.85  2.32 18.61  1  1    4    1

> head(dbGetQuery(conn, "select mpg, gear from mtcars"), 3)
   MPG GEAR
1   21    4
2   21    4
3 22.8    4

delete vs delete[] operators in C++

delete is used for one single pointer and delete[] is used for deleting an array through a pointer. This might help you to understand better.

How big can a MySQL database get before performance starts to degrade

I'm currently managing a MySQL database on Amazon's cloud infrastructure that has grown to 160 GB. Query performance is fine. What has become a nightmare is backups, restores, adding slaves, or anything else that deals with the whole dataset, or even DDL on large tables. Getting a clean import of a dump file has become problematic. In order to make the process stable enough to automate, various choices needed to be made to prioritize stability over performance. If we ever had to recover from a disaster using a SQL backup, we'd be down for days.

Horizontally scaling SQL is also pretty painful, and in most cases leads to using it in ways you probably did not intend when you chose to put your data in SQL in the first place. Shards, read slaves, multi-master, et al, they are all really shitty solutions that add complexity to everything you ever do with the DB, and not one of them solves the problem; only mitigates it in some ways. I would strongly suggest looking at moving some of your data out of MySQL (or really any SQL) when you start approaching a dataset of a size where these types of things become an issue.

Update: a few years later, and our dataset has grown to about 800 GiB. In addition, we have a single table which is 200+ GiB and a few others in the 50-100 GiB range. Everything I said before holds. It still performs just fine, but the problems of running full dataset operations have become worse.

AngularJS : The correct way of binding to a service properties

Building on the examples above I thought I'd throw in a way of transparently binding a controller variable to a service variable.

In the example below changes to the Controller $scope.count variable will automatically be reflected in the Service count variable.

In production we're actually using the this binding to update an id on a service which then asynchronously fetches data and updates its service vars. Further binding that means that controllers automagically get updated when the service updates itself.

The code below can be seen working at http://jsfiddle.net/xuUHS/163/

View:

<div ng-controller="ServiceCtrl">
    <p> This is my countService variable : {{count}}</p>
    <input type="number" ng-model="count">
    <p> This is my updated after click variable : {{countS}}</p>

    <button ng-click="clickC()" >Controller ++ </button>
    <button ng-click="chkC()" >Check Controller Count</button>
    </br>

    <button ng-click="clickS()" >Service ++ </button>
    <button ng-click="chkS()" >Check Service Count</button>
</div>

Service/Controller:

var app = angular.module('myApp', []);

app.service('testService', function(){
    var count = 10;

    function incrementCount() {
      count++;
      return count;
    };

    function getCount() { return count; }

    return {
        get count() { return count },
        set count(val) {
            count = val;
        },
        getCount: getCount,
        incrementCount: incrementCount
    }

});

function ServiceCtrl($scope, testService)
{

    Object.defineProperty($scope, 'count', {
        get: function() { return testService.count; },
        set: function(val) { testService.count = val; },
    });

    $scope.clickC = function () {
       $scope.count++;
    };
    $scope.chkC = function () {
        alert($scope.count);
    };

    $scope.clickS = function () {
       ++testService.count;
    };
    $scope.chkS = function () {
        alert(testService.count);
    };

}

Deploy a project using Git push

As complementary answer I would like to offer an alternative. I'm using git-ftp and it works fine.

https://github.com/git-ftp/git-ftp

Easy to use, only type:

git ftp push

and git will automatically upload project files.

Regards

getaddrinfo: nodename nor servname provided, or not known

I ran into a similar situation today - deploying an app to a mac os x server, and receiving the 'getaddrinfo' message when I tried to access an external api. It turns out that the error occurs when the ssh session that originally launched the app is no longer active. That's why everything works perfectly if you ssh into your server and run commands manually (or launch the server manually) - as long as you keep your ssh session alive, this error won't occur.

Whether this is a bug or a quirk in OS X, I'm not sure. Here's the page that led me to the solution - http://lists.apple.com/archives/unix-porting/2010/Jul/msg00001.html

All I had to do was update my capistrano task to launch the app using 'nohup'. So changing

run "cd #{current_path} && RAILS_ENV=production unicorn_rails -c config/unicorn.rb -D"

to

run "cd #{current_path} && RAILS_ENV=production nohup unicorn_rails -c config/unicorn.rb -D"

did the trick for me.

Hope this helps somebody - it was quite a pain to figure out!

SQL providerName in web.config

 WebConfigurationManager.ConnectionStrings["YourConnectionString"].ProviderName;

How to display alt text for an image in chrome

To display the Alt text of missing images, we have to add a style like this. I think, there is no need to add extra javascript for this.

.Your_Image_Class_Name {
  font-size: 14px;
}

It's work for me. Enjoy!!!!

Why doesn't margin:auto center an image?

i know this is an old post, but wanted to share how i solved the same problem.

My image was inheriting a float:left from a parent class. By setting float:none I was able to make margin:0 auto and display: block work properly. Hope it may help someone in the future.

How to communicate between iframe and the parent site?

You can also use

postMessage(message, '*');

Maintain model of scope when changing between views in AngularJS

Solution that will work for multiple scopes and multiple variables within those scopes

This service was based off of Anton's answer, but is more extensible and will work across multiple scopes and allows the selection of multiple scope variables in the same scope. It uses the route path to index each scope, and then the scope variable names to index one level deeper.

Create service with this code:

angular.module('restoreScope', []).factory('restoreScope', ['$rootScope', '$route', function ($rootScope, $route) {

    var getOrRegisterScopeVariable = function (scope, name, defaultValue, storedScope) {
        if (storedScope[name] == null) {
            storedScope[name] = defaultValue;
        }
        scope[name] = storedScope[name];
    }

    var service = {

        GetOrRegisterScopeVariables: function (names, defaultValues) {
            var scope = $route.current.locals.$scope;
            var storedBaseScope = angular.fromJson(sessionStorage.restoreScope);
            if (storedBaseScope == null) {
                storedBaseScope = {};
            }
            // stored scope is indexed by route name
            var storedScope = storedBaseScope[$route.current.$$route.originalPath];
            if (storedScope == null) {
                storedScope = {};
            }
            if (typeof names === "string") {
                getOrRegisterScopeVariable(scope, names, defaultValues, storedScope);
            } else if (Array.isArray(names)) {
                angular.forEach(names, function (name, i) {
                    getOrRegisterScopeVariable(scope, name, defaultValues[i], storedScope);
                });
            } else {
                console.error("First argument to GetOrRegisterScopeVariables is not a string or array");
            }
            // save stored scope back off
            storedBaseScope[$route.current.$$route.originalPath] = storedScope;
            sessionStorage.restoreScope = angular.toJson(storedBaseScope);
        },

        SaveState: function () {
            // get current scope
            var scope = $route.current.locals.$scope;
            var storedBaseScope = angular.fromJson(sessionStorage.restoreScope);

            // save off scope based on registered indexes
            angular.forEach(storedBaseScope[$route.current.$$route.originalPath], function (item, i) {
                storedBaseScope[$route.current.$$route.originalPath][i] = scope[i];
            });

            sessionStorage.restoreScope = angular.toJson(storedBaseScope);
        }
    }

    $rootScope.$on("savestate", service.SaveState);

    return service;
}]);

Add this code to your run function in your app module:

$rootScope.$on('$locationChangeStart', function (event, next, current) {
    $rootScope.$broadcast('savestate');
});

window.onbeforeunload = function (event) {
    $rootScope.$broadcast('savestate');
};

Inject the restoreScope service into your controller (example below):

function My1Ctrl($scope, restoreScope) {
    restoreScope.GetOrRegisterScopeVariables([
         // scope variable name(s)
        'user',
        'anotherUser'
    ],[
        // default value(s)
        { name: 'user name', email: '[email protected]' },
        { name: 'another user name', email: '[email protected]' }
    ]);
}

The above example will initialize $scope.user to the stored value, otherwise will default to the provided value and save that off. If the page is closed, refreshed, or the route is changed, the current values of all registered scope variables will be saved off, and will be restored the next time the route/page is visited.

Delete multiple rows by selecting checkboxes using PHP

Delete Multiple checkbox using PHP Code

<input type="checkbox" name="chkbox[]  value=".$row[0]."/>
<input type="submit" name="delete" value="delete"/>
<?php
if(isset($_POST['delete']))
{
 $cnt=array();
 $cnt=count($_POST['chkbox']);
 for($i=0;$i<$cnt;$i++)
  {
     $del_id=$_POST['chkbox'][$i];
     $query="delete from $tablename where Id=".$del_id;
     mysql_query($query);
  }
}

maven command line how to point to a specific settings.xml for a single command?

You can simply use:

mvn --settings YourOwnSettings.xml clean install

or

mvn -s YourOwnSettings.xml clean install

How to read file from res/raw by name

With the help of the given links I was able to solve the problem myself. The correct way is to get the resource ID with

getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
                             "raw", getPackageName());

To get it as a InputStream

InputStream ins = getResources().openRawResource(
            getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
            "raw", getPackageName()));

How do I generate random number for each row in a TSQL Select?

RAND(CHECKSUM(NEWID()))

The above will generate a (pseudo-) random number between 0 and 1, exclusive. If used in a select, because the seed value changes for each row, it will generate a new random number for each row (it is not guaranteed to generate a unique number per row however).

Example when combined with an upper limit of 10 (produces numbers 1 - 10):

CAST(RAND(CHECKSUM(NEWID())) * 10 as INT) + 1

Transact-SQL Documentation:

  1. CAST(): https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql
  2. RAND(): http://msdn.microsoft.com/en-us/library/ms177610.aspx
  3. CHECKSUM(): http://msdn.microsoft.com/en-us/library/ms189788.aspx
  4. NEWID(): https://docs.microsoft.com/en-us/sql/t-sql/functions/newid-transact-sql

state provider and route provider in angularJS

You shouldn't use both ngRoute and UI-router. Here's a sample code for UI-router:

_x000D_
_x000D_
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
  _x000D_
  $stateProvider_x000D_
    .state('state1', {_x000D_
      url: "/state1",_x000D_
      templateUrl: "partials/state1.html",_x000D_
      controller: 'YourCtrl'_x000D_
    })_x000D_
    _x000D_
    .state('state2', {_x000D_
      url: "/state2",_x000D_
      templateUrl: "partials/state2.html",_x000D_
      controller: 'YourOtherCtrl'_x000D_
    });_x000D_
    $urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
_x000D_
_x000D_

You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?

You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router

Bash: infinite sleep (infinite blocking)

What about sending a SIGSTOP to itself?

This should pause the process until SIGCONT is received. Which is in your case: never.

kill -STOP "$$";
# grace time for signal delivery
sleep 60;

Mapping many-to-many association table with extra column(s)

I search a way to map a many-to-many association table with extra column(s) with hibernate in xml files configuration.

Assuming with have two table 'a' & 'c' with a many to many association with a column named 'extra'. Cause I didn't find any complete example, here is my code. Hope it will help :).

First here is the Java objects.

public class A implements Serializable{  

    protected int id;
    // put some others fields if needed ...   
    private Set<AC> ac = new HashSet<AC>();

    public A(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Set<AC> getAC() {
        return ac;
    }

    public void setAC(Set<AC> ac) {
        this.ac = ac;
    }

    /** {@inheritDoc} */
    @Override
    public int hashCode() {
        final int prime = 97;
        int result = 1;
        result = prime * result + id;
        return result;
    }

    /** {@inheritDoc} */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!(obj instanceof A))
            return false;
        final A other = (A) obj;
        if (id != other.getId())
            return false;
        return true;
    }

}

public class C implements Serializable{

    protected int id;
    // put some others fields if needed ...    

    public C(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    /** {@inheritDoc} */
    @Override
    public int hashCode() {
        final int prime = 98;
        int result = 1;
        result = prime * result + id;
        return result;
    }

    /** {@inheritDoc} */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!(obj instanceof C))
            return false;
        final C other = (C) obj;
        if (id != other.getId())
            return false;
        return true;
    }

}

Now, we have to create the association table. The first step is to create an object representing a complex primary key (a.id, c.id).

public class ACId implements Serializable{

    private A a;
    private C c;

    public ACId() {
        super();
    }

    public A getA() {
        return a;
    }
    public void setA(A a) {
        this.a = a;
    }
    public C getC() {
        return c;
    }
    public void setC(C c) {
        this.c = c;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((a == null) ? 0 : a.hashCode());
        result = prime * result
                + ((c == null) ? 0 : c.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ACId other = (ACId) obj;
        if (a == null) {
            if (other.a != null)
                return false;
        } else if (!a.equals(other.a))
            return false;
        if (c == null) {
            if (other.c != null)
                return false;
        } else if (!c.equals(other.c))
            return false;
        return true;
    }
}

Now let's create the association object itself.

public class AC implements java.io.Serializable{

    private ACId id = new ACId();
    private String extra;

    public AC(){

    }

    public ACId getId() {
        return id;
    }

    public void setId(ACId id) {
        this.id = id;
    }

    public A getA(){
        return getId().getA();
    }

    public C getC(){
        return getId().getC();
    }

    public void setC(C C){
        getId().setC(C);
    }

    public void setA(A A){
        getId().setA(A);
    }

    public String getExtra() {
        return extra;
    }

    public void setExtra(String extra) {
        this.extra = extra;
    }

    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;

        AC that = (AC) o;

        if (getId() != null ? !getId().equals(that.getId())
                : that.getId() != null)
            return false;

        return true;
    }

    public int hashCode() {
        return (getId() != null ? getId().hashCode() : 0);
    }
}

At this point, it's time to map all our classes with hibernate xml configuration.

A.hbm.xml and C.hxml.xml (quiete the same).

<class name="A" table="a">
        <id name="id" column="id_a" unsaved-value="0">
            <generator class="identity">
                <param name="sequence">a_id_seq</param>
            </generator>
        </id>
<!-- here you should map all others table columns -->
<!-- <property name="otherprop" column="otherprop" type="string" access="field" /> -->
    <set name="ac" table="a_c" lazy="true" access="field" fetch="select" cascade="all">
        <key>
            <column name="id_a" not-null="true" />
        </key>
        <one-to-many class="AC" />
    </set>
</class>

<class name="C" table="c">
        <id name="id" column="id_c" unsaved-value="0">
            <generator class="identity">
                <param name="sequence">c_id_seq</param>
            </generator>
        </id>
</class>

And then association mapping file, a_c.hbm.xml.

<class name="AC" table="a_c">
    <composite-id name="id" class="ACId">
        <key-many-to-one name="a" class="A" column="id_a" />
        <key-many-to-one name="c" class="C" column="id_c" />
    </composite-id>
    <property name="extra" type="string" column="extra" />
</class>

Here is the code sample to test.

A = ADao.get(1);
C = CDao.get(1);

if(A != null && C != null){
    boolean exists = false;
            // just check if it's updated or not
    for(AC a : a.getAC()){
        if(a.getC().equals(c)){
            // update field
            a.setExtra("extra updated");
            exists = true;
            break;
        }
    }

    // add 
    if(!exists){
        ACId idAC = new ACId();
        idAC.setA(a);
        idAC.setC(c);

        AC AC = new AC();
        AC.setId(idAC);
        AC.setExtra("extra added"); 
        a.getAC().add(AC);
    }

    ADao.save(A);
}

node.js string.replace doesn't work?

According to the Javascript standard, String.replace isn't supposed to modify the string itself. It just returns the modified string. You can refer to the Mozilla Developer Network documentation for more info.

You can always just set the string to the modified value:

variableABC = variableABC.replace('B', 'D')

Edit: The code given above is to only replace the first occurrence.

To replace all occurrences, you could do:

 variableABC = variableABC.replace(/B/g, "D");  

To replace all occurrences and ignore casing

 variableABC = variableABC.replace(/B/gi, "D");  

How to use bootstrap datepicker

You should include bootstrap-datepicker.js after bootstrap.js and you should bind the datepicker to your control.

$(function(){
   $('.datepicker').datepicker({
      format: 'mm-dd-yyyy'
    });
});

Working with huge files in VIM

Since you don't need to actually edit the file:

  1. view (or vim -R) should work reasonably well on large files.
  2. Or you can use more or less

How can I disable an <option> in a <select> based on its value in JavaScript?

I would like to give you also the idea to disable an <option> with a given defined value (not innerhtml). I recommend to it with jQuery to get the simplest way. See my sample below.

HTML

Status:  
<div id="option">
   <select class="status">
      <option value="hand" selected>Hand</option>
      <option value="simple">Typed</option>
      <option value="printed">Printed</option>
   </select>
</div>

Javascript

The idea here is how to disable Printed option when current Status is Hand

var status = $('#option').find('.status');//to get current the selected value
var op = status.find('option');//to get the elements for disable attribute
(status.val() == 'hand')? op[2].disabled = true: op[2].disabled = false;

You may see how it works here:

https://jsfiddle.net/chetabahana/f7ejxhnk/28/

Execution failed for task ':app:processDebugResources' even with latest build tools

Error:Execution failed for task com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException:

finished with non-zero exit value 1

One reason for this error to occure is that the file path to a resource file is to long:

Error: File path too long on Windows, keep below 240 characters 

Fix: Move your project folder closer to the root of your disk

Don't:// folder/folder/folder/folder/very_long_folder_name/MyProject...

Do://folder/short_name/MyProject


Another reason could be duplicated resources or name spaces

Example:

  <style name="MyButton" parent="android:Widget.Button">
      <item name="android:textColor">@color/accent_color</item>
      <item name="android:textColor">#000000</item>
  </style>

And make sure all file names and extensions are in lowercase

Wrong

myimage.PNG
myImage.png

Correct

my_image.png

Make sure to Clean/Rebuild project

(delete the 'build' folder)

Peak signal detection in realtime timeseries data

Perl implementation of @Jean-Paul's algorithm.

#!/usr/bin/perl

use strict;
use Data::Dumper;

sub mean {
    my $data = shift;
    my $sum = 0;
    my $mean_val = 0;
    for my $item (@$data) {
        $sum += $item;
    }
    $mean_val = $sum / (scalar @$data) if @$data;
    return $mean_val;
}

sub variance {
    my $data = shift;
    my $variance_val = 0;
    my $mean_val = mean($data);
    my $sum = 0;
    for my $item (@$data) {
        $sum += ($item - $mean_val)**2;
    }
    $variance_val = $sum / (scalar @$data) if @$data;
    return $variance_val;
}

sub std {
    my $data = shift;
    my $variance_val = variance($data);
    return sqrt($variance_val);
}

# @param y - The input vector to analyze
# @parameter lag - The lag of the moving window
# @parameter threshold - The z-score at which the algorithm signals
# @parameter influence - The influence (between 0 and 1) of new signals on the mean and standard deviation
sub thresholding_algo {
    my ($y, $lag, $threshold, $influence) = @_;

    my @signals = (0) x @$y;
    my @filteredY = @$y;
    my @avgFilter = (0) x @$y;
    my @stdFilter = (0) x @$y;

    $avgFilter[$lag - 1] = mean([@$y[0..$lag-1]]);
    $stdFilter[$lag - 1] = std([@$y[0..$lag-1]]);

    for (my $i=$lag; $i <= @$y - 1; $i++) {
        if (abs($y->[$i] - $avgFilter[$i-1]) > $threshold * $stdFilter[$i-1]) {
            if ($y->[$i] > $avgFilter[$i-1]) {
                $signals[$i] = 1;
            } else {
                $signals[$i] = -1;
            }

            $filteredY[$i] = $influence * $y->[$i] + (1 - $influence) * $filteredY[$i-1];
            $avgFilter[$i] = mean([@filteredY[($i-$lag)..($i-1)]]);
            $stdFilter[$i] = std([@filteredY[($i-$lag)..($i-1)]]);
        }
        else {
            $signals[$i] = 0;
            $filteredY[$i] = $y->[$i];
            $avgFilter[$i] = mean([@filteredY[($i-$lag)..($i-1)]]);
            $stdFilter[$i] = std([@filteredY[($i-$lag)..($i-1)]]);
        }
    }

    return {
        signals => \@signals,
        avgFilter => \@avgFilter,
        stdFilter => \@stdFilter
    };
}

my $y = [1,1,1.1,1,0.9,1,1,1.1,1,0.9,1,1.1,1,1,0.9,1,1,1.1,1,1,1,1,1.1,0.9,1,1.1,1,1,0.9,
       1,1.1,1,1,1.1,1,0.8,0.9,1,1.2,0.9,1,1,1.1,1.2,1,1.5,1,3,2,5,3,2,1,1,1,0.9,1,1,3,
       2.6,4,3,3.2,2,1,1,0.8,4,4,2,2.5,1,1,1];

my $lag = 30;
my $threshold = 5;
my $influence = 0;

my $result = thresholding_algo($y, $lag, $threshold, $influence);

print Dumper $result;

jquery - Check for file extension before uploading

        function yourfunctionName() {
            var yourFileName = $("#yourinputfieldis").val();

            var yourFileExtension = yourFileName .replace(/^.*\./, '');
            switch (yourFileExtension ) {
                case 'pdf':
                case 'jpg':
                case 'doc':
                    $("#formId").submit();// your condition what you want to do
                    break;
                default:
                    alert('your File extension is wrong.');
                    this.value = '';
            }    
        }

How do I use cx_freeze?

I'm really not sure what you're doing to get that error, it looks like you're trying to run cx_Freeze on its own, without arguments. So here is a short step-by-step guide on how to do it in windows (Your screenshot looks rather like the windows command line, so I'm assuming that's your platform)

  1. Write your setup.py file. Your script above looks correct so it should work, assuming that your script exists.

  2. Open the command line (Start -> Run -> "cmd")

  3. Go to the location of your setup.py file and run python setup.py build

Notes:

  1. There may be a problem with the name of your script. "Main.py" contains upper case letters, which might cause confusion since windows' file names are not case sensitive, but python is. My approach is to always use lower case for scripts to avoid any conflicts.

  2. Make sure that python is on your PATH (read http://docs.python.org/using/windows.html)1

  3. Make sure are are looking at the new cx_Freeze documentation. Google often seems to bring up the old docs.

How do I find the version of Apache running without access to the command line?

In the default installation, call a page that doesn't exist and you get an error with the version at the end:

Object not found!

The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.
If you think this is a server error, please contact the webmaster.
Error 404
localhost
10/03/08 14:41:45
Apache/2.2.8 (Win32) DAV/2 mod_ssl/2.2.8 OpenSSL/0.9.8g mod_autoindex_color PHP/5.2.5

MVC Return Partial View as JSON

Url.Action("Evil", model)

will generate a get query string but your ajax method is post and it will throw error status of 500(Internal Server Error). – Fereydoon Barikzehy Feb 14 at 9:51

Just Add "JsonRequestBehavior.AllowGet" on your Json object.

Angularjs $q.all

The issue seems to be that you are adding the deffered.promise when deffered is itself the promise you should be adding:

Try changing to promises.push(deffered); so you don't add the unwrapped promise to the array.

 UploadService.uploadQuestion = function(questions){

            var promises = [];

            for(var i = 0 ; i < questions.length ; i++){

                var deffered  = $q.defer();
                var question  = questions[i]; 

                $http({

                    url   : 'upload/question',
                    method: 'POST',
                    data  : question
                }).
                success(function(data){
                    deffered.resolve(data);
                }).
                error(function(error){
                    deffered.reject();
                });

                promises.push(deffered);
            }

            return $q.all(promises);
        }

Jquery get form field value

You have to use value attribute to get its value

<input type="text" name="FirstName" value="First Name" />

try -

var text = $('#DynamicValueAssignedHere').find('input[name="FirstName"]').val();

How to Display Multiple Google Maps per page with API V3

OP wanted two specific maps, but if you'd like to have a dynamic number of maps on one page (for instance a list of retailer locations) you need to go another route. The standard implementation of Google maps API defines the map as a global variable, this won't work with a dynamic number of maps. Here's my code to solve this without global variables:

function mapAddress(mapElement, address) {
var geocoder = new google.maps.Geocoder();

geocoder.geocode({ 'address': address }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        var mapOptions = {
            zoom: 14,
            center: results[0].geometry.location,
            disableDefaultUI: true
        };
        var map = new google.maps.Map(document.getElementById(mapElement), mapOptions);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
    } else {
        alert("Geocode was not successful for the following reason: " + status);
    }
});
}

Just pass the ID and address of each map to the function to plot the map and mark the address.

Sort dataGridView columns in C# ? (Windows Form)

dataGridView1.Sort(dataGridView1.Columns[0],ListSortDirection.Ascending);

Is optimisation level -O3 dangerous in g++?

Yes, O3 is buggier. I'm a compiler developer and I've identified clear and obvious gcc bugs caused by O3 generating buggy SIMD assembly instructions when building my own software. From what I've seen, most production software ships with O2 which means O3 will get less attention wrt testing and bug fixes.

Think of it this way: O3 adds more transformations on top of O2, which adds more transformations on top of O1. Statistically speaking, more transformations means more bugs. That's true for any compiler.

Is quitting an application frowned upon?

This is an interesting and insightful discussion with so many experts contributing. I feel this post should be looped back from within the Android development main website, because it does revolve around one of the core designs of the Android OS.

I would also like to add my two cents here.

So far I have been impressed with Android's way of handling lifecycle events, bringing the concept of a web-like experience to native apps.

Having said that I still believe that there should be a Quit button. Why? ... not for me or Ted or any of the tech gurus here, but for the sole purpose of meeting an end user demand.

Though I am not a big fan of Windows, but long back they introduced a concept that most end users are used to (an X button) ... "I want to quit running a widget when 'I' want to".

That does not mean someone (OS, developer?) will take care of that at its/his/her own discretion... it simply means "where is my Red X button that I am used to". My action should be analogous to 'end a call on pressing of a button', 'turn off the device by pressing a button', and so on and so forth ... it's a perception. It brings a satisfaction per se that my action indeed achieve its purpose.

Even though a developer can spoof this behavior using suggestions given here, the perception still remains i.e. an application should completely cease to function (now), by an independent, trusted and neutral source (OS) on demand from the end user.

How can I send an HTTP POST request to a server from Excel using VBA?

I did this before using the MSXML library and then using the XMLHttpRequest object, see here.

Using SSH keys inside docker container

You can pass the authorised keys in to your container using a shared folder and set permissions using a docker file like this:

FROM ubuntu:16.04
RUN apt-get install -y openssh-server
RUN mkdir /var/run/sshd
EXPOSE 22
RUN cp /root/auth/id_rsa.pub /root/.ssh/authorized_keys
RUN rm -f /root/auth
RUN chmod 700 /root/.ssh
RUN chmod 400 /root/.ssh/authorized_keys
RUN chown root. /root/.ssh/authorized_keys
CMD /usr/sbin/sshd -D

And your docker run contains something like the following to share an auth directory on the host (holding the authorised_keys) with the container then open up the ssh port which will be accessable through port 7001 on the host.

-d -v /home/thatsme/dockerfiles/auth:/root/auth -–publish=127.0.0.1:7001:22

You may want to look at https://github.com/jpetazzo/nsenter which appears to be another way to open a shell on a container and execute commands within a container.

How to change MySQL column definition?

This should do it:

ALTER TABLE test MODIFY locationExpert VARCHAR(120) 

How to display a list inline using Twitter's Bootstrap

While TheBrent's answer is true in general, it does not answer the question of how to do it in the official bootstrap way. The markup for bootstrap is simple:

<ul class="inline">
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

Source

http://jsfiddle.net/MgcDU/4602/

C++ equivalent of StringBuffer/StringBuilder?

The Rope container may be worth if have to insert/delete string into the random place of destination string or for a long char sequences. Here is an example from SGI's implementation:

crope r(1000000, 'x');          // crope is rope<char>. wrope is rope<wchar_t>
                                // Builds a rope containing a million 'x's.
                                // Takes much less than a MB, since the
                                // different pieces are shared.
crope r2 = r + "abc" + r;       // concatenation; takes on the order of 100s
                                // of machine instructions; fast
crope r3 = r2.substr(1000000, 3);       // yields "abc"; fast.
crope r4 = r2.substr(1000000, 1000000); // also fast.
reverse(r2.mutable_begin(), r2.mutable_end());
                                // correct, but slow; may take a
                                // minute or more.

AddRange to a Collection

Remember that each Add will check the capacity of the collection and resize it whenever necessary (slower). With AddRange, the collection will be set the capacity and then added the items (faster). This extension method will be extremely slow, but will work.

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

I know this is an older question, but for reference, a really simple way for formatting dates without any data annotations or any other settings is as follows:

@Html.TextBoxFor(m => m.StartDate, new { @Value = Model.StartDate.ToString("dd-MMM-yyyy") })

The above format can of course be changed to whatever.

How to put labels over geom_bar in R with ggplot2

As with many tasks in ggplot, the general strategy is to put what you'd like to add to the plot into a data frame in a way such that the variables match up with the variables and aesthetics in your plot. So for example, you'd create a new data frame like this:

dfTab <- as.data.frame(table(df))
colnames(dfTab)[1] <- "x"
dfTab$lab <- as.character(100 * dfTab$Freq / sum(dfTab$Freq))

So that the x variable matches the corresponding variable in df, and so on. Then you simply include it using geom_text:

ggplot(df) + geom_bar(aes(x,fill=x)) + 
    geom_text(data=dfTab,aes(x=x,y=Freq,label=lab),vjust=0) +
    opts(axis.text.x=theme_blank(),axis.ticks=theme_blank(),
        axis.title.x=theme_blank(),legend.title=theme_blank(),
        axis.title.y=theme_blank())

This example will plot just the percentages, but you can paste together the counts as well via something like this:

dfTab$lab <- paste(dfTab$Freq,paste("(",dfTab$lab,"%)",sep=""),sep=" ")

Note that in the current version of ggplot2, opts is deprecated, so we would use theme and element_blank now.

CSS Div stretch 100% page height

* {
margin: 0;
}
html, body {
height: 90%;
}
.content {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto ;
}

Vue.js img src concatenate variable and text

just try

_x000D_
_x000D_
<img :src="require(`${imgPreUrl}img/logo.png`)">
_x000D_
_x000D_
_x000D_

Switching to a TabBar tab view programmatically?

I tried what Disco S2 suggested, it was close but this is what ended up working for me. This was called after completing an action inside another tab.

for (UINavigationController *controller in self.tabBarController.viewControllers)
{
    if ([controller isKindOfClass:[MyViewController class]])
    {
        [self.tabBarController setSelectedViewController:controller];
        break;
    }
}

Show div #id on click with jQuery

The problem you're having is that the event-handlers are being bound before the elements are present in the DOM, if you wrap the jQuery inside of a $(document).ready() then it should work perfectly well:

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").show("slow");
        });

    });

An alternative is to place the <script></script> at the foot of the page, so it's encountered after the DOM has been loaded and ready.

To make the div hide again, once the #music element is clicked, simply use toggle():

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").toggle();
        });
    });

JS Fiddle demo.

And for fading:

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").fadeToggle();
        });
    });

JS Fiddle demo.

convert pfx format to p12

This is more of a continuation of jglouie's response.

If you are using openssl to convert the PKCS#12 certificate to public/private PEM keys, there is no need to rename the file. Assuming the file is called cert.pfx, the following three commands will create a public pem key and an encrypted private pem key:

openssl pkcs12 -in cert.pfx     -out cert.pem     -nodes -nokeys
openssl pkcs12 -in cert.pfx     -out cert_key.pem -nodes -nocerts
openssl rsa    -in cert_key.pem -out cert_key.pem -des3

The first two commands may prompt for an import password. This will be a password that was provided with the PKCS#12 file.

The third command will let you specify the encryption passphrase for the certificate. This is what you will enter when using the certificate.

Awk if else issues

Try the code

awk '{s=($3==0)?"-":$3/$4; print s}'

Get file size before uploading

<script type="text/javascript">
function AlertFilesize(){
    if(window.ActiveXObject){
        var fso = new ActiveXObject("Scripting.FileSystemObject");
        var filepath = document.getElementById('fileInput').value;
        var thefile = fso.getFile(filepath);
        var sizeinbytes = thefile.size;
    }else{
        var sizeinbytes = document.getElementById('fileInput').files[0].size;
    }

    var fSExt = new Array('Bytes', 'KB', 'MB', 'GB');
    fSize = sizeinbytes; i=0;while(fSize>900){fSize/=1024;i++;}

    alert((Math.round(fSize*100)/100)+' '+fSExt[i]);
}
</script>

<input id="fileInput" type="file" onchange="AlertFilesize();" />

Work on IE and FF

How to convert image to byte array

Sample code to change an image into a byte array

public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
   using (var ms = new MemoryStream())
   {
      imageIn.Save(ms,imageIn.RawFormat);
      return  ms.ToArray();
   }
}

C# Image to Byte Array and Byte Array to Image Converter Class

How to check if spark dataframe is empty?

You can do it like:

val df = sqlContext.emptyDataFrame
if( df.eq(sqlContext.emptyDataFrame) )
    println("empty df ")
else 
    println("normal df")

Return a value if no rows are found in Microsoft tSQL

You can do something just like this.

IF EXISTS ( SELECT * FROM TableName WHERE Column=colval)
BEGIN
   select 
select name ,Id from TableName WHERE Column=colval
END
ELSE
  SELECT 'test' as name,0 as Id

rename the columns name after cbind the data

If you offer cbind a set of arguments all of whom are vectors, you will get not a dataframe, but rather a matrix, in this case an all character matrix. They have different features. You can get a dataframe if some of your arguments remain dataframes, Try:

merger <- cbind(Date =as.character(Date),
             weather1[ , c("High", "Low", "Avg..High", "Avg.Low")] , 
             ScnMov =sale$Scanned.Movement[a] )

JOIN two SELECT statement results

you can use the UNION ALL keyword for this.

Here is the MSDN doc to do it in T-SQL http://msdn.microsoft.com/en-us/library/ms180026.aspx

UNION ALL - combines the result set

UNION- Does something like a Set Union and doesnt output duplicate values

For the difference with an example: http://sql-plsql.blogspot.in/2010/05/difference-between-union-union-all.html

How to create new folder?

Have you tried os.mkdir?

You might also try this little code snippet:

mypath = ...
if not os.path.isdir(mypath):
   os.makedirs(mypath)

makedirs creates multiple levels of directories, if needed.

Import JavaScript file and call functions using webpack, ES6, ReactJS

Named exports:

Let's say you create a file called utils.js, with utility functions that you want to make available for other modules (e.g. a React component). Then you would make each function a named export:

export function add(x, y) {
  return x + y
}

export function mutiply(x, y) {
  return x * y
}

Assuming that utils.js is located in the same directory as your React component, you can use its exports like this:

import { add, multiply } from './utils.js';
...
add(2, 3) // Can be called wherever in your component, and would return 5.

Or if you prefer, place the entire module's contents under a common namespace:

import * as utils from './utils.js'; 
...
utils.multiply(2,3)

Default exports:

If you on the other hand have a module that only does one thing (could be a React class, a normal function, a constant, or anything else) and want to make that thing available to others, you can use a default export. Let's say we have a file log.js, with only one function that logs out whatever argument it's called with:

export default function log(message) {
  console.log(message);
}

This can now be used like this:

import log from './log.js';
...
log('test') // Would print 'test' in the console.

You don't have to call it log when you import it, you could actually call it whatever you want:

import logToConsole from './log.js';
...
logToConsole('test') // Would also print 'test' in the console.

Combined:

A module can have both a default export (max 1), and named exports (imported either one by one, or using * with an alias). React actually has this, consider:

import React, { Component, PropTypes } from 'react';

Java method to sum any number of ints

You need:

public int sumAll(int...numbers){

    int result = 0;
    for(int i = 0 ; i < numbers.length; i++) {
        result += numbers[i];
    } 
    return result;
}

Then call the method and give it as many int values as you need:

int result = sumAll(1,4,6,3,5,393,4,5);//.....
System.out.println(result);

What is difference between 'git reset --hard HEAD~1' and 'git reset --soft HEAD~1'?

git reset does know five "modes": soft, mixed, hard, merge and keep. I will start with the first three, since these are the modes you'll usually encounter. After that you'll find a nice little a bonus, so stay tuned.

soft

When using git reset --soft HEAD~1 you will remove the last commit from the current branch, but the file changes will stay in your working tree. Also the changes will stay on your index, so following with a git commit will create a commit with the exact same changes as the commit you "removed" before.

mixed

This is the default mode and quite similar to soft. When "removing" a commit with git reset HEAD~1 you will still keep the changes in your working tree but not on the index; so if you want to "redo" the commit, you will have to add the changes (git add) before commiting.

hard

When using git reset --hard HEAD~1 you will lose all uncommited changes in addition to the changes introduced in the last commit. The changes won't stay in your working tree so doing a git status command will tell you that you don't have any changes in your repository.

Tread carefully with this one. If you accidentally remove uncommited changes which were never tracked by git (speak: committed or at least added to the index), you have no way of getting them back using git.

Bonus

keep

git reset --keep HEAD~1 is an interesting and useful one. It only resets the files which are different between the current HEAD and the given commit. It aborts the reset if one or more of these files has uncommited changes. It basically acts as a safer version of hard.


You can read more about that in the git reset documentation.

Note
When doing git reset to remove a commit the commit isn't really lost, there just is no reference pointing to it or any of it's children. You can still recover a commit which was "deleted" with git reset by finding it's SHA-1 key, for example with a command such as git reflog.

How to embed images in html email

This is the code I'm using to embed images into HTML mail and PDF documents.

<?php
$logo_path = 'http://localhost/img/logo.jpg';
$type = pathinfo($logo_path, PATHINFO_EXTENSION);
$image_contents = file_get_contents($logo_path);
$image64 = 'data:image/' . $type . ';base64,' . base64_encode($image_contents);

echo '<img src="' . $image64 .'" />';
?>

Java: is there a map function?

Since Java 8, there are some standard options to do this in JDK:

Collection<E> in = ...
Object[] mapped = in.stream().map(e -> doMap(e)).toArray();
// or
List<E> mapped = in.stream().map(e -> doMap(e)).collect(Collectors.toList());

See java.util.Collection.stream() and java.util.stream.Collectors.toList().

Python timedelta in years

How exact do you need it to be? td.days / 365.25 will get you pretty close, if you're worried about leap years.

Commit only part of a file in Git

Much like jdsumsion's answer you can also stash your current work but then use a difftool like meld to pull selected changes from the stash. That way you can even edit the hunks manually very easy, which is a bit of a pain when in git add -p:

$ git stash -u
$ git difftool -d -t meld stash
$ git commit -a -m "some message"
$ git stash pop

Using the stash method gives you the opportunity to test, if your code still works, before you commit it.

Mock MVC - Add Request Parameter to test

If anyone came to this question looking for ways to add multiple parameters at the same time (my case), you can use .params with a MultivalueMap instead of adding each .param :

LinkedMultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>()
requestParams.add("id", "1");
requestParams.add("name", "john");
requestParams.add("age", "30");

mockMvc.perform(get("my/endpoint").params(requestParams)).andExpect(status().isOk())

Printing the last column of a line in a file

To print the last column of a line just use $(NF):

awk '{print $(NF)}' 

Cannot push to GitHub - keeps saying need merge

git pull prints Already up-to-date

solution:

you might be created a repository/project in remote(server) and added some file there, Then again created a Folder in your local and initialised git git init - this is the mistake, you should not create git init in local, instead clone the project to your local using git clone

then pull

Bootstrap-select - how to fire event on change

My implementation

import $ from 'jquery';

$(document).ready(() => {
  $('#whatDescribesYouSelectInput').on('change', (e) => {
    if (e.target.value === 'Other') {
      $('#whatDescribesYouOtherInput').attr('type', 'text');
      $('#specifyLabel').show();
    } else {
      $('#whatDescribesYouOtherInput').attr('type', 'hidden');
      $('#specifyLabel').hide();
    }
  });
});

Convert json to a C# array?

Old question but worth adding an answer if using .NET Core 3.0 or later. JSON serialization/deserialization is built into the framework (System.Text.Json), so you don't have to use third party libraries any more. Here's an example based off the top answer given by @Icarus

using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";

            // use the built in Json deserializer to convert the string to a list of Person objects
            var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);

            foreach (var person in people)
            {
                Console.WriteLine(person.Name + " is " + person.Age + " years old.");
            }
        }

        public class Person
        {
            public int Age { get; set; }
            public string Name { get; set; }
        }
    }
}

Revert to a commit by a SHA hash in Git?

Should be as simple as:

git reset --hard 56e05f

That'll get you back to that specific point in time.

calling server side event from html button control

You may use event handler serverclick as below

//cmdAction is the id of HTML button as below

<body>
    <form id="form1" runat="server">
        <button type="submit" id="cmdAction" text="Button1" runat="server">
            Button1
        </button>
    </form>
</body>

//cs code

public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
                cmdAction.ServerClick += new EventHandler(submit_click);  
        }

        protected void submit_click(object sender, EventArgs e)
        {
            Response.Write("HTML Server Button Control");
        }
    }

How to get a product's image in Magento?

I recently needed to do this as well... here's how I got to it:

$_product->getMediaGalleryImages()->getItemByColumnValue('label', 'LABEL_NAME')->getUrl();

Hope that helps you!

VirtualBox error "Failed to open a session for the virtual machine"

For windows users ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯

I had the same issue, and this trick works for me

  1. Goto control panel
  2. Open Uninstall program
  3. Click on turn windows features on or off
  4. Scroll down and find the hyper-V folder.
  5. Uncheck the Hyper-V.
  6. Apply changes and restart your system.
  7. Now here you go... Open your virtual box and start the os you want.

Hope this helps..

Retrofit 2 - URL Query Parameter

 public interface IService { 

  String BASE_URL = "https://api.demo.com/";

  @GET("Login") //i.e https://api.demo.com/Search? 
  Call<Products> getUserDetails(@Query("email") String emailID, @Query("password") String password)

} 

It will be called this way. Considering you did the rest of the code already.

Call<Results> call = service.getUserDetails("[email protected]", "Password@123");

For example when a query is returned, it will look like this.

https://api.demo.com/[email protected]&password=Password@123

VS 2017 Metadata file '.dll could not be found

After facing so many troubles, here is the solution that I found.

  1. open your project folder.
  2. find Your_Project_Name.csproj[Visual C# Project file (.csproj)]
  3. open that file in any text editor and find your missing file ItemGroup.

    <ItemGroup> <None Include="..." /> </ItemGroup>

  4. remove that ItemGroup and open once again your project and build

  5. If that reference is important for you then add once again.

Why does modern Perl avoid UTF-8 by default?

I think you misunderstand Unicode and its relationship to Perl. No matter which way you store data, Unicode, ISO-8859-1, or many other things, your program has to know how to interpret the bytes it gets as input (decoding) and how to represent the information it wants to output (encoding). Get that interpretation wrong and you garble the data. There isn't some magic default setup inside your program that's going to tell the stuff outside your program how to act.

You think it's hard, most likely, because you are used to everything being ASCII. Everything you should have been thinking about was simply ignored by the programming language and all of the things it had to interact with. If everything used nothing but UTF-8 and you had no choice, then UTF-8 would be just as easy. But not everything does use UTF-8. For instance, you don't want your input handle to think that it's getting UTF-8 octets unless it actually is, and you don't want your output handles to be UTF-8 if the thing reading from them can't handle UTF-8. Perl has no way to know those things. That's why you are the programmer.

I don't think Unicode in Perl 5 is too complicated. I think it's scary and people avoid it. There's a difference. To that end, I've put Unicode in Learning Perl, 6th Edition, and there's a lot of Unicode stuff in Effective Perl Programming. You have to spend the time to learn and understand Unicode and how it works. You're not going to be able to use it effectively otherwise.

Is it possible to send a variable number of arguments to a JavaScript function?

This is a sample program for calculating sum of integers for variable arguments and array on integers. Hope this helps.

var CalculateSum = function(){
    calculateSumService.apply( null, arguments );
}

var calculateSumService = function(){
    var sum = 0;

    if( arguments.length === 1){
        var args = arguments[0];

        for(var i = 0;i<args.length; i++){
           sum += args[i]; 
        }
    }else{
        for(var i = 0;i<arguments.length; i++){
           sum += arguments[i]; 
        }        
    }

     alert(sum);

}


//Sample method call

// CalculateSum(10,20,30);         

// CalculateSum([10,20,30,40,50]);

// CalculateSum(10,20);

Why is "using namespace std;" considered bad practice?

It's case by case. We want to minimize the "total cost of ownership" of the software over its lifespan. Stating "using namespace std" has some costs, but not using it also has a cost in legibility.

People correctly point out that when using it, when the standard library introduces new symbols and definitions, your code ceases to compile, and you may be forced to rename variables. And yet this is probably good long-term, since future maintainers will be momentarily confused or distracted if you're using a keyword for some surprising purpose.

You don't want to have a template called vector, say, which isn't the vector known by everyone else. And the number of new definitions thus introduced in the C++ library is small enough it may simply not come up. There is a cost to having to do this kind of change, but the cost is not high and is offset by the clarity gained by not using std symbol names for other purposes.

Given the number of classes, variables, and functions, stating std:: on every one might fluff up your code by 50% and make it harder to get your head around. An algorithm or step in a method that could be taken in on one screenful of code now requires scrolling back and forth to follow. This is a real cost. Arguably it may not be a high cost, but people who deny it even exists are inexperienced, dogmatic, or simply wrong.

I'd offer the following rules:

  1. std is different from all other libraries. It is the one library everyone basically needs to know, and in my view is best thought of as part of the language. Generally speaking there is an excellent case for using namespace std even if there isn't for other libraries.

  2. Never force the decision onto the author of a compilation unit (a .cpp file) by putting this using in a header. Always defer the decision to the compilation unit author. Even in a project that has decided to use using namespace std everywhere may fine a few modules that are best handled as exceptions to that rule.

  3. Even though the namespace feature lets you have many modules with symbols defined the same, it's going to be confusing to do so. Keep the names different to the extent possible. Even if not using the namespace feature, if you have a class named foo and std introduces a class named foo, it's probably better long-run to rename your class anyway.

  4. An alternative to using namespaces is to manually namespace symbols by prefixing them. I have two libraries I've used for decades, both starting as C libraries, actually, where every symbol is prefixed with "AK" or "SCWin". Generally speaking, this is like avoiding the "using" construct, but you don't write the twin colons. AK::foo() is instead AKFoo(). It makes code 5-10% denser and less verbose, and the only downside is that you'll be in big trouble if you have to use two such libraries that have the same prefixing. Note the X Window libraries are excellent in this regard, except they forgot to do so with a few #defines: TRUE and FALSE should have been XTRUE and XFALSE, and this set up a namespace clash with Sybase or Oracle that likewise used TRUE and FALSE with different values! (ASCII 0 and 1 in the case of the database!) One special advantage of this is that it applies seemlessly to preprocessor definitions, whereas the C++ using/namespace system doesn't handle them. A nice benefit of this is that it gives an organic slope from being part of a project to eventually being a library. In a large application of mine, all window classes are prefixed Win, all signal-processing modules Mod, and so on. There's little chance of any of these being reused so there's no practical benefit to making each group into a library, but it makes obvious in a few seconds how the project breaks into sub-projects.

How to set Internet options for Android emulator?

It was setting the DNS that did the trick for me. If you are using the Eclipse or Netbeans plugins, you can set it through Default Emulator options, or Emulator Options respectively. You can also use set it from the command line if you start your emulator from CLI. In all cases, the option is "-dns-server x.x.x.x,x.x.x.x" without the quotes. There is no option in the ADB gui to permanently associate the option with your virtual device.

How much overhead does SSL impose?

Order of magnitude: zero.

In other words, you won't see your throughput cut in half, or anything like it, when you add TLS. Answers to the "duplicate" question focus heavily on application performance, and how that compares to SSL overhead. This question specifically excludes application processing, and seeks to compare non-SSL to SSL only. While it makes sense to take a global view of performance when optimizing, that is not what this question is asking.

The main overhead of SSL is the handshake. That's where the expensive asymmetric cryptography happens. After negotiation, relatively efficient symmetric ciphers are used. That's why it can be very helpful to enable SSL sessions for your HTTPS service, where many connections are made. For a long-lived connection, this "end-effect" isn't as significant, and sessions aren't as useful.


Here's an interesting anecdote. When Google switched Gmail to use HTTPS, no additional resources were required; no network hardware, no new hosts. It only increased CPU load by about 1%.

Can I find events bound on an element with jQuery?

I'm adding this for posterity; There's an easier way that doesn't involve writing more JS. Using the amazing firebug addon for firefox,

  1. Right click on the element and select 'Inspect element with Firebug'
  2. In the sidebar panels (shown in the screenshot), navigate to the events tab using the tiny > arrow
  3. The events tab shows the events and corresponding functions for each event
  4. The text next to it shows the function location

enter image description here

Android WebView not loading an HTTPS URL

override onReceivedSslError and remove

super.onReceivedSslError(view, handler, error)

And to solve Google security:

setDomStorageEnabled(true);

Full code is:

webView.enableJavaScript();
webView.getSettings().setDomStorageEnabled(true); // Add this
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.setWebViewClient(new WebViewClient(){
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            // DO NOT CALL SUPER METHOD
            super.onReceivedSslError(view, handler, error);
        }
    });

Select current element in jQuery

Fortunately, jQuery selectors allow you much more freedom:

$("div a").click( function(event)
{
   var clicked = $(this); // jQuery wrapper for clicked element
   // ... click-specific code goes here ...
});

...will attach the specified callback to each <a> contained in a <div>.

ImportError: No module named six

For Mac OS X:

pip install --ignore-installed six

org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused in android

Two solutions for this error:

1. add this permission in your androidManifest.xml of your Android project

<uses-permission android:name="android.permission.INTERNET"/>

2. Turn on the Internet Connection of your device first.

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

I also got the same error in my SQL Code, This solution works for me,


Check the data in Primary Table May be you are entering a column value which is not present in the primary key column.

Can't compare naive and aware datetime.now() <= challenge.datetime_end

Disable time zone. Use challenge.datetime_start.replace(tzinfo=None);

You can also use replace(tzinfo=None) for other datetime.

if challenge.datetime_start.replace(tzinfo=None) <= datetime.now().replace(tzinfo=None) <= challenge.datetime_end.replace(tzinfo=None):

Mongoimport of json file

A bit late for probable answer, might help new people. In case you have multiple instances of database:

mongoimport --host <host_name>:<host_port> --db <database_name> --collection <collection_name>  --file <path_to_dump_file> -u <my_user> -p <my_pass>

Assuming credentials needed, otherwise remove this option.

Rails migration for change column

To complete answers in case of editing default value :

In your rails console :

rails g migration MigrationName

In the migration :

  def change
    change_column :tables, :field_name, :field_type, default: value
  end

Will look like :

  def change
    change_column :members, :approved, :boolean, default: true
  end

Read file data without saving it in Flask

I was trying to do the exact same thing, open a text file (a CSV for Pandas actually). Don't want to make a copy of it, just want to open it. The form-WTF has a nice file browser, but then it opens the file and makes a temporary file, which it presents as a memory stream. With a little work under the hood,

form = UploadForm() 
 if form.validate_on_submit(): 
      filename = secure_filename(form.fileContents.data.filename)  
      filestream =  form.fileContents.data 
      filestream.seek(0)
      ef = pd.read_csv( filestream  )
      sr = pd.DataFrame(ef)  
      return render_template('dataframe.html',tables=[sr.to_html(justify='center, classes='table table-bordered table-hover')],titles = [filename], form=form) 

SSL Error: CERT_UNTRUSTED while using npm command

I had same problem and finally I understood that my node version is old. For example, you can install the current active LTS node version in Ubuntu by the following steps:

sudo apt-get update
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
sudo apt-get install nodejs -y

Installation instructions for more versions and systems can be found in the following link:

https://github.com/nodesource/distributions/blob/master/README.md

cannot redeclare block scoped variable (typescript)

In my case (using IntelliJ) File - Invalidate Caches / Restart... did the trick.

Comparing Java enum members: == or equals()?

Can == be used on enum?

Yes: enums have tight instance controls that allows you to use == to compare instances. Here's the guarantee provided by the language specification (emphasis by me):

JLS 8.9 Enums

An enum type has no instances other than those defined by its enum constants.

It is a compile-time error to attempt to explicitly instantiate an enum type. The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants.

Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant. (The equals method in Enum is a final method that merely invokes super.equals on its argument and returns the result, thus performing an identity comparison.)

This guarantee is strong enough that Josh Bloch recommends, that if you insist on using the singleton pattern, the best way to implement it is to use a single-element enum (see: Effective Java 2nd Edition, Item 3: Enforce the singleton property with a private constructor or an enum type; also Thread safety in Singleton)


What are the differences between == and equals?

As a reminder, it needs to be said that generally, == is NOT a viable alternative to equals. When it is, however (such as with enum), there are two important differences to consider:

== never throws NullPointerException

enum Color { BLACK, WHITE };

Color nothing = null;
if (nothing == Color.BLACK);      // runs fine
if (nothing.equals(Color.BLACK)); // throws NullPointerException

== is subject to type compatibility check at compile time

enum Color { BLACK, WHITE };
enum Chiral { LEFT, RIGHT };

if (Color.BLACK.equals(Chiral.LEFT)); // compiles fine
if (Color.BLACK == Chiral.LEFT);      // DOESN'T COMPILE!!! Incompatible types!

Should == be used when applicable?

Bloch specifically mentions that immutable classes that have proper control over their instances can guarantee to their clients that == is usable. enum is specifically mentioned to exemplify.

Item 1: Consider static factory methods instead of constructors

[...] it allows an immutable class to make the guarantee that no two equal instances exist: a.equals(b) if and only if a==b. If a class makes this guarantee, then its clients can use the == operator instead of the equals(Object) method, which may result in improved performance. Enum types provide this guarantee.

To summarize, the arguments for using == on enum are:

  • It works.
  • It's faster.
  • It's safer at run-time.
  • It's safer at compile-time.

PHP: Count a stdClass object

The count function is meant to be used on

  1. Arrays
  2. Objects that are derived from classes that implement the countable interface

A stdClass is neither of these. The easier/quickest way to accomplish what you're after is

$count = count(get_object_vars($some_std_class_object));

This uses PHP's get_object_vars function, which will return the properties of an object as an array. You can then use this array with PHP's count function.

How to store Java Date to Mysql datetime with JPA

Are you perhaps using java.sql.Date? While that has millisecond granularity as a Java class (it is a subclass of java.util.Date, bad design decision), it will be interpreted by the JDBC driver as a date without a time component. You have to use java.sql.Timestamp instead.

Row count with PDO

As it often happens, this question is confusing as hell. People are coming here having two different tasks in mind:

  1. They need to know how many rows in the table
  2. They need to know whether a query returned any rows

That's two absolutely different tasks that have nothing in common and cannot be solved by the same function. Ironically, for neither of them the actual PDOStatement::rowCount() function has to be used.

Let's see why

Counting rows in the table

Before using PDO I just simply used mysql_num_rows().

Means you already did it wrong. Using mysql_num_rows() or rowCount() to count the number of rows in the table is a real disaster in terms of consuming the server resources. A database has to read all the rows from the disk, consume the memory on the database server, then send all this heap of data to PHP, consuming PHP process' memory as well, burdening your server with absolute no reason.
Besides, selecting rows only to count them simply makes no sense. A count(*) query has to be run instead. The database will count the records out of the index, without reading the actual rows and then only one row returned.

For this purpose the code suggested in the accepted answer is fair, save for the fact it won't be an "extra" query but the only query to run.

Counting the number rows returned.

The second use case is not as disastrous as rather pointless: in case you need to know whether your query returned any data, you always have the data itself!

Say, if you are selecting only one row. All right, you can use the fetched row as a flag:

$stmt->execute();
$row = $stmt->fetch();
if (!$row) { // here! as simple as that
    echo 'No data found';
}

In case you need to get many rows, then you can use fetchAll().

fetchAll() is something I won't want as I may sometimes be dealing with large datasets

Yes of course, for the first use case it would be twice as bad. But as we learned already, just don't select the rows only to count them, neither with rowCount() nor fetchAll().

But in case you are going to actually use the rows selected, there is nothing wrong in using fetchAll(). Remember that in a web application you should never select a huge amount of rows. Only rows that will be actually used on a web page should be selected, hence you've got to use LIMIT, WHERE or a similar clause in your SQL. And for such a moderate amount of data it's all right to use fetchAll(). And again, just use this function's result in the condition:

$stmt->execute();
$data = $stmt->fetchAll();
if (!$data) { // again, no rowCount() is needed!
    echo 'No data found';
}

And of course it will be absolute madness to run an extra query only to tell whether your other query returned any rows, as it suggested in the two top answers.

Counting the number of rows in a large resultset

In such a rare case when you need to select a real huge amount of rows (in a console application for example), you have to use an unbuffered query, in order to reduce the amount of memory used. But this is the actual case when rowCount() won't be available, thus there is no use for this function as well.

Hence, that's the only use case when you may possibly need to run an extra query, in case you'd need to know a close estimate for the number of rows selected.

How do I include inline JavaScript in Haml?

You can actually do what Chris Chalmers does in his answer, but you must make sure that HAML doesn't parse the JavaScript. This approach is actually useful when you need to use a different type than text/javascript, which is was I needed to do for MathJax.

You can use the plain filter to keep HAML from parsing the script and throwing an illegal nesting error:

%script{type: "text/x-mathjax-config"}
  :plain
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [["$","$"],["\\(","\\)"]]
      }
    });

SQL Server Format Date DD.MM.YYYY HH:MM:SS

CONVERT(VARCHAR,GETDATE(),120)