For today's Date
$(document).ready(function() {
$('#textboxname').datepicker();
$('#textboxname').datepicker('setDate', 'today');});
In my case, I have given this attribute to the input tag
data-date-start-date="0d"
data-date-end-date="0d"
There are multiple suggestions here, but as far as I can see the jQuery UI guys have broken the dialogue control at present.
I say this because I include a dialogue on my page, and its semi transparent and the modal blanking div is behind some other elements. That can't be right!
In the end based on some other posts I developed this global solution, as an extension to the dialogue widget. It works for me but I'm not sure what it would do if I opened a dialogue from within a dialogue.
Basically it looks for the zIndex of everything else on the page and moves the .ui-widget-overlay to be one higher, and the dialogue itself to be one higher than that.
$.widget("ui.dialog", $.ui.dialog,
{
open: function ()
{
var $dialog = $(this.element[0]);
var maxZ = 0;
$('*').each(function ()
{
var thisZ = $(this).css('zIndex');
thisZ = (thisZ === 'auto' ? (Number(maxZ) + 1) : thisZ);
if (thisZ > maxZ) maxZ = thisZ;
});
$(".ui-widget-overlay").css("zIndex", (maxZ + 1));
$dialog.parent().css("zIndex", (maxZ + 2));
return this._super();
}
});
Thanks to the following, as this is where I got the info from of how to do this: https://stackoverflow.com/a/20942857
http://learn.jquery.com/jquery-ui/widget-factory/extending-widgets/
Be aware that there is org.codehaus.jackson.annotate.JsonProperty
in Jackson 1.x and com.fasterxml.jackson.annotation.JsonProperty
in Jackson 2.x. Check which ObjectMapper you are using (from which version), and make sure you use the proper annotation.
I use something like this in my document.ready
var height = $(window).height();//gets height from device
var width = $(window).width(); //gets width from device
$("#container").width(width+"px");
$("#container").height(height+"px");
var dt = new Date();
var renewal = moment(dt).add(1,'year').format('YYYY-MM-DD');
// moment().add(number, period)
// moment().subtract(number, period)
// period : year, days, hours, months, week...
You can use the Jquery UI for drag and drop with an additional library that translates mouse events into touch which is what you need, the library I recommend is https://github.com/furf/jquery-ui-touch-punch, with this your drag and drop from Jquery UI should work on touch devises
or you can use this code which I am using, it also converts mouse events into touch and it works like magic.
function touchHandler(event) {
var touch = event.changedTouches[0];
var simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent({
touchstart: "mousedown",
touchmove: "mousemove",
touchend: "mouseup"
}[event.type], true, true, window, 1,
touch.screenX, touch.screenY,
touch.clientX, touch.clientY, false,
false, false, false, 0, null);
touch.target.dispatchEvent(simulatedEvent);
event.preventDefault();
}
function init() {
document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);
}
And in your document.ready just call the init() function
code found from Here
Just want to add this for the future programmer.
This code limits the date min and max. The year is fully controlled by getting the current year as max year.
Hope this could help to anyone.
Here's the code.
var dateToday = new Date();
var yrRange = '2014' + ":" + (dateToday.getFullYear());
$(function () {
$("[id$=txtDate]").datepicker({
showOn: 'button',
changeMonth: true,
changeYear: true,
showButtonPanel: true,
buttonImageOnly: true,
yearRange: yrRange,
buttonImage: 'calendar3.png',
buttonImageOnly: true,
minDate: new Date(2014,1-1,1),
maxDate: '+50Y',
inline:true
});
});
var w = $('#dialogText').text().length;
$("#dialog").dialog('option', 'width', (w * 10));
did what i needed it to do for resizing the width of the dialog.
Just bind the datepicker to a class rather than binding it to the id . Remove the class when you want to revoke the datepicker...
$("#ddlSearchType").change(function () {
if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date") {
$("#txtSearch").addClass("mydate");
$(".mydate").datepicker()
} else {
$("#txtSearch").removeClass("mydate");
}
});
I had the same problem and it was solved by putting the references and includes in that order:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
var datePicker = angular.module('app', []);_x000D_
_x000D_
datePicker.directive('jqdatepicker', function () {_x000D_
return {_x000D_
restrict: 'A',_x000D_
require: 'ngModel',_x000D_
link: function (scope, element, attrs, ngModelCtrl) {_x000D_
element.datepicker({_x000D_
dateFormat: 'dd/mm/yy',_x000D_
onSelect: function (date) {_x000D_
scope.date = date;_x000D_
scope.$apply();_x000D_
}_x000D_
});_x000D_
}_x000D_
};_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>_x000D_
<link href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" rel="stylesheet"/>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>_x000D_
_x000D_
<body ng-app="app">_x000D_
<input type="text" ng-model="date" jqdatepicker />_x000D_
<br/>_x000D_
{{ date }}_x000D_
</body>
_x000D_
Sometimes you do not want use Datepicker http://jqueryui.com/datepicker/ in your project because:
Please see my very simple cross browser code for date input. My code apply only if your browser is not supports the date type input
<!doctype html>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" >_x000D_
<head>_x000D_
<title>Input Key Filter Test</title>_x000D_
<meta name="author" content="Andrej Hristoliubov [email protected]">_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>_x000D_
_x000D_
<!-- For compatibility of IE browser with audio element in the beep() function._x000D_
https://www.modern.ie/en-us/performance/how-to-use-x-ua-compatible -->_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=9"/>_x000D_
_x000D_
<link rel="stylesheet" href="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.css" type="text/css"> _x000D_
<script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/Common.js"></script>_x000D_
<script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<h1>Date field</h1>_x000D_
Date:_x000D_
<input type='date' id='date' />_x000D_
New date: <span id="NewDate"></span>_x000D_
<script>_x000D_
CreateDateFilter('date', {_x000D_
formatMessage: 'Please type date %s'_x000D_
, onblur: function (target) {_x000D_
if (target.value == target.defaultValue)_x000D_
return;_x000D_
document.getElementById('NewDate').innerHTML = target.value;_x000D_
}_x000D_
, min: new Date((new Date().getFullYear() - 10).toString()).toISOString().match(/^(.*)T.*$/i)[1]//'2006-06-27'//10 years ago_x000D_
, max: new Date().toISOString().match(/^(.*)T.*$/i)[1]//"2016-06-27" //Current date_x000D_
, dateLimitMessage: 'Please type date between "%min" and "%max"'_x000D_
}_x000D_
);_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Change draggable
attribute from
<span draggable="true">Label</span>
to
<span draggable="false">Label</span>
From what I can tell, per the documentation here: http://jqueryui.com/demos/tabs/#event-select, it seems as though you're not quite initializing it right. The demos state that you need a main wrapped <div>
element, with a <ul>
or possibly <ol>
element representing the tabs, and then an element for each tab page (presumable a <div>
or <p>
, possibly a <section>
if we're using HTML5). Then you call $().tabs() on the main <div>
, not the <ul>
element.
After that, you can bind to the tabsselect event no problem. Check out this fiddle for basic, basic example:
Building on @stankovski's answer, a more precise way of doing it which will work for all use cases (for example, when a tab is loading via ajax and so the anchor's href attribute doesn't correspond with the hash), the id in any case will correspond with the li element's "aria-controls" attribute. So for example if you are trying to activate a tab based on the location.hash, which is set to the tab id, then it is better to look for "aria-controls" than for "href".
With jQuery UI >= 1.9:
var index = $('#tabs > ul > li[aria-controls="simple-tab-2"]').parent().index();
$("#tabs").tabs("option", "active", index);
In the case of setting and checking the url hash:
When creating the tabs, use the 'activate' event to set the location.hash to the panel id:
$('#tabs').tabs({
activate: function(event, ui) {
var scrollTop = $(window).scrollTop(); // save current scroll position
window.location.hash = ui.newPanel.attr('id');
$(window).scrollTop(scrollTop); // keep scroll at current position
}
});
Then use the window hashchange event to compare the location.hash to the panel id (do this by looking for the li element's aria-controls attribute):
$(window).on('hashchange', function () {
if (!location.hash) {
$('#tabs').tabs('option', 'active', 0);
return;
}
$('#tabs > ul > li').each(function (index, li) {
if ('#' + $(li).attr('aria-controls') == location.hash) {
$('#tabs').tabs('option', 'active', index);
return;
}
});
});
This will handle all cases, even where tabs use ajax. Also if you have nested tabs, it isn't too difficult to handle that either using a little more logic.
You could use jquery ui's switchClass
, Heres an example:
$( "selector" ).switchClass( "oldClass", "newClass", 1000, "easeInOutQuad" );
Or see this jsfiddle.
This project on github may be your solution
If don't store it locally and use the link that they provide you might have an improved performance.The client might have the scripts already cached in some cases. As for the case of jQueryUI i would recommend not loading it until necessary. They are both minimized, but you can fire up the console and look at the network tab and see how long it takes for it to load, once it is initially downloaded it will be cached so you shouldn't worry afterwards.My conclusion would be yes use them both but use a CDN
The plugin developed by @dubrox is very lightweight and works almost identical to jQuery UI. My requirement was to have the ability to restrict the number of dates selected.
Intuitively, the maxPicks
property seems to have been provided for this purpose, but it doesn't work unfortunately.
For those of you looking for this fix, here it is:
First up, you need to patch jquery.ui.multidatespicker.js
. I have submitted a pull request on github. You can use that until dubrox merges it with the master or comes up with a fix of his own.
Usage is really straightforward. The below code causes the date picker to not select any dates once the specified number of dates (maxPicks
) has been already selected. If you unselect any previously selected date, it will let you select again until you reach the limit once again.
$("#mydatefield").multiDatesPicker({maxPicks: 3});
As Arnaud suggested in a comment to the original post, you should put this in your html header:
<meta http-equiv="X-UA-Compatible" content="IE=edge">
I don't want any cred for this. I just want to make it more visible for anyone else that come here.
In case if you find Active tab Index and then point to Active Tab
First get the Active index
var activeIndex = $("#panel").tabs('option', 'active');
Then using the css class get the tab content panel
// this will return the html element
var element= $("#panel").find( ".ui-tabs-panel" )[activeIndex];
now wrapped it in jQuery object to further use it
var tabContent$ = $(element);
here i want to add two info the class .ui-tabs-nav
is for Navigation associated with and .ui-tabs-panel
is associated with tab content panel. in this link demo in jquery ui website you will see this class is used - http://jqueryui.com/tabs/#manipulation
The parseInt solution is the best way to go as it is clear what is happening.
For completeness it is worth mentioning that this can also be done with the + operator
$('.load_more').live("click",function() { //When user clicks
var newcurrentpageTemp = +$(this).attr("id") + 1; //Get the id from the hyperlink
alert(newcurrentpageTemp);
dosomething();
});
i suspect that your default date format is different than the scripts default settigns. test your script with the 'dateformat' option
$( "#datepicker" ).datepicker({
dateFormat: 'dd-mm-yy'
});
instead of dd-mm-yy, your desired format
Use this code it will help you.
<script>
InitializeDate();
</script>
<input type="text" id="txtFromDate" class="datepicker calendar-icon" placeholder="From Date" style="width: 100px; margin-right: 10px; padding: 0px 0px 0px 7px;">
<input type="text" id="txtToDate" class="datepicker calendar-icon" placeholder="To Date" style="width: 100px; margin-right: 10px; padding: 0px 0px 0px 7px;">
function InitializeDate() {
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth() + 1;
var yyyy = date.getFullYear();
var ToDate = mm + '/' + dd + '/' + yyyy;
var FromDate = mm + '/01/' + yyyy;
$('#txtToDate').datepicker('setDate', ToDate);
$('#txtFromDate').datepicker('setDate', FromDate);
}
I was having the same problem. It ended up being the jquery.dimensions.js plugin. If I removed it, everything worked fine. I included it because of another plugin that required it, however I found out from the link here that dimensions was included in the jQuery core quite a while ago (http://api.jquery.com/category/dimensions). You should be ok simply getting rid of the dimensions plugin.
fix show position problem daterangepicker.jQuery.js
//Original Code
//show, hide, or toggle rangepicker
function showRP() {
if (rp.data('state') == 'closed') {
rp.data('state', 'open');
rp.fadeIn(300);
options.onOpen();
}
}
//Fixed
//show, hide, or toggle rangepicker
function showRP() {
rp.parent().css('left', rangeInput.offset().left);
rp.parent().css('top', rangeInput.offset().top + rangeInput.outerHeight());
if (rp.data('state') == 'closed') {
rp.data('state', 'open');
rp.fadeIn(300);
options.onOpen();
}
}
You can use belw code for show and hide bootstrap model.
$('#my-model').on('shown.bs.modal', function (e) {
// do something here...
})
and if you want to hide model then you can use below code.
$('#my-model').on('hidden.bs.modal', function() {
// do something here...
});
I hope this answer is useful for your project.
Without setting the type
attribute, you could also return false
from your OnClick
handler, and declare the onclick
attribute as onclick="return onBtnClick(event)"
.
Configuration Options:
$(document).ready(function () {
$("#companiesTable").dataTable({
"sPaginationType": "full_numbers",
"bJQueryUI": true,
"bAutoWidth": false, // Disable the auto width calculation
"aoColumns": [
{ "sWidth": "30%" }, // 1st column width
{ "sWidth": "30%" }, // 2nd column width
{ "sWidth": "40%" } // 3rd column width and so on
]
});
});
Specify the css for the table:
table.display {
margin: 0 auto;
width: 100%;
clear: both;
border-collapse: collapse;
table-layout: fixed; // add this
word-wrap:break-word; // add this
}
HTML:
<table id="companiesTable" class="display">
<thead>
<tr>
<th>Company name</th>
<th>Address</th>
<th>Town</th>
</tr>
</thead>
<tbody>
<% for(Company c: DataRepository.GetCompanies()){ %>
<tr>
<td><%=c.getName()%></td>
<td><%=c.getAddress()%></td>
<td><%=c.getTown()%></td>
</tr>
<% } %>
</tbody>
</table>
It works for me!
function calenderEdit(dob) {
var date= $('#'+dob).val();
$("#dob").datepicker({
changeMonth: true,
changeYear: true, yearRange: '1950:+10'
}).datepicker("setDate", date);
}
I wouldn't expect vertical tabs to need different Javascript from horizontal tabs. The only thing that would be different is the CSS for presenting the tabs and content on the page. JS for tabs generally does no more than show/hide/maybe load content.
You need to add quotes around the "ok". That is the text of the button. As it is, the button's text is currently empty (and hence not displayed) because it is trying to resolve the value of that variable.
Modal dialogs aren't meant to be closed in any fashion other than pressing the [ok] or [cancel] buttons. If you want the [x] in the right hand corner, set modal: false or just remove it altogether.
Modals always load the content into an element on the page, which more often than not is a div
. Think of this div
as the iframe
equivalent when it comes to jQuery UI Dialogs. Now it depends on your requirements whether you want static content that resides within the page or you want to fetch the content from some other location. You may use this code and see if it works for you:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>test</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<link rel="stylesheet" type="text/css" media="screen" href="css/jquery-ui-1.8.23.custom.css"/>
</head>
<body>
<p>First open a modal <a href="http://ibm.com" class="example"> dialog</a></p>
<div id="dialog"></div>
</body>
<!--jQuery-->
<script src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script src="js/jquery-ui-1.8.23.custom.min.js"></script>
<script type="text/javascript">
$(function(){
//modal window start
$(".example").unbind('click');
$(".example").bind('click',function(){
showDialog();
var titletext=$(this).attr("title");
var openpage=$(this).attr("href");
$("#dialog").dialog( "option", "title", titletext );
$("#dialog").dialog( "option", "resizable", false );
$("#dialog").dialog( "option", "buttons", {
"Close": function() {
$(this).dialog("close");
$(this).dialog("destroy");
}
});
$("#dialog").load(openpage);
return false;
});
//modal window end
//Modal Window Initiation start
function showDialog(){
$("#dialog").dialog({
height: 400,
width: 500,
modal: true
}
</script>
</html>
There are, however, a few things which you should keep in mind. You will not be able to load remote URL's on your local system, you need to upload to a server if you want to load remote URL. Even then, you may only load URL's which belong to the same domain; e.g. if you upload this file to 'www.example.com' you may only access files hosted on 'www.example.com'. For loading external links this might help. All this information you will find in the link as suggested by @Robin.
$('input').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [ array.indexOf(string) == -1 ]
}
});
Use minDate as string:
$('#datePickerId').datepicker({minDate: '0'});
This would set today as minimum selectable date .
This answer really helped me get started (noob) - but I encountered some weird behavior when I set a start date of 12/31/2014 and added +1 to default the end date. Instead of giving me an end date of 01/01/2015 I was getting 02/01/2015 (!!!). This version parses the components of the start date to avoid these end of year oddities.
$( "#date_start" ).datepicker({
minDate: 0,
dateFormat: "mm/dd/yy",
onSelect: function(selected) {
$("#date_end").datepicker("option","minDate", selected); // mindate on the End datepicker cannot be less than start date already selected.
var date = $(this).datepicker('getDate');
var tempStartDate = new Date(date);
var default_end = new Date(tempStartDate.getFullYear(), tempStartDate.getMonth(), tempStartDate.getDate()+1); //this parses date to overcome new year date weirdness
$('#date_end').datepicker('setDate', default_end); // Set as default
}
});
$( "#date_end" ).datepicker({
minDate: 0,
dateFormat: "mm/dd/yy",
onSelect: function(selected) {
$("#date_start").datepicker("option","maxDate", selected); // maxdate on the Start datepicker cannot be more than end date selected.
}
});
Use below Code, It worked for me.
<script type="text/javascript">
$(document).ready(function () {
$('#dialog').dialog({
autoOpen: false,
title: 'Basic Dialog'
});
$('#contactUs').click(function () {
$('#dialog').dialog('open');
});
});
</script>
If you are doing form validation such as
type="submit" onsubmit="return validateForm(this)"
validateForm = function(form) {
if ($('input#company').val() === "" || $('input#company').val() === "Company") {
$('input#company').val("Company").css('color','red'); finalReturn = false;
$('input#company').on('mouseover',(function() {
$('input#company').val("").css('color','black');
$('input#company').off('mouseover');
finalReturn = true;
}));
}
return finalReturn;
}
Double check you are returning true. This seems simple but I had
var finalReturn = false;
When the form was correct it was not being corrected by validateForm and so not being submitted as finalReturn was still initialized to false instead of true. By the way, above code works nicely with address, city, state and so on.
I use the dialog as an dialog file browser and uploader then I rewrite the code like this
var dialog1 = $("#dialog").dialog({
autoOpen: false,
height: 480,
width: 640
});
$('#tikla').click(function() {
dialog1.load('./browser.php').dialog('open');
});
everything seems to work great.
You have to initialize the datepicker before calling a datepicker method
Here is a
$("#mydate").datepicker().datepicker("setDate", new Date());_x000D_
//-initialization--^ ^-- method invokation
_x000D_
<link href="https://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>_x000D_
<input type="text" id="mydate" />
_x000D_
P.S: This assumes that you have the correct date set in your computer
... Thanks guys... all I needed was the 'value' of the checked radio button where each radio button in the set had a different id...
var user_cat = $("input[name='user_cat']:checked").val();
works for me...
I am a fan of one-liners (where they work!). Here is what works for me:
$("#dialog").siblings(".ui-dialog-titlebar").find(".ui-dialog-titlebar-close").hide();
I had the same exact issue, Maybe you already chececked this but got it solved just by placing the "images" folder in the same location as the jquery-ui.css
If you should need to replace the handle with something else entirely, rather than just restyling it:
$('.slider').append('<div class="my-handle ui-slider-handle"><svg height="18" width="14"><path d="M13,9 5,1 A 10,10 0, 0, 0, 5,17z"/></svg></div>');_x000D_
_x000D_
$('.slider').slider({_x000D_
range: "min",_x000D_
value: 10_x000D_
});
_x000D_
.slider .ui-state-default {_x000D_
background: none;_x000D_
}_x000D_
.slider.ui-slider .ui-slider-handle {_x000D_
width: 14px;_x000D_
height: 18px;_x000D_
margin-left: -5px;_x000D_
top: -4px;_x000D_
border: none;_x000D_
background: none;_x000D_
}_x000D_
.slider {_x000D_
height: 10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.9.1/jquery-ui.min.js"></script>_x000D_
<link href="https://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" />_x000D_
<div class="slider"></div>
_x000D_
NamingException's answer worked for me. Except I used
var date = $("#date").dtpicker({ dateFormat: 'dd,MM,yyyy' }).val()
datepicker
didn't work but dtpicker
did.
Here is example how you can do localization by yourself.
jQuery(function($) {_x000D_
$('input.datetimepicker').datepicker({_x000D_
duration: '',_x000D_
changeMonth: false,_x000D_
changeYear: false,_x000D_
yearRange: '2010:2020',_x000D_
showTime: false,_x000D_
time24h: true_x000D_
});_x000D_
_x000D_
$.datepicker.regional['cs'] = {_x000D_
closeText: 'Zavrít',_x000D_
prevText: '<Dríve',_x000D_
nextText: 'Pozdeji>',_x000D_
currentText: 'Nyní',_x000D_
monthNames: ['leden', 'únor', 'brezen', 'duben', 'kveten', 'cerven', 'cervenec', 'srpen',_x000D_
'zárí', 'ríjen', 'listopad', 'prosinec'_x000D_
],_x000D_
monthNamesShort: ['led', 'úno', 'bre', 'dub', 'kve', 'cer', 'cvc', 'srp', 'zár', 'ríj', 'lis', 'pro'],_x000D_
dayNames: ['nedele', 'pondelí', 'úterý', 'streda', 'ctvrtek', 'pátek', 'sobota'],_x000D_
dayNamesShort: ['ne', 'po', 'út', 'st', 'ct', 'pá', 'so'],_x000D_
dayNamesMin: ['ne', 'po', 'út', 'st', 'ct', 'pá', 'so'],_x000D_
weekHeader: 'Týd',_x000D_
dateFormat: 'dd/mm/yy',_x000D_
firstDay: 1,_x000D_
isRTL: false,_x000D_
showMonthAfterYear: false,_x000D_
yearSuffix: ''_x000D_
};_x000D_
_x000D_
$.datepicker.setDefaults($.datepicker.regional['cs']);_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link data-require="jqueryui@*" data-semver="1.10.0" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/css/smoothness/jquery-ui-1.10.0.custom.min.css" />_x000D_
<script data-require="jqueryui@*" data-semver="1.10.0" src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/jquery-ui.js"></script>_x000D_
<script src="datepicker-cs.js"></script>_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
console.log("test");_x000D_
$("#test").datepicker({_x000D_
dateFormat: "dd.m.yy",_x000D_
minDate: 0,_x000D_
showOtherMonths: true,_x000D_
firstDay: 1_x000D_
});_x000D_
});_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<h1>Here is your datepicker</h1>_x000D_
<input id="test" type="text" />_x000D_
</body>_x000D_
</html>
_x000D_
This solution may help.
$(document).ready(function () {_x000D_
var userLang = navigator.language || navigator.userLanguage;_x000D_
_x000D_
var options = $.extend({},_x000D_
$.datepicker.regional["ja"], {_x000D_
dateFormat: "yy/mm/dd",_x000D_
changeMonth: true,_x000D_
changeYear: true,_x000D_
highlightWeek: true_x000D_
}_x000D_
);_x000D_
_x000D_
$("#japaneseCalendar").datepicker(options);_x000D_
});
_x000D_
#ui-datepicker-div {_x000D_
font-size: 14px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<link rel="stylesheet" type="text/css"_x000D_
href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.min.css">_x000D_
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<h3>Japanese JQuery UI Datepicker</h3>_x000D_
<input type="text" id="japaneseCalendar"/>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
jQuery now has a CDN access:
code.jquery.com/ui/[version]/themes/[theme name]/jquery-ui.css
And to make this a little more easy, Here you go:
just trigger a click, it's work for me:
$("#tabX").trigger("click");
You can try this
$('#startdate').val()
or
$('#startdate').data('date')
If you're including the .button()
plugin/widget that jQuery UI contains (if you have the full library and are on 1.8+, you have it), you can use it to disable the button and update the state visually, like this:
$(".ui-dialog-buttonpane button:contains('Confirm')").button("disable");
You can give it a try here...or if you're on an older version or not using the button widget, you can disable it like this:
$(".ui-dialog-buttonpane button:contains('Confirm')").attr("disabled", true)
.addClass("ui-state-disabled");
If you want it inside a specific dialog, say by ID, then do this:
$("#dialogID").next(".ui-dialog-buttonpane button:contains('Confirm')")
.attr("disabled", true);
In other cases where :contains()
might give false positives then you can use .filter()
like this, but it's overkill here since you know your two buttons. If that is the case in other situations, it'd look like this:
$("#dialogID").next(".ui-dialog-buttonpane button").filter(function() {
return $(this).text() == "Confirm";
}).attr("disabled", true);
This would prevent :contains()
from matching a substring of something else.
It has been a while since this question was posted, but the following code works across all browsers (note although MattPII
's answer works in FFox and Chrome, it throws script errors in IE).
$('#foo').dialog({
autoOpen: true,
buttons: [
{
text: 'OK',
open: function() { $(this).addClass('b') }, //will append a class called 'b' to the created 'OK' button.
click: function() { alert('OK Clicked')}
},
{
text: "Cancel",
click: function() { alert('Cancel Clicked')}
}
]
});
Register an event listener for keyup
event:
document.getElementById("input").addEventListener("keyup", function(e){
var someVarName = input.value;
sessionStorage.setItem("someVarKey", someVarName);
input.value = sessionStorage.getItem("someVarKey");
});
The obvious answer would be to generate different ids, a separate id for each text box, something like
[int i=0]
<% Using Html.BeginForm()%>
<% For Each item In Model.MyRecords%>
[i++]
<%=Html.TextBox("my_date[i]")%> <br/>
<% Next%>
<% End Using%>
I don't know ASP.net so I just added some general C-like syntax code within square brackets. Translating it to actual ASP.net code shouldn't be a problem.
Then, you have to find a way to generate as many
$('#my_date[i]').datepicker();
as items in your Model.MyRecords
. Again, within square brackets is your counter, so your jQuery function would be something like:
<script type="text/javascript">
$(function() {
$('#my_date1').datepicker();
$('#my_date2').datepicker();
$('#my_date3').datepicker();
...
});
</script>
The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.
It's very simple:
$(":button:contains('Authenticate')").prop("disabled", true).addClass("ui-state-disabled");
If someone wants expandable/collapsible version of the treeview from Vitaliy Bychik's answer, you can save some time :)
http://jsfiddle.net/mehmetatas/fXzHS/2/
$(function () {
$('.tree li').hide();
$('.tree li:first').show();
$('.tree li').on('click', function (e) {
var children = $(this).find('> ul > li');
if (children.is(":visible")) children.hide('fast');
else children.show('fast');
e.stopPropagation();
});
});
I used jsPDF
and dom-to-image
library to export HTML to PDF.
I post here as reference to whom concern.
$('#downloadPDF').click(function () {
domtoimage.toPng(document.getElementById('content2'))
.then(function (blob) {
var pdf = new jsPDF('l', 'pt', [$('#content2').width(), $('#content2').height()]);
pdf.addImage(blob, 'PNG', 0, 0, $('#content2').width(), $('#content2').height());
pdf.save("test.pdf");
});
});
A lot of great editors have come out since my original answer. I currently use the following text editors: Sublime Text 3 (Mac/Windows), Visual Studio Code (Mac/Windows) and Atom (Mac/Windows). I also use the following IDEs: Visual Studio 2015 (Windows/Paid & Free Versions) and Jetrbrains WebStorm (Windows/Paid, tried the demo and liked it).
My preference is using Sublime Text 3.
Microsoft Web Matrix and Dreamweaver are great.
Visual Studio and Expression Web are also great but may be overkill for you.
For just plain text editors, Sublime Text 2 is really cool
you can also overwrite bootstrap.css by simply removing "top:-25%;"
once removed, the modal will simply fade in and out without the slide animation.
Set specific tab index as active:
$(this).tabs({ active: # }); /* Where # is the tab index. The index count starts at 0 */
Set last tab as active
$(this).tabs({ active: -1 });
Set specific tab by ID:
$(this).tabs({ active: $('a[href="#tab-101"]').parent().index() });
Update (2017): The following two libraries have now become the most common drop-down libraries used with Javascript. While they are jQuery-native, they have been customized to work with everything from AngularJS 1.x to having custom CSS for Bootstrap. (Chosen JS, the original answer here, seems to have dropped to #3 in popularity.)
Obligatory screenshots below.
Original answer (2012): I think that the Chosen library might also be useful. Its available in jQuery, Prototype and MooTools versions.
Attached is a screenshot of how the multi-select functionality looks in Chosen.
$('div#someID').datepicker({
onSelect: function(dateText, inst) { alert(dateText); }
});
you must bind it to input element only
Use the minDate option to set the minimum possible date. http://jqueryui.com/demos/datepicker/#option-minDate
You can use the open event handler to apply additional styling:
open: function(event) {
$('.ui-dialog-buttonpane').find('button:contains("Cancel")').addClass('cancelButton');
}
I had the same problem and, after a day of research, I came up with this solution: http://jsfiddle.net/konstantc/4jkef3a1/
// *** (month and year only) ***_x000D_
$(function() { _x000D_
$('#datepicker1').datepicker( {_x000D_
yearRange: "c-100:c",_x000D_
changeMonth: true,_x000D_
changeYear: true,_x000D_
showButtonPanel: true,_x000D_
closeText:'Select',_x000D_
currentText: 'This year',_x000D_
onClose: function(dateText, inst) {_x000D_
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();_x000D_
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
$(this).val($.datepicker.formatDate('MM yy (M y) (mm/y)', new Date(year, month, 1)));_x000D_
}_x000D_
}).focus(function () {_x000D_
$(".ui-datepicker-calendar").hide();_x000D_
$(".ui-datepicker-current").hide();_x000D_
$("#ui-datepicker-div").position({_x000D_
my: "left top",_x000D_
at: "left bottom",_x000D_
of: $(this)_x000D_
});_x000D_
}).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------_x000D_
_x000D_
_x000D_
_x000D_
// *** (year only) ***_x000D_
$(function() { _x000D_
$('#datepicker2').datepicker( {_x000D_
yearRange: "c-100:c",_x000D_
changeMonth: false,_x000D_
changeYear: true,_x000D_
showButtonPanel: true,_x000D_
closeText:'Select',_x000D_
currentText: 'This year',_x000D_
onClose: function(dateText, inst) {_x000D_
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
$(this).val($.datepicker.formatDate('yy', new Date(year, 1, 1)));_x000D_
}_x000D_
}).focus(function () {_x000D_
$(".ui-datepicker-month").hide();_x000D_
$(".ui-datepicker-calendar").hide();_x000D_
$(".ui-datepicker-current").hide();_x000D_
$(".ui-datepicker-prev").hide();_x000D_
$(".ui-datepicker-next").hide();_x000D_
$("#ui-datepicker-div").position({_x000D_
my: "left top",_x000D_
at: "left bottom",_x000D_
of: $(this)_x000D_
});_x000D_
}).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------_x000D_
_x000D_
_x000D_
_x000D_
// *** (year only, no controls) ***_x000D_
$(function() { _x000D_
$('#datepicker3').datepicker( {_x000D_
dateFormat: "yy",_x000D_
yearRange: "c-100:c",_x000D_
changeMonth: false,_x000D_
changeYear: true,_x000D_
showButtonPanel: false,_x000D_
closeText:'Select',_x000D_
currentText: 'This year',_x000D_
onClose: function(dateText, inst) {_x000D_
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
$(this).val($.datepicker.formatDate('yy', new Date(year, 1, 1)));_x000D_
},_x000D_
onChangeMonthYear : function () {_x000D_
$(this).datepicker( "hide" );_x000D_
}_x000D_
}).focus(function () {_x000D_
$(".ui-datepicker-month").hide();_x000D_
$(".ui-datepicker-calendar").hide();_x000D_
$(".ui-datepicker-current").hide();_x000D_
$(".ui-datepicker-prev").hide();_x000D_
$(".ui-datepicker-next").hide();_x000D_
$("#ui-datepicker-div").position({_x000D_
my: "left top",_x000D_
at: "left bottom",_x000D_
of: $(this)_x000D_
});_x000D_
}).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
<h2 class="font-weight-light text-lg-left mt-4 mb-0"><b>jQuery UI Datepicker</b> custom select</h2>_x000D_
_x000D_
<hr class="mt-2 mb-3">_x000D_
<div class="row text-lg-left">_x000D_
<div class="col-12">_x000D_
_x000D_
<form>_x000D_
_x000D_
<div class="form-label-group">_x000D_
<label for="datepicker1">(month and year only : <code>id="datepicker1"</code> )</label>_x000D_
<input type="text" class="form-control" id="datepicker1" _x000D_
placeholder="(month and year only)" />_x000D_
</div>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<div class="form-label-group">_x000D_
<label for="datepicker2">(year only : <code>input id="datepicker2"</code> )</label>_x000D_
<input type="text" class="form-control" id="datepicker2" _x000D_
placeholder="(year only)" />_x000D_
</div>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<div class="form-label-group">_x000D_
<label for="datepicker3">(year only, no controls : <code>input id="datepicker3"</code> )</label>_x000D_
<input type="text" class="form-control" id="datepicker3" _x000D_
placeholder="(year only, no controls)" />_x000D_
</div>_x000D_
_x000D_
</form>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
I know this question is pretty old but I thought that my solution can be of use to others that encounter this problem. Hope it helps.
Hi you can try viewing this jsFiddle.
I used this code:
var day = $(this).datepicker('getDate').getDate();
var month = $(this).datepicker('getDate').getMonth();
var year = $(this).datepicker('getDate').getYear();
I hope this helps.
If you want to check if the dialog's open on a particular element you can do this:
if ($('#elem').closest('.ui-dialog').is(':visible')) {
// do something
}
Or if you just want to check if the element itself is visible you can do:
if ($('#elem').is(':visible')) {
// do something
}
Or...
if ($('#elem:visible').length) {
// do something
}
Ok the first issue with the div tag was easy enough:
I just added a style="display:none;"
to it and then before showing the dialog I added this in my dialog script:
$("#dialog").css("display", "inherit");
But for the post version I'm still out of luck.
You need to use the ui.item.label (the text) and ui.item.value (the id) properties
$('#selector').autocomplete({
source: url,
select: function (event, ui) {
$("#txtAllowSearch").val(ui.item.label); // display the selected text
$("#txtAllowSearchID").val(ui.item.value); // save selected id to hidden input
}
});
$('#button').click(function() {
alert($("#txtAllowSearchID").val()); // get the id from the hidden input
});
[Edit] You also asked how to create the multi-dimensional array...
You should be able create the array like so:
var $local_source = [[0,"c++"], [1,"java"], [2,"php"], [3,"coldfusion"],
[4,"javascript"], [5,"asp"], [6,"ruby"]];
Read more about how to work with multi-dimensional arrays here: http://www.javascriptkit.com/javatutors/literal-notation2.shtml
With ES6 you can write this:
const countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
const $ul = $('<ul>', { class: "mylist" }).append(
countries.map(country =>
$("<li>").append($("<a>").text(country))
)
);
Try like this
$("#drop").change(function () {
var end = this.value;
var firstDropVal = $('#pick').val();
});
You have a couple of options...
1) You need to call the destroy()
method not remove()
so...
$('#date').datepicker('destroy');
Then call your method to recreate the datepicker
object.
2) You can update the property of the existing object
via
$('#date').datepicker('option', 'minDate', new Date(startDate));
$('#date').datepicker('option', 'maxDate', new Date(endDate));
or...
$('#date').datepicker('option', { minDate: new Date(startDate),
maxDate: new Date(endDate) });
You can call sortable
on a <tbody>
instead of on the individual rows.
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>?
<script>
$('tbody').sortable();
</script>
$(function() {_x000D_
$( "tbody" ).sortable();_x000D_
});
_x000D_
_x000D_
table {_x000D_
border-spacing: collapse;_x000D_
border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
width: 50px;_x000D_
height: 25px;_x000D_
border: 1px solid black;_x000D_
}
_x000D_
_x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td>4</td>_x000D_
</tr>_x000D_
<tr> _x000D_
<td>5</td>_x000D_
<td>6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>7</td>_x000D_
<td>8</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>9</td> _x000D_
<td>10</td>_x000D_
</tr> _x000D_
</tbody> _x000D_
</table>
_x000D_
Set the auto complete:
$("#searchBox").autocomplete({
source: queryDB
});
The source function that gets the data:
function queryDB(request, response) {
var query = request.term;
var data = getDataFromDB(query);
response(data); //puts the results on the UI
}
I have done a jQuery plugin that has the same look of jQuery UI Accordion and can keep all tabs\sections open
you can find it here
http://anasnakawa.wordpress.com/2011/01/25/jquery-ui-multi-open-accordion/
works with the same markup
<div id="multiOpenAccordion">
<h3><a href="#">tab 1</a></h3>
<div>Lorem ipsum dolor sit amet</div>
<h3><a href="#">tab 2</a></h3>
<div>Lorem ipsum dolor sit amet</div>
</div>
Javascript code
$(function(){
$('#multiOpenAccordion').multiAccordion();
// you can use a number or an array with active option to specify which tabs to be opened by default:
$('#multiOpenAccordion').multiAccordion({ active: 1 });
// OR
$('#multiOpenAccordion').multiAccordion({ active: [1, 2, 3] });
$('#multiOpenAccordion').multiAccordion({ active: false }); // no opened tabs
});
UPDATE: the plugin has been updated to support default active tabs option
UPDATE: This plugin is now deprecated.
You did not include the datepicker library
so add
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>
to your <head>
tag
root/
assets/
lib/-------------------------libraries--------------------
bootstrap/--------------Libraries can have js/css/images------------
css/
js/
images/
jquery/
js/
font-awesome/
css/
images/
common/--------------------common section will have application level resources
css/
js/
img/
index.html
This is how I organized my application's static resources.
Try this:
<script type="text/javascript">
$.fn.toggleFuncs = function() {
var functions = Array.prototype.slice.call(arguments),
_this = this.click(function(){
var i = _this.data('func_count') || 0;
functions[i%functions.length]();
_this.data('func_count', i+1);
});
}
$('$showmenu').toggleFuncs(
function() {
$( ".menu" ).toggle( "drop" );
},
function() {
$( ".menu" ).toggle( "drop" );
}
);
</script>
First fuction is an alternative to JQuery deprecated toggle :) . Works good with JQuery 2.0.3 and JQuery UI 1.10.3
Here is an out of the box future proof date snippet. Firefox defaults to jquery ui datepicker. Otherwise HTML5 datepicker is used. If FF ever support HTML5 type="date" the script will simply be redundant. Dont forget the three dependencies are needed in the head tag.
<script>
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<link rel="stylesheet"href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!--Form element uses HTML 5 type="date"-->
<div class="form-group row">
<label for="date" class="col-sm-2 col-form-label"Date</label>
<div class="col-sm-10">
<input type="date" class="form-control" name="date" id="date" placeholder="date">
</div>
</div>
<!--if the user is using FireFox it
autoconverts type='date' into type='text'. If the type is text the
script below will assign the jquery ui datepicker with options-->
<script>
$(function()
{
var elem = document.createElement('input');
elem.setAttribute('type', 'date');
if ( elem.type === 'text' )
{
$('#date').datepicker();
$( "#date" ).datepicker( "option", "dateFormat", 'yy-mm-dd' );
}
});
A lot of these seem to be overcomplicated. I achieved what I wanted with just the following:
$(".ui-accordion-content").show();
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()
Jquery Touch Punch is great but what it also does is disable all the controls on the draggable div so to prevent this you have to alter the lines... (at the time of writing - line 75)
change
if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])){
to read
if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0]) || event.originalEvent.target.localName === 'textarea'
|| event.originalEvent.target.localName === 'input' || event.originalEvent.target.localName === 'button' || event.originalEvent.target.localName === 'li'
|| event.originalEvent.target.localName === 'a'
|| event.originalEvent.target.localName === 'select' || event.originalEvent.target.localName === 'img') {
add as many ors as you want for each of the elements you want to 'unlock'
Hope that helps someone
Although this is a old post, I have spent 3 hours to fix my issue and I think this might help someone in future.
Here is my jquery-dialog
hack to show html content inside an <iframe>
:
let modalProperties = {autoOpen: true, width: 900, height: 600, modal: true, title: 'Modal Title'};
let modalHtmlContent = '<div>My Content First div</div><div>My Content Second div</div>';
// create wrapper iframe
let wrapperIframe = $('<iframe src="" frameborder="0" style="width:100%; height:100%;"></iframe>');
// create jquery dialog by a 'div' with 'iframe' appended
$("<div></div>").append(wrapperIframe).dialog(modalProperties);
// insert html content to iframe 'body'
let wrapperIframeDocument = wrapperIframe[0].contentDocument;
let wrapperIframeBody = $('body', wrapperIframeDocument);
wrapperIframeBody.html(modalHtmlContent);
With ASP.NET just use UseSubmitBehavior="false"
in your ASP.NET button:
<asp:Button ID="btnButton" runat="server" Text="Button" onclick="btnButton_Click" UseSubmitBehavior="false" />
Reference: Button.UseSubmitBehavior Property
That is because you are trying to access the plugin before it's loaded. You should try making a call to it when the DOM is loaded by surrounding it with this:
$(document).ready(function(){
$("#colorpicker").colorpicker();
}
You can use jQuery UI and do something like this
Html:
<button id="callConfirm">Confirm!</button>
<div id="dialog" title="Confirmation Required">
Are you sure about this?
</div>?
Javascript:
$("#dialog").dialog({
autoOpen: false,
modal: true,
buttons : {
"Confirm" : function() {
alert("You have confirmed!");
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
$("#callConfirm").on("click", function(e) {
e.preventDefault();
$("#dialog").dialog("open");
});
?
You need to run the .datepicker();
again after you've dynamically created the other textbox elements.
I would recommend doing so in the callback method of the call that is adding the elements to the DOM.
So lets say you're using the JQuery Load method to pull the elements from a source and load them into the DOM, you would do something like this:
$('#id_of_div_youre_dynamically_adding_to').load('ajax/get_textbox', function() {
$(".datepicker_recurring_start" ).datepicker();
});
If MouseEvent.offsetX is supported by your browser (all major browsers actually support it), The jQuery Event object will contain this property.
The MouseEvent.offsetX read-only property provides the offset in the X coordinate of the mouse pointer between that event and the padding edge of the target node.
$("#seek-bar").click(function(event) {
var x = event.offsetX
alert(x);
});
As a quick addition, and I'm surprised nobody has thought of this, you could use the in
operator:
"chrome" in window
Obviously this isn't using JQuery, but I figured I'd put it since it's handy for times when you aren't using any external libraries.
Use jquery animate and give it a long duration say 2000
$("#Friends").animate({
top: "-=30px",
}, duration );
The -= means that the animation will be relative to the current top position.
Note that the Friends
element must have position set to relative in the css:
#Friends{position:relative;}
As long as we're using jQuery (> v1.8), we can parse the incoming string with $.parseHTML().
$('.tooltip').tooltip({
content: function () {
var tooltipContent = $('<div />').html( $.parseHTML( $(this).attr('title') ) );
return tooltipContent;
},
});
We'll parse the incoming string's attribute for unpleasant things, then convert it back to jQuery-readable HTML. The beauty of this is that by the time it hits the parser the strings are already concatenates, so it doesn't matter if someone is trying to split the script tag into separate strings. If you're stuck using jQuery's tooltips, this appears to be a solid solution.
Since "$(this).parent().index();" and "$(this).parent('table').index();" don't work for me, I use this code instead:
$('td').click(function(){
var row_index = $(this).closest("tr").index();
var col_index = $(this).index();
});
This is bit of an opinion piece, but we had great success with WebShims. It can decay cleanly to use jQuery datepicker if native is not available. Demo here
You did not include jquery library. In jsfiddle its already there. Just include this line in your head section.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
If you are using HTML 5, there is the <audio>
element.
On MDN:
The
audio
element is used to embed sound content in an HTML or XHTML document. The audio element was added as part of HTML5.
Update:
In order to play audio in the browser in HTML versions before 5 (including XHTML), you need to use one of the many flash audio players.
You may want to check out Eclipse CDT. It provides a C/C++ IDE that runs on multiple platforms (e.g. Windows, Linux, Mac OS X, etc.). Debugging with Eclipse CDT is comparable to using other tools such as Visual Studio.
You can check out the Eclipse CDT Debug tutorial that also includes a number of screenshots.
"Line 1" - maybe something about windows vs unix newlines? (as i saw windows 7 mentioned above).
There are two ways, one httpCookies
element in web.config
allows you to turn on requireSSL
which only transmit all cookies including session in SSL only and also inside forms authentication, but if you turn on SSL on httpcookies you must also turn it on inside forms configuration too.
Edit for clarity:
Put this in <system.web>
<httpCookies requireSSL="true" />
You can use ComboBox, then point your mouse to the upper arrow facing right, it will unfold a box called ComboBox Tasks and in there you can go ahead and edit your items or fill in the items / strings one per line. This should be the easiest.
var myError = new Error('foo');
myError instanceof Error // true
var myString = "Whatever";
myString instanceof Error // false
Only problem with this is
myError instanceof Object // true
An alternative to this would be to use the constructor property.
myError.constructor === Object // false
myError.constructor === String // false
myError.constructor === Boolean // false
myError.constructor === Symbol // false
myError.constructor === Function // false
myError.constructor === Error // true
Although it should be noted that this match is very specific, for example:
myError.constructor === TypeError // false
For me, dataBinding { enabled true } was enabled in gradle, removing this helped me
I tried reading from input1.txt which was inside one of my packages together with the class which was trying to read it.
The following works:
String fileName = FileTransferClient.class.getResource("input1.txt").getPath();
System.out.println(fileName);
BufferedReader bufferedTextIn = new BufferedReader(new FileReader(fileName));
The most important part was to call getPath()
if you want the correct path name in String format. DO NOT USE toString()
because it will add some extra formatting text which will TOTALLY MESS UP the fileName (you can try it and see the print out).
Spent 2 hours debugging this... :(
import time
start = time.time()
fun()
# python 2
print 'It took', time.time()-start, 'seconds.'
# python 3
print('It took', time.time()-start, 'seconds.')
Use:
('#yourdropdownid').find(':selected').text();
Use this one
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
@Test
public void testInsertObject() throws Exception {
String url = BASE_URL + "/object";
ObjectBean anObject = new ObjectBean();
anObject.setObjectId("33");
anObject.setUserId("4268321");
//... more
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
String requestJson=ow.writeValueAsString(anObject );
mockMvc.perform(post(url).contentType(APPLICATION_JSON_UTF8)
.content(requestJson))
.andExpect(status().isOk());
}
As described in the comments, this works because the object is converted to json and passed as the request body. Additionally, the contentType is defined as Json (APPLICATION_JSON_UTF8).
When you use a const
string, the compiler embeds the string's value at compile-time.
Therefore, if you use a const
value in a different assembly, then update the original assembly and change the value, the other assembly won't see the change until you re-compile it.
A static readonly
string is a normal field that gets looked up at runtime. Therefore, if the field's value is changed in a different assembly, the changes will be seen as soon as the assembly is loaded, without recompiling.
This also means that a static readonly
string can use non-constant members, such as Environment.UserName
or DateTime.Now.ToString()
. A const
string can only be initialized using other constants or literals.
Also, a static readonly
string can be set in a static constructor; a const
string can only be initialized inline.
Note that a static string
can be modified; you should use static readonly
instead.
They don't do the same thing. The first one works if obj is of type ClassA or of some subclass of ClassA. The second one will only match objects of type ClassA. The second one will be faster since it doesn't have to check the class hierarchy.
For those who want to know the reason, but don't want to read the article referenced in is vs typeof.
You may want to create a subRepeater.
<asp:Repeater ID="SubRepeater" runat="server" DataSource='<%# Eval("Fields") %>'>
<ItemTemplate>
<span><%# Eval("Name") %></span>
</ItemTemplate>
</asp:Repeater>
You can also cast your fields
<%# ((ArrayFields)Container.DataItem).Fields[0].Name %>
Finally you could do a little CSV Function and write out your fields with a function
<%# GetAsCsv(((ArrayFields)Container.DataItem).Fields) %>
public string GetAsCsv(IEnumerable<Fields> fields)
{
var builder = new StringBuilder();
foreach(var f in fields)
{
builder.Append(f);
builder.Append(",");
}
builder.Remove(builder.Length - 1);
return builder.ToString();
}
to clarify your question:
From Python Source code to Java source code? (I don't think so)
.. or from Python source code to Java Bytecode? (Jython does this under the hood)
You shouldn't use float unless you have to. In 99% of cases, double is a better choice.
int x = 1111111111;
int y = 10000;
float f = (float) x / y;
double d = (double) x / y;
System.out.println("f= "+f);
System.out.println("d= "+d);
prints
f= 111111.12
d= 111111.1111
Following @Matt's comment.
float has very little precision (6-7 digits) and shows significant rounding error fairly easily. double has another 9 digits of accuracy. The cost of using double instead of float is notional in 99% of cases however the cost of a subtle bug due to rounding error is much higher. For this reason, many developers recommend not using floating point at all and strongly recommend BigDecimal.
However I find that double can be used in most cases provided sensible rounding is used.
In this case, int x has 32-bit precision whereas float has a 24-bit precision, even dividing by 1 could have a rounding error. double on the other hand has 53-bit of precision which is more than enough to get a reasonably accurate result.
Pick an element in the HTML panel of the developer tools and type this in the console:
angular.element($0).scope()
In WebKit and Firefox, $0
is a reference to the selected DOM node in the elements tab, so by doing this you get the selected DOM node scope printed out in the console.
You can also target the scope by element ID, like so:
angular.element(document.getElementById('yourElementId')).scope()
Addons/Extensions
There are some very useful Chrome extensions that you might want to check out:
Batarang. This has been around for a while.
ng-inspector. This is the newest one, and as the name suggests, it allows you to inspect your application's scopes.
Playing with jsFiddle
When working with jsfiddle you can open the fiddle in show mode by adding /show
at the end of the URL. When running like this you have access to the angular
global. You can try it here:
http://jsfiddle.net/jaimem/Yatbt/show
jQuery Lite
If you load jQuery before AngularJS, angular.element
can be passed a jQuery selector. So you could inspect the scope of a controller with
angular.element('[ng-controller=ctrl]').scope()
Of a button
angular.element('button:eq(1)').scope()
... and so on.
You might actually want to use a global function to make it easier:
window.SC = function(selector){
return angular.element(selector).scope();
};
Now you could do this
SC('button:eq(10)')
SC('button:eq(10)').row // -> value of scope.row
Check here: http://jsfiddle.net/jaimem/DvRaR/1/show/
Update 2018-10-16
Reportedly, as of VS 2013, this warning can be disabled. See the comment by @Mark Ransom.
Original Answer
You can't disable that specific warning.
According to Geoff Chappell the 4099 warning is treated as though it's too important to ignore, even by using in conjunction with /wx (which would treat warnings as errors and ignore the specified warning in other situations)
Here is the relevant text from the link:
Not Quite Unignorable Warnings
For some warning numbers, specification in a /ignore option is accepted but not necessarily acted upon. Should the warning occur while the /wx option is not active, then the warning message is still displayed, but if the /wx option is active, then the warning is ignored. It is as if the warning is thought important enough to override an attempt at ignoring it, but not if the user has put too high a price on unignored warnings.
The following warning numbers are affected:
4200, 4203, 4204, 4205, 4206, 4207, 4208, 4209, 4219, 4231 and 4237
You can create Custom date picker, that is work for all api levels.
public class CustomDatePickerDialog extends DatePickerDialog {
int maxYear;
int maxMonth;
int maxDay;
public CustomDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
super(context, callBack, year, monthOfYear, dayOfMonth);
}
public void setMaxDate(long maxDate) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getDatePicker().setMaxDate(System.currentTimeMillis());
} else {
final Calendar c = Calendar.getInstance();
c.setTimeInMillis(maxDate);
maxYear = c.get(Calendar.YEAR);
maxMonth = c.get(Calendar.MONTH);
maxDay = c.get(Calendar.DAY_OF_MONTH);
}
}
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
super.onDateChanged(view, year, monthOfYear, dayOfMonth);
} else {
if (year > maxYear)
view.updateDate(maxYear, maxMonth, maxDay);
if (monthOfYear > maxMonth && year == maxYear)
view.updateDate(maxYear, maxMonth, maxDay);
if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
view.updateDate(maxYear, maxMonth, maxDay);
}
}
set max date
final CustomDatePickerDialog pickerDialog = new CustomDatePickerDialog(getActivity(),
myDateListener, year, month, day);
pickerDialog.setMaxDate(System.currentTimeMillis());
pickerDialog.show();
Using Microsoft SQL Server Management Studio you can create Linked Server
. First make connection to current (local) server, then go to Server Objects
> Linked Servers
> context menu > New Linked Server
. In window New Linked Server
you have to specify desired server name for remote server, real server name or IP address (Data Source) and credentials (Security page).
And further you can select data from linked server:
select * from [linked_server_name].[database].[schema].[table]
It is not automatic. Your top function looks ok.
Use <br>
tags
<div class="container">
<div class="row" id="a">
<img src="http://placehold.it/300">
</div>
<br><br> <!--insert one, two, or more here-->
<div class="row" id="b">
<button>Hello</button>
</div>
</div>
Since I can't comment on the top comment, I'm forced to submit an "answer."
The problem with the selected answer is that setting the field to readonly takes the field out of the tab order on the iPhone. So if you like entering forms by hitting "next", you'll skip right over the field.
Collation defines how you sort and compare string values
For example, it defines how to deal with
äàa
etc)Aa
)cote < côte < coté < côté.
cote < coté < côte < côté
Does the user you're executing this script under even see that table??
select top 1 * from products
Do you get any output for this??
If yes: does this user have the permission to modify the table, i.e. execute DDL scripts like ALTER TABLE
etc.? Typically, regular users don't have this elevated permissions.
You can add the id="MyID123"
at the start of the cartHTML text appends.
The first line would therefore be:
var cartHTML = '<div id="MyID123" class="soft_add_wrapper" onmouseover="setTimer();">';
-OR-
If you want the ID to be in a variable, then something like this:
var MyIDvariable = "MyID123";
var cartHTML = '<div id="'+MyIDvariable+'" class="soft_add_wrapper" onmouseover="setTimer();">';
/* ... the rest of your code ... */
Most suggestions will fail if there so much as a single leading or trailing space, which would matter if the file is being edited by hand. This would make it less susceptible in that case:
grep '^[[:blank:]]*ABB\.log[[:blank:]]*$' a.tmp
A simple while-read loop in shell would do this implicitly:
while read file
do
case $file in
(ABB.log) printf "%s\n" "$file"
esac
done < a.tmp
It depends on what you are trying to do.
file, err := os.Open("file.txt")
fmt.print(file)
The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File
), not file-content. To obtain file-content, you may READ
from a file-descriptor.
To read all file content(in bytes) to memory, ioutil.ReadAll
package main
import (
"fmt"
"io/ioutil"
"os"
"log"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
b, err := ioutil.ReadAll(file)
fmt.Print(b)
}
But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read
from *os.File
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
buf := make([]byte, 32*1024) // define your buffer size here.
for {
n, err := file.Read(buf)
if n > 0 {
fmt.Print(buf[:n]) // your read buffer.
}
if err == io.EOF {
break
}
if err != nil {
log.Printf("read %d bytes: %v", n, err)
break
}
}
}
Otherwise, you could also use the standard util package: bufio
, try Scanner
. A Scanner
reads your file in tokens: separator.
By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).
package main
import (
"fmt"
"os"
"log"
"bufio"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() { // internally, it advances token based on sperator
fmt.Println(scanner.Text()) // token in unicode-char
fmt.Println(scanner.Bytes()) // token in bytes
}
}
Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.
mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given
This means that the first parameter you passed is a boolean (true or false).
The first parameter is $result
, and it is false
because there is a syntax error in the query.
" ... WHERE PartNumber = $partid';"
You should never directly include a request variable in a SQL query, else the users are able to inject SQL in your queries. (See SQL injection.)
You should escape the variable:
" ... WHERE PartNumber = '" . mysqli_escape_string($conn,$partid) . "';"
Or better, use Prepared Statements
.
You can use following Node.js module to do it with a breeze:
If possible, use NumberUtils in Apache Commons Lang - plenty of great utilities there.
NumberUtils.max(int[])
Actually you can fix it with following steps -
cls.__dict__
{'isFilled':True}
or {'isFilled':False}
depending upon what you have set.del cls.__dict__['isFilled']
In this case, we delete the entry which overrides the method as mentioned by BrenBarn.
import numpy as np
x=np.array([1,2,3])
y=np.multiply(np.ones((len(x),len(x))),x).T
print(y)
yields:
[[ 1. 1. 1.]
[ 2. 2. 2.]
[ 3. 3. 3.]]
First, one of Perlis's epigrams:
"If you have a procedure with 10 parameters, you probably missed some."
Some of the 10 arguments are presumably related. Group them into an object, and pass that instead.
Making an example up, because there's not enough information in the question to answer directly:
class PersonInfo(object):
def __init__(self, name, age, iq):
self.name = name
self.age = age
self.iq = iq
Then your 10 argument function:
def f(x1, x2, name, x3, iq, x4, age, x5, x6, x7):
...
becomes:
def f(personinfo, x1, x2, x3, x4, x5, x6, x7):
...
and the caller changes to:
personinfo = PersonInfo(name, age, iq)
result = f(personinfo, x1, x2, x3, x4, x5, x6, x7)
The most naive way would be to iterate over the String and make sure all the elements are valid digits for the given radix. This is about as efficient as it could possibly get, since you must look at each element at least once. I suppose we could micro-optimize it based on the radix, but for all intents and purposes this is as good as you can expect to get.
public static boolean isInteger(String s) {
return isInteger(s,10);
}
public static boolean isInteger(String s, int radix) {
if(s.isEmpty()) return false;
for(int i = 0; i < s.length(); i++) {
if(i == 0 && s.charAt(i) == '-') {
if(s.length() == 1) return false;
else continue;
}
if(Character.digit(s.charAt(i),radix) < 0) return false;
}
return true;
}
Alternatively, you can rely on the Java library to have this. It's not exception based, and will catch just about every error condition you can think of. It will be a little more expensive (you have to create a Scanner object, which in a critically-tight loop you don't want to do. But it generally shouldn't be too much more expensive, so for day-to-day operations it should be pretty reliable.
public static boolean isInteger(String s, int radix) {
Scanner sc = new Scanner(s.trim());
if(!sc.hasNextInt(radix)) return false;
// we know it starts with a valid int, now make sure
// there's nothing left!
sc.nextInt(radix);
return !sc.hasNext();
}
If best practices don't matter to you, or you want to troll the guy who does your code reviews, try this on for size:
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}
Dockerfile comments start with '#', just like Python. Here is a good example (kstaken/dockerfile-examples):
# Install a more-up-to date version of MongoDB than what is included in the default Ubuntu repositories.
FROM ubuntu
MAINTAINER Kimbro Staken
RUN apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10
RUN echo "deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen" | tee -a /etc/apt/sources.list.d/10gen.list
RUN apt-get update
RUN apt-get -y install apt-utils
RUN apt-get -y install mongodb-10gen
#RUN echo "" >> /etc/mongodb.conf
CMD ["/usr/bin/mongod", "--config", "/etc/mongodb.conf"]
Yes it is possible
public class User {
private String name = "";
private String surname = "";
private int age = 0;
public User(){
this("name is undefined","surname is undefined",0);
}
public User(String name,String surname){
this(name,surname,0);
}
public User(String name, String surname, int age) {
this.name = name;
this.surname = surname;
this.age = age;
}
}
You can use Chr(13). Then just wrap the whole thing in Chr(34). Chr(34) is double quotes.
Here is how you can fix it:
/var/lib/jenkins/config.xml
<useSecurity>true</useSecurity>
to false sudo service jenkins restart
allow anyone to do anything
, and allow user signup.www.yoursite.com/securityRealm/addUser
and create a userallow anyone to do anything
to whatever you actually want users to be able to do. In my case, it is allow logged in users to do anything
.You can make use of the first-child selector
<div class="sidebar">
<div class="box">
<p>
Text is here
</p>
</div>
<div class="box">
<p>
Text is here
</p>
</div>
</div>
and in CSS
.box {
padding: 10px;
text-align: justify;
margin-top: 20px;
}
.box:first-child {
margin-top: none;
}
You could use a named function expression (in this case the function is named abc
), like so:
let click = 0;
canvas.addEventListener('click', function abc(event) {
click++;
if (click >= 50) {
// remove event listener function `abc`
canvas.removeEventListener('click', abc);
}
// More code here ...
}
Quick and dirty working example: http://jsfiddle.net/8qvdmLz5/2/.
More information about named function expressions: http://kangax.github.io/nfe/.
That code looks like the route you want to take with a few changes.
You'll want to change the append method to look like this. I've changed it to accept the number 0, and to make it return this
so you can chain your appends.
StringBuilder.prototype.append = function (value) {
if (value || value === 0) {
this.strings.push(value);
}
return this;
}
There is a new extension for Visual Studio 2017 called SelectNextOccurrence which is free and open-source.
This extension makes it possible to select next occurrences of a selected text for editing.
Aims to replicate the Ctrl+D command of Sublime Text for faster coding.
Features:
Visual Studio commands:
SelectNextOccurrence.SelectNextOccurrence
is bound to Ctrl+D by default.SelectNextOccurrence.SkipOccurrence
is not bound by default. (Recommended Ctrl+K, Ctrl+D)SelectNextOccurrence.UndoOccurrence
is not bound by default. (Recommended Ctrl+U)SelectNextOccurrence.AddCaretAbove
is not bound by default. (Recommended Ctrl+Alt+Up)SelectNextOccurrence.AddCaretBelow
is not bound by default. (Recommended Ctrl+Alt+Down)https://marketplace.visualstudio.com/items?itemName=thomaswelen.SelectNextOccurrence
You can now use CSS Grid to fix this.
<div class="outer">
<div class="top"> </div>
<div class="below"> </div>
</div>
And the css for this:
.outer {
display: grid;
grid-template: 1fr / 1fr;
place-items: center;
}
.outer > * {
grid-column: 1 / 1;
grid-row: 1 / 1;
}
.outer .below {
z-index: 2;
}
.outer .top {
z-index: 1;
}
I don't think one needs it any more. The latest versions of Eclipse have Maven plugin enabled. So you will just need to import a Maven project into Eclipse and no more as an existing project. Eclipse will create the needed .project, .settings, .classpath files based on your pom.xml and environment settings (installed Java version, etc.) . The earlier versions of Eclipse needed to have run the command mvn eclipse:eclipse
which produced the same result.
You have to check on this.
HTML
<button id="saveActionId"> Save </button>
manifest.json
"permissions": [
"activeTab",
"tabs"
]
JavaScript
The below code will save all the urls of active window into JSON object as part of button click.
var saveActionButton = document.getElementById('saveActionId');
saveActionButton.addEventListener('click', function() {
myArray = [];
chrome.tabs.query({"currentWindow": true}, //{"windowId": targetWindow.id, "index": tabPosition});
function (array_of_Tabs) { //Tab tab
arrayLength = array_of_Tabs.length;
//alert(arrayLength);
for (var i = 0; i < arrayLength; i++) {
myArray.push(array_of_Tabs[i].url);
}
obj = JSON.parse(JSON.stringify(myArray));
});
}, false);
mycollection.find_one_and_update({"_id": mongo_id},
{"$set": {"newfield": "abc"}})
should work splendidly for you. If there is no document of id mongo_id
, it will fail, unless you also use upsert=True
. This returns the old document by default. To get the new one, pass return_document=ReturnDocument.AFTER
. All parameters are described in the API.
The method was introduced for MongoDB 3.0. It was extended for 3.2, 3.4, and 3.6.
Actually, casting doesn't always work. If the object is not an instanceof
the class you're casting it to you will get a ClassCastException
at runtime.
Lets say that "==" operator returns true if both both operands belong to same object but when it will return true as we can't assign a single object multiple values
public static void main(String [] args){
String s1 = "Hello";
String s1 = "Hello"; // This is not possible to assign multiple values to single object
if(s1 == s1){
// Now this retruns true
}
}
Now when this happens practically speaking, If its not happen then why this is == compares functionality....
You must place the label after a caption in order to for label
to store the table's number, not the chapter's number.
\begin{table} \begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |} -- cut -- \end{tabular} \caption{My table} \label{table:kysymys} \end{table} Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...
Using &
operator, don't forget to wrap the sub-statements with ()
:
males = df[(df[Gender]=='Male') & (df[Year]==2014)]
To store your dataframes in a dict
using a for loop:
from collections import defaultdict
dic={}
for g in ['male', 'female']:
dic[g]=defaultdict(dict)
for y in [2013, 2014]:
dic[g][y]=df[(df[Gender]==g) & (df[Year]==y)] #store the DataFrames to a dict of dict
A demo for your getDF
:
def getDF(dic, gender, year):
return dic[gender][year]
print genDF(dic, 'male', 2014)
The issue is that the URL is being blocked from being created by Windows.
Steps to fix: Run command prompt as an administrator. Add the URL to the ACL
netsh http add urlacl url=http://+:8000/ServiceModelSamples/Service user=mylocaluser
USE this i hope help you
var interval;
function updateDiv(){
$.ajax({
url: 'getContent.php',
success: function(data){
$('.square').html(data);
},
error: function(){
/* clearInterval(interval); */
stopinterval(); // stop the interval
$.playSound('oneday.wav');
$('.square').html('<span style="color:red">Connection problems</span>');
}
});
}
function playinterval(){
updateDiv();
interval = setInterval(function(){updateDiv();},3000);
return false;
}
function stopinterval(){
clearInterval(interval);
return false;
}
$(document)
.on('ready',playinterval)
.on({click:playinterval},"#playinterval")
.on({click:stopinterval},"#stopinterval");
In 3 words: inline-block
is better.
Inline Block
The only drawback to the display: inline-block
approach is that in IE7 and below an element can only be displayed inline-block
if it was already inline
by default. What this means is that instead of using a <div>
element you have to use a <span>
element. It's not really a huge drawback at all because semantically a <div>
is for dividing the page while a <span>
is just for covering a span of a page, so there's not a huge semantic difference. A huge benefit of display:inline-block
is that when other developers are maintaining your code at a later point, it is much more obvious what display:inline-block
and text-align:right
is trying to accomplish than a float:left
or float:right
statement. My favorite benefit of the inline-block
approach is that it's easy to use vertical-align: middle
, line-height
and text-align: center
to perfectly center the elements, in a way that is intuitive. I found a great blog post on how to implement cross-browser inline-block, on the Mozilla blog. Here is the browser compatibility.
Float
The reason that using the float
method is not suited for layout of your page is because the float
CSS property was originally intended only to have text wrap around an image (magazine style) and is, by design, not best suited for general page layout purposes. When changing floated elements later, sometimes you will have positioning issues because they are not in the page flow. Another disadvantage is that it generally requires a clearfix otherwise it may break aspects of the page. The clearfix requires adding an element after the floated elements to stop their parent from collapsing around them which crosses the semantic line between separating style from content and is thus an anti-pattern in web development.
Any white space problems mentioned in the link above could easily be fixed with the white-space
CSS property.
SitePoint is a very credible source for web design advice and they seem to have the same opinion that I do:
If you’re new to CSS layouts, you’d be forgiven for thinking that using CSS floats in imaginative ways is the height of skill. If you have consumed as many CSS layout tutorials as you can find, you might suppose that mastering floats is a rite of passage. You’ll be dazzled by the ingenuity, astounded by the complexity, and you’ll gain a sense of achievement when you finally understand how floats work.
Don’t be fooled. You’re being brainwashed.
http://www.sitepoint.com/give-floats-the-flick-in-css-layouts/
2015 Update - Flexbox is a good alternative for modern browsers:
.container {
display: flex; /* or inline-flex */
}
.item {
flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ]
}
Dec 21, 2016 Update
Bootstrap 4 is removing support for IE9, and thus is getting rid of floats from rows and going full Flexbox.
Also, you may update the project by clicking,
Right Click on project name -> Select Maven -> Right click -> Update Project.
This helped out for me.
Thanks.
On Windows, I followed the same path as the previous answers. The difference is that the path to php.ini is usually different from the traditional ones, usually in Apache.
To find php.ini, I used the following path: C:\tools\php80\php.ini
After that, I uncommented the pdo extension files
and the migration worked.
If using Perl is an option and you're content with basing expansions on environment variables only (as opposed to all shell variables), consider Stuart P. Bentley's robust answer.
This answer aims to provide a bash-only solution that - despite use of eval
- should be safe to use.
The goals are:
${name}
and $name
variable references.$(...)
and legacy syntax `...`
) $((...))
and legacy syntax $[...]
).\
(\${name}
)."
and \
instances.Function expandVars()
:
expandVars() {
local txtToEval=$* txtToEvalEscaped
# If no arguments were passed, process stdin input.
(( $# == 0 )) && IFS= read -r -d '' txtToEval
# Disable command substitutions and arithmetic expansions to prevent execution
# of arbitrary commands.
# Note that selectively allowing $((...)) or $[...] to enable arithmetic
# expressions is NOT safe, because command substitutions could be embedded in them.
# If you fully trust or control the input, you can remove the `tr` calls below
IFS= read -r -d '' txtToEvalEscaped < <(printf %s "$txtToEval" | tr '`([' '\1\2\3')
# Pass the string to `eval`, escaping embedded double quotes first.
# `printf %s` ensures that the string is printed without interpretation
# (after processing by by bash).
# The `tr` command reconverts the previously escaped chars. back to their
# literal original.
eval printf %s "\"${txtToEvalEscaped//\"/\\\"}\"" | tr '\1\2\3' '`(['
}
Examples:
$ expandVars '\$HOME="$HOME"; `date` and $(ls)'
$HOME="/home/jdoe"; `date` and $(ls) # only $HOME was expanded
$ printf '\$SHELL=${SHELL}, but "$(( 1 \ 2 ))" will not expand' | expandVars
$SHELL=/bin/bash, but "$(( 1 \ 2 ))" will not expand # only ${SHELL} was expanded
${HOME:0:10}
, as long as they contain no embedded command or arithmetic substitutions, such as ${HOME:0:$(echo 10)}
$(
and `
instances are blindly escaped).${HOME
(missing closing }
) BREAK the function.\$name
prevents expansion.\
not followed by $
is preserved as is.\
instances, you must double them; e.g.:
\\
-> \
- the same as just \
\\\\
-> \\
0x1
, 0x2
, 0x3
.eval
.If you're looking for a more restrictive solution that only supports ${name}
expansions - i.e., with mandatory curly braces, ignoring $name
references - see this answer of mine.
Here is an improved version of the bash-only, eval
-free solution from the accepted answer:
The improvements are:
${name}
and $name
variable references.\
-escaping variable references that shouldn't be expanded.eval
-based solution above,
IFS= read -d '' -r lines # read all input from stdin at once
end_offset=${#lines}
while [[ "${lines:0:end_offset}" =~ (.*)\$(\{([a-zA-Z_][a-zA-Z_0-9]*)\}|([a-zA-Z_][a-zA-Z_0-9]*))(.*) ]] ; do
pre=${BASH_REMATCH[1]} # everything before the var. reference
post=${BASH_REMATCH[5]}${lines:end_offset} # everything after
# extract the var. name; it's in the 3rd capture group, if the name is enclosed in {...}, and the 4th otherwise
[[ -n ${BASH_REMATCH[3]} ]] && varName=${BASH_REMATCH[3]} || varName=${BASH_REMATCH[4]}
# Is the var ref. escaped, i.e., prefixed with an odd number of backslashes?
if [[ $pre =~ \\+$ ]] && (( ${#BASH_REMATCH} % 2 )); then
: # no change to $lines, leave escaped var. ref. untouched
else # replace the variable reference with the variable's value using indirect expansion
lines=${pre}${!varName}${post}
fi
end_offset=${#pre}
done
printf %s "$lines"
Just add vertical-align:top for first td alone needed not for all td.
tr>td:first-child {_x000D_
vertical-align: top;_x000D_
}
_x000D_
<tr>_x000D_
<td>Description</td>_x000D_
<td>more text</td>_x000D_
</tr>
_x000D_
Update
Dav Glass from Yahoo has given a talk at YuiConf2010 in November which is now available in Video from.
He shows to great extend how one can use YUI3 to render out widgets on the server side an make them work with GET requests when JS is disabled, or just make them work normally when it's active.
He also shows examples of how to use server side DOM to apply style sheets before rendering and other cool stuff.
The demos can be found on his GitHub Account.
The part that's missing IMO to make this really awesome, is some kind of underlying storage of the widget state. So that one can visit the page without JavaScript and everything works as expected, then they turn JS on and now the widget have the same state as before but work without page reloading, then throw in some saving to the server + WebSockets to sync between multiple open browser.... and the next generation of unobtrusive and gracefully degrading ARIA's is born.
Original Answer
Well go ahead and built it yourself then.
Seriously, 90% of all WebApps out there work fine with a REST approach, of course you could do magical things like superior user tracking, tracking of downloads in real time, checking which parts of videos are being watched etc.
One problem is scalability, as soon as you have more then 1 Node process, many (but not all) of the benefits of having the data stored between requests go away, so you have to make sure that clients always hit the same process. And even then, bigger things will yet again need a database layer.
Node.js isn't the solution to everything, I'm sure people will build really great stuff in the future, but that needs some time, right now many are just porting stuff over to Node to get things going.
What (IMHO) makes Node.js so great, is the fact that it streamlines the Development process, you have to write less code, it works perfectly with JSON, you loose all that context switching.
I mainly did gaming experiments so far, but I can for sure say that there will be many cool multi player (or even MMO) things in the future, that use both HTML5 and Node.js.
Node.js is still gaining traction, it's not even near to the RoR Hype some years ago (just take a look at the Node.js tag here on SO, hardly 4-5 questions a day).
Rome (or RoR) wasn't built over night, and neither will Node.js be.
Node.js has all the potential it needs, but people are still trying things out, so I'd suggest you to join them :)
Add in activity
requestWindowFeature(Window.FEATURE_NO_TITLE);
and add your style.xml
file with the following two lines:
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
This occurs when you specify the different name for repository table name and database table name. Please check your table name with database and repository.
Go to Start and search for "Anaconda Prompt" - right click this and choose "Open File Location", which will open a folder of shortcuts. Right click the "Anaconda Prompt" shortcut, choose "Properties" and you can adjust the starting dir in the "Start in" box.
The attribute align=middle
sets vertical alignment. To set horizontal alignment using HTML, you can wrap the element inside a center
element and remove all the CSS you have now.
<center><img src=_x000D_
"http://icons.iconarchive.com/icons/rokey/popo-emotions/128/big-smile-icon.png"_x000D_
width="42" height="42"></center>
_x000D_
If you would rather do it in CSS, there are several ways. A simple one is to set text-align
on a container:
<div style="text-align: center"><img src=_x000D_
"http://icons.iconarchive.com/icons/rokey/popo-emotions/128/big-smile-icon.png"_x000D_
width="42" height="42"></div>
_x000D_
It depends at least on the version of PHP that is used. wp-includes/class-phpass.php
contains all the answers.
Use CRTL+BREAK to suspend execution at any point. You will be put into break mode and can press F5 to continue the execution or F8 to execute the code step-by-step in the visual debugger.
Of course this only works when there is no message box open, so if your VBA code constantly opens message boxes for some reason it will become a little tricky to press the keys at the right moment.
You can even edit most of the code while it is running.
Use Debug.Print
to print out messages to the Immediate Window in the VBA editor, that's way more convenient than MsgBox
.
Use breakpoints or the Stop
keyword to automatically halt execution in interesting areas.
You can use Debug.Assert
to halt execution conditionally.
with open('target.txt','w') as out:
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print("I'm going to write these to the file.")
out.write('{}\n{}\n{}\n'.format(line1,line2,line3))
Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements.
// Outputs F because A is replaced with B, then B is replaced with C, and so on... // Finally E is replaced with F, because of left to right replacements. $search = array('A', 'B', 'C', 'D', 'E'); $replace = array('B', 'C', 'D', 'E', 'F'); $subject = 'A'; echo str_replace($search, $replace, $subject);
I have try the code from first answer, it not working but I have play around and this work for me
$('#vip').change(function(){
if ($(this).is(':checked')) {
alert('checked');
} else {
alert('uncheck');
}
});
This works for MVC 5:
<a href="@Url.Action("ActionName", "ControllerName", new { paramName1 = item.paramValue1, paramName2 = item.paramValue2 })" >
Link text
</a>
You can put two figures inside one figure environment. For example:
\begin{figure}[p]
\centering
\includegraphics{fig1}
\caption{Caption 1}
\includegraphics{fig2}
\caption{Caption 2}
\end{figure}
Each caption will generate a separate figure number.
You can try this ! This should work on windows machines.
for /F "usebackq tokens=1,2,3 delims=-" %%I IN (`echo %date%`) do echo "%%I" "%%J" "%%K"
Very easy:
handleSubmit(e){_x000D_
e.preventDefault();_x000D_
e.target.reset();_x000D_
}
_x000D_
<form onSubmit={this.handleSubmit.bind(this)}>_x000D_
..._x000D_
</form>
_x000D_
Good luck :)
You can make both arguments lower case, and that way you will always end up with a case insensitive search.
var string1 = "aBc";
var string2 = "AbC";
if (string1.toLowerCase() === string2.toLowerCase())
{
#stuff
}
The functionality is indeed similar (apart from the calling semantics, where call-template
requires a name
attribute and a corresponding names template).
However, the parser will not execute the same way.
From MSDN:
Unlike
<xsl:apply-templates>
,<xsl:call-template>
does not change the current node or the current node-list.
Step-by-step:
[newline]ab
ab
[backspace]si
asi
[carriage-return]ha
hai
Carriage return, does not cause a newline. Under some circumstances a single CR or LF may be translated to a CR-LF pair. This is console and/or stream dependent.
You can solve the negative bearing problem by adding 360°. Unfortunately, this might result in bearings larger than 360° for positive bearings. This is a good candidate for the modulo operator, so all in all you should add the line
Bearing = (Bearing + 360) % 360
at the end of your method.
For me - here is a less confusing way of doing the socket.setTimeout
var request=require('https').get(
url
,function(response){
var r='';
response.on('data',function(chunk){
r+=chunk;
});
response.on('end',function(){
console.dir(r); //end up here if everything is good!
});
}).on('error',function(e){
console.dir(e.message); //end up here if the result returns an error
});
request.on('error',function(e){
console.dir(e); //end up here if a timeout
});
request.on('socket',function(socket){
socket.setTimeout(1000,function(){
request.abort(); //causes error event ?
});
});
for total compatibility with twitter bootstrap 3, I need to override some plugins methods:
// override jquery validate plugin defaults
$.validator.setDefaults({
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
See Example: http://jsfiddle.net/mapb_1990/hTPY7/7/
Below works on sql server 2008
select *, ROW_NUMBER() OVER(order by items) as row#
from
( select 134 myColumn1, 34 myColumn2, 'd,c,k,e,f,g,h,a' comaSeperatedColumn) myTable
cross apply
SPLIT (rtrim(comaSeperatedColumn), ',') splitedTable -- gives 'items' column
Will get all Cartesian product with the origin table columns plus "items" of split table.
BABEL TEAM UPDATE:
We're super excited that you're trying to use ES2015 syntax, but instead of continuing yearly presets, the team recommends using babel-preset-env. By default, it has the same behavior as previous presets to compile ES2015+ to ES5
If you are using Babel version 7 you will need to run npm install @babel/preset-env and have "presets": ["@babel/preset-env"] in your .babelrc
configuration.
This will compile all latest features to es5 transpiled code:
Prerequisites:
Step-1:: npm install --save-dev @babel/preset-env
Step-2: In order to compile JSX
code to es5 babel provides @babel/preset-react
package to convert reactjsx
extension file to native browser understandable code.
Step-3: npm install --save-dev @babel/preset-react
Step-4: create .babelrc
file inside root path path of your project where webpack.config.js
exists.
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
Step-5: webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: path.resolve(__dirname, 'src/index.js'),
output: {
path: path.resolve(__dirname, 'output'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./public/index.html",
filename: "./index.html"
})
]
}
Check below method is working awesome also Oreo 8.1 ..
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO ManualMT-generated method stub
switch (requestCode) {
case PICKFILE_RESULT_CODE:
if (resultCode == RESULT_OK) {
try {
FilePath = data.getData().getPath();
Uri selectedImageUri = data.getData();
if (selectedImageUri.toString().contains("storage/emulated")){
String[] split = selectedImageUri.toString().split("storage/");
FilePath = "storage/"+split[1];
} else {
FilePath = ImageFilePath.getPath(getApplicationContext(), selectedImageUri);
}
recyclerview.setVisibility(View.VISIBLE);
if (FilePath == null) {
FilePath = "";
}
File file = new File(FilePath);
reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
image_list.add(FilePath);
composeImageAdapter.notifyDataSetChanged();
} catch (Exception e){
Toast.makeText(ClusterCreateNote.this , e.toString(),Toast.LENGTH_SHORT).show();
}
}
break;
}
}
URI path Class:
public static class ImageFilePath {
/**
* Method for return file path of Gallery image
*
* @param context
* @param uri
* @return path of the selected image file from gallery
*/
public static String getPath(final Context context, final Uri uri) {
String selection = null;
String[] selectionArgs = null;
// DocumentProvider
if (DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.wifAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Log.e("typetype",type);
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
selection = "_id=?";
selectionArgs = new String[]{
split[1]
};
Log.e("gddhjf",getDataColumn(context, contentUri, selection, selectionArgs));
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
if ("content".equalsIgnoreCase(uri.getScheme())) {
if (isGooglePhotosUri(uri)) {
return uri.getLastPathSegment();
}
String[] projection = {
MediaStore.Images.Media.DATA
};
Cursor cursor = null;
try {
cursor = context.getContentResolver()
.query(uri, projection, selection, selectionArgs, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return
"com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static boolean isGooglePhotosUri(Uri uri) {
return
"com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}
Another thing that people may find useful...make sure to leave off ".py" from your module name. For example, if you are trying to generate documentation for 'original' in 'original.py':
yourcode_dir$ pydoc -w original.py no Python documentation found for 'original.py' yourcode_dir$ pydoc -w original wrote original.html
You have to instantiate the object first. The simplest way is:
var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++) {
data.push({label: lab[i], value: val[i]});
}
Or an other, less concise way, but closer to your original code:
for(var i=0; i<4; i++) {
data[i] = {}; // creates a new object
data[i].label = lab[i];
data[i].value = val[i];
}
array()
will not create a new array (unless you defined that function). Either Array()
or new Array()
or just []
.
I recommend to read the MDN JavaScript Guide.
Try either multi-table update syntax
UPDATE config t1 JOIN config t2
ON t1.config_name = 'name1' AND t2.config_name = 'name2'
SET t1.config_value = 'value',
t2.config_value = 'value2';
Here is SQLFiddle demo
or conditional update
UPDATE config
SET config_value = CASE config_name
WHEN 'name1' THEN 'value'
WHEN 'name2' THEN 'value2'
ELSE config_value
END
WHERE config_name IN('name1', 'name2');
Here is SQLFiddle demo
Other approach for Vanilla JavaScript:
for(var o of document.querySelectorAll('#models > option')) {
o.remove()
}
For arbitrary, potentially large number of optional parameters, a nice idiom is to use Functional options.
For your type Foobar
, first write only one constructor:
func NewFoobar(options ...func(*Foobar) error) (*Foobar, error){
fb := &Foobar{}
// ... (write initializations with default values)...
for _, op := range options{
err := op(fb)
if err != nil {
return nil, err
}
}
return fb, nil
}
where each option is a function which mutates the Foobar. Then provide convenient ways for your user to use or create standard options, for example :
func OptionReadonlyFlag(fb *Foobar) error {
fb.mutable = false
return nil
}
func OptionTemperature(t Celsius) func(*Foobar) error {
return func(fb *Foobar) error {
fb.temperature = t
return nil
}
}
For conciseness, you may give a name to the type of the options (Playground) :
type OptionFoobar func(*Foobar) error
If you need mandatory parameters, add them as first arguments of the constructor before the variadic options
.
The main benefits of the Functional options idiom are :
This technique was coined by Rob Pike and also demonstrated by Dave Cheney.
Wait -- did you actually mean that "the same number of rows ... are being processed" or that "the same number of rows are being returned"? In general, the outer join would process many more rows, including those for which there is no match, even if it returns the same number of records.
In this particular case, a viewModel is required to launch the task and notify the view upon its completion. An "async property", not an "async constructor", is in order.
I just released AsyncMVVM, which solves exactly this problem (among others). Should you use it, your ViewModel would become:
public class ViewModel : AsyncBindableBase
{
public ObservableCollection<TData> Data
{
get { return Property.Get(GetDataAsync); }
}
private Task<ObservableCollection<TData>> GetDataAsync()
{
//Get the data asynchronously
}
}
Strangely enough, Silverlight is supported. :)
Use IEquatable<T>
Interface which has a method Equals
.
VLookup
You can do it with a simple VLOOKUP formula. I've put the data in the same sheet, but you can also reference a different worksheet. For the price column just change the last value from 2 to 3, as you are referencing the third column of the matrix "A2:C4".
External Reference
To reference a cell of the same Workbook use the following pattern:
<Sheetname>!<Cell>
Example:
Table1!A1
To reference a cell of a different Workbook use this pattern:
[<Workbook_name>]<Sheetname>!<Cell>
Example:
[MyWorkbook]Table1!A1
<a href=".">refresh current page</a>
or if you want to pass parameters:
<a href=".?curreny='usd'">refresh current page</a>
It depends on your OS, but 2147483647 is the usual value, according to the manual.
Setting:
request.Referer = @"http://www.somesite.com/";
and adding cookies
than worked for me
I had the same problem as the current .NET SDK does not support targeting .NET Core 3.1. Either target .NET Core 1.1 or lower, or use a version of the .NET SDK that supports .NET Core 3.1
1) Make sure .Net core SDK installed on your machine. Download .NET!
2) set PATH environment variables as below Path
I have two button for form submission, button named save and exit bypasses the validation :
$('.save_exist').on('click', function (event) {
$('#MyformID').removeData('validator');
$('.form-control').removeClass('error');
$('.form-control').removeClass('required');
$("#loanApplication").validate().cancelSubmit = true;
$('#loanApplication').submit();
event.preventDefault();
});
Sure you can.
You can use case x ... y for the range
Example:
#include <iostream.h>
#include <stdio.h>
int main()
{
int Answer;
cout << "How many cars do you have?";
cin >> Answer;
switch (Answer)
{
case 1 ... 4:
cout << "You need more cars. ";
break;
case 5 ... 8:
cout << "Now you need a house. ";
break;
default:
cout << "What are you? A peace-loving hippie freak? ";
}
cout << "\nPress ENTER to continue... " << endl;
getchar();
return 0;
}
Make sure you have "-std=c++0x" flag enabled within your compiler
If you want to transform a variable containing a relative path into an absolute one, this works :
dir=`cd "$dir"`
"cd" echoes without changing the working directory, because executed here in a sub-shell.
A simple way to do this is using ifelse
, which is vectorized. If the condition is satisfied, we use a replacement value, otherwise we use the original value.
v <- c(3, 2, 1, 0, 4, 0)
ifelse(v == 0, 1, v)
We can avoid a named variable by using a pipe.
c(3, 2, 1, 0, 4, 0) %>% ifelse(. == 0, 1, .)
A common task is to do multiple replacements. Instead of nested ifelse
statements, we can use case_when
from dplyr:
case_when(v == 0 ~ 1,
v == 1 ~ 2,
TRUE ~ v)
Old answer:
For factor or character vectors, we can use revalue
from plyr
:
> revalue(c("a", "b", "c"), c("b" = "B"))
[1] "a" "B" "c"
This has the advantage of only specifying the input vector once, so we can use a pipe like
x %>% revalue(c("b" = "B"))
In your scenario, you can have a look at asp.net membership, it is good practice to store user's password as hashed string in the database. you can authenticate the user by comparing the hashed incoming password with the one stored in the database.
Everything has been built for this purposes, check out asp.net membership
mercurial_keyring installation on Mac OSX using MacPorts:
sudo port install py-keyring
sudo port install py-mercurial_keyring
Add the following to ~/.hgrc:
# Add your username if you haven't already done so.
[ui]
username = [email protected]
[extensions]
mercurial_keyring =
As I notice The application could not be verified. raise up because in your device there is already an app installed with the same bundle identifier.
I got this issue because in my device there is my app that download from App store. and i test its update Version from Xcode. And i used same identifier that is live app and my development testing app. So i just remove app-store Live app from my device and this error going to be fix.
To attach the Java source code with Eclipse,
When you install the JDK, you must have selected the option to install the Java source files too. This will copy the src.zip file in the installation directory. In Eclipse, go to Window -> Preferences -> Java -> Installed JREs -> Add and choose the JDK you have in your system. Eclipse will now list the JARs found in the dialog box. There, select the rt.jar and choose Source Attachment. By default, this will be pointing to the correct src.zip. If not, choose the src.zip file which you have in your java installation directory. java source attach in eclipse Similarly, if you have the javadoc downloaded in your machine, you can configure that too in this dialog box.
You can return json in PHP this way:
header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;
Try this out:
INSERT INTO table (id, name, age) VALUES (1, 'A', 19) ON DUPLICATE KEY UPDATE id = id + 1;
Hope this helps.
Firstly, if you're doing MVVM you would typically have this information available to your VM via separate properties bound from the view. That saves you having to pass any parameters at all to your commands.
However, you could also multi-bind and use a converter to create the parameters:
<Button Content="Zoom" Command="{Binding MyViewModel.ZoomCommand">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource YourConverter}">
<Binding Path="Width" ElementName="MyCanvas"/>
<Binding Path="Height" ElementName="MyCanvas"/>
</MultiBinding>
</Button.CommandParameter>
</Button>
In your converter:
public class YourConverter : IMultiValueConverter
{
public object Convert(object[] values, ...)
{
return values.Clone();
}
...
}
Then, in your command execution logic:
public void OnExecute(object parameter)
{
var values = (object[])parameter;
var width = (double)values[0];
var height = (double)values[1];
}
It depends on the concrete situation.. but in general:
PUT = update or change a concrete resource with a concrete URI of the resource.
POST = create a new resource under the source of the given URI.
I.e.
Edit a blog post:
PUT: /blog/entry/1
Create a new one:
POST: /blog/entry
PUT may create a new resource in some circumstances where the URI of the new ressource is clear before the request. POST can be used to implement several other use cases, too, which are not covered by the others (GET, PUT, DELETE, HEAD, OPTIONS)
The general understanding for CRUD systems is GET = request, POST = create, Put = update, DELETE = delete
Martin's solution is very similar to mine, however how would you handle a default descriptions when the desired translation isn't found ?
Would that require an IFNULL() and another SELECT statement for each field ?
The default translation would be stored in the same table, where a flag like "isDefault" indicates wether that description is the default description in case none has been found for the current language.
As Rasmus states in his article "The difference between UTF-8 and Unicode?":
If asked the question, "What is the difference between UTF-8 and Unicode?", would you confidently reply with a short and precise answer? In these days of internationalization all developers should be able to do that. I suspect many of us do not understand these concepts as well as we should. If you feel you belong to this group, you should read this ultra short introduction to character sets and encodings.
Actually, comparing UTF-8 and Unicode is like comparing apples and oranges:
UTF-8 is an encoding - Unicode is a character set
A character set is a list of characters with unique numbers (these numbers are sometimes referred to as "code points"). For example, in the Unicode character set, the number for A is 41.
An encoding on the other hand, is an algorithm that translates a list of numbers to binary so it can be stored on disk. For example UTF-8 would translate the number sequence 1, 2, 3, 4 like this:
00000001 00000010 00000011 00000100
Our data is now translated into binary and can now be saved to disk.
All together now
Say an application reads the following from the disk:
1101000 1100101 1101100 1101100 1101111
The app knows this data represent a Unicode string encoded with UTF-8 and must show this as text to the user. First step, is to convert the binary data to numbers. The app uses the UTF-8 algorithm to decode the data. In this case, the decoder returns this:
104 101 108 108 111
Since the app knows this is a Unicode string, it can assume each number represents a character. We use the Unicode character set to translate each number to a corresponding character. The resulting string is "hello".
Conclusion
So when somebody asks you "What is the difference between UTF-8 and Unicode?", you can now confidently answer short and precise:
UTF-8 (Unicode Transformation Format) and Unicode cannot be compared. UTF-8 is an encoding used to translate numbers into binary data. Unicode is a character set used to translate characters into numbers.
try this:
powershell "C:\Dummy Directory 1\Foo.ps1 'C:\Dummy Directory 2\File.txt'"
I prefer this method as it doesn't require manually emitting markup. I use this because I'm rendering Razor Pages to strings and sending them out via email, which is an environment where the white-space styling won't always work.
public static IHtmlContent RenderNewlines<TModel>(this IHtmlHelper<TModel> html, string content)
{
if (string.IsNullOrEmpty(content) || html is null)
{
return null;
}
TagBuilder brTag = new TagBuilder("br");
IHtmlContent br = brTag.RenderSelfClosingTag();
HtmlContentBuilder htmlContent = new HtmlContentBuilder();
// JAS: On the off chance a browser is using LF instead of CRLF we strip out CR before splitting on LF.
string lfContent = content.Replace("\r", string.Empty, StringComparison.InvariantCulture);
string[] lines = lfContent.Split('\n', StringSplitOptions.None);
foreach(string line in lines)
{
_ = htmlContent.Append(line);
_ = htmlContent.AppendHtml(br);
}
return htmlContent;
}
There is a lot of thing that have been said about both editors, but I just have my 5 pence to add. Both editors are wonderful and you cannot go wrong with either of them.
I am a vi/vim user for about 15 years now. I've tried converting to emacs several times but every time was rather discovering that vim actually can do the missing thing out of the box without the need to write a lisp extension or install something.
For me the main difference in the editors that vim makes you use the environment/OS, while emacs tries to encapsulate it or replace it. For instance you can add a date in you text by :r!date in vim, or calendar with :r!cal 1 2014, or even replace the contents of you buffer with the hex version of the contents. Eg. :%!xxd, edit hex and then get back with :%!xxd -r, and many more other uses, like builtin grep, sed, etc.
Another example is use with jq
and gron
. Eg. paste json blob to the editor and then run for tranformation:
:r!curl -s http://interesting/api/v1/get/stuff
:%!gron | grep 'interesting' | gron -u
OR
:%!jq .path.to.stuff
Each of the piped commands above can be run separately via :%!<command>
, where %
means all document, but can also be run on selection, selected lines, etc. Here gron output
can be used as jq
path.
You also get the EX batch editing functionality, eg. Replacing certain words, reformatting the code, converting dos->unix newline characters, run a macro on say 100 files at a time. It is easily done with ex. I am not sure if emacs has something similar.
In other words IMHO vim goes closer to the unix philosophy. It generally simpler and smaller, but if you know your OS and your tools, you wont likely need more than it(VIM) has to offer. I never do.
Besides vi is defacto standard on any unix/linux system, why learn to use 2 tools that do the same thing. Of course some systems offer mg or something similar, but definitely not all of them. Unix + Vi < 3.
Well, just my 5 pence.
This answer assumes that you have python3.6
installed. For python3.7
, replace 3.6
with 3.7
. For python3.8
, replace 3.6
with 3.8
, but it may also first require the python3.8-distutils
package.
With regard to installing pip
, using curl
(instead of wget
) avoids writing the file to disk.
curl https://bootstrap.pypa.io/get-pip.py | sudo -H python3.6
The -H
flag is evidently necessary with sudo
in order to prevent errors such as the following when installing pip for an updated python interpreter:
The directory '/home/someuser/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/someuser/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
curl https://bootstrap.pypa.io/get-pip.py | python3.6 - --user
This may sometimes give a warning such as:
WARNING: The script wheel is installed in '/home/ubuntu/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
After this, pip
, pip3
, and pip3.6
can all be expected to point to the same target:
$ (pip -V && pip3 -V && pip3.6 -V) | uniq
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)
Of course you can alternatively use python3.6 -m pip
as well.
$ python3.6 -m pip -V
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)
Check you PATH environment variable once. Make sure the correct location of your JDK is specified there.
SELECT name
FROM gallery
WHERE CONVERT(name USING utf8) LIKE _utf8 '%$q%'
GROUP BY name COLLATE utf8_general_ci LIMIT 5
Easy, short and no need window focus:
Also here a usefull list of Virtual Key Codes
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);
private void button1_Click(object sender, EventArgs e)
{
const int WM_SYSKEYDOWN = 0x0104;
const int VK_F5 = 0x74;
IntPtr WindowToFind = FindWindow(null, "Google - Mozilla Firefox");
PostMessage(WindowToFind, WM_SYSKEYDOWN, VK_F5, 0);
}
To open docs automatically in Chrome without them being saved;
Go to the the three vertical dots on your top far right corner in Chrome.
Scroll down to Settings and click.
Scroll down to Show advance settings...
Scroll down to Downloads under Download location: click the Change button and chose tmp folder. Then just close the screen.
Click on any attachments and a small box to the left will appear, it should automatically open if you click on it.
When the bottom left box appears it will contain an arrow; click on it and choose the option "Always open files of this type". Going forward it will open the file instantly instead of the small box appearing to the left and you having to click on it to open. You will have to do it just once for various files such PDF, Excel 2010, Excel 2013 Word, ect.
you can simply escape & by following a dot. try this:
INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 &. Oracle_14');
faced the same problem. solved by following these steps
java org.tij.exercises.HelloWorld
Simplest: get rid of enums. They are not easily modifiable, and thus should very rarely be used.
Answer to your question:
You can download Xcode 8.x from Apple Download Portal or Download Xcode 8.3.3 (or see: Where to download older version of Xcode), if you've premium developer account (apple id). You can install & work with both Xcode 9 and Xcode 8.x in single (mac) system. (Make sure you've Command Line Tools
supporting both version of Xcode, to work with terminal (see: How to install 'Command Line Tool'))
Hint: How to migrate your code Xcode 9 compatible Swift versions (Swift 3.2 or 4)
Xcode 9 allows conversion/migration from Swift 3.0
to Swift 3.2/4.0
only. So if current version of Swift language of your project is below 3.0 then you must migrate your code in Swift 3 compatible version Using Xcode 8.x.
This is common error message that Xcode 9 shows if it identifies Swift language below 3.0, during migration.
Swift 3.2 is supported by Xcode 9 & Xcode 8 both.
Project ? (Select Your Project Target) ? Build Settings ? (Type 'swift' in Searchbar) Swift Compiler Language ? Swift Language Version ? Click on Language list to open it.
Convert your source code from Swift 2.0 to 3.2 using Xcode 8 and then continue with Xcode 9 (Swift 3.2 or 4).
For easier migration of your code, follow these steps: (it will help you to convert into latest version of swift supported by your Xcode Tool)
Xcode: Menus: Edit ? Covert ? To Current Swift Syntax
Its a old question, but lets to show in the REST way (JAX-RS):
import java.util.Arrays;
import javax.ws.rs.*
(...)
Response response = client
.target( url )
.request()
.get();
// Looking if response is "200", "201" or "202", for example:
if( Arrays.asList( Status.OK, Status.CREATED, Status.ACCEPTED ).contains( response.getStatusInfo() ) ) {
// lets something...
}
(...)
If you need to use the vector over and over again and your current code declares it repeatedly within your loop or on every function call, it is likely that you will run out of memory. I suggest that you declare it outside, pass them as pointers in your functions and use:
my_arr.resize()
This way, you keep using the same memory sequence for your vectors instead of requesting for new sequences every time. Hope this helped. Note: resizing it to different sizes may add random values. Pass an integer such as 0 to initialise them, if required.
If youre using Maven, here's something for your pom.xml file
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
The h
helper method:
<%=h "<p> will be preserved" %>
Look at 'The Practice of Programming' (TPOP) by Kernighan & Pike. It includes an example of parsing CSV files in both C and C++. But it would be worth reading the book even if you don't use the code.
(Previous URL: http://cm.bell-labs.com/cm/cs/tpop/)
label {_x000D_
padding: 10px 0;_x000D_
position: relative;_x000D_
}
_x000D_
Add some padding-top and padding-bottom instead of height.
It might be worth noting that this can also occur when Windows blocks downloads that it considers to be unsafe. This can be addressed by right-clicking the jar file (such as ojdbc7.jar), and checking the 'Unblock' box at the bottom.
Windows JAR File Properties Dialog:
I know this has already been answered, but for anybody looking for a simple, no-frills implementation of a ViewPager indicator, I've implemented one that I've open sourced. For anyone finding Jake Wharton's version a bit complex for their needs, have a look at https://github.com/jarrodrobins/SimpleViewPagerIndicator.
I use this Function I modified (the Days part) From @Dane answer: https://stackoverflow.com/a/57720/2097023
CREATE FUNCTION dbo.EdadAMD
(
@FECHA DATETIME
)
RETURNS NVARCHAR(10)
AS
BEGIN
DECLARE
@tmpdate DATETIME
, @years INT
, @months INT
, @days INT
, @EdadAMD NVARCHAR(10);
SELECT @tmpdate = @FECHA;
SELECT @years = DATEDIFF(yy, @tmpdate, GETDATE()) - CASE
WHEN (MONTH(@FECHA) > MONTH(GETDATE()))
OR (
MONTH(@FECHA) = MONTH(GETDATE())
AND DAY(@FECHA) > DAY(GETDATE())
) THEN
1
ELSE
0
END;
SELECT @tmpdate = DATEADD(yy, @years, @tmpdate);
SELECT @months = DATEDIFF(m, @tmpdate, GETDATE()) - CASE
WHEN DAY(@FECHA) > DAY(GETDATE()) THEN
1
ELSE
0
END;
SELECT @tmpdate = DATEADD(m, @months, @tmpdate);
IF MONTH(@FECHA) = MONTH(GETDATE())
AND DAY(@FECHA) > DAY(GETDATE())
SELECT @days =
DAY(EOMONTH(GETDATE(), -1)) - (DAY(@FECHA) - DAY(GETDATE()));
ELSE
SELECT @days = DATEDIFF(d, @tmpdate, GETDATE());
SELECT @EdadAMD = CONCAT(@years, 'a', @months, 'm', @days, 'd');
RETURN @EdadAMD;
END;
GO
It works pretty well.
Shorter way :
import re
cleanString = re.sub('\W+','', string )
If you want spaces between words and numbers substitute '' with ' '
map
, applymap
and ap
ply
: Context MattersFirst major difference: DEFINITION
map
is defined on Series ONLYapplymap
is defined on DataFrames ONLYapply
is defined on BOTHSecond major difference: INPUT ARGUMENT
map
accepts dict
s, Series
, or callableapplymap
and apply
accept callables onlyThird major difference: BEHAVIOR
map
is elementwise for Seriesapplymap
is elementwise for DataFramesapply
also works elementwise but is suited to more complex operations and aggregation. The behaviour and return value depends on the function.Fourth major difference (the most important one): USE CASE
map
is meant for mapping values from one domain to another, so is optimised for performance (e.g., df['A'].map({1:'a', 2:'b', 3:'c'})
)applymap
is good for elementwise transformations across multiple rows/columns (e.g., df[['A', 'B', 'C']].applymap(str.strip)
)apply
is for applying any function that cannot be vectorised (e.g., df['sentences'].apply(nltk.sent_tokenize)
)Footnotes
map
when passed a dictionary/Series will map elements based on the keys in that dictionary/Series. Missing values will be recorded as NaN in the output.
applymap
in more recent versions has been optimised for some operations. You will findapplymap
slightly faster thanapply
in some cases. My suggestion is to test them both and use whatever works better.
map
is optimised for elementwise mappings and transformation. Operations that involve dictionaries or Series will enable pandas to use faster code paths for better performance.Series.apply
returns a scalar for aggregating operations, Series otherwise. Similarly forDataFrame.apply
. Note thatapply
also has fastpaths when called with certain NumPy functions such asmean
,sum
, etc.
I know there are many answers for this, but to me, this answer, by Robert Harvey, summarized it much more clearly:
A stable sort is one which preserves the original order of the input set, where the [unstable] algorithm does not distinguish between two or more items.
There's a whole page of the Django documentation devoted to this, well indexed from the contents page.
As that page states, you need to do:
my_obj.categories.add(fragmentCategory.objects.get(id=1))
or
my_obj.categories.create(name='val1')
Also known as Frozen Binaries but not the same as as the output of a true compiler- they run byte code through a virtual machine (PVM). Run the same as a compiled program just larger because the program is being compiled along with the PVM. Py2exe can freeze standalone programs that use the tkinter, PMW, wxPython, and PyGTK GUI libraties; programs that use the pygame game programming toolkit; win32com client programs; and more. The Stackless Python system is a standard CPython implementation variant that does not save state on the C language call stack. This makes Python more easy to port to small stack architectures, provides efficient multiprocessing options, and fosters novel programming structures such as coroutines. Other systems of study that are working on future development: Pyrex is working on the Cython system, the Parrot project, the PyPy is working on replacing the PVM altogether, and of course the founder of Python is working with Google to get Python to run 5 times faster than C with the Unladen Swallow project. In short, py2exe is the easiest and Cython is more efficient for now until these projects improve the Python Virtual Machine (PVM) for standalone files.
I have come up with a solution that is relatively accurate at evaluating when the angular initialisation is complete.
The directive is:
.directive('initialisation',['$rootScope',function($rootScope) {
return {
restrict: 'A',
link: function($scope) {
var to;
var listener = $scope.$watch(function() {
clearTimeout(to);
to = setTimeout(function () {
console.log('initialised');
listener();
$rootScope.$broadcast('initialised');
}, 50);
});
}
};
}]);
That can then just be added as an attribute to the body
element and then listened for using $scope.$on('initialised', fn)
It works by assuming that the application is initialised when there are no more $digest cycles. $watch is called every digest cycle and so a timer is started (setTimeout not $timeout so a new digest cycle is not triggered). If a digest cycle does not occur within the timeout then the application is assumed to have initialised.
It is obviously not as accurate as satchmoruns solution (as it is possible a digest cycle takes longer than the timeout) but my solution doesn't need you to keep track of the modules which makes it that much easier to manage (particularly for larger projects). Anyway, seems to be accurate enough for my requirements. Hope it helps.
Mono is a runtime environment that can run .NET applications and that works on both Windows and Linux. It includes a C# compiler.
As an IDE, you could use MonoDevelop, and I suppose there's something available for Eclipse, too.
Note that WinForms support on Mono is there, but somewhat lacking. Generally, Mono developers seem to prefer different GUI toolkits such as Gtk#.
If none of the other answers work for you, it may be because you are binding the ContentProperty
of a control in the OnLoad
function, which means this won't work:
private void UserControl_Load(object sender, RoutedEventArgs e)
{
Bind.SetBindingElement(labelName, String.Format("{0:0.00}", PropertyName), Label.ContentProperty)
}
The solution is simple: there is a ContentStringFormat
property in the xaml. So when you create the label do this:
//if you want the decimal places definite
<Label Content="0" Name="labelName" ContentStringFormat="0.00"/>
Or
//if you want the decimal places to be optional
<Label Content="0" Name="labelName" ContentStringFormat="0.##"/>
My opinion is C# and ASP.NET would be the best of the three for development that is web biased.
I doubt anyone writes new web apps in C or C++ anymore. It was done 10 years ago, and there's likely a lot of legacy code still in use, but they're not particularly well suited, there doesn't appear to be as much (ongoing) tool support, and they probably have a small active community that does web development (except perhaps for web server development). I wrote many website C++ COM objects back in the day, but C# is far more productive that there's no compelling reason to code C or C++ (in this context) unless you need to.
I do still write C++ if necessary, but it's typically for a small problem domain. e.g. communicating from C# via P/Invoke to old C-style dll's - doing some things that are downright clumsy in C# were a breeze to create a C++ COM object as a bridge.
The nice thing with C# is that you can also easily transfer into writing Windows and Console apps and stay in C#. With Mono you're also not limited to Windows (although you may be limited to which libraries you use).
Anyways this is all from a web-biased perspective. If you asked about embedded devices I'd say C or C++. You could argue none of these are suited for web development, but C#/ASP.NET is pretty slick, it works well, there are heaps of online resources, a huge community, and free dev tools.
So from a real-world perspective, picking only one of C#, C++ and C as requested, as a general rule, you're better to stick with C#.
Here is a pitfall to avoid. In case you need to access your variable $name within a function, you need to say "global $name;" at the beginning of that function. You need to repeat this for each function in the same file.
include('front.inc');
global $name;
function foo() {
echo $name;
}
function bar() {
echo $name;
}
foo();
bar();
will only show errors. The correct way to do that would be:
include('front.inc');
function foo() {
global $name;
echo $name;
}
function bar() {
global $name;
echo $name;
}
foo();
bar();
The advantage of Java 1.8 forEach method over 1.7 Enhanced for loop is that while writing code you can focus on business logic only.
forEach method takes java.util.function.Consumer object as an argument, so It helps in having our business logic at a separate location that you can reuse it anytime.
Have look at below snippet,
Here I have created new Class that will override accept class method from Consumer Class, where you can add additional functionility, More than Iteration..!!!!!!
class MyConsumer implements Consumer<Integer>{
@Override
public void accept(Integer o) {
System.out.println("Here you can also add your business logic that will work with Iteration and you can reuse it."+o);
}
}
public class ForEachConsumer {
public static void main(String[] args) {
// Creating simple ArrayList.
ArrayList<Integer> aList = new ArrayList<>();
for(int i=1;i<=10;i++) aList.add(i);
//Calling forEach with customized Iterator.
MyConsumer consumer = new MyConsumer();
aList.forEach(consumer);
// Using Lambda Expression for Consumer. (Functional Interface)
Consumer<Integer> lambda = (Integer o) ->{
System.out.println("Using Lambda Expression to iterate and do something else(BI).. "+o);
};
aList.forEach(lambda);
// Using Anonymous Inner Class.
aList.forEach(new Consumer<Integer>(){
@Override
public void accept(Integer o) {
System.out.println("Calling with Anonymous Inner Class "+o);
}
});
}
}
consistency and readability (self-documenting code) are important. some clues (such as case) can and should be used to avoid collisions, and to indicate whether an instance is required.
one of the best practices i got into was the use of code formatters (astyle and uncrustify are 2 examples). code formatters can destroy your code formatting - configure the formatter, and let it do its job. seriously, forget about manual formatting and get into the practice of using them. they will save a ton of time.
as mentioned, be very descriptive with naming. also, be very specific with scoping (class types/data/namespaces/anonymous namespaces). in general, i really like much of java's common written form - that is a good reference and similar to c++.
as for specific appearance/naming, this is a small sample similar to what i use (variables/arguments are lowerCamel and this only demonstrates a portion of the language's features):
/** MYC_BEGIN_FILE_ID::FD_Directory_nanotimer_FN_nanotimer_hpp_::MYC_BEGIN_FILE_DIR::Directory/nanotimer::MYC_BEGIN_FILE_FILE::nanotimer.hpp::Copyright... */
#ifndef FD_Directory_nanotimer_FN_nanotimer_hpp_
#define FD_Directory_nanotimer_FN_nanotimer_hpp_
/* typical commentary omitted -- comments detail notations/conventions. also, no defines/macros other than header guards */
namespace NamespaceName {
/* types prefixed with 't_' */
class t_nanotimer : public t_base_timer {
/* private types */
class t_thing {
/*...*/
};
public:
/* public types */
typedef uint64_t t_nanosecond;
/* factory initializers -- UpperCamel */
t_nanotimer* WithFloat(const float& arg);
/* public/protected class interface -- UpperCamel */
static float Uptime();
protected:
/* static class data -- UpperCamel -- accessors, if needed, use Get/Set prefix */
static const t_spoke Spoke;
public:
/* enums in interface are labeled as static class data */
enum { Granularity = 4 };
public:
/* construction/destruction -- always use proper initialization list */
explicit t_nanotimer(t_init);
explicit t_nanotimer(const float& arg);
virtual ~t_nanotimer();
/*
public and protected instance methods -- lowercaseCamel()
- booleans prefer is/has
- accessors use the form: getVariable() setVariable().
const-correctness is important
*/
const void* address() const;
virtual uint64_t hashCode() const;
protected:
/* interfaces/implementation of base pure virtuals (assume this was pure virtual in t_base_timer) */
virtual bool hasExpired() const;
private:
/* private methods and private static data */
void invalidate();
private:
/*
instance variables
- i tend to use underscore suffix, but d_ (for example) is another good alternative
- note redundancy in visibility
*/
t_thing ivar_;
private:
/* prohibited stuff */
explicit t_nanotimer();
explicit t_nanotimer(const int&);
};
} /* << NamespaceName */
/* i often add a multiple include else block here, preferring package-style inclusions */
#endif /* MYC_END_FILE::FD_Directory_nanotimer_FN_nanotimer_hpp_ */
.example.com TRUE / FALSE 1560211200 MY_VARIABLE MY_VALUE
The cookies file format apparently consists of a line per cookie and each line consists of the following seven tab-delimited fields:
If a programmer is interested in only parsing a table from a webpage, they can utilize the pandas method pandas.read_html
.
Let's say we want to extract the GDP data table from the website: https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries
Then following codes does the job perfectly (No need of beautifulsoup and fancy html):
import pandas as pd
import requests
url = "https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries"
r = requests.get(url)
df_list = pd.read_html(r.text) # this parses all the tables in webpages to a list
df = df_list[0]
df.head()
To clarify one point in @EdChum's answer, per the documentation, you can include the object columns by using df.describe(include='all')
. It won't provide many statistics, but will provide a few pieces of info, including count, number of unique values, top value. This may be a new feature, I don't know as I am a relatively new user.
Use
find \( -path "./tmp" -o -path "./scripts" \) -prune -o -name "*_peaks.bed" -print
or
find \( -path "./tmp" -o -path "./scripts" \) -prune -false -o -name "*_peaks.bed"
or
find \( -path "./tmp" -path "./scripts" \) ! -prune -o -name "*_peaks.bed"
The order is important. It evaluates from left to right. Always begin with the path exclusion.
Do not use -not
(or !
) to exclude whole directory. Use -prune
.
As explained in the manual:
-prune The primary shall always evaluate as true; it
shall cause find not to descend the current
pathname if it is a directory. If the -depth
primary is specified, the -prune primary shall
have no effect.
and in the GNU find manual:
-path pattern
[...]
To ignore a whole
directory tree, use -prune rather than checking
every file in the tree.
Indeed, if you use -not -path "./pathname"
,
find will evaluate the expression for each node under "./pathname"
.
find expressions are just condition evaluation.
\( \)
- groups operation (you can use -path "./tmp" -prune -o -path "./scripts" -prune -o
, but it is more verbose).-path "./script" -prune
- if -path
returns true and is a directory, return true for that directory and do not descend into it.-path "./script" ! -prune
- it evaluates as (-path "./script") AND (! -prune)
. It revert the "always true" of prune to always false. It avoids printing "./script"
as a match.-path "./script" -prune -false
- since -prune
always returns true, you can follow it with -false
to do the same than !
.-o
- OR operator. If no operator is specified between two expressions, it defaults to AND operator.Hence, \( -path "./tmp" -o -path "./scripts" \) -prune -o -name "*_peaks.bed" -print
is expanded to:
[ (-path "./tmp" OR -path "./script") AND -prune ] OR ( -name "*_peaks.bed" AND print )
The print is important here because without it is expanded to:
{ [ (-path "./tmp" OR -path "./script" ) AND -prune ] OR (-name "*_peaks.bed" ) } AND print
-print
is added by find - that is why most of the time, you do not need to add it in you expression. And since -prune
returns true, it will print "./script" and "./tmp".
It is not necessary in the others because we switched -prune
to always return false.
Hint: You can use find -D opt expr 2>&1 1>/dev/null
to see how it is optimized and expanded,
find -D search expr 2>&1 1>/dev/null
to see which path is checked.
I got Broyden's method to work for coupled non-linear equations (generally involving polynomials and exponentials) in IDL, but I haven't tried it in Python:
scipy.optimize.broyden1
scipy.optimize.broyden1(F, xin, iter=None, alpha=None, reduction_method='restart', max_rank=None, verbose=False, maxiter=None, f_tol=None, f_rtol=None, x_tol=None, x_rtol=None, tol_norm=None, line_search='armijo', callback=None, **kw)[source]
Find a root of a function, using Broyden’s first Jacobian approximation.
This method is also known as “Broyden’s good method”.
Javascript has no way of telling the CPU usage. This would break the sandbox javascript runs inside.
Other than that, hooking the page's onmouseover and onkeydown events would probably work.
You could also set use setTimeout in the onload event to schedule a function to be called after a delay.
// Call aFunction after 1 second
window.setTimeout(aFunction, 1000);
gethostname()
using the IP from $_SERVER['REMOTE_ADDR']
while accessing the script remotely will return the IP of your internet connection, not your computer.
I do it this way when there are many points to use...
public enum Status {
VALID("valid"), OLD("old");
private final String val;
Status(String val) {
this.val = val;
}
public String getStatus() {
return val;
}
public static void setRequestAttributes(HttpServletRequest request) {
Map<String,String> vals = new HashMap<String,String>();
for (Status val : Status.values()) {
vals.put(val.name(), val.value);
}
request.setAttribute("Status", vals);
}
}
JSP
<%@ page import="...Status" %>
<% Status.setRequestAttributes(request) %>
<c:when test="${dp.status eq Status.VALID}">
...
I believe you can set the SVN_USER
environment variable to change your SVN username.
Use
It is the entity used to represent a non-breaking space. It is essentially a standard space, the primary difference being that a browser should not break (or wrap) a line of text at the point that this occupies.
var a = 'something' + '         ' + 'something'
A common character entity used in HTML is the non-breaking space ( ).
Remember that browsers will always truncate spaces in HTML pages. If you write 10 spaces in your text, the browser will remove 9 of them. To add real spaces to your text, you can use the character entity.
http://www.w3schools.com/html/html_entities.asp
Demo
var a = 'something' + '         ' + 'something';_x000D_
_x000D_
document.body.innerHTML = a;
_x000D_
Suppose, you have a class String
:
class String {
public:
String(int n); // allocate n bytes to the String object
String(const char *p); // initializes object with char *p
};
Now, if you try:
String mystring = 'x';
The character 'x'
will be implicitly converted to int
and then the String(int)
constructor will be called. But, this is not what the user might have intended. So, to prevent such conditions, we shall define the constructor as explicit
:
class String {
public:
explicit String (int n); //allocate n bytes
String(const char *p); // initialize sobject with string p
};
You need to remove the /
before the [
. Predicates (the parts in [
]
) shouldn't have slashes immediately before them. Also, to select the Employee element itself, you should leave off the /text()
at the end or otherwise you'd just be selecting the whitespace text values immediately under the Employee element.
//Employee[@id='4']
Edit: As Jens points out in the comments, //
can be very slow because it searches the entire document for matching nodes. If the structure of the documents you're working with is going to be consistent, you are probably best off using a full path, for example:
/Employees/Employee[@id='4']
To shorten Narendra's logic, you can use this:
boolean var = lis1.stream().anyMatch(element -> list2.contains(element));
I have never had any luck with any scrollable content placed inside a stackpanel (anything derived from ScrollableContainer. The stackpanel has an odd layout mechanism that confuses child controls when the measure operation is completed and I found the vertical size ends up infinite, therefore not constrained - so it goes beyond the boundaries of the container and ends up clipped. The scrollbar doesn't show because the control thinks it has all the space in the world when it doesn't.
You should always place scrollable content inside a container that can resolve to a known height during its layout operation at runtime so that the scrollbars size appropriately. The parent container up in the visual tree must be able to resolve to an actual height, and this happens in the grid if you set the height of the RowDefinition o to auto or fixed.
This also happens in Silverlight.
-em-
Don't use Rstudio to update R. Rstudio IS NOT R, Rstudio is just an IDE. This answer is a summary of previous answers for different OS. For all OS it is convenient to have a look in advance what will happen with the packages you have already installed here.
WINDOWS ->> Open CMD/Powershell as an administrator and type "R" to go into interactive mode. If this does not work, search and run RGui.exe instead of writing R in the console ...and then:
lib_path <- gsub( "/", "\\\\" , Sys.getenv("R_LIBS_USER"))
install.packages("installr", lib = lib_path)
install.packages("stringr", lib_path)
library(stringr, lib.loc = lib_path)
library(installr, lib.loc = lib_path)
installr::updateR()
MacOS ->> You can use updateR package. The package is not on CRAN, so you’ll need to run the following code in Rgui:
install.packages("devtools")
devtools::install_github("AndreaCirilloAC/updateR")
updateR(admin_password = "PASSWORD") # Where "PASSWORD" stands for your system password
Note that it is planned to merge updateR and installR in the near future to work for both Mac and Windows.
Linux ->> For the moment installr
is NOT available for Linux/MacOS (see documentation for current version 0.20). As R is installed, you can follow these instructions (in Ubuntu, although the idea is the same in other distros: add the source, update and upgrade and install.)
Interface Builder uses them to determine what members and messages can be 'wired' up to the interface controls you are using in your window/view.
IBOutlet and IBAction are purely there as markers that Interface Builder looks for when it parses your code at design time, they don't have any affect on the code generated by the compiler.
Actually, his example won't work (although at first I thought that it would, too). Based on the help for the Start command, the first parameter is the name of the newly created Command Prompt window, and the second and third should be the path to the application and its parameters, respectively. If you add another "" before path to the app, it should work (at least it did for me). Use something like this:
start "" "c:\path with spaces\app.exe" param1 "param with spaces"
You can change the first argument to be whatever you want the title of the new command prompt to be. If it's a Windows app that is created, then the command prompt won't be displayed, and the title won't matter.
Subscribing to the IUS Community Project Repository
cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh
Run the script:
sudo bash setup-ius.sh
Upgrading mod_php with Apache
This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.
Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.
sudo yum remove php-cli mod_php php-common
Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.
sudo yum install mod_php70u php70u-cli php70u-mysqlnd
Finally, restart Apache to load the new version of mod_php:
sudo apachectl restart
You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:
systemctl status httpd
Replace your line with this.
notificationManager.notify((int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE), notification);
I recently came to this question because the usual suspects were not working with linked packages. If you're like me and are taking advantage of npm link
during development to effectively work on a project that is made up of many packages, it's important that changes that occur in dependencies trigger a reload as well.
After having tried node-mon and pm2, even following their instructions for additionally watching the node_modules folder, they still did not pick up changes. Although there are some custom solutions in the answers here, for something like this, a separate package is cleaner. I came across node-dev today and it works perfectly without any options or configuration.
From the Readme:
In contrast to tools like supervisor or nodemon it doesn't scan the filesystem for files to be watched. Instead it hooks into Node's require() function to watch only the files that have been actually required.
See the relevant documentation in general and specifically
from matplotlib.ticker import FormatStrFormatter
fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
Now it's possible and supported by all major browsers: https://developer.mozilla.org/en-US/docs/Web/API/File/File
var file = new File(["foo"], "foo.txt", {
type: "text/plain",
});
I wrote this simple marco for the same purpose, hope it helps:
{%- macro stringMaxLength(str, maxLength) -%}
{%- if str | length < maxLength -%}
{{ str }}
{%- else -%}
{{ str|slice(0, maxLength) }}...
{%- endif -%}
{%- endmacro -%}
Usage Example #1 (Output: "my long string here ..."):
{{ _self.stringMaxLength("my long string here bla bla bla la", 20) }}
Usage Example #2 (Output: "shorter string!"):
{{ _self.stringMaxLength("shorter string!", 20) }}
Use the CSS property border on the <td>
s following the <tr>
s you do not want to have the border.
In my example I made a class noBorder
that I gave to one <tr>
. Then I use a simple selector tr.noBorder td
to make the border go away for all the <td>
s that are inside of <tr>
s with the noBorder
class by assigning border: 0
.
Note that you do not need to provide the unit (i.e. px
) if you set something to 0
as it does not matter anyway. Zero is just zero.
table, tr, td {_x000D_
border: 3px solid red;_x000D_
}_x000D_
tr.noBorder td {_x000D_
border: 0;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>A1</td>_x000D_
<td>B1</td>_x000D_
<td>C1</td>_x000D_
</tr>_x000D_
<tr class="noBorder">_x000D_
<td>A2</td>_x000D_
<td>B2</td>_x000D_
<td>C2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>A3</td>_x000D_
<td>A3</td>_x000D_
<td>A3</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Here's the output as an image:
Email Validation Regex
^[a-z0-9][-a-z0-9._]+@([-a-z0-9]+.)+[a-z]{2,5}$
Or
^[a-z0-9][-a-z0-9._]+@([-a-z0-9]+[.])+[a-z]{2,5}$
Demo Link:
to allow letters ans spaces
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z\s]+$/i.test(value);
}, "Only alphabetical characters");
$('#yourform').validate({
rules: {
name_field: {
lettersonly: true
}
}
});
I have noticed api example code contains an example of barchart with the value of the bar displayed on each bar:
"""
========
Barchart
========
A bar plot with errorbars and height labels on individual bars
"""
import numpy as np
import matplotlib.pyplot as plt
N = 5
men_means = (20, 35, 30, 35, 27)
men_std = (2, 3, 4, 1, 2)
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(ind, men_means, width, color='r', yerr=men_std)
women_means = (25, 32, 34, 20, 25)
women_std = (3, 5, 2, 3, 3)
rects2 = ax.bar(ind + width, women_means, width, color='y', yerr=women_std)
# add some text for labels, title and axes ticks
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind + width / 2)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
ax.legend((rects1[0], rects2[0]), ('Men', 'Women'))
def autolabel(rects):
"""
Attach a text label above each bar displaying its height
"""
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
'%d' % int(height),
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
plt.show()
output:
FYI What is the unit of height variable in "barh" of matplotlib? (as of now, there is no easy way to set a fixed height for each bar)
The most important thing to know about async
and await
is that await
doesn't wait for the associated call to complete. What await
does is to return the result of the operation immediately and synchronously if the operation has already completed or, if it hasn't, to schedule a continuation to execute the remainder of the async
method and then to return control to the caller. When the asynchronous operation completes, the scheduled completion will then execute.
The answer to the specific question in your question's title is to block on an async
method's return value (which should be of type Task
or Task<T>
) by calling an appropriate Wait
method:
public static async Task<Foo> GetFooAsync()
{
// Start asynchronous operation(s) and return associated task.
...
}
public static Foo CallGetFooAsyncAndWaitOnResult()
{
var task = GetFooAsync();
task.Wait(); // Blocks current thread until GetFooAsync task completes
// For pedagogical use only: in general, don't do this!
var result = task.Result;
return result;
}
In this code snippet, CallGetFooAsyncAndWaitOnResult
is a synchronous wrapper around asynchronous method GetFooAsync
. However, this pattern is to be avoided for the most part since it will block a whole thread pool thread for the duration of the asynchronous operation. This an inefficient use of the various asynchronous mechanisms exposed by APIs that go to great efforts to provide them.
The answer at "await" doesn't wait for the completion of call has several, more detailed, explanations of these keywords.
Meanwhile, @Stephen Cleary's guidance about async void
holds. Other nice explanations for why can be found at http://www.tonicodes.net/blog/why-you-should-almost-never-write-void-asynchronous-methods/ and https://jaylee.org/archive/2012/07/08/c-sharp-async-tips-and-tricks-part-2-async-void.html
Well java.lang.Exception extends java.lang.Throwable. java.io.FileNotFoundException extends java.lang.Exception. So if a method throws java.io.FileNotFoundException then in the override method you cannot throw anything higher up the hierarchy than FileNotFoundException e.g. you can't throw java.lang.Exception. You could throw a subclass of FileNotFoundException though. However you would be forced to handle the FileNotFoundException in the overriden method. Knock up some code and give it a try!
The rules are there so you don't lose the original throws declaration by widening the specificity, as the polymorphism means you can invoke the overriden method on the superclass.
Something like this would do:
xargs cat <filenames.txt
The xargs
program reads its standard input, and for each line of input runs the cat
program with the input lines as argument(s).
If you really want to do this in a loop, you can:
for fn in `cat filenames.txt`; do
echo "the next file is $fn"
cat $fn
done
<script>
function deleteItem()
{
var resp = confirm("Do you want to delete this item???");
if (resp == true) {
//do something
}
else {
//do something
}
}
</script>
call this function using onClick
Driver for Huawei was not found. So I've been using the universal ADB driver:
ADBDriverInstaller
and Run the file. Make sure you have connected your device through USB to your computer.Restart
button. Before doing that read this link:
(The above. in brief, says to press Restart button in the dialog box. Select Troubleshoot. Select Advance Option. Select Startup Setting. Press Restart. After system's been restarted, on the appearing screen press 7)
ADBDriverInstaller
file again. Select your device from the options. Press install. And it's done :)
Let's say I have 32-bit ARGB value with 8-bits per channel. I want to replace the alpha component with another alpha value, such as 0x45
unsigned long alpha = 0x45
unsigned long pixel = 0x12345678;
pixel = ((pixel & 0x00FFFFFF) | (alpha << 24));
The mask turns the top 8 bits to 0, where the old alpha value was. The alpha value is shifted up to the final bit positions it will take, then it is OR-ed into the masked pixel value. The final result is 0x45345678 which is stored into pixel.
It is possible without any Javascript :)
The HTML:
<div class='box'>
<div class='content'>Aspect ratio of 1:1</div>
</div>
The CSS:
.box {
position: relative;
width: 50%; /* desired width */
}
.box:before {
content: "";
display: block;
padding-top: 100%; /* initial ratio of 1:1*/
}
.content {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
/* Other ratios - just apply the desired class to the "box" element */
.ratio2_1:before{
padding-top: 50%;
}
.ratio1_2:before{
padding-top: 200%;
}
.ratio4_3:before{
padding-top: 75%;
}
.ratio16_9:before{
padding-top: 56.25%;
}
This happens when you push first time without net connection or poor net connection.But when you try again using good connection 2,3 times problem will be solved.
Just Right Click on Project
Click on Team
Click Refresh/Cleaup
this will remove all the current lock files created by SVN
hope this will help !!!!
Sometimes size
"picks the wrong one" and returns a hash (which is what count
would do)
In that case, use length
to get an integer instead of hash.
res.json
forces the argument to JSON. res.send
will take an non-json object or non-json array and send another type. For example:
This will return a JSON number.
res.json(100)
This will return a status code and issue a warning to use sendStatus.
res.send(100)
If your argument is not a JSON object or array (null,undefined,boolean,string), and you want to ensure it is sent as JSON, use res.json
.
You may need to install Hotfix KB980368.
This article describes a update that enables certain Internet Information Services (IIS) 7.0 or IIS 7.5 handlers to handle requests whose URLs do not end with a period. Specifically, these handlers are mapped to "." request paths. Currently, a handler that is mapped to a "." request path handles only requests whose URLs end with a period. For example, the handler handles only requests whose URLs resemble the following URL:
http://www.example.com/ExampleSite/ExampleFile.
After you apply this update, handlers that are mapped to a "*." request path can handle requests whose URLs end with a period and requests whose URLs do not end with a period. For example, the handler can now handle requests that resemble the following URLs:
http://www.example.com/ExampleSite/ExampleFile
http://www.example.com/ExampleSite/ExampleFile.
After this patch is applied, ASP.NET 4 applications can handle requests for extensionless URLs. Therefore, managed HttpModules that run prior to handler execution will run. In some cases, the HttpModules can return errors for extensionless URLs. For example, an HttpModule that was written to expect only .aspx requests may now return errors when it tries to access the HttpContext.Session property.
A little bit naive but this is what I usually remember off the top of my head:
for i in 1 2 3; do
some commands
done
Very similar to @joe-koberg's answer. His is better especially if you need many repetitions, just harder for me to remember other syntax because in last years I'm not using bash
a lot. I mean not for scripting at least.
I needed to snapshot a div on the page (for a webapp I wrote) that is protected by JWT's and makes very heavy use of Angular.
I had no luck with any of the above methods.
I ended up taking the outerHTML of the div I needed, cleaning it up a little (*) and then sending it to the server where I run wkhtmltopdf against it.
This is working very well for me.
(*) various input devices in my pages didn't render as checked or have their text values when viewed in the pdf... So I run a little bit of jQuery on the html before I send it up for rendering. ex: for text input items -- I copy their .val()'s into 'value' attributes, which then can be seen by wkhtmlpdf
I had a similar problem with HTML input fields in MVC. The web paged only showed the first keyword of the field. Example: input field: "The quick brown fox" Displayed value: "The"
The resolution was to put the variable in quotes in the value statement as follows:
<input class="ParmInput" type="text" id="respondingRangerUnit" name="respondingRangerUnit"
onchange="validateInteger(this.value)" value="@ViewBag.respondingRangerUnit">
To refresh page you don't need react-router, simple js:
window.location.reload();
To re-render view in React component, you can just fire update with props/state.
In versions of Gradle prior to 5, the test.single
system property can be used to specify a single test.
You can do gradle -Dtest.single=ClassUnderTestTest test
if you want to test single class or use regexp like gradle -Dtest.single=ClassName*Test test
you can find more examples of filtering classes for tests under this link.
Gradle 5 removed this option, as it was superseded by test filtering using the --tests
command line option.
To remove a remote:
git remote remove origin
To add a remote:
git remote add origin yourRemoteUrl
and finally
git push -u origin master
Here's some JavaScript for copy-paste ease (this is irritate's answer):
function scaleBetween(unscaledNum, minAllowed, maxAllowed, min, max) {
return (maxAllowed - minAllowed) * (unscaledNum - min) / (max - min) + minAllowed;
}
Applied like so, scaling the range 10-50 to a range between 0-100.
var unscaledNums = [10, 13, 25, 28, 43, 50];
var maxRange = Math.max.apply(Math, unscaledNums);
var minRange = Math.min.apply(Math, unscaledNums);
for (var i = 0; i < unscaledNums.length; i++) {
var unscaled = unscaledNums[i];
var scaled = scaleBetween(unscaled, 0, 100, minRange, maxRange);
console.log(scaled.toFixed(2));
}
0.00, 18.37, 48.98, 55.10, 85.71, 100.00
Edit:
I know I answered this a long time ago, but here's a cleaner function that I use now:
Array.prototype.scaleBetween = function(scaledMin, scaledMax) {
var max = Math.max.apply(Math, this);
var min = Math.min.apply(Math, this);
return this.map(num => (scaledMax-scaledMin)*(num-min)/(max-min)+scaledMin);
}
Applied like so:
[-4, 0, 5, 6, 9].scaleBetween(0, 100);
[0, 30.76923076923077, 69.23076923076923, 76.92307692307692, 100]
const mode = (str) => {
return str
.split(' ')
.reduce((data, key) => {
let counter = data.map[key] + 1 || 1
data.map[key] = counter
if (counter > data.counter) {
data.counter = counter
data.mode = key
}
return data
}, {
counter: 0,
mode: null,
map: {}
})
.mode
}
console.log(mode('the t-rex is the greatest of them all'))
In my case I did a "Convert to application" to the wrong folder on iis. My application was set in a subfolder of where it should have been.
If, for example, x = 5 and is stored as string, you can also just:
x = x + 0
and the new x would be stored as a numeric value.
Try using ZoomView
for zooming any other view.
http://code.google.com/p/android-zoom-view/ it's easy, free and fun to use!
The checked
and selected
attributes are allowed only two values, which are a copy of the attribute name and (from HTML 5 onwards) an empty string. Giving any other value is an error.
If you don't want to set the attribute, then the entire attribute must be omitted.
Note that in HTML 4 you may omit everything except the value. HTML 5 changed this to omit everything except the name (which makes no practical difference).
Thus, the complete (aside from variations in cAsE) set of valid representations of the attribute are:
<input ... checked="checked"> <!-- All versions of HTML / XHTML -->
<input ... checked > <!-- Only HTML 4.01 and earlier -->
<input ... checked > <!-- Only HTML 5 and later -->
<input ... checked="" > <!-- Only HTML 5 and later -->
Documents served as text/html (HTML or XHTML) will be fed through a tag soup parser, and the presence of a checked attribute (with any value) will be treated as "This element should be checked". Thus, while invalid, checked="true"
, checked="yes"
, and checked="false"
will all trigger the checked state.
I've not had any inclination to find out what error recovery mechanisms are in place for XML parsing mode should a different value be given to the attribute, but I would expect that the legacy of HTML and/or simple error recovery would treat it in the same way: If the attribute is there then the element is checked.
(And all the above applies equally to selected
as it does to checked
.)
Great answers. I also had a problem with NULLS and managed to solve it by including a COALESCE inside of the GROUP_CONCAT. Example as follows:
SELECT id, GROUP_CONCAT(COALESCE(name,'') SEPARATOR ' ')
FROM table
GROUP BY id;
Hope this helps someone else
Object.keys(Array.apply(0, Array(3))).map(Number)
Returns [0, 1, 2]
. Very similar to Igor Shubin's excellent answer, but with slightly less trickery (and one character longer).
Array(3) // [undefined × 3]
Generate an array of length n=3. Unfortunately this array is almost useless to us, so we have to…Array.apply(0,Array(3)) // [undefined, undefined, undefined]
make the array iterable. Note: null's more common as apply's first arg but 0's shorter.Object.keys(Array.apply(0,Array(3))) // ['0', '1', '2']
then get the keys of the array (works because Arrays are the typeof array is an object with indexes for keys.Object.keys(Array.apply(0,Array(3))).map(Number) // [0, 1, 2]
and map over the keys, converting strings to numbers.Just my 2 cents as stated in the answer above : The copy() method shouldn't be used as-is for copying files without a slight adjustment:
function copy(callback) {
var readStream = fs.createReadStream(oldPath);
var writeStream = fs.createWriteStream(newPath);
readStream.on('error', callback);
writeStream.on('error', callback);
// Do not callback() upon "close" event on the readStream
// readStream.on('close', function () {
// Do instead upon "close" on the writeStream
writeStream.on('close', function () {
callback();
});
readStream.pipe(writeStream);
}
The copy function wrapped in a Promise:
function copy(oldPath, newPath) {
return new Promise((resolve, reject) => {
const readStream = fs.createReadStream(oldPath);
const writeStream = fs.createWriteStream(newPath);
readStream.on('error', err => reject(err));
writeStream.on('error', err => reject(err));
writeStream.on('close', function() {
resolve();
});
readStream.pipe(writeStream);
})
However, keep in mind that the filesystem might crash if the target folder doesn't exist.
// Here is very simple way to go:
// Your DataSet.
let numberArray = [
{
"x": "8/11/2009",
"y": 0.026572007
},
{
"x": "8/12/2009",
"y": 0.025057454
},
{
"x": "8/13/2009",
"y": 0.024530916
},
{
"x": "8/14/2009",
"y": 0.031004457
}
]
// 1. First create Array, containing all the value of Y
let result = numberArray.map((y) => y)
console.log(result) // >> [0.026572007,0.025057454,0.024530916,0.031004457]
// 2.
let maxValue = Math.max.apply(null, result)
console.log(maxValue) // >> 0.031004457
Here's a method, not a library, which seems to work for me.
The goals here are to be terse, each argument parsed by a single line, the args line up for readability, the code is simple and doesn't depend on any special modules (only os + sys), warns about missing or unknown arguments gracefully, use a simple for/range() loop, and works across python 2.x and 3.x
Shown are two toggle flags (-d, -v), and two values controlled by arguments (-i xxx and -o xxx).
import os,sys
def HelpAndExit():
print("<<your help output goes here>>")
sys.exit(1)
def Fatal(msg):
sys.stderr.write("%s: %s\n" % (os.path.basename(sys.argv[0]), msg))
sys.exit(1)
def NextArg(i):
'''Return the next command line argument (if there is one)'''
if ((i+1) >= len(sys.argv)):
Fatal("'%s' expected an argument" % sys.argv[i])
return(1, sys.argv[i+1])
### MAIN
if __name__=='__main__':
verbose = 0
debug = 0
infile = "infile"
outfile = "outfile"
# Parse command line
skip = 0
for i in range(1, len(sys.argv)):
if not skip:
if sys.argv[i][:2] == "-d": debug ^= 1
elif sys.argv[i][:2] == "-v": verbose ^= 1
elif sys.argv[i][:2] == "-i": (skip,infile) = NextArg(i)
elif sys.argv[i][:2] == "-o": (skip,outfile) = NextArg(i)
elif sys.argv[i][:2] == "-h": HelpAndExit()
elif sys.argv[i][:1] == "-": Fatal("'%s' unknown argument" % sys.argv[i])
else: Fatal("'%s' unexpected" % sys.argv[i])
else: skip = 0
print("%d,%d,%s,%s" % (debug,verbose,infile,outfile))
The goal of NextArg() is to return the next argument while checking for missing data, and 'skip' skips the loop when NextArg() is used, keeping the flag parsing down to one liners.