Programs & Examples On #Form submit

The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to form elements. Forms can be submitted either by clicking an explicit , , or

How do you handle multiple submit buttons in ASP.NET MVC Framework?

Give your submit buttons a name, and then inspect the submitted value in your controller method:

<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
<input type="submit" name="submitButton" value="Send" />
<input type="submit" name="submitButton" value="Cancel" />
<% Html.EndForm(); %>

posting to

public class MyController : Controller {
    public ActionResult MyAction(string submitButton) {
        switch(submitButton) {
            case "Send":
                // delegate sending to another controller action
                return(Send());
            case "Cancel":
                // call another action to perform the cancellation
                return(Cancel());
            default:
                // If they've submitted the form without a submitButton, 
                // just return the view again.
                return(View());
        }
    }

    private ActionResult Cancel() {
        // process the cancellation request here.
        return(View("Cancelled"));
    }

    private ActionResult Send() {
        // perform the actual send operation here.
        return(View("SendConfirmed"));
    }

}

EDIT:

To extend this approach to work with localized sites, isolate your messages somewhere else (e.g. compiling a resource file to a strongly-typed resource class)

Then modify the code so it works like:

<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
<input type="submit" name="submitButton" value="<%= Html.Encode(Resources.Messages.Send)%>" />
<input type="submit" name="submitButton" value="<%=Html.Encode(Resources.Messages.Cancel)%>" />
<% Html.EndForm(); %>

and your controller should look like this:

// Note that the localized resources aren't constants, so 
// we can't use a switch statement.

if (submitButton == Resources.Messages.Send) { 
    // delegate sending to another controller action
    return(Send());

} else if (submitButton == Resources.Messages.Cancel) {
     // call another action to perform the cancellation
     return(Cancel());
}

jQuery - add additional parameters on submit (NOT ajax)

This one did it for me:

var input = $("<input>")
               .attr("type", "hidden")
               .attr("name", "mydata").val("bla");
$('#form1').append(input);

is based on the Daff's answer, but added the NAME attribute to let it show in the form collection and changed VALUE to VAL Also checked the ID of the FORM (form1 in my case)

used the Firefox firebug to check whether the element was inserted.

Hidden elements do get posted back in the form collection, only read-only fields are discarded.

Michel

Submit form without reloading page

I guess this is what you need. Try this .

<form action="" method="get">
                <input name="search" type="text">
                <input type="button" value="Search" onclick="return updateTable();">
                </form>

and your javascript code is the same

function updateTable()
    {   
        var photoViewer = document.getElementById('photoViewer');
        var photo = document.getElementById('photo1').href;
        var numOfPics = 5;
        var columns = 3; 
        var rows = Math.ceil(numOfPics/columns);
        var content="";
        var count=0;

        content = "<table class='photoViewer' id='photoViewer'>";
            for (r = 0; r < rows; r++) {
                content +="<tr>";
                for (c = 0; c < columns; c++) {
                    count++;
                    if(count == numOfPics)break; // here is check if number of cells equal Number of Pictures to stop
                        content +="<td><a href='"+photo+"' id='photo1'><img class='photo' src='"+photo+"' alt='Photo'></a><p>City View</p></td>";
                }
                content +="</tr>";
            }
        content += "</table>";

        photoViewer.innerHTML = content; 
}

A button to start php script, how?

I know this question is 5 years old, but for anybody wondering how to do this without re-rendering the main page. This solution uses the dart editor/scripting language.

You could have an <object> tag that contains a data attribute. Make the <object> 1px by 1px and then use something like dart to dynamically change the <object>'s data attribute which re-renders the data in the 1px by 1px object.

HTML Script:

<object id="external_source" type="text/html" data="" width="1px" height="1px">
</object>

<button id="button1" type="button">Start Script</button>

<script async type="application/dart" src="dartScript.dart"></script>
<script async src="packages/browser/dart.js"></script>

someScript.php:

<?php
echo 'hello world';
?>

dartScript.dart:

import 'dart:html';

InputElement button1;
ObjectElement externalSource;

void main() {
    button1 = querySelector('#button1')
        ..onClick.listen(runExternalSource);

    externalSource = querySelector('#external_source');
}

void runExternalSource(Event e) {
    externalSource.setAttribute('data', 'someScript.php');
}

So long as you aren't posting any information and you are just looking to run a script, this should work just fine.

Just build the dart script using "pub Build(generate JS)" and then upload the package onto your server.

Jquery function BEFORE form submission

Just because I made this mistake every time when using the submit function.

This is the full code you need:

Add the id "yourid" to the HTML form tag.

<form id="yourid" action='XXX' name='form' method='POST' accept-charset='UTF-8' enctype='multipart/form-data'>

the jQuery code:

$('#yourid').submit(function() {
  // do something
});

Setting onSubmit in React.js

In your doSomething() function, pass in the event e and use e.preventDefault().

doSomething = function (e) {
    alert('it works!');
    e.preventDefault();
}

HTML form do some "action" when hit submit button

Ok, I'll take a stab at this. If you want to work with PHP, you will need to install and configure both PHP and a webserver on your machine. This article might get you started: PHP Manual: Installation on Windows systems

Once you have your environment setup, you can start working with webforms. Directly From the article: Processing form data with PHP:

For this example you will need to create two pages. On the first page we will create a simple HTML form to collect some data. Here is an example:

<html>   
<head>
 <title>Test Page</title>
</head>   
<body>   
    <h2>Data Collection</h2><p>
    <form action="process.php" method="post">  
        <table>
            <tr>
                <td>Name:</td>
                <td><input type="text" name="Name"/></td>
            </tr>   
            <tr>
                <td>Age:</td>
                <td><input type="text" name="Age"/></td>
            </tr>   
            <tr>
                <td colspan="2" align="center">
                <input type="submit"/>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

This page will send the Name and Age data to the page process.php. Now lets create process.php to use the data from the HTML form we made:

<?php   
    print "Your name is ". $Name;   
    print "<br />";   
    print "You are ". $Age . " years old";   
    print "<br />";   $old = 25 + $Age;
    print "In 25 years you will be " . $old . " years old";   
?>

As you may be aware, if you leave out the method="post" part of the form, the URL with show the data. For example if your name is Bill Jones and you are 35 years old, our process.php page will display as http://yoursite.com/process.php?Name=Bill+Jones&Age=35 If you want, you can manually change the URL in this way and the output will change accordingly.

Additional JavaScript Example

This single file example takes the html from your question and ties the onSubmit event of the form to a JavaScript function that pulls the values of the 2 textboxes and displays them in an alert box.

Note: document.getElementById("fname").value gets the object with the ID tag that equals fname and then pulls it's value - which in this case is the text in the First Name textbox.

 <html>
    <head>
     <script type="text/javascript">
     function ExampleJS(){
        var jFirst = document.getElementById("fname").value;
        var jLast = document.getElementById("lname").value;
        alert("Your name is: " + jFirst + " " + jLast);
     }
     </script>

    </head>
    <body>
        <FORM NAME="myform" onSubmit="JavaScript:ExampleJS()">

             First name: <input type="text" id="fname" name="firstname" /><br />
             Last name:  <input type="text" id="lname" name="lastname" /><br />
            <input name="Submit"  type="submit" value="Update" />
        </FORM>
    </body>
</html>

jquery disable form submit on enter

Complete Solution in JavaScript for all browsers

The code above and most of the solutions are perfect. However, I think the most liked one "short answer" which is incomplete.

So here's the entire answer. in JavaScript with native Support for IE 7 as well.

var form = document.getElementById("testForm");
form.addEventListener("submit",function(e){e.preventDefault(); return false;});

This solution will now prevent the user from submit using the enter Key and will not reload the page, or take you to the top of the page, if your form is somewhere below.

Serializing and submitting a form with jQuery and PHP

You can use this function

var datastring = $("#contactForm").serialize();
$.ajax({
    type: "POST",
    url: "your url.php",
    data: datastring,
    dataType: "json",
    success: function(data) {
        //var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
        // do what ever you want with the server response
    },
    error: function() {
        alert('error handling here');
    }
});

return type is json

EDIT: I use event.preventDefault to prevent the browser getting submitted in such scenarios.

Adding more data to the answer.

dataType: "jsonp" if it is a cross-domain call.

beforeSend: // this is a pre-request call back function

complete: // a function to be called after the request ends.so code that has to be executed regardless of success or error can go here

async: // by default, all requests are sent asynchronously

cache: // by default true. If set to false, it will force requested pages not to be cached by the browser.

Find the official page here

Prevent users from submitting a form by hitting Enter

Instead of preventing users from pressing Enter, which may seem unnatural, you can leave the form as is and add some extra client-side validation: When the survey is not finished the result is not sent to the server and the user gets a nice message telling what needs to be finished to complete the form. If you are using jQuery, try the Validation plugin:

http://docs.jquery.com/Plugins/Validation

This will require more work than catching the Enter button, but surely it will provide a richer user experience.

How to pass value from <option><select> to form action

instead of trying to catch both POST and GET responses - you can have everything you want in the POST.

Your code:

<form method="POST" action="index.php?action=contact_agent&agent_id=">
  <select>
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
</form>

can easily become:

<form method="POST" action="index.php">
  <input type="hidden" name="action" value="contact_agent">
  <select name="agent_id">
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
  <button type="submit">Submit POST Data</button>
</form>

then in index.php - these values will be populated

$_POST['action'] // "contact_agent"
$_POST['agent_id'] // 1, 2 or 3 based on selection in form... 

How to locate and insert a value in a text box (input) using Python Selenium?

Assuming your page is available under "http://example.com"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://example.com")

Select element by id:

inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')

Now you can simulate hitting ENTER:

inputElement.send_keys(Keys.ENTER)

or if it is a form you can submit:

inputElement.submit() 

How do I capture response of form.submit

You won't be able to do this easily with plain javascript. When you post a form, the form inputs are sent to the server and your page is refreshed - the data is handled on the server side. That is, the submit() function doesn't actually return anything, it just sends the form data to the server.

If you really wanted to get the response in Javascript (without the page refreshing), then you'll need to use AJAX, and when you start talking about using AJAX, you'll need to use a library. jQuery is by far the most popular, and my personal favourite. There's a great plugin for jQuery called Form which will do exactly what it sounds like you want.

Here's how you'd use jQuery and that plugin:

$('#myForm')
    .ajaxForm({
        url : 'myscript.php', // or whatever
        dataType : 'json',
        success : function (response) {
            alert("The server says: " + response);
        }
    })
;

How do I use an image as a submit button?

Why not:

<button type="submit">
<img src="mybutton.jpg" />
</button>

validation of input text field in html using javascript

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>Validation</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript">
            var tags = document.getElementsByTagName("input");
            var radiotags = document.getElementsByName("gender");
            var compareValidator = ['compare'];
            var formtag = document.getElementsByTagName("form");
            function validation(){
                for(var i=0;i<tags.length;i++){
                    var tagid = tags[i].id;
                    var tagval = tags[i].value;
                    var tagtit = tags[i].title;
                    var tagclass = tags[i].className;
                    //Validation for Textbox Start
                    if(tags[i].type == "text"){
                        if(tagval == "" || tagval == null){
                            var lbl = $(tags[i]).prev().text();
                            lbl = lbl.replace(/ : /g,'')
                            //alert("Please Enter "+lbl);
                            $(".span"+tagid).remove();
                            $("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Please Enter "+lbl+"</span>");
                            $("#"+tagid).focus();
                            //return false;
                        }
                        else if(tagval != "" || tagval != null){
                            $(".span"+tagid).remove();
                        }
                        //Validation for compare text in two text boxes Start
                        //put two tags with same class name and put class name in compareValidator.
                        for(var j=0;j<compareValidator.length;j++){
                            if((tagval != "") && (tagclass.indexOf(compareValidator[j]) != -1)){
                                if(($('.'+compareValidator[j]).first().val()) != ($('.'+compareValidator[j]).last().val())){
                                    $("."+compareValidator[j]+":last").after("<span style='color:red;' class='span"+tagid+"'>Invalid Text</span>");
                                    $("span").prev("span").remove();
                                    $("."+compareValidator[j]+":last").focus();
                                    //return false;
                                }
                            }
                        }
                        //Validation for compare text in two text boxes End
                        //Validation for Email Start
                        if((tagval != "") && (tagclass.indexOf('email') != -1)){
                        //enter class = email where you want to use email validator
                            var reg = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
                            if (reg.test(tagval)){
                                $(".span"+tagid).remove();
                                return true; 
                            }
                            else{
                                $(".span"+tagid).remove();
                                $("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Email is Invalid</span>");
                                $("#"+tagid).focus();
                                return false;
                            }
                        }
                        //Validation for Email End
                    }
                    //Validation for Textbox End
                    //Validation for Radio Start
                    else if(tags[i].type == "radio"){
                    //enter class = gender where you want to use gender validator
                        if((radiotags[0].checked == false) && (radiotags[1].checked == false)){
                            $(".span"+tagid).remove();
                            //$("#"+tagid").after("<span style='color:red;' class='span"+tagid+"'>Please Select Your Gender </span>");
                            $(".gender:last").next().after("<span style='color:red;' class='span"+tagid+"'> Please Select Your Gender</span>");
                            $("#"+tagid).focus();
                            i += 1;
                        }
                        else{
                            $(".span"+tagid).remove();
                        }
                    }
                    //Validation for Radio End              
                    else{

                    }
                }
                //return false;
            }
            function Validate(){
               if(!validation()){
                    return false;
                }
                return true;
            }
            function onloadevents(){
                tags[tags.length -1].onclick = function(){
                    //return Validate();
                }
                for(var j=0;j<formtag.length;j++){
                    formtag[j].onsubmit = function(){
                        return Validate();
                    }
                }
                for(var i=0;i<tags.length;i++){
                    var tagid = tags[i].id;
                    var tagval = tags[i].value;
                    var tagtit = tags[i].title;
                    var tagclass = tags[i].className;
                    if((tags[i].type == "text") && (tagclass.indexOf('numeric') != -1)){
                        //enter class = numeric where you want to use numeric validator
                        document.getElementById(tagid).onkeypress = function(){
                            numeric(event);
                        }
                    }
                }
            }
            function numeric(event){
                var KeyBoardCode = (event.which) ? event.which : event.keyCode; 
                if (KeyBoardCode > 31 && (KeyBoardCode < 48 || KeyBoardCode > 57)){
                    event.preventDefault();
                    $(".spannum").remove();
                    //$(".numeric").after("<span class='spannum'>Numeric Keys Please</span>");
                    //$(".numeric").focus();
                    return false;
                }
                    $(".spannum").remove();
                    return true;
            }
            if (document.addEventListener) {
              document.addEventListener("DOMContentLoaded", onloadevents, false);
            }
            //window.onload = onloadevents;
        </script>
    </head>
    <body>
        <form method="post">
            <label for="fname">Test 1 : </label><input type="text" title="Test 1" id="fname" class="form1"><br>
            <label for="fname1">Test 2 : </label><input type="text" title="Test 2" id="fname1" class="form1 compare"><br>
            <label for="fname2">Test 3 : </label><input type="text" title="Test 3" id="fname2" class="form1 compare"><br>
            <label for="gender">Gender : </label>
            <input type="radio" title="Male" id="fname3" class="gender" name="gender" value="Male"><label for="gender">Male</label>
            <input type="radio" title="Female" id="fname4" class="gender" name="gender" value="Female"><label for="gender">Female</label><br>
            <label for="fname5">Mobile : </label><input type="text" title="Mobile" id="fname5" class="numeric"><br>
            <label for="fname6">Email : </label><input type="text" title="Email" id="fname6" class="email"><br>
            <input type="submit" id="sub" value="Submit">
        </form>
    </body>
</html>

How to disable submit button once it has been clicked?

I don't think you need this.form.submit(). The disabling code should run, then it will pass on the click which will click the form.

Values of disabled inputs will not be submitted

select controls are still clickable even on readonly attrib

if you want to still disable the control but you want its value posted. You might consider creating a hidden field. with the same value as your control.

then create a jquery, on select change

$('#your_select_id').change(function () {
    $('#your_hidden_selectid').val($('#your_select_id').val());
});

Submit form with Enter key without submit button?

Jay Gilford's answer will work, but I think really the easiest way is to just slap a display: none; on a submit button in the form.

Disable form auto submit on button click

<button>'s are in fact submit buttons, they have no other main functionality. You will have to set the type to button.
But if you bind your event handler like below, you target all buttons and do not have to do it manually for each button!

$('form button').on("click",function(e){
    e.preventDefault();
});

Submitting HTML form using Jquery AJAX

Quick Description of AJAX

AJAX is simply Asyncronous JSON or XML (in most newer situations JSON). Because we are doing an ASYNC task we will likely be providing our users with a more enjoyable UI experience. In this specific case we are doing a FORM submission using AJAX.

Really quickly there are 4 general web actions GET, POST, PUT, and DELETE; these directly correspond with SELECT/Retreiving DATA, INSERTING DATA, UPDATING/UPSERTING DATA, and DELETING DATA. A default HTML/ASP.Net webform/PHP/Python or any other form action is to "submit" which is a POST action. Because of this the below will all describe doing a POST. Sometimes however with http you might want a different action and would likely want to utilitize .ajax.

My code specifically for you (described in code comments):

