Programs & Examples On #Heredoc

A Here-document is a special syntax of writing literal strings in sourcecode, used by different programming languages.

Using variables inside a bash heredoc

As a late corolloary to the earlier answers here, you probably end up in situations where you want some but not all variables to be interpolated. You can solve that by using backslashes to escape dollar signs and backticks; or you can put the static text in a variable.

Name='Rich Ba$tard'
dough='$$$dollars$$$'
cat <<____HERE
$Name, you can win a lot of $dough this week!
Notice that \`backticks' need escaping if you want
literal text, not `pwd`, just like in variables like
\$HOME (current value: $HOME)
____HERE

Demo: https://ideone.com/rMF2XA

Note that any of the quoting mechanisms -- \____HERE or "____HERE" or '____HERE' -- will disable all variable interpolation, and turn the here-document into a piece of literal text.

A common task is to combine local variables with script which should be evaluated by a different shell, programming language, or remote host.

local=$(uname)
ssh -t remote <<:
    echo "$local is the value from the host which ran the ssh command"
    # Prevent here doc from expanding locally; remote won't see backslash
    remote=\$(uname)
    # Same here
    echo "\$remote is the value from the host we ssh:ed to"
:

What is the advantage of using heredoc in PHP?

I don't know if I would say heredoc is laziness. One can say that doing anything is laziness, as there are always more cumbersome ways to do anything.

For example, in certain situations you may want to output text, with embedded variables without having to fetch from a file and run a template replace. Heredoc allows you to forgo having to escape quotes, so the text you see is the text you output. Clearly there are some negatives, for example, you can't indent your heredoc, and that can get frustrating in certain situation, especially if your a stickler for unified syntax, which I am.

Creating multiline strings in JavaScript

You can use += to concatenate your string, seems like no one answered that, which will be readable, and also neat... something like this

var hello = 'hello' +
            'world' +
            'blah';

can be also written as

var hello = 'hello';
    hello += ' world';
    hello += ' blah';

console.log(hello);

How can I write a heredoc to a file in Bash script?

For future people who may have this issue the following format worked:

(cat <<- _EOF_
        LogFile /var/log/clamd.log
        LogTime yes
        DatabaseDirectory /var/lib/clamav
        LocalSocket /tmp/clamd.socket
        TCPAddr 127.0.0.1
        SelfCheck 1020
        ScanPDF yes
        _EOF_
) > /etc/clamd.conf

here-document gives 'unexpected end of file' error

The EOF token must be at the beginning of the line, you can't indent it along with the block of code it goes with.

If you write <<-EOF you may indent it, but it must be indented with Tab characters, not spaces. So it still might not end up even with the block of code.

Also make sure you have no whitespace after the EOF token on the line.

Executing multi-line statements in the one-line command-line?

this style can be used in makefiles too (and in fact it is used quite often).

python - <<EOF
import sys
for r in range(3): print 'rob'
EOF

or

python - <<-EOF
    import sys
    for r in range(3): print 'rob'
EOF

in latter case leading tab characters are removed too (and some structured outlook can be achieved)

instead of EOF can stand any marker word not appearing in the here document at a beginning of a line (see also here documents in the bash manpage or here).

How to cat <<EOF >> a file containing code?

This should work, I just tested it out and it worked as expected: no expansion, substitution, or what-have-you took place.

cat <<< '
#!/bin/bash
curr=`cat /sys/class/backlight/intel_backlight/actual_brightness`
if [ $curr -lt 4477 ]; then
  curr=$((curr+406));
  echo $curr  > /sys/class/backlight/intel_backlight/brightness;
fi' > file # use overwrite mode so that you don't keep on appending the same script to that file over and over again, unless that's what you want. 

Using the following also works.

cat <<< ' > file
 ... code ...'

Also, it's worth noting that when using heredocs, such as << EOF, substitution and variable expansion and the like takes place. So doing something like this:

cat << EOF > file
cd "$HOME"
echo "$PWD" # echo the current path
EOF

will always result in the expansion of the variables $HOME and $PWD. So if your home directory is /home/foobar and the current path is /home/foobar/bin, file will look like this:

cd "/home/foobar"
echo "/home/foobar/bin"

instead of the expected:

cd "$HOME"
echo "$PWD"

How does "cat << EOF" work in bash?

This is called heredoc format to provide a string into stdin. See https://en.wikipedia.org/wiki/Here_document#Unix_shells for more details.


From man bash:

Here Documents

This type of redirection instructs the shell to read input from the current source until a line containing only word (with no trailing blanks) is seen.

All of the lines read up to that point are then used as the standard input for a command.

The format of here-documents is:

          <<[-]word
                  here-document
          delimiter

No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. In the latter case, the character sequence \<newline> is ignored, and \ must be used to quote the characters \, $, and `.

If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line containing delimiter. This allows here-documents within shell scripts to be indented in a natural fashion.

How to assign a heredoc value to a variable in Bash?

Thanks to dimo414's answer, this shows how his great solution works, and shows that you can have quotes and variables in the text easily as well:

example output

$ ./test.sh

The text from the example function is:
  Welcome dev: Would you "like" to know how many 'files' there are in /tmp?

  There are "      38" files in /tmp, according to the "wc" command

test.sh

#!/bin/bash

function text1()
{
  COUNT=$(\ls /tmp | wc -l)
cat <<EOF

  $1 Would you "like" to know how many 'files' there are in /tmp?

  There are "$COUNT" files in /tmp, according to the "wc" command

EOF
}

function main()
{
  OUT=$(text1 "Welcome dev:")
  echo "The text from the example function is: $OUT"
}

main

Global javascript variable inside document.ready

like this: put intro outside your document ready, Good discussion here: http://forum.jquery.com/topic/how-do-i-declare-a-global-variable-in-jquery @thecodeparadox is awesomely fast :P anyways!

 var intro;

$(document).ready(function() {



    if ($('.intro_check').is(':checked')) {
        intro = true;
        $('.intro').wrap('<div class="disabled"></div>');
    };

    $('.intro_check').change(function(){
        if(this.checked) {
            intro = false;
            $('.enabled').removeClass('enabled').addClass('disabled');
        } else {
            intro = true;
            if($('.intro').exists()) {
                $('.disabled').removeClass('disabled').addClass('enabled'); 
            } else {
                $('.intro').wrap('<div class="disabled"></div>');
            }
        }
    });
});

Center content in responsive bootstrap navbar

from the bootstrap official site (and, almost, like Eric S. Bullington said.

https://getbootstrap.com/components/#navbar-default

the example navbar looks like:

<nav class="navbar navbar-default">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
        ...etc

to center the nav, that what i've done:

<div class="container-fluid" id="nav_center">

css:

@media (min-width:768px) { /* don't break navbar on small screen */
    #nav_center {
        width: 700px /* need to found your width according to your entry*/
    }
}

work with class="container" and navbar-right or left, and of course you can replace id by class. :D

Setting the default ssh key location

man ssh gives me this options would could be useful.

-i identity_file Selects a file from which the identity (private key) for RSA or DSA authentication is read. The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_rsa and ~/.ssh/id_dsa for pro- tocol version 2. Identity files may also be specified on a per- host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in config- uration files).

So you could create an alias in your bash config with something like

alias ssh="ssh -i /path/to/private_key"

I haven't looked into a ssh configuration file, but like the -i option this too could be aliased

-F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config.

Ruby objects and JSON serialization (without Rails)

require 'json'
{"foo" => "bar"}.to_json
# => "{\"foo\":\"bar\"}"

How to enable cURL in PHP / XAMPP

On Debian with Apache 2:

apt-get install php5-curl
/etc/init.d/apache2 restart

(php4-curl if it's php4)

How to reload a page using JavaScript

Automatic reload page after 20 seconds.

<script>
    window.onload = function() {
        setTimeout(function () {
            location.reload()
        }, 20000);
     };
</script>

How do you import classes in JSP?

FYI - if you are importing a List into a JSP, chances are pretty good that you are violating MVC principles. Take a few hours now to read up on the MVC approach to web app development (including use of taglibs) - do some more googling on the subject, it's fascinating and will definitely help you write better apps.

If you are doing anything more complicated than a single JSP displaying some database results, please consider using a framework like Spring, Grails, etc... It will absolutely take you a bit more effort to get going, but it will save you so much time and effort down the road that I really recommend it. Besides, it's cool stuff :-)

How to verify Facebook access token?

Exchange Access Token for Mobile Number and Country Code (Server Side OR Client Side)

You can get the mobile number with your access_token with this API https://graph.accountkit.com/v1.1/me/?access_token=xxxxxxxxxxxx. Maybe, once you have the mobile number and the id, you can work with it to verify the user with your server & database.

xxxxxxxxxx above is the Access Token

Example Response :

{
   "id": "61940819992708",
   "phone": {
      "number": "+91XX82923912",
      "country_prefix": "91",
      "national_number": "XX82923912"
   }
}


Exchange Auth Code for Access Token (Server Side)

If you have an Auth Code instead, you can first get the Access Token with this API - https://graph.accountkit.com/v1.1/access_token?grant_type=authorization_code&code=xxxxxxxxxx&access_token=AA|yyyyyyyyyy|zzzzzzzzzz

xxxxxxxxxx, yyyyyyyyyy and zzzzzzzzzz above are the Auth Code, App ID and App Secret respectively.

Example Response

{
   "id": "619XX819992708",
   "access_token": "EMAWdcsi711meGS2qQpNk4XBTwUBIDtqYAKoZBbBZAEZCZAXyWVbqvKUyKgDZBniZBFwKVyoVGHXnquCcikBqc9ROF2qAxLRrqBYAvXknwND3dhHU0iLZCRwBNHNlyQZD",
   "token_refresh_interval_sec": XX92000
}

Note - This is preferred on the server-side since the API requires the APP Secret which is not meant to be shared for security reasons.

Good Luck.

Disable pasting text into HTML form

Just got this, we can achieve it using onpaste:"return false", thanks to: http://sumtips.com/2011/11/prevent-copy-cut-paste-text-field.html

We have various other options available as listed below.

<input type="text" onselectstart="return false" onpaste="return false;" onCopy="return false" onCut="return false" onDrag="return false" onDrop="return false" autocomplete=off/><br>

Comparison of DES, Triple DES, AES, blowfish encryption for data

The encryption methods described are symmetric key block ciphers.

Data Encryption Standard (DES) is the predecessor, encrypting data in 64-bit blocks using a 56 bit key. Each block is encrypted in isolation, which is a security vulnerability.

Triple DES extends the key length of DES by applying three DES operations on each block: an encryption with key 0, a decryption with key 1 and an encryption with key 2. These keys may be related.

DES and 3DES are usually encountered when interfacing with legacy commercial products and services.

AES is considered the successor and modern standard. http://en.wikipedia.org/wiki/Advanced_Encryption_Standard

I believe the use of Blowfish is discouraged.

It is highly recommended that you do not attempt to implement your own cryptography and instead use a high-level implementation such as GPG for data at rest or SSL/TLS for data in transit. Here is an excellent and sobering video on encryption vulnerabilities http://rdist.root.org/2009/08/06/google-tech-talk-on-common-crypto-flaws/

How to get all Errors from ASP.Net MVC modelState?

As I discovered having followed the advice in the answers given so far, you can get exceptions occuring without error messages being set, so to catch all problems you really need to get both the ErrorMessage and the Exception.

String messages = String.Join(Environment.NewLine, ModelState.Values.SelectMany(v => v.Errors)
                                                           .Select( v => v.ErrorMessage + " " + v.Exception));

or as an extension method

public static IEnumerable<String> GetErrors(this ModelStateDictionary modelState)
{
      return modelState.Values.SelectMany(v => v.Errors)
                              .Select( v => v.ErrorMessage + " " + v.Exception).ToList();

}

How do I pass a string into subprocess.Popen (using the stdin argument)?

Beware that Popen.communicate(input=s)may give you trouble ifsis too big, because apparently the parent process will buffer it before forking the child subprocess, meaning it needs "twice as much" used memory at that point (at least according to the "under the hood" explanation and linked documentation found here). In my particular case,swas a generator that was first fully expanded and only then written tostdin so the parent process was huge right before the child was spawned, and no memory was left to fork it:

File "/opt/local/stow/python-2.7.2/lib/python2.7/subprocess.py", line 1130, in _execute_child self.pid = os.fork() OSError: [Errno 12] Cannot allocate memory

Returning the product of a list

One option is to use numba and the @jit or @njit decorator. I also made one or two little tweaks to your code (at least in Python 3, "list" is a keyword that shouldn't be used for a variable name):

@njit
def njit_product(lst):
    p = lst[0]  # first element
    for i in lst[1:]:  # loop over remaining elements
        p *= i
    return p

For timing purposes, you need to run once to compile the function first using numba. In general, the function will be compiled the first time it is called, and then called from memory after that (faster).

njit_product([1, 2])  # execute once to compile

Now when you execute your code, it will run with the compiled version of the function. I timed them using a Jupyter notebook and the %timeit magic function:

product(b)  # yours
# 32.7 µs ± 510 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

njit_product(b)
# 92.9 µs ± 392 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Note that on my machine, running Python 3.5, the native Python for loop was actually the fastest. There may be a trick here when it comes to measuring numba-decorated performance with Jupyter notebooks and the %timeit magic function. I am not sure that the timings above are correct, so I recommend trying it out on your system and seeing if numba gives you a performance boost.

Get div height with plain JavaScript

var clientHeight = document.getElementById('myDiv').clientHeight;

or

var offsetHeight = document.getElementById('myDiv').offsetHeight;

clientHeight includes padding.

offsetHeight includes padding, scrollBar and borders.

How to create a scrollable Div Tag Vertically?

Well, your code worked for me (running Chrome 5.0.307.9 and Firefox 3.5.8 on Ubuntu 9.10), though I switched

overflow-y: scroll;

to

overflow-y: auto;

Demo page over at: http://davidrhysthomas.co.uk/so/tableDiv.html.

xhtml below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
    <META http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <title>Div in table</title>
    <link rel="stylesheet" type="text/css" href="css/stylesheet.css" />

        <style type="text/css" media="all">

        th      {border-bottom: 2px solid #ccc; }

        th,td       {padding: 0.5em 1em; 
                margin: 0;
                border-collapse: collapse;
                }

        tr td:first-child
                {border-right: 2px solid #ccc; } 

        td > div    {width: 249px;
                height: 299px;
                background-color:Gray;
                overflow-y: auto;
                max-width:230px;
                max-height:100px;
                }
        </style>

    <script type="text/javascript" src="js/jquery.js"></script>

    <script type="text/javascript">

    </script>

</head>

<body>

<div>

    <table>

        <thead>
            <tr><th>This is column one</th><th>This is column two</th><th>This is column three</th>
        </thead>



        <tbody>
            <tr><td>This is row one</td><td>data point 2.1</td><td>data point 3.1</td>
            <tr><td>This is row two</td><td>data point 2.2</td><td>data point 3.2</td>
            <tr><td>This is row three</td><td>data point 2.3</td><td>data point 3.3</td>
            <tr><td>This is row four</td><td><div><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ultricies mattis dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum a accumsan purus. Vivamus semper tempus nisi et convallis. Aliquam pretium rutrum lacus sed auctor. Phasellus viverra elit vel neque lacinia ut dictum mauris aliquet. Etiam elementum iaculis lectus, laoreet tempor ligula aliquet non. Mauris ornare adipiscing feugiat. Vivamus condimentum luctus tortor venenatis fermentum. Maecenas eu risus nec leo vehicula mattis. In nisi nibh, fermentum vitae tincidunt non, mattis eu metus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nunc vel est purus. Ut accumsan, elit non lacinia porta, nibh magna pretium ligula, sed iaculis metus tortor aliquam urna. Duis commodo tincidunt aliquam. Maecenas in augue ut ligula sodales elementum quis vitae risus. Vivamus mollis blandit magna, eu fringilla velit auctor sed.</p></div></td><td>data point 3.4</td>
            <tr><td>This is row five</td><td>data point 2.5</td><td>data point 3.5</td>
            <tr><td>This is row six</td><td>data point 2.6</td><td>data point 3.6</td>
            <tr><td>This is row seven</td><td>data point 2.7</td><td>data point 3.7</td>
        </body>



    </table>

</div>

</body>

</html>

What is the most efficient/quickest way to loop through rows in VBA (excel)?

If you are just looping through 10k rows in column A, then dump the row into a variant array and then loop through that.

You can then either add the elements to a new array (while adding rows when needed) and using Transpose() to put the array onto your range in one move, or you can use your iterator variable to track which row you are on and add rows that way.

Dim i As Long
Dim varray As Variant

varray = Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row).Value

For i = 1 To UBound(varray, 1)
    ' do stuff to varray(i, 1)
Next

Here is an example of how you could add rows after evaluating each cell. This example just inserts a row after every row that has the word "foo" in column A. Not that the "+2" is added to the variable i during the insert since we are starting on A2. It would be +1 if we were starting our array with A1.

Sub test()

Dim varray As Variant
Dim i As Long

varray = Range("A2:A10").Value

'must step back or it'll be infinite loop
For i = UBound(varray, 1) To LBound(varray, 1) Step -1
    'do your logic and evaluation here
    If varray(i, 1) = "foo" Then
       'not how to offset the i variable 
       Range("A" & i + 2).EntireRow.Insert
    End If
Next

End Sub

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

Send password when using scp to copy files from one server to another

Here is how I resolved it.

It is not the most secure way however it solved my problem as security was not an issue on internal servers.

Create a new file say password.txt and store the password for the server where the file will be pasted. Save this to a location on the host server.

scp -W location/password.txt copy_file_location paste_file_location

Cheers!

WooCommerce - get category for product page

Thanks Box. I'm using MyStile Theme and I needed to display the product category name in my search result page. I added this function to my child theme functions.php

Hope it helps others.

/* Post Meta */


if (!function_exists( 'woo_post_meta')) {
    function woo_post_meta( ) {
        global $woo_options;
        global $post;

        $terms = get_the_terms( $post->ID, 'product_cat' );
        foreach ($terms as $term) {
            $product_cat = $term->name;
            break;
        }

?>
<aside class="post-meta">
    <ul>
        <li class="post-category">
            <?php the_category( ', ', $post->ID) ?>
                        <?php echo $product_cat; ?>

        </li>
        <?php the_tags( '<li class="tags">', ', ', '</li>' ); ?>
        <?php if ( isset( $woo_options['woo_post_content'] ) && $woo_options['woo_post_content'] == 'excerpt' ) { ?>
            <li class="comments"><?php comments_popup_link( __( 'Leave a comment', 'woothemes' ), __( '1 Comment', 'woothemes' ), __( '% Comments', 'woothemes' ) ); ?></li>
        <?php } ?>
        <?php edit_post_link( __( 'Edit', 'woothemes' ), '<li class="edit">', '</li>' ); ?>
    </ul>
</aside>
<?php
    }
}


?>

When is a language considered a scripting language?

Scripting languages are programming languages where the programs are typically delivered to end users in a readable textual form and where there is a program that can apparently execute that program directly. (The program may well compile the script internally; that's not relevant here because it is not visible to the user.)

It's relatively common for scripting languages to be able to support an interactive session where users can just type in their program and have it execute immediately. This is because this is a trivial extension of the essential requirement from the first paragraph; the main extra requirement is the addition of a mechanism to figure out when a typed-in statement is complete so that it can be sent to the execution engine.

Simple PHP Pagination script

Some of the tutorials I found that are easy to understand are:

It makes way more sense to break up your list into page-sized chunks, and only query your database one chunk at a time. This drastically reduces server processing time and page load time, as well as gives your user smaller pieces of info to digest, so he doesn't choke on whatever crap you're trying to feed him. The act of doing this is called pagination.

A basic pagination routine seems long and scary at first, but once you close your eyes, take a deep breath, and look at each piece of the script individually, you will find it's actually pretty easy stuff

The script:

// find out how many rows are in the table 
$sql = "SELECT COUNT(*) FROM numbers";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];

// number of rows to show per page
$rowsperpage = 10;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);

// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
   // cast var as int
   $currentpage = (int) $_GET['currentpage'];
} else {
   // default page num
   $currentpage = 1;
} // end if

// if current page is greater than total pages...
if ($currentpage > $totalpages) {
   // set current page to last page
   $currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
   // set current page to first page
   $currentpage = 1;
} // end if

// the offset of the list, based on current page 
$offset = ($currentpage - 1) * $rowsperpage;

// get the info from the db 
$sql = "SELECT id, number FROM numbers LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);

// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
   // echo data
   echo $list['id'] . " : " . $list['number'] . "<br />";
} // end while

