Programs & Examples On #Modal dialog

Refers to a graphical dialog used to display important information to the user. These dialogs appear above all other content, blocking application flow until user input is received.

how to destroy bootstrap modal window completely?

$('#myModal').on('hidden.bs.modal', function () {
      $(this).data('bs.modal', null).remove();
});

//Just add .remove(); 
//Bootstrap v3.0.3

How can I display a modal dialog in Redux that performs asynchronous actions?

Wrap the modal into a connected container and perform the async operation in here. This way you can reach both the dispatch to trigger actions and the onClose prop too. To reach dispatch from props, do not pass mapDispatchToProps function to connect.

class ModalContainer extends React.Component {
  handleDelete = () => {
    const { dispatch, onClose } = this.props;
    dispatch({type: 'DELETE_POST'});

    someAsyncOperation().then(() => {
      dispatch({type: 'DELETE_POST_SUCCESS'});
      onClose();
    })
  }

  render() {
    const { onClose } = this.props;
    return <Modal onClose={onClose} onSubmit={this.handleDelete} />
  }
}

export default connect(/* no map dispatch to props here! */)(ModalContainer);

The App where the modal is rendered and its visibility state is set:

class App extends React.Component {
  state = {
    isModalOpen: false
  }

  handleModalClose = () => this.setState({ isModalOpen: false });

  ...

  render(){
    return (
      ...
      <ModalContainer onClose={this.handleModalClose} />  
      ...
    )
  }

}

jQuery UI Dialog Box - does not open after being closed

I had the same problem with jquery-ui overlay dialog box - it would work only once and then stop unless i reload the page. I found the answer in one of their examples -
Multiple overlays on a same page
flowplayer_tools_multiple_open_close
- who would have though, right?? :-) -

the important setting appeared to be

oneInstance: false

so, now i have it like this -