_x000D_
_x000D_
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault();

  /* get the action attribute from the <form action=""> element */
  var $form = $(this),
    url = $form.attr('action');

  /* Send the data using post with element id name and name2*/
  var posting = $.post(url, {
    name: $('#name').val(),
    name2: $('#name2').val()
  });

  /* Alerts the results */
  posting.done(function(data) {
    $('#result').text('success');
  });
  posting.fail(function() {
    $('#result').text('failed');
  });
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="formoid" action="studentFormInsert.php" title="" method="post">
  <div>
    <label class="title">First Name</label>
    <input type="text" id="name" name="name">
  </div>
  <div>
    <label class="title">Last Name</label>
    <input type="text" id="name2" name="name2">
  </div>
  <div>
    <input type="submit" id="submitButton" name="submitButton" value="Submit">
  </div>
</form>

<div id="result"></div>
_x000D_
_x000D_
_x000D_


Documentation

From jQuery website $.post documentation.

Example: Send form data using ajax requests

$.post("test.php", $("#testform").serialize());

Example: Post a form using ajax and put results in a div

<!DOCTYPE html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    </head>
    <body>
        <form action="/" id="searchForm">
            <input type="text" name="s" placeholder="Search..." />
            <input type="submit" value="Search" />
        </form>
        <!-- the result of the search will be rendered inside this div -->
        <div id="result"></div>
        <script>
            /* attach a submit handler to the form */
            $("#searchForm").submit(function(event) {

                /* stop form from submitting normally */
                event.preventDefault();

                /* get some values from elements on the page: */
                var $form = $(this),
                    term = $form.find('input[name="s"]').val(),
                    url = $form.attr('action');

                /* Send the data using post */
                var posting = $.post(url, {
                    s: term
                });

                /* Put the results in a div */
                posting.done(function(data) {
                    var content = $(data).find('#content');
                    $("#result").empty().append(content);
                });
            });
        </script>
    </body>
</html>

Important Note

Without using OAuth or at minimum HTTPS (TLS/SSL) please don't use this method for secure data (credit card numbers, SSN, anything that is PCI, HIPAA, or login related)

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

After inserting it to database, call unset() method to clear the data.

unset($_POST);

To prevent refresh data insertion, do a page redirection to same page or different page after record insert.

header('Location:'.$_SERVER['PHP_SELF']);

How to check if text fields are empty on form submit using jQuery?

A simple solution would be something like this

$( "form" ).on( "submit", function() { 

   var has_empty = false;

   $(this).find( 'input[type!="hidden"]' ).each(function () {

      if ( ! $(this).val() ) { has_empty = true; return false; }
   });

   if ( has_empty ) { return false; }
});

Note: The jQuery.on() method is only available in jQuery version 1.7+, but it is now the preferred method of attaching event handlers.

This code loops through all of the inputs in the form and prevents form submission by returning false if any of them have no value. Note that it doesn't display any kind of message to the user about why the form failed to submit (I would strongly recommend adding one).

Or, you could look at the jQuery validate plugin. It does this and a lot more.

NB: This type of technique should always be used in conjunction with server side validation.

Multiple submit buttons in an HTML form

This is what I have tried out:

  1. You need to make sure you give your buttons different names
  2. Write an if statement that will do the required action if either button is clicked.

 

<form>
    <input type="text" name="field1" /> <!-- Put your cursor in this field and press Enter -->

    <input type="submit" name="prev" value="Previous Page" /> <!-- This is the button that will submit -->
    <input type="submit" name="next" value="Next Page" /> <!-- But this is the button that I WANT to submit -->
</form>

In PHP,

if(isset($_POST['prev']))
{
    header("Location: previous.html");
    die();
}

if(isset($_POST['next']))
{
    header("Location: next.html");
    die();
}

How to compare strings in Bash

The following script reads from a file named "testonthis" line by line and then compares each line with a simple string, a string with special characters and a regular expression. If it doesn't match, then the script will print the line, otherwise not.

Space in Bash is so much important. So the following will work:

[ "$LINE" != "table_name" ] 

But the following won't:

["$LINE" != "table_name"] 

So please use as is:

cat testonthis | while read LINE
do
if [ "$LINE" != "table_name" ] && [ "$LINE" != "--------------------------------" ] && [[ "$LINE" =~ [^[:space:]] ]] && [[ "$LINE" != SQL* ]]; then
echo $LINE
fi
done

Hibernate JPA Sequence (non-Id)

I've been in a situation like you (JPA/Hibernate sequence for non @Id field) and I ended up creating a trigger in my db schema that add a unique sequence number on insert. I just never got it to work with JPA/Hibernate

The difference between the 'Local System' account and the 'Network Service' account?

Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.

First the actual accounts:

  • LocalService account (preferred)

    A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.

    • Name: NT AUTHORITY\LocalService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the LocalService user account
    • has minimal privileges on the local computer
    • presents anonymous credentials on the network
    • SID: S-1-5-19
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-19)

     

  • NetworkService account

    Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).

    • NT AUTHORITY\NetworkService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the NetworkService user account
    • has minimal privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers
    • SID: S-1-5-20
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-20)
    • If trying to schedule a task using it, enter NETWORK SERVICE into the Select User or Group dialog

     

  • LocalSystem account (dangerous, don't use!)

    Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

    • Name: .\LocalSystem (can also use LocalSystem or ComputerName\LocalSystem)
    • the account has no password (any password information you provide is ignored)
    • SID: S-1-5-18
    • does not have any profile of its own (HKCU represents the default user)
    • has extensive privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers

     

Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService can still access the internet.

The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).

It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.

In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).


In Windows Server 2003 you cannot run a scheduled task as

  • NT_AUTHORITY\LocalService (aka the Local Service account), or
  • NT AUTHORITY\NetworkService (aka the Network Service account).

That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.

A service running as NetworkService presents the machine credentials on the network. This means that if your computer was called mango, it would present as the machine account MANGO$:

enter image description here

Pass multiple arguments into std::thread

If you're getting this, you may have forgotten to put #include <thread> at the beginning of your file. OP's signature seems like it should work.

How to use WebRequest to POST some data and read response?

From MSDN

// Create a request using a URL that can receive a post. 
WebRequest request = WebRequest.Create ("http://contoso.com/PostAccepter.aspx ");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();

Take into account that the information must be sent in the format key1=value1&key2=value2

What is Hive: Return Code 2 from org.apache.hadoop.hive.ql.exec.MapRedTask

The top answer is right, that the error code doesn't give you much info. One of the common causes that we saw in our team for this error code was when the query was not optimized well. A known reason was when we do an inner join with the left side table magnitudes bigger than the table on right side. Swapping these tables would usually do the trick in such cases.

Google Maps API Multiple Markers with Infowindows

You could use a closure. Just modify your code like this:

google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){ 
    return function() {
        infowindow.setContent(content);
        infowindow.open(map,marker);
    };
})(marker,content,infowindow));  

Here is the DEMO

How to display a list inline using Twitter's Bootstrap

According to the Bootstrap documentation, you need to add the class 'inline' to your list; like this:

<ul class="inline">
    <li>Item one</li>
    <li>Item two</li>
    <li>Item three</li>
</ul>

However, this does not work as there seems to be some CSS missing in the Bootstrap CSS file referring to the class 'inline'. So additionally, add the following lines to your CSS file to make it work:

ul.inline > li, ol.inline > li {
    display: inline-block;
    padding-right: 5px;
    padding-left: 5px;
}

UIScrollView scroll to bottom programmatically

I also found another useful way of doing this in the case you are using a UITableview (which is a subclass of UIScrollView):

[(UITableView *)self.view scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

How to stop java process gracefully?

Similar Question Here

Finalizers in Java are bad. They add a lot of overhead to garbage collection. Avoid them whenever possible.

The shutdownHook will only get called when the VM is shutting down. I think it very well may do what you want.

What are .a and .so files?

.a files are usually libraries which get statically linked (or more accurately archives), and
.so are dynamically linked libraries.

To do a port you will need the source code that was compiled to make them, or equivalent files on your AIX machine.

Practical uses for AtomicInteger

There are two main uses of AtomicInteger:

  • As an atomic counter (incrementAndGet(), etc) that can be used by many threads concurrently

  • As a primitive that supports compare-and-swap instruction (compareAndSet()) to implement non-blocking algorithms.

    Here is an example of non-blocking random number generator from Brian Göetz's Java Concurrency In Practice:

    public class AtomicPseudoRandom extends PseudoRandom {
        private AtomicInteger seed;
        AtomicPseudoRandom(int seed) {
            this.seed = new AtomicInteger(seed);
        }
    
        public int nextInt(int n) {
            while (true) {
                int s = seed.get();
                int nextSeed = calculateNext(s);
                if (seed.compareAndSet(s, nextSeed)) {
                    int remainder = s % n;
                    return remainder > 0 ? remainder : remainder + n;
                }
            }
        }
        ...
    }
    

    As you can see, it basically works almost the same way as incrementAndGet(), but performs arbitrary calculation (calculateNext()) instead of increment (and processes the result before return).

How to convert string to char array in C++?

str.copy(cstr, str.length()+1); // since C++11
cstr[str.copy(cstr, str.length())] = '\0';  // before C++11
cstr[str.copy(cstr, sizeof(cstr)-1)] = '\0';  // before C++11 (safe)

It's a better practice to avoid C in C++, so std::string::copy should be the choice instead of strcpy.

Style child element when hover on parent

Yes, you can definitely do this. Just use something like

.parent:hover .child {
   /* ... */
}

According to this page it's supported by all major browsers.

Add two numbers and display result in textbox with Javascript

var first_number = parseInt(document.getElementById("Text1").value);
var second_number = parseInt(document.getElementById("Text2").value);

// This is because your method .getElementById has the letter 's': .getElement**s**ById

What regular expression will match valid international phone numbers?

Try this, it works for me.

^(00|\+)[1-9]{1}([0-9][\s]*){9,16}$

setting request headers in selenium

Webdriver doesn't contain an API to do it. See issue 141 from Selenium tracker for more info. The title of the issue says that it's about response headers but it was decided that Selenium won't contain API for request headers in scope of this issue. Several issues about adding API to set request headers have been marked as duplicates: first, second, third.

Here are a couple of possibilities that I can propose:

  1. Use another driver/library instead of selenium
  2. Write a browser-specific plugin (or find an existing one) that allows you to add header for request.
  3. Use browsermob-proxy or some other proxy.

I'd go with option 3 in most of cases. It's not hard.

Note that Ghostdriver has an API for it but it's not supported by other drivers.

Encapsulation vs Abstraction?

Answering my own question after 5 years as i feel it still need more details

Abstraction:

Technical Definition :- Abstraction is a concept to hide unnecessary details(complex or simple) and only show the essential features of the object. There is no implementaion here its just an concept

What it means practically:- When i say my company needs some medium/device so that employees can connect to customer . This is the purest form of abstaction(like interface in java) as that device/medium can be phone or internet or skype or in person or email etc. I am not going into nitty gritty of device/medium

Even when i say my company needs some medium/device so that employees can connect to customer through voice call. Then also i am talking abstract but at bit lower level as device/medium can be phone or skype or something else etc

Now when i say my company needs some phone so that employees can connect to customer through voice call. Then also i am talking abstract but at bit lower level as phone can be of any company like iphone or samsung or nokia etc

Encapsulation:- Its basically about hiding the state(information) of object with the help of modifiers like private,public,protected etc. we expose the state thru public methods only if require.

What it means practically:- Now when i say my company needs some iphone so that employees can connect to customer through voice call.Now i am talking about some concrete object(like iphone). Even though i am not going into nitty gritty of iphone here too but iphone has some state/concrecrete info/implementation associated with it where device/medium does not have. When i say concrete object, actually it means any object which has some(not complete like java abstract class) implementation/info associated with it.

So iphone actually used here encapsulation as strategy to hide its state/information and expose only the ones which it think should be exposed. So both abstraction and encapsulation hides some unnecessary details but abstraction at the concept level and encapsulation actually at implementation level

This is the gist based on answers in this post and below ones

  1. difference between abstraction and encapsulation?
  2. encapsulation vs abstraction real world example

python for increment inner loop

for a in range(1):

    for b in range(3):
        a = b*2
        print(a)

As per your question, you want to iterate the outer loop with help of the inner loop.

  1. In outer loop, we are iterating the inner loop 1 time.
  2. In the inner loop, we are iterating the 3 digits which are in the multiple of 2, starting from 0.

    Output:
    0
    2
    4
    

"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat

sending tag <img src="c:\images\mypic.jpg"> would cause user browser to access image from his filesystem. if you have to store images in folder located in c:\images i would suggest to create an servlet like images.jsp, that as a parameter takes name of a file, then sets servlet response content to an image/jpg and then loads bytes of image from server location and put it to a response.

But what you use to create your application? is it pure servlet? Spring? JSF?

Here you can find some info about, how to do it.

How to BULK INSERT a file into a *temporary* table where the filename is a variable?

It is possible to do everything you want. Aaron's answer was not quite complete.

His approach is correct, up to creating the temporary table in the inner query. Then, you need to insert the results into a table in the outer query.

The following code snippet grabs the first line of a file and inserts it into the table @Lines:

declare @fieldsep char(1) = ',';
declare @recordsep char(1) = char(10);

declare @Lines table (
    line varchar(8000)
);

declare @sql varchar(8000) = ' 
    create table #tmp (
        line varchar(8000)
    );

    bulk insert #tmp
        from '''+@filename+'''
        with (FirstRow = 1, FieldTerminator = '''+@fieldsep+''', RowTerminator = '''+@recordsep+''');

    select * from #tmp';

insert into @Lines
    exec(@sql);

select * from @lines

Equivalent of typedef in C#

The best alternative to typedef that I've found in C# is using. For example, I can control float precision via compiler flags with this code:

#if REAL_T_IS_DOUBLE
using real_t = System.Double;
#else
using real_t = System.Single;
#endif

Unfortunately, it requires that you place this at the top of every file where you use real_t. There is currently no way to declare a global namespace type in C#.

What's the purpose of SQL keyword "AS"?

If you design query using the Query editor in SQL Server 2012 for example you would get this:

  SELECT        e.EmployeeID, s.CompanyName, o.ShipName
FROM            Employees AS e INNER JOIN
                         Orders AS o ON e.EmployeeID = o.EmployeeID INNER JOIN
                         Shippers AS s ON o.ShipVia = s.ShipperID
WHERE        (s.CompanyName = 'Federal Shipping')

However removing the AS does not make any difference as in the following:

 SELECT        e.EmployeeID, s.CompanyName, o.ShipName
FROM            Employees e INNER JOIN
                         Orders o ON e.EmployeeID = o.EmployeeID INNER JOIN
                         Shippers s ON o.ShipVia = s.ShipperID
WHERE        (s.CompanyName = 'Federal Shipping')

In this case use of AS is superfluous but in many other places it is needed.

Calculate the center point of multiple latitude/longitude coordinate pairs

I did this task in javascript like below

function GetCenterFromDegrees(data){
    // var data = [{lat:22.281610498720003,lng:70.77577162868579},{lat:22.28065743343672,lng:70.77624369747241},{lat:22.280860953131217,lng:70.77672113067706},{lat:22.281863655593973,lng:70.7762061465462}];
    var num_coords = data.length;
    var X = 0.0;
    var Y = 0.0;
    var Z = 0.0;

    for(i=0; i<num_coords; i++){
        var lat = data[i].lat * Math.PI / 180;
        var lon = data[i].lng * Math.PI / 180;
        var a = Math.cos(lat) * Math.cos(lon);
        var b = Math.cos(lat) * Math.sin(lon);
        var c = Math.sin(lat);

        X += a;
        Y += b;
        Z += c;
    }

    X /= num_coords;
    Y /= num_coords;
    Z /= num_coords;

    lon = Math.atan2(Y, X);
    var hyp = Math.sqrt(X * X + Y * Y);
    lat = Math.atan2(Z, hyp);

    var finalLat = lat * 180 / Math.PI;
    var finalLng =  lon * 180 / Math.PI; 

    var finalArray = Array();
    finalArray.push(finalLat);
    finalArray.push(finalLng);
    return finalArray;
}

How to convert DateTime to a number with a precision greater than days in T-SQL?

If the purpose of this is to create a unique value from the date, here is what I would do

DECLARE @ts TIMESTAMP 
SET @ts = CAST(getdate() AS TIMESTAMP)
SELECT @ts

This gets the date and declares it as a simple timestamp

Windows could not start the SQL Server (MSSQLSERVER) on Local Computer... (error code 3417)

i had the same problem before

the error code 3417 : the SQL SERVER cannot start the master database, without master db SQL SERVER can't start MSSQLSERVER_3417

The master database records all the system-level information for a SQL Server system. This includes instance-wide metadata such as logon accounts, endpoints, linked servers, and system configuration settings. In SQL Server, system objects are no longer stored in the master database; instead, they are stored in the Resource database. Also, master is the database that records the existence of all other databases and the location of those database files and records the initialization information for SQL Server. Therefore, SQL Server cannot start if the master database is unavailable MSDN Master DB so you need to reconfigure all settings after restoring master db

solutions

  • replace master mdf and ldf files with the same files from another instance of sql Server as long as its the same version reference
  • Rebuild System Databases refrence
  • reinstall sql server