/******  build the pagination links ******/
// range of num links to show
$range = 3;

// if not on page 1, don't show back links
if ($currentpage > 1) {
   // show << link to go back to page 1
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
   // get previous page num
   $prevpage = $currentpage - 1;
   // show < link to go back to 1 page
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if 

// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
   // if it's a valid page number...
   if (($x > 0) && ($x <= $totalpages)) {
      // if we're on current page...
      if ($x == $currentpage) {
         // 'highlight' it but don't make a link
         echo " [<b>$x</b>] ";
      // if not current page...
      } else {
         // make it a link
         echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
      } // end else
   } // end if 
} // end for

// if not on last page, show forward and last page links        
if ($currentpage != $totalpages) {
   // get next page
   $nextpage = $currentpage + 1;
    // echo forward link for next page 
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
   // echo forward link for lastpage
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
?>

This tutorial is intended for developers who wish to give their users the ability to step through a large number of database rows in manageable chunks instead of the whole lot in one go.

Delete files older than 3 months old in a directory using .NET

For example: To go My folder project on source, i need to up two folder. I make this algorim to 2 days week and into four hour

public static void LimpiarArchivosViejos()
    {
        DayOfWeek today = DateTime.Today.DayOfWeek;
        int hora = DateTime.Now.Hour;
        if(today == DayOfWeek.Monday || today == DayOfWeek.Tuesday && hora < 12 && hora > 8)
        {
            CleanPdfOlds();
            CleanExcelsOlds();
        }

    }
    private static void CleanPdfOlds(){
        string[] files = Directory.GetFiles("../../Users/Maxi/Source/Repos/13-12-2017_config_pdfListados/ApplicaAccWeb/Uploads/Reports");
        foreach (string file in files)
        {
            FileInfo fi = new FileInfo(file);
            if (fi.CreationTime < DateTime.Now.AddDays(-7))
                fi.Delete();
        }
    }
    private static void CleanExcelsOlds()
    {
        string[] files2 = Directory.GetFiles("../../Users/Maxi/Source/Repos/13-12-2017_config_pdfListados/ApplicaAccWeb/Uploads/Excels");
        foreach (string file in files2)
        {
            FileInfo fi = new FileInfo(file);
            if (fi.CreationTime < DateTime.Now.AddDays(-7))
                fi.Delete();
        }
    }

Android widget: How to change the text of a button

I was able to change the button's text like this:

import android.widget.RemoteViews;

//grab the layout, then set the text of the Button called R.id.Counter:
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.my_layout);
remoteViews.setTextViewText(R.id.Counter, "Set button text here");

How to change the status bar color in Android?

this is very easy way to do this without any Library: if the OS version is not supported - under kitkat - so nothing happend. i do this steps:

  1. in my xml i added to the top this View:
<View
        android:id="@+id/statusBarBackground"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

then i made this method:

 public void setStatusBarColor(View statusBar,int color){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
           Window w = getWindow();
           w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
           //status bar height
           int actionBarHeight = getActionBarHeight();
           int statusBarHeight = getStatusBarHeight();
           //action bar height
           statusBar.getLayoutParams().height = actionBarHeight + statusBarHeight;
           statusBar.setBackgroundColor(color);
     }
}

also you need those both methods to get action Bar & status bar height:

public int getActionBarHeight() {
    int actionBarHeight = 0;
    TypedValue tv = new TypedValue();
    if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
    {
       actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
    }
    return actionBarHeight;
}

public int getStatusBarHeight() {
    int result = 0;
    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        result = getResources().getDimensionPixelSize(resourceId);
    }
    return result;
}

then the only thing you need is this line to set status bar color:

setStatusBarColor(findViewById(R.id.statusBarBackground),getResources().getColor(android.R.color.white));

What's the most elegant way to cap a number to a segment?

The way you do it is pretty standard. You can define a utility clamp function:

/**
 * Returns a number whose value is limited to the given range.
 *
 * Example: limit the output of this computation to between 0 and 255
 * (x * 255).clamp(0, 255)
 *
 * @param {Number} min The lower boundary of the output range
 * @param {Number} max The upper boundary of the output range
 * @returns A number in the range [min, max]
 * @type Number
 */
Number.prototype.clamp = function(min, max) {
  return Math.min(Math.max(this, min), max);
};

(Although extending language built-ins is generally frowned upon)

Windows shell command to get the full path to the current directory?

For Windows we can use

cd

and for Linux

pwd

command is there.

how to send a post request with a web browser

with a form, just set method to "post"

<form action="blah.php" method="post">
  <input type="text" name="data" value="mydata" />
  <input type="submit" />
</form>

Quick way to retrieve user information Active Directory

You can simplify this code to:

        DirectorySearcher searcher = new DirectorySearcher();
        searcher.Filter = "(&(objectCategory=user)(cn=steve.evans))";

        SearchResultCollection results = searcher.FindAll();

        if (results.Count == 1)
        {
            //do what you want to do
        }
        else if (results.Count == 0)
        {
            //user does not exist
        }
        else
        {
            //found more than one user
            //something is wrong
        }

If you can narrow down where the user is you can set searcher.SearchRoot to a specific OU that you know the user is under.

You should also use objectCategory instead of objectClass since objectCategory is indexed by default.

You should also consider searching on an attribute other than CN. For example it might make more sense to search on the username (sAMAccountName) since it's guaranteed to be unique.

CSS3 transition doesn't work with display property

I faced the problem with display:none

I have several horizontal bars with transition effects but I wanted to show only part of that container and fold the rest while maintaining the effects. I reproduced a small demo here

The obvious was to wrap those hidden animated bars in a div then toggle that element's height and opacity

.hide{
  opacity: 0;
  height: 0;
}
.bars-wrapper.expanded > .hide{
 opacity: 1;
 height: auto;
}

The animation works well but the issue was that these hidden bars were still consuming space on my page and overlapping other elements

enter image description here

so adding display:none to the hidden wrapper .hide solves the margin issue but not the transition, neither applying display:none or height:0;opacity:0 works on the children elements.

So my final workaround was to give those hidden bars a negative and absolute position and it worked well with CSS transitions.

Jsfiddle

How can I make all images of different height and width the same via CSS?

Simplest way - This will keep the image size as it is and fill the other area with space, this way all the images will take same specified space regardless of the image size without stretching

.img{
   width:100px;
   height:100px;

/*Scale down will take the necessary specified space that is 100px x 100px without stretching the image*/
    object-fit:scale-down;

}

How to handle checkboxes in ASP.NET MVC forms?

Using @mmacaulay , I came up with this for bool:

// MVC Work around for checkboxes.
bool active = (Request.Form["active"] == "on");

If checked active = true

If unchecked active = false

Are PDO prepared statements sufficient to prevent SQL injection?

Prepared statements / parameterized queries are generally sufficient to prevent 1st order injection on that statement*. If you use un-checked dynamic sql anywhere else in your application you are still vulnerable to 2nd order injection.

2nd order injection means data has been cycled through the database once before being included in a query, and is much harder to pull off. AFAIK, you almost never see real engineered 2nd order attacks, as it is usually easier for attackers to social-engineer their way in, but you sometimes have 2nd order bugs crop up because of extra benign ' characters or similar.

You can accomplish a 2nd order injection attack when you can cause a value to be stored in a database that is later used as a literal in a query. As an example, let's say you enter the following information as your new username when creating an account on a web site (assuming MySQL DB for this question):

' + (SELECT UserName + '_' + Password FROM Users LIMIT 1) + '

If there are no other restrictions on the username, a prepared statement would still make sure that the above embedded query doesn't execute at the time of insert, and store the value correctly in the database. However, imagine that later the application retrieves your username from the database, and uses string concatenation to include that value a new query. You might get to see someone else's password. Since the first few names in users table tend to be admins, you may have also just given away the farm. (Also note: this is one more reason not to store passwords in plain text!)

We see, then, that prepared statements are enough for a single query, but by themselves they are not sufficient to protect against sql injection attacks throughout an entire application, because they lack a mechanism to enforce all access to a database within an application uses safe code. However, used as part of good application design — which may include practices such as code review or static analysis, or use of an ORM, data layer, or service layer that limits dynamic sql — prepared statements are the primary tool for solving the Sql Injection problem. If you follow good application design principles, such that your data access is separated from the rest of your program, it becomes easy to enforce or audit that every query correctly uses parameterization. In this case, sql injection (both first and second order) is completely prevented.


*It turns out that MySql/PHP are (okay, were) just dumb about handling parameters when wide characters are involved, and there is still a rare case outlined in the other highly-voted answer here that can allow injection to slip through a parameterized query.

How to remove all CSS classes using jQuery/JavaScript?

Just set the className attribute of the real DOM element to '' (nothing).

$('#item')[0].className = ''; // the real DOM element is at [0]

Edit: Other people have said that just calling removeClass works - I tested this with the Google JQuery Playground: http://savedbythegoog.appspot.com/?id=ag5zYXZlZGJ5dGhlZ29vZ3ISCxIJU2F2ZWRDb2RlGIS61gEM ... and it works. So you can also do it this way:

$("#item").removeClass();

ListView with OnItemClickListener

1) Check if you are using OnItemClickListener or OnClickListener (which is not supported for ListView)
Documentation Android Developers ListView

2) Check if you added Listener to your ListView properly. It's hooked on ListView not on ListAdapter!

ListView.setOnItemClickListener(listener);

3) If you need to use OnClickListener, check if you do use DialogInterface.OnClickListener or View.OnClickListener (they can be easily exchanged if not validated or if using both of them)

how to remove css property using javascript?

div.style.removeProperty('zoom');

string.Replace in AngularJs

var oldString = "stackoverflow";
var str=oldString.replace(/stackover/g,"NO");
$scope.newString= str;

It works for me. Use an intermediate variable.

What do the icons in Eclipse mean?

In eclipse help documentation, we can all icons information as follows. Common path for all eclipse versions except eclipse version:

enter image description here

https://help.eclipse.org/2019-09/index.jsp?nav=%2F1

How to make Toolbar transparent?

Add below code to styles.xml file

<style name="LayoutPageTheme" parent="@style/Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowActionBarOverlay">true</item>
    <!-- Support library compatibility -->
    <item name="windowActionBarOverlay">true</item>
    <item name="android:actionBarStyle">@style/TransparentActionBar</item>
</style>
<!-- ActionBar styles -->
<style name="TransparentActionBar"
    parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:background">@android:color/transparent</item>
</style>

          <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
           android:background="@android:color/transparent"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

Don't forget to write: android:background="@android:color/transparent"

Track a new remote branch created on GitHub

First of all you have to fetch the remote repository:

git fetch remoteName

Than you can create the new branch and set it up to track the remote branch you want:

git checkout -b newLocalBranch remoteName/remoteBranch