$(document).ready(function() {

 var overlays = null;

 overlays = jQuery("a[rel]");

 for (var n = 0; n < overlays.length; n++) {

    $(overlays[n]).overlay({
        oneInstance: false, 
        mask: '#669966',
        effect: 'apple',
        onBeforeLoad: function() {
            overlay_before_load(this);
        }
    });

  }

}

and everything works just fine

hope this helps somebody

O.

Disable click outside of bootstrap modal area to close modal

In my application, I am using the below piece of code to show Bootstrap modal via jQuery.

 $('#myModall').modal({
                        backdrop: 'static',
                        keyboard: true, 
                        show: true
                }); 

Bootstrap modal opening on page load

Use a document.ready() event around your call.

$(document).ready(function () {

    $('#memberModal').modal('show');

});

jsFiddle updated - http://jsfiddle.net/uvnggL8w/1/

Bootstrap Modal sitting behind backdrop

I Found that applying ionic framework (ionic.min.cs) after bootstrap coursing this issue for me.

jQuery UI Dialog individual CSS styling

You can add the class to the title like this:

$('#dialog_style1').siblings('div.ui-dialog-titlebar').addClass('dialog1');

Load content with ajax in bootstrap modal

The top voted answer is deprecated in Bootstrap 3.3 and will be removed in v4. Try this instead:

JavaScript:

// Fill modal with content from link href
$("#myModal").on("show.bs.modal", function(e) {
    var link = $(e.relatedTarget);
    $(this).find(".modal-body").load(link.attr("href"));
});

Html (Based on the official example. Note that for Bootstrap 3.* we set data-remote="false" to disable the deprecated Bootstrap load function):

<!-- Link trigger modal -->
<a href="remoteContent.html" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-default">
    Launch Modal
</a>

<!-- Default bootstrap modal example -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Try it yourself: https://jsfiddle.net/ednon5d1/

Open Jquery modal dialog on click event

Try this

    $(function() {

$('#clickMe').click(function(event) {
    var mytext = $('#myText').val();


    $('<div id="dialog">'+mytext+'</div>').appendTo('body');        
    event.preventDefault();

        $("#dialog").dialog({                   
            width: 600,
            modal: true,
            close: function(event, ui) {
                $("#dialog").remove();
                }
            });
    }); //close click
});

And in HTML

<h3 id="clickMe">Open dialog</h3>
<textarea cols="0" rows="0" id="myText" style="display:none">Some hidden text display none</textarea>

Custom "confirm" dialog in JavaScript?

Faced with the same problem, I was able to solve it using only vanilla JS, but in an ugly way. To be more accurate, in a non-procedural way. I removed all my function parameters and return values and replaced them with global variables, and now the functions only serve as containers for lines of code - they're no longer logical units.

In my case, I also had the added complication of needing many confirmations (as a parser works through a text). My solution was to put everything up to the first confirmation in a JS function that ends by painting my custom popup on the screen, and then terminating.

Then the buttons in my popup call another function that uses the answer and then continues working (parsing) as usual up to the next confirmation, when it again paints the screen and then terminates. This second function is called as often as needed.

Both functions also recognize when the work is done - they do a little cleanup and then finish for good. The result is that I have complete control of the popups; the price I paid is in elegance.

How to make modal dialog in WPF?

Given a Window object myWindow, myWindow.Show() will open it modelessly and myWindow.ShowDialog() will open it modally. However, even the latter doesn't block, from what I remember.

Close Bootstrap Modal

We can close the modal pop-up in the following ways:

// We use data-dismiss property of modal-up in html to close the modal-up,such as

<div class='modal-footer'><button type='button' class="btn btn-default" data-dismiss='modal'>Close</button></div>

 // We can close the modal pop-up through java script, such as

 <div class='modal fade pageModal'  id='openModal' tabindex='-1' data-keyboard='false' data-backdrop='static'>

    $('#openModal').modal('hide'); //Using modal pop-up Id.
    $('.pageModal').modal('hide'); //Using class that is defined in modal html.

Invoking modal window in AngularJS Bootstrap UI using JavaScript

Quick and Dirty Way!

It's not a good way, but for me it seems the most simplest.

Add an anchor tag which contains the modal data-target and data-toggle, have an id associated with it. (Can be added mostly anywhere in the html view)

<a href="" data-toggle="modal" data-target="#myModal" id="myModalShower"></a>

Now,

Inside the angular controller, from where you want to trigger the modal just use

angular.element('#myModalShower').trigger('click');

This will mimic a click to the button based on the angular code and the modal will appear.

Javascript to stop HTML5 video playback on modal window close

Try this:

$(document).ready(function(){
    $("#showSimpleModal").click(function() {
        $("div#simpleModal").addClass("show");
        $("#videoContainer")[0].play();
        return false;   
    });

    $("#closeSimple").click(function() {
        $("div#simpleModal").removeClass("show");
        $("#videoContainer")[0].pause();
        return false;                   
    });
});

Can not get a simple bootstrap modal to work

I run into this issue too. I was including bootstrap.js AND bootstrap-modal.js. If you already have bootstrap.js, you don't need to include popover.

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs

curious - why doesn't the 'nothing easier than this' answer (above) not work? it looks logical? http://206.251.38.181/jquery-learn/ajax/iframe.html

How to set the focus for a particular field in a Bootstrap modal, once it appears

A little cleaner and more modular solution might be:

$(document).ready(function(){
    $('.modal').success(function() { 
        $('input:text:visible:first').focus();
    });  
});

Or using your ID as an example instead:

$(document).ready(function(){
    $('#modal-content').modal('show').success(function() {
        $('input:text:visible:first').focus();
    });  
});

Hope that helps..

How to hide Bootstrap previous modal when you opening new one?

You hide Bootstrap modals with:

$('#modal').modal('hide');

Saying $().hide() makes the matched element invisible, but as far as the modal-related code is concerned, it's still there. See the Methods section in the Modals documentation.

Bind a function to Twitter Bootstrap Modal Close

I would do it like this:

$('body').on('hidden.bs.modal', '#myModal', function(){ //this call your method });

The rest has already been written by others. I also recommend reading the documentation:jquery - on method

How to use Bootstrap modal using the anchor tag for Register?

Here is a link to W3Schools that answers your question https://www.w3schools.com/bootstrap/bootstrap_ref_js_modal.asp

Note: For anchor tag elements, omit data-target, and use href="#modalID" instead:

I hope that helps

How to implement "confirmation" dialog in Jquery UI dialog?

Well this is the answer of your questions...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>
<HEAD>
<TITLE>Santa Luisa</TITLE>
<style>
    body{margin:0;padding:0;background-color:#ffffff;}
    a:link {color:black;}    
a:visited {color:black;}  
a:hover {color:red;}  
a:active {color:red;}
</style>

</HEAD>
<body>

<link rel="stylesheet" href="jquery/themes/base/jquery.ui.all.css">
    <script src="jquery-1.4.4.js"></script>

    <script src="external/jquery.bgiframe-2.1.2.js"></script>
    <script src="ui/jquery.ui.core.js"></script>

    <script src="ui/jquery.ui.widget.js"></script>
    <script src="ui/jquery.ui.mouse.js"></script>
    <script src="ui/jquery.ui.draggable.js"></script>
    <script src="ui/jquery.ui.position.js"></script>

    <script src="ui/jquery.ui.resizable.js"></script>
    <script src="ui/jquery.ui.dialog.js"></script>

    <link rel="stylesheet" href="demos.css">
    <script>
    var lastdel;
    $(function() {
        $( "#dialog" ).dialog({
            autoOpen: false,modal: true,closeOnEscape: true
        });

        $(".confirmLink").click(function(e) {
            e.preventDefault();
            var lastdel = $(this).attr("href");

        });


        $("#si").click( function() {
            $('#dialog').dialog('close');
            window.location.href =lastdel;

        });
        $("#no").click( function() {
            $('#dialog').dialog('close');
        });
    });

    </script>

<SCRIPT LANGUAGE="JavaScript">
<!--
        var currentimgx;
        var cimgoverx=200-6;
        var cimgoutx=200;


        function overbx(obj){
        color='#FF0000';
        width='3px';
        obj.style.borderTopWidth = width;
        obj.style.borderTopColor =color;
        obj.style.borderTopStyle ='solid';

        obj.style.borderLeftWidth = width;
        obj.style.borderLeftColor =color;
        obj.style.borderLeftStyle ='solid';

        obj.style.borderRightWidth = width;
        obj.style.borderRightColor =color;
        obj.style.borderRightStyle ='solid';

        obj.style.borderBottomWidth = width;
        obj.style.borderBottomColor =color;
        obj.style.borderBottomStyle ='solid';


        currentimgx.style.width=cimgoverx+"px";
        currentimgx.style.height=cimgoverx+"px"; 

    }

    function outbx(obj){
        obj.style.borderTopWidth = '0px';   
        obj.style.borderLeftWidth = '0px';
        obj.style.borderRightWidth = '0px';
        obj.style.borderBottomWidth = '0px';

        currentimgx.style.width=cimgoutx+"px";
        currentimgx.style.height=cimgoutx+"px"; 
    }

function ifocusx(obj){
        color='#FF0000';
        width='3px';
        obj.style.borderTopWidth = width;
        obj.style.borderTopColor =color;
        obj.style.borderTopStyle ='solid';

        obj.style.borderLeftWidth = width;
        obj.style.borderLeftColor =color;
        obj.style.borderLeftStyle ='solid';

        obj.style.borderRightWidth = width;
        obj.style.borderRightColor =color;
        obj.style.borderRightStyle ='solid';

        obj.style.borderBottomWidth = width;
        obj.style.borderBottomColor =color;
        obj.style.borderBottomStyle ='solid';

    }

    function iblurx(obj){
        color='#000000';
        width='3px';
        obj.style.borderTopWidth = width;
        obj.style.borderTopColor =color;
        obj.style.borderTopStyle ='solid';

        obj.style.borderLeftWidth = width;
        obj.style.borderLeftColor =color;
        obj.style.borderLeftStyle ='solid';

        obj.style.borderRightWidth = width;
        obj.style.borderRightColor =color;
        obj.style.borderRightStyle ='solid';

        obj.style.borderBottomWidth = width;
        obj.style.borderBottomColor =color;
        obj.style.borderBottomStyle ='solid';
    }

    function cimgx(obj){
        currentimgx=obj;
    }


    function pause(millis){
    var date = new Date();
    var curDate = null;

    do { curDate = new Date(); }
    while(curDate-date < millis);
    } 


//-->
</SCRIPT>
<div id="dialog" title="CONFERMA L`AZIONE" style="text-align:center;">
    <p><FONT  COLOR="#000000" style="font-family:Arial;font-size:22px;font-style:bold;COLOR:red;">CONFERMA L`AZIONE:<BR>POSSO CANCELLARE<BR>QUESTA RIGA ?</FONT></p>

    <p><INPUT TYPE="submit" VALUE="SI" NAME="" id="si"> --><INPUT TYPE="submit" VALUE="NO" NAME="" id="no"></p>
</div>



<TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="100%" height="100%">
<TR valign="top" align="center">
    <TD>
    <FONT COLOR="red" style="font-family:Arial;font-size:25px;font-style:bold;color:red;">Modifica/Dettagli:<font style="font-family:Arial;font-size:20px;font-style:bold;background-color:yellow;color:red;">&nbsp;298&nbsp;</font><font style="font-family:Arial;font-size:20px;font-style:bold;background-color:red;color:yellow;">dsadas&nbsp;sadsadas&nbsp;</font>&nbsp;</FONT>
    </TD>
</TR>

<tr valign="top">
    <td align="center">
        <TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="">
        <TR align="left">

            <TD>
                <TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="">

                <TR align="left">
                    <TD>
                    <font style="font-sixe:30px;"><span style="color:red;">1</span></font><br><TABLE class="tabela" CELLSPACING="0" CELLPADDING="0" BORDER="1" WIDTH="800px"><TR style="color:white;background-color:black;"><TD align="center">DATA</TD><TD align="center">CODICE</TD><TD align="center">NOME/NOMI</TD><TD  align="center">TESTO</TD><td>&nbsp;</td><td>&nbsp;</td></TR><TR align="center"><TD>12/22/2010&nbsp;</TD><TD>298&nbsp;</TD><TD>daaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</TD><TD><A HREF="modificarigadiario.php?codice=298"  style="font-weight:bold;color:red;font-size:30px;">Modifica</A></TD><TD><A HREF="JavaScript:void(0);"  style="font-weight:bold;color:red;font-size:30px;" onclick="$('#dialog').dialog('open');$('#dialog').animate({ backgroundColor: '#aa0000', color: '#fff', width: 250 }, 2000);lastdel='cancellarighe.php?codice=298&id=1';alert(lastdel);" class="confirmLink">Cancella</A></TD><TR align="center"><TD>22/10/2010&nbsp;</TD><TD>298&nbsp;</TD><TD>dfdsfsdfsf</TD><TD><A HREF="modificarigadiario.php?codice=298"  style="font-weight:bold;color:red;font-size:30px;">Modifica</A></TD><TD><A HREF="JavaScript:void(0);"  style="font-weight:bold;color:red;font-size:30px;" onclick="$('#dialog').dialog('open');$('#dialog').animate({ backgroundColor: '#aa0000', color: '#fff', width: 250 }, 2000);lastdel='cancellarighe.php?codice=298&id=2';alert(lastdel);" class="confirmLink">Cancella</A></TD></TABLE><font style="font-sixe:30px;"><span style="color:red;">1</span></font><br>

                    </TD>
                </TR>

                </TABLE>
            </TD>
        </TR>
        </TABLE>
    </td>
</tr>
</tbody></table>


</body>
</html>

make sure you have jquery 1.4.4 and jquery.ui

Display Bootstrap Modal using javascript onClick

I was looking for the onClick option to set the title and body of the modal based on the item in a list. T145's answer helped a lot, so I wanted to share how I used it.

Make sure the tag containing the JavaScript function is of type text/javascript to avoid conflicts:

<script type="text/javascript"> function showMyModalSetTitle(myTitle, myBodyHtml) {

   /*
    * '#myModayTitle' and '#myModalBody' refer to the 'id' of the HTML tags in
    * the modal HTML code that hold the title and body respectively. These id's
    * can be named anything, just make sure they are added as necessary.
    *
    */

   $('#myModalTitle').html(myTitle);
   $('#myModalBody').html(myBodyHtml);

   $('#myModal').modal('show');
}</script>

This function can now be called in the onClick method from inside an element such as a button:

<button type="button" onClick="javascript:showMyModalSetTitle('Some Title', 'Some body txt')"> Click Me! </button>

How to hide Bootstrap modal with javascript?

With the modal open in the browser window, use the browser's console to try

$('#myModal').modal('hide');

If it works (and the modal closes) then you know that your close Javascript is not being sent from the server to the browser correctly.

If it doesn't work then you need to investigate further on the client what is happening. Eg make sure that there aren't two elements with the same id. Eg does it work the first time after page load but not the second time?

Browser's console: firebug for firefox, the debugging console for Chrome or Safari, etc.

Bootstrap 3 - How to load content in modal body via AJAX?

A simple way to use modals is with eModal!

Ex from github:

  1. Link to eModal.js <script src="//rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>
  2. use eModal to display a modal for alert, ajax, prompt or confirm

    // Display an alert modal with default title (Attention)
    eModal.ajax('your/url.html');
    

_x000D_
_x000D_
$(document).ready(function () {/* activate scroll spy menu */_x000D_
_x000D_
    var iconPrefix = '.glyphicon-';_x000D_
_x000D_
_x000D_
    $(iconPrefix + 'cloud').click(ajaxDemo);_x000D_
    $(iconPrefix + 'comment').click(alertDemo);_x000D_
    $(iconPrefix + 'ok').click(confirmDemo);_x000D_
    $(iconPrefix + 'pencil').click(promptDemo);_x000D_
    $(iconPrefix + 'screenshot').click(iframeDemo);_x000D_
    ///////////////////* Implementation *///////////////////_x000D_
_x000D_
    // Demos_x000D_
    function ajaxDemo() {_x000D_
        var title = 'Ajax modal';_x000D_
        var params = {_x000D_
            buttons: [_x000D_
               { text: 'Close', close: true, style: 'danger' },_x000D_
               { text: 'New content', close: false, style: 'success', click: ajaxDemo }_x000D_
            ],_x000D_
            size: eModal.size.lg,_x000D_
            title: title,_x000D_
            url: 'http://maispc.com/app/proxy.php?url=http://loripsum.net/api/' + Math.floor((Math.random() * 7) + 1) + '/short/ul/bq/prude/code/decorete'_x000D_
        };_x000D_
_x000D_
        return eModal_x000D_
            .ajax(params)_x000D_
            .then(function () { alert('Ajax Request complete!!!!', title) });_x000D_
    }_x000D_
_x000D_
    function alertDemo() {_x000D_
        var title = 'Alert modal';_x000D_
        return eModal_x000D_
            .alert('You welcome! Want clean code ?', title)_x000D_
            .then(function () { alert('Alert modal is visible.', title); });_x000D_
    }_x000D_
_x000D_
    function confirmDemo() {_x000D_
        var title = 'Confirm modal callback feedback';_x000D_
        return eModal_x000D_
            .confirm('It is simple enough?', 'Confirm modal')_x000D_
            .then(function (/* DOM */) { alert('Thank you for your OK pressed!', title); })_x000D_
            .fail(function (/*null*/) { alert('Thank you for your Cancel pressed!', title) });_x000D_
    }_x000D_
_x000D_
    function iframeDemo() {_x000D_
        var title = 'Insiders';_x000D_
        return eModal_x000D_
            .iframe('https://www.youtube.com/embed/VTkvN51OPfI', title)_x000D_
            .then(function () { alert('iFrame loaded!!!!', title) });_x000D_
    }_x000D_
_x000D_
    function promptDemo() {_x000D_
        var title = 'Prompt modal callback feedback';_x000D_
        return eModal_x000D_
            .prompt({ size: eModal.size.sm, message: 'What\'s your name?', title: title })_x000D_
            .then(function (input) { alert({ message: 'Hi ' + input + '!', title: title, imgURI: 'https://avatars0.githubusercontent.com/u/4276775?v=3&s=89' }) })_x000D_
            .fail(function (/**/) { alert('Why don\'t you tell me your name?', title); });_x000D_
    }_x000D_
_x000D_
    //#endregion_x000D_
});
_x000D_
.fa{_x000D_
  cursor:pointer;_x000D_
 }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.5/united/bootstrap.min.css" rel="stylesheet" >_x000D_
<link href="http//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">_x000D_
_x000D_
<div class="row" itemprop="about">_x000D_
 <div class="col-sm-1 text-center"></div>_x000D_
 <div class="col-sm-2 text-center">_x000D_
  <div class="row">_x000D_
   <div class="col-sm-10 text-center">_x000D_
    <h3>Ajax</h3>_x000D_
    <p>You must get the message from a remote server? No problem!</p>_x000D_
    <i class="glyphicon glyphicon-cloud fa-5x pointer" title="Try me!"></i>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
 <div class="col-sm-2 text-center">_x000D_
  <div class="row">_x000D_
   <div class="col-sm-10 text-center">_x000D_
    <h3>Alert</h3>_x000D_
    <p>Traditional alert box. Using only text or a lot of magic!?</p>_x000D_
    <i class="glyphicon glyphicon-comment fa-5x pointer" title="Try me!"></i>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
_x000D_
 <div class="col-sm-2 text-center">_x000D_
  <div class="row">_x000D_
   <div class="col-sm-10 text-center">_x000D_
    <h3>Confirm</h3>_x000D_
    <p>Get an okay from user, has never been so simple and clean!</p>_x000D_
    <i class="glyphicon glyphicon-ok fa-5x pointer" title="Try me!"></i>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
 <div class="col-sm-2 text-center">_x000D_
  <div class="row">_x000D_
   <div class="col-sm-10  text-center">_x000D_
    <h3>Prompt</h3>_x000D_
    <p>Do you have a question for the user? We take care of it...</p>_x000D_
    <i class="glyphicon glyphicon-pencil fa-5x pointer" title="Try me!"></i>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
 <div class="col-sm-2 text-center">_x000D_
  <div class="row">_x000D_
   <div class="col-sm-10  text-center">_x000D_
    <h3>iFrame</h3>_x000D_
    <p>IFrames are hard to deal with it? We don't think so!</p>_x000D_
    <i class="glyphicon glyphicon-screenshot fa-5x pointer" title="Try me!"></i>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
 <div class="col-sm-1 text-center"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Prevent Bootstrap Modal from disappearing when clicking outside or pressing escape?

Your code is working when i click out side the modal, but if i use html input field inside modal-body then focus your cursor on that input then press esc key the modal has closed. Click here

Twitter Bootstrap Modal Form Submit

Simple

<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary" onclick="event.preventDefault();document.getElementById('your-form').submit();">Save changes</button>

Using Bootstrap Modal window as PartialView

I do this with mustache.js and templates (you could use any JavaScript templating library).

In my view, I have something like this:

<script type="text/x-mustache-template" id="modalTemplate">
    <%Html.RenderPartial("Modal");%>
</script>

...which lets me keep my templates in a partial view called Modal.ascx:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
    <div>
        <div class="modal-header">
            <a class="close" data-dismiss="modal">&times;</a>
            <h3>{{Name}}</h3>
        </div>
        <div class="modal-body">
            <table class="table table-striped table-condensed">
                <tbody>
                    <tr><td>ID</td><td>{{Id}}</td></tr>
                    <tr><td>Name</td><td>{{Name}}</td></tr>
                </tbody>
            </table>
        </div>
        <div class="modal-footer">
            <a class="btn" data-dismiss="modal">Close</a>
        </div>
    </div>

I create placeholders for each modal in my view:

<%foreach (var item in Model) {%>
    <div data-id="<%=Html.Encode(item.Id)%>"
         id="modelModal<%=Html.Encode(item.Id)%>" 
         class="modal hide fade">
    </div>
<%}%>

...and make ajax calls with jQuery:

<script type="text/javascript">
    var modalTemplate = $("#modalTemplate").html()
    $(".modal[data-id]").each(function() {
        var $this = $(this)
        var id = $this.attr("data-id")
        $this.on("show", function() {
            if ($this.html()) return
            $.ajax({
                type: "POST",
                url: "<%=Url.Action("SomeAction")%>",
                data: { id: id },
                success: function(data) {
                    $this.append(Mustache.to_html(modalTemplate, data))
                }
            })
        })
    })
</script>

Then, you just need a trigger somewhere:

<%foreach (var item in Model) {%>
    <a data-toggle="modal" href="#modelModal<%=Html.Encode(item.Id)%>">
        <%=Html.Encode(item.DutModel.Name)%>
    </a>
<%}%>

How to get twitter bootstrap modal to close (after initial launch)

.modal('hide') manually hides a modal. Use following code to close your bootstrap model

$('#myModal').modal('hide');

Take a look at working codepen here

Or

Try here

_x000D_
_x000D_
$(function () {_x000D_
    $(".custom-close").on('click', function() {_x000D_
        $('#myModal').modal('hide');_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<!-- Button trigger modal -->_x000D_
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">_x000D_
  Launch demo modal_x000D_
</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">_x000D_
  <div class="modal-dialog">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>_x000D_
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        _x000D_
          _x000D_
          <a class="custom-close"> My Custom Close Link </a>_x000D_
          _x000D_
          _x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        <button type="button" class="btn btn-primary">Save changes</button>_x000D_
      </div>_x000D_
    </div><!-- /.modal-content -->_x000D_
  </div><!-- /.modal-dialog -->_x000D_
</div><!-- /.modal -->
_x000D_
_x000D_
_x000D_

jQuery: Load Modal Dialog Contents via Ajax

may be this code may give you some idea.

http://blog.nemikor.com/2009/04/18/loading-a-page-into-a-dialog/

$(document).ready(function() {
    $('#page-help').each(function() {
        var $link = $(this);
        var $dialog = $('<div></div>')
            .load($link.attr('href'))
            .dialog({
                autoOpen: false,
                title: $link.attr('title'),
                width: 500,
                height: 300
            });

        $link.click(function() {
            $dialog.dialog('open');

            return false;
        });
    });
});

Send parameter to Bootstrap modal window?

I found the solution at: Passing data to a bootstrap modal

So simply use:

 $(e.relatedTarget).data('book-id'); 

with 'book-id' is a attribute of modal with pre-fix 'data-'

Multiple modals overlay

Something shorter version based off Yermo Lamers' suggestion, this seems to work alright. Even with basic animations like fade in/out and even crazy batman newspaper rotate. http://jsfiddle.net/ketwaroo/mXy3E/

$('.modal').on('show.bs.modal', function(event) {
    var idx = $('.modal:visible').length;
    $(this).css('z-index', 1040 + (10 * idx));
});
$('.modal').on('shown.bs.modal', function(event) {
    var idx = ($('.modal:visible').length) -1; // raise backdrop after animation.
    $('.modal-backdrop').not('.stacked').css('z-index', 1039 + (10 * idx));
    $('.modal-backdrop').not('.stacked').addClass('stacked');
});

Twitter bootstrap modal-backdrop doesn't disappear

I had the same problem. I discovered it was due to a conflict between Bootstrap and JQueryUI.

Both use the class "close". Changing the class in one or the other fixes this.

Angular 2.0 and Modal Dialog

try to use ng-window, it's allow developer to open and full control multiple windows in single page applications in simple way, No Jquery, No Bootstrap.

enter image description here

Avilable Configration

  • Maxmize window
  • Minimize window
  • Custom size,
  • Custom posation
  • the window is dragable
  • Block parent window or not
  • Center the window or not
  • Pass values to chield window
  • Pass values from chield window to parent window
  • Listening to closing chield window in parent window
  • Listen to resize event with your custom listener
  • Open with maximum size or not
  • Enable and disable window resizing
  • Enable and disable maximization
  • Enable and disable minimization

jQuery dialog popup

Your problem is on the call for the dialog

If you dont initialize the dialog, you don't have to pass "open" for it to show:

$("#dialog").dialog();

Also, this code needs to be on a $(document).ready(); function or be below the elements for it to work.

How to check if bootstrap modal is open, so I can use jquery validate?

As a workaround I personally use a custom global flag to determine whether the modal has been opened or not and I reset it on 'hidden.bs.modal'

Calling a function on bootstrap modal open

You can use the shown event/show event based on what you need:

$( "#code" ).on('shown', function(){
    alert("I want this to appear after the modal has opened!");
});

Demo: Plunker

Update for Bootstrap 3.0

For Bootstrap 3.0 you can still use the shown event but you would use it like this:

$('#code').on('shown.bs.modal', function (e) {
  // do something...
})

See the Bootstrap 3.0 docs here under "Events".

Bootstrap modal appearing under background

I had this issue and the easiest way to fix it was addind z-index greater than 1040 on the modal-dialog div:

<div class="modal-dialog" style="z-index: 1100;">

I believe bootstrap create a div modal-backdrop fade in which in my case has the z-index 1040, so if You put the modal-dialog on top of this, it should not be grey out anymore.

How to pass values arguments to modal.show() function in Bootstrap

I want to share how I did this. I spent the last few days rattling my head with how to pass a couple of parameters to the bootstrap modal dialog. After much head bashing, I came up with a rather simple way of doing this.

Here is my modal code:

<div class="modal fade" id="editGroupNameModal" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div id="editGroupName" class="modal-header">Enter new name for group </div>
        <div class="modal-body">
          <%= form_tag( { action: 'update_group', port: portnum } ) do %>
          <%= text_field_tag( :gid, "", { type: "hidden" })  %>
          <div class="input-group input-group-md">
          <span class="input-group-addon" style="font-size: 16px; padding: 3;" >Name</span>
          <%= text_field_tag( :gname, "", { placeholder: "New name goes here", class: "form-control", aria: {describedby: "basic-addon1"}})  %>
        </div>
        <div class="modal-footer">
          <%= submit_tag("Submit") %>
        </div>
        <% end %>
      </div>
    </div>
  </div>
</div>

And here is the simple javascript to change the gid, and gname input values:

function editGroupName(id, name) {
    $('input#gid').val(id);
    $('input#gname.form-control').val(name);
  }

I just used the onclick event in a link:

//                                                                              &#39; is single quote
//                                                                                   ('1', 'admin')
<a data-toggle="modal" data-target="#editGroupNameModal" onclick="editGroupName(&#39;1&#39;, &#39;admin&#39;); return false;" href="#">edit</a>

The onclick fires first, changing the value property of the input boxes, so when the dialog pops up, values are in place for the form to submit.

I hope this helps someone someday. Cheers.

bootstrap jquery show.bs.modal event won't fire

use this:

$(document).on('show.bs.modal','#myModal', function () {
  alert('hi');
})

Avoid browser popup blockers

Based on Jason Sebring's very useful tip, and on the stuff covered here and there, I found a perfect solution for my case:

Pseudo code with Javascript snippets:

  1. immediately create a blank popup on user action

     var importantStuff = window.open('', '_blank');
    

    (Enrich the call to window.open with whatever additional options you need.)

    Optional: add some "waiting" info message. Examples:

    a) An external HTML page: replace the above line with

     var importantStuff = window.open('http://example.com/waiting.html', '_blank');
    

    b) Text: add the following line below the above one:

     importantStuff.document.write('Loading preview...');
    
  2. fill it with content when ready (when the AJAX call is returned, for instance)

     importantStuff.location.href = 'https://example.com/finally.html';
    

    Alternatively, you could close the window here if you don't need it after all (if ajax request fails, for example - thanks to @Goose for the comment):

     importantStuff.close();
    

I actually use this solution for a mailto redirection, and it works on all my browsers (windows 7, Android). The _blank bit helps for the mailto redirection to work on mobile, btw.

Set bootstrap modal body height by percentage

You've no doubt solved this by now or decided to do something different, but as it has not been answered & I stumbled across this when looking for something similar I thought I'd share my method.

I've taken to using two div sets. One has hidden-xs and is for sm, md & lg device viewing. The other has hidden-sm, -md, -lg and is only for mobile. Now I have a lot more control over the display in my CSS.

You can see a rough idea in this js fiddle where I set the footer and buttons to be smaller when the resolution is of the -xs size.

  <div class="modal-footer">
      <div class="hidden-xs">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="button" class="btn btn-primary">Save changes</button>
      </div>
      <div class="hidden-sm hidden-md hidden-lg sml-footer">
    <button type="button" class="btn btn-xs btn-default" data-dismiss="modal">Close</button>
    <button type="button" class="btn btn-xs btn-primary">Save changes</button>
      </div>
  </div>

Bootstrap 3 modal vertical position center

Here's one other css only method that works pretty well and is based on this: http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/

sass:

.modal {
    height: 100%;

    .modal-dialog {
        top: 50% !important;
        margin-top:0;
        margin-bottom:0;
    }

    //keep proper transitions on fade in
    &.fade .modal-dialog {
        transform: translateY(-100%) !important;
    }
    &.in .modal-dialog {
        transform: translateY(-50%) !important;
    }
}

Trying to make bootstrap modal wider

You could try:

.modal.modal-wide .modal-dialog {
  width: 90%;
}

.modal-wide .modal-body {
  overflow-y: auto;
}

Just add .modal-wide to your classes

Twitter Bootstrap: Print content of modal window

Another solution

Here is a new solution based on Bennett McElwee answer in the same question as mentioned below.

Tested with IE 9 & 10, Opera 12.01, Google Chrome 22 and Firefox 15.0.
jsFiddle example

1.) Add this CSS to your site:

@media screen {
  #printSection {
      display: none;
  }
}

@media print {
  body * {
    visibility:hidden;
  }
  #printSection, #printSection * {
    visibility:visible;
  }
  #printSection {
    position:absolute;
    left:0;
    top:0;
  }
}

2.) Add my JavaScript function

function printElement(elem, append, delimiter) {
    var domClone = elem.cloneNode(true);

    var $printSection = document.getElementById("printSection");

    if (!$printSection) {
        $printSection = document.createElement("div");
        $printSection.id = "printSection";
        document.body.appendChild($printSection);
    }

    if (append !== true) {
        $printSection.innerHTML = "";
    }

    else if (append === true) {
        if (typeof (delimiter) === "string") {
            $printSection.innerHTML += delimiter;
        }
        else if (typeof (delimiter) === "object") {
            $printSection.appendChild(delimiter);
        }
    }

    $printSection.appendChild(domClone);
}?

You're ready to print any element on your site!
Just call printElement() with your element(s) and execute window.print() when you're finished.

Note: If you want to modify the content before it is printed (and only in the print version), checkout this example (provided by waspina in the comments): http://jsfiddle.net/95ezN/121/

One could also use CSS in order to show the additional content in the print version (and only there).


Former solution

I think, you have to hide all other parts of the site via CSS.

It would be the best, to move all non-printable content into a separate DIV:

<body>
  <div class="non-printable">
    <!-- ... -->
  </div>

  <div class="printable">
    <!-- Modal dialog comes here -->
  </div>
</body>

And then in your CSS:

.printable { display: none; }

@media print
{
    .non-printable { display: none; }
    .printable { display: block; }
}

Credits go to Greg who has already answered a similar question: Print <div id="printarea"></div> only?

There is one problem in using JavaScript: the user cannot see a preview - at least in Internet Explorer!

How to add an event after close the modal window?

I find answer. Thanks all but right answer next:

$("#myModal").on("hidden", function () {
  $('#result').html('yes,result');
});

Events here http://bootstrap-ru.com/javascript.php#modals

UPD

For Bootstrap 3.x need use hidden.bs.modal:

$("#myModal").on("hidden.bs.modal", function () {
  $('#result').html('yes,result');
});

Open Bootstrap Modal from code-behind

All of the example above should work just add a document ready action and change the order of how you perform the updates to the texts, also make sure your using Script manager alternatively non of this will work for you. Here is the text within the code behind.

aspx

<div class="modal fade" id="myModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <asp:UpdatePanel ID="upModal" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
                <ContentTemplate>
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4 class="modal-title"><asp:Label ID="lblModalTitle" runat="server" Text=""></asp:Label></h4>
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        </div>
                        <div class="modal-body">
                            <asp:Label ID="lblModalBody" runat="server" Text=""></asp:Label>
                        </div>
                        <div class="modal-footer">
                            <button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">Close</button>
                        </div>
                    </div>
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
    </div>

Code Behind

lblModalTitle.Text = "Validation Errors";
lblModalBody.Text = form.Error;
upModal.Update();
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myModal", "$(document).ready(function () {$('#myModal').modal();});", true);

How to prevent background scrolling when Bootstrap 3 modal open on mobile browsers?

I tried the accepted answer which prevented the body from scrolling but had the issue of scrolling to the top. This should solve both issues.

As a side note, it appears overflow:hidden doesn't work on body for iOS Safari only as iOS Chrome works fine.

var scrollPos = 0;

$('.modal')
    .on('show.bs.modal', function (){
        scrollPos = $('body').scrollTop();
        $('body').css({
            overflow: 'hidden',
            position: 'fixed',
            top : -scrollPos
        });
    })
    .on('hide.bs.modal', function (){
        $('body').css({
            overflow: '',
            position: '',
            top: ''
        }).scrollTop(scrollPos);
    });

Send values from one form to another form

There are several solutions to this but this is the pattern I tend to use.

// Form 1
// inside the button click event
using(Form2 form2 = new Form2()) 
{
    if(form2.ShowDialog() == DialogResult.OK) 
    {
        someControlOnForm1.Text = form2.TheValue;
    }
}

And...

// Inside Form2
// Create a public property to serve the value
public string TheValue 
{
    get { return someTextBoxOnForm2.Text; }
}

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • How to handle the modal closing event in Twitter Bootstrap?

    Updated for Bootstrap 3 and 4

    Bootstrap 3 and Bootstrap 4 docs refer two events you can use.

    hide.bs.modal: This event is fired immediately when the hide instance method has been called.
    hidden.bs.modal: This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete).

    And provide an example on how to use them:

    $('#myModal').on('hidden.bs.modal', function () {
      // do something…
    })
    

    Legacy Bootstrap 2.3.2 answer

    Bootstrap's documentation refers two events you can use.

    hide: This event is fired immediately when the hide instance method has been called.
    hidden: This event is fired when the modal has finished being hidden from the user (will wait for css transitions to complete).

    And provides an example on how to use them:

    $('#myModal').on('hidden', function () {
        // do something…
    })
    

    Auto-click button element on page load using jQuery

    Use the following code

    $("#modal").trigger('click');
    

    Bootstrap modal not displaying

    if you are using custom CSS instead of defining modal class as "modal fade" or "modal fade in" change it to only "modal" in HTML page then try again.

    Closing Bootstrap modal onclick

    You can hide the modal and popup the window to review the carts in validateShipping() function itself.

    function validateShipping(){
    ...
    ...
    $('#product-options').modal('hide');
    //pop the window to select items
    }
    

    Bootstrap: Open Another Modal in Modal

    Why not just change the content of the modal body?

        window.switchContent = function(myFile){
            $('.modal-body').load(myFile);
        };
    

    In the modal just put a link or a button

        <a href="Javascript: switchContent('myFile.html'); return false;">
         click here to load another file</a>
    

    If you just want to switch beetween 2 modals:

        window.switchModal = function(){
            $('#myModal-1').modal('hide');
            setTimeout(function(){ $('#myModal-2').modal(); }, 500);
            // the setTimeout avoid all problems with scrollbars
        };
    

    In the modal just put a link or a button

        <a href="Javascript: switchModal(); return false;">
         click here to switch to the second modal</a>
    

    Bootstrap Modal immediately disappearing

    Had to face the same issue. The reason is same as the @merv. Issue was with a calendar component added to the page.The component itself add the modal feature to be used in the calendar popup.

    So the reasons to break model popup will be one or more of the following

    • Loading more than one bootstrap js versions/files (minified ...)
    • Adding an external calendar to the page where bootstrap is used
    • Adding custom alert or popup library to the page
    • Any other library which adds popup behavior

    Bootstrap Modal before form Submit

    I noticed some of the answers were not triggering the HTML5 required attribute (as stuff was being executed on the action of clicking rather than the action of form send, causing to bypass it when the inputs were empty):

    1. Have a <form id='xform'></form> with some inputs with the required attribute and place a <input type='submit'> at the end.
    2. A confirmation input where typing "ok" is expected <input type='text' name='xconf' value='' required>
    3. Add a modal_1_confirm to your html (to confirm the form of sending).
    4. (on modal_1_confirm) add the id modal_1_accept to the accept button.
    5. Add a second modal_2_errMsg to your html (to display form validation errors).
    6. (on modal_2_errMsg) add the id modal_2_accept to the accept button.
    7. (on modal_2_errMsg) add the id m2_Txt to the displayed text holder.
    8. The JS to intercept before the form is sent:

      $("#xform").submit(function(e){
          var msg, conf, preventSend;
      
          if($("#xform").attr("data-send")!=="ready"){
              msg="Error."; //default error msg
              preventSend=false;
      
              conf=$("[name='xconf']").val().toLowerCase().replace(/^"|"$/g, "");
      
              if(conf===""){
                  msg="The field is empty.";
                  preventSend=true;
              }else if(conf!=="ok"){
                  msg="You didn't write \"ok\" correctly.";
                  preventSend=true;
              }
      
              if(preventSend){ //validation failed, show the error
                  $("#m2_Txt").html(msg); //displayed text on modal_2_errMsg
                  $("#modal_2_errMsg").modal("show");
              }else{ //validation passed, now let's confirm the action
                  $("#modal_1_confirm").modal("show");
              }
      
              e.preventDefault();
              return false;
          }
      });
      

    `9. Also some stuff when clicking the Buttons from the modals:

    $("#modal_1_accept").click(function(){
        $("#modal_1_confirm").modal("hide");
        $("#xform").attr("data-send", "ready").submit();
    });
    
    $("#modal_2_accept").click(function(){
        $("#modal_2_errMsg").modal("hide");
    });
    

    Important Note: So just be careful if you add an extra way to show the modal, as simply clicking the accept button $("#modal_1_accept") will assume the validation passed and it will add the "ready" attribute:

    • The reasoning for this is that $("#modal_1_confirm").modal("show"); is shown only when it passed the validation, so clicking $("#modal_1_accept") should be unreachable without first getting the form validated.

    How to jump to top of browser page

    You can set the scrollTop, like this:

    $('html,body').scrollTop(0);
    

    Or if you want a little animation instead of a snap to the top:

    $('html, body').animate({ scrollTop: 0 }, 'fast');
    

    Disallow Twitter Bootstrap modal window from closing

    Well, this is another solution that some of you guys might be looking for (as I was..)

    My problem was similar, the modal box was closing while the iframe I had inside was loading, so I had to disable the modal dismiss until the Iframe finishes loading, then re-enable.

    The solutions presented here were not working 100%.

    My solution was this:

    showLocationModal = function(loc){
    
        var is_loading = true;
    
        if(is_loading === true) {
    
            is_loading  = false;
            var $modal   = $('#locationModal');
    
            $modal.modal({show:true});
    
            // prevent Modal to close before the iframe is loaded
            $modal.on("hide", function (e) {
                if(is_loading !== true) {
                    e.preventDefault();
                    return false
                }
            });
    
            // populate Modal
            $modal.find('.modal-body iframe').hide().attr('src', location.link).load(function(){
    
                is_loading = true;
         });
    }};
    

    So I temporarily prevent the Modal from closing with:

    $modal.on("hide", function (e) {
        if(is_loading !== true) {
            e.preventDefault();
            return false
        }
    });
    

    But ith the var is_loading that will re enable closing after the Iframe has loaded.

    Using :before CSS pseudo element to add image to modal

    1.this is my answer for your problem.

    .ModalCarrot::before {
    content:'';
    background: url('blackCarrot.png'); /*url of image*/
    height: 16px; /*height of image*/
    width: 33px;  /*width of image*/
    position: absolute;
    }
    

    How to make a JFrame Modal in Swing java

    not sure the contetns of your JFrame, if you ask some input from users, you can use JOptionPane, this also can set JFrame as modal

                JFrame frame = new JFrame();
                String bigList[] = new String[30];
    
                for (int i = 0; i < bigList.length; i++) {
                  bigList[i] = Integer.toString(i);
                }
    
                JOptionPane.showInputDialog(
                        frame, 
                        "Select a item", 
                        "The List", 
                        JOptionPane.PLAIN_MESSAGE,
                        null,
                        bigList,
                        "none");
                }
    

    How to present a modal atop the current view in Swift

    This worked for me in Swift 5.0. Set the Storyboard Id in the identity inspector as "destinationVC".

    @IBAction func buttonTapped(_ sender: Any) {
        let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
        let destVC = storyboard.instantiateViewController(withIdentifier: "destinationVC") as! MyViewController
    
        destVC.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
        destVC.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
    
        self.present(destVC, animated: true, completion: nil)
    }
    

    make bootstrap twitter dialog modal draggable

    i did this:

    $("#myModal").modal({}).draggable();
    

    and it make my very standard/basic modal draggable.

    not sure how/why it worked, but it did.

    Bootstrap 3 with remote Modal

    I did this:

    $('#myModal').on 'shown.bs.modal', (e) ->  
      $(e.target).find('.modal-body').load('http://yourserver.com/content')
    

    Twitter bootstrap remote modal shows same content every time

    For bootstrap 3 you should use:

    $('body').on('hidden.bs.modal', '.modal', function () {
        $(this).removeData('bs.modal');
    });
    

    Close dialog on click (anywhere)

    If the code of the previous posts doesn't work, give this a try:

    $("a.ui-dialog-titlebar-close")[0].click();
    

    Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+)

    There are two ways to do it.

    1. In the method that opens the dialog, pass in the following configuration option disableClose as the second parameter in MatDialog#open() and set it to true:

      export class AppComponent {
        constructor(private dialog: MatDialog){}
        openDialog() {
          this.dialog.open(DialogComponent, { disableClose: true });
        }
      }
      
    2. Alternatively, do it in the dialog component itself.

      export class DialogComponent {
        constructor(private dialogRef: MatDialogRef<DialogComponent>){
          dialogRef.disableClose = true;
        }
      }
      

    Here's what you're looking for:

    <code>disableClose</code> property in material.angular.io

    And here's a Stackblitz demo


    Other use cases

    Here's some other use cases and code snippets of how to implement them.

    Allow esc to close the dialog but disallow clicking on the backdrop to close the dialog

    As what @MarcBrazeau said in the comment below my answer, you can allow the esc key to close the modal but still disallow clicking outside the modal. Use this code on your dialog component:

    import { Component, OnInit, HostListener } from '@angular/core';
    import { MatDialogRef } from '@angular/material';
    @Component({
      selector: 'app-third-dialog',
      templateUrl: './third-dialog.component.html'
    })
    export class ThirdDialogComponent {
      constructor(private dialogRef: MatDialogRef<ThirdDialogComponent>) {      
    }
      @HostListener('window:keyup.esc') onKeyUp() {
        this.dialogRef.close();
      }
    
    }
    

    Prevent esc from closing the dialog but allow clicking on the backdrop to close

    P.S. This is an answer which originated from this answer, where the demo was based on this answer.

    To prevent the esc key from closing the dialog but allow clicking on the backdrop to close, I've adapted Marc's answer, as well as using MatDialogRef#backdropClick to listen for click events to the backdrop.

    Initially, the dialog will have the configuration option disableClose set as true. This ensures that the esc keypress, as well as clicking on the backdrop will not cause the dialog to close.

    Afterwards, subscribe to the MatDialogRef#backdropClick method (which emits when the backdrop gets clicked and returns as a MouseEvent).

    Anyways, enough technical talk. Here's the code:

    openDialog() {
      let dialogRef = this.dialog.open(DialogComponent, { disableClose: true });
      /*
         Subscribe to events emitted when the backdrop is clicked
         NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
         See https://stackoverflow.com/a/41086381 for more info
      */
      dialogRef.backdropClick().subscribe(() => {
        // Close the dialog
        dialogRef.close();
      })
    
      // ...
    }
    

    Alternatively, this can be done in the dialog component:

    export class DialogComponent {
      constructor(private dialogRef: MatDialogRef<DialogComponent>) {
        dialogRef.disableClose = true;
        /*
          Subscribe to events emitted when the backdrop is clicked
          NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
          See https://stackoverflow.com/a/41086381 for more info
        */
        dialogRef.backdropClick().subscribe(() => {
          // Close the dialog
          dialogRef.close();
        })
      }
    }
    

    How to deal with ModalDialog using selenium webdriver?

    I have tried it, it works for you.

    String mainWinHander = webDriver.getWindowHandle();
    
    // code for clicking button to open new window is ommited
    
    //Now the window opened. So here reture the handle with size = 2
    Set<String> handles = webDriver.getWindowHandles();
    
    for(String handle : handles)
    {
        if(!mainWinHander.equals(handle))
        {
            // Here will block for ever. No exception and timeout!
            WebDriver popup = webDriver.switchTo().window(handle);
            // do something with popup
            popup.close();
        }
    }
    

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

    I have found it!

    You can catch the close event using the following code:

     $('div#popup_content').on('dialogclose', function(event) {
         alert('closed');
     });
    

    Obviously I can replace the alert with whatever I need to do.
    Edit: As of Jquery 1.7, the bind() has become on()

    Remove all line breaks from a long string of text

    A method taking into consideration

    • additional white characters at the beginning/end of string
    • additional white characters at the beginning/end of every line
    • various end-line characters

    it takes such a multi-line string which may be messy e.g.

    test_str = '\nhej ho \n aaa\r\n   a\n '
    

    and produces nice one-line string

    >>> ' '.join([line.strip() for line in test_str.strip().splitlines()])
    'hej ho aaa a'
    

    UPDATE: To fix multiple new-line character producing redundant spaces:

    ' '.join([line.strip() for line in test_str.strip().splitlines() if line.strip()])
    

    This works for the following too test_str = '\nhej ho \n aaa\r\n\n\n\n\n a\n '

    Angular2 Error: There is no directive with "exportAs" set to "ngForm"

    I faced the same issue. I had missed the forms module import tag in the app.module.ts

    import { FormsModule } from '@angular/forms';
    
    @NgModule({
        imports: [BrowserModule,
            FormsModule
        ],
    

    How to execute a remote command over ssh with arguments?

    I'm using the following to execute commands on the remote from my local computer:

    ssh -i ~/.ssh/$GIT_PRIVKEY user@$IP "bash -s" < localpath/script.sh $arg1 $arg2
    

    Check if an apt-get package is installed and then install it if it's not on Linux

    I had a similar requirement when running test locally instead of in docker. Basically I only wanted to install any .deb files found if they weren't already installed.

    # If there are .deb files in the folder, then install them
    if [ `ls -1 *.deb 2> /dev/null | wc -l` -gt 0 ]; then
      for file in *.deb; do
        # Only install if not already installed (non-zero exit code)
        dpkg -I ${file} | grep Package: | sed -r 's/ Package:\s+(.*)/\1/g' | xargs dpkg -s
        if [ $? != 0 ]; then
            dpkg -i ${file}
        fi;
      done;
    else
      err "No .deb files found in '$PWD'"
    fi
    

    I guess they only problem I can see is that it doesn't check the version number of the package so if .deb file is a newer version, then this wouldn't overwrite the currently installed package.

    Format cell color based on value in another sheet and cell

    You can also do this with named ranges so you don't have to copy the cells from Sheet1 to Sheet2:

    1. Define a named range, say Sheet1Vals for the column that has the values on which you want to base your condition. You can define a new named range by using the Insert\Name\Define... menu item. Type in your name, then use the cell browser in the Refers to box to select the cells you want in the range. If the range will change over time (add or remove rows) you can use this formula instead of selecting the cells explicitly:

      =OFFSET('SheetName'!$COL$ROW,0,0,COUNTA('SheetName'!$COL:$COL)).

      Add a -1 before the last ) if the column has a header row.

    2. Define a named range, say Sheet2Vals for the column that has the values you want to conditionally format.

    3. Use the Conditional Formatting dialog to create your conditions. Specify Formula Is in the dropdown, then put this for the formula:

      =INDEX(Sheet1Vals, MATCH([FirstCellInRange],Sheet2Vals))=[Condition]

      where [FirstCellInRange] is the address of the cell you want to format and [Condition] is the value your checking.

    For example, if my conditions in Sheet1 have the values of 1, 2 and 3 and the column I'm formatting is column B in Sheet2 then my conditional formats would be something like:

    =INDEX(Sheet1Vals, MATCH(B1,Sheet2Vals))=1
    =INDEX(Sheet1Vals, MATCH(B1,Sheet2Vals))=2
    =INDEX(Sheet1Vals, MATCH(B1,Sheet2Vals))=3
    

    You can then use the format painter to copy these formats to the rest of the cells.

    How to check if an appSettings key exists?

    if (ConfigurationManager.AppSettings.AllKeys.Contains("myKey"))
    {
        // Key exists
    }
    else
    {
        // Key doesn't exist
    }
    

    Setting default value in select drop-down using Angularjs

    Problem 1:

    The generated HTML you're getting is normal. Apparently it's a feature of Angular to be able to use any kind of object as value for a select. Angular does the mapping between the HTML option-value and the value in the ng-model. Also see Umur's comment in this question: How do I set the value property in AngularJS' ng-options?

    Problem 2:

    Make sure you're using the following ng-options:

    <select ng-model="object.item" ng-options="item.id as item.name for item in list" />
    

    And put this in your controller to select a default value:

    object.item = 4
    

    How to set JAVA_HOME in Linux for all users

    For all users, I would recommend placing the following line in /etc/profile

    export JAVA_HOME=$(readlink -f /usr/bin/javac | sed "s:/bin/javac::")
    

    This will update dynamically and works well with the alternatives system. Do note though that the update will only take place in a new login shell.

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

    Five years late to the party.

    It is mentioned in the provided links of the accepted answer, but I think it deserves an explicit answer on SO - dynamically building the query based on provided parameters. E.g.:

    Setup

    -- drop table Person
    create table Person
    (
        PersonId INT NOT NULL IDENTITY(1, 1) CONSTRAINT PK_Person PRIMARY KEY,
        FirstName NVARCHAR(64) NOT NULL,
        LastName NVARCHAR(64) NOT NULL,
        Title NVARCHAR(64) NULL
    )
    GO
    
    INSERT INTO Person (FirstName, LastName, Title)
    VALUES ('Dick', 'Ormsby', 'Mr'), ('Serena', 'Kroeger', 'Ms'), 
        ('Marina', 'Losoya', 'Mrs'), ('Shakita', 'Grate', 'Ms'), 
        ('Bethann', 'Zellner', 'Ms'), ('Dexter', 'Shaw', 'Mr'),
        ('Zona', 'Halligan', 'Ms'), ('Fiona', 'Cassity', 'Ms'),
        ('Sherron', 'Janowski', 'Ms'), ('Melinda', 'Cormier', 'Ms')
    GO
    

    Procedure

    ALTER PROCEDURE spDoSearch
        @FirstName varchar(64) = null,
        @LastName varchar(64) = null,
        @Title varchar(64) = null,
        @TopCount INT = 100
    AS
    BEGIN
        DECLARE @SQL NVARCHAR(4000) = '
            SELECT TOP ' + CAST(@TopCount AS VARCHAR) + ' *
            FROM Person
            WHERE 1 = 1'
    
        PRINT @SQL
    
        IF (@FirstName IS NOT NULL) SET @SQL = @SQL + ' AND FirstName = @FirstName'
        IF (@LastName IS NOT NULL) SET @SQL = @SQL + ' AND FirstName = @LastName'
        IF (@Title IS NOT NULL) SET @SQL = @SQL + ' AND Title = @Title'
    
        EXEC sp_executesql @SQL, N'@TopCount INT, @FirstName varchar(25), @LastName varchar(25), @Title varchar(64)', 
             @TopCount, @FirstName, @LastName, @Title
    END
    GO
    

    Usage

    exec spDoSearch @TopCount = 3
    exec spDoSearch @FirstName = 'Dick'
    

    Pros:

    • easy to write and understand
    • flexibility - easily generate the query for trickier filterings (e.g. dynamic TOP)

    Cons:

    • possible performance problems depending on provided parameters, indexes and data volume

    Not direct answer, but related to the problem aka the big picture

    Usually, these filtering stored procedures do not float around, but are being called from some service layer. This leaves the option of moving away business logic (filtering) from SQL to service layer.

    One example is using LINQ2SQL to generate the query based on provided filters:

        public IList<SomeServiceModel> GetServiceModels(CustomFilter filters)
        {
            var query = DataAccess.SomeRepository.AllNoTracking;
    
            // partial and insensitive search 
            if (!string.IsNullOrWhiteSpace(filters.SomeName))
                query = query.Where(item => item.SomeName.IndexOf(filters.SomeName, StringComparison.OrdinalIgnoreCase) != -1);
            // filter by multiple selection
            if ((filters.CreatedByList?.Count ?? 0) > 0)
                query = query.Where(item => filters.CreatedByList.Contains(item.CreatedById));
            if (filters.EnabledOnly)
                query = query.Where(item => item.IsEnabled);
    
            var modelList = query.ToList();
            var serviceModelList = MappingService.MapEx<SomeDataModel, SomeServiceModel>(modelList);
            return serviceModelList;
        }
    

    Pros:

    • dynamically generated query based on provided filters. No parameter sniffing or recompile hints needed
    • somewhat easier to write for those in the OOP world
    • typically performance friendly, since "simple" queries will be issued (appropriate indexes are still needed though)

    Cons:

    • LINQ2QL limitations may be reached and forcing a downgrade to LINQ2Objects or going back to pure SQL solution depending on the case
    • careless writing of LINQ might generate awful queries (or many queries, if navigation properties loaded)

    How to save an image to localStorage and display it on the next page?

    I have come up with the same issue, instead of storing images, that eventually overflow the local storage, you can just store the path to the image. something like:

    let imagen = ev.target.getAttribute('src');
    arrayImagenes.push(imagen);
    

    Using the AND and NOT Operator in Python

    You should write :

    if (self.a != 0) and (self.b != 0) :
    

    "&" is the bit wise operator and does not suit for boolean operations. The equivalent of "&&" is "and" in Python.

    A shorter way to check what you want is to use the "in" operator :

    if 0 not in (self.a, self.b) :
    

    You can check if anything is part of a an iterable with "in", it works for :

    • Tuples. I.E : "foo" in ("foo", 1, c, etc) will return true
    • Lists. I.E : "foo" in ["foo", 1, c, etc] will return true
    • Strings. I.E : "a" in "ago" will return true
    • Dict. I.E : "foo" in {"foo" : "bar"} will return true

    As an answer to the comments :

    Yes, using "in" is slower since you are creating an Tuple object, but really performances are not an issue here, plus readability matters a lot in Python.

    For the triangle check, it's easier to read :

    0 not in (self.a, self.b, self.c)
    

    Than

    (self.a != 0) and (self.b != 0) and (self.c != 0) 
    

    It's easier to refactor too.

    Of course, in this example, it really is not that important, it's very simple snippet. But this style leads to a Pythonic code, which leads to a happier programmer (and losing weight, improving sex life, etc.) on big programs.

    Accessing the index in 'for' loops?

    If there is no duplicate value in the list:

    for i in ints:
        indx = ints.index(i)
        print(i, indx)
    

    when I run mockito test occurs WrongTypeOfReturnValue Exception

    In my case the problem was caused by trying to mock a static method and forgetting to call mockStatic on the class. Also I forgot to include the class into the @PrepareForTest()

    How can I change the language (to english) in Oracle SQL Developer?

    You can also set language at runtime

    sqldeveloper.exe --AddVMOption=-Duser.language=en
    

    to avoid editing sqldeveloper.conf every time you install new version.

    Foreign Key to multiple tables

    Another approach is to create an association table that contains columns for each potential resource type. In your example, each of the two existing owner types has their own table (which means you have something to reference). If this will always be the case you can have something like this:

    CREATE TABLE dbo.Group
    (
        ID int NOT NULL,
        Name varchar(50) NOT NULL
    )  
    
    CREATE TABLE dbo.User
    (
        ID int NOT NULL,
        Name varchar(50) NOT NULL
    )
    
    CREATE TABLE dbo.Ticket
    (
        ID int NOT NULL,
        Owner_ID int NOT NULL,
        Subject varchar(50) NULL
    )
    
    CREATE TABLE dbo.Owner
    (
        ID int NOT NULL,
        User_ID int NULL,
        Group_ID int NULL,
        {{AdditionalEntity_ID}} int NOT NULL
    )
    
    

    With this solution, you would continue to add new columns as you add new entities to the database and you would delete and recreate the foreign key constraint pattern shown by @Nathan Skerl. This solution is very similar to @Nathan Skerl but looks different (up to preference).

    If you are not going to have a new Table for each new Owner type then maybe it would be good to include an owner_type instead of a foreign key column for each potential Owner:

    CREATE TABLE dbo.Group
    (
        ID int NOT NULL,
        Name varchar(50) NOT NULL
    )  
    
    CREATE TABLE dbo.User
    (
        ID int NOT NULL,
        Name varchar(50) NOT NULL
    )
    
    CREATE TABLE dbo.Ticket
    (
        ID int NOT NULL,
        Owner_ID int NOT NULL,
        Owner_Type string NOT NULL, -- In our example, this would be "User" or "Group"
        Subject varchar(50) NULL
    )
    
    

    With the above method, you could add as many Owner Types as you want. Owner_ID would not have a foreign key constraint but would be used as a reference to the other tables. The downside is that you would have to look at the table to see what the owner types there are since it isn't immediately obvious based upon the schema. I would only suggest this if you don't know the owner types beforehand and they won't be linking to other tables. If you do know the owner types beforehand, I would go with a solution like @Nathan Skerl.

    Sorry if I got some SQL wrong, I just threw this together.

    Could not obtain information about Windows NT group user

    I just got this error and it turns out my AD administrator deleted the service account used by EVERY SQL Server instance in the entire company. Thank goodness AD has its own recycle bin.

    See if you can run the Active Directory Users and Computers utility (%SystemRoot%\system32\dsa.msc), and check to make sure the account you are relying on still exists.

    Replace multiple strings with multiple other strings

    All solutions work great, except when applied in programming languages that closures (e.g. Coda, Excel, Spreadsheet's REGEXREPLACE).

    Two original solutions of mine below use only 1 concatenation and 1 regex.

    Method #1: Lookup for replacement values

    The idea is to append replacement values if they are not already in the string. Then, using a single regex, we perform all needed replacements:

    _x000D_
    _x000D_
    var str = "I have a cat, a dog, and a goat.";
    str = (str+"||||cat,dog,goat").replace(
       /cat(?=[\s\S]*(dog))|dog(?=[\s\S]*(goat))|goat(?=[\s\S]*(cat))|\|\|\|\|.*$/gi, "$1$2$3");
    document.body.innerHTML = str;
    _x000D_
    _x000D_
    _x000D_

    Explanations:

    • cat(?=[\s\S]*(dog)) means that we look for "cat". If it matches, then a forward lookup will capture "dog" as group 1, and "" otherwise.
    • Same for "dog" that would capture "goat" as group 2, and "goat" that would capture "cat" as group 3.
    • We replace with "$1$2$3" (the concatenation of all three groups), which will always be either "dog", "cat" or "goat" for one of the above cases
    • If we manually appended replacements to the string like str+"||||cat,dog,goat", we remove them by also matching \|\|\|\|.*$, in which case the replacement "$1$2$3" will evaluate to "", the empty string.

    Method #2: Lookup for replacement pairs

    One problem with Method #1 is that it cannot exceed 9 replacements at a time, which is the maximum number of back-propagation groups. Method #2 states not to append just replacement values, but replacements directly:

    _x000D_
    _x000D_
    var str = "I have a cat, a dog, and a goat.";
    str = (str+"||||,cat=>dog,dog=>goat,goat=>cat").replace(
       /(\b\w+\b)(?=[\s\S]*,\1=>([^,]*))|\|\|\|\|.*$/gi, "$2");
    document.body.innerHTML = str;
    _x000D_
    _x000D_
    _x000D_

    Explanations:

    • (str+"||||,cat=>dog,dog=>goat,goat=>cat") is how we append a replacement map to the end of the string.
    • (\b\w+\b) states to "capture any word", that could be replaced by "(cat|dog|goat) or anything else.
    • (?=[\s\S]*...) is a forward lookup that will typically go to the end of the document until after the replacement map.
      • ,\1=> means "you should find the matched word between a comma and a right arrow"
      • ([^,]*) means "match anything after this arrow until the next comma or the end of the doc"
    • |\|\|\|\|.*$ is how we remove the replacement map.

    How do I put a clear button inside my HTML text input box like the iPhone does?

    Of course the best approach is to use the ever-more-supported <input type="search" />.

    Anyway for a bit of coding fun I thought that it could be achieved also using the form's reset button, and this is the working result (it is worth noting that you cannot have other inputs in the form but the search field with this approach, or the reset button will erase them too), no javascript needed:

    _x000D_
    _x000D_
    form{
        position: relative;
        width: 200px;
    }
    
    form input {
        width: 100%;
        padding-right: 20px;
        box-sizing: border-box;
    }
    
    form input:placeholder-shown + button{
      opacity: 0;
      pointer-events: none;
    } 
    
    form button {
        position: absolute;
        border: none;
        display: block;
        width: 15px;
        height: 15px;
        line-height: 16px;
        font-size: 12px;
        border-radius: 50%;
        top: 0;
        bottom: 0;
        right: 5px;
        margin: auto;
        background: #ddd;
        padding: 0;
        outline: none;
        cursor: pointer;
        transition: .1s;
    }
    _x000D_
    <form>
            <input type="text" placeholder=" " />
            <button type="reset">&times;</button>
    </form>
    _x000D_
    _x000D_
    _x000D_

    Get image data url in JavaScript?

    This is all you need to read.

    https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsBinaryString

    var height = 200;
    var width  = 200;
    
    canvas.width  = width;
    canvas.height = height;
    
    var ctx = canvas.getContext('2d');
    
    ctx.strokeStyle = '#090';
    ctx.beginPath();
    ctx.arc(width/2, height/2, width/2 - width/10, 0, Math.PI*2);
    ctx.stroke();
    
    canvas.toBlob(function (blob) {
      //consider blob is your file object
    
      var reader = new FileReader();
    
      reader.onload = function () {
        console.log(reader.result);
      }
    
      reader.readAsBinaryString(blob);
    });
    

    java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

    I had the same problem, my code is below:

    private Connection conn = DriverManager.getConnection(Constant.MYSQL_URL, Constant.MYSQL_USER, Constant.MYSQL_PASSWORD);
    private Statement stmt = conn.createStatement();
    

    I have not loaded the driver class, but it works locally, I can query the results from MySQL, however, it does not work when I deploy it to Tomcat, and the errors below occur:

    No suitable driver found for jdbc:mysql://172.16.41.54:3306/eduCloud
    

    so I loaded the driver class, as below, when I saw other answers posted:

    Class.forName("com.mysql.jdbc.Driver");
    

    It works now! I don't know why it works well locally, I need your help, thank you so much!

    How to change the locale in chrome browser

    [on hold: broken in Chrome 72; reported to work in Chrome 71]

    The "Quick Language Switcher" extension may help too: https://chrome.google.com/webstore/detail/quick-language-switcher/pmjbhfmaphnpbehdanbjphdcniaelfie

    The Quick Language Switcher extension allows the user to supersede the locale the browser is currently using in favor of the value chosen through the extension.

    Adding a new line/break tag in XML

    Had same issue when I had to develop a fixed length field format.

    Usually we do not use line separator for binary files but For some reason our customer wished to add a line break as separator between records. They set

    < record_delimiter value="\n"/ >

    but this didn't work as records got two additional characters:
    < record1 > \n < record2 > \n.... and so on.

    Did following change and it just worked.

    < record_delimiter value="\n"/> => < record_delimiter value="&#xA;"/ >

    After unmarshaling Java interprets as new line character.

    Unzip files programmatically in .net

    String ZipPath = @"c:\my\data.zip";
    String extractPath = @"d:\\myunzips";
    ZipFile.ExtractToDirectory(ZipPath, extractPath);
    

    To use the ZipFile class, you must add a reference to the System.IO.Compression.FileSystem assembly in your project

    How do you change the character encoding of a postgres database?

    # dump into file
    pg_dump myDB > /tmp/myDB.sql
    
    # create an empty db with the right encoding (on older versions the escaped single quotes are needed!)
    psql -c 'CREATE DATABASE "tempDB" WITH OWNER = "myself" LC_COLLATE = '\''de_DE.utf8'\'' TEMPLATE template0;'
    
    # import in the new DB
    psql -d tempDB -1 -f /tmp/myDB.sql
    
    # rename databases
    psql -c 'ALTER DATABASE "myDB" RENAME TO "myDB_wrong_encoding";' 
    psql -c 'ALTER DATABASE "tempDB" RENAME TO "myDB";'
    
    # see the result
    psql myDB -c "SHOW LC_COLLATE"   
    

    C# Encoding a text string with line breaks

    Try \n\n , it will work! :)

    public async Task AjudaAsync(IDialogContext context, LuisResult result){
    await context.PostAsync("How can I help you? \n\n 1.To Schedule \n\n 2.Consult");
    context.Wait(MessageReceived);
    }
    

    Git Clone from GitHub over https with two-factor authentication

    To everyone struggling, what worked for me was creating personal access token and then using it as a username AND password (in the prompt that opened).

    Find element in List<> that contains a value

    Either use LINQ:

    var value = MyList.First(item => item.name == "foo").value;
    

    (This will just find the first match, of course. There are lots of options around this.)

    Or use Find instead of FindIndex:

    var value = MyList.Find(item => item.name == "foo").value;
    

    I'd strongly suggest using LINQ though - it's a much more idiomatic approach these days.

    (I'd also suggest following the .NET naming conventions.)

    How do I center a Bootstrap div with a 'spanX' class?

    Update

    As of BS3 there's a .center-block helper class. From the docs:

    // Classes
    .center-block {
      display: block;
      margin-left: auto;
      margin-right: auto;
    }
    
    // Usage as mixins
    .element {
      .center-block();
    }
    

    There is hidden complexity in this seemingly simple problem. All the answers given have some issues.

    1. Create a Custom Class (Major Gotcha)

    Create .col-centred class, but there is a major gotcha.

    .col-centred {
       float: none !important;
       margin: 0 auto;
    }
    
    <!-- Bootstrap 3 -->
    <div class="col-lg-6 col-centred">
      Centred content.
    </div>
    <!-- Bootstrap 2 -->
    <div class="span-6 col-centred">
      Centred content.
    </div>
    

    The Gotcha

    Bootstrap requires columns add up to 12. If they do not they will overlap, which is a problem. In this case the centred column will overlap the column above it. Visually the page may look the same, but mouse events will not work on the column being overlapped (you can't hover or click links, for example). This is because mouse events are registering on the centred column that's overlapping the elements you try to click.

    The Fixes

    You can resolve this issue by using a clearfix element. Using z-index to bring the centred column to the bottom will not work because it will be overlapped itself, and consequently mouse events will work on it.

    <div class="row">
      <div class="col-lg-12">
        I get overlapped by `col-lg-7 centered` unless there's a clearfix.
      </div>
      <div class="clearfix"></div>
      <div class="col-lg-7 centred">
      </div>
    </div>
    

    Or you can isolate the centred column in its own row.

    <div class="row">
      <div class="col-lg-12">
      </div>
    </div>
    <div class="row">
      <div class="col-lg-7 centred">
        Look I am in my own row.
      </div>
    </div>
    

    2. Use col-lg-offset-x or spanx-offset (Major Gotcha)

    <!-- Bootstrap 3 -->
    <div class="col-lg-6 col-lg-offset-3">
      Centred content.
    </div>
    <!-- Bootstrap 2 -->
    <div class="span-6 span-offset-3">
      Centred content.
    </div>
    

    The first problem is that your centred column must be an even number because the offset value must divide evenly by 2 for the layout to be centered (left/right).

    Secondly, as some have commented, using offsets is a bad idea. This is because when the browser resizes the offset will turn into blank space, pushing the actual content down the page.

    3. Create an Inner Centred Column

    This is the best solution in my opinion. No hacking required and you don't mess around with the grid, which could cause unintended consequences, as per solutions 1 and 2.

    .col-centred {
       margin: 0 auto;
    }
    
    <div class="row">
      <div class="col-lg-12">
        <div class="centred">
            Look I am in my own row.
        </div>
      </div>
    </div>
    

    2D cross-platform game engine for Android and iOS?

    I currently use Corona for business applications with great success. As far as games go, I'm under the impression that it doesn't provide the performance that some of the other cross-platform development engines do. It is worth noting that Carlos (founder of Ansca Mobile/Corona SDK) has started another company on a competing engine; Lanica Platino Engine for Appcelerator Titanium. While I haven't worked with this personally, it does look promising. Keep in mind, however, that it comes with a $999/yr price tag.

    All that said, I have been researching Moai for a little while now (since I am already familiar with Lua syntax) and it does seem promising. The fact that it can compile for multiple platforms, not limited to mobile environments, is appealing.

    Multimedia Fusion 2 is also a worth contender, considering the complexity of games produced and the performance realized from them. Vincere Totus Astrum (http://gamesare.com) comes to mind.

    Encoding conversion in java

    You don't need a library beyond the standard one - just use Charset. (You can just use the String constructors and getBytes methods, but personally I don't like just working with the names of character encodings. Too much room for typos.)

    EDIT: As pointed out in comments, you can still use Charset instances but have the ease of use of the String methods: new String(bytes, charset) and String.getBytes(charset).

    See "URL Encoding (or: 'What are those "%20" codes in URLs?')".

    ImportError: No module named 'django.core.urlresolvers'

    urlresolver has been removed in the higher version of Django - Please upgrade your django installation. I fixed it using the following command.

    pip install django==2.0 --upgrade
    

    Get value (String) of ArrayList<ArrayList<String>>(); in Java

    The right way to iterate on a list inside list is:

    //iterate on the general list
    for(int i = 0 ; i < collection.size() ; i++) {
        ArrayList<String> currentList = collection.get(i);
        //now iterate on the current list
        for (int j = 0; j < currentList.size(); j++) {
            String s = currentList.get(1);
        }
    }
    

    Select From all tables - MySQL

    Improve to @inno answer

    delimiter //
    
    DROP PROCEDURE IF EXISTS get_product;  
    CREATE PROCEDURE get_product()
    BEGIN
       DECLARE i VARCHAR(100); 
       DECLARE cur1 CURSOR FOR SELECT DISTINCT table_name FROM information_schema.columns WHERE COLUMN_NAME IN ('Product');
       OPEN cur1;
    
       read_loop: LOOP
           FETCH cur1 INTO i;
        
           SELECT i; -- printing table name
        
           SET @s = CONCAT('select * from ', i, ' where Product like %XYZ%'); 
           PREPARE stmt1 FROM @s;
           EXECUTE stmt1;
           DEALLOCATE PREPARE stmt1;
    
       END LOOP read_loop;
    
       CLOSE cur1;
    END//
    
    delimiter ;
    
    call get_product();
    

    SQL alias for SELECT statement

    You could store this into a temporary table.

    So instead of doing the CTE/sub query you would use a temp table.

    Good article on these here http://codingsight.com/introduction-to-temporary-tables-in-sql-server/

    Show a popup/message box from a Windows batch file

    Few more ways.

    1) The geekiest and hackiest - it uses the IEXPRESS to create small exe that will create a pop-up with a single button (it can create two more types of pop-up messages). Works on EVERY windows from XP and above:

    ;@echo off
    ;setlocal
    
    ;set ppopup_executable=popupe.exe
    ;set "message2=click OK to continue"
    ;
    ;del /q /f %tmp%\yes >nul 2>&1
    ;
    ;copy /y "%~f0" "%temp%\popup.sed" >nul 2>&1
    
    ;(echo(FinishMessage=%message2%)>>"%temp%\popup.sed";
    ;(echo(TargetName=%cd%\%ppopup_executable%)>>"%temp%\popup.sed";
    ;(echo(FriendlyName=%message1_title%)>>"%temp%\popup.sed"
    ;
    ;iexpress /n /q /m %temp%\popup.sed
    ;%ppopup_executable%
    ;rem del /q /f %ppopup_executable% >nul 2>&1
    
    ;pause
    
    ;endlocal
    ;exit /b 0
    
    
    [Version]
    Class=IEXPRESS
    SEDVersion=3
    [Options]
    PackagePurpose=InstallApp
    ShowInstallProgramWindow=1
    HideExtractAnimation=1
    UseLongFileName=0
    InsideCompressed=0
    CAB_FixedSize=0
    CAB_ResvCodeSigning=0
    RebootMode=N
    InstallPrompt=%InstallPrompt%
    DisplayLicense=%DisplayLicense%
    FinishMessage=%FinishMessage%
    TargetName=%TargetName%
    FriendlyName=%FriendlyName%
    AppLaunched=%AppLaunched%
    PostInstallCmd=%PostInstallCmd%
    AdminQuietInstCmd=%AdminQuietInstCmd%
    UserQuietInstCmd=%UserQuietInstCmd%
    SourceFiles=SourceFiles
    [SourceFiles]
    SourceFiles0=C:\Windows\System32\
    [SourceFiles0]
    %FILE0%=
    
    
    [Strings]
    AppLaunched=subst.exe
    PostInstallCmd=<None>
    AdminQuietInstCmd=
    UserQuietInstCmd=
    FILE0="subst.exe"
    DisplayLicense=
    InstallPrompt=
    

    2) Using MSHTA. Also works on every windows machine from XP and above (despite the OP do not want "external" languages the JavaScript here is minimized). Should be saved as .bat:

    @if (true == false) @end /*!
    @echo off
    mshta "about:<script src='file://%~f0'></script><script>close()</script>" %*
    goto :EOF */
    
    alert("Hello, world!");
    

    or in one line:

    mshta "about:<script>alert('Hello, world!');close()</script>"
    

    or

    mshta "javascript:alert('message');close()"
    

    or

    mshta.exe vbscript:Execute("msgbox ""message"",0,""title"":close")
    

    3) Here's parameterized .bat/jscript hybrid (should be saved as bat). It again uses JavaScript despite the OP request but as it is a bat it can be called as a bat file without worries. It uses POPUP which allows a little bit more control than the more popular MSGBOX. It uses WSH, but not MSHTA like in the example above.

     @if (@x)==(@y) @end /***** jscript comment ******
         @echo off
    
         cscript //E:JScript //nologo "%~f0" "%~nx0" %*
         exit /b 0
    
     @if (@x)==(@y) @end ******  end comment *********/
    
    
    var wshShell = WScript.CreateObject("WScript.Shell");
    var args=WScript.Arguments;
    var title=args.Item(0);
    
    var timeout=-1;
    var pressed_message="button pressed";
    var timeout_message="timed out";
    var message="";
    
    function printHelp() {
        WScript.Echo(title + "[-title Title] [-timeout m] [-tom \"Time-out message\"] [-pbm \"Pressed button message\"]  [-message \"pop-up message\"]");
    }
    
    if (WScript.Arguments.Length==1){
        runPopup();
        WScript.Quit(0);
    }
    
    if (args.Item(1).toLowerCase() == "-help" || args.Item(1).toLowerCase() == "-h" ) {
        printHelp();
        WScript.Quit(0);
    }
    
    if (WScript.Arguments.Length % 2 == 0 ) {
        WScript.Echo("Illegal arguments ");
        printHelp();
        WScript.Quit(1);
    }
    
    for (var arg = 1 ; arg<args.Length;arg=arg+2) {
    
        if (args.Item(arg).toLowerCase() == "-title") {
            title = args.Item(arg+1);
        }
    
        if (args.Item(arg).toLowerCase() == "-timeout") {
            timeout = parseInt(args.Item(arg+1));
            if (isNaN(timeout)) {
                timeout=-1;
            }
        }
    
        if (args.Item(arg).toLowerCase() == "-tom") {
            timeout_message = args.Item(arg+1);
        }
    
        if (args.Item(arg).toLowerCase() == "-pbm") {
            pressed_message = args.Item(arg+1);
        }
    
        if (args.Item(arg).toLowerCase() == "-message") {
            message = args.Item(arg+1);
        }
    }
    
    function runPopup(){
        var btn = wshShell.Popup(message, timeout, title, 0x0 + 0x10);
    
        switch(btn) {
            // button pressed.
            case 1:
                WScript.Echo(pressed_message);
                break;
    
            // Timed out.
            case -1:
               WScript.Echo(timeout_message);
               break;
        }
    }
    
    runPopup();
    

    4) and one jscript.net/.bat hybrid (should be saved as .bat) .This time it uses .NET and compiles a small .exe file that could be deleted:

    @if (@X)==(@Y) @end /****** silent jscript comment ******
    
    @echo off
    ::::::::::::::::::::::::::::::::::::
    :::       compile the script    ::::
    ::::::::::::::::::::::::::::::::::::
    setlocal
    
    
    ::if exist "%~n0.exe" goto :skip_compilation
    
    :: searching the latest installed .net framework
    for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
        if exist "%%v\jsc.exe" (
            rem :: the javascript.net compiler
            set "jsc=%%~dpsnfxv\jsc.exe"
            goto :break_loop
        )
    )
    echo jsc.exe not found && exit /b 0
    :break_loop
    
    
    
    call %jsc% /nologo /out:"%~n0.exe" "%~f0" 
    ::::::::::::::::::::::::::::::::::::
    :::       end of compilation    ::::
    ::::::::::::::::::::::::::::::::::::
    :skip_compilation
    
    ::
    ::::::::::
    "%~n0.exe" %*
    ::::::::
    ::
    endlocal
    exit /b 0
    
    ****** end of jscript comment ******/
    
    import System;
    import System.Windows;
    import System.Windows.Forms
    
    var arguments:String[] = Environment.GetCommandLineArgs();
    MessageBox.Show(arguments[1],arguments[0]);
    

    5) and at the end one single call to powershell that creates a pop-up (can be called from command line or from batch if powershell is installed):

    powershell [Reflection.Assembly]::LoadWithPartialName("""System.Windows.Forms""");[Windows.Forms.MessageBox]::show("""Hello World""", """My PopUp Message Box""")
    

    6) And the dbenham's approach seen here

    start "" cmd /c "echo(&echo(&echo              Hello world!     &echo(&pause>nul"
    

    7) For a system tray notifications you can try this:

    call SystemTrayNotification.bat  -tooltip warning -time 3000 -title "Woow" -text "Boom" -icon question
    

    Find all matches in workbook using Excel VBA

    Function GetSearchArray(strSearch)
    Dim strResults As String
    Dim SHT As Worksheet
    Dim rFND As Range
    Dim sFirstAddress
    For Each SHT In ThisWorkbook.Worksheets
        Set rFND = Nothing
        With SHT.UsedRange
            Set rFND = .Cells.Find(What:=strSearch, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlRows, SearchDirection:=xlNext, MatchCase:=False)
            If Not rFND Is Nothing Then
                sFirstAddress = rFND.Address
                Do
                    If strResults = vbNullString Then
                        strResults = "Worksheet(" & SHT.Index & ").Range(" & Chr(34) & rFND.Address & Chr(34) & ")"
                    Else
                        strResults = strResults & "|" & "Worksheet(" & SHT.Index & ").Range(" & Chr(34) & rFND.Address & Chr(34) & ")"
                    End If
                    Set rFND = .FindNext(rFND)
                Loop While Not rFND Is Nothing And rFND.Address <> sFirstAddress
            End If
        End With
    Next
    If strResults = vbNullString Then
        GetSearchArray = Null
    ElseIf InStr(1, strResults, "|", 1) = 0 Then
        GetSearchArray = Array(strResults)
    Else
        GetSearchArray = Split(strResults, "|")
    End If
    End Function
    
    Sub test2()
    For Each X In GetSearchArray("1")
        Debug.Print X
    Next
    End Sub
    

    Careful when doing a Find Loop that you don't get yourself into an infinite loop... Reference the first found cell address and compare after each "FindNext" statement to make sure it hasn't returned back to the first initially found cell.

    Force re-download of release dependency using Maven

    Just delete ~/.m2/repository...../actual_path where the invalid LOC is coming as it forces to re-download the deleted jar files. Dont delete the whole repository folder instead delete the specific folder from where the error is coming.

    How do you uninstall all dependencies listed in package.json (NPM)?

    // forcibly remove and reinstall all package dependencies
    ren package.json package.json-bak
    echo {} > package.json
    npm prune
    del package.json
    ren package.json-bak package.json
    npm i
    

    This essentially creates a fake, empty package.json, calls npm prune to remove everything in node_modules, restores the original package.json and re-installs everything.

    Some of the other solutions might be more elegant, but I suspect this is faster and exhaustive. On other threads I've seen people suggest just deleting the node_modules directory, but at least for windows, this causes npm to choke afterward because the bin directory goes missing. Maybe on linux it gets restored properly, but not windows.

    convert string to specific datetime format?

    More formats:

     require 'date'
    
     date = "01/07/2016 09:17AM"
     DateTime.parse(date).strftime("%A, %b %d")
     #=> Friday, Jul 01
    
     DateTime.parse(date).strftime("%m/%d/%Y")
     #=> 07/01/2016
    
     DateTime.parse(date).strftime("%m-%e-%y %H:%M")
     #=> 07- 1-16 09:17
    
     DateTime.parse(date).strftime("%b %e")
     #=> Jul  1
    
     DateTime.parse(date).strftime("%l:%M %p")
     #=>  9:17 AM
    
     DateTime.parse(date).strftime("%B %Y")
     #=> July 2016
     DateTime.parse(date).strftime("%b %d, %Y")
     #=> Jul 01, 2016
     DateTime.parse(date).strftime("%a, %e %b %Y %H:%M:%S %z")
     #=> Fri,  1 Jul 2016 09:17:00 +0200
     DateTime.parse(date).strftime("%Y-%m-%dT%l:%M:%S%z")
     #=> 2016-07-01T 9:17:00+0200
     DateTime.parse(date).strftime("%I:%M:%S %p")
     #=> 09:17:00 AM
     DateTime.parse(date).strftime("%H:%M:%S")
     #=> 09:17:00
     DateTime.parse(date).strftime("%e %b %Y %H:%M:%S%p")
     #=>  1 Jul 2016 09:17:00AM
     DateTime.parse(date).strftime("%d.%m.%y")
     #=> 01.07.16
     DateTime.parse(date).strftime("%A, %d %b %Y %l:%M %p")
     #=> Friday, 01 Jul 2016  9:17 AM
    

    Java get String CompareTo as a comparator object

    The Arrays class has versions of sort() and binarySearch() which don't require a Comparator. For example, you can use the version of Arrays.sort() which just takes an array of objects. These methods call the compareTo() method of the objects in the array.

    org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class

    Just leaving this here for future visitors:

    In my case the /WEB-INF/classes directory was missing. If you are using Eclipse, make sure the .settings/org.eclipse.wst.common.component is correct (Deployment Assembly in the project settings).

    In my case it was missing

        <wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
        <wb-resource deploy-path="/WEB-INF/classes" source-path="/src/test/resources"/>
    

    This file is also a common source of errors as mentioned by Anuj (missing dependencies of other projects).

    Otherwise, hopefully the other answers (or the "Problems" tab) will help you.

    How to calculate growth with a positive and negative number?

    These questions are answering the question of "how should I?" without considering the question "should I?" A change in the value of a variable that takes positive and negative values is fairly meaning less, statistically speaking. The suggestion to "shift" might work well for some variables (e.g. temperature which can be shifted to a kelvin scale or something to take care of the problem) but very poorly for others, where negativity has a precise implication for direction. For example net income or losses. Operating at a loss (negative income) has a precise meaning in this context, and moving from -50 to 30 is not in any way the same for this context as moving from 110 to 190, as a previous post suggests. These percentage changes should most likely be reported as "NA".

    python inserting variable string as file name

    Very similar to peixe.
    You don't have to mention the number if the variables you add as parameters are in order of appearance

    f = open('{}.csv'.format(name), 'wb')
    

    Another option - the f-string formatting (ref):

    f = open(f"{name}.csv", 'wb') 
    

    Remove all occurrences of char from string

    Using

    public String replaceAll(String regex, String replacement)
    

    will work.

    Usage would be str.replace("X", "");.

    Executing

    "Xlakjsdf Xxx".replaceAll("X", "");
    

    returns:

    lakjsdf xx
    

    How to redirect to a different domain using NGINX?

    Temporary redirect

    rewrite ^ http://www.RedirectToThisDomain.com$request_uri? redirect;
    

    Permanent redirect

    rewrite ^ http://www.RedirectToThisDomain.com$request_uri? permanent;
    

    In nginx configuration file for specific site:

    server {    
        server_name www.example.com;
        rewrite ^ http://www.RedictToThisDomain.com$request_uri? redirect;
    
    }
    

    How do I delete virtual interface in Linux?

    Have you tried:

    ifconfig 10:35978f0 down

    As the physical interface is 10 and the virtual aspect is after the colon :.

    See also https://www.cyberciti.biz/faq/linux-command-to-remove-virtual-interfaces-or-network-aliases/

    Concatenating Matrices in R

    Sounds like you're looking for rbind:

    > a<-matrix(nrow=10,ncol=5)
    > b<-matrix(nrow=20,ncol=5)
    > dim(rbind(a,b))
    [1] 30  5
    

    Similarly, cbind stacks the matrices horizontally.

    I am not entirely sure what you mean by the last question ("Can I do this for matrices of different rows and columns.?")

    Set start value for column with autoincrement

    From Resetting SQL Server Identity Columns:

    Retrieving the identity for the table Employees:

    DBCC checkident ('Employees')
    

    Repairing the identity seed (if for some reason the database is inserting duplicate identities):

    DBCC checkident ('Employees', reseed)
    

    Changing the identity seed for the table Employees to 1000:

    DBCC checkident ('Employees', reseed, 1000)
    

    The next row inserted will begin at 1001.

    How to set page content to the middle of screen?

    HTML

    <!DOCTYPE html>
    <html>
        <head>
            <title>Center</title>        
        </head>
        <body>
            <div id="main_body">
              some text
            </div>
        </body>
    </html>
    

    CSS

    body
    {
       width: 100%;
       Height: 100%;
    }
    #main_body
    {
        background: #ff3333;
        width: 200px;
        position: absolute;
    }?
    

    JS ( jQuery )

    $(function(){
        var windowHeight = $(window).height();
        var windowWidth = $(window).width();
        var main = $("#main_body");    
        $("#main_body").css({ top: ((windowHeight / 2) - (main.height() / 2)) + "px",
                              left:((windowWidth / 2) - (main.width() / 2)) + "px" });
    });
    

    See example here

    Left align block of equations

    You can use \begin{flalign}, like the example bellow:

    \begin{flalign}
        &f(x) = -1.25x^{2} + 1.5x&
    \end{flalign}
    

    How should I import data from CSV into a Postgres table using pgAdmin 3?

    assuming you have a SQL table called mydata - you can load data from a csv file as follows:

    COPY MYDATA FROM '<PATH>/MYDATA.CSV' CSV HEADER;
    

    For more details refer to: http://www.postgresql.org/docs/9.2/static/sql-copy.html

    Select2 open dropdown on focus

    Somehow select2Focus didn't work here with empty selection, couldn't figured out the issue, therefore I added manual control when after focus event auto open get's triggered.

    Here is coffeescript:

    $("#myid").select2()
      .on 'select2-blur', ->
        $(this).data('select2-auto-open', 'true')
      .on 'select2-focus', ->
        $(this).data('select2').open() if $(this).data('select2-auto-open') != 'false'
      .on 'select2-selecting', ->
        $(this).data('select2-auto-open', 'false')
    

    Converting String Array to an Integer Array

    Java has a method for this, "convertStringArrayToIntArray".

    String numbers = sc.nextLine();
    int[] intArray = convertStringArrayToIntArray(numbers.split(", "));
    

    Passing functions with arguments to another function in Python?

    Do you mean this?

    def perform(fun, *args):
        fun(*args)
    
    def action1(args):
        # something
    
    def action2(args):
        # something
    
    perform(action1)
    perform(action2, p)
    perform(action3, p, r)
    

    Javascript sleep/delay/wait function

    You can use this -

    function sleep(milliseconds) {
        var start = new Date().getTime();
        for (var i = 0; i < 1e7; i++) {
            if ((new Date().getTime() - start) > milliseconds){
                break;
            }
        }
    }
    

    sudo echo "something" >> /etc/privilegedFile doesn't work

    The problem is that the shell does output redirection, not sudo or echo, so this is being done as your regular user.

    Try the following code snippet:

    sudo sh -c "echo 'something' >> /etc/privilegedfile"
    

    Perl: Use s/ (replace) and return new string

    print "bla: ", $_, "\n" if ($_ = $myvar) =~ s/a/b/g or 1;
    

    Convert Unix timestamp to a date string

    With GNU's date you can do:

    date -d "@$TIMESTAMP"
    
    # date -d @0
    Wed Dec 31 19:00:00 EST 1969
    

    (From: BASH: Convert Unix Timestamp to a Date)

    On OS X, use date -r.

    date -r "$TIMESTAMP"
    

    Alternatively, use strftime(). It's not available directly from the shell, but you can access it via gawk. The %c specifier displays the timestamp in a locale-dependent manner.

    echo "$TIMESTAMP" | gawk '{print strftime("%c", $0)}'
    
    # echo 0 | gawk '{print strftime("%c", $0)}'
    Wed 31 Dec 1969 07:00:00 PM EST
    

    How can I trigger the click event of another element in ng-click using angularjs?

    One more directive

    html

    <btn-file-selector/>
    

    code

    .directive('btnFileSelector',[function(){
      return {
        restrict: 'AE', 
        template: '<div></div>', 
        link: function(s,e,a){
    
          var el = angular.element(e);
          var button = angular.element('<button type="button" class="btn btn-default btn-upload">Add File</button>'); 
          var fileForm = angular.element('<input type="file" style="display:none;"/>'); 
    
          fileForm.on('change', function(){
             // Actions after the file is selected
             console.log( fileForm[0].files[0].name );
          });
    
          button.bind('click',function(){
            fileForm.click();
          });     
    
    
         el.append(fileForm);
         el.append(button);
        }
      }  
    }]); 
    

    removing table border

    Use table style Border-collapse at the table level

    How do I delete NuGet packages that are not referenced by any project in my solution?

    VS2019 > Tools > Options > Nuget Package Manager > General > Click on "Clear All Nuger Cache(s)"

    How to compare two tags with git?

    If source code is on Github, you can use their comparing tool: https://help.github.com/articles/comparing-commits-across-time/

    Get git branch name in Jenkins Pipeline/Jenkinsfile

    Switching to a multibranch pipeline allowed me to access the branch name. A regular pipeline was not advised.

    Get div's offsetTop positions in React

    A better solution with ref to avoid findDOMNode that is discouraged.

    ...
    onScroll() {
        let offsetTop  = this.instance.getBoundingClientRect().top;
    }
    ...
    render() {
    ...
    <Component ref={(el) => this.instance = el } />
    ...
    

    ASP.NET Core Identity - get current user

    I have put something like this in my Controller class and it worked:

    IdentityUser user = await userManager.FindByNameAsync(HttpContext.User.Identity.Name);
    

    where userManager is an instance of Microsoft.AspNetCore.Identity.UserManager class (with all weird setup that goes with it).

    Transfer data from one database to another database

    For those on Azure, follow these modified instructions from Virus:

    1. Open SSMS.
    2. Right-click the Database you wish to copy data from.
    3. Select Generate Scripts >> Select Specific Database Objects >> Choose the tables/object you wish to transfer. strong text
    4. In the "Save to file" pane, click Advanced
    5. Set "Types of data to script" to Schema and data
    6. Set "Script DROP and CREATE" to Script DROP and CREATE
    7. Under "Table/View Options" set relevant items to TRUE. Though I recommend setting all to TRUE just in case. You can always modify the script after it generates.
    8. Set filepath >> Next >> Next
    9. Open newly created SQL file. Remove "Use" from top of file.
    10. Open new query window on destination database, paste script contents (without using) and execute.

    What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

    The issue as others have stated more elegantly is that you either have a Cartesian product of the OneToMany columns or you're doing N+1 Selects. Either possible gigantic resultset or chatty with the database, respectively.

    I'm surprised this isn't mentioned but this how I have gotten around this issue... I make a semi-temporary ids table. I also do this when you have the IN () clause limitation.

    This doesn't work for all cases (probably not even a majority) but it works particularly well if you have a lot of child objects such that the Cartesian product will get out of hand (ie lots of OneToMany columns the number of results will be a multiplication of the columns) and its more of a batch like job.

    First you insert your parent object ids as batch into an ids table. This batch_id is something we generate in our app and hold onto.

    INSERT INTO temp_ids 
        (product_id, batch_id)
        (SELECT p.product_id, ? 
        FROM product p ORDER BY p.product_id
        LIMIT ? OFFSET ?);
    

    Now for each OneToMany column you just do a SELECT on the ids table INNER JOINing the child table with a WHERE batch_id= (or vice versa). You just want to make sure you order by the id column as it will make merging result columns easier (otherwise you will need a HashMap/Table for the entire result set which may not be that bad).

    Then you just periodically clean the ids table.

    This also works particularly well if the user selects say 100 or so distinct items for some sort of bulk processing. Put the 100 distinct ids in the temporary table.

    Now the number of queries you are doing is by the number of OneToMany columns.

    Declare a variable in DB2 SQL

    I imagine this forum posting, which I quote fully below, should answer the question.


    Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):

    BEGIN ATOMIC
     DECLARE example VARCHAR(15) ;
     SET example = 'welcome' ;
     SELECT *
     FROM   tablename
     WHERE  column1 = example ;
    END
    

    or (in any environment):

    WITH t(example) AS (VALUES('welcome'))
    SELECT *
    FROM   tablename, t
    WHERE  column1 = example
    

    or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):

    CREATE VARIABLE example VARCHAR(15) ;
    SET example = 'welcome' ;
    SELECT *
    FROM   tablename
    WHERE  column1 = example ;
    

    How to change the ROOT application?

    According to the Apache Tomcat docs, you can change the application by creating a ROOT.xml file. See this for more info:

    http://tomcat.apache.org/tomcat-6.0-doc/config/context.html

    "The default web application may be defined by using a file called ROOT.xml."

    What's the best practice to "git clone" into an existing folder?

    This is the Best of all methods i came across

    Clone just the repository's .git folder (excluding files as they are already in existing-dir) into an empty temporary directory

    1. git clone --no-checkout repo-path-to-clone existing-dir/existing-dir.tmp //might want --no-hardlinks for cloning local repo

    Move the .git folder to the directory with the files. This makes existing-dir a git repo.

    1. mv existing-dir/existing-dir.tmp/.git existing-dir/

    Delete the temporary directory

    1. rmdir existing-dir/existing-dir.tmp

    2. cd existing-dir

    Git thinks all files are deleted, this reverts the state of the repo to HEAD.

    WARNING: any local changes to the files will be lost.

    1. git reset --mixed HEAD

    What is the purpose of the var keyword and when should I use it (or omit it)?

    Without using "var" variables can only define when set a value. In example:

    my_var;
    

    cannot work in global scope or any other scope. It should be with value like:

    my_var = "value";
    

    On the other hand you can define a vaiable like;

    var my_var;
    

    Its value is undefined ( Its value is not null and it is not equal to null interestingly.).

    How to store phone numbers on MySQL databases?

    I would say store them as an big integer, as a phone number itself is just a number. This also gives you more flexibility in how you present your phone numbers later, depending on what situation you are in.

    Visual Studio 2015 installer hangs during install?

    I have experienced similar problems with Visual Studio 2015 Update 3. In my case core issue was corrupted windows installer cache (C:\Windows\Installer)

    Here is the line from msi installer log:

    MSI (s) (4C:64) [10:40:10:059]: Warning: Local cached package 'C:\WINDOWS\Installer\3442502.msi' is missing.

    You should check installation logs if installation cache is corrupted same way. If it is you should pray for sfc utility to recover system integrity or you would reinstall windows from scratch as corrupted windows installer cache is a complete disaster and a reason to perform clear windows installation immediately.

    sql - insert into multiple tables in one query

    You can't. However, you CAN use a transaction and have both of them be contained within one transaction.

    START TRANSACTION;
    INSERT INTO table1 VALUES ('1','2','3');
    INSERT INTO table2 VALUES ('bob','smith');
    COMMIT;
    

    http://dev.mysql.com/doc/refman/5.1/en/commit.html

    How to right-align and justify-align in Markdown?

    If you want to use justify align in Jupyter Notebook use the following syntax:

    <p style='text-align: justify;'> Your Text </p>
    

    For right alignment:

    <p style='text-align: right;'> Your Text </p>
    

    Perform .join on value in array of objects

    An old thread I know but still super relevant to anyone coming across this.

    Array.map has been suggested here which is an awesome method that I use all the time. Array.reduce was also mentioned...

    I would personally use an Array.reduce for this use case. Why? Despite the code being slightly less clean/clear. It is a much more efficient than piping the map function to a join.

    The reason for this is because Array.map has to loop over each element to return a new array with all of the names of the object in the array. Array.join then loops over the contents of array to perform the join.

    You can improve the readability of jackweirdys reduce answer by using template literals to get the code on to a single line. "Supported in all modern browsers too"

    // a one line answer to this question using modern JavaScript
    x.reduce((a, b) => `${a.name || a}, ${b.name}`);
    

    PowerShell: Run command from script's directory

    This would work fine.

    Push-Location $PSScriptRoot
    
    Write-Host CurrentDirectory $CurDir
    

    SQL Server 2012 can't start because of a login failure

    One possibility is when installed sql server data tools Bi, while sql server was already set up.

    Solution:- 1.Just Repair the sql server with the set up instance

    if solution does not work , than its worth your time meddling with services.msc

    SQL Server: Get data for only the past year

    Well, I think something is missing here. User wants to get data from the last year and not from the last 365 days. There is a huge diference. In my opinion, data from the last year is every data from 2007 (if I am in 2008 now). So the right answer would be:

    SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1
    

    Then if you want to restrict this query, you can add some other filter, but always searching in the last year.

    SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1 AND DATE > '05/05/2007'
    

    using wildcards in LDAP search filters/queries

    This should work, at least according to the Search Filter Syntax article on MSDN network.

    The "hang-up" you have noticed is probably just a delay. Try running the same query with narrower scope (for example the specific OU where the test object is located), as it may take very long time for processing if you run it against all AD objects.

    You may also try separating the filter into two parts:

    (|(displayName=*searchstring)(displayName=searchstring*))
    

    cast or convert a float to nvarchar?

    If you're storing phone numbers in a float typed column (which is a bad idea) then they are presumably all integers and could be cast to int before casting to nvarchar.

    So instead of:

    select cast(cast(1234567890 as float) as nvarchar(50))
    1.23457e+009
    

    You would use:

    select cast(cast(cast(1234567890 as float) as int) as nvarchar(50))
    1234567890
    

    In these examples the innermost cast(1234567890 as float) is used in place of selecting a value from the appropriate column.

    I really recommend that you not store phone numbers in floats though!
    What if the phone number starts with a zero?

    select cast(0100884555 as float)
    100884555
    

    Whoops! We just stored an incorrect phone number...

    Use grep --exclude/--include syntax to not grep through certain files

    On CentOS 6.6/Grep 2.6.3, I have to use it like this:

    grep "term" -Hnir --include \*.php --exclude-dir "*excluded_dir*"
    

    Notice the lack of equal signs "=" (otherwise --include, --exclude, include-dir and --exclude-dir are ignored)

    How to stop C++ console application from exiting immediately?

    All you have to do set a variable for x then just type this in before the return 0;

    cout<<"\nPress any key and hit enter to end...";
    cin>>x;
    

    .c vs .cc vs. .cpp vs .hpp vs .h vs .cxx

    Those extensions aren't really new, they are old. :-)

    When C++ was new, some people wanted to have a .c++ extension for the source files, but that didn't work on most file systems. So they tried something close to that, like .cxx, or .cpp instead.

    Others thought about the language name, and "incrementing" .c to get .cc or even .C in some cases. Didn't catch on that much.

    Some believed that if the source is .cpp, the headers ought to be .hpp to match. Moderately successful.

    JPA CascadeType.ALL does not delete orphans

    I had the same problem and I wondered why this condition below did not delete the orphans. The list of dishes were not deleted in Hibernate (5.0.3.Final) when I executed a named delete query:

    @OneToMany(mappedBy = "menuPlan", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Dish> dishes = new ArrayList<>();
    

    Then I remembered that I must not use a named delete query, but the EntityManager. As I used the EntityManager.find(...) method to fetch the entity and then EntityManager.remove(...) to delete it, the dishes were deleted as well.

    Open file dialog box in JavaScript

    The simplest way:

    _x000D_
    _x000D_
    #file-input {_x000D_
      display: none;_x000D_
    }
    _x000D_
    <label for="file-input">_x000D_
      <div>Click this div and select a file</div>_x000D_
    </label>_x000D_
    <input type="file" id="file-input"/>
    _x000D_
    _x000D_
    _x000D_

    What's important, usage of display: none ensures that no place will be occupied by the hidden file input (what happens using opacity: 0).

    Meaning of - <?xml version="1.0" encoding="utf-8"?>

    This is the XML optional preamble.

    • version="1.0" means that this is the XML standard this file conforms to
    • encoding="utf-8" means that the file is encoded using the UTF-8 Unicode encoding

    How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

    Check this key for 32 bits and 64 bits Windows machines.

     HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
    

    and this for Windows 64 bits with 32 Bits JRE.

     HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment
    

    This will work for the oracle-sun JRE.

    How to read line by line of a text area HTML tag

    A simple regex should be efficent to check your textarea:

    /\s*\d+\s*\n/g.test(text) ? "OK" : "KO"
    

    How can I call controller/view helper methods from the console in Ruby on Rails?

    Inside any controller action or view, you can invoke the console by calling the console method.

    For example, in a controller:

    class PostsController < ApplicationController
      def new
        console
        @post = Post.new
      end
    end
    

    Or in a view:

    <% console %>
    
    <h2>New Post</h2>
    

    This will render a console inside your view. You don't need to care about the location of the console call; it won't be rendered on the spot of its invocation but next to your HTML content.

    See: http://guides.rubyonrails.org/debugging_rails_applications.html

    SQL Query for Logins

    Select * From Master..SysUsers Where IsSqlUser = 1
    

    tomcat - CATALINA_BASE and CATALINA_HOME variables

    That is the parent folder of bin which contains tomcat.exe file:

    CATALINA_HOME='C:\Program Files\Apache Software Foundation\Tomcat 6.0'
    

    CATALINA_BASE is the same as CATALINA_HOME.

    Should methods in a Java interface be declared with or without a public access modifier?

    I disagree with the popular answer, that having public implies that there are other options and so it shouldn't be there. The fact is that now with Java 9 and beyond there ARE other options.

    I think instead Java should enforce/require 'public' to be specified. Why? Because the absence of a modifier means 'package' access everywhere else, and having this as a special case is what leads to the confusion. If you simply made it a compile error with a clear message (e.g. "Package access is not allowed in an interface.") we would get rid of the apparent ambiguity that having the option to leave out 'public' introduces.

    Note the current wording at: https://docs.oracle.com/javase/specs/jls/se9/html/jls-9.html#jls-9.4

    "A method in the body of an interface may be declared public or private (§6.6). If no access modifier is given, the method is implicitly public. It is permitted, but discouraged as a matter of style, to redundantly specify the public modifier for a method declaration in an interface."

    See that 'private' IS allowed now. I think that last sentence should have been removed from the JLS. It is unfortunate that the "implicitly public" behaviour was ever allowed as it will now likely remain for backward compatibilty and lead to the confusion that the absence of the access modifier means 'public' in interfaces and 'package' elsewhere.

    #1071 - Specified key was too long; max key length is 1000 bytes

    I had this issue, and solved by following:

    Cause

    There is a known bug with MySQL related to MyISAM, the UTF8 character set and indexes that you can check here.

    Resolution

    • Make sure MySQL is configured with the InnoDB storage engine.

    • Change the storage engine used by default so that new tables will always be created appropriately:

      set GLOBAL storage_engine='InnoDb';

    • For MySQL 5.6 and later, use the following:

      SET GLOBAL default_storage_engine = 'InnoDB';

    • And finally make sure that you're following the instructions provided in Migrating to MySQL.

    Reference

    Removing object from array in Swift 3

    The correct and working one-line solution for deleting a unique object (named "objectToRemove") from an array of these objects (named "array") in Swift 3 is:

    if let index = array.enumerated().filter( { $0.element === objectToRemove }).map({ $0.offset }).first {
       array.remove(at: index)
    }
    

    setting y-axis limit in matplotlib

    This worked at least in matplotlib version 2.2.2:

    plt.axis([None, None, 0, 100])
    

    Probably this is a nice way to set up for example xmin and ymax only, etc.

    How to refresh activity after changing language (Locale) inside application

    If I imagined that you set android:configChanges in manifest.xml and create several directory for several language such as: values-fr OR values-nl, I could suggest this code(In Activity class):

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        Button btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new OnClickListener() {
    
            @Override
            public void onClick(View v) {
                // change language by onclick a button
                 Configuration newConfig = new Configuration();
                 newConfig.locale = Locale.FRENCH;
                 onConfigurationChanged(newConfig);
            }
        });
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    
        getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());
        setContentView(R.layout.main);
        setTitle(R.string.app_name);
    
        // Checks the active language
        if (newConfig.locale == Locale.ENGLISH) {
            Toast.makeText(this, "English", Toast.LENGTH_SHORT).show();
        } else if (newConfig.locale == Locale.FRENCH){
            Toast.makeText(this, "French", Toast.LENGTH_SHORT).show();
        }
    }
    

    I tested this code, It is correct.

    Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

    If you are using windows, Change folder security settings by giving fully controlled to the current user. It's worked for me.

    properties

    jQuery changing style of HTML element

    changing style with jquery

    Try This

    $('#selector_id').css('display','none');
    

    You can also change multiple attribute in a single query

    Try This

    $('#replace-div').css({'padding-top': '5px' , 'margin' : '10px'});
    

    Determine a string's encoding in C#

    Check out Utf8Checker it is simple class that does exactly this in pure managed code. http://utf8checker.codeplex.com

    Notice: as already pointed out "determine encoding" makes sense only for byte streams. If you have a string it is already encoded from someone along the way who already knew or guessed the encoding to get the string in the first place.

    Reading int values from SqlDataReader

    TxtFarmerSize.Text = (int)reader[3];
    

    SQL Server - stop or break execution of a SQL script

    This was my solution:

    ...

    BEGIN
        raiserror('Invalid database', 15, 10)
        rollback transaction
        return
    END
    

    How to remove duplicates from Python list and keep order?

    > but I don't know how to retrieve the list members from the hash in alphabetical order.

    Not really your main question, but for future reference Rod's answer using sorted can be used for traversing a dict's keys in sorted order:

    for key in sorted(my_dict.keys()):
       print key, my_dict[key]
       ...
    

    and also because tuple's are ordered by the first member of the tuple, you can do the same with items:

    for key, val in sorted(my_dict.items()):
        print key, val
        ...
    

    How can I give access to a private GitHub repository?

    If you are the owner it is simple:

    • Go to your repo and click the Settings button.
    • In the left menu click Collaborators
    • Then Add their name.

    Then collaborator should visit this example repo link https://github.com/user/repo/invitations

    Source: Github Docs.

    Can't open and lock privilege tables: Table 'mysql.user' doesn't exist

    You have to initialize the data directory by running the following command

    mysqld --initialize [with random root password]

    mysqld --initialize-insecure [with blank root password]

    How to change default text color using custom theme?

        <style name="Mytext" parent="@android:style/TextAppearance.Medium"> 
        <item name="android:textSize">20sp</item> 
        <item name="android:textColor">@color/white</item> 
        <item name="android:textStyle">bold</item>
        <item name="android:typeface">sans</item>
    </style>
    

    try this one ...

    On - window.location.hash - Change?

    Note that in case of Internet Explorer 7 and Internet Explorer 9 the if statment will give true (for "onhashchange" in windows), but the window.onhashchange will never fire, so it's better to store hash and check it after every 100 millisecond whether it's changed or not for all versions of Internet Explorer.

        if (("onhashchange" in window) && !($.browser.msie)) {
             window.onhashchange = function () {
                  alert(window.location.hash);
             }
             // Or $(window).bind( 'hashchange',function(e) {
             //       alert(window.location.hash);
             //   });
        }
        else {
            var prevHash = window.location.hash;
            window.setInterval(function () {
               if (window.location.hash != prevHash) {
                  prevHash = window.location.hash;
                  alert(window.location.hash);
               }
            }, 100);
        }
    

    EDIT - Since jQuery 1.9, $.browser.msie is not supported. Source: http://api.jquery.com/jquery.browser/

    Allow a div to cover the whole page instead of the area within the container

    Set the html and body tags height to 100% and remove the margin around the body:

    html, body {
        height: 100%;
        margin: 0px; /* Remove the margin around the body */
    }
    

    Now set the position of your div to fixed:

    #dimScreen
    {
        width: 100%;
        height: 100%;
        background:rgba(255,255,255,0.5);
    
        position: fixed;
        top: 0px;
        left: 0px;
    
        z-index: 1000; /* Now the div will be on top */
    }
    

    Demo: http://jsfiddle.net/F3LHW/

    phpMyAdmin - The MySQL Extension is Missing

    In my case I had to install the extension:

    yum install php php-mysql httpd
    

    and then restart apache:

    service httpd restart
    

    That solved the problem.

    MSSQL Regular expression

    Disclaimer: The original question was about MySQL. The SQL Server answer is below.

    MySQL

    In MySQL, the regex syntax is the following:

    SELECT * FROM YourTable WHERE (`url` NOT REGEXP '^[-A-Za-z0-9/.]+$') 
    

    Use the REGEXP clause instead of LIKE. The latter is for pattern matching using % and _ wildcards.


    SQL Server

    Since you made a typo, and you're using SQL Server (not MySQL), you'll have to create a user-defined CLR function to expose regex functionality.

    Take a look at this article for more details.

    MultipartException: Current request is not a multipart request

    In application.properties, please add this:

    spring.servlet.multipart.max-file-size=128KB
    spring.servlet.multipart.max-request-size=128KB
    spring.http.multipart.enabled=false
    

    and in your html form, you need an : enctype="multipart/form-data". For example:

    <form method="POST" enctype="multipart/form-data" action="/">
    

    Hope this help!

    How to convert a file into a dictionary?

    If you love one liners, try:

    d=eval('{'+re.sub('\'[\s]*?\'','\':\'',re.sub(r'([^'+input('SEP: ')+',]+)','\''+r'\1'+'\'',open(input('FILE: ')).read().rstrip('\n').replace('\n',',')))+'}')
    

    Input FILE = Path to file, SEP = Key-Value separator character

    Not the most elegant or efficient way of doing it, but quite interesting nonetheless :)

    How do I find my host and username on mysql?

    The default username is root. You can reset the root password if you do not know it: http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html. You should not, however, use the root account from PHP, set up a limited permission user to do that: http://dev.mysql.com/doc/refman/5.1/en/adding-users.html

    If MySql is running on the same computer as your webserver, you can just use "localhost" as the host

    How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

    Veverke mentioned that it is possible to disable generation of binding redirects by setting AutoGEneratedBindingRedirects to false. Not sure if it's a new thing since this question was posted, but there is an "Skip applying binding redirects" option in Tools/Options/Nuget Packet Manager, which can be toggled. By default it is off, meaning the redirects will be applied. However if you do this, you will have to manage any necessary binding redirects manually.

    How do I pass options to the Selenium Chrome driver using Python?

    from selenium import webdriver
    
    options = webdriver.ChromeOptions()
    options.add_argument('--disable-logging')
    
    # Update your desired_capabilities dict withe extra options.
    desired_capabilities.update(options.to_capabilities())
    driver = webdriver.Remote(desired_capabilities=options.to_capabilities())
    

    Both the desired_capabilities and options.to_capabilities() are dictionaries. You can use the dict.update() method to add the options to the main set.

    Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"

    you should run standlone.bat or .sh with -c standalone-full.xml switch may be work.

    Load image with jQuery and append it to the DOM

    $('<img src="'+ imgPath +'">').load(function() {
      $(this).width(some).height(some).appendTo('#some_target');
    });
    

    If you want to do for several images then:

    function loadImage(path, width, height, target) {
        $('<img src="'+ path +'">').load(function() {
          $(this).width(width).height(height).appendTo(target);
        });
    }
    

    Use:

    loadImage(imgPath, 800, 800, '#some_target');
    

    Background color of text in SVG

    Answer by Robert Longson (@RobertLongson) with modifications:

    <svg width="100%" height="100%">
      <defs>
        <filter x="0" y="0" width="1" height="1" id="solid">
          <feFlood flood-color="yellow"/>
          <feComposite in="SourceGraphic" operator="xor"/>
        </filter>
      </defs>
      <text filter="url(#solid)" x="20" y="50" font-size="50"> solid background </text>
      <text x="20" y="50" font-size="50">solid background</text>
    </svg>
    

    and we have no bluring and no heavy "getBBox" :) Padding is provided by white spaces in text-element with filter. It's worked for me

    Standard Android menu icons, for example refresh

    Maybe a bit late. Completing the other answers, you have the hdpi refresh icon in:

    "android_sdk"\platforms\"android_api_level"\data\res\drawable-hdpi\ic_menu_refresh.png

    Excel VBA - Range.Copy transpose paste

    WorksheetFunction Transpose()

    Instead of copying, pasting via PasteSpecial, and using the Transpose option you can simply type a formula

        =TRANSPOSE(Sheet1!A1:A5)
    

    or if you prefer VBA:

        Dim v
        v = WorksheetFunction.Transpose(Sheet1.Range("A1:A5"))
        Sheet2.Range("A1").Resize(1, UBound(v)) = v
    

    Note: alternatively you could use late-bound Application.Transpose instead.

    MS help reference states that having a current version of Microsoft 365, one can simply input the formula in the top-left-cell of the target range, otherwise the formula must be entered as a legacy array formula via Ctrl+Shift+Enter to confirm it.

    Versions Excel vers. 2007+, Mac since 2011, Excel for Microsoft 365

    How do I avoid the specification of the username and password at every git push?

    1. Generate an SSH key

    Linux/Mac

    Open terminal to create ssh keys:

    cd ~                 #Your home directory
    ssh-keygen -t rsa    #Press enter for all values
    

    For Windows

    (Only works if the commit program is capable of using certificates/private & public ssh keys)

    1. Use Putty Gen to generate a key
    2. Export the key as an open SSH key

    Here is a walkthrough on putty gen for the above steps

    2. Associate the SSH key with the remote repository

    This step varies, depending on how your remote is set up.

    • If it is a GitHub repository and you have administrative privileges, go to settings and click 'add SSH key'. Copy the contents of your ~/.ssh/id_rsa.pub into the field labeled 'Key'.

    • If your repository is administered by somebody else, give the administrator your id_rsa.pub.

    • If your remote repository is administered by your, you can use this command for example:

      scp ~/.ssh/id_rsa.pub YOUR_USER@YOUR_IP:~/.ssh/authorized_keys/id_rsa.pub

    3. Set your remote URL to a form that supports SSH 1

    If you have done the steps above and are still getting the password prompt, make sure your repo URL is in the form

    git+ssh://[email protected]/username/reponame.git
    

    as opposed to

    https://github.com/username/reponame.git
    

    To see your repo URL, run:

    git remote show origin
    

    You can change the URL with:

    git remote set-url origin git+ssh://[email protected]/username/reponame.git
    

    [1] This section incorporates the answer from Eric P

    How to get enum value by string or int

    Here is an example to get string/value

        public enum Suit
        {
            Spades = 0x10,
            Hearts = 0x11,
            Clubs = 0x12,
            Diamonds = 0x13
        }
    
        private void print_suit()
        {
            foreach (var _suit in Enum.GetValues(typeof(Suit)))
            {
                int suitValue = (byte)(Suit)Enum.Parse(typeof(Suit), _suit.ToString());
                MessageBox.Show(_suit.ToString() + " value is 0x" + suitValue.ToString("X2"));
            }
        }
    

        Result of Message Boxes
        Spade value is 0x10
        Hearts value is 0x11
        Clubs value is 0x12
        Diamonds value is 0x13
    

    Oracle SQL Developer - tables cannot be seen

    SQL Developer 3.1 fixes this issue. Its an early adopter release at the moment though.

    How does an SSL certificate chain bundle work?

    The original order is in fact backwards. Certs should be followed by the issuing cert until the last cert is issued by a known root per IETF's RFC 5246 Section 7.4.2

    This is a sequence (chain) of certificates. The sender's certificate MUST come first in the list. Each following certificate MUST directly certify the one preceding it.

    See also SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch for troubleshooting techniques.

    But I still don't know why they wrote the spec so that the order matters.

    How can I do an asc and desc sort using underscore.js?

    You can use .sortBy, it will always return an ascending list:

    _.sortBy([2, 3, 1], function(num) {
        return num;
    }); // [1, 2, 3]
    

    But you can use the .reverse method to get it descending:

    var array = _.sortBy([2, 3, 1], function(num) {
        return num;
    });
    
    console.log(array); // [1, 2, 3]
    console.log(array.reverse()); // [3, 2, 1]
    

    Or when dealing with numbers add a negative sign to the return to descend the list:

    _.sortBy([-3, -2, 2, 3, 1, 0, -1], function(num) {
        return -num;
    }); // [3, 2, 1, 0, -1, -2, -3]
    

    Under the hood .sortBy uses the built in .sort([handler]):

    // Default is ascending:
    [2, 3, 1].sort(); // [1, 2, 3]
    
    // But can be descending if you provide a sort handler:
    [2, 3, 1].sort(function(a, b) {
        // a = current item in array
        // b = next item in array
        return b - a;
    });
    

    Function that creates a timestamp in c#

    when you need in a timestamp in seconds, you can use the following:

    var timestamp = (int)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalSeconds;
    

    How to open the Chrome Developer Tools in a new window?

    You have to click and hold until the other icon shows up, then slide the mouse down to the icon.

    Inserting into Oracle and retrieving the generated sequence ID

    You can do this with a single statement - assuming you are calling it from a JDBC-like connector with in/out parameters functionality:

    insert into batch(batchid, batchname) 
    values (batch_seq.nextval, 'new batch')
    returning batchid into :l_batchid;
    

    or, as a pl-sql script:

    variable l_batchid number;
    
    insert into batch(batchid, batchname) 
    values (batch_seq.nextval, 'new batch')
    returning batchid into :l_batchid;
    
    select :l_batchid from dual;
    

    how to load url into div tag

    <html>
    <head>
    <script type="text/javascript">
        $(document).ready(function(){
        $("#content").attr("src","http://vnexpress.net");
    })
    </script>
    </head>
    <body>
    <iframe id="content"></div>
    </body>
    </html>
    

    Load content with ajax in bootstrap modal

    The top voted answer is deprecated in Bootstrap 3.3 and will be removed in v4. Try this instead:

    JavaScript:

    // Fill modal with content from link href
    $("#myModal").on("show.bs.modal", function(e) {
        var link = $(e.relatedTarget);
        $(this).find(".modal-body").load(link.attr("href"));
    });
    

    Html (Based on the official example. Note that for Bootstrap 3.* we set data-remote="false" to disable the deprecated Bootstrap load function):

    <!-- Link trigger modal -->
    <a href="remoteContent.html" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-default">
        Launch Modal
    </a>
    
    <!-- Default bootstrap modal example -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">Modal title</h4>
          </div>
          <div class="modal-body">
            ...
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
          </div>
        </div>
      </div>
    </div>
    

    Try it yourself: https://jsfiddle.net/ednon5d1/

    How can I check whether Google Maps is fully loaded?

    If you're using web components, then they have this as an example:

    map.addEventListener('google-map-ready', function(e) {
       alert('Map loaded!');
    });
    

    Android, landscape only orientation?

    You can try with

     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    

    How to embed a PDF viewer in a page?

    have a try with Flex Paper http://flexpaper.devaldi.com/

    it works like scribd

    How do I find out what License has been applied to my SQL Server installation?

    I know this post is older, but haven't seen a solution that provides the actual information, so I want to share what I use for SQL Server 2012 and above. the link below leads to the screenshot showing the information.

    First (so no time is wasted):

    SQL Server 2000:
    SELECT SERVERPROPERTY('LicenseType'), SERVERPROPERTY('NumLicenses')

    SQL Server 2005+

    The "SELECT SERVERPROPERTY('LicenseType'), SERVERPROPERTY('NumLicenses')" is not in use anymore. You can see more details on MSFT documentation: https://docs.microsoft.com/en-us/sql/t-sql/functions/serverproperty-transact-sql?view=sql-server-2017

    SQL Server 2005 - 2008R2 you would have to:

    Using PowerShell: https://www.ryadel.com/en/sql-server-retrieve-product-key-from-an-existing-installation/

    Using TSQL (you would need to know the registry key path off hand): https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-server-registry-transact-sql?view=sql-server-2017

    SQL Server 2012+

    Now, you can extract SQL Server Licensing information from the SQL Server Error Log, granted it may not be formatted the way you want, but the information is there and can be parsed, along with more descriptive information that you probably didn't expect.

    EXEC sp_readerrorlog @p1 = 0
                        ,@p2 = 1
                        ,@p3 = N'licensing'
    

    NOTE: I tried pasting the image directly, but since I am new at stakoverflow we have to follow the link below.

    SQL Server License information via sp_readerrorlog

    WARNING: Can't verify CSRF token authenticity rails

    I just thought I'd link this here as the article has most of the answer you're looking for and it's also very interesting

    http://www.kalzumeus.com/2011/11/17/i-saw-an-extremely-subtle-bug-today-and-i-just-have-to-tell-someone/

    How to get the filename without the extension from a path in Python?

    On Windows system I used drivername prefix as well, like:

    >>> s = 'c:\\temp\\akarmi.txt'
    >>> print(os.path.splitext(s)[0])
    c:\temp\akarmi
    

    So because I do not need drive letter or directory name, I use:

    >>> print(os.path.splitext(os.path.basename(s))[0])
    akarmi
    

    Twitter Bootstrap alert message close and open again

    I ran into this problem as well and the the problem with simply hacking the close-button is that I still need access to the standard bootstrap alert-close events.

    My solution was to write a small, customisable, jquery plugin that injects a properly formed Bootstrap 3 alert (with or without close button as you need it) with a minimum of fuss and allows you to easily regenerate it after the box is closed.

    See https://github.com/davesag/jquery-bs3Alert for usage, tests, and examples.

    socket programming multiple client to one server

    This is the echo server handling multiple clients... Runs fine and good using Threads

    // echo server
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    
    public class Server_X_Client {
    public static void main(String args[]){
    
    
        Socket s=null;
        ServerSocket ss2=null;
        System.out.println("Server Listening......");
        try{
            ss2 = new ServerSocket(4445); // can also use static final PORT_NUM , when defined
    
        }
        catch(IOException e){
        e.printStackTrace();
        System.out.println("Server error");
    
        }
    
        while(true){
            try{
                s= ss2.accept();
                System.out.println("connection Established");
                ServerThread st=new ServerThread(s);
                st.start();
    
            }
    
        catch(Exception e){
            e.printStackTrace();
            System.out.println("Connection Error");
    
        }
        }
    
    }
    
    }
    
    class ServerThread extends Thread{  
    
        String line=null;
        BufferedReader  is = null;
        PrintWriter os=null;
        Socket s=null;
    
        public ServerThread(Socket s){
            this.s=s;
        }
    
        public void run() {
        try{
            is= new BufferedReader(new InputStreamReader(s.getInputStream()));
            os=new PrintWriter(s.getOutputStream());
    
        }catch(IOException e){
            System.out.println("IO error in server thread");
        }
    
        try {
            line=is.readLine();
            while(line.compareTo("QUIT")!=0){
    
                os.println(line);
                os.flush();
                System.out.println("Response to Client  :  "+line);
                line=is.readLine();
            }   
        } catch (IOException e) {
    
            line=this.getName(); //reused String line for getting thread name
            System.out.println("IO Error/ Client "+line+" terminated abruptly");
        }
        catch(NullPointerException e){
            line=this.getName(); //reused String line for getting thread name
            System.out.println("Client "+line+" Closed");
        }
    
        finally{    
        try{
            System.out.println("Connection Closing..");
            if (is!=null){
                is.close(); 
                System.out.println(" Socket Input Stream Closed");
            }
    
            if(os!=null){
                os.close();
                System.out.println("Socket Out Closed");
            }
            if (s!=null){
            s.close();
            System.out.println("Socket Closed");
            }
    
            }
        catch(IOException ie){
            System.out.println("Socket Close Error");
        }
        }//end finally
        }
    }
    

    Also here is the code for the client.. Just execute this code for as many times as you want to create multiple client..

    // A simple Client Server Protocol .. Client for Echo Server
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    
    public class NetworkClient {
    
    public static void main(String args[]) throws IOException{
    
    
        InetAddress address=InetAddress.getLocalHost();
        Socket s1=null;
        String line=null;
        BufferedReader br=null;
        BufferedReader is=null;
        PrintWriter os=null;
    
        try {
            s1=new Socket(address, 4445); // You can use static final constant PORT_NUM
            br= new BufferedReader(new InputStreamReader(System.in));
            is=new BufferedReader(new InputStreamReader(s1.getInputStream()));
            os= new PrintWriter(s1.getOutputStream());
        }
        catch (IOException e){
            e.printStackTrace();
            System.err.print("IO Exception");
        }
    
        System.out.println("Client Address : "+address);
        System.out.println("Enter Data to echo Server ( Enter QUIT to end):");
    
        String response=null;
        try{
            line=br.readLine(); 
            while(line.compareTo("QUIT")!=0){
                    os.println(line);
                    os.flush();
                    response=is.readLine();
                    System.out.println("Server Response : "+response);
                    line=br.readLine();
    
                }
    
    
    
        }
        catch(IOException e){
            e.printStackTrace();
        System.out.println("Socket read Error");
        }
        finally{
    
            is.close();os.close();br.close();s1.close();
                    System.out.println("Connection Closed");
    
        }
    
    }
    }
    

    Querying Datatable with where condition

    You can do it with Linq, as mamoo showed, but the oldies are good too:

    var filteredDataTable = dt.Select(@"EmpId > 2
        AND (EmpName <> 'abc' OR EmpName <> 'xyz')
        AND EmpName like '%il%'" );
    

    How to import spring-config.xml of one project into spring-config.xml of another project?

    You have to add the jar/war of the module B in the module A and add the classpath in your new spring-module file. Just add this line

    spring-moduleA.xml - is a file in module A under the resource folder. By adding this line, it imports all the bean definition from module A to module B.

    MODULE B/ spring-moduleB.xml


    import resource="classpath:spring-moduleA.xml"/>
    
    <bean id="helloBeanB" class="basic.HelloWorldB">
      <property name="name" value="BMVNPrj" />
    </bean>
    

    javascript code to check special characters

    Directly from the w3schools website:

       var str = "The best things in life are free";
       var patt = new RegExp("e");
       var res = patt.test(str);
    

    To combine their example with a regular expression, you could do the following:

    function checkUserName() {
        var username = document.getElementsByName("username").value;
        var pattern = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/); //unacceptable chars
        if (pattern.test(username)) {
            alert("Please only use standard alphanumerics");
            return false;
        }
        return true; //good user input
    }
    

    Visual Studio debugger error: Unable to start program Specified file cannot be found

    I think that what you have to check is:

    1. if the target EXE is correctly configured in the project settings ("command", in the debugging tab). Since all individual projects run when you start debugging it's well possible that only the debugging target for the "ALL" solution is missing, check which project is currently active (you can also select the debugger target by changing the active project).

    2. dependencies (DLLs) are also located at the target debugee directory or can be loaded (you can use the "depends.exe" tool for checking dependencies of an executable or DLL).

    When to use async false and async true in ajax function in jquery

    In basic terms synchronous requests wait for the response to be received from the request before it allows any code processing to continue. At first this may seem like a good thing to do, but it absolutely is not.

    As mentioned, while the request is in process the browser will halt execution of all script and also rendering of the UI as the JS engine of the majority of browsers is (effectively) single-threaded. This means that to your users the browser will appear unresponsive and they may even see OS-level warnings that the program is not responding and to ask them if its process should be ended. It's for this reason that synchronous JS has been deprecated and you see warnings about its use in the devtools console.

    The alternative of asynchronous requests is by far the better practice and should always be used where possible. This means that you need to know how to use callbacks and/or promises in order to handle the responses to your async requests when they complete, and also how to structure your JS to work with this pattern. There are many resources already available covering this, this, for example, so I won't go into it here.

    There are very few occasions where a synchronous request is necessary. In fact the only one I can think of is when making a request within the beforeunload event handler, and even then it's not guaranteed to work.

    In summary. you should look to learn and employ the async pattern in all requests. Synchronous requests are now an anti-pattern which cause more issues than they generally solve.

    Stop on first error

    Maybe you want set -e:

    www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:

    This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

    javascript filter array multiple conditions

    If the finality of you code is to get the filtered user, I would invert the for to evaluate the user instead of reducing the result array during each iteration.

    Here an (untested) example:

    function filterUsers (users, filter) {
        var result = [];
    
        for (i=0;i<users.length;i++){
            for (var prop in filter) {
                if (users.hasOwnProperty(prop) && users[i][prop] === filter[prop]) {
                    result.push(users[i]);
                }
            }
        }
        return result;
    }
    

    Paste a multi-line Java String in Eclipse

    The EclipsePasteAsJavaString plug-in allows you to insert text as a Java string by Ctrl + Shift + V

    Example

    Paste as usual via Ctrl+V:

    some text with tabs and new lines

    Paste as Java string via Ctrl+Shift+V

    "some text\twith tabs\r\n" + "and new \r\n" + "lines"

    How do I set the maximum line length in PyCharm?

    For PyCharm 2018.1 on Mac:

    Preferences (?+,), then Editor -> Code Style:

    enter image description here

    For PyCharm 2018.3 on Windows:

    File -> Settings (Ctrl+Alt+S), then Editor -> Code Style:

    To follow PEP-8 set Hard wrap at to 80.

    PHP Try and Catch for SQL Insert

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    

    I am not sure if there is a mysql version of this but adding this line of code allows throwing mysqli_sql_exception.
    I know, passed a lot of time and the question is already checked answered but I got a different answer and it may be helpful.

    webpack command not working

    npm i webpack -g
    

    installs webpack globally on your system, that makes it available in terminal window.

    No numeric types to aggregate - change in groupby() behaviour?

    How are you generating your data?

    See how the output shows that your data is of 'object' type? the groupby operations specifically check whether each column is a numeric dtype first.

    In [31]: data
    Out[31]: 
    <class 'pandas.core.frame.DataFrame'>
    DatetimeIndex: 2557 entries, 2004-01-01 00:00:00 to 2010-12-31 00:00:00
    Freq: <1 DateOffset>
    Columns: 360 entries, -89.75 to 89.75
    dtypes: object(360)
    

    look ?


    Did you initialize an empty DataFrame first and then filled it? If so that's probably why it changed with the new version as before 0.9 empty DataFrames were initialized to float type but now they are of object type. If so you can change the initialization to DataFrame(dtype=float).

    You can also call frame.astype(float)

    Blur or dim background when Android PopupWindow active

    For me, something like Abdelhak Mouaamou's answer works, tested on API level 16 and 27.

    Instead of using popupWindow.getContentView().getParent() and casting the result to View (which crashes on API level 16 cause there it returns a ViewRootImpl object which isn't an instance of View) I just use .getRootView() which returns a view already, so no casting required there.

    Hope it helps someone :)

    complete working example scrambled together from other stackoverflow posts, just copy-paste it, e.g., in the onClick listener of a button:

    // inflate the layout of the popup window
    LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
    if(inflater == null) {
        return;
    }
    //View popupView = inflater.inflate(R.layout.my_popup_layout, null); // this version gives a warning cause it doesn't like null as argument for the viewRoot, c.f. https://stackoverflow.com/questions/24832497 and https://stackoverflow.com/questions/26404951
    View popupView = View.inflate(MyParentActivity.this, R.layout.my_popup_layout, null);
    
    // create the popup window
    final PopupWindow popupWindow = new PopupWindow(popupView,
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT,
            true // lets taps outside the popup also dismiss it
            );
    
    // do something with the stuff in your popup layout, e.g.:
    //((TextView)popupView.findViewById(R.id.textview_popup_helloworld))
    //      .setText("hello stackoverflow");
    
    // dismiss the popup window when touched
    popupView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                popupWindow.dismiss();
                return true;
            }
    });
    
    // show the popup window
    // which view you pass in doesn't matter, it is only used for the window token
    popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
    //popupWindow.setOutsideTouchable(false); // doesn't seem to change anything for me
    
    View container = popupWindow.getContentView().getRootView();
    if(container != null) {
        WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
        WindowManager.LayoutParams p = (WindowManager.LayoutParams)container.getLayoutParams();
        p.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
        p.dimAmount = 0.3f;
        if(wm != null) {
            wm.updateViewLayout(container, p);
        }
    }
    

    Looping through array and removing items, without breaking for loop

    Two examples that work:

    (Example ONE)
    // Remove from Listing the Items Checked in Checkbox for Delete
    let temp_products_images = store.state.c_products.products_images
    if (temp_products_images != null) {
        for (var l = temp_products_images.length; l--;) {
            // 'mark' is the checkbox field
            if (temp_products_images[l].mark == true) {
                store.state.c_products.products_images.splice(l,1);         // THIS WORKS
                // this.$delete(store.state.c_products.products_images,l);  // THIS ALSO WORKS
            }
        }
    }
    
    (Example TWO)
    // Remove from Listing the Items Checked in Checkbox for Delete
    let temp_products_images = store.state.c_products.products_images
    if (temp_products_images != null) {
        let l = temp_products_images.length
        while (l--)
        {
            // 'mark' is the checkbox field
            if (temp_products_images[l].mark == true) {
                store.state.c_products.products_images.splice(l,1);         // THIS WORKS
                // this.$delete(store.state.c_products.products_images,l);  // THIS ALSO WORKS
            }
        }
    }
    

    Dealing with commas in a CSV file

    There is a library available through nuget for dealing with pretty much any well formed CSV (.net) - CsvHelper

    Example to map to a class:

    var csv = new CsvReader( textReader );
    var records = csv.GetRecords<MyClass>();
    

    Example to read individual fields:

    var csv = new CsvReader( textReader );
    while( csv.Read() )
    {
        var intField = csv.GetField<int>( 0 );
        var stringField = csv.GetField<string>( 1 );
        var boolField = csv.GetField<bool>( "HeaderName" );
    }
    

    Letting the client drive the file format:
    , is the standard field delimiter, " is the standard value used to escape fields that contain a delimiter, quote, or line ending.

    To use (for example) # for fields and ' for escaping:

    var csv = new CsvReader( textReader );
    csv.Configuration.Delimiter = "#";
    csv.Configuration.Quote = ''';
    // read the file however meets your needs
    

    More Documentation

    How to load data from a text file in a PostgreSQL database?

    Let consider that your data are in the file values.txt and that you want to import them in the database table myTable then the following query does the job

    COPY myTable FROM 'value.txt' (DELIMITER('|'));
    

    https://www.postgresql.org/docs/current/static/sql-copy.html

    MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

    The argument to remove() is a filter document, so passing in an empty document means 'remove all':

    db.user.remove({})
    

    However, if you definitely want to remove everything you might be better off dropping the collection. Though that probably depends on whether you have user defined indexes on the collection i.e. whether the cost of preparing the collection after dropping it outweighs the longer duration of the remove() call vs the drop() call.

    More details in the docs.

    How to implement common bash idioms in Python?

    Yes, of course :)

    Take a look at these libraries which help you Never write shell scripts again (Plumbum's motto).

    Also, if you want to replace awk, sed and grep with something Python based then I recommend pyp -

    "The Pyed Piper", or pyp, is a linux command line text manipulation tool similar to awk or sed, but which uses standard python string and list methods as well as custom functions evolved to generate fast results in an intense production environment.

    How can labels/legends be added for all chart types in chart.js (chartjs.org)?

    For line chart, I use the following codes.

    First create custom style

    .boxx{
        position: relative;
        width: 20px;
        height: 20px;
        border-radius: 3px;
    }
    

    Then add this on your line options

    var lineOptions = {
                legendTemplate : '<table>'
                                +'<% for (var i=0; i<datasets.length; i++) { %>'
                                +'<tr><td><div class=\"boxx\" style=\"background-color:<%=datasets[i].fillColor %>\"></div></td>'
                                +'<% if (datasets[i].label) { %><td><%= datasets[i].label %></td><% } %></tr><tr height="5"></tr>'
                                +'<% } %>'
                                +'</table>',
                multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>"
    
    var ctx = document.getElementById("lineChart").getContext("2d");
    var myNewChart = new Chart(ctx).Line(lineData, lineOptions);
    document.getElementById('legendDiv').innerHTML = myNewChart.generateLegend();
    

    Don't forget to add

    <div id="legendDiv"></div>
    

    on your html where do you want to place your legend. That's it!

    'printf' vs. 'cout' in C++

    I'm surprised that everyone in this question claims that std::cout is way better than printf, even if the question just asked for differences. Now, there is a difference - std::cout is C++, and printf is C (however, you can use it in C++, just like almost anything else from C). Now, I'll be honest here; both printf and std::cout have their advantages.

    Real differences

    Extensibility

    std::cout is extensible. I know that people will say that printf is extensible too, but such extension is not mentioned in the C standard (so you would have to use non-standard features - but not even common non-standard feature exists), and such extensions are one letter (so it's easy to conflict with an already-existing format).

    Unlike printf, std::cout depends completely on operator overloading, so there is no issue with custom formats - all you do is define a subroutine taking std::ostream as the first argument and your type as second. As such, there are no namespace problems - as long you have a class (which isn't limited to one character), you can have working std::ostream overloading for it.

    However, I doubt that many people would want to extend ostream (to be honest, I rarely saw such extensions, even if they are easy to make). However, it's here if you need it.

    Syntax

    As it could be easily noticed, both printf and std::cout use different syntax. printf uses standard function syntax using pattern string and variable-length argument lists. Actually, printf is a reason why C has them - printf formats are too complex to be usable without them. However, std::cout uses a different API - the operator << API that returns itself.

    Generally, that means the C version will be shorter, but in most cases it won't matter. The difference is noticeable when you print many arguments. If you have to write something like Error 2: File not found., assuming error number, and its description is placeholder, the code would look like this. Both examples work identically (well, sort of, std::endl actually flushes the buffer).

    printf("Error %d: %s.\n", id, errors[id]);
    std::cout << "Error " << id << ": " << errors[id] << "." << std::endl;
    

    While this doesn't appear too crazy (it's just two times longer), things get more crazy when you actually format arguments, instead of just printing them. For example, printing of something like 0x0424 is just crazy. This is caused by std::cout mixing state and actual values. I never saw a language where something like std::setfill would be a type (other than C++, of course). printf clearly separates arguments and actual type. I really would prefer to maintain the printf version of it (even if it looks kind of cryptic) compared to iostream version of it (as it contains too much noise).

    printf("0x%04x\n", 0x424);
    std::cout << "0x" << std::hex << std::setfill('0') << std::setw(4) << 0x424 << std::endl;
    

    Translation

    This is where the real advantage of printf lies. The printf format string is well... a string. That makes it really easy to translate, compared to operator << abuse of iostream. Assuming that the gettext() function translates, and you want to show Error 2: File not found., the code to get translation of the previously shown format string would look like this:

    printf(gettext("Error %d: %s.\n"), id, errors[id]);
    

    Now, let's assume that we translate to Fictionish, where the error number is after the description. The translated string would look like %2$s oru %1$d.\n. Now, how to do it in C++? Well, I have no idea. I guess you can make fake iostream which constructs printf that you can pass to gettext, or something, for purposes of translation. Of course, $ is not C standard, but it's so common that it's safe to use in my opinion.

    Not having to remember/look-up specific integer type syntax

    C has lots of integer types, and so does C++. std::cout handles all types for you, while printf requires specific syntax depending on an integer type (there are non-integer types, but the only non-integer type you will use in practice with printf is const char * (C string, can be obtained using to_c method of std::string)). For instance, to print size_t, you need to use %zd, while int64_t will require using %"PRId64". The tables are available at http://en.cppreference.com/w/cpp/io/c/fprintf and http://en.cppreference.com/w/cpp/types/integer.

    You can't print the NUL byte, \0

    Because printf uses C strings as opposed to C++ strings, it cannot print NUL byte without specific tricks. In certain cases it's possible to use %c with '\0' as an argument, although that's clearly a hack.

    Differences nobody cares about

    Performance

    Update: It turns out that iostream is so slow that it's usually slower than your hard drive (if you redirect your program to file). Disabling synchronization with stdio may help, if you need to output lots of data. If the performance is a real concern (as opposed to writing several lines to STDOUT), just use printf.

    Everyone thinks that they care about performance, but nobody bothers to measure it. My answer is that I/O is bottleneck anyway, no matter if you use printf or iostream. I think that printf could be faster from a quick look into assembly (compiled with clang using the -O3 compiler option). Assuming my error example, printf example does way fewer calls than the cout example. This is int main with printf:

    main:                                   @ @main
    @ BB#0:
            push    {lr}
            ldr     r0, .LCPI0_0
            ldr     r2, .LCPI0_1
            mov     r1, #2
            bl      printf
            mov     r0, #0
            pop     {lr}
            mov     pc, lr
            .align  2
    @ BB#1:
    

    You can easily notice that two strings, and 2 (number) are pushed as printf arguments. That's about it; there is nothing else. For comparison, this is iostream compiled to assembly. No, there is no inlining; every single operator << call means another call with another set of arguments.

    main:                                   @ @main
    @ BB#0:
            push    {r4, r5, lr}
            ldr     r4, .LCPI0_0
            ldr     r1, .LCPI0_1
            mov     r2, #6
            mov     r3, #0
            mov     r0, r4
            bl      _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
            mov     r0, r4
            mov     r1, #2
            bl      _ZNSolsEi
            ldr     r1, .LCPI0_2
            mov     r2, #2
            mov     r3, #0
            mov     r4, r0
            bl      _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
            ldr     r1, .LCPI0_3
            mov     r0, r4
            mov     r2, #14
            mov     r3, #0
            bl      _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
            ldr     r1, .LCPI0_4
            mov     r0, r4
            mov     r2, #1
            mov     r3, #0
            bl      _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
            ldr     r0, [r4]
            sub     r0, r0, #24
            ldr     r0, [r0]
            add     r0, r0, r4
            ldr     r5, [r0, #240]
            cmp     r5, #0
            beq     .LBB0_5
    @ BB#1:                                 @ %_ZSt13__check_facetISt5ctypeIcEERKT_PS3_.exit
            ldrb    r0, [r5, #28]
            cmp     r0, #0
            beq     .LBB0_3
    @ BB#2:
            ldrb    r0, [r5, #39]
            b       .LBB0_4
    .LBB0_3:
            mov     r0, r5
            bl      _ZNKSt5ctypeIcE13_M_widen_initEv
            ldr     r0, [r5]
            mov     r1, #10
            ldr     r2, [r0, #24]
            mov     r0, r5
            mov     lr, pc
            mov     pc, r2
    .LBB0_4:                                @ %_ZNKSt5ctypeIcE5widenEc.exit
            lsl     r0, r0, #24
            asr     r1, r0, #24
            mov     r0, r4
            bl      _ZNSo3putEc
            bl      _ZNSo5flushEv
            mov     r0, #0
            pop     {r4, r5, lr}
            mov     pc, lr
    .LBB0_5:
            bl      _ZSt16__throw_bad_castv
            .align  2
    @ BB#6:
    

    However, to be honest, this means nothing, as I/O is the bottleneck anyway. I just wanted to show that iostream is not faster because it's "type safe". Most C implementations implement printf formats using computed goto, so the printf is as fast as it can be, even without compiler being aware of printf (not that they aren't - some compilers can optimize printf in certain cases - constant string ending with \n is usually optimized to puts).

    Inheritance

    I don't know why you would want to inherit ostream, but I don't care. It's possible with FILE too.

    class MyFile : public FILE {}
    

    Type safety

    True, variable length argument lists have no safety, but that doesn't matter, as popular C compilers can detect problems with printf format string if you enable warnings. In fact, Clang can do that without enabling warnings.

    $ cat safety.c
    
    #include <stdio.h>
    
    int main(void) {
        printf("String: %s\n", 42);
        return 0;
    }
    
    $ clang safety.c
    
    safety.c:4:28: warning: format specifies type 'char *' but the argument has type 'int' [-Wformat]
        printf("String: %s\n", 42);
                        ~~     ^~
                        %d
    1 warning generated.
    $ gcc -Wall safety.c
    safety.c: In function ‘main’:
    safety.c:4:5: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
         printf("String: %s\n", 42);
         ^
    

    Is it bad to have my virtualenv directory inside my git repository?

    If you just setting up development env, then use pip freeze file, caz that makes the git repo clean.

    Then if doing production deployment, then checkin the whole venv folder. That will make your deployment more reproducible, not need those libxxx-dev packages, and avoid the internet issues.

    So there are two repos. One for your main source code, which includes a requirements.txt. And a env repo, which contains the whole venv folder.

    Change color of bootstrap navbar on hover link?

    If you Navbar code as like as follow:

    <div class="navbar navbar-default navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">Project name</a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li class="active"><a href="#">Home</a></li>
                <li><a href="#about">About</a></li>
                <li><a href="#contact">Contact</a></li>
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
                    <ul class="dropdown-menu">
                        <li><a href="#">Action</a></li>
                        <li><a href="#">Another action</a></li>
                        <li><a href="#">Something else here</a></li>
                        <li class="divider"></li>
                        <li class="dropdown-header">Nav header</li>
                        <li><a href="#">Separated link</a></li>
                        <li><a href="#">One more separated link</a></li>
                    </ul>
                </li>
            </ul>
            <ul class="nav navbar-nav navbar-right">
                <li><a href="../navbar/">Default</a></li>
                <li><a href="../navbar-static-top/">Static top</a></li>
                <li class="active"><a href="./">Fixed top</a></li>
            </ul>
        </div><!--/.nav-collapse -->
    </div>
    

    Then just use the following CSS style to change hover color of your navbar-brand

    .navbar-default .navbar-brand:hover,
    .navbar-default .navbar-brand:focus {
         color: white;
    }
    

    So your navbad-brand hover color will be changed to white. I just tested it and it's working for me correctly.

    How to find array / dictionary value using key?

    It looks like you're writing PHP, in which case you want:

    <?
    $arr=array('us'=>'United', 'ca'=>'canada');
    $key='ca';
    echo $arr[$key];
    ?>
    

    Notice that the ('us'=>'United', 'ca'=>'canada') needs to be a parameter to the array function in PHP.

    Most programming languages that support associative arrays or dictionaries use arr['key'] to retrieve the item specified by 'key'

    For instance:

    Ruby

    ruby-1.9.1-p378 > h = {'us' => 'USA', 'ca' => 'Canada' }
     => {"us"=>"USA", "ca"=>"Canada"} 
    ruby-1.9.1-p378 > h['ca']
     => "Canada" 
    

    Python

    >>> h = {'us':'USA', 'ca':'Canada'}
    >>> h['ca']
    'Canada'
    

    C#

    class P
    {
        static void Main()
        {
            var d = new System.Collections.Generic.Dictionary<string, string> { {"us", "USA"}, {"ca", "Canada"}};
            System.Console.WriteLine(d["ca"]);
        }
    }
    

    Lua

    t = {us='USA', ca='Canada'}
    print(t['ca'])
    print(t.ca) -- Lua's a little different with tables
    

    How do I remove the non-numeric character from a string in java?

    You will want to use the String class' Split() method and pass in a regular expression of "\D+" which will match at least one non-number.

    myString.split("\\D+");
    

    How to count the number of true elements in a NumPy bool array

    That question solved a quite similar question for me and I thought I should share :

    In raw python you can use sum() to count True values in a list :

    >>> sum([True,True,True,False,False])
    3
    

    But this won't work :

    >>> sum([[False, False, True], [True, False, True]])
    TypeError...
    

    How to check variable type at runtime in Go language

    See type assertions here:

    http://golang.org/ref/spec#Type_assertions

    I'd assert a sensible type (string, uint64) etc only and keep it as loose as possible, performing a conversion to the native type last.

    Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

    In the case you have classes with same property names, here is a small extension to Praveen's answer:

     catch (DbEntityValidationException dbEx)
     {
        foreach (var validationErrors in dbEx.EntityValidationErrors)
        {
           foreach (var validationError in validationErrors.ValidationErrors)
           {
              Trace.TraceInformation(
                    "Class: {0}, Property: {1}, Error: {2}",
                    validationErrors.Entry.Entity.GetType().FullName,
                    validationError.PropertyName,
                    validationError.ErrorMessage);
           }
        }
     }
    

    How to uncheck a checkbox in pure JavaScript?

    Recommended, without jQuery:

    Give your <input> an ID and refer to that. Also, remove the checked="" part of the <input> tag if you want the checkbox to start out unticked. Then it's:

    document.getElementById("my-checkbox").checked = true;
    

    Pure JavaScript, with no Element ID (#1):

    var inputs = document.getElementsByTagName('input');
    
    for(var i = 0; i<inputs.length; i++){
    
      if(typeof inputs[i].getAttribute === 'function' && inputs[i].getAttribute('name') === 'copyNewAddrToBilling'){
    
        inputs[i].checked = true;
    
        break;
    
      }
    }
    

    Pure Javascript, with no Element ID (#2):

    document.querySelectorAll('.text input[name="copyNewAddrToBilling"]')[0].checked = true;
    
    document.querySelector('.text input[name="copyNewAddrToBilling"]').checked = true;
    

    Note that the querySelectorAll and querySelector methods are supported in these browsers: IE8+, Chrome 4+, Safari 3.1+, Firefox 3.5+ and all mobile browsers.

    If the element may be missing, you should test for its existence, e.g.:

    var input = document.querySelector('.text input[name="copyNewAddrToBilling"]');
    if (!input) { return; }
    

    With jQuery:

    $('.text input[name="copyNewAddrToBilling"]').prop('checked', true);
    

    android listview item height

    I did something like that :

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    
        View view = super.getView(position, convertView, parent);
    
        TextView textView = (TextView) view.findViewById(android.R.id.text1);
        textView.setHeight(30);
        textView.setMinimumHeight(30);
    
        /*YOUR CHOICE OF COLOR*/
        textView.setTextColor(Color.BLACK);
    
        return view;
    }
    

    You must put the both fields textView.setHeight(30); textView.setMinimumHeight(30); or it won't change anything. For me it worked & i had the same problem.

    Running Google Maps v2 on the Android emulator

    I have successfully run our app, which requires Google Maps API 2, on an AndroVM virtual machine.

    AndroVM does not come with Google Maps or Google Play installed, but provides a modified copy of the Cyanogen Gapps archive, which is a set of the proprietary Google apps installed on most Android devices.

    The instructions, copied from the AndroVM FAQ:

    How can I install Google Apps (including the Market/Play app) ?

    • Download Google Apps : gapps-jb-20121011-androvm.tgz [basically the /system directory from the Cyanogen gapps archive without the GoogleTTS app which crashes on AndroVM]
    • Untar the gapps…tgz file on your host – you’ll have a system directory created
    • Get the management IP address of your AndroVM (“AndroVM Configuration” tool) and do “adb connect x.y.z.t”
    • do “adb root”
    • reconnect with “adn connect x.y.z.t”
    • do “adb remount”
    • do “adb push system/ /system/”

    Your VM will reboot and you should have google apps including Market/Play.

    You won’t have some Google Apps, like Maps, but they can be downloaded from the Market/Play.

    So follow those instructions, then just install Google Maps using Google Play!

    Some great side effects of using a VM rather than the emulator:

    • Vastly superior general performance
    • OpenGL acceleration
    • Google Play support

    The only bump in the road so far has been lack of multi-touch gestures, which is a bummer for a mapping app! I plan to work around this with a hidden UI mechanism, so not such a huge problem.

    CodeIgniter: How To Do a Select (Distinct Fieldname) MySQL Query

    You can also run ->select('DISTINCT `field`', FALSE) and the second parameter tells CI not to escape the first argument.

    With the second parameter as false, the output would be SELECT DISTINCT `field` instead of without the second parameter, SELECT `DISTINCT` `field`

    Error: Expression must have integral or unscoped enum type

    Your variable size is declared as: float size;

    You can't use a floating point variable as the size of an array - it needs to be an integer value.

    You could cast it to convert to an integer:

    float *temp = new float[(int)size];
    

    Your other problem is likely because you're writing outside of the bounds of the array:

       float *temp = new float[size];
    
        //Getting input from the user
        for (int x = 1; x <= size; x++){
            cout << "Enter temperature " << x << ": ";
    
            // cin >> temp[x];
            // This should be:
            cin >> temp[x - 1];
        }
    

    Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.

    What is the 'dynamic' type in C# 4.0 used for?

    It evaluates at runtime, so you can switch the type like you can in JavaScript to whatever you want. This is legit:

    dynamic i = 12;
    i = "text";
    

    And so you can change the type as you need. Use it as a last resort; it i s beneficial, but I heard a lot goes on under the scenes in terms of generated IL and that can come at a performance price.

    How to use sed to replace only the first occurrence in a file?

    As an alternative suggestion you may want to look at the ed command.

    man 1 ed
    
    teststr='
    #include <stdio.h>
    #include <stdlib.h>
    #include <inttypes.h>
    '
    
    # for in-place file editing use "ed -s file" and replace ",p" with "w"
    # cf. http://wiki.bash-hackers.org/howto/edit-ed
    cat <<-'EOF' | sed -e 's/^ *//' -e 's/ *$//' | ed -s <(echo "$teststr")
       H
       /# *include/i
       #include "newfile.h"
       .
       ,p
       q
    EOF
    

    HTML table headers always visible at top of window when viewing a large table

    It's frustrating that what works great in one browser doesn't work in others. The following works in Firefox, but not in Chrome or IE:

    <table width="80%">
    
     <thead>
    
     <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
     </tr>
    
     </thead>
    
     <tbody style="height:50px; overflow:auto">
    
      <tr>
        <td>Cell A1</td>
        <td>Cell B1</td>
        <td>Cell C1</td>
      </tr>
    
      <tr>
        <td>Cell A2</td>
        <td>Cell B2</td>
        <td>Cell C2</td>
      </tr>
    
      <tr>
        <td>Cell A3</td>
        <td>Cell B3</td>
        <td>Cell C3</td>
      </tr>
    
     </tbody>
    
    </table>
    

    Query for array elements inside JSON type

    Create a table with column as type json

    CREATE TABLE friends ( id serial primary key, data jsonb);
    

    Now let's insert json data

    INSERT INTO friends(data) VALUES ('{"name": "Arya", "work": ["Improvements", "Office"], "available": true}');
    INSERT INTO friends(data) VALUES ('{"name": "Tim Cook", "work": ["Cook", "ceo", "Play"], "uses": ["baseball", "laptop"], "available": false}');
    

    Now let's make some queries to fetch data

    select data->'name' from friends;
    select data->'name' as name, data->'work' as work from friends;
    

    You might have noticed that the results comes with inverted comma( " ) and brackets ([ ])

        name    |            work            
    ------------+----------------------------
     "Arya"     | ["Improvements", "Office"]
     "Tim Cook" | ["Cook", "ceo", "Play"]
    (2 rows)
    

    Now to retrieve only the values just use ->>

    select data->>'name' as name, data->'work'->>0 as work from friends;
    select data->>'name' as name, data->'work'->>0 as work from friends where data->>'name'='Arya';
    

    How can I use querySelector on to pick an input element by name?

    Note: if the name includes [ or ] itself, add two backslashes in front of it, like:

    <input name="array[child]" ...
    
    document.querySelector("[name=array\\[child\\]]");
    

    how to get the cookies from a php curl into a variable

    Although this question is quite old, and the accepted response is valid, I find it a bit unconfortable because the content of the HTTP response (HTML, XML, JSON, binary or whatever) becomes mixed with the headers.

    I've found a different alternative. CURL provides an option (CURLOPT_HEADERFUNCTION) to set a callback that will be called for each response header line. The function will receive the curl object and a string with the header line.

    You can use a code like this (adapted from TML response):

    $cookies = Array();
    $ch = curl_init('http://www.google.com/');
    // Ask for the callback.
    curl_setopt($ch, CURLOPT_HEADERFUNCTION, "curlResponseHeaderCallback");
    $result = curl_exec($ch);
    var_dump($cookies);
    
    function curlResponseHeaderCallback($ch, $headerLine) {
        global $cookies;
        if (preg_match('/^Set-Cookie:\s*([^;]*)/mi', $headerLine, $cookie) == 1)
            $cookies[] = $cookie;
        return strlen($headerLine); // Needed by curl
    }
    

    This solution has the drawback of using a global variable, but I guess this is not an issue for short scripts. And you can always use static methods and attributes if curl is being wrapped into a class.

    Get URL query string parameters

    Here is my function to rebuild parts of the REFERRER's query string.

    If the calling page already had a query string in its own URL, and you must go back to that page and want to send back some, not all, of that $_GET vars (e.g. a page number).

    Example: Referrer's query string was ?foo=1&bar=2&baz=3 calling refererQueryString( 'foo' , 'baz' ) returns foo=1&baz=3":

    function refererQueryString(/* var args */) {
    
        //Return empty string if no referer or no $_GET vars in referer available:
        if (!isset($_SERVER['HTTP_REFERER']) ||
            empty( $_SERVER['HTTP_REFERER']) ||
            empty(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY ))) {
    
            return '';
        }
    
        //Get URL query of referer (something like "threadID=7&page=8")
        $refererQueryString = parse_url(urldecode($_SERVER['HTTP_REFERER']), PHP_URL_QUERY);
    
        //Which values do you want to extract? (You passed their names as variables.)
        $args = func_get_args();
    
        //Get '[key=name]' strings out of referer's URL:
        $pairs = explode('&',$refererQueryString);
    
        //String you will return later:
        $return = '';
    
        //Analyze retrieved strings and look for the ones of interest:
        foreach ($pairs as $pair) {
            $keyVal = explode('=',$pair);
            $key = &$keyVal[0];
            $val = urlencode($keyVal[1]);
            //If you passed the name as arg, attach current pair to return string:
            if(in_array($key,$args)) {
                $return .= '&'. $key . '=' .$val;
            }
        }
    
        //Here are your returned 'key=value' pairs glued together with "&":
        return ltrim($return,'&');
    }
    
    //If your referer was 'page.php?foo=1&bar=2&baz=3'
    //and you want to header() back to 'page.php?foo=1&baz=3'
    //(no 'bar', only foo and baz), then apply:
    
    header('Location: page.php?'.refererQueryString('foo','baz'));
    

    Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

    Goto windows+R and type %temp% and hit enter. delete the temp folder and files and then try opening the same

    What is the best way to programmatically detect porn images?

    I would rather allow users report on bad images. Image recognition development can take too much efforts and time and won't be as much as accurate as human eyes. It's much cheaper to outsource that moderation job.

    Take a look at: Amazon Mechanical Turk

    "The Amazon Mechanical Turk (MTurk) is one of the suite of Amazon Web Services, a crowdsourcing marketplace that enables computer programs to co-ordinate the use of human intelligence to perform tasks which computers are unable to do."

    Can you use a trailing comma in a JSON object?

    Use JSON5. Don't use JSON.

    • Objects and arrays can have trailing commas
    • Object keys can be unquoted if they're valid identifiers
    • Strings can be single-quoted
    • Strings can be split across multiple lines
    • Numbers can be hexadecimal (base 16)
    • Numbers can begin or end with a (leading or trailing) decimal point.
    • Numbers can include Infinity and -Infinity.
    • Numbers can begin with an explicit plus (+) sign.
    • Both inline (single-line) and block (multi-line) comments are allowed.

    http://json5.org/

    https://github.com/aseemk/json5

    Create Map in Java

    With the newer Java versions (i.e., Java 9 and forwards) you can use :

    Map.of(1, new Point2D.Double(50, 50), 2, new Point2D.Double(100, 50), ...)
    

    generically:

    Map.of(Key1, Value1, Key2, Value2, KeyN, ValueN)
    

    Bear in mind however that Map.of only works for at most 10 entries, if you have more than 10 entries that you can use :

    Map.ofEntries(entry(1, new Point2D.Double(50, 50)), entry(2,  new Point2D.Double(100, 50)), ...);
    

    Format date and Subtract days using Moment.js

    startdate = moment().subtract(1, 'days').startOf('day')

    gdb: "No symbol table is loaded"

    I have the same problem and I followed this Post, it solved my problem.

    Follow the following 2 steps:

    1. Make sure the optimization level is -O0
    2. Add -ggdb flag when compiling your program

    Good luck!

    How to push a new folder (containing other folders and files) to an existing git repo?

    You need to git add my_project to stage your new folder. Then git add my_project/* to stage its contents. Then commit what you've staged using git commit and finally push your changes back to the source using git push origin master (I'm assuming you wish to push to the master branch).

    How can I insert data into a MySQL database?

    Here is OOP:

    import MySQLdb
    
    
    class Database:
    
        host = 'localhost'
        user = 'root'
        password = '123'
        db = 'test'
    
        def __init__(self):
            self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
            self.cursor = self.connection.cursor()
    
        def insert(self, query):
            try:
                self.cursor.execute(query)
                self.connection.commit()
            except:
                self.connection.rollback()
    
    
    
        def query(self, query):
            cursor = self.connection.cursor( MySQLdb.cursors.DictCursor )
            cursor.execute(query)
    
            return cursor.fetchall()
    
        def __del__(self):
            self.connection.close()
    
    
    if __name__ == "__main__":
    
        db = Database()
    
        #CleanUp Operation
        del_query = "DELETE FROM basic_python_database"
        db.insert(del_query)
    
        # Data Insert into the table
        query = """
            INSERT INTO basic_python_database
            (`name`, `age`)
            VALUES
            ('Mike', 21),
            ('Michael', 21),
            ('Imran', 21)
            """
    
        # db.query(query)
        db.insert(query)
    
        # Data retrieved from the table
        select_query = """
            SELECT * FROM basic_python_database
            WHERE age = 21
            """
    
        people = db.query(select_query)
    
        for person in people:
            print "Found %s " % person['name']
    

    Accessing Imap in C#

    MailSystem.NET contains all your need for IMAP4. It's free & open source.

    (I'm involved in the project)

    Cross-platform way of getting temp directory in Python

    The simplest way, based on @nosklo's comment and answer:

    import tempfile
    tmp = tempfile.mkdtemp()
    

    But if you want to manually control the creation of the directories:

    import os
    from tempfile import gettempdir
    tmp = os.path.join(gettempdir(), '.{}'.format(hash(os.times())))
    os.makedirs(tmp)
    

    That way you can easily clean up after yourself when you are done (for privacy, resources, security, whatever) with:

    from shutil import rmtree
    rmtree(tmp, ignore_errors=True)
    

    This is similar to what applications like Google Chrome and Linux systemd do. They just use a shorter hex hash and an app-specific prefix to "advertise" their presence.

    How can I output leading zeros in Ruby?

    Use String#next as the counter.

    >> n = "000"
    >> 3.times { puts "file_#{n.next!}" }
    file_001
    file_002
    file_003
    

    next is relatively 'clever', meaning you can even go for

    >> n = "file_000"
    >> 3.times { puts n.next! }
    file_001
    file_002
    file_003
    

    How to upgrade PowerShell version from 2.0 to 3.0

    Just run this in a console.

    @powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%systemdrive%\chocolatey\bin
    cinst powershell
    

    It installs the latest version using a Chocolatey repository.

    Originally I was using command cinst powershell 3.0.20121027, but it looks like it later stopped working. Since this question is related to PowerShell 3.0 this was the right way. At this moment (June 26, 2014) cinst powershell refers to version 3.0 of PowerShell, and that may change in future.

    See the Chocolatey PowerShell package page for details on what version will be installed.

    The number of method references in a .dex file cannot exceed 64k API 17

    Can also try this :

    android{
        .
        .
        // to avoid DexIndexOverflowException
        dexOptions {
           jumboMode true
        }
    }
    

    Hope it helps someone. Thanks

    How to Read from a Text File, Character by Character in C++

        //Variables
        char END_OF_FILE = '#';
        char singleCharacter;
    
        //Get a character from the input file
        inFile.get(singleCharacter);
    
        //Read the file until it reaches #
        //When read pointer reads the # it will exit loop
        //This requires that you have a # sign as last character in your text file
    
        while (singleCharacter != END_OF_FILE)
        {
             cout << singleCharacter;
             inFile.get(singleCharacter);
        }
    
       //If you need to store each character, declare a variable and store it
       //in the while loop.
    

    What JSON library to use in Scala?

    Maybe I've late a bit, but you really should try to use json library from play framework. You could look at documentation. In current 2.1.1 release you could not separately use it without whole play 2, so dependency will looks like this:

    val typesaferepo  = "TypeSafe Repo" at "http://repo.typesafe.com/typesafe/releases"
    val play2 = "play" %% "play" % "2.1.1"
    

    It will bring you whole play framework with all stuff on board.

    But as I know guys from Typesafe have a plan to separate it in 2.2 release. So, there is standalone play-json from 2.2-snapshot.

    Getting value from appsettings.json in .net core

        public static void GetSection()
        {
            Configuration = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json")
                .Build();
    
            string BConfig = Configuration.GetSection("ConnectionStrings")["BConnection"];
    
        }