'names' attribute must be the same length as the vector

I want to explain the error with an example below:

> names(lenses)
[1] "X1..1..1..1..1..3"

names(lenses)=c("ID","Age","Sight","Astigmatism","Tear","Class") Error in names(lenses) = c("ID", "Age", "Sight", "Astigmatism", "Tear", : 'names' attribute [6] must be the same length as the vector [1]

The error happened because of mismatch in a number of attributes. I only have one but trying to add 6 names. In this case, the error happens. See below the correct one:::::>>>>

> names(lenses)=c("ID")
> names(lenses)

[1] "ID"

Now there was no error.

I hope this will help!

scp from Linux to Windows

This one worked for me.

scp /home/ubuntu/myfile username@IP_of_windows_machine:/C:/Users/Anshul/Desktop 

How to have a transparent ImageButton: Android

Set the background of the ImageButton as @null in XML

<ImageButton android:id="@+id/previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/media_skip_backward"
android:background="@null"></ImageButton>

Convert JSON to Map

If you need pure Java without any dependencies, you can use build in Nashorn API from Java 8. It is deprecated in Java 11.

This is working for me:

...
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
...

public class JsonUtils {

    public static Map parseJSON(String json) throws ScriptException {
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine engine = sem.getEngineByName("javascript");

        String script = "Java.asJSONCompatible(" + json + ")";

        Object result = engine.eval(script);

        return (Map) result;
    }
}

Sample usage

JSON:

{
    "data":[
        {"id":1,"username":"bruce"},
        {"id":2,"username":"clark"},
        {"id":3,"username":"diana"}
    ]
}

Code:

...
import jdk.nashorn.internal.runtime.JSONListAdapter;
...

public static List<String> getUsernamesFromJson(Map json) {
    List<String> result = new LinkedList<>();

    JSONListAdapter data = (JSONListAdapter) json.get("data");

    for(Object obj : data) {
        Map map = (Map) obj;
        result.add((String) map.get("username"));
    }

    return result;
}

Xcode 10: A valid provisioning profile for this executable was not found

Be aware that accepted answer prevents build to be uploaded to App Store Connect.

Is there a way to do repetitive tasks at intervals?

If you do not care about tick shifting (depending on how long did it took previously on each execution) and you do not want to use channels, it's possible to use native range function.

i.e.

package main

import "fmt"
import "time"

func main() {
    go heartBeat()
    time.Sleep(time.Second * 5)
}

func heartBeat() {
    for range time.Tick(time.Second * 1) {
        fmt.Println("Foo")
    }
}

Playground

scale fit mobile web content using viewport meta tag

ok, here is my final solution with 100% native javascript:

<meta id="viewport" name="viewport">

<script type="text/javascript">
//mobile viewport hack
(function(){

  function apply_viewport(){
    if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)   ) {

      var ww = window.screen.width;
      var mw = 800; // min width of site
      var ratio =  ww / mw; //calculate ratio
      var viewport_meta_tag = document.getElementById('viewport');
      if( ww < mw){ //smaller than minimum size
        viewport_meta_tag.setAttribute('content', 'initial-scale=' + ratio + ', maximum-scale=' + ratio + ', minimum-scale=' + ratio + ', user-scalable=no, width=' + mw);
      }
      else { //regular size
        viewport_meta_tag.setAttribute('content', 'initial-scale=1.0, maximum-scale=1, minimum-scale=1.0, user-scalable=yes, width=' + ww);
      }
    }
  }

  //ok, i need to update viewport scale if screen dimentions changed
  window.addEventListener('resize', function(){
    apply_viewport();
  });

  apply_viewport();

}());
</script>

how to query for a list<String> in jdbctemplate

To populate a List of String, you need not use custom row mapper. Implement it using queryForList.

List<String>data=jdbcTemplate.queryForList(query,String.class)

SecurityException during executing jnlp file (Missing required Permissions manifest attribute in main jar)

If you'd like to set this globally for all users of a machine, you can create the following directory and file structures:

mkdir %windir%\Sun\Java\Deployment

Create a file deployment.config with the content:

deployment.system.config=file:///c:/windows/Sun/Java/Deployment/deployment.properties
deployment.system.config.mandatory=TRUE

Create a file deployment.properties

deployment.user.security.exception.sites=C\:/WINDOWS/Sun/Java/Deployment/exception.sites

Create a file exception.sites

http://example1.com
http://example2.com/path/to/specific/directory/

Reference https://blogs.oracle.com/java-platform-group/entry/upcoming_exception_site_list_in

Batch files - number of command line arguments

You tend to handle number of arguments with this sort of logic:

IF "%1"=="" GOTO HAVE_0
IF "%2"=="" GOTO HAVE_1
IF "%3"=="" GOTO HAVE_2

etc.

If you have more than 9 arguments then you are screwed with this approach though. There are various hacks for creating counters which you can find here, but be warned these are not for the faint hearted.

How to create a MySQL hierarchical recursive query?

Just use BlueM/tree php class for make tree of a self-relation table in mysql.

Tree and Tree\Node are PHP classes for handling data that is structured hierarchically using parent ID references. A typical example is a table in a relational database where each record’s “parent” field references the primary key of another record. Of course, Tree cannot only use data originating from a database, but anything: you supply the data, and Tree uses it, regardless of where the data came from and how it was processed. read more

Here is an example of using BlueM/tree:

<?php 
require '/path/to/vendor/autoload.php'; $db = new PDO(...); // Set up your database connection 
$stm = $db->query('SELECT id, parent, title FROM tablename ORDER BY title'); 
$records = $stm->fetchAll(PDO::FETCH_ASSOC); 
$tree = new BlueM\Tree($records); 
...

Problems using Maven and SSL behind proxy

The fact is that your maven plugin try to connect to an https remote repository
(e.g https://repo.maven.apache.org/maven2/)

This is a new SSL connectivity for Maven Central was made available in august, 2014 !

So please, can you verify that your settings.xml has the correct configuration.

    <settings>
  <activeProfiles>
    <!--make the profile active all the time -->
    <activeProfile>securecentral</activeProfile>
  </activeProfiles>
  <profiles>
    <profile>
      <id>securecentral</id>
      <!--Override the repository (and pluginRepository) "central" from the
         Maven Super POM -->
      <repositories>
        <repository>
          <id>central</id>
          <url>http://repo1.maven.org/maven2</url>
          <releases>
            <enabled>true</enabled>
          </releases>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <id>central</id>
          <url>http://repo1.maven.org/maven2</url>
          <releases>
            <enabled>true</enabled>
          </releases>
        </pluginRepository>
      </pluginRepositories>
    </profile>
  </profiles>
</settings>

You can alternatively use the simple http maven repository like this

 <pluginRepositories>
    <pluginRepository>
      <id>central</id>
      <name>Maven Plugin Repository</name>
      <url>http://repo1.maven.org/maven2</url>
      <layout>default</layout>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <releases>
        <updatePolicy>never</updatePolicy>
      </releases>
    </pluginRepository>
  </pluginRepositories>

Please let me know if my solution works ;)

J.

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

(Updated - Thanks to the people who commented)

Modern Versions of PostgreSQL

Suppose you have a table named test1, to which you want to add an auto-incrementing, primary-key id (surrogate) column. The following command should be sufficient in recent versions of PostgreSQL:

   ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;

Older Versions of PostgreSQL

In old versions of PostgreSQL (prior to 8.x?) you had to do all the dirty work. The following sequence of commands should do the trick:

  ALTER TABLE test1 ADD COLUMN id INTEGER;
  CREATE SEQUENCE test_id_seq OWNED BY test1.id;
  ALTER TABLE test ALTER COLUMN id SET DEFAULT nextval('test_id_seq');
  UPDATE test1 SET id = nextval('test_id_seq');

Again, in recent versions of Postgres this is roughly equivalent to the single command above.

How do I update a formula with Homebrew?

You will first need to update the local formulas by doing

brew update

and then upgrade the package by doing

brew upgrade formula-name

An example would be if i wanted to upgrade mongodb, i would do something like this, assuming mongodb was already installed :

brew update && brew upgrade mongodb && brew cleanup mongodb

Setting focus on an HTML input box on page load

You could also use:

<body onload="focusOnInput()">
    <form name="passwordForm" action="verify.php" method="post">
        <input name="passwordInput" type="password" />
    </form>
</body>

And then in your JavaScript:

function focusOnInput() {
    document.forms["passwordForm"]["passwordInput"].focus();
}

Dropdownlist width in IE

This is something l have done taking bits from other people's stuff.

        $(document).ready(function () {
        if (document.all) {

            $('#<%=cboDisability.ClientID %>').mousedown(function () {
                $('#<%=cboDisability.ClientID %>').css({ 'width': 'auto' });
            });

            $('#<%=cboDisability.ClientID %>').blur(function () {
                $(this).css({ 'width': '208px' });
            });

            $('#<%=cboDisability.ClientID %>').change(function () {
                $('#<%=cboDisability.ClientID %>').css({ 'width': '208px' });
            });

            $('#<%=cboEthnicity.ClientID %>').mousedown(function () {
                $('#<%=cboEthnicity.ClientID %>').css({ 'width': 'auto' });
            });

            $('#<%=cboEthnicity.ClientID %>').blur(function () {
                $(this).css({ 'width': '208px' });
            });

            $('#<%=cboEthnicity.ClientID %>').change(function () {
                $('#<%=cboEthnicity.ClientID %>').css({ 'width': '208px' });
            });

        }
    });

where cboEthnicity and cboDisability are dropdowns with option text wider than the width of the select itself.

As you can see, l have specified document.all as this only works in IE. Also, l encased the dropdowns within div elements like this:

<div id="dvEthnicity" style="width: 208px; overflow: hidden; position: relative; float: right;"><asp:DropDownList CssClass="select" ID="cboEthnicity" runat="server" DataTextField="description" DataValueField="id" Width="200px"></asp:DropDownList></div>

This takes care of the other elements moving out of place when your dropdown expands. The only downside here is that the menulist visual disappears when you are selecting but returns as soon as you have selected.

Hope this helps someone.

INFO: No Spring WebApplicationInitializer types detected on classpath

My silly reason was: Build Automatically was disabled!

Ant if else condition?

The quirky syntax using conditions on the target (described by Mads) is the only supported way to perform conditional execution in core ANT.

ANT is not a programming language and when things get complicated I choose to embed a script within my build as follows:

<target name="prepare-copy" description="copy file based on condition">
    <groovy>
        if (properties["some.condition"] == "true") {
            ant.copy(file:"${properties["some.dir"]}/true", todir:".")
        }
    </groovy>
</target>

ANT supports several languages (See script task), my preference is Groovy because of it's terse syntax and because it plays so well with the build.

Apologies, David I am not a fan of ant-contrib.

Changing text color onclick

A rewrite of the answer by Sarfraz would be something like this, I think:

<script>

    document.getElementById('change').onclick = changeColor;   

    function changeColor() {
        document.body.style.color = "purple";
        return false;
    }   

</script>

You'd either have to put this script at the bottom of your page, right before the closing body tag, or put the handler assignment in a function called onload - or if you're using jQuery there's the very elegant $(document).ready(function() { ... } );

Note that when you assign event handlers this way, it takes the functionality out of your HTML. Also note you set it equal to the function name -- no (). If you did onclick = myFunc(); the function would actually execute when the handler is being set.

And I'm curious -- you knew enough to script changing the background color, but not the text color? strange:)

How to store arbitrary data for some HTML tags

You could use hidden input tags. I get no validation errors at w3.org with this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang='en' xml:lang='en' xmlns='http://www.w3.org/1999/xhtml'>
  <head>
    <meta content="text/html;charset=UTF-8" http-equiv="content-type" />
    <title>Hello</title>
  </head>
  <body>
    <div>
      <a class="article" href="link/for/non-js-users.html">
        <input style="display: none" name="articleid" type="hidden" value="5" />
      </a>
    </div>
  </body>
</html>

With jQuery you'd get the article ID with something like (not tested):

$('.article input[name=articleid]').val();

But I'd recommend HTML5 if that is an option.

Xcode 5.1 - No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=i386)

I found that it was necessary to enter the architecture names by hand:

enter image description here

I don't know why this was necessary, i.e. why these values were not inherited from Xcode itself. But as soon as I did this, the problem went away.

Implements vs extends: When to use? What's the difference?

We use SubClass extends SuperClass only when the subclass wants to use some functionality (methods or instance variables) that is already declared in the SuperClass, or if I want to slightly modify the functionality of the SuperClass (Method overriding). But say, I have an Animal class(SuperClass) and a Dog class (SubClass) and there are few methods that I have defined in the Animal class eg. doEat(); , doSleep(); ... and many more.

Now, my Dog class can simply extend the Animal class, if i want my dog to use any of the methods declared in the Animal class I can invoke those methods by simply creating a Dog object. So this way I can guarantee that I have a dog that can eat and sleep and do whatever else I want the dog to do.

Now, imagine, one day some Cat lover comes into our workspace and she tries to extend the Animal class(cats also eat and sleep). She makes a Cat object and starts invoking the methods.

But, say, someone tries to make an object of the Animal class. You can tell how a cat sleeps, you can tell how a dog eats, you can tell how an elephant drinks. But it does not make any sense in making an object of the Animal class. Because it is a template and we do not want any general way of eating.

So instead, I will prefer to make an abstract class that no one can instantiate but can be used as a template for other classes.

So to conclude, Interface is nothing but an abstract class(a pure abstract class) which contains no method implementations but only the definitions(the templates). So whoever implements the interface just knows that they have the templates of doEat(); and doSleep(); but they have to define their own doEat(); and doSleep(); methods according to their need.

You extend only when you want to reuse some part of the SuperClass(but keep in mind, you can always override the methods of your SuperClass according to your need) and you implement when you want the templates and you want to define them on your own(according to your need).

I will share with you a piece of code: You try it with different sets of inputs and look at the results.

class AnimalClass {

public void doEat() {
    
    System.out.println("Animal Eating...");
}

public void sleep() {
    
    System.out.println("Animal Sleeping...");
}

}

public class Dog extends AnimalClass implements AnimalInterface, Herbi{

public static void main(String[] args) {
    
    AnimalInterface a = new Dog();
    Dog obj = new Dog();
    obj.doEat();
    a.eating();
    
    obj.eating();
    obj.herbiEating();
}

public void doEat() {
    System.out.println("Dog eating...");
}

@Override
public void eating() {
    
    System.out.println("Eating through an interface...");
    // TODO Auto-generated method stub
    
}

@Override
public void herbiEating() {
    
    System.out.println("Herbi eating through an interface...");
    // TODO Auto-generated method stub
    
}


}

Defined Interfaces :

public interface AnimalInterface {

public void eating();

}


interface Herbi {

public void herbiEating();

}

What __init__ and self do in Python?

Here, the guy has written pretty well and simple: https://www.jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/

Read above link as a reference to this:

self? So what's with that self parameter to all of the Customer methods? What is it? Why, it's the instance, of course! Put another way, a method like withdraw defines the instructions for withdrawing money from some abstract customer's account. Calling jeff.withdraw(100.0) puts those instructions to use on the jeff instance.

So when we say def withdraw(self, amount):, we're saying, "here's how you withdraw money from a Customer object (which we'll call self) and a dollar figure (which we'll call amount). self is the instance of the Customer that withdraw is being called on. That's not me making analogies, either. jeff.withdraw(100.0) is just shorthand for Customer.withdraw(jeff, 100.0), which is perfectly valid (if not often seen) code.

init self may make sense for other methods, but what about init? When we call init, we're in the process of creating an object, so how can there already be a self? Python allows us to extend the self pattern to when objects are constructed as well, even though it doesn't exactly fit. Just imagine that jeff = Customer('Jeff Knupp', 1000.0) is the same as calling jeff = Customer(jeff, 'Jeff Knupp', 1000.0); the jeff that's passed in is also made the result.

This is why when we call init, we initialize objects by saying things like self.name = name. Remember, since self is the instance, this is equivalent to saying jeff.name = name, which is the same as jeff.name = 'Jeff Knupp. Similarly, self.balance = balance is the same as jeff.balance = 1000.0. After these two lines, we consider the Customer object "initialized" and ready for use.

Be careful what you __init__

After init has finished, the caller can rightly assume that the object is ready to use. That is, after jeff = Customer('Jeff Knupp', 1000.0), we can start making deposit and withdraw calls on jeff; jeff is a fully-initialized object.

2 "style" inline css img tags?

Do not use more than one style attribute. Just seperate styles in the style attribute with ; It is a block of inline CSS, so think of this as you would do CSS in a separate stylesheet.

So in this case its: style="height:100px;width:100px;"

You can use this for any CSS style, so if you wanted to change the colour of the text to white: style="height:100px;width:100px;color:#ffffff" and so on.

However, it is worth using inline CSS sparingly, as it can make code less manageable in future. Using an external stylesheet may be a better option for this. It depends really on your requirements. Inline CSS does make for quicker coding.

Random numbers with Math.random() in Java

Your formula generates numbers between min and min + max.

The one Google found generates numbers between min and max.

Google wins!

How to avoid mysql 'Deadlock found when trying to get lock; try restarting transaction'

In case someone is still struggling with this issue:

I faced similar issue where 2 requests were hitting the server at the same time. There was no situation like below:

T1:
    BEGIN TRANSACTION
    INSERT TABLE A
    INSERT TABLE B
    END TRANSACTION

T2:
    BEGIN TRANSACTION
    INSERT TABLE B
    INSERT TABLE A
    END TRANSACTION

So, I was puzzled why deadlock is happening.

Then I found that there was parent child relation ship between 2 tables because of foreign key. When I was inserting a record in child table, the transaction was acquiring a lock on parent table's row. Immediately after that I was trying to update the parent row which was triggering elevation of lock to EXCLUSIVE one. As 2nd concurrent transaction was already holding a SHARED lock, it was causing deadlock.

Refer to: https://blog.tekenlight.com/2019/02/21/database-deadlock-mysql.html

Programmatically center TextView text

Try adding the following code for applying the layout params to the TextView

LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(LinearLayout.CENTER_IN_PARENT);
textView.setLayoutParams(lp);

Chart won't update in Excel (2007)

I had a similar problem - Charts didn't appear to update. I tried just about everything on this thread with no luck. I finally realized that the charts that I was copying and pasting were linked to the source data, and that is why they were all showing the same results.

Be sure you are copying and pasting pictures before you go through all the other motions....

How do I execute a PowerShell script automatically using Windows task scheduler?

Create the scheduled task and set the action to:

Program/Script: Powershell.exe

Arguments: -File "C:\Users\MyUser\Documents\ThisisMyFile.ps1"

How to input a regex in string.replace?

don't have to use regular expression (for your sample string)

>>> s
'this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>. \nand there are many other lines in the txt files\nwith<[3> such tags </[3>\n'

>>> for w in s.split(">"):
...   if "<" in w:
...      print w.split("<")[0]
...
this is a paragraph with
 in between
 and then there are cases ... where the
 number ranges from 1-100
.
and there are many other lines in the txt files
with
 such tags

How to do an array of hashmaps?

The Java Language Specification, section 15.10, states:

An array creation expression creates an object that is a new array whose elements are of the type specified by the PrimitiveType or ClassOrInterfaceType. It is a compile-time error if the ClassOrInterfaceType does not denote a reifiable type (§4.7).

and

The rules above imply that the element type in an array creation expression cannot be a parameterized type, other than an unbounded wildcard.

The closest you can do is use an unchecked cast, either from the raw type, as you have done, or from an unbounded wildcard:

 HashMap<String, String>[] responseArray = (Map<String, String>[]) new HashMap<?,?>[games.size()];

Your version is clearly better :-)

When to use StringBuilder in Java

The + operator uses public String concat(String str) internally. This method copies the characters of the two strings, so it has memory requirements and runtime complexity proportional to the length of the two strings. StringBuilder works more efficent.

However I have read here that the concatination code using the + operater is changed to StringBuilder on post Java 4 compilers. So this might not be an issue at all. (Though I would really check this statement if I depend on it in my code!)

How to combine paths in Java?

To enhance JodaStephen's answer, Apache Commons IO has FilenameUtils which does this. Example (on Linux):

assert org.apache.commons.io.FilenameUtils.concat("/home/bob", "work\\stuff.log") == "/home/bob/work/stuff.log"

It's platform independent and will produce whatever separators your system needs.

Printing the correct number of decimal points with cout

I had this similar problem in a coding competition and this is how I handled it. Setting a precision of 2 to all double values

First adding the header to use setprecision

#include <iomanip>

Then adding the following code in our main

  double answer=5.9999;
  double answer2=5.0000;
  cout<<setprecision(2)<<fixed;
  cout <<answer << endl;
  cout <<answer2 << endl;

Output:

5.99
5.00

You need to use fixed for writing 5.00 thats why,your output won't come for 5.00.

A short reference video link I'm adding which is helpful

How to bind Close command to a button

All it takes is a bit of XAML...

<Window x:Class="WCSamples.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Window.CommandBindings>
        <CommandBinding Command="ApplicationCommands.Close"
                        Executed="CloseCommandHandler"/>
    </Window.CommandBindings>
    <StackPanel Name="MainStackPanel">
        <Button Command="ApplicationCommands.Close" 
                Content="Close Window" />
    </StackPanel>
</Window>

And a bit of C#...

private void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
    this.Close();
}

(adapted from this MSDN article)

Modifying location.hash without page scrolling

A snippet of your original code:

$("#buttons li a").click(function(){
    $("#buttons li a").removeClass('selected');
    $(this).addClass('selected');
    document.location.hash=$(this).attr("id")
});

Change this to:

$("#buttons li a").click(function(e){
    // need to pass in "e", which is the actual click event
    e.preventDefault();
    // the preventDefault() function ... prevents the default action.
    $("#buttons li a").removeClass('selected');
    $(this).addClass('selected');
    document.location.hash=$(this).attr("id")
});

Convert an object to an XML string

I realize this is a very old post, but after looking at L.B's response I thought about how I could improve upon the accepted answer and make it generic for my own application. Here's what I came up with:

public static string Serialize<T>(T dataToSerialize)
{
    try
    {
        var stringwriter = new System.IO.StringWriter();
        var serializer = new XmlSerializer(typeof(T));
        serializer.Serialize(stringwriter, dataToSerialize);
        return stringwriter.ToString();
    }
    catch
    {
        throw;
    }
}

public static T Deserialize<T>(string xmlText)
{
    try
    {
        var stringReader = new System.IO.StringReader(xmlText);
        var serializer = new XmlSerializer(typeof(T));
        return (T)serializer.Deserialize(stringReader);
    }
    catch
    {
        throw;
    }
}

These methods can now be placed in a static helper class, which means no code duplication to every class that needs to be serialized.

Trigger insert old values- values that was updated

ALTER trigger ETU on Employee FOR UPDATE AS insert into Log (EmployeeId, LogDate, OldName) select EmployeeId, getdate(), name from deleted go

Aren't promises just callbacks?

No, Not at all.

Callbacks are simply Functions In JavaScript which are to be called and then executed after the execution of another function has finished. So how it happens?

Actually, In JavaScript, functions are itself considered as objects and hence as all other objects, even functions can be sent as arguments to other functions. The most common and generic use case one can think of is setTimeout() function in JavaScript.

Promises are nothing but a much more improvised approach of handling and structuring asynchronous code in comparison to doing the same with callbacks.

The Promise receives two Callbacks in constructor function: resolve and reject. These callbacks inside promises provide us with fine-grained control over error handling and success cases. The resolve callback is used when the execution of promise performed successfully and the reject callback is used to handle the error cases.

Stash just a single file

I think stash -p is probably the choice you want, but just in case you run into other even more tricky things in the future, remember that:

Stash is really just a very simple alternative to the only slightly more complex branch sets. Stash is very useful for moving things around quickly, but you can accomplish more complex things with branches without that much more headache and work.

# git checkout -b tmpbranch
# git add the_file
# git commit -m "stashing the_file"
# git checkout master

go about and do what you want, and then later simply rebase and/or merge the tmpbranch. It really isn't that much extra work when you need to do more careful tracking than stash will allow.

How to set max and min value for Y axis

yAxes: [{
    display: true,
    ticks: {
        beginAtZero: true,
        steps:10,
        stepValue:5,
        max:100
    }
}]

Get latitude and longitude automatically using php, API

//add urlencode to your address
$address = urlencode("technopark, Trivandrun, kerala,India");
$region = "IND";
$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region");

echo $json;

$decoded = json_decode($json);

print_r($decoded);

How to create json by JavaScript for loop?

Your question is pretty hard to decode, but I'll try taking a stab at it.

You say:

I want to create a json object having two fields uniqueIDofSelect and optionValue in javascript.

And then you say:

I need output like

[{"selectID":2,"optionValue":"2"},
{"selectID":4,"optionvalue":"1"}]

Well, this example output doesn't have the field named uniqueIDofSelect, it only has optionValue.

Anyway, you are asking for array of objects...

Then in the comment to michaels answer you say:

It creates json object array. but I need only one json object.

So you don't want an array of objects?

What do you want then?

Please make up your mind.

How to resize an image with OpenCV2.0 and Python2.6

Here's a function to upscale or downscale an image by desired width or height while maintaining aspect ratio

# Resizes a image and maintains aspect ratio
def maintain_aspect_ratio_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
    # Grab the image size and initialize dimensions
    dim = None
    (h, w) = image.shape[:2]

    # Return original image if no need to resize
    if width is None and height is None:
        return image

    # We are resizing height if width is none
    if width is None:
        # Calculate the ratio of the height and construct the dimensions
        r = height / float(h)
        dim = (int(w * r), height)
    # We are resizing width if height is none
    else:
        # Calculate the ratio of the width and construct the dimensions
        r = width / float(w)
        dim = (width, int(h * r))

    # Return the resized image
    return cv2.resize(image, dim, interpolation=inter)

Usage

import cv2

image = cv2.imread('1.png')
cv2.imshow('width_100', maintain_aspect_ratio_resize(image, width=100))
cv2.imshow('width_300', maintain_aspect_ratio_resize(image, width=300))
cv2.waitKey()

Using this example image

enter image description here

Simply downscale to width=100 (left) or upscale to width=300 (right)

enter image description here enter image description here

How in node to split string by newline ('\n')?

The first one should work:

> "a\nb".split("\n");
[ 'a', 'b' ]
> var a = "test.js\nagain.js"
undefined
> a.split("\n");
[ 'test.js', 'again.js' ]

Setting format and value in input type="date"

function getDefaultDate(curDate){
var dt = new Date(curDate);`enter code here`
var date = dt.getDate();
var month = dt.getMonth();
var year = dt.getFullYear();
if (month.toString().length == 1) {
    month = "0" + month
}
if (date.toString().length == 1) {
    date = "0" + date
}
return year.toString() + "-" + month.toString() + "-" + date.toString();
}

In function pass your date string.

How to get start and end of day in Javascript?

FYI (merged version of Tvanfosson)

it will return actual date => date when you are calling function

export const today = {
  iso: {
    start: () => new Date(new Date().setHours(0, 0, 0, 0)).toISOString(),
    now: () => new Date().toISOString(),
    end: () => new Date(new Date().setHours(23, 59, 59, 999)).toISOString()
  },
  local: {
  start: () => new Date(new Date(new Date().setHours(0, 0, 0, 0)).toString().split('GMT')[0] + ' UTC').toISOString(),
  now: () => new Date(new Date().toString().split('GMT')[0] + ' UTC').toISOString(),
  end: () => new Date(new Date(new Date().setHours(23, 59, 59, 999)).toString().split('GMT')[0] + ' UTC').toISOString()
  }
}

// how to use

today.local.now(); //"2018-09-07T01:48:48.000Z" BAKU +04:00
today.iso.now(); // "2018-09-06T21:49:00.304Z" * 

* it is applicable for Instant time type on Java8 which convert your local time automatically depending on your region.(if you are planning write global app)

JavaScript/jQuery - "$ is not defined- $function()" error

I have solved it as follow.

import $ from 'jquery';

(function () {
    // ... code let script = $(..)
})();

How to read data from a file in Lua

Just a little addition if one wants to parse a space separated text file line by line.

read_file = function (path)
local file = io.open(path, "rb") 
if not file then return nil end

local lines = {}

for line in io.lines(path) do
    local words = {}
    for word in line:gmatch("%w+") do 
        table.insert(words, word) 
    end    
  table.insert(lines, words)
end

file:close()
return lines;
end

How to set zoom level in google map

What you're looking for are the scales for each zoom level. The numbers are in metres. Use these:

20 : 1128.497220

19 : 2256.994440

18 : 4513.988880

17 : 9027.977761

16 : 18055.955520

15 : 36111.911040

14 : 72223.822090

13 : 144447.644200

12 : 288895.288400

11 : 577790.576700

10 : 1155581.153000

9 : 2311162.307000

8 : 4622324.614000

7 : 9244649.227000

6 : 18489298.450000

5 : 36978596.910000

4 : 73957193.820000

3 : 147914387.600000

2 : 295828775.300000

1 : 591657550.500000

How can I require at least one checkbox be checked before a form can be submitted?

Here's an example using jquery and your html.

<html>
<head>
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
</head>
<body>

<script type="text/javascript">
$(document).ready(function () {
    $('#checkBtn').click(function() {
      checked = $("input[type=checkbox]:checked").length;

      if(!checked) {
        alert("You must check at least one checkbox.");
        return false;
      }

    });
});

</script>

<p>Box Set 1</p>
<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 1" required><label>Box 1</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 2" required><label>Box 2</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 3" required><label>Box 3</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 4" required><label>Box 4</label></li>
</ul>
<p>Box Set 2</p>
<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 5" required><label>Box 5</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 6" required><label>Box 6</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 7" required><label>Box 7</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 8" required><label>Box 8</label></li>
</ul>
<p>Box Set 3</p>
<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 9" required><label>Box 9</label></li>
</ul>
<p>Box Set 4</p>
<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 10" required><label>Box 10</label></li>
</ul>

<input type="button" value="Test Required" id="checkBtn">

</body>
</html>

Node.js EACCES error when listening on most ports

This means the port is used somewhere else. so, you need to try another one or stop using the old port.

Cannot import XSSF in Apache POI

1) imported all the JARS from POI folder 2) Imported all the JARS from ooxml folder which a subdirectory of POI folder 3) Imported all the JARS from lib folder which is a subdirectory of POI folder