You can also use "git branch --track" instead of "git checkout -b" as max specified.

git branch --track newLocalBranch remoteName/remoteBranch

percentage of two int?

Well to make the decimal into a percent you can do this,

float percentage = (correct * 100.0f) / questionNum;

How to set the custom border color of UIView programmatically?

If you Use Swift 2.0+

self.yourView.layer.borderWidth = 1
self.yourView.layer.borderColor = UIColor(red:222/255, green:225/255, blue:227/255, alpha: 1).cgColor

How to do error logging in CodeIgniter (PHP)

More oin regards to question part 4 How do you e-mail that error to an email address? The error_log function has email destination too. http://php.net/manual/en/function.error-log.php

Agha, here I found an example that shows a usage. Send errors message via email using error_log()

error_log($this->_errorMsg, 1, ADMIN_MAIL, "Content-Type: text/html; charset=utf8\r\nFrom: ".MAIL_ERR_FROM."\r\nTo: ".ADMIN_MAIL);

Find p-value (significance) in scikit-learn LinearRegression

There could be a mistake in @JARH's answer in the case of a multivariable regression. (I do not have enough reputation to comment.)

In the following line:

p_values =[2*(1-stats.t.cdf(np.abs(i),(len(newX)-1))) for i in ts_b],

the t-values follows a chi-squared distribution of degree len(newX)-1 instead of following a chi-squared distribution of degree len(newX)-len(newX.columns)-1.

So this should be:

p_values =[2*(1-stats.t.cdf(np.abs(i),(len(newX)-len(newX.columns)-1))) for i in ts_b]

(See t-values for OLS regression for more details)

Foreach Control in form, how can I do something to all the TextBoxes in my Form?

The trick here is that Controls is not a List<> or IEnumerable but a ControlCollection.

I recommend using an extension of Control that will return something more..queriyable ;)

public static IEnumerable<Control> All(this ControlCollection controls)
    {
        foreach (Control control in controls)
        {
            foreach (Control grandChild in control.Controls.All())
                yield return grandChild;

            yield return control;
        }
    }

Then you can do :

foreach(var textbox in this.Controls.All().OfType<TextBox>)
{
    // Apply logic to the textbox here
}

System.Net.WebException: The remote name could not be resolved:

Open the hosts file located at : **C:\windows\system32\drivers\etc**.

Hosts file is for what?

Add the following at end of this file :

YourServerIP YourDNS

Example:

198.168.1.1 maps.google.com

External VS2013 build error "error MSB4019: The imported project <path> was not found"

I had the same issue and find an easier solution

It is due to Vs2012 adding the following to the csproj file:

<PropertyGroup>
  <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
  <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>

You can safely remove that part and your solution will build.

As Sielu pointed out you have to ensure that the .proj file begin with <Project ToolsVersion="12" otherwise the next time you open the project with visual studio 2010, it will add the removed node again.

Otherwise, if you need to use webdeploy or you use a build server, the above solution will not work but you can specify the VisualStudioVersion property in your build script:

msbuild myproject.csproj /p:VisualStudioVersion=12.0

or edit your build definition:

edit build definition to specify the <code>VisualStudioVersion</code> property

how to delete all commit history in github?

Deleting the .git folder may cause problems in your git repository. If you want to delete all your commit history but keep the code in its current state, it is very safe to do it as in the following:

  1. Checkout

    git checkout --orphan latest_branch

  2. Add all the files

    git add -A

  3. Commit the changes

    git commit -am "commit message"

  4. Delete the branch

    git branch -D main

  5. Rename the current branch to main

    git branch -m main

  6. Finally, force update your repository

    git push -f origin main

PS: this will not keep your old commit history around

Confirm postback OnClientClick button ASP.NET

You can put the above answers into one line like this. And you don't need to write the function.

    <asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton"
         OnClick="BtnUserDelete_Click" meta:resourcekey="BtnUserDeleteResource1"
OnClientClick="if ( !confirm('Are you sure you want to delete this user?')) return false;"  />

Selecting between two dates within a DateTime field - SQL Server

SELECT * 
FROM tbl 
WHERE myDate BETWEEN #date one# AND #date two#;

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

You are using multiple versions of the Android Support Libraries:

compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
compile 'com.android.support:cardview-v7:26.0.0-alpha1'
compile 'com.android.support:design:25+'

Two are 26.0.0-alpha1, and one is using 25+.

Pick one concrete version and use it for all three of these. Since your compileSdkVersion is not O, use 25.3.1 for all three of these libraries, resulting in:

compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.android.support:design:25.3.1'

How to set aliases in the Git Bash for Windows?

To Add a Temporary Alias:

  1. Goto Terminal (I'm using git bash for windows).
  2. Type $ alias gpuom='git push origin master'
  3. To See a List of All the aliases type $ alias hit Enter.

To Add a Permanent Alias:

  1. Goto Terminal (I'm using git bash for windows).
  2. Type $ vim ~/.bashrc and hit Enter (I'm guessing you are familiar with vim).
  3. Add your new aliases (For reference look at the snippet below).
    #My custom aliases  
    alias gpuom='git push origin master' 
    alias gplom='git pull origin master'
    
  4. Save and Exit (Press Esc then type :wq).
  5. To See a List of All the aliases type $ alias hit Enter.

Hour from DateTime? in 24 hours format

Using ToString("HH:mm") certainly gives you what you want as a string.

If you want the current hour/minute as numbers, string manipulation isn't necessary; you can use the TimeOfDay property:

TimeSpan timeOfDay = fechaHora.TimeOfDay;
int hour = timeOfDay.Hours;
int minute = timeOfDay.Minutes;

Grunt watch error - Waiting...Fatal error: watch ENOSPC

I ran into this error after my client PC crashed, the jest --watch command I was running on the server persisted, and I tried to run jest --watch again.

The addition to /etc/sysctl.conf described in the answers above worked around this issue, but it was also important to find my old process via ps aux | grep node and kill it.

How to create a project from existing source in Eclipse and then find it?

This answer is going to be for the question

How to create a new eclipse project and add a folder or a new package into the project, or how to build a new project for existing java files.

  1. Create a new project from the menu File->New-> Java Project
  2. If you are going to add a new pakcage, then create the same package name here by File->New-> Package
  3. Click the name of the package in project navigator, and right click, and import... Import->General->File system (choose your file or package)

this worked for me I hope it helps others. Thank you.

How do I clone into a non-empty directory?

Here's what I ended up doing when I had the same problem (at least I think it's the same problem). I went into directory A and ran git init.

Since I didn't want the files in directory A to be followed by git, I edited .gitignore and added the existing files to it. After this I ran git remote add origin '<url>' && git pull origin master et voíla, B is "cloned" into A without a single hiccup.

Making LaTeX tables smaller?

http://en.wikibooks.org/wiki/LaTeX/Tables#Resize_tables talks about two ways to do this.

I used:

\scalebox{0.7}{
  \begin{tabular}
    ...
  \end{tabular}
}

Flatten List in LINQ

iList.SelectMany(x => x).ToArray()

Can you write virtual functions / methods in Java?

From wikipedia

In Java, all non-static methods are by default "virtual functions." Only methods marked with the keyword final, which cannot be overridden, along with private methods, which are not inherited, are non-virtual.

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

The best way to handle the LazyInitializationException is to fetch it upon query time, like this:

select t
from Topic t
left join fetch t.comments

You should ALWAYS avoid the following anti-patterns:

Therefore, make sure that your FetchType.LAZY associations are initialized at query time or within the original @Transactional scope using Hibernate.initialize for secondary collections.

how to configuring a xampp web server for different root directory

For XAMMP versions >=7.5.9-0 also change the DocumentRoot in file "/opt/lampp/etc/extra/httpd-ssl.conf" accordingly.

What's the best way to share data between activities?

Do what google commands you to do! here: http://developer.android.com/resources/faq/framework.html#3

  • Primitive Data Types
  • Non-Persistent Objects
  • Singleton class - my favorite :D
  • A public static field/method
  • A HashMap of WeakReferences to Objects
  • Persistent Objects (Application Preferences, Files, contentProviders, SQLite DB)

How do I loop through a date range?

You might consider writing an iterator instead, which allows you to use normal 'for' loop syntax like '++'. I searched and found a similar question answered here on StackOverflow which gives pointers on making DateTime iterable.

How to add minutes to current time in swift

You can use Calendar's method

func date(byAdding component: Calendar.Component, value: Int, to date: Date, wrappingComponents: Bool = default) -> Date?

to add any Calendar.Component to any Date. You can create a Date extension to add x minutes to your UIDatePicker's date:

Xcode 8 and Xcode 9 • Swift 3.0 and Swift 4.0

extension Date {
    func adding(minutes: Int) -> Date {
        return Calendar.current.date(byAdding: .minute, value: minutes, to: self)!
    }
}

Then you can just use the extension method to add minutes to the sender (UIDatePicker):

let section1 = sender.date.adding(minutes: 5)
let section2 = sender.date.adding(minutes: 10)

Playground testing:

Date().adding(minutes: 10)  //  "Jun 14, 2016, 5:31 PM"

What regular expression will match valid international phone numbers?

Modified @Eric's regular expression - added a list of all country codes (got them from xxxdepy @ Github. I hope you will find it helpful:

/(\+|00)(297|93|244|1264|358|355|376|971|54|374|1684|1268|61|43|994|257|32|229|226|880|359|973|1242|387|590|375|501|1441|591|55|1246|673|975|267|236|1|61|41|56|86|225|237|243|242|682|57|269|238|506|53|5999|61|1345|357|420|49|253|1767|45|1809|1829|1849|213|593|20|291|212|34|372|251|358|679|500|33|298|691|241|44|995|44|233|350|224|590|220|245|240|30|1473|299|502|594|1671|592|852|504|385|509|36|62|44|91|246|353|98|964|354|972|39|1876|44|962|81|76|77|254|996|855|686|1869|82|383|965|856|961|231|218|1758|423|94|266|370|352|371|853|590|212|377|373|261|960|52|692|389|223|356|95|382|976|1670|258|222|1664|596|230|265|60|262|264|687|227|672|234|505|683|31|47|977|674|64|968|92|507|64|51|63|680|675|48|1787|1939|850|351|595|970|689|974|262|40|7|250|966|249|221|65|500|4779|677|232|503|378|252|508|381|211|239|597|421|386|46|268|1721|248|963|1649|235|228|66|992|690|993|670|676|1868|216|90|688|886|255|256|380|598|1|998|3906698|379|1784|58|1284|1340|84|678|681|685|967|27|260|263)(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)\d{4,20}$/

Attempt to present UIViewController on UIViewController whose view is not in the window hierarchy

Probably, like me, you have a wrong root viewController

I want to display a ViewController in a non-UIViewController context,

So I can't use such code:

[self presentViewController:]

So, I get a UIViewController:

[[[[UIApplication sharedApplication] delegate] window] rootViewController]

For some reason (logical bug), the rootViewController is something other than expected (a normal UIViewController). Then I correct the bug, replacing rootViewController with a UINavigationController, and the problem is gone.

HTTP Status 500 - Error instantiating servlet class pkg.coreServlet

The above error can occur for multiple cases during servlet startup / request. Hope you check the full stack trace of the server log, If you have tomcat, you can also see the exact causes in html preview of the 500 Internal Server Error page.

Weird thing is, if you try to hit the request url a second time, you would get 404 Not Found page.

You can also debug this issue, by placing breakpoints on all the classes constructor initialization block, whose objects are created during servlet startup/request.

In my case, I didn't had javaassist jar loaded for the Weld CDI injection to work. And it shown NoClassDefFound Error.

How to configure welcome file list in web.xml

This is my way to setup Servlet as welcome page.

I share for whom concern.

web.xml

  <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>Demo</servlet-name>
        <servlet-class>servlet.Demo</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Demo</servlet-name>
        <url-pattern></url-pattern>
    </servlet-mapping>

Servlet class

@WebServlet(name = "/demo")
public class Demo extends HttpServlet {
   public void doGet(HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException  {
       RequestDispatcher rd = req.getRequestDispatcher("index.jsp");
   }
}

JVM property -Dfile.encoding=UTF8 or UTF-8?

Both UTF8 and UTF-8 work for me.

CREATE TABLE IF NOT EXISTS equivalent in SQL Server

if not exists (select * from sysobjects where name='cars' and xtype='U')
    create table cars (
        Name varchar(64) not null
    )
go

The above will create a table called cars if the table does not already exist.

How to convert Javascript datetime to C# datetime?

JS:

 function createDateObj(date) {
            var day = date.getDate();           // yields 
            var month = date.getMonth();    // yields month
            var year = date.getFullYear();      // yields year
            var hour = date.getHours();         // yields hours 
            var minute = date.getMinutes();     // yields minutes
            var second = date.getSeconds();     // yields seconds
            var millisec = date.getMilliseconds();
            var jsDate = Date.UTC(year, month, day, hour, minute, second, millisec);
            return jsDate;
        }

JS:

var oRequirementEval = new Object();
var date = new Date($("#dueDate").val());

CS:

requirementEvaluations.DeadLine = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
    .AddMilliseconds(Convert.ToDouble( arrayUpdateRequirementEvaluationData["DeadLine"]))
    .ToLocalTime();

Regular expression to match standard 10 digit phone number

Perhaps the easiest one compare to several others.

\(?\d+\)?[-.\s]?\d+[-.\s]?\d+

It matches the following:

(555) 444-6789

555-444-6789

555.444.6789

555 444 6789

How to refresh app upon shaking the device?

You should subscribe as a SensorEventListener, and get the accelerometer data. Once you have it, you should monitor for sudden change in direction (sign) of acceleration on a certain axis. It would be a good indication for the 'shake' movement of device.

Getting value of select (dropdown) before change

This is an improvement on @thisisboris answer. It adds a current value to data, so the code can control when a variable set to the current value is changed.

(function()
{
    // Initialize the previous-attribute
    var selects = $( 'select' );
    $.each( selects, function( index, myValue ) {
        $( myValue ).data( 'mgc-previous', myValue.value );
        $( myValue ).data( 'mgc-current', myValue.value );  
    });

    // Listen on the body for changes to selects
    $('body').on('change', 'select',
        function()
        {
            alert('I am a body alert');
            $(this).data('mgc-previous', $(this).data( 'mgc-current' ) );
            $(this).data('mgc-current', $(this).val() );
        }
    );
})();

Node.js - How to send data from html to express

Using http.createServer is very low-level and really not useful for creating web applications as-is.

A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using npm install express.

When you have, you can create a basic application to handle your form:

var express = require('express');
var bodyParser = require('body-parser');
var app     = express();

//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true })); 

//app.use(express.bodyParser());

app.post('/myaction', function(req, res) {
  res.send('You sent the name "' + req.body.name + '".');
});

app.listen(8080, function() {
  console.log('Server running at http://127.0.0.1:8080/');
});

You can make your form point to it using:

<form action="http://127.0.0.1:8080/myaction" method="post">

The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your index.html). You could use Express to also serve static content, like index.html, using the express.static middleware.

Should MySQL have its timezone set to UTC?

This is a working example:

jdbc:mysql://localhost:3306/database?useUnicode=yes&characterEncoding=UTF-8&serverTimezone=Europe/Moscow

Bootstrap modal link

A Simple Approach will be to use a normal link and add Bootstrap modal effect to it. Just make use of my Code, hopefully you will get it run.

 <div class="container">
        <div class="row">
            <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="addContact" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><b style="color:#fb3600; font-weight:700;">X</b></button><!--&times;-->
                            <h4 class="modal-title text-center" id="addContact">Add Contact</h4>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <ul class="nav nav-tabs">
                                    <li class="active">
                                        <a data-toggle="tab" style="background-color:#f5dfbe" href="#contactTab">Contact</a>
                                    </li>
                                    <li>
                                        <a data-toggle="tab" style="background-color:#a6d2f6" href="#speechTab">Speech</a>
                                    </li>
                                </ul>
                                <div class="tab-content">
                                    <div id="contactTab" class="tab-pane in active"><partial name="CreateContactTag"></div>
                                    <div id="speechTab" class="tab-pane fade in"><partial name="CreateSpeechTag"></div>
                                </div>

                            </div>
                        </div>
                        <div class="modal-footer">
                            <a class="btn btn-info" data-dismiss="modal">Close</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

IndentationError expected an indented block

If you are using a mac and sublime text 3, this is what you do.

Go to your /Packages/User/ and create a file called Python.sublime-settings.

Typically /Packages/User is inside your ~/Library/Application Support/Sublime Text 3/Packages/User/Python.sublime-settings if you are using mac os x.

Then you put this in the Python.sublime-settings.

{
    "tab_size": 4,
    "translate_tabs_to_spaces": false
}

Credit goes to Mark Byer's answer, sublime text 3 docs and python style guide.

This answer is mostly for readers who had the same issue and stumble upon this and are using sublime text 3 on Mac OS X.

How to change colors of a Drawable in Android?

There are so many solution but nobody suggested if the color resource xml file already have color then we can pick directly from there also as below:

ImageView imageView = (ImageView) findViewById(R.id.imageview);
imageView.setColorFilter(getString(R.color.your_color));

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

I had this problem. I searched the internet, took all advices, changes configurations, but the problem is still there. Finally with the help of the server administrator, he found that the problem lies in MySQL database column definition. one of the columns in the a table was assigned to 'Longtext' which leads to allocate 4,294,967,295 bites of memory. It seems working OK if you don't use MySqli prepare statement, but once you use prepare statement, it tries to allocate that amount of memory. I changed the column type to Mediumtext which needs 16,777,215 bites of memory space. The problem is gone. Hope this help.

Creating an instance of class

   /* 1 */ Foo* foo1 = new Foo ();

Creates an object of type Foo in dynamic memory. foo1 points to it. Normally, you wouldn't use raw pointers in C++, but rather a smart pointer. If Foo was a POD-type, this would perform value-initialization (it doesn't apply here).

   /* 2 */ Foo* foo2 = new Foo;

Identical to before, because Foo is not a POD type.

   /* 3 */ Foo foo3;

Creates a Foo object called foo3 in automatic storage.

   /* 4 */ Foo foo4 = Foo::Foo();

Uses copy-initialization to create a Foo object called foo4 in automatic storage.

   /* 5 */ Bar* bar1 = new Bar ( *new Foo() );

Uses Bar's conversion constructor to create an object of type Bar in dynamic storage. bar1 is a pointer to it.

   /* 6 */ Bar* bar2 = new Bar ( *new Foo );

Same as before.

   /* 7 */ Bar* bar3 = new Bar ( Foo foo5 );

This is just invalid syntax. You can't declare a variable there.

   /* 8 */ Bar* bar3 = new Bar ( Foo::Foo() );

Would work and work by the same principle to 5 and 6 if bar3 wasn't declared on in 7.

5 & 6 contain memory leaks.

Syntax like new Bar ( Foo::Foo() ); is not usual. It's usually new Bar ( (Foo()) ); - extra parenthesis account for most-vexing parse. (corrected)

Single TextView with multiple colored text

Kotlin version of @Swapnil Kotwal's answer.

Android Studio 4.0.1, Kotlin 1.3.72

val greenText = SpannableString("This is green,")
greenText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someGreenColor), null), 0, greenText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.text = greenText

val yellowText = SpannableString("this is yellow, ")
yellowText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someYellowColor), null), 0, yellowText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.append(yellowText)

val redText = SpannableString("and this is red.")
redText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someRedColor), null), 0, redText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.append(redText)

How can I pad a String in Java?

Besides Apache Commons, also see String.format which should be able to take care of simple padding (e.g. with spaces).

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

The following works for me. Add the following method to the entity that is not the owner of the relationship (Group)

@PreRemove
private void removeGroupsFromUsers() {
    for (User u : users) {
        u.getGroups().remove(this);
    }
}

Keep in mind that for this to work, the Group must have an updated list of Users (which is not done automatically). so everytime you add a Group to the group list in User entity, you should also add a User to the user list in the Group entity.

Setting max width for body using Bootstrap

Edit

A better way to do this is:

  1. Create your own less file as a main less file ( like bootstrap.less ).

  2. Import all bootstrap less files you need. (in this case, you just need to Import all responsive less files but responsive-1200px-min.less)

  3. If you need to modify anything in original bootstrap less file, you just need to write your own less to overwrite bootstrap's less code. (Just remember to put your less code/file after @import { /* bootstrap's less file */ };).

Original

I have the same problem. This is how I fixed it.

Find the media query:

@media (max-width:1200px) ...

Remove it. (I mean the whole thing , not just @media (max-width:1200px))

Since the default width of Bootstrap is 940px, you don't need to do anything.

If you want to have your own max-width, just modify the css rule in the media query that matches your desired width.

SQL Left Join first match only

Try this

 SELECT *
 FROM people P 
 where P.IDNo in (SELECT DISTINCT IDNo
              FROM people)

Received an invalid column length from the bcp client for colid 6

I know this post is old but I ran into this same issue and finally figured out a solution to determine which column was causing the problem and report it back as needed. I determined that colid returned in the SqlException is not zero based so you need to subtract 1 from it to get the value. After that it is used as the index of the _sortedColumnMappings ArrayList of the SqlBulkCopy instance not the index of the column mappings that were added to the SqlBulkCopy instance. One thing to note is that SqlBulkCopy will stop on the first error received so this may not be the only issue but at least helps to figure it out.

try
{
    bulkCopy.WriteToServer(importTable);
    sqlTran.Commit();
}    
catch (SqlException ex)
{
    if (ex.Message.Contains("Received an invalid column length from the bcp client for colid"))
    {
        string pattern = @"\d+";
        Match match = Regex.Match(ex.Message.ToString(), pattern);
        var index = Convert.ToInt32(match.Value) -1;

        FieldInfo fi = typeof(SqlBulkCopy).GetField("_sortedColumnMappings", BindingFlags.NonPublic | BindingFlags.Instance);
        var sortedColumns = fi.GetValue(bulkCopy);
        var items = (Object[])sortedColumns.GetType().GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(sortedColumns);

        FieldInfo itemdata = items[index].GetType().GetField("_metadata", BindingFlags.NonPublic | BindingFlags.Instance);
        var metadata = itemdata.GetValue(items[index]);

        var column = metadata.GetType().GetField("column", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(metadata);
        var length = metadata.GetType().GetField("length", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(metadata);
        throw new DataFormatException(String.Format("Column: {0} contains data with a length greater than: {1}", column, length));
    }

    throw;
}

Copy entire contents of a directory to another using php

<?php
    function copy_directory( $source, $destination ) {
        if ( is_dir( $source ) ) {
        @mkdir( $destination );
        $directory = dir( $source );
        while ( FALSE !== ( $readdirectory = $directory->read() ) ) {
            if ( $readdirectory == '.' || $readdirectory == '..' ) {
                continue;
            }
            $PathDir = $source . '/' . $readdirectory; 
            if ( is_dir( $PathDir ) ) {
                copy_directory( $PathDir, $destination . '/' . $readdirectory );
                continue;
            }
            copy( $PathDir, $destination . '/' . $readdirectory );
        }

        $directory->close();
        }else {
        copy( $source, $destination );
        }
    }
?>

from the last 4th line , make this

$source = 'wordpress';//i.e. your source path

and

$destination ='b';

What is the most "pythonic" way to iterate over a list in chunks?

You can use partition or chunks function from funcy library:

from funcy import partition

for a, b, c, d in partition(4, ints):
    foo += a * b * c * d

These functions also has iterator versions ipartition and ichunks, which will be more efficient in this case.

You can also peek at their implementation.

Package doesn't exist error in intelliJ

I tried to "Maven > Reimport" but the only thing that actually fixed it was to close the project, delete the .idea directory, and reopen the project.

Abort a git cherry-pick?

For me, the only way to reset the failed cherry-pick-attempt was

git reset --hard HEAD

How to ignore a particular directory or file for tslint?

As an addition

To disable all rules for the next line // tslint:disable-next-line

To disable specific rules for the next line: // tslint:disable-next-line:rule1 rule2...

To disable all rules for the current line: someCode(); // tslint:disable-line

To disable specific rules for the current line: someCode(); // tslint:disable-line:rule1

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

The finalizeQueue may be too long

i think that java may require GC.SuppressFinalize() & GC.ReRegisterForFinalize() to let user reduce the finalizedQueue length explicitly

if the JVM' source code is available, may implement these method ourself, such as android ROM maker

HTML input fields does not get focus when clicked

In my case it was Bootstrap popup in opened state. Text input was in another calendar popup on top of Bootstrap one, input got its focus back after removing tabindex="-1" attribute from Bootstrap modal.

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

Somehow I fixed it by changing

<add name="Access-Control-Allow-Headers" 
     value="Origin, X-Requested-With, Content-Type, Accept, Authorization" 
     />

to

<add name="Access-Control-Allow-Headers" 
     value="Origin, Content-Type, Accept, Authorization" 
     />

req.body empty on posts

In postman, even after following the accepted answer, I was getting an empty request body. The issue turned out to be not passing a header called

Content-Length : <calculated when request is sent>

This header was present by default (along with 5 others) which I have disabled. Enable this and you'll receive the request body.

How to break lines at a specific character in Notepad++?

I have no idea how it can work automatically, but you can copy "], " together with new line and then use replace function.

Why is nginx responding to any domain name?

You should have a default server for catch-all, you can return 404 or better to not respond at all (will save some bandwidth) by returning 444 which is nginx specific HTTP response that simply close the connection and return nothing

server {
    listen       80  default_server;
    server_name  _; # some invalid name that won't match anything
    return       444;
}

Difference between VARCHAR2(10 CHAR) and NVARCHAR2(10)

I don't think answer from Vincent Malgrat is correct. When NVARCHAR2 was introduced long time ago nobody was even talking about Unicode.

Initially Oracle provided VARCHAR2 and NVARCHAR2 to support localization. Common data (include PL/SQL) was hold in VARCHAR2, most likely US7ASCII these days. Then you could apply NLS_NCHAR_CHARACTERSET individually (e.g. WE8ISO8859P1) for each of your customer in any country without touching the common part of your application.

Nowadays character set AL32UTF8 is the default which fully supports Unicode. In my opinion today there is no reason anymore to use NLS_NCHAR_CHARACTERSET, i.e. NVARCHAR2, NCHAR2, NCLOB. Note, there are more and more Oracle native functions which do not support NVARCHAR2, so you should really avoid it. Maybe the only reason is when you have to support mainly Asian characters where AL16UTF16 consumes less storage compared to AL32UTF8.

How do I do a multi-line string in node.js?

As an aside to what folks have been posting here, I've heard that concatenation can be much faster than join in modern javascript vms. Meaning:

var a = 
[ "hey man, this is on a line",
  "and this is on another",
  "and this is on a third"
].join('\n');

Will be slower than:

var a = "hey man, this is on a line\n" + 
        "and this is on another\n" +
        "and this is on a third";    

In certain cases. http://jsperf.com/string-concat-versus-array-join/3

As another aside, I find this one of the more appealing features in Coffeescript. Yes, yes, I know, haters gonna hate.

html = '''
       <strong>
         cup of coffeescript
       </strong>
       '''

Its especially nice for html snippets. I'm not saying its a reason to use it, but I do wish it would land in ecma land :-(.

Josh

Difference between using "chmod a+x" and "chmod 755"

chmod a+x modifies the argument's mode while chmod 755 sets it. Try both variants on something that has full or no permissions and you will notice the difference.

How to open an existing project in Eclipse?

from Eclipse main gui: select "Window->Show View->Other->General->Project Explorer" Double-clicking on "Project Explorer" brings up the "Project Explorer" window which shows every project in your workspace. That worked for me.

Good luck.

PostgreSQL error: Fatal: role "username" does not exist

Installing postgres using apt-get does not create a user role or a database.

To create a superuser role and a database for your personal user account:

sudo -u postgres createuser -s $(whoami); createdb $(whoami)

PHP "php://input" vs $_POST

First, a basic truth about PHP.

PHP was not designed to explicitly give you a pure REST (GET, POST, PUT, PATCH, DELETE) like interface for handling HTTP requests.

However, the $_SERVER, $_COOKIE, $_POST, $_GET, and $_FILES superglobals, and the function filter_input_array() are very useful for the average person's / layman's needs.

The number one hidden advantage of $_POST (and $_GET) is that your input data is url-decoded automatically by PHP. You never even think about having to do it, especially for query string parameters within a standard GET request, or HTTP body data submitted with a POST request.

Other HTTP Request Methods

Those studying the underlying HTTP protocol and its various request methods come to understand that there are many HTTP request methods, including the often referenced PUT, PATCH (not used in Google's Apigee), and DELETE.

In PHP, there are no superglobals or input filter functions for getting HTTP request body data when POST is not used. What are disciples of Roy Fielding to do? ;-)

However, then you learn more ...

That being said, as you advance in your PHP programming knowledge and want to use JavaScript's XmlHttpRequest object (jQuery for some), you come to see the limitation of this scheme.

$_POST limits you to the use of two media types in the HTTP Content-Type header:

  1. application/x-www-form-urlencoded, and
  2. multipart/form-data

Thus, if you want to send data values to PHP on the server, and have it show up in the $_POST superglobal, then you must urlencode it on the client-side and send said data as key/value pairs--an inconvenient step for novices (especially when trying to figure out if different parts of the URL require different forms of urlencoding: normal, raw, etc..).

For all you jQuery users, the $.ajax() method is converting your JSON to URL encoded key/value pairs before transmitting them to the server. You can override this behavior by setting processData: false. Just read the $.ajax() documentation, and don't forget to send the correct media type in the Content-Type header.

php://input, but ...

Even if you use php://input instead of $_POST for your HTTP POST request body data, it will not work with an HTTP Content-Type of multipart/form-data This is the content type that you use on an HTML form when you want to allow file uploads!

<form enctype="multipart/form-data" accept-charset="utf-8" action="post">
    <input type="file" name="resume">
</form>

Therefore, in traditional PHP, to deal with a diversity of content types from an HTTP POST request, you will learn to use $_POST or filter_input_array(POST), $_FILES, and php://input. There is no way to just use one, universal input source for HTTP POST requests in PHP.

You cannot get files through $_POST, filter_input_array(POST), or php://input, and you cannot get JSON/XML/YAML in either filter_input_array(POST) or $_POST.

PHP Manual: php://input

php://input is a read-only stream that allows you to read raw data from the request body...php://input is not available with enctype="multipart/form-data".

PHP Frameworks to the rescue?

PHP frameworks like Codeigniter 4 and Laravel use a facade to provide a cleaner interface (IncomingRequest or Request objects) to the above. This is why professional PHP developers use frameworks instead of raw PHP.

Of course, if you like to program, you can devise your own facade object to provide what frameworks do. It is because I have taken time to investigate this issue that I am able to write this answer.

URL encoding? What the heck!!!???

Typically, if you are doing a normal, synchronous (when the entire page redraws) HTTP requests with an HTML form, the user-agent (web browser) will urlencode your form data for you. If you want to do an asynchronous HTTP requests using the XmlHttpRequest object, then you must fashion a urlencoded string and send it, if you want that data to show up in the $_POST superglobal.

How in touch are you with JavaScript? :-)

Converting from a JavaScript array or object to a urlencoded string bothers many developers (even with new APIs like Form Data). They would much rather just be able to send JSON, and it would be more efficient for the client code to do so.

Remember (wink, wink), the average web developer does not learn to use the XmlHttpRequest object directly, global functions, string functions, array functions, and regular expressions like you and I ;-). Urlencoding for them is a nightmare. ;-)