String fileName = "C:/File raw.xlsx";
File file = new File(fileName);
FileInputStream fileInputStream;
Workbook workbook = null;
Sheet sheet;
Iterator<Row> rowIterator;
try {
        fileInputStream = new FileInputStream(file);
        String fileExtension = fileName.substring(fileName.indexOf("."));
        System.out.println(fileExtension);
        if(fileExtension.equals(".xls")){
        workbook  = new HSSFWorkbook(new POIFSFileSystem(fileInputStream));
        }
        else if(fileExtension.equals(".xlsx")){
        workbook  = new XSSFWorkbook(fileInputStream);
        }
        else {
        System.out.println("Wrong File Type");
        } 
        FormulaEvaluator evaluator workbook.getCreationHelper().createFormulaEvaluator();
        sheet = workbook.getSheetAt(0);
        rowIterator = sheet.iterator();
        while(rowIterator.hasNext()){
        Row row = rowIterator.next();
        Iterator<Cell> cellIterator = row.cellIterator();
        while (cellIterator.hasNext()){
        Cell cell = cellIterator.next();
        //Check the cell type after evaluating formulae
       //If it is formula cell, it will be evaluated otherwise no change will happen
        switch (evaluator.evaluateInCell(cell).getCellType()){
        case Cell.CELL_TYPE_NUMERIC:
        System.out.print(cell.getNumericCellValue() + " ");
        break;
        case Cell.CELL_TYPE_STRING:
        System.out.print(cell.getStringCellValue() + " ");
        break;
        case Cell.CELL_TYPE_FORMULA:
        Not again
        break;
        case Cell.CELL_TYPE_BLANK:
        break;
        }
}
 System.out.println("\n");
}
//System.out.println(sheet);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}?

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

It IS possible, using something like the below example that I put together with the help of work from (https://gist.github.com/bitinn/1700068a276fb29740a7) that didn't quite work on iOS 11:

Here's the modified code that works on iOS 11.03, please comment if it worked for you.

The key is adding some size to BODY so the browser can scroll, ex: height: calc(100% + 40px);

Full sample below & link to view in your browser (please test!)

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeHots iOS WebApp Minimal UI via Scroll Test</title>

    <style>
        html, body {
            height: 100%;
        }
        html {
            background-color: red;
        }
        body {
            background-color: blue;
            /* important to allow page to scroll */
            height: calc(100% + 40px);
            margin: 0;
        }
        div.header {
            width: 100%;
            height: 40px;
            background-color: green;
            overflow: hidden;
        }
        div.content {
            height: 100%;
            height: calc(100% - 40px);
            width: 100%;
            background-color: purple;
            overflow: hidden;
        }
        div.cover {
            position: absolute;
            top: 0;
            left: 0;
            z-index: 100;
            width: 100%;
            height: 100%;
            overflow: hidden;
            background-color: rgba(0, 0, 0, 0.5);
            color: #fff;
            display: none;
        }
        @media screen and (width: 320px) {
            html {
                height: calc(100% + 72px);
            }
            div.cover {
                display: block;
            }
        }
    </style>
    <script>
        var timeout;

        function interceptTouchMove(){
            // and disable the touchmove features 
            window.addEventListener("touchmove", (event)=>{
                if (!event.target.classList.contains('scrollable')) {
                    // no more scrolling
                    event.preventDefault();
                }
            }, false); 
        }

        function scrollDetect(event){
            // wait for the result to settle
            if( timeout ) clearTimeout(timeout);

            timeout = setTimeout(function() {
                console.log( 'scrolled up detected..' );
                if (window.scrollY > 35) {
                    console.log( ' .. moved up enough to go into minimal UI mode. cover off and locking touchmove!');
                    // hide the fixed scroll-cover
                    var cover = document.querySelector('div.cover');
                    cover.style.display = 'none';

                    // push back down to designated start-point. (as it sometimes overscrolls (this is jQuery implementation I used))
                    window.scrollY = 40;

                    // and disable the touchmove features 
                    interceptTouchMove();

                    // turn off scroll checker
                    window.removeEventListener('scroll', scrollDetect );                
                }
            }, 200);            
        }

        // listen to scroll to know when in minimal-ui mode.
        window.addEventListener('scroll', scrollDetect, false );
    </script>
</head>
<body>

    <div class="header">
        <p>header zone</p>
    </div>
    <div class="content">
        <p>content</p>
    </div>
    <div class="cover">
        <p>scroll to soft fullscreen</p>
    </div>

</body>

Full example link here: https://repos.codehot.tech/misc/ios-webapp-example2.html

Remove leading and trailing spaces?

Expand your one liner into multiple lines. Then it becomes easy:

f.write(re.split("Tech ID:|Name:|Account #:",line)[-1])

parts = re.split("Tech ID:|Name:|Account #:",line)
wanted_part = parts[-1]
wanted_part_stripped = wanted_part.strip()
f.write(wanted_part_stripped)

C++ inheritance - inaccessible base?

You have to do this:

class Bar : public Foo
{
    // ...
}

The default inheritance type of a class in C++ is private, so any public and protected members from the base class are limited to private. struct inheritance on the other hand is public by default.

What is Express.js?

Express is a module framework for Node that you can use for applications that are based on server/s that will "listen" for any input/connection requests from clients. When you use it in Node, it is just saying that you are requesting the use of the built-in Express file from your Node modules.

Express is the "backbone" of a lot of Web Apps that have their back end in NodeJS. From what I know, its primary asset being the providence of a routing system that handles the services of "interaction" between 2 hosts. There are plenty of alternatives for it, such as Sails.

Powershell equivalent of bash ampersand (&) for forking/running background processes

As long as the command is an executable or a file that has an associated executable, use Start-Process (available from v2):

Start-Process -NoNewWindow ping google.com

You can also add this as a function in your profile:

function bg() {Start-Process -NoNewWindow @args}

and then the invocation becomes:

bg ping google.com

In my opinion, Start-Job is an overkill for the simple use case of running a process in the background:

  1. Start-Job does not have access to your existing scope (because it runs in a separate session). You cannot do "Start-Job {notepad $myfile}"
  2. Start-Job does not preserve the current directory (because it runs in a separate session). You cannot do "Start-Job {notepad myfile.txt}" where myfile.txt is in the current directory.
  3. The output is not displayed automatically. You need to run Receive-Job with the ID of the job as parameter.

NOTE: Regarding your initial example, "bg sleep 30" would not work because sleep is a Powershell commandlet. Start-Process only works when you actually fork a process.

Uninstall Node.JS using Linux command line?

If you installed from source, you can issue the following command:

sudo make uninstall

If you followed the instructions on https://github.com/nodejs/node/wiki to install to your $HOME/local/node, then you have to type the following before the line above:

./configure --prefix=$HOME/local/node

Git: Cannot see new remote branch

Doing a git remote update will also update the list of branches available from the remote repository.

If you are using TortoiseGit, as of version 1.8.3.0, you can do "Git -> Sync" and there will be a "Remote Update" button in the lower left of the window that appears. Click that. Then you should be able to do "Git -> Switch/Checkout" and have the new remote branch appear in the dropdown of branches you can select.

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

You must declare the reportfile as variable for console.

Problem is all the Dokumentations you can find are not running so .. I was give 1 day of my live to find the right way ....

Example: for batch/console

cmd.exe /K set FFREPORT=file='C:\ffmpeg\proto\test.log':level=32 && C:\ffmpeg\bin\ffmpeg.exe -loglevel warning -report -i inputfile f outputfile

Exemple Javascript:

var reortlogfile = "cmd.exe /K set FFREPORT=file='C:\ffmpeg\proto\" + filename + ".log':level=32 && C:\ffmpeg\bin\ffmpeg.exe" .......;

You can change the dir and filename how ever you want.

Frank from Berlin

How to connect to a remote Git repository?

It's simple and follow the small Steps to proceed:

  • Install git on the remote server say some ec2 instance
  • Now create a project folder `$mkdir project.git
  • $cd project and execute $git init --bare

Let's say this project.git folder is present at your ip with address inside home_folder/workspace/project.git, forex- ec2 - /home/ubuntu/workspace/project.git

Now in your local machine, $cd into the project folder which you want to push to git execute the below commands:

  • git init .

  • git remote add origin [email protected]:/home/ubuntu/workspace/project.git

  • git add .
  • git commit -m "Initial commit"

Below is an optional command but found it has been suggested as i was working to setup the same thing

git config --global remote.origin.receivepack "git receive-pack"

  • git pull origin master
  • git push origin master

This should work fine and will push the local code to the remote git repository.

To check the remote fetch url, cd project_folder/.git and cat config, this will give the remote url being used for pull and push operations.

You can also use an alternative way, after creating the project.git folder on git, clone the project and copy the entire content into that folder. Commit the changes and it should be the same way. While cloning make sure you have access or the key being is the secret key for the remote server being used for deployment.

Difference between System.DateTime.Now and System.DateTime.Today

DateTime.Today represents the current system date with the time part set to 00:00:00

and

DateTime.Now represents the current system date and time

WPF: Setting the Width (and Height) as a Percentage Value

The way to stretch it to the same size as the parent container is to use the attribute:

 <Textbox HorizontalAlignment="Stretch" ...

That will make the Textbox element stretch horizontally and fill all the parent space horizontally (actually it depends on the parent panel you're using but should work for most cases).

Percentages can only be used with grid cell values so another option is to create a grid and put your textbox in one of the cells with the appropriate percentage.

How to serve an image using nodejs

It is too late but helps someone, I'm using node version v7.9.0 and express version 4.15.0

if your directory structure is something like this:

your-project
   uploads
   package.json
   server.js

server.js code:

var express         = require('express');
var app             = express();
app.use(express.static(__dirname + '/uploads'));// you can access image 
 //using this url: http://localhost:7000/abc.jpg
//make sure `abc.jpg` is present in `uploads` dir.

//Or you can change the directory for hiding real directory name:

`app.use('/images', express.static(__dirname+'/uploads/'));// you can access image using this url: http://localhost:7000/images/abc.jpg


app.listen(7000);

How to calculate md5 hash of a file using javascript

HTML5 + spark-md5 and Q

Assuming your'e using a modern browser (that supports HTML5 File API), here's how you calculate the MD5 Hash of a large file (it will calculate the hash on variable chunks)

_x000D_
_x000D_
function calculateMD5Hash(file, bufferSize) {
  var def = Q.defer();

  var fileReader = new FileReader();
  var fileSlicer = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
  var hashAlgorithm = new SparkMD5();
  var totalParts = Math.ceil(file.size / bufferSize);
  var currentPart = 0;
  var startTime = new Date().getTime();

  fileReader.onload = function(e) {
    currentPart += 1;

    def.notify({
      currentPart: currentPart,
      totalParts: totalParts
    });

    var buffer = e.target.result;
    hashAlgorithm.appendBinary(buffer);

    if (currentPart < totalParts) {
      processNextPart();
      return;
    }

    def.resolve({
      hashResult: hashAlgorithm.end(),
      duration: new Date().getTime() - startTime
    });
  };

  fileReader.onerror = function(e) {
    def.reject(e);
  };

  function processNextPart() {
    var start = currentPart * bufferSize;
    var end = Math.min(start + bufferSize, file.size);
    fileReader.readAsBinaryString(fileSlicer.call(file, start, end));
  }

  processNextPart();
  return def.promise;
}

function calculate() {

  var input = document.getElementById('file');
  if (!input.files.length) {
    return;
  }

  var file = input.files[0];
  var bufferSize = Math.pow(1024, 2) * 10; // 10MB

  calculateMD5Hash(file, bufferSize).then(
    function(result) {
      // Success
      console.log(result);
    },
    function(err) {
      // There was an error,
    },
    function(progress) {
      // We get notified of the progress as it is executed
      console.log(progress.currentPart, 'of', progress.totalParts, 'Total bytes:', progress.currentPart * bufferSize, 'of', progress.totalParts * bufferSize);
    });
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/q.js/1.4.1/q.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/spark-md5/2.0.2/spark-md5.min.js"></script>

<div>
  <input type="file" id="file"/>
  <input type="button" onclick="calculate();" value="Calculate" class="btn primary" />
</div>
_x000D_
_x000D_
_x000D_

How to do joins in LINQ on multiple fields in single join

As a full method chain that would look like this:

lista.SelectMany(a => listb.Where(xi => b.Id == a.Id && b.Total != a.Total),
                (a, b) => new ResultItem
                {
                    Id = a.Id,
                    ATotal = a.Total,
                    BTotal = b.Total
                }).ToList();

How can I get the DateTime for the start of the week?

Ugly but it at least gives the right dates back

With start of week set by system:

    public static DateTime FirstDateInWeek(this DateTime dt)
    {
        while (dt.DayOfWeek != System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
            dt = dt.AddDays(-1);
        return dt;
    }

Without:

    public static DateTime FirstDateInWeek(this DateTime dt, DayOfWeek weekStartDay)
    {
        while (dt.DayOfWeek != weekStartDay)
            dt = dt.AddDays(-1);
        return dt;
    }

How Do I Take a Screen Shot of a UIView?

The following snippet is used to take screenshot :

UIGraphicsBeginImageContext(self.muUIView.bounds.size);

[myUIView.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Use renderInContext: method instead of drawInContext: method

renderInContext: method renders the receiver and its sublayers into current context. This method renders directly from the layer tree.

Multidimensional Lists in C#

If for some reason you don't want to define a Person class and use List<Person> as advised, you can use a tuple, such as (C# 7):

var people = new List<(string Name, string Email)>
{
  ("Joe Bloggs", "[email protected]"),
  ("George Forman", "[email protected]"),
  ("Peter Pan", "[email protected]")
};

var georgeEmail = people[1].Email;

The Name and Email member names are optional, you can omit them and access them using Item1 and Item2 respectively.

There are defined tuples for up to 8 members.

For earlier versions of C#, you can still use a List<Tuple<string, string>> (or preferably ValueTuple using this NuGet package), but you won't benefit from customized member names.

How to extract IP Address in Spring MVC Controller get call?

I am late here, but this might help someone looking for the answer. Typically servletRequest.getRemoteAddr() works.

In many cases your application users might be accessing your web server via a proxy server or maybe your application is behind a load balancer.

So you should access the X-Forwarded-For http header in such a case to get the user's IP address.

e.g. String ipAddress = request.getHeader("X-FORWARDED-FOR");

Hope this helps.

Non-numeric Argument to Binary Operator Error in R

Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.

- is the 'binary operator' your error is referencing, and either CurrentDay or MA (or both) are non-numeric.

A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). + is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).

R only knows how to apply + (and other binary operators, such as -) to numeric arguments:

> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator

When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.

EDIT:

Your error lies in the use of [ instead of [[. Because Day is a list, subsetting with [ will return a list, not a numeric vector. [[, however, returns an object of the class of the item contained in the list:

> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator

> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3

Transaction, as you've defined it, returns a list of two vectors. Above, Day is a list contain one vector. Day2, however, is simply a vector.

VBA Excel - Insert row below with same format including borders and frames

When inserting a row, regardless of the CopyOrigin, Excel will only put vertical borders on the inserted cells if the borders above and below the insert position are the same.

I'm running into a similar (but rotated) situation with inserting columns, but Copy/Paste is too slow for my workbook (tens of thousands of rows, many columns, and complex formatting).

I've found three workarounds that don't require copying the formatting from the source row:

  1. Ensure the vertical borders are the same weight, color, and pattern above and below the insert position so Excel will replicate them in your new row. (This is the "It hurts when I do this," "Stop doing that!" answer.)

  2. Use conditional formatting to establish the border (with a Formula of "=TRUE"). The conditional formatting will be copied to the new row, so you still end up with a border.Caveats:

    • Conditional formatting borders are limited to the thin-weight lines.
    • Works best for sheets where borders are relatively consistent so you don't have to create a bunch of conditional formatting rules.
  3. Set the border on the inserted row in VBA after inserting the row. Setting a border on a range is much faster than copying and pasting all of the formatting just to get a border (assuming you know ahead of time what the border should be or can sample it from the row above without losing performance).

How remove border around image in css?

it's a good idea to use a reset CSS. add this at the top of your CSS file

img, a {border:none, outline: none;}

hope this helps

C++ - how to find the length of an integer

Not necessarily the most efficient, but one of the shortest and most readable using C++:

std::to_string(num).length()

How to get param from url in angular 4?

This should do the trick retrieving the params from the url:

constructor(private activatedRoute: ActivatedRoute) {
  this.activatedRoute.queryParams.subscribe(params => {
        let date = params['startdate'];
        console.log(date); // Print the parameter to the console. 
    });
}

The local variable date should now contain the startdate parameter from the URL. The modules Router and Params can be removed (if not used somewhere else in the class).

iptables v1.4.14: can't initialize iptables table `nat': Table does not exist (do you need to insmod?)

"IP conntrack functionality has some negative impact on venet performance (uo to about 10%), so they better be disabled by default." It's need for nat

https://serverfault.com/questions/593263/iptables-nat-does-not-exist

Git will not init/sync/update new submodules

Deleting submodule dir and its contents ("external/pyfacebook" folder) if it exists before git submodule add ... might fix problems.

Access images inside public folder in laravel

If you are inside a blade template

{{ URL::to('/') }}/images/stackoverflow.png

Spring Security with roles and permissions

This is the simplest way to do it. Allows for group authorities, as well as user authorities.

-- Postgres syntax

create table users (
  user_id serial primary key,
  enabled boolean not null default true,
  password text not null,
  username citext not null unique
);

create index on users (username);

create table groups (
  group_id serial primary key,
  name citext not null unique
);

create table authorities (
  authority_id serial primary key,
  authority citext not null unique
);

create table user_authorities (
  user_id int references users,
  authority_id int references authorities,
  primary key (user_id, authority_id)
);

create table group_users (
  group_id int references groups,
  user_id int referenecs users,
  primary key (group_id, user_id)
);

create table group_authorities (
  group_id int references groups,
  authority_id int references authorities,
  primary key (group_id, authority_id)
);

Then in META-INF/applicationContext-security.xml

<beans:bean class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" id="passwordEncoder" />

<authentication-manager>
    <authentication-provider>

        <jdbc-user-service
                data-source-ref="dataSource"

                users-by-username-query="select username, password, enabled from users where username=?"

                authorities-by-username-query="select users.username, authorities.authority from users join user_authorities using(user_id) join authorities using(authority_id) where users.username=?"

                group-authorities-by-username-query="select groups.id, groups.name, authorities.authority from users join group_users using(user_id) join groups using(group_id) join group_authorities using(group_id) join authorities using(authority_id) where users.username=?"

                />

          <password-encoder ref="passwordEncoder" />

    </authentication-provider>
</authentication-manager>

Uploading files to file server using webclient class

Just use

File.Copy(filepath, "\\\\192.168.1.28\\Files");

A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web.

The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it right, this can be done.

You may run into problems because you are using the IP address instead of the server name (windows trust settings prevent leaving the domain - by using IP you are hiding any domain details). If at all possible, use the server name!

If this is not on the same windows domain, and you are trying to use a different domain account, you will need to specify the username as "[domain_or_machine]\[username]"

If you need to specify explicit credentials, you'll need to look into coding an impersonation solution.

Define constant variables in C++ header

I like the namespace better for this kind of purpose.

Option 1 :

#ifndef MYLIB_CONSTANTS_H
#define MYLIB_CONSTANTS_H

//  File Name : LibConstants.hpp    Purpose : Global Constants for Lib Utils
namespace LibConstants
{
  const int CurlTimeOut = 0xFF;     // Just some example
  ...
}
#endif

// source.cpp
#include <LibConstants.hpp>
int value = LibConstants::CurlTimeOut;

Option 2 :

#ifndef MYLIB_CONSTANTS_H
#define MYLIB_CONSTANTS_H
//  File Name : LibConstants.hpp    Purpose : Global Constants for Lib Utils
namespace CurlConstants
{
  const int CurlTimeOut = 0xFF;     // Just some example
  ...
}

namespace MySQLConstants
{
  const int DBPoolSize = 0xFF;      // Just some example
  ...
}
#endif



// source.cpp
#include <LibConstants.hpp>
int value = CurlConstants::CurlTimeOut;
int val2  = MySQLConstants::DBPoolSize;

And I would never use a Class to hold this type of HardCoded Const variables.

How can I specify my .keystore file with Spring Boot and Tomcat?

For external keystores, prefix with "file:"

server.ssl.key-store=file:config/keystore 

Enter triggers button click

Where ever you use a <button> element by default it considers that button type="submit" so if you define the button type="button" then it won't consider that <button> as submit button.

JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object

You cannot install just the 64bit, you must first install the 32bit and then add the 64bit components.

From java.com:

Installing the JRE on a 64-bit system that allows a 32-bit JVM is a two-step process: first install the 32-bit JRE and then install the additional support for 64-bit operations. The file names are as follows:

Creating Roles in Asp.net Identity MVC 5

Here we go:

var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));


   if(!roleManager.RoleExists("ROLE NAME"))
   {
      var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
      role.Name = "ROLE NAME";
      roleManager.Create(role);

    }

For each row in an R dataframe

I was curious about the time performance of the non-vectorised options. For this purpose, I have used the function f defined by knguyen

f <- function(x, output) {
  wellName <- x[1]
  plateName <- x[2]
  wellID <- 1
  print(paste(wellID, x[3], x[4], sep=","))
  cat(paste(wellID, x[3], x[4], sep=","), file= output, append = T, fill = T)
}

and a dataframe like the one in his example:

n = 100; #number of rows for the data frame
d <- data.frame( name = LETTERS[ sample.int( 25, n, replace=T ) ],
                  plate = paste0( "P", 1:n ),
                  value1 = 1:n,
                  value2 = (1:n)*10 )

I included two vectorised functions (for sure quicker than the others) in order to compare the cat() approach with a write.table() one...

library("ggplot2")
library( "microbenchmark" )
library( foreach )
library( iterators )

tm <- microbenchmark(S1 =
                       apply(d, 1, f, output = 'outputfile1'),
                     S2 = 
                       for(i in 1:nrow(d)) {
                         row <- d[i,]
                         # do stuff with row
                         f(row, 'outputfile2')
                       },
                     S3 = 
                       foreach(d1=iter(d, by='row'), .combine=rbind) %dopar% f(d1,"outputfile3"),
                     S4= {
                       print( paste(wellID=rep(1,n), d[,3], d[,4], sep=",") )
                       cat( paste(wellID=rep(1,n), d[,3], d[,4], sep=","), file= 'outputfile4', sep='\n',append=T, fill = F)                           
                     },
                     S5 = {
                       print( (paste(wellID=rep(1,n), d[,3], d[,4], sep=",")) )
                       write.table(data.frame(rep(1,n), d[,3], d[,4]), file='outputfile5', row.names=F, col.names=F, sep=",", append=T )
                     },
                     times=100L)
autoplot(tm)

The resulting image shows that apply gives the best performance for a non-vectorised version, whereas write.table() seems to outperform cat(). ForEachRunningTime

Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH

This can be caused by a full disk (Ubuntu/Nginx).

My situation:

Multiplying across in a numpy array

You could also use matrix multiplication (aka dot product):

a = [[1,2,3],[4,5,6],[7,8,9]]
b = [0,1,2]
c = numpy.diag(b)

numpy.dot(c,a)

Which is more elegant is probably a matter of taste.

Sorting an IList in C#

In VS2008, when I click on the service reference and select "Configure Service Reference", there is an option to choose how the client de-serializes lists returned from the service.

Notably, I can choose between System.Array, System.Collections.ArrayList and System.Collections.Generic.List

How to redirect from one URL to another URL?

Since you tagged the question with javascript and html...

For a purely HTML solution, you can use a meta tag in the header to "refresh" the page, specifying a different URL:

<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.yourdomain.com/somepage.html">

If you can/want to use JavaScript, you can set the location.href of the window:

<script type="text/javascript">
    window.location.href = "http://www.yourdomain.com/somepage.html";
</script>

Can I set text box to readonly when using Html.TextBoxFor?

In case if you have to apply your custom class you can use

  @Html.TextBoxFor(m => m.Birthday,   new Dictionary<string, object>() { {"readonly", "true"}, {"class", "commonField"} } )

Where are

commonField is CSS class

and Birthday could be string field that you probably can use to keep jQuery Datapicker date :)

<script>
             $(function () {
                 $("#Birthday").datepicker({

                 });
             });
  </script>

That's a real life example.

How to get a Static property with Reflection

Or just look at this...

Type type = typeof(MyClass); // MyClass is static class with static properties
foreach (var p in type.GetProperties())
{
   var v = p.GetValue(null, null); // static classes cannot be instanced, so use null...
}

Changing the default icon in a Windows Forms application

Select your project properties from Project Tab Then Application->Resource->Icon And Manifest->change the default icon

This works in Visual studio 2019 finely Note:Only files with .ico format can be added as icon

Convert an NSURL to an NSString

If you're interested in the pure string:

[myUrl absoluteString];

If you're interested in the path represented by the URL (and to be used with NSFileManager methods for example):

[myUrl path];

How do I get a human-readable file size in bytes abbreviation using .NET?

This is not the most efficient way to do it, but it's easier to read if you are not familiar with log maths, and should be fast enough for most scenarios.

string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = new FileInfo(filename).Length;
int order = 0;
while (len >= 1024 && order < sizes.Length - 1) {
    order++;
    len = len/1024;
}

// Adjust the format string to your preferences. For example "{0:0.#}{1}" would
// show a single decimal place, and no space.
string result = String.Format("{0:0.##} {1}", len, sizes[order]);

Can the "IN" operator use LIKE-wildcards (%) in Oracle?

It seems that you can use regexp too

WHERE NOT REGEXP_LIKE(field, '^Done|^Finished')

I'm not sure how well this will perform though ... see here

How to fix "containing working copy admin area is missing" in SVN?

What I did to fix this was to delete the local copy of the folder under question and then do an svn update of the parent directly afterwards.

Fixed it right up.

PHP parse/syntax errors; and how to solve them

Unexpected T_IF
Unexpected T_ELSEIF
Unexpected T_ELSE
Unexpected T_ENDIF

Conditional control blocks if, elseif and else follow a simple structure. When you encounter a syntax error, it's most likely just invalid block nesting ? with missing { curly braces } - or one too many.

enter image description here

  1. Missing { or } due to incorrect indentation

    Mismatched code braces are common to less well-formatted code such as:

    if((!($opt["uniQartz5.8"]!=$this->check58)) or (empty($_POST['poree']))) {if
    ($true) {echo"halp";} elseif((!$z)or%b){excSmthng(False,5.8)}elseif (False){
    

    If your code looks like this, start afresh! Otherwise it's unfixable to you or anyone else. There's no point in showcasing this on the internet to inquire for help.

    You will only be able to fix it, if you can visually follow the nested structure and relation of if/else conditionals and their { code blocks }. Use your IDE to see if they're all paired.

    if (true) {
         if (false) {
                  …
         }
         elseif ($whatever) {
             if ($something2) {
                 …
             } 
             else {
                 …
             }
         }
         else {
             …
         }
         if (false) {    //   a second `if` tree
             …
         }
         else {
             …
         }
    }
    elseif (false) {
        …
    }
    

    Any double } } will not just close a branch, but a previous condition structure. Therefore stick with one coding style; don't mix and match in nested if/else trees.

    Apart from consistency here, it turns out helpful to avoid lengthy conditions too. Use temporary variables or functions to avoid unreadable if-expressions.

  2. IF cannot be used in expressions

    A surprisingly frequent newcomer mistake is trying to use an if statement in an expression, such as a print statement:

                       ?
    echo "<a href='" . if ($link == "example.org") { echo …
    

    Which is invalid of course.

    You can use a ternary conditional, but beware of readability impacts.

    echo "<a href='" . ($link ? "http://yes" : "http://no") . "</a>";
    

    Otherwise break such output constructs up: use multiple ifs and echos.
    Better yet, use temporary variables, and place your conditionals before:

    if ($link) { $href = "yes"; } else { $href = "no"; }
    echo "<a href='$href'>Link</a>";
    

    Defining functions or methods for such cases often makes sense too.

    Control blocks don't return "results"

    Now this is less common, but a few coders even try to treat if as if it could return a result:

    $var = if ($x == $y) { "true" };
    

    Which is structurally identical to using if within a string concatenation / expression.

    • But control structures (if / foreach / while) don't have a "result".
    • The literal string "true" would also just be a void statement.

    You'll have to use an assignment in the code block:

    if ($x == $y) { $var = "true"; }
    

    Alternatively, resort to a ?: ternary comparison.

    If in If

    You cannot nest an if within a condition either:

                        ?
    if ($x == true and (if $y != false)) { ... }
    

    Which is obviously redundant, because the and (or or) already allows chaining comparisons.

  3. Forgotten ; semicolons

    Once more: Each control block needs to be a statement. If the previous code piece isn't terminated by a semicolon, then that's a guaranteed syntax error:

                    ?
    $var = 1 + 2 + 3
    if (true) { … }
    

    Btw, the last line in a {…} code block needs a semicolon too.

  4. Semicolon too early

    Now it's probably wrong to blame a particular coding style, as this pitfall is too easy to overlook:

                ?
    if ($x == 5);
    {
        $y = 7;
    }
    else           ?
    {
        $x = -1;    
    }
    

    Which happens more often than you might imagine.

    • When you terminate the if () expression with ; it will execute a void statement. The ; becomes a an empty {} of its own!
    • The {…} block thus is detached from the if, and would always run.
    • So the else no longer had a relation to an open if construct, which is why this would lead to an Unexpected T_ELSE syntax error.

    Which also explains a likewise subtle variation of this syntax error:

    if ($x) { x_is_true(); }; else { something_else(); };
    

    Where the ; after the code block {…} terminates the whole if construct, severing the else branch syntactically.

  5. Not using code blocks

    It's syntactically allowed to omit curly braces {} for code blocks in if/elseif/else branches. Which sadly is a syntax style very common to unversed coders. (Under the false assumption this was quicker to type or read).

    However that's highly likely to trip up the syntax. Sooner or later additional statements will find their way into the if/else branches:

    if (true)
        $x = 5;
    elseif (false)
        $x = 6;
        $y = 7;     ?
    else
        $z = 0;
    

    But to actually use code blocks, you do have to write {} them as such!

    Even seasoned programmers avoid this braceless syntax, or at least understand it as an exceptional exception to the rule.

  6. Else / Elseif in wrong order

    One thing to remind yourself is the conditional order, of course.

    if ($a) { … }
    else { … }
    elseif ($b) { … }
    ?
    

    You can have as many elseifs as you want, but else has to go last. That's just how it is.

  7. Class declarations

    As mentioned above, you can't have control statements in a class declaration:

    class xyz {
        if (true) {
            function ($var) {}
        }
    

    You either forgot a function definition, or closed one } too early in such cases.

  8. Unexpected T_ELSEIF / T_ELSE

    When mixing PHP and HTML, the closing } for an if/elseif must be in the same PHP block <?php ?> as the next elseif/else. This will generate an error as the closing } for the if needs to be part of the elseif:

    <?php if ($x) { ?>
        html
    <?php } ?>
    <?php elseif ($y) { ?>
        html
    <?php } ?>
    

    The correct form <?php } elseif:

    <?php if ($x) { ?>
        html
    <?php } elseif ($y) { ?>
        html
    <?php } ?>
    

    This is more or less a variation of incorrect indentation - presumably often based on wrong coding intentions.
    You cannot mash other statements inbetween if and elseif/else structural tokens:

    if (true) {
    }
    echo "in between";    ?
    elseif (false) {
    }
    ?> text <?php      ?
    else {
    }
    

    Either can only occur in {…} code blocks, not in between control structure tokens.

    • This wouldn't make sense anyway. It's not like that there was some "undefined" state when PHP jumps between if and else branches.
    • You'll have to make up your mind where print statements belong to / or if they need to be repeated in both branches.

    Nor can you part an if/else between different control structures:

    foreach ($array as $i) {
        if ($i) { … }
    }
    else { … }
    

    There is no syntactic relation between the if and else. The foreach lexical scope ends at }, so there's no point for the if structure to continue.

  9. T_ENDIF

    If an unexpected T_ENDIF is complained about, you're using the alternative syntax style if: ? elseif: ? else: ? endif;. Which you should really think twice about.

    • A common pitfall is confusing the eerily similar : colon for a ; semicolon. (Covered in "Semicolon too early")

    • As indentation is harder to track in template files, the more when using the alternative syntax - it's plausible your endif; does not match any if:.

    • Using } endif; is a doubled if-terminator.

    While an "unexpected $end" is usually the price for a forgotten closing } curly brace.

  10. Assignment vs. comparison

    So, this is not a syntax error, but worth mentioning in this context:

           ?
    if ($x = true) { }
    else { do_false(); }
    

    That's not a ==/=== comparison, but an = assignment. This is rather subtle, and will easily lead some users to helplessly edit whole condition blocks. Watch out for unintended assignments first - whenver you experience a logic fault / misbeheviour.

How to center an image horizontally and align it to the bottom of the container?

This is tricky; the reason it's failing is that you can't position via margin or text-align while absolutely positioned.

If the image is alone in the div, then I recommend something like this:

.image_block {
    width: 175px;
    height: 175px;
    line-height: 175px;
    text-align: center;
    vertical-align: bottom;
}

You may need to stick the vertical-align call on the image instead; not really sure without testing it. Using vertical-align and line-height is going to treat you a lot better, though, than trying to mess around with absolute positioning.

scale Image in an UIButton to AspectFit?

1 - clear Button default text (important)

2 - set alignment like image

3 - set content mode like image

enter image description here

Restore LogCat window within Android Studio

In my case, Logcat is showing in Android Project but not in Flutter Project.

In Flutter project, click on “Event Log” tab

it will show

23/03/20
6:52  Frameworks Detected
Android framework is detected.

click “Configure”, and it will show logcat

How to convert string values from a dictionary, into int/float datatypes?

  newlist=[]                       #make an empty list
  for i in list:                   # loop to hv a dict in list  
     s={}                          # make an empty dict to store new dict data 
     for k in i.keys():            # to get keys in the dict of the list 
         s[k]=int(i[k])        # change the values from string to int by int func
     newlist.append(s)             # to add the new dict with integer to the list

How do I convert uint to int in C#?

Assuming you want to simply lift the 32bits from one type and dump them as-is into the other type:

uint asUint = unchecked((uint)myInt);
int asInt = unchecked((int)myUint);

The destination type will blindly pick the 32 bits and reinterpret them.

Conversely if you're more interested in keeping the decimal/numerical values within the range of the destination type itself:

uint asUint = checked((uint)myInt);
int asInt = checked((int)myUint);

In this case, you'll get overflow exceptions if:

  • casting a negative int (eg: -1) to an uint
  • casting a positive uint between 2,147,483,648 and 4,294,967,295 to an int

In our case, we wanted the unchecked solution to preserve the 32bits as-is, so here are some examples:

Examples

int => uint

int....: 0000000000 (00-00-00-00)
asUint.: 0000000000 (00-00-00-00)
------------------------------
int....: 0000000001 (01-00-00-00)
asUint.: 0000000001 (01-00-00-00)
------------------------------
int....: -0000000001 (FF-FF-FF-FF)
asUint.: 4294967295 (FF-FF-FF-FF)
------------------------------
int....: 2147483647 (FF-FF-FF-7F)
asUint.: 2147483647 (FF-FF-FF-7F)
------------------------------
int....: -2147483648 (00-00-00-80)
asUint.: 2147483648 (00-00-00-80)

uint => int

uint...: 0000000000 (00-00-00-00)
asInt..: 0000000000 (00-00-00-00)
------------------------------
uint...: 0000000001 (01-00-00-00)
asInt..: 0000000001 (01-00-00-00)
------------------------------
uint...: 2147483647 (FF-FF-FF-7F)
asInt..: 2147483647 (FF-FF-FF-7F)
------------------------------
uint...: 4294967295 (FF-FF-FF-FF)
asInt..: -0000000001 (FF-FF-FF-FF)
------------------------------

Code

int[] testInts = { 0, 1, -1, int.MaxValue, int.MinValue };
uint[] testUints = { uint.MinValue, 1, uint.MaxValue / 2, uint.MaxValue };

foreach (var Int in testInts)
{
    uint asUint = unchecked((uint)Int);
    Console.WriteLine("int....: {0:D10} ({1})", Int, BitConverter.ToString(BitConverter.GetBytes(Int)));
    Console.WriteLine("asUint.: {0:D10} ({1})", asUint, BitConverter.ToString(BitConverter.GetBytes(asUint)));
    Console.WriteLine(new string('-',30));
}
Console.WriteLine(new string('=', 30));
foreach (var Uint in testUints)
{
    int asInt = unchecked((int)Uint);
    Console.WriteLine("uint...: {0:D10} ({1})", Uint, BitConverter.ToString(BitConverter.GetBytes(Uint)));
    Console.WriteLine("asInt..: {0:D10} ({1})", asInt, BitConverter.ToString(BitConverter.GetBytes(asInt)));
    Console.WriteLine(new string('-', 30));
}  

How to get Linux console window width in Python

use

import console
(width, height) = console.getTerminalSize()

print "Your terminal's width is: %d" % width

EDIT: oh, I'm sorry. That's not a python standard lib one, here's the source of console.py (I don't know where it's from).

The module seems to work like that: It checks if termcap is available, when yes. It uses that; if no it checks whether the terminal supports a special ioctl call and that does not work, too, it checks for the environment variables some shells export for that. This will probably work on UNIX only.

def getTerminalSize():
    import os
    env = os.environ
    def ioctl_GWINSZ(fd):
        try:
            import fcntl, termios, struct, os
            cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
        '1234'))
        except:
            return
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        cr = (env.get('LINES', 25), env.get('COLUMNS', 80))

        ### Use get(key[, default]) instead of a try/catch
        #try:
        #    cr = (env['LINES'], env['COLUMNS'])
        #except:
        #    cr = (25, 80)
    return int(cr[1]), int(cr[0])