PHP, what gives?

PHP's lack of intuitive XML and JSON handling turns many people off. You would think it would be part of PHP by now (sigh).

So many media types (MIME types in the past)

XML, JSON, and YAML all have media types that can be put into an HTTP Content-Type header.

  • application/xml
  • applicaiton/json
  • application/yaml (although IANA has no official designation listed)

Look how many media-types (formerly, MIME types) are defined by IANA.

Look how many HTTP headers there are.

php://input or bust

Using the php://input stream allows you to circumvent the baby-sitting / hand holding level of abstraction that PHP has forced on the world. :-) With great power comes great responsibility!

Now, before you deal with data values streamed through php://input, you should / must do a few things.

  1. Determine if the correct HTTP method has been indicated (GET, POST, PUT, PATCH, DELETE, ...)
  2. Determine if the HTTP Content-Type header has been transmitted.
  3. Determine if the value for the Content-Type is the desired media type.
  4. Determine if the data sent is well formed XML / JSON / YAML / etc.
  5. If necessary, convert the data to a PHP datatype: array or object.
  6. If any of these basic checks or conversions fails, throw an exception!

What about the character encoding?

AH, HA! Yes, you might want the data stream being sent into your application to be UTF-8 encoded, but how can you know if it is or not?

Two critical problems.

  1. You do not know how much data is coming through php://input.
  2. You do not know for certain the current encoding of the data stream.

Are you going to attempt to handle stream data without knowing how much is there first? That is a terrible idea. You cannot rely exclusively on the HTTP Content-Length header for guidance on the size of streamed input because it can be spoofed.

You are going to need a:

  1. Stream size detection algorithm.
  2. Application defined stream size limits (Apache / Nginx / PHP limits may be too broad).

Are you going to attempt to convert stream data to UTF-8 without knowing the current encoding of the stream? How? The iconv stream filter (iconv stream filter example) seems to want a starting and ending encoding, like this.

'convert.iconv.ISO-8859-1/UTF-8'

Thus, if you are conscientious, you will need:

  1. Stream encoding detection algorithm.
  2. Dynamic / runtime stream filter definition algorithm (because you cannot know the starting encoding a priori).

(Update: 'convert.iconv.UTF-8/UTF-8' will force everything to UTF-8, but you still have to account for characters that the iconv library might not know how to translate. In other words, you have to some how define what action to take when a character cannot be translated: 1) Insert a dummy character, 2) Fail / throw and exception).

You cannot rely exclusively on the HTTP Content-Encoding header, as this might indicate something like compression as in the following. This is not what you want to make a decision off of in regards to iconv.

Content-Encoding: gzip

Therefore, the general steps might be ...

Part I: HTTP Request Related

  1. Determine if the correct HTTP method has been indicated (GET, POST, PUT, PATCH, DELETE, ...)
  2. Determine if the HTTP Content-Type header has been transmitted.
  3. Determine if the value for the Content-Type is the desired media type.

Part II: Stream Data Related

  1. Determine the size of the input stream (optional, but recommended).
  2. Determine the encoding of the input stream.
  3. If necessary, convert the input stream to the desired character encoding (UTF-8).
  4. If necessary, reverse any application level compression or encryption, and then repeat steps 4, 5, and 6.

Part III: Data Type Related

  1. Determine if the data sent is well formed XML / JSON / YMAL / etc.

(Remember, the data can still be a URL encoded string which you must then parse and URL decode).

  1. If necessary, convert the data to a PHP datatype: array or object.

Part IV: Data Value Related

  1. Filter input data.

  2. Validate input data.

Now do you see?

The $_POST superglobal, along with php.ini settings for limits on input, are simpler for the layman. However, dealing with character encoding is much more intuitive and efficient when using streams because there is no need to loop through superglobals (or arrays, generally) to check input values for the proper encoding.

Write objects into file with Node.js

If you're geting [object object] then use JSON.stringify

fs.writeFile('./data.json', JSON.stringify(obj) , 'utf-8');

It worked for me.

Removing the password from a VBA project

After opening xlsm file with 7 zip, extracting vbaproject.bin and in Notepad ++ replacing DpB with DPx and re-saving I got a Lot of vbaproject errors and vba project password was gone but no code/forms.

I right clicked to export and was able to re-import to a new project.

Java switch statement multiple cases

From the last java-12 release multiple constants in the same case label is available in preview language feature

It is available in a JDK feature release to provoke developer feedback based on real world use; this may lead to it becoming permanent in a future Java SE Platform.

It looks like:

switch(variable) {
    case 1 -> doSomething();
    case 2, 3, 4 -> doSomethingElse();
};

See more JEP 325: Switch Expressions (Preview)

How to use ScrollView in Android?

How to use ScrollView

Using ScrollView is not very difficult. You can just add one to your layout and put whatever you want to scroll inside. ScrollView only takes one child so if you want to put a few things inside then you should make the first thing be something like a LinearLayout.

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <!-- things to scroll -->

    </LinearLayout>
</ScrollView>

If you want to scroll things horizontally, then use a HorizontalScrollView.

Making the content fill the screen

As is talked about in this post, sometimes you want the ScrollView content to fill the screen. For example, if you had some buttons at the end of a readme. You want the buttons to always be at the end of the text and at bottom of the screen, even if the text doesn't scroll.

If the content scrolls, everything is fine. However, if the content is smaller than the size of the screen, the buttons are not at the bottom.

enter image description here

This can be solved with a combination of using fillViewPort on the ScrollView and using a layout weight on the content. Using fillViewPort makes the ScrollView fill the parent area. Setting the layout_weight on one of the views in the LinearLayout makes that view expand to fill any extra space.

enter image description here

Here is the XML

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">                        <--- fillViewport

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textview"
            android:layout_height="0dp"                <--- 
            android:layout_weight="1"                  <--- set layout_weight
            android:layout_width="match_parent"
            android:padding="6dp"
            android:text="hello"/>

        <LinearLayout
            android:layout_height="wrap_content"       <--- wrap_content
            android:layout_width="match_parent"
            android:background="@android:drawable/bottom_bar"
            android:gravity="center_vertical">

            <Button
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:text="Accept" />

            <Button
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:text="Refuse" />

        </LinearLayout>
    </LinearLayout>
</ScrollView>

The idea for this answer came from a previous answer that is now deleted (link for 10K users). The content of this answer is an update and adaptation of this post.

Disable building workspace process in Eclipse

if needed programmatic from a PDE or JDT code:

public static void setWorkspaceAutoBuild(boolean flag) throws CoreException 
{
IWorkspace workspace = ResourcesPlugin.getWorkspace();
final IWorkspaceDescription description = workspace.getDescription();
description.setAutoBuilding(flag);
workspace.setDescription(description);
}

How do I timestamp every ping result?

My original submission was incorrect because it did not evaluate date for each line. Corrections have been made.

Try this

 ping google.com | xargs -L 1 -I '{}' date '+%+: {}'

produces the following output

Thu Aug 15 10:13:59 PDT 2013: PING google.com (74.125.239.103): 56 data bytes
Thu Aug 15 10:13:59 PDT 2013: 64 bytes from 74.125.239.103: icmp_seq=0 ttl=55 time=14.983 ms
Thu Aug 15 10:14:00 PDT 2013: 64 bytes from 74.125.239.103: icmp_seq=1 ttl=55 time=17.340 ms
Thu Aug 15 10:14:01 PDT 2013: 64 bytes from 74.125.239.103: icmp_seq=2 ttl=55 time=15.898 ms
Thu Aug 15 10:14:02 PDT 2013: 64 bytes from 74.125.239.103: icmp_seq=3 ttl=55 time=15.720 ms
Thu Aug 15 10:14:03 PDT 2013: 64 bytes from 74.125.239.103: icmp_seq=4 ttl=55 time=16.899 ms
Thu Aug 15 10:14:04 PDT 2013: 64 bytes from 74.125.239.103: icmp_seq=5 ttl=55 time=16.242 ms
Thu Aug 15 10:14:05 PDT 2013: 64 bytes from 74.125.239.103: icmp_seq=6 ttl=55 time=16.574 ms

The -L 1 option causes xargs to process one line at a time instead of words.

JavaScript closures vs. anonymous functions

I wrote this a while ago to remind myself of what a closure is and how it works in JS.

A closure is a function that, when called, uses the scope in which it was declared, not the scope in which it was called. In javaScript, all functions behave like this. Variable values in a scope persist as long as there is a function that still points to them. The exception to the rule is 'this', which refers to the object that the function is inside when it is called.

var z = 1;
function x(){
    var z = 2; 
    y(function(){
      alert(z);
    });
}
function y(f){
    var z = 3;
    f();
}
x(); //alerts '2' 

How to get css background color on <tr> tag to span entire row

Try this:

    .rowhighlight > td { background: green;}

Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

Also, if you're just looking for a specific value nested within the JSON content you can do something like so:

yourJObject.GetValue("jsonObjectName").Value<string>("jsonPropertyName");

And so on from there.

This could help if you don't want to bear the cost of converting the entire JSON into a C# object.

Is there a command to undo git init?

remove the .git folder in your project root folder

if you installed submodules and want to remove their git, also remove .git from submodules folders

Socket send and receive byte array

First, do not use DataOutputStream unless it’s really necessary. Second:

Socket socket = new Socket("host", port);
OutputStream socketOutputStream = socket.getOutputStream();
socketOutputStream.write(message);

Of course this lacks any error checking but this should get you going. The JDK API Javadoc is your friend and can help you a lot.

sweet-alert display HTML code in text

I just struggled with this. I upgraded from sweetalert 1 -> 2. This library: https://sweetalert.js.org/guides/

The example from documentation "string" doesn't work as I expected. You just can't put it like this.

content: `my es6 string <strong>template</strong>` 

How I solved it:

const template = (`my es6 string <strong'>${variable}</strong>`);
content: {
      element: 'p',
      attributes: {
        innerHTML: `${template}`,
      },
    }

There is no documentation how to do this, it was pure trial and error, but at least seems to work.

Can we overload the main method in Java?

Yes, you can overload main method in Java. you have to call the overloaded main method from the actual main method.

What is the best way to test for an empty string with jquery-out-of-the-box?

Since you can also input numbers as well as fixed type strings, the answer should actually be:

function isBlank(value) {
  return $.trim(value);
}

error: This is probably not a problem with npm. There is likely additional logging output above

Delete node_modules

rm -r node_modules

install packages again

npm install

Strange PostgreSQL "value too long for type character varying(500)"

We had this same issue. We solved it adding 'length' to entity attribute definition:

@Column(columnDefinition="text", length=10485760)
private String configFileXml = ""; 

JavaScript Number Split into individual digits

Without converting to string:

function toDigits(number) {
    var left;
    var results = [];

    while (true) {
        left = number % 10;
        results.unshift(left);
        number = (number - left) / 10;
        if (number === 0) {
            break;
        }
    }

    return results;
}

SQL Server : check if variable is Empty or NULL for WHERE clause

If you can use some dynamic query, you can use LEN . It will give false on both empty and null string. By this way you can implement the option parameter.

ALTER PROCEDURE [dbo].[psProducts] 
(@SearchType varchar(50))
AS
BEGIN
    SET NOCOUNT ON;

DECLARE @Query nvarchar(max) = N'
    SELECT 
        P.[ProductId],
        P.[ProductName],
        P.[ProductPrice],
        P.[Type]
    FROM [Product] P'
    -- if @Searchtype is not null then use the where clause
    SET @Query = CASE WHEN LEN(@SearchType) > 0 THEN @Query + ' WHERE p.[Type] = ' + ''''+ @SearchType + '''' ELSE @Query END   

    EXECUTE sp_executesql @Query
    PRINT @Query
END

Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host

For those who may find this later, after .NET version 4.6, I was running into this problem as well.

Make sure that you check your web.config file for the following lines:

<compilation debug="true" targetFramework="4.5">
...
<httpRuntime targetFramework="4.5" />

If you are running 4.6.x or a higher version of .NET on the server, make sure you adjust these targetFramework values to match the version of the framework on your server. If your versions read less than 4.6.x, then I would recommend you upgrade .NET and use the newer version unless your code is dependent on an older version (which, in that case, you should consider updating it).

I changed the targetFrameworks to 4.7.2 and the problem disappeared:

<compilation debug="true" targetFramework="4.7.2">
...
<httpRuntime targetFramework="4.7.2" />

The newer frameworks sort this issue out by using the best protocol available and blocking insecure or obsolete ones. If the remote service you are trying to connect to or call is giving this error, it could be that they don't support the old protocols anymore.

Is it possible to disable the network in iOS Simulator?

I would suggest you using Charles Proxy app on Mac

It allows you using Bandwidth Throttle feature that was created just for adjusting network connection

Star/Stop Throttling ? command + T
Throttle Settings... ? command + T + ? shift

*If you create you own Preset via Add Preset with Bandwidth 0 and 0 for Download and upload you can simulate no Internet connection. Also it is very useful to enable it only for some specific hosts

As an alternative you can disable your connection on Mac because all traffic from Simulator go thought your computer

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

From the v3 documentation (Developer's Guide > Concepts > Developing for Mobile Devices):

Android and iOS devices respect the following <meta> tag:

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

This setting specifies that the map should be displayed full-screen and should not be resizable by the user. Note that the iPhone's Safari browser requires this <meta> tag be included within the page's <head> element.

How do I find the date a video (.AVI .MP4) was actually recorded?

Quick Command for Finding Date/Time Metadata in Many Video Files

The following command has served me well in finding date/time metadata on various AVI/MP4 videos:

ffmpeg -i /path/to/video.mp4 -dump

Note: as mentioned in other answers, there is no guarantee that such information is available in all video files or available in a specific format.

Abbreviated Sample Output for Some AVI File

    Metadata:
      Make            : FUJIFILM
      Model           : FinePix AX655
      DateTime        : 2014:08:25 05:19:45
      JPEGInterchangeFormat:     658
      JPEGInterchangeFormatLength:    1521
      Copyright       :     
      DateTimeOriginal: 2014:08:25 05:19:45
      DateTimeDigitized: 2014:08:25 05:19:45

Abbreviated Sample Output for Some MP4 File

  Metadata:
    major_brand     : mp41
    minor_version   : 538120216
    compatible_brands: mp41
    creation_time   : 2018-03-13T15:43:24.000000Z

Finding non-numeric rows in dataframe in pandas?

You could use np.isreal to check the type of each element (applymap applies a function to each element in the DataFrame):

In [11]: df.applymap(np.isreal)
Out[11]:
          a     b
item
a      True  True
b      True  True
c      True  True
d     False  True
e      True  True

If all in the row are True then they are all numeric:

In [12]: df.applymap(np.isreal).all(1)
Out[12]:
item
a        True
b        True
c        True
d       False
e        True
dtype: bool

So to get the subDataFrame of rouges, (Note: the negation, ~, of the above finds the ones which have at least one rogue non-numeric):

In [13]: df[~df.applymap(np.isreal).all(1)]
Out[13]:
        a    b
item
d     bad  0.4

You could also find the location of the first offender you could use argmin:

In [14]: np.argmin(df.applymap(np.isreal).all(1))
Out[14]: 'd'

As @CTZhu points out, it may be slightly faster to check whether it's an instance of either int or float (there is some additional overhead with np.isreal):

df.applymap(lambda x: isinstance(x, (int, float)))

how to extract only the year from the date in sql server 2008?

year(@date)
year(getdate())
year('20120101')

update table
set column = year(date_column)
whre ....

or if you need it in another table

 update t
   set column = year(t1.date_column)
     from table_source t1
     join table_target t on (join condition)
    where ....

Regex to validate date format dd/mm/yyyy

Please Following Expression

Regex regex = new Regex(@"(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$");

Run an Ansible task only when the variable contains a specific string

This example uses regex_search to perform a substring search.

- name: make conditional variable
  command: "file -s /dev/xvdf"
  register: fsm_out

- name: makefs
  command: touch "/tmp/condition_satisfied"
  when: fsm_out.stdout | regex_search(' data')

ansible version: 2.4.3.0

How to send a PUT/DELETE request in jQuery?

From here, you can do this:

/* Extend jQuery with functions for PUT and DELETE requests. */

function _ajax_request(url, data, callback, type, method) {
    if (jQuery.isFunction(data)) {
        callback = data;
        data = {};
    }
    return jQuery.ajax({
        type: method,
        url: url,
        data: data,
        success: callback,
        dataType: type
        });
}

jQuery.extend({
    put: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'PUT');
    },
    delete_: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'DELETE');
    }
});