How to verify static void method has been called with power mockito

If you are mocking the behavior (with something like doNothing()) there should really be no need to call to verify*(). That said, here's my stab at re-writing your test method:

@PrepareForTest({InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest { //Note the renaming of the test class.
   public void testProcessOrder() {
        //Variables
        InternalService is = new InternalService();
        Order order = mock(Order.class);

        //Mock Behavior
        when(order.isSuccessful()).thenReturn(true);
        mockStatic(Internalutils.class);
        doNothing().when(InternalUtils.class); //This is the preferred way
                                               //to mock static void methods.
        InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());

        //Execute
        is.processOrder(order);            

        //Verify
        verifyStatic(InternalUtils.class); //Similar to how you mock static methods
                                           //this is how you verify them.
        InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
   }
}

I grouped into four sections to better highlight what is going on:

1. Variables

I choose to declare any instance variables / method arguments / mock collaborators here. If it is something used in multiple tests, consider making it an instance variable of the test class.

2. Mock Behavior

This is where you define the behavior of all of your mocks. You're setting up return values and expectations here, prior to executing the code under test. Generally speaking, if you set the mock behavior here you wouldn't need to verify the behavior later.

3. Execute

Nothing fancy here; this just kicks off the code being tested. I like to give it its own section to call attention to it.

4. Verify

This is when you call any method starting with verify or assert. After the test is over, you check that the things you wanted to have happen actually did happen. That is the biggest mistake I see with your test method; you attempted to verify the method call before it was ever given a chance to run. Second to that is you never specified which static method you wanted to verify.

Additional Notes

This is mostly personal preference on my part. There is a certain order you need to do things in but within each grouping there is a little wiggle room. This helps me quickly separate out what is happening where.

I also highly recommend going through the examples at the following sites as they are very robust and can help with the majority of the cases you'll need:

There has been an error processing your request, Error log record number

A common solution is to upgrade magento setup by running this command

php bin/magento setup:upgrade && php bin/magento setup:di:compile

Otherwise just check var/report/{error number}

Calculate the number of business days between two dates?

This is a generic solution.

startdayvalue is day number of start date.

weekendday_1 is day numner of week end.

day number - MON - 1, TUE - 2, ... SAT - 6, SUN -7.

difference is difference between two dates..

Example : Start Date : 4 April, 2013, End Date : 14 April, 2013

Difference : 10, startdayvalue : 4, weekendday_1 : 7 (if SUNDAY is a weekend for you.)

This will give you number of holidays.

No of business day = (Difference + 1) - holiday1

    if (startdayvalue > weekendday_1)
    {

        if (difference > ((7 - startdayvalue) + weekendday_1))
        {
            holiday1 = (difference - ((7 - startdayvalue) + weekendday_1)) / 7;
            holiday1 = holiday1 + 1;
        }
        else
        {
            holiday1 = 0;
        }
    }
    else if (startdayvalue < weekendday_1)
    {

        if (difference > (weekendday_1 - startdayvalue))
        {
            holiday1 = (difference - (weekendday_1 - startdayvalue)) / 7;
            holiday1 = holiday1 + 1;
        }
        else if (difference == (weekendday_1 - startdayvalue))
        {
            holiday1 = 1;
        }
        else
        {
            holiday1 = 0;
        }
    }
    else
    {
        holiday1 = difference / 7;
        holiday1 = holiday1 + 1;
    }

How to get current html page title with javascript

Like this :

jQuery(document).ready(function () {
    var title = jQuery(this).attr('title');
});

works for IE, Firefox and Chrome.

How to convert a Title to a URL slug in jQuery?

function slugify(text){
  return text.toString().toLowerCase()
    .replace(/\s+/g, '-')           // Replace spaces with -
    .replace(/[^\u0100-\uFFFF\w\-]/g,'-') // Remove all non-word chars ( fix for UTF-8 chars )
    .replace(/\-\-+/g, '-')         // Replace multiple - with single -
    .replace(/^-+/, '')             // Trim - from start of text
    .replace(/-+$/, '');            // Trim - from end of text
}

*based on https://gist.github.com/mathewbyrne/1280286

now you can transform this string:

Barack_Obama       ?????_????? ~!@#$%^&*()+/-+?><:";'{}[]\|`

into:

barack_obama-?????_?????

applying to your code:

$("#Restaurant_Name").keyup(function(){
    var Text = $(this).val();
    Text = slugify(Text);
    $("#Restaurant_Slug").val(Text);
});

Android customized button; changing text color

ok very simple first go to 1. res-valuse and open colors.xml 2.copy 1 of the defined text their for example #FF4081 and change name for instance i changed to white and change its value for instance i changed to #FFFFFF for white value like this

<color name="White">#FFFFFF</color>

then inside your button add this line

 b3.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.White));