It's basically just a copy of $.post() with the method parameter adapted.

Twitter Bootstrap dropdown menu

It actually requires inclusion of Twitter Bootstrap's dropdown.js

http://getbootstrap.com/2.3.2/components.html

How to fix UITableView separator on iOS 7?

This is default by iOS7 design. try to do the below:

[tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];

You can set the 'Separator Inset' from the storyboard:

enter image description here

enter image description here

Send data from javascript to a mysql database

The other posters are correct you cannot connect to MySQL directly from javascript. This is because JavaScript is at client side & mysql is server side.

So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net

If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.

http://api.jquery.com/jQuery.ajax/

How can I easily add storage to a VirtualBox machine with XP installed?

Taked from here => forums.virtualbox.org/viewtopic.php?p=41118#p41118

You could try something like this (see also Tutorial - All about VDIs: How can I resize the partitions inside my VDI?):

  • Create a new VDI of the desired size.
  • Boot GParted Live in a VM with both old and new VDIs attached.
  • Check in the partition editor (opened automatically after booting) what your old and new disk locations are. (It'll be something like /dev/hda and /dev/hdb.)
  • Copy contents from old to new disk. This will take a fair amount of time. (Here /dev/hdX is your original disk and /dev/hdY the new one).

    dd if=/dev/hdX of=/dev/hdY

    Warning: Make sure you do not mix up your input and output disks or you'll wipe all information from your original disk! (if= specifies the input and of= specifies the output.)

  • Reboot (again with GParted-Live). Now you should be able to increase the Windows partition size on the new disk.

Once you've verified the larger VDI boots Windows fine (and disk size is as you'd expect) you can of course delete the old smaller VDI.

Edit: Instead of rebooting before you resize the partition you should be able to run partprobe and the hit CTRL+R in GParted instead.

change background image in body

If you're page has an Open Graph image, commonly used for social sharing, you can use it to set the background image at runtime with vanilla JavaScript like so:

<script>
  const meta = document.querySelector('[property="og:image"]');
  const body = document.querySelector("body");
  body.style.background = `url(${meta.content})`;
</script>

The above uses document.querySelector and Attribute Selectors to assign meta the first Open Graph image it selects. A similar task is performed to get the body. Finally, string interpolation is used to assign body the background.style the value of the path to the Open Graph image.

If you want the image to cover the entire viewport and stay fixed set background-size like so:

body.style.background = `url(${meta.content}) center center no-repeat fixed`;
body.style.backgroundSize = 'cover';

Using this approach you can set a low-quality background image placeholder using CSS and swap with a high-fidelity image later using an image onload event, thereby reducing perceived latency.

Force to open "Save As..." popup open at text link click for PDF in HTML

If you have a plugin within the browser which knows how to open a PDF file it will open directly. Like in case of images and HTML content.

So the alternative approach is not to send your MIME type in the response. In this way the browser will never know which plugin should open it. Hence it will give you a Save/Open dialog box.

How do I add a library project to Android Studio?

If you need access to the resources of a library project (as you do with ABS) ensure that you add the library project/module as a "Module Dependency" instead of a "Library".

Java, Check if integer is multiple of a number

Use modulo

whenever a number x is a multiple of some number y, then always x % y equal to 0, which can be used as a check. So use

if (j % 4 == 0) 

python: Appending a dictionary to a list - I see a pointer like behavior

Also with dict

a = []
b = {1:'one'}

a.append(dict(b))
print a
b[1]='iuqsdgf'
print a

result

[{1: 'one'}]
[{1: 'one'}]

The difference between the Runnable and Callable interfaces in Java

Purpose of these interfaces from oracle documentation :

Runnable interface should be implemented by any class whose instances are intended to be executed by a Thread. The class must define a method of no arguments called run.

Callable: A task that returns a result and may throw an exception. Implementors define a single method with no arguments called call. The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.

Other differences:

  1. You can pass Runnable to create a Thread. But you can't create new Thread by passing Callable as parameter. You can pass Callable only to ExecutorService instances.

    Example:

    public class HelloRunnable implements Runnable {
    
        public void run() {
            System.out.println("Hello from a thread!");
        }   
    
        public static void main(String args[]) {
            (new Thread(new HelloRunnable())).start();
        }
    
    }
    
  2. Use Runnable for fire and forget calls. Use Callable to verify the result.

  3. Callable can be passed to invokeAll method unlike Runnable. Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete

  4. Trivial difference : method name to be implemented => run() for Runnable and call() for Callable.

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

Refresh Page C# ASP.NET

Use:

Response.Redirect(Request.RawUrl, true);

Hide Show content-list with only CSS, no javascript used

I used a hidden checkbox to persistent view of some message. The checkbox could be hidden (display:none) or not. This is a tiny code that I could write.

You can see and test the demo on JSFiddle

HTML:

<input type=checkbox id="show">
<label for="show">Help?</label>
<span id="content">Do you need some help?</span>

CSS:

#show,#content{display:none;}
#show:checked~#content{display:block;}

Run code snippet:

_x000D_
_x000D_
#show,#content{display:none;}_x000D_
#show:checked~#content{display:block;}
_x000D_
<input id="show" type=checkbox>_x000D_
<label for="show">Click for Help</label>_x000D_
<span  id="content">Do you need some help?</span>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/9s8scbL7/

Use jQuery to navigate away from page

window.location.href = "/somewhere/else";

Getting "TypeError: failed to fetch" when the request hasn't actually failed

I know it's a relative old post but, I would like to share what worked for me: I've simply input "http://" before "localhost" in the url. Hope it helps somebody.

MySQL Insert into multiple tables? (Database normalization?)

Just a remark about your saying

Hi, I tried searching a way to insert information in multiple tables in the same query

Do you eat all your lunch dishes mixed with drinks in the same bowl?
I suppose - no.

Same here.
There are things we do separately.
2 insert queries are 2 insert queries. It's all right. Nothing wrong with it. No need to mash it in one.
Same for select. Query must be sensible and do it's job. That's the only reasons. Number of queries is not.

As for the transactions - you may use them, but it's not THAT big deal for the average web-site. If it happened once a year (if ever) that one user registration being broken you'll be able to fix, no doubt.
there are hundreds of thousands sites running mysql with no transaction support driver. Have you heard of terrible disasters breaking these sites apart? Me neither.

And mysql_insert_id() has noting to do with transactions. you may include in into transaction all right. it's just different matters. Someone raised this question out of nowhere.

What port is used by Java RMI connection?

From the javadoc of java.rmi.registry.Registry

Therefore, a registry's remote object implementation is typically exported with a well-known address, such as with a well-known ObjID and TCP port number (default is 1099).

See more in the javadoc of java.rmi.registry.LocateRegistry.

Is this the proper way to do boolean test in SQL?

I personally prefer using char(1) with values 'Y' and 'N' for databases that don't have a native type for boolean. Letters are more user frendly than numbers which assume that those reading it will now that 1 corresponds to true and 0 corresponds to false.

'Y' and 'N' also maps nicely when using (N)Hibernate.

Injection of autowired dependencies failed;

Do you have a bean declared in your context file that has an id of "articleService"? I believe that autowiring matches the id of a bean in your context files with the variable name that you are attempting to Autowire.

PHP: How can I determine if a variable has a value that is between two distinct constant values?

if (($value > 1 && $value < 10) || ($value > 20 && $value < 40))

How to configure SSL certificates with Charles Web Proxy and the latest Android Emulator on Windows?

What worked for me - should really be moved to iPhone:

Charles

  1. Enable transparent Http proxying
  2. Enable SSL proxying
  3. Right click on incoming request and select SSL proxying

Mac

  1. Download Charles CA Certificate bundle http://www.charlesproxy.com/ssl.zip
  2. Email yourself charles-proxy-ssl-proxying-certificate.crt

iPhone

  1. Enable http proxy for Charles on port 8888
  2. Select and install email attachment, yes trust it!

Voila, you can now view encrypted traffic from the domain added in the SSL proxying

Show/hide div if checkbox selected

<input type="checkbox" name="check1" value="checkbox" onchange="showMe('div1')" /> checkbox

<div id="div1" style="display:none;">NOTICE</div>

  <script type="text/javascript">
<!--
   function showMe (box) {
    var chboxs = document.getElementById("div1").style.display;
    var vis = "none";
        if(chboxs=="none"){
         vis = "block"; }
        if(chboxs=="block"){
         vis = "none"; }
    document.getElementById(box).style.display = vis;
}
  //-->
</script>

How to create user for a db in postgresql?

From CLI:

$ su - postgres 
$ psql template1
template1=# CREATE USER tester WITH PASSWORD 'test_password';
template1=# GRANT ALL PRIVILEGES ON DATABASE "test_database" to tester;
template1=# \q

PHP (as tested on localhost, it works as expected):

  $connString = 'port=5432 dbname=test_database user=tester password=test_password';
  $connHandler = pg_connect($connString);
  echo 'Connected to '.pg_dbname($connHandler);

Keep values selected after form submission

<select name="name">
   <option <?php if ($_GET['name'] == 'a') { ?>selected="true" <?php }; ?>value="a">a</option>
   <option <?php if ($_GET['name'] == 'b') { ?>selected="true" <?php }; ?>value="b">b</option>
</select>

How do you refresh the MySQL configuration file without restarting?

Try:

sudo /etc/init.d/mysql reload

or

sudo /etc/init.d/mysql force-reload

That should initiate a reload of the configuration. Make sureyour init.d script supports it though, I don't know what version of MySQL/OS you are using?

My MySQL script contains the following:

'reload'|'force-reload')
        log_daemon_msg "Reloading MySQL database server" "mysqld"
        $MYADMIN reload
        log_end_msg 0
        ;;

Find duplicate records in MySQL

The key is to rewrite this query so that it can be used as a subquery.

SELECT firstname, 
   lastname, 
   list.address 
FROM list
   INNER JOIN (SELECT address
               FROM   list
               GROUP  BY address
               HAVING COUNT(id) > 1) dup
           ON list.address = dup.address;

What is the purpose of a self executing function in javascript?

Self executing function are used to manage the scope of a Variable.

The scope of a variable is the region of your program in which it is defined.

A global variable has global scope; it is defined everywhere in your JavaScript code and can be accessed from anywhere within the script, even in your functions. On the other hand, variables declared within a function are defined only within the body of the function. They are local variables, have local scope and can only be accessed within that function. Function parameters also count as local variables and are defined only within the body of the function.

As shown below, you can access the global variables variable inside your function and also note that within the body of a function, a local variable takes precedence over a global variable with the same name.

var globalvar = "globalvar"; // this var can be accessed anywhere within the script

function scope() {
    alert(globalvar);
    var localvar = "localvar"; //can only be accessed within the function scope
}

scope(); 

So basically a self executing function allows code to be written without concern of how variables are named in other blocks of javascript code.

Bootstrap: Collapse other sections when one is expanded

Using data-parent, first solution is to stick to the example selector architecture

<div id="myGroup">
    <button class="btn dropdown" data-toggle="collapse" data-target="#keys" data-parent="#myGroup"><i class="icon-chevron-right"></i> Keys  <span class="badge badge-info pull-right">X</span></button>
    <button class="btn dropdown" data-toggle="collapse" data-target="#attrs" data-parent="#myGroup"><i class="icon-chevron-right"></i> Attributes</button>
    <button class="btn dropdown" data-toggle="collapse" data-target="#edit" data-parent="#myGroup"><i class="icon-chevron-right"></i> Edit Details</button>

    <div class="accordion-group">
        <div class="collapse indent" id="keys">
            keys
        </div>

        <div class="collapse indent" id="attrs">
            attrs
        </div>

        <div class="collapse" id="edit">
            edit
        </div>
    </div>
</div>

Demo (jsfiddle)

Second solution is to bind on the events and hide the other collapsible elements yourself.

var $myGroup = $('#myGroup');
$myGroup.on('show.bs.collapse','.collapse', function() {
    $myGroup.find('.collapse.in').collapse('hide');
});

Demo (jsfiddle)

PS: the strange effect in the demos is caused by the min-height set for the example, just ignore that.


Edit: changed the JS event from show to show.bs.collapse as specified in Bootstrap documentation.

Handling the window closing event with WPF / MVVM Light Toolkit

This code works just fine:

ViewModel.cs:

public ICommand WindowClosing
{
    get
    {
        return new RelayCommand<CancelEventArgs>(
            (args) =>{
                     });
    }
}

and in XAML:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Closing">
        <command:EventToCommand Command="{Binding WindowClosing}" PassEventArgsToCommand="True" />
    </i:EventTrigger>
</i:Interaction.Triggers>

assuming that:

  • ViewModel is assigned to a DataContext of the main container.
  • xmlns:command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.SL5"
  • xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

How to find which version of Oracle is installed on a Linux server (In terminal)

Login as sys user in sql*plus. Then do this query:

select * from v$version; 

or

select * from product_component_version;

Call removeView() on the child's parent first

You can also do it by checking if View's indexOfView method if indexOfView method returns -1 then we can use.

ViewGroup's detachViewFromParent(v); followed by ViewGroup's removeDetachedView(v, true/false);

MySQL - How to select rows where value is in array?

If you use the FIND_IN_SET function:

FIND_IN_SET(a, columnname) yields all the records that have "a" in them, alone or with others

AND

FIND_IN_SET(columnname, a) yields only the records that have "a" in them alone, NOT the ones with the others

So if record1 is (a,b,c) and record2 is (a)

FIND_IN_SET(columnname, a) yields only record2 whereas FIND_IN_SET(a, columnname) yields both records.

How do I install the OpenSSL libraries on Ubuntu?

As a general rule, when on Debian or Ubuntu and you're missing a development file (or any other file for that matter), use apt-file to figure out which package provides that file:

~ apt-file search openssl/bio.h
android-libboringssl-dev: /usr/include/android/openssl/bio.h
libssl-dev: /usr/include/openssl/bio.h
libwolfssl-dev: /usr/include/cyassl/openssl/bio.h
libwolfssl-dev: /usr/include/wolfssl/openssl/bio.h

A quick glance at each of the packages that are returned by the command, using apt show will tell you which among the packages is the one you're looking for:

~ apt show libssl-dev
Package: libssl-dev
Version: 1.1.1d-2
Priority: optional
Section: libdevel
Source: openssl
Maintainer: Debian OpenSSL Team <[email protected]>
Installed-Size: 8,095 kB
Depends: libssl1.1 (= 1.1.1d-2)
Suggests: libssl-doc
Conflicts: libssl1.0-dev
Homepage: https://www.openssl.org/
Tag: devel::lang:c, devel::library, implemented-in::TODO, implemented-in::c,
 protocol::ssl, role::devel-lib, security::cryptography