ok b3 is the name of my button so changed of the name of ur button all others will be same if u use white color if you change different color then change white to the name of your color but first you have define that color in colors.xml like i explained in pont 2

UTF-8 problems while reading CSV file with fgetcsv

Encountered similar problem: parsing CSV file with special characters like é, è, ö etc ...

The following worked fine for me:

To represent the characters correctly on the html page, the header was needed :

header('Content-Type: text/html; charset=UTF-8');

In order to parse every character correctly, I used:

utf8_encode(fgets($file));

Dont forget to use in all following string operations the 'Multibyte String Functions', like:

mb_strtolower($value, 'UTF-8');

How does the stack work in assembly language?

The stack is just a way that programs and functions use memory.

The stack always confused me, so I made an illustration:

The stack is like stalactites

(svg version here)

  • A push "attaches a new stalactite to the ceiling".
  • A pop "pops off a stalactite".

Hope it's more helpful than confusing.

Feel free to use the SVG image (CC0 licensed).

Open File in Another Directory (Python)

If you know the full path to the file you can just do something similar to this. However if you question directly relates to relative paths, that I am unfamiliar with and would have to research and test.

path = 'C:\\Users\\Username\\Path\\To\\File'

with open(path, 'w') as f:
    f.write(data)

Edit:

Here is a way to do it relatively instead of absolute. Not sure if this works on windows, you will have to test it.

import os

cur_path = os.path.dirname(__file__)

new_path = os.path.relpath('..\\subfldr1\\testfile.txt', cur_path)
with open(new_path, 'w') as f:
    f.write(data)

Edit 2: One quick note about __file__, this will not work in the interactive interpreter due it being ran interactively and not from an actual file.

How can I use optional parameters in a T-SQL stored procedure?

You can do in the following case,

CREATE PROCEDURE spDoSearch
   @FirstName varchar(25) = null,
   @LastName varchar(25) = null,
   @Title varchar(25) = null
AS
  BEGIN
      SELECT ID, FirstName, LastName, Title
      FROM tblUsers
      WHERE
        (@FirstName IS NULL OR FirstName = @FirstName) AND
        (@LastNameName IS NULL OR LastName = @LastName) AND
        (@Title IS NULL OR Title = @Title)
END

however depend on data sometimes better create dynamic query and execute them.

Enum "Inheritance"

This is not possible. Enums cannot inherit from other enums. In fact all enums must actually inherit from System.Enum. C# allows syntax to change the underlying representation of the enum values which looks like inheritance, but in actuality they still inherit from System.enum.

See section 8.5.2 of the CLI spec for the full details. Relevant information from the spec

  • All enums must derive from System.Enum
  • Because of the above, all enums are value types and hence sealed

Uncaught ReferenceError: function is not defined with onclick

I was receiving the error (I'm using Vue) and I switched my onclick="someFunction()" to @click="someFunction" and now they are working.

How to append in a json file in Python?

Assuming you have a test.json file with the following content:

{"67790": {"1": {"kwh": 319.4}}}

Then, the code below will load the json file, update the data inside using dict.update() and dump into the test.json file:

import json

a_dict = {'new_key': 'new_value'}

with open('test.json') as f:
    data = json.load(f)

data.update(a_dict)

with open('test.json', 'w') as f:
    json.dump(data, f)

Then, in test.json, you'll have:

{"new_key": "new_value", "67790": {"1": {"kwh": 319.4}}}

Hope this is what you wanted.

Android App Not Install. An existing package by the same name with a conflicting signature is already installed

There may be another reason when your application will not update when you either change/add/remove shareId in AndroidManifiest.

"android:sharedUserId"

Please check that also.

To prevent would recommend to use sharedUserId in your application despite in your current requirement you need or now.

Difference between .on('click') vs .click()

Is there any difference between the following code?

No, there is no functional difference between the two code samples in your question. .click(fn) is a "shortcut method" for .on("click", fn). From the documentation for .on():

There are shorthand methods for some events such as .click() that can be used to attach or trigger event handlers. For a complete list of shorthand methods, see the events category.

Note that .on() differs from .click() in that it has the ability to create delegated event handlers by passing a selector parameter, whereas .click() does not. When .on() is called without a selector parameter, it behaves exactly the same as .click(). If you want event delegation, use .on().

How to test if a list contains another list?

If we refine the problem talking about testing if a list contains another list with as a sequence, the answer could be the next one-liner:

def contains(subseq, inseq):
    return any(inseq[pos:pos + len(subseq)] == subseq for pos in range(0, len(inseq) - len(subseq) + 1))

Here unit tests I used to tune up this one-liner:

https://gist.github.com/anonymous/6910a85b4978daee137f

angularjs: ng-src equivalent for background-image:url(...)

just a matter of taste but if you prefer accessing the variable or function directly like this:

<div id="playlist-icon" back-img="playlist.icon">

instead of interpolating like this:

<div id="playlist-icon" back-img="{{playlist.icon}}">

then you can define the directive a bit differently with scope.$watch which will do $parse on the attribute

angular.module('myApp', [])
.directive('bgImage', function(){

    return function(scope, element, attrs) {
        scope.$watch(attrs.bgImage, function(value) {
            element.css({
                'background-image': 'url(' + value +')',
                'background-size' : 'cover'
            });
        });
    };
})

there is more background on this here: AngularJS : Difference between the $observe and $watch methods

How to make an input type=button act like a hyperlink and redirect using a get request?

Do not do it. I might want to run my car on monkey blood. I have my reasons, but sometimes it's better to stick with using things the way they were designed even if it doesn't "absolutely perfectly" match the exact look you are driving for.

To back up my argument I submit the following.

  • See how this image lacks the status bar at the bottom. This link is using the onclick="location.href" model. (This is a real-life production example from my predecessor) This can make users hesitant to click on the link, since they have no idea where it is taking them, for starters.

Image

You are also making Search engine optimization more difficult IMO as well as making the debugging and reading of your code/HTML more complex. A submit button should submit a form. Why should you(the development community) try to create a non-standard UI?

Getting Current time to display in Label. VB.net

try

total.Text = DateTime.Now.ToString()

or

Dim theDate As DateTime = System.DateTime.Now
total.Text = theDate.ToString()

You declare Start as an Integer, while you are trying to put a DateTime in it, which is not possible.

iOS detect if user is on an iPad

Be Careful: If your app is targeting iPhone device only, iPad running with iphone compatible mode will return false for below statement:

#define IPAD     UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad

The right way to detect physical iPad device is:

#define IS_IPAD_DEVICE      ([(NSString *)[UIDevice currentDevice].model hasPrefix:@"iPad"])

How can I bind to the change event of a textarea in jQuery?

Try to do it with focusout

$("textarea").focusout(function() {
   alert('textarea focusout');
});

TypeScript: casting HTMLElement

I would also recommend the sitepen guides

https://www.sitepen.com/blog/2013/12/31/definitive-guide-to-typescript/ (see below) and https://www.sitepen.com/blog/2014/08/22/advanced-typescript-concepts-classes-types/

TypeScript also allows you to specify different return types when an exact string is provided as an argument to a function. For example, TypeScript’s ambient declaration for the DOM’s createElement method looks like this:

createElement(tagName: 'a'): HTMLAnchorElement;
createElement(tagName: 'abbr'): HTMLElement;
createElement(tagName: 'address'): HTMLElement;
createElement(tagName: 'area'): HTMLAreaElement;
// ... etc.
createElement(tagName: string): HTMLElement;

This means, in TypeScript, when you call e.g. document.createElement('video'), TypeScript knows the return value is an HTMLVideoElement and will be able to ensure you are interacting correctly with the DOM Video API without any need to type assert.

What is the size of a boolean variable in Java?

I read that Java reserves one byte for a boolean datatype, but it uses only one bit. However, the documentation says that "its "size" isn't something that's precisely defined". See here.

Send data from a textbox into Flask?

All interaction between server(your flask app) and client(browser) going by request and response. When user hit button submit in your form his browser send request with this form to your server (flask app), and you can get content of the form like:

request.args.get('form_name')

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

In case if you are using WPF application using PRISM framework then configuration should exist in your start up project (i.e. in the project where your bootstrapper resides.)

In short just remove it from the class library and put into a start up project.

Get Root Directory Path of a PHP project

I want to point to the way Wordpress handles this:

define( 'ABSPATH', dirname( __FILE__ ) . '/' );

As Wordpress is very heavy used all over the web and also works fine locally I have much trust in this method. You can find this definition on the bottom of your wordpress wp-config.php file

Show/Hide the console window of a C# console application

If you don't have a problem integrating a small batch application, there is this program called Cmdow.exe that will allow you to hide console windows based on console title.

Console.Title = "MyConsole";
System.Diagnostics.Process HideConsole = new System.Diagnostics.Process();
HideConsole.StartInfo.UseShellExecute = false;
HideConsole.StartInfo.Arguments = "MyConsole /hid";
HideConsole.StartInfo.FileName = "cmdow.exe";
HideConsole.Start();

Add the exe to the solution, set the build action to "Content", set Copy to Output Directory to what suits you, and cmdow will hide the console window when it is ran.

To make the console visible again, you just change the Arguments

HideConsole.StartInfo.Arguments = "MyConsole /Vis";

Animation fade in and out

According to the documentation AnimationSet

Represents a group of Animations that should be played together. The transformation of each individual animation are composed together into a single transform. If AnimationSet sets any properties that its children also set (for example, duration or fillBefore), the values of AnimationSet override the child values

AnimationSet mAnimationSet = new AnimationSet(false); //false means don't share interpolators

Pass true if all of the animations in this set should use the interpolator associated with this AnimationSet. Pass false if each animation should use its own interpolator.

ImageView imageView= (ImageView)findViewById(R.id.imageView);
Animation fadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
Animation fadeOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
mAnimationSet.addAnimation(fadeInAnimation);
mAnimationSet.addAnimation(fadeOutAnimation);
imageView.startAnimation(mAnimationSet);

I hope this will help you.

How to TryParse for Enum value?

There's currently no out of the box Enum.TryParse. This has been requested on Connect (Still no Enum.TryParse) and got a response indicating possible inclusion in the next framework after .NET 3.5. You'll have to implement the suggested workarounds for now.

Can I use GDB to debug a running process?

ps -elf doesn't seem to show the PID. I recommend using instead:

ps -ld | grep foo
gdb -p PID

Copy all values in a column to a new column in a pandas dataframe

I think the correct access method is using the index:

df_2.loc[:,'D'] = df_2['B']

How do I set bold and italic on UILabel of iPhone/iPad?

As has already been mentioned in these answers, you just need the right font name. I find that iOSFonts.com is the most helpful resource for knowing exactly what name to use.

Does Django scale?

  1. "What are the largest sites built on Django today?"

    There isn't any single place that collects information about traffic on Django built sites, so I'll have to take a stab at it using data from various locations. First, we have a list of Django sites on the front page of the main Django project page and then a list of Django built sites at djangosites.org. Going through the lists and picking some that I know have decent traffic we see:

  2. "Can Django deal with 100,000 users daily, each visiting the site for a couple of hours?"

    Yes, see above.

  3. "Could a site like Stack Overflow run on Django?"

    My gut feeling is yes but, as others answered and Mike Malone mentions in his presentation, database design is critical. Strong proof might also be found at www.cnprog.com if we can find any reliable traffic stats. Anyway, it's not just something that will happen by throwing together a bunch of Django models :)

There are, of course, many more sites and bloggers of interest, but I have got to stop somewhere!


Blog post about Using Django to build high-traffic site michaelmoore.com described as a top 10,000 website. Quantcast stats and compete.com stats.


(*) The author of the edit, including such reference, used to work as outsourced developer in that project.

How do I include the string header?

Maybe this link will help you.

See: std::string documentation.

#include <string> is the most widely accepted.

How to make URL/Phone-clickable UILabel?

Swift 4.0 possible solution using UIButton

     phoneButton = UIButton(frame: CGRect(x: view.frame.width * 0, y: view.frame.height * 0.1, width: view.frame.width * 1, height: view.frame.height * 0.05))
     phoneButton.setTitle("333-333-3333", for: .normal )
     phoneButton.setTitleColor(UIColor(red: 0 / 255, green: 0 / 255, blue: 238 / 255, alpha: 1.0), for: .normal)
     phoneButton.addTarget(self, action: #selector(self.callPhone), for: .touchUpInside )

     @objc func callPhone(){

         UIApplication.shared.open(URL(string:"tel://3333333333")!, options: [:] , completionHandler: nil)


    }

cURL not working (Error #77) for SSL connections on CentOS for non-root users

The error is due to corrupt or missing SSL chain certificate files in the PKI directory. You’ll need to make sure the files ca-bundle, following steps: In your console/terminal:

mkdir /usr/src/ca-certificates && cd /usr/src/ca-certificates

Enter this site: https://rpmfind.net/linux/rpm2html/search.php?query=ca-certificates , get your ca-certificate, for yout SO, for example: ftp://rpmfind.net/linux/fedora/linux/updates/24/x86_64/c/ca-certificates-2016.2.8-1.0.fc24.noarch.rpm << CentOS. Copy url of download and paste in url: wget your_url_donwload_ca-ceritificated.rpm now, install yout rpm:

rpm2cpio your_url_donwload_ca-ceritificated.rpm | cpio -idmv

now restart your service: my example this command:

sudo service2 httpd restart

very great good look

Check if element found in array c++

You can use old C-style programming to do the job. This will require little knowledge about C++. Good for beginners.

For modern C++ language you usually accomplish this through lambda, function objects, ... or algorithm: find, find_if, any_of, for_each, or the new for (auto& v : container) { } syntax. find class algorithm takes more lines of code. You may also write you own template find function for your particular need.

Here is my sample code

#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>

using namespace std;

/**
 * This is old C-like style.  It is mostly gong from 
 * modern C++ programming.  You can still use this
 * since you need to know very little about C++.
 * @param storeSize you have to know the size of store
 *    How many elements are in the array.
 * @return the index of the element in the array,
 *   if not found return -1
 */
int in_array(const int store[], const int storeSize, const int query) {
   for (size_t i=0; i<storeSize; ++i) {
      if (store[i] == query) {
         return i;
      }
   }
   return -1;
}

void testfind() {
   int iarr[] = { 3, 6, 8, 33, 77, 63, 7, 11 };

   // for beginners, it is good to practice a looping method
   int query = 7;
   if (in_array(iarr, 8, query) != -1) {
      cout << query << " is in the array\n";
   }

   // using vector or list, ... any container in C++
   vector<int> vecint{ 3, 6, 8, 33, 77, 63, 7, 11 };
   auto it=find(vecint.begin(), vecint.end(), query);
   cout << "using find()\n";
   if (it != vecint.end()) {
      cout << "found " << query << " in the container\n";
   }
   else {
      cout << "your query: " << query << " is not inside the container\n";
   }

   using namespace std::placeholders;
   // here the query variable is bound to the `equal_to` function 
   // object (defined in std)
   cout << "using any_of\n";
   if (any_of(vecint.begin(), vecint.end(), bind(equal_to<int>(), _1, query))) {
      cout << "found " << query << " in the container\n";
   }
   else {
      cout << "your query: " << query << " is not inside the container\n";
   }

   // using lambda, here I am capturing the query variable
   // into the lambda function
   cout << "using any_of with lambda:\n";
   if (any_of(vecint.begin(), vecint.end(),
            [query](int val)->bool{ return val==query; })) {
      cout << "found " << query << " in the container\n";
   }
   else {
      cout << "your query: " << query << " is not inside the container\n";
   }
}

int main(int argc, char* argv[]) {
   testfind();

   return 0;
}

Say this file is named 'testalgorithm.cpp' you need to compile it with

g++ -std=c++11 -o testalgorithm testalgorithm.cpp

Hope this will help. Please update or add if I have made any mistake.

Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

Mine was not having @Entity on the many side entity

@Entity // this was commented
@Table(name = "some_table")
public class ChildEntity {
    @JoinColumn(name = "parent", referencedColumnName = "id")
    @ManyToOne
    private ParentEntity parentEntity;
}

Problems installing the devtools package

If you are using Ubuntu/Linux:

sudo apt-get install libcurl4-openssl-dev libssl-dev

Typescript : Property does not exist on type 'object'

If your object could contain any key/value pairs, you could declare an interface called keyable like :

interface keyable {
    [key: string]: any  
}

then use it as follows :

let countryProviders: keyable[];

or

let countryProviders: Array<keyable>;

Changing font size and direction of axes text in ggplot2

Another way to deal with overlapping labels is using guide = guide_axis(n.dodge = 2).

library(dplyr)
library(tibble)
library(ggplot2)

dt <- mtcars %>% rownames_to_column("name") %>% 
  dplyr::filter(cyl == 4)

# Overlapping labels
ggplot(dt, aes(x = name, y = mpg)) + geom_point()

enter image description here

ggplot(dt, aes(x = name, y = mpg)) + geom_point() +
  scale_x_discrete(guide = guide_axis(n.dodge = 2))

enter image description here

Oracle JDBC ojdbc6 Jar as a Maven Dependency

Below config worked for me. Refer this link for more details.

<dependency>
 <groupId>com.oracle.jdbc</groupId>
 <artifactId>ojdbc7</artifactId>
 <version>12.1.0.2</version>
</dependency>

Is there a developers api for craigslist.org

Craigslist does have a "bulk posting interface" which allows for multiple posts to happen at once through HTTPS POST. See:

http://www.craigslist.org/about/bulk_posting_interface

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

For those that are not overflowing but hiding by negative margin:

$('#element').height() + -parseInt($('#element').css("margin-top"));

(ugly but only one that works so far)

SQL Error: ORA-12899: value too large for column

ORA-12899: value too large for column "DJ"."CUSTOMERS"."ADDRESS" (actual: 25, maximum: 2

Tells you what the error is. Address can hold maximum of 20 characters, you are passing 25 characters.

How to add header data in XMLHttpRequest when using formdata?

Use: xmlhttp.setRequestHeader(key, value);

what is reverse() in Django

Existing answers did a great job at explaining the what of this reverse() function in Django.

However, I'd hoped that my answer shed a different light at the why: why use reverse() in place of other more straightforward, arguably more pythonic approaches in template-view binding, and what are some legitimate reasons for the popularity of this "redirect via reverse() pattern" in Django routing logic.

One key benefit is the reverse construction of a url, as others have mentioned. Just like how you would use {% url "profile" profile.id %} to generate the url from your app's url configuration file: e.g. path('<int:profile.id>/profile', views.profile, name="profile").

But as the OP have noted, the use of reverse() is also commonly combined with the use of HttpResponseRedirect. But why?

I am not quite sure what this is but it is used together with HttpResponseRedirect. How and when is this reverse() supposed to be used?

Consider the following views.py:

from django.http import HttpResponseRedirect
from django.urls import reverse

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected = question.choice_set.get(pk=request.POST['choice'])
    except KeyError:
        # handle exception
        pass
    else:
        selected.votes += 1
        selected.save()
        return HttpResponseRedirect(reverse('polls:polls-results',
                                    args=(question.id)
        ))

And our minimal urls.py:

from django.urls import path
from . import views

app_name = 'polls'
urlpatterns = [
    path('<int:question_id>/results/', views.results, name='polls-results'),
    path('<int:question_id>/vote/', views.vote, name='polls-vote')
]

In the vote() function, the code in our else block uses reverse along with HttpResponseRedirect in the following pattern:

HttpResponseRedirect(reverse('polls:polls-results',
                                        args=(question.id)

This first and foremost, means we don't have to hardcode the URL (consistent with the DRY principle) but more crucially, reverse() provides an elegant way to construct URL strings by handling values unpacked from the arguments (args=(question.id) is handled by URLConfig). Supposed question has an attribute id which contains the value 5, the URL constructed from the reverse() would then be:

'/polls/5/results/'

In normal template-view binding code, we use HttpResponse() or render() as they typically involve less abstraction: one view function returning one template:

def index(request):
    return render(request, 'polls/index.html') 

But in many legitimate cases of redirection, we typically care about constructing the URL from a list of parameters. These include cases such as:

  • HTML form submission through POST request
  • User login post-validation
  • Reset password through JSON web tokens

Most of these involve some form of redirection, and a URL constructed through a set of parameters. Hope this adds to the already helpful thread of answers!

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

Just do what the message is asking for, create the user pma@localhost in the phpMyAdmin panel with no password

Uncaught TypeError: Cannot read property 'appendChild' of null

For people who have the same issue of querySelector or getElementById that returns the following error:

Uncaught TypeError: Cannot read property 'appendChild' of null

but you have a class name or id in the HTML...

If your script tag is in the head, the JavaScript is loaded before your HTML. You will need to add defer to your script like so:

<script src="script.js" defer></script>

Android: How to overlay a bitmap and draw over a bitmap?

If the purpose is to obtain a bitmap, this is very simple:

Canvas canvas = new Canvas();
canvas.setBitmap(image);
canvas.drawBitmap(image2, new Matrix(), null);

In the end, image will contain the overlap of image and image2.

How to identify server IP address in PHP

$serverIP = $_SERVER["SERVER_ADDR"];
echo "Server IP is: <b>{$serverIP}</b>";

Pipe output and capture exit status in Bash

This solution works without using bash specific features or temporary files. Bonus: in the end the exit status is actually an exit status and not some string in a file.

Situation:

someprog | filter

you want the exit status from someprog and the output from filter.

Here is my solution:

((((someprog; echo $? >&3) | filter >&4) 3>&1) | (read xs; exit $xs)) 4>&1

echo $?

See my answer for the same question on unix.stackexchange.com for a detailed explanation and an alternative without subshells and some caveats.

Create WordPress Page that redirects to another URL

(This is for posts, not pages - the principle is same. The permalink hook is different by exact use case)

I just had the same issue and created a more convenient way to do that - where you don't have to re-edit your functions.php all the time, or fiddle around with your server settings on each addition (I do not like both).

TLTR

You can add a filter on the actual WP permalink function you need (for me it was post_link, because I needed that page alias in an archive/category list), and dynamically read the referenced ID from the alias post itself.

This is ok, because the post is an alias, so you won't need the content anyways.

First step is to open the alias post and put the ID of the referenced post as content (and nothing else):

enter image description here

Next, open your functions.php and add:

function prefix_filter_post_permalink($url, $post) {
    // if the content of the post to get the permalink for is just a number...
    if (is_numeric($post->post_content)) {
        // instead, return the permalink for the post that has this ID
        return get_the_permalink((int)$post->post_content);
    }
    return $url;
}
add_filter('post_link', 'prefix_filter_post_permalink', 10, 2 );

That's it

Now, each time you need to create an alias post, just put the ID of the referenced post as the content, and you're done.

This will just change the permalink. Title, excerpt and so on will be shown as-is, which is usually desired. More tweaking to your needs is on you, also, the "is it a number" part in the PHP code is far from ideal, but like this for making the point readable.

Difference between .dll and .exe?

Difference in DLL and EXE:

1) DLL is an In-Process Component which means running in the same memory space as the client process. EXE is an Out-Process Component which means it runs in its own separate memory space.

2) The DLL contains functions and procedures that other programs can use (promotes reuability) while EXE cannot be shared with other programs.

3) DLL cannot be directly executed as they're designed to be loaded and run by other programs. EXE is a program that is executed directly.

Hide particular div onload and then show div after click

You are missing # hash character before id selectors, this should work:

$(document).ready(function() {
    $("#div2").hide();

    $("#preview").click(function() {
      $("#div1").hide();
      $("#div2").show();
    });

});

Learn More about jQuery ID Selectors

OS X Terminal UTF-8 issues

For me, this helped: I checked locale on my local shell in terminal

$ locale
LANG="cs_CZ.UTF-8"
LC_COLLATE="cs_CZ.UTF-8"

Then connected to any remote host I am using via ssh and edited file /etc/profile as root - at the end I added line:

export LANG=cs_CZ.UTF-8

After next connection it works fine in bash, ls and nano.

IndentationError: unindent does not match any outer indentation level

I got this error even though I didn't have any tabs in my code, and the reason was there was a superfluous closing parenthesis somewhere in my code. I should have figured this out earlier because it was messing up spaces before and after some equal signs... If you find anything off even after running Reformat code in your IDE (or manually running autopep8), make sure all your parentheses match, starting backwards from the weird spaces before/after the first equals sign.

403 Forbidden vs 401 Unauthorized HTTP responses

This question was asked some time ago, but people's thinking moves on.

Section 6.5.3 in this draft (authored by Fielding and Reschke) gives status code 403 a slightly different meaning to the one documented in RFC 2616.

It reflects what happens in authentication & authorization schemes employed by a number of popular web-servers and frameworks.

I've emphasized the bit I think is most salient.

6.5.3. 403 Forbidden

The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).

If authentication credentials were provided in the request, the server considers them insufficient to grant access. The client SHOULD NOT repeat the request with the same credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons unrelated to the credentials.

An origin server that wishes to "hide" the current existence of a forbidden target resource MAY instead respond with a status code of 404 (Not Found).

Whatever convention you use, the important thing is to provide uniformity across your site / API.

Getting files by creation date in .NET

You can use Linq

var files = Directory.GetFiles(@"C:\", "*").OrderByDescending(d => new FileInfo(d).CreationTime);

How to fix the error "Windows SDK version 8.1" was not found?

  • Install the required version of Windows SDK or change the SDK version in the project property pages

    or

  • by right-clicking the solution and selecting "Retarget solution"

If you do visual studio guide, you will resolve the problem.

adding onclick event to dynamically added button?

but.onclick = function() { yourjavascriptfunction();};

or

but.onclick = function() { functionwithparam(param);};

Get column from a two dimensional array

This function works to arrays and objects. obs: it works like array_column php function. It means that an optional third parameter can be passed to define what column will correspond to the indices of return.

function array_column(list, column, indice){
    var result;

    if(typeof indice != "undefined"){
        result = {};

        for(key in list)
            result[list[key][indice]] = list[key][column];
    }else{
        result = [];

        for(key in list)
            result.push( list[key][column] );
    }

    return result;
}

This is a conditional version:

function array_column_conditional(list, column, indice){
    var result;

    if(typeof indice != "undefined"){
        result = {};

        for(key in list)
            if(typeof list[key][column] !== 'undefined' && typeof list[key][indice] !== 'undefined')
                result[list[key][indice]] = list[key][column];
    }else{
        result = [];

        for(key in list)
            if(typeof list[key][column] !== 'undefined')
                result.push( list[key][column] );
    }

    return result;
}

usability:

var lista = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

var obj_list = [
  {a: 1, b: 2, c: 3},
  {a: 4, b: 5, c: 6},
  {a: 8, c: 9}
];

var objeto = {
  d: {a: 1, b: 3},
  e: {a: 4, b: 5, c: 6},
  f: {a: 7, b: 8, c: 9}
};

var list_obj = {
  d: [1, 2, 3],
  e: [4, 5],
  f: [7, 8, 9]
};

console.log( "column list: ", array_column(lista, 1) );
console.log( "column obj_list: ", array_column(obj_list, 'b', 'c') );
console.log( "column objeto: ", array_column(objeto, 'c') );
console.log( "column list_obj: ", array_column(list_obj, 0, 0) );

console.log( "column list conditional: ", array_column_conditional(lista, 1) );
console.log( "column obj_list conditional: ", array_column_conditional(obj_list, 'b', 'c') );
console.log( "column objeto conditional: ", array_column_conditional(objeto, 'c') );
console.log( "column list_obj conditional: ", array_column_conditional(list_obj, 0, 0) );

Output:

/*
column list:  Array [ 2, 5, 8 ]
column obj_list:  Object { 3: 2, 6: 5, 9: undefined }
column objeto:  Array [ undefined, 6, 9 ]
column list_obj:  Object { 1: 1, 4: 4, 7: 7 }

column list conditional:  Array [ 2, 5, 8 ]
column obj_list conditional:  Object { 3: 2, 6: 5 }
column objeto conditional:  Array [ 6, 9 ]
column list_obj conditional:  Object { 1: 1, 4: 4, 7: 7 }
*/

Converting Float to Dollars and Cents

In Python 3.x and 2.7, you can simply do this:

>>> '${:,.2f}'.format(1234.5)
'$1,234.50'

The :, adds a comma as a thousands separator, and the .2f limits the string to two decimal places (or adds enough zeroes to get to 2 decimal places, as the case may be) at the end.

Structs data type in php?

I cobbled together a 'dynamic' struct class today, had a look tonight and someone has written something similar with better handling of constructor parameters, it might be worth a look:

http://code.activestate.com/recipes/577160-php-struct-port/

One of the comments on this page mentions an interesting thing in PHP - apparently you're able to cast an array as an object, which lets you refer to array elements using the arrow notation, as you would with a Struct pointer in C. The comment's example was as follows:

$z = array('foo' => 1, 'bar' => true, 'baz' => array(1,2,3));
//accessing values as properties
$y = (object)$z;
echo $y->foo;

I haven't tried this myself yet, but it may be that you could get the desired notation by just casting - if that's all you're after. These are of course 'dynamic' data structures, just syntactic sugar for accessing key/value pairs in a hash.

If you're actually looking for something more statically typed, then ASpencer's answer is the droid you're looking for (as Obi-Wan might say.)

How do I use a C# Class Library in a project?

I'm not certain why everyone is claiming that you need a using statement at the top of your file, as this is entirely unnecessary.

Right-click on the "References" folder in your project and select "Add Reference". If your new class library is a project in the same solution, select the "Project" tab and pick the project. If the new library is NOT in the same solution, click the "Browse" tab and find the .dll for your new project.

PostgreSQL error 'Could not connect to server: No such file or directory'

I had that problem when I upgraded Postgres to 9.3.x. The quick fix for me was to downgrade to whichever 9.2.x version I had before (no need to install a new one).

$ ls /usr/local/Cellar/postgresql/
9.2.4
9.3.2
$ brew switch postgresql 9.2.4
$ launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
$ launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
<open a new Terminal tab or window to reload>
$ psql

"Homebrew install specific version of formula?" offers a much more comprehensive explanation along with alternative ways to fix the problem.