Download-Size: 1,797 kB
APT-Sources: http://ftp.fr.debian.org/debian unstable/main amd64 Packages
Description: Secure Sockets Layer toolkit - development files
 This package is part of the OpenSSL project's implementation of the SSL
 and TLS cryptographic protocols for secure communication over the
 Internet.
 .
 It contains development libraries, header files, and manpages for libssl
 and libcrypto.

N: There is 1 additional record. Please use the '-a' switch to see it

How to format a numeric column as phone number in SQL

You Can Use FORMAT if you column is a number Syntax like FORMAT ( value, format [, culture ] ) In use like FORMAT ( @d, 'D', 'en-US' ) or FORMAT(123456789,'###-##-####') (But This works for only SQL SERVER 2012 And After)

In Use Like UPDATE TABLE_NAME SET COLUMN_NAME = FORMAT(COLUMN_NAME ,'###-##-####')

And

if your column is Varchar Or Nvarchar use do like this CONCAT(SUBSTRING(CELLPHONE,0,4),' ',SUBSTRING(CELLPHONE,4,3),' ',SUBSTRING(CELLPHONE,7,2) ,' ',SUBSTRING(CELLPHONE,9,2) )

You can always get help from

https://msdn.microsoft.com/en-us/library/hh213505.aspx

How to overload functions in javascript?

There are multiple aspects to argument overloading in Javascript:

  1. Variable arguments - You can pass different sets of arguments (in both type and quantity) and the function will behave in a way that matches the arguments passed to it.

  2. Default arguments - You can define a default value for an argument if it is not passed.

  3. Named arguments - Argument order becomes irrelevant and you just name which arguments you want to pass to the function.

Below is a section on each of these categories of argument handling.

Variable Arguments

Because javascript has no type checking on arguments or required qty of arguments, you can just have one implementation of myFunc() that can adapt to what arguments were passed to it by checking the type, presence or quantity of arguments.

jQuery does this all the time. You can make some of the arguments optional or you can branch in your function depending upon what arguments are passed to it.

In implementing these types of overloads, you have several different techniques you can use:

  1. You can check for the presence of any given argument by checking to see if the declared argument name value is undefined.
  2. You can check the total quantity or arguments with arguments.length.
  3. You can check the type of any given argument.
  4. For variable numbers of arguments, you can use the arguments pseudo-array to access any given argument with arguments[i].

Here are some examples:

Let's look at jQuery's obj.data() method. It supports four different forms of usage:

obj.data("key");
obj.data("key", value);
obj.data();
obj.data(object);

Each one triggers a different behavior and, without using this dynamic form of overloading, would require four separate functions.

Here's how one can discern between all these options in English and then I'll combine them all in code:

// get the data element associated with a particular key value
obj.data("key");

If the first argument passed to .data() is a string and the second argument is undefined, then the caller must be using this form.


// set the value associated with a particular key
obj.data("key", value);

If the second argument is not undefined, then set the value of a particular key.


// get all keys/values
obj.data();

If no arguments are passed, then return all keys/values in a returned object.


// set all keys/values from the passed in object
obj.data(object);

If the type of the first argument is a plain object, then set all keys/values from that object.


Here's how you could combine all of those in one set of javascript logic:

 // method declaration for .data()
 data: function(key, value) {
     if (arguments.length === 0) {
         // .data()
         // no args passed, return all keys/values in an object
     } else if (typeof key === "string") {
         // first arg is a string, look at type of second arg
         if (typeof value !== "undefined") {
             // .data("key", value)
             // set the value for a particular key
         } else {
             // .data("key")
             // retrieve a value for a key
         }
     } else if (typeof key === "object") {
         // .data(object)
         // set all key/value pairs from this object
     } else {
         // unsupported arguments passed
     }
 },

The key to this technique is to make sure that all forms of arguments you want to accept are uniquely identifiable and there is never any confusion about which form the caller is using. This generally requires ordering the arguments appropriately and making sure that there is enough uniqueness in the type and position of the arguments that you can always tell which form is being used.

For example, if you have a function that takes three string arguments:

obj.query("firstArg", "secondArg", "thirdArg");

You can easily make the third argument optional and you can easily detect that condition, but you cannot make only the second argument optional because you can't tell which of these the caller means to be passing because there is no way to identify if the second argument is meant to be the second argument or the second argument was omitted so what's in the second argument's spot is actually the third argument:

obj.query("firstArg", "secondArg");
obj.query("firstArg", "thirdArg");

Since all three arguments are the same type, you can't tell the difference between different arguments so you don't know what the caller intended. With this calling style, only the third argument can be optional. If you wanted to omit the second argument, it would have to be passed as null (or some other detectable value) instead and your code would detect that:

obj.query("firstArg", null, "thirdArg");

Here's a jQuery example of optional arguments. both arguments are optional and take on default values if not passed:

clone: function( dataAndEvents, deepDataAndEvents ) {
    dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
    deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;

    return this.map( function () {
        return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
    });
},

Here's a jQuery example where the argument can be missing or any one of three different types which gives you four different overloads:

html: function( value ) {
    if ( value === undefined ) {
        return this[0] && this[0].nodeType === 1 ?
            this[0].innerHTML.replace(rinlinejQuery, "") :
            null;

    // See if we can take a shortcut and just use innerHTML
    } else if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
        (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
        !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {

        value = value.replace(rxhtmlTag, "<$1></$2>");

        try {
            for ( var i = 0, l = this.length; i < l; i++ ) {
                // Remove element nodes and prevent memory leaks
                if ( this[i].nodeType === 1 ) {
                    jQuery.cleanData( this[i].getElementsByTagName("*") );
                    this[i].innerHTML = value;
                }
            }

        // If using innerHTML throws an exception, use the fallback method
        } catch(e) {
            this.empty().append( value );
        }

    } else if ( jQuery.isFunction( value ) ) {
        this.each(function(i){
            var self = jQuery( this );

            self.html( value.call(this, i, self.html()) );
        });

    } else {
        this.empty().append( value );
    }

    return this;
},

Named Arguments

Other languages (like Python) allow one to pass named arguments as a means of passing only some arguments and making the arguments independent of the order they are passed in. Javascript does not directly support the feature of named arguments. A design pattern that is commonly used in its place is to pass a map of properties/values. This can be done by passing an object with properties and values or in ES6 and above, you could actually pass a Map object itself.

Here's a simple ES5 example:

jQuery's $.ajax() accepts a form of usage where you just pass it a single parameter which is a regular Javascript object with properties and values. Which properties you pass it determine which arguments/options are being passed to the ajax call. Some may be required, many are optional. Since they are properties on an object, there is no specific order. In fact, there are more than 30 different properties that can be passed on that object, only one (the url) is required.

Here's an example:

$.ajax({url: "http://www.example.com/somepath", data: myArgs, dataType: "json"}).then(function(result) {
    // process result here
});

Inside of the $.ajax() implementation, it can then just interrogate which properties were passed on the incoming object and use those as named arguments. This can be done either with for (prop in obj) or by getting all the properties into an array with Object.keys(obj) and then iterating that array.

This technique is used very commonly in Javascript when there are large numbers of arguments and/or many arguments are optional. Note: this puts an onus on the implementating function to make sure that a minimal valid set of arguments is present and to give the caller some debug feedback what is missing if insufficient arguments are passed (probably by throwing an exception with a helpful error message).

In an ES6 environment, it is possible to use destructuring to create default properties/values for the above passed object. This is discussed in more detail in this reference article.

Here's one example from that article:

function selectEntries({ start=0, end=-1, step=1 } = {}) {
    ···
};

This creates default properties and values for the start, end and step properties on an object passed to the selectEntries() function.

Default values for function arguments

In ES6, Javascript adds built-in language support for default values for arguments.

For example:

function multiply(a, b = 1) {
  return a*b;
}

multiply(5); // 5

Further description of the ways this can be used here on MDN.

Ansible date variable

The filter option filters only the first level subkey below ansible_facts

How can I debug git/git-shell related problems?

For even more verbose output use following:

GIT_CURL_VERBOSE=1 GIT_TRACE=1 git pull origin master

How to know elastic search installed version from kibana?

If you are logged into your Kibana, you can click on the Management tab and that will show your Kibana version. Alternatively, you can click on the small tube-like icon enter image description here and that will show the version number.

How to conclude your merge of a file?

If you encounter this error in SourceTree, go to Actions>Resolve Conflicts>Restart Merge.

SourceTree version used is 1.6.14.0

How to retrieve the LoaderException property?

catch (ReflectionTypeLoadException ex)
{        
    foreach (var item in ex.LoaderExceptions)
    {
          MessageBox.Show(item.Message);                    
    }
}

I'm sorry for resurrecting an old thread, but wanted to post a different solution to pull the loader exception (Using the actual ReflectionTypeLoadException) for anybody else to come across this.

Open mvc view in new window from controller

Yeah you can do some tricky works to simulate what you want:

1) Call your controller from a view by ajax. 2) Return your View

3) Use something like the following in the success (or maybe error! error works for me!) section of your $.ajax request:

$("#imgPrint").click(function () {
        $.ajax({
            url: ...,
            type: 'POST', dataType: 'json',
            data: $("#frm").serialize(),
            success: function (data, textStatus, jqXHR) {
                //Here it is:
                //Gets the model state
                var isValid = '@Html.Raw(Json.Encode(ViewData.ModelState.IsValid))'; 
                // checks that model is valid                    
                if (isValid == 'true') {
                    //open new tab or window - according to configs of browser
                    var w = window.open();
                    //put what controller gave in the new tab or win 
                    $(w.document.body).html(jqXHR.responseText);
                }
                $("#imgSpinner1").hide();
            },
            error: function (jqXHR, textStatus, errorThrown) {
                // And here it is for error section. 
                //Pay attention to different order of 
                //parameters of success and error sections!
                var isValid = '@Html.Raw(Json.Encode(ViewData.ModelState.IsValid))';                    
                if (isValid == 'true') {
                    var w = window.open();
                    $(w.document.body).html(jqXHR.responseText);
                }
                $("#imgSpinner1").hide();
            },
            beforeSend: function () { $("#imgSpinner1").show(); },
            complete: function () { $("#imgSpinner1").hide(); }
        });            
    });      

Get all variables sent with POST?

The variable $_POST is automatically populated.

Try var_dump($_POST); to see the contents.

You can access individual values like this: echo $_POST["name"];

This, of course, assumes your form is using the typical form encoding (i.e. enctype=”multipart/form-data”

If your post data is in another format (e.g. JSON or XML, you can do something like this:

$post = file_get_contents('php://input');

and $post will contain the raw data.

Assuming you're using the standard $_POST variable, you can test if a checkbox is checked like this:

if(isset($_POST['myCheckbox']) && $_POST['myCheckbox'] == 'Yes')
{
     ...
}

If you have an array of checkboxes (e.g.

<form action="myscript.php" method="post">
  <input type="checkbox" name="myCheckbox[]" value="A" />val1<br />
  <input type="checkbox" name="myCheckbox[]" value="B" />val2<br />
  <input type="checkbox" name="myCheckbox[]" value="C" />val3<br />
  <input type="checkbox" name="myCheckbox[]" value="D" />val4<br />
  <input type="checkbox" name="myCheckbox[]" value="E" />val5
  <input type="submit" name="Submit" value="Submit" />
</form>

Using [ ] in the checkbox name indicates that the selected values will be accessed by PHP script as an array. In this case $_POST['myCheckbox'] won't return a single string but will return an array consisting of all the values of the checkboxes that were checked.

For instance, if I checked all the boxes, $_POST['myCheckbox'] would be an array consisting of: {A, B, C, D, E}. Here's an example of how to retrieve the array of values and display them:

  $myboxes = $_POST['myCheckbox'];
  if(empty($myboxes))
  {
    echo("You didn't select any boxes.");
  }
  else
  {
    $i = count($myboxes);
    echo("You selected $i box(es): <br>");
    for($j = 0; $j < $i; $j++)
    {
      echo $myboxes[$j] . "<br>";
    }
  }

How do you open a file in C++?

There are three ways to do this, depending on your needs. You could use the old-school C way and call fopen/fread/fclose, or you could use the C++ fstream facilities (ifstream/ofstream), or if you're using MFC, use the CFile class, which provides functions to accomplish actual file operations.

All of these are suitable for both text and binary, though none have a specific readline functionality. What you'd most likely do instead in that case is use the fstream classes (fstream.h) and use the stream operators (<< and >>) or the read function to read/write blocks of text:

int nsize = 10;
char *somedata;
ifstream myfile;
myfile.open("<path to file>");
myfile.read(somedata,nsize);
myfile.close();

Note that, if you're using Visual Studio 2005 or higher, traditional fstream may not be available (there's a new Microsoft implementation, which is slightly different, but accomplishes the same thing).

Declaring a python function with an array parameters and passing an array argument to the function call?

Maybe you want unpack elements of array, I don't know if I got it, but below a example:

def my_func(*args):
    for a in args:
        print a

my_func(*[1,2,3,4])
my_list = ['a','b','c']
my_func(*my_list)

A method to reverse effect of java String.split()?

Below code gives a basic idea. This is not best solution though.

public static String splitJoin(String sourceStr, String delim,boolean trim,boolean ignoreEmpty){
    return join(Arrays.asList(sourceStr.split(delim)), delim, ignoreEmpty);
}


public static String join(List<?> list, String delim, boolean ignoreEmpty) {
    int len = list.size();
    if (len == 0)
        return "";
    StringBuilder sb = new StringBuilder(list.get(0).toString());
    for (int i = 1; i < len; i++) {
        if (ignoreEmpty && !StringUtils.isBlank(list.get(i).toString())) {
            sb.append(delim);
            sb.append(list.get(i).toString().trim());
        }
    }
    return sb.toString();
}

How to create and add users to a group in Jenkins for authentication?

I installed the Role plugin under Jenkins-3.5, but it does not show the "Manage Roles" option under "Manage Jenkins", and when one follows the security install page from the wiki, all users are locked out instantly. I had to manually shutdown Jenkins on the server, restore the correct configuration settings (/me is happy to do proper backups) and restart Jenkins.

I didn't have high hopes, as that plugin was last updated in 2011

Using JAXB to unmarshal/marshal a List<String>

This can be done MUCH easier using wonderful XStream library. No wrappers, no annotations.

Target XML

<Strings>
  <String>a</String>
  <String>b</String>
</Strings>

Serialization

(String alias can be avoided by using lowercase string tag, but I used OP's code)

List <String> list = new ArrayList <String>();
list.add("a");
list.add("b");

XStream xStream = new XStream();
xStream.alias("Strings", List.class);
xStream.alias("String", String.class);
String result = xStream.toXML(list);

Deserialization

Deserialization into ArrayList

XStream xStream = new XStream();
xStream.alias("Strings", ArrayList.class);
xStream.alias("String", String.class);
xStream.addImplicitArray(ArrayList.class, "elementData");
List <String> result = (List <String>)xStream.fromXML(file);

Deserialization into String[]

XStream xStream = new XStream();
xStream.alias("Strings", String[].class);
xStream.alias("String", String.class);
String[] result = (String[])xStream.fromXML(file);

Note, that XStream instance is thread-safe and can be pre-configured, shrinking code amount to one-liners.

XStream can also be used as a default serialization mechanism for JAX-RS service. Example of plugging XStream in Jersey can be found here

How to show two figures using matplotlib?

Alternatively, I would suggest turning interactive on in the beginning and at the very last plot, turn it off. All will show up, but they will not disappear as your program will stay around until you close the figures.

import matplotlib.pyplot as plt
from matplotlib import interactive

plt.figure(1)
... code to make figure (1)

interactive(True)
plt.show()

plt.figure(2)
... code to make figure (2)

plt.show()

plt.figure(3)
... code to make figure (3)

interactive(False)
plt.show()

Expanding tuples into arguments

Note that you can also expand part of argument list:

myfun(1, *("foo", "bar"))

HTML Button Close Window

Use the code below. It works every time.

<button onclick="self.close()">Close</button>

It works every time in Chrome and also works on Firefox.

Save file/open file dialog box, using Swing & Netbeans GUI editor

I have created a sample UI which shows the save and open file dialog. Click on save button to open save dialog and click on open button to open file dialog.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class FileChooserEx {
    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                new FileChooserEx().createUI();
            }
        };

        EventQueue.invokeLater(r);
    }

    private void createUI() {
        JFrame frame = new JFrame();
        frame.setLayout(new BorderLayout());

        JButton saveBtn = new JButton("Save");
        JButton openBtn = new JButton("Open");

        saveBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser saveFile = new JFileChooser();
                saveFile.showSaveDialog(null);
            }
        });

        openBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser openFile = new JFileChooser();
                openFile.showOpenDialog(null);
            }
        });

        frame.add(new JLabel("File Chooser"), BorderLayout.NORTH);
        frame.add(saveBtn, BorderLayout.CENTER);
        frame.add(openBtn, BorderLayout.SOUTH);
        frame.setTitle("File Chooser");
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

How to update nested state properties in React

i saw following in a book:

this.setState(state => state.someProperty.falg = false);

but i'm not sure if it's right..

Redirect on select option in select box

    {{-- dynamic select/dropdown --}}
    <select class="form-control m-bot15" name="district_id" 
        onchange ="location = this.options[this.selectedIndex].value;"
        >
          <option value="">--Select--</option>
          <option value="?">All</option>

            @foreach($location as $district)
                <option  value="?district_id={{ $district->district_id }}" >
                  {{ $district->district }}
                </option> 
            @endforeach   

    </select>

How to read from a file or STDIN in Bash?

This one is easy to use on the terminal:

$ echo '1\n2\n3\n' | while read -r; do echo $REPLY; done
1
2
3

Compare if BigDecimal is greater than zero

It's as simple as:

if (value.compareTo(BigDecimal.ZERO) > 0)

The documentation for compareTo actually specifies that it will return -1, 0 or 1, but the more general Comparable<T>.compareTo method only guarantees less than zero, zero, or greater than zero for the appropriate three cases - so I typically just stick to that comparison.

How can I declare optional function parameters in JavaScript?

With ES6: This is now part of the language:

function myFunc(a, b = 0) {
   // function body
}

Please keep in mind that ES6 checks the values against undefined and not against truthy-ness (so only real undefined values get the default value - falsy values like null will not default).


With ES5:

function myFunc(a,b) {
  b = b || 0;

  // b will be set either to b or to 0.
}

This works as long as all values you explicitly pass in are truthy. Values that are not truthy as per MiniGod's comment: null, undefined, 0, false, ''

It's pretty common to see JavaScript libraries to do a bunch of checks on optional inputs before the function actually starts.

How to jump to a particular line in a huge text file?

linecache:

The linecache module allows one to get any line from a Python source file, while attempting to optimize internally, using a cache, the common case where many lines are read from a single file. This is used by the traceback module to retrieve source lines for inclusion in the formatted traceback...

TypeError: unhashable type: 'dict', when dict used as a key for another dict

What it seems like to me is that by calling the keys method you're returning to python a dictionary object when it's looking for a list or a tuple. So try taking all of the keys in the dictionary, putting them into a list and then using the for loop.

Compress images on client side before uploading

I just developed a javascript library called JIC to solve that problem. It allows you to compress jpg and png on the client side 100% with javascript and no external libraries required!

You can try the demo here : http://makeitsolutions.com/labs/jic and get the sources here : https://github.com/brunobar79/J-I-C

Generate unique random numbers between 1 and 100

I would do this:

function randomInt(min, max) {
    return Math.round(min + Math.random()*(max-min));
}
var index = {}, numbers = [];
for (var i=0; i<8; ++i) {
    var number;
    do {
        number = randomInt(1, 100);
    } while (index.hasOwnProperty("_"+number));
    index["_"+number] = true;
    numbers.push(number);
}
delete index;

XAMPP, Apache - Error: Apache shutdown unexpectedly

Try the following, none of the above solved it for me

Select "Run as administrator"

enter image description here

Then click on the big left box next to Apache

And Choose to uninstall Apache

enter image description here

I have no idea why this worked but it solved my problem directly!

How to extend available properties of User.Identity

Whenever you want to extend the properties of User.Identity with any additional properties like the question above, add these properties to the ApplicationUser class first like so:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }

    // Your Extended Properties
    public long? OrganizationId { get; set; }
}

Then what you need is to create an extension method like so (I create mine in an new Extensions folder):

namespace App.Extensions
{
    public static class IdentityExtensions
    {
        public static string GetOrganizationId(this IIdentity identity)
        {
            var claim = ((ClaimsIdentity)identity).FindFirst("OrganizationId");
            // Test for null to avoid issues during local testing
            return (claim != null) ? claim.Value : string.Empty;
        }
    }
}

When you create the Identity in the ApplicationUser class, just add the Claim -> OrganizationId like so:

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here => this.OrganizationId is a value stored in database against the user
        userIdentity.AddClaim(new Claim("OrganizationId", this.OrganizationId.ToString()));

        return userIdentity;
    }

Once you added the claim and have your extension method in place, to make it available as a property on your User.Identity, add a using statement on the page/file you want to access it:

in my case: using App.Extensions; within a Controller and @using. App.Extensions withing a .cshtml View file.

EDIT:

What you can also do to avoid adding a using statement in every View is to go to the Views folder, and locate the Web.config file in there. Now look for the <namespaces> tag and add your extension namespace there like so:

<add namespace="App.Extensions" />

Save your file and you're done. Now every View will know of your extensions.

You can access the Extension Method:

var orgId = User.Identity.GetOrganizationId();

Abstraction vs Encapsulation in Java

OO Abstraction occurs during class level design, with the objective of hiding the implementation complexity of how the the features offered by an API / design / system were implemented, in a sense simplifying the 'interface' to access the underlying implementation.

The process of abstraction can be repeated at increasingly 'higher' levels (layers) of classes, which enables large systems to be built without increasing the complexity of code and understanding at each layer.

For example, a Java developer can make use of the high level features of FileInputStream without concern for how it works (i.e. file handles, file system security checks, memory allocation and buffering will be managed internally, and are hidden from consumers). This allows the implementation of FileInputStream to be changed, and as long as the API (interface) to FileInputStream remains consistent, code built against previous versions will still work.

Similarly, when designing your own classes, you will want to hide internal implementation details from others as far as possible.

In the Booch definition1, OO Encapsulation is achieved through Information Hiding, and specifically around hiding internal data (fields / members representing the state) owned by a class instance, by enforcing access to the internal data in a controlled manner, and preventing direct, external change to these fields, as well as hiding any internal implementation methods of the class (e.g. by making them private).

For example, the fields of a class can be made private by default, and only if external access to these was required, would a get() and/or set() (or Property) be exposed from the class. (In modern day OO languages, fields can be marked as readonly / final / immutable which further restricts change, even within the class).

Example where NO information hiding has been applied (Bad Practice):

class Foo {
   // BAD - NOT Encapsulated - code external to the class can change this field directly
   // Class Foo has no control over the range of values which could be set.
   public int notEncapsulated;
}

Example where field encapsulation has been applied:

class Bar {
   // Improvement - access restricted only to this class
   private int encapsulatedPercentageField;

   // The state of Bar (and its fields) can now be changed in a controlled manner
   public void setEncapsulatedField(int percentageValue) {
      if (percentageValue >= 0 && percentageValue <= 100) {
          encapsulatedPercentageField = percentageValue;
      }
      // else throw ... out of range
   }
}

Example of immutable / constructor-only initialization of a field:

class Baz {
   private final int immutableField;

   public void Baz(int onlyValue) {
      // ... As above, can also check that onlyValue is valid
      immutableField = onlyValue;
   }
   // Further change of `immutableField` outside of the constructor is NOT permitted, even within the same class 
}

Re : Abstraction vs Abstract Class

Abstract classes are classes which promote reuse of commonality between classes, but which themselves cannot directly be instantiated with new() - abstract classes must be subclassed, and only concrete (non abstract) subclasses may be instantiated. Possibly one source of confusion between Abstraction and an abstract class was that in the early days of OO, inheritance was more heavily used to achieve code reuse (e.g. with associated abstract base classes). Nowadays, composition is generally favoured over inheritance, and there are more tools available to achieve abstraction, such as through Interfaces, events / delegates / functions, traits / mixins etc.

Re : Encapsulation vs Information Hiding

The meaning of encapsulation appears to have evolved over time, and in recent times, encapsulation can commonly also used in a more general sense when determining which methods, fields, properties, events etc to bundle into a class.

Quoting Wikipedia:

In the more concrete setting of an object-oriented programming language, the notion is used to mean either an information hiding mechanism, a bundling mechanism, or the combination of the two.

For example, in the statement

I've encapsulated the data access code into its own class

.. the interpretation of encapsulation is roughly equivalent to the Separation of Concerns or the Single Responsibility Principal (the "S" in SOLID), and could arguably be used as a synonym for refactoring.


[1] Once you've seen Booch's encapsulation cat picture you'll never be able to forget encapsulation - p46 of Object Oriented Analysis and Design with Applications, 2nd Ed

MongoDB - Update objects in a document's array (nested updating)

For question #1, let's break it into two parts. First, increment any document that has "items.item_name" equal to "my_item_two". For this you'll have to use the positional "$" operator. Something like:

 db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } , 
                {$inc : {"items.$.price" : 1} } , 
                false , 
                true);

Note that this will only increment the first matched subdocument in any array (so if you have another document in the array with "item_name" equal to "my_item_two", it won't get incremented). But this might be what you want.

The second part is trickier. We can push a new item to an array without a "my_item_two" as follows:

 db.bar.update( {user_id : 123456, "items.item_name" : {$ne : "my_item_two" }} , 
                {$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
                false , 
                true);

For your question #2, the answer is easier. To increment the total and the price of item_three in any document that contains "my_item_three," you can use the $inc operator on multiple fields at the same time. Something like:

db.bar.update( {"items.item_name" : {$ne : "my_item_three" }} ,
               {$inc : {total : 1 , "items.$.price" : 1}} ,
               false ,
               true);

How can I use the MS JDBC driver with MS SQL Server 2008 Express?

You have the wrong URL.

I don't know what you mean by "JDBC 2005". When I looked on the microsoft site, I found something called the Microsoft SQL Server JDBC Driver 2.0. You're going to want that one - it includes lots of fixes and some perf improvements. [edit: you're probably going to want the latest driver. As of March 2012, the latest JDBC driver from Microsoft is JDBC 4.0]

Check the release notes. For this driver, you want:

URL:  jdbc:sqlserver://server:port;DatabaseName=dbname
Class name: com.microsoft.sqlserver.jdbc.SQLServerDriver

It seems you have the class name correct, but the URL wrong.

Microsoft changed the class name and the URL after its initial release of a JDBC driver. The URL you are using goes with the original JDBC driver from Microsoft, the one MS calls the "SQL Server 2000 version". But that driver uses a different classname.

For all subsequent drivers, the URL changed to the form I have here.

This is in the release notes for the JDBC driver.

Xcode5 "No matching provisioning profiles found issue" (but good at xcode4)

Sometimes, especially after generating a new certificate or starting to use a new code signing identity, there seems to be no other way to fix this, other than doing some cleaning the .pbxproj file. This is probably a bug that will be fixed, so if you are reading this long after this post, maybe you should try some other solution.

There is an excellent post about this in the pixeldock blog: http://www.pixeldock.com/blog/code-sign-error-provisioning-profile-cant-be-found/

In short, mostly quoting from that article, you need to:

  1. Make sure you have fetched all your remote iTunes Connect certificates in xcode5 from Preferences, Accounts, (select your account), View Details, press refresh button. (Normally, I answer no when xcode asks if I want to create certficate signing requests, it's not necessary when you only want to download/refresh your certificates)
  2. Close Xcode
  3. Right click on your project’s .xcodeproj bundle to show it’s contents.
  4. Open the .pbxproj file in a text editor of your choice (make a backup copy first if you feel paranoid)
  5. Find all lines in that file that include the word PROVISIONING_PROFILE and delete them.
  6. Open Xcode
  7. Enter your target and select the provisioning profile that you want to use.
  8. Build your project

Good luck!

Tokenizing strings in C

Do it like this:

char s[256];
strcpy(s, "one two three");
char* token = strtok(s, " ");
while (token) {
    printf("token: %s\n", token);
    token = strtok(NULL, " ");
}

Note: strtok modifies the string its tokenising, so it cannot be a const char*.

ToList()-- does it create a new list?

A new list is created but the items in it are references to the orginal items (just like in the original list). Changes to the list itself are independent, but to the items will find the change in both lists.

How to iterate over array of objects in Handlebars?

This fiddle has both each and direct json. http://jsfiddle.net/streethawk707/a9ssja22/.

Below are the two ways of iterating over array. One is with direct json passing and another is naming the json array while passing to content holder.

Eg1: The below example is directly calling json key (data) inside small_data variable.

In html use the below code:

<div id="small-content-placeholder"></div>

The below can be placed in header or body of html:

<script id="small-template" type="text/x-handlebars-template">
    <table>
        <thead>
            <th>Username</th>
            <th>email</th>
        </thead>
        <tbody>
            {{#data}}
                <tr>
                    <td>{{username}}
                    </td>
                    <td>{{email}}</td>
                </tr>
            {{/data}}
        </tbody>
    </table>
</script>

The below one is on document ready:

var small_source   = $("#small-template").html();
var small_template = Handlebars.compile(small_source);

The below is the json:

var small_data = {
            data: [
                {username: "alan1", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
                {username: "alan2", firstName: "Alan", lastName: "Johnson", email: "[email protected]" }
            ]
        };

Finally attach the json to content holder:

$("#small-content-placeholder").html(small_template(small_data));

Eg2: Iteration using each.

Consider the below json.

var big_data = [
            {
                name: "users1",
                details: [
                    {username: "alan1", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
                    {username: "allison1", firstName: "Allison", lastName: "House", email: "[email protected]" },
                    {username: "ryan1", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
                  ]
            },
            {
                name: "users2",
                details: [
                    {username: "alan2", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
                    {username: "allison2", firstName: "Allison", lastName: "House", email: "[email protected]" },
                    {username: "ryan2", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
                  ]
            }
      ];

While passing the json to content holder just name it in this way:

$("#big-content-placeholder").html(big_template({big_data:big_data}));

And the template looks like :

<script id="big-template" type="text/x-handlebars-template">
    <table>
        <thead>
            <th>Username</th>
            <th>email</th>
        </thead>
        <tbody>
            {{#each big_data}}
                <tr>
                    <td>{{name}}
                            <ul>
                                {{#details}}
                                    <li>{{username}}</li>
                                    <li>{{email}}</li>
                                {{/details}}
                            </ul>
                    </td>
                    <td>{{email}}</td>
                </tr>
            {{/each}}
        </tbody>
    </table>
</script>

How do I enable php to work with postgresql?

You need to install the pgsql module for php. In debian/ubuntu is something like this:

sudo apt-get install php5-pgsql

Or if the package is installed, you need to enable de module in php.ini

extension=php_pgsql.dll (windows)
extension=php_pgsql.so (linux)

Greatings.