If you already have a number of dates already highlighted and want to determine which date was last clicked then you'll need the following:
$('#startdate').data('datepicker').viewDate
viewDate
returns a JavaScript date object so you'll need to handle it accordingly.
$("#year").datepicker( {
format: "yyyy",
viewMode: "years",
minViewMode: "years"
}).on('changeDate', function(e){
$(this).datepicker('hide');
});
There is no need to destroy current instance, just refresh.
$('#datepicker')
.datepicker('option', 'minDate', new Date)
.datepicker('refresh');
I'm not entirely sure if I understood your question, but it seems that you're trying to set value for an input type Date.
If you want to set a value for an input type 'Date', then it has to be formatted as "yyyy-MM-dd" (Note: capital MM for Month, lower case mm for minutes). Otherwise, it will clear the value and leave the datepicker empty.
Let's say you have a button called "DateChanger" and you want to set your datepicker to "22 Dec 2012" when you click it.
<script>
$(document).ready(function () {
$('#DateChanger').click(function() {
$('#dtFrom').val("2012-12-22");
});
});
</script>
<input type="date" id="dtFrom" name="dtFrom" />
<button id="DateChanger">Click</button>
Remember to include JQuery reference.
Use Code:
var startDate = "2019-03-12"; //Date Format YYYY-MM-DD
$('#datepicker').val(startDate).datepicker("update");
Explanation:
Datepicker(input field) Selector #datepicker.
Update input field.
Call datepicker with option update.
This line looks questionable:
page_output.innerHTML = str_output;
You can use .innerHTML
within jQuery, or you can use it without, but you have to address the selector semantically one way or the other:
$('#page_output').innerHTML /* for jQuery */
document.getElementByID('page_output').innerHTML /* for standard JS */
or better yet
$('#page_output').html(str_output);
Or, using datetimepicker plugin.
The code above doesn't set the value of the input element nor does it fire a change event. The code below works in Chrome and Firefox (not tested in other browsers):
$('input[type="date"]').click(function(e){
e.preventDefault();
}).datepicker({
onSelect: function(dateText){
var d = new Date(dateText),
dv = d.getFullYear().toString().pad(4)+'-'+(d.getMonth()+1).toString().pad(2)+'-'+d.getDate().toString().pad(2);
$(this).val(dv).trigger('change');
}
});
pad is a simple custom String method to pad strings with zeros (required)
In my case, I have given this attribute to the input tag
data-date-start-date="0d"
data-date-end-date="0d"
Most answers and explanations are not to explain what is a valid string of endDate
or startDate
.
Danny gave us two useful example.
$('#datepicker').datepicker({
startDate: '-2m',
endDate: '+2d'
});
But why?let's take a look at the source code at bootstrap-datetimepicker.js
.
There are some code begin line 1343 tell us how does it work.
if (/^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$/.test(date)) {
var part_re = /([-+]\d+)([dmwy])/,
parts = date.match(/([-+]\d+)([dmwy])/g),
part, dir;
date = new Date();
for (var i = 0; i < parts.length; i++) {
part = part_re.exec(parts[i]);
dir = parseInt(part[1]);
switch (part[2]) {
case 'd':
date.setUTCDate(date.getUTCDate() + dir);
break;
case 'm':
date = Datetimepicker.prototype.moveMonth.call(Datetimepicker.prototype, date, dir);
break;
case 'w':
date.setUTCDate(date.getUTCDate() + dir * 7);
break;
case 'y':
date = Datetimepicker.prototype.moveYear.call(Datetimepicker.prototype, date, dir);
break;
}
}
return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), 0);
}
There are four kinds of expressions.
w
means weekm
means monthy
means yeard
means dayLook at the regular expression ^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$
.
You can do more than these -0d
or +1m
.
Try harder like startDate:'+1y,-2m,+0d,-1w'
.And the separator ,
could be one of [\f\n\r\t\v,]
When you make the input, set it to be readonly.
<input type="text" name="datepicker" id="datepicker" readonly="readonly" />
$(function() {
$("#datepicker").datepicker({
//showOn: both - datepicker will come clicking the input box as well as the calendar icon
//showOn: button - datepicker will come only clicking the calendar icon
showOn: 'button',
//you can use your local path also eg. buttonImage: 'images/x_office_calendar.png'
buttonImage: 'http://theonlytutorials.com/demo/x_office_calendar.png',
buttonImageOnly: true,
changeMonth: true,
changeYear: true,
showAnim: 'slideDown',
duration: 'fast',
dateFormat: 'dd-mm-yy'
});
});
The above code belongs to this link
Twitter Bootstrap is incompatible with jQuery UI styles at the moment.
https://github.com/twitter/bootstrap/issues/156
This might help you https://github.com/sferik/rails_admin ( http://rails-admin-tb.herokuapp.com/admin/drafts/new )
if you are using ASP.NET MVC
Open the layout file "_Layout.cshtml" or your custom one
At the part of the code you see, as below:
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
@Scripts.Render("~/bundles/jquery")
Remove the line "@Scripts.Render("~/bundles/jquery")"
(at the part of the code you see) past as the latest line, as below:
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/jquery")
This help me and hope helps you as well.
$(document).ready(function(){
$("#dateFrom").datepicker({
todayBtn: 1,
autoclose: true,
}).on('changeDate', function (selected) {
var minDate = new Date(selected.date.valueOf());
$('#dateTo').datepicker('setStartDate', minDate);
});
$("#dateTo").datepicker({
todayBtn: 1,
autoclose: true,}) ;
});
I ran into the same problem and after a couple of hours of logging and investigating, I fixed it.
It turned out that for the first time the value is set in a date picker, $viewValue is a string so the dateFilter displays it as is. All I did is parse it into a Date object.
Search for that block in ui-bootstrap-tpls file
ngModel.$render = function() {
var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';
element.val(date);
updateCalendar();
};
and replace it by:
ngModel.$render = function() {
ngModel.$viewValue = new Date(ngModel.$viewValue);
var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';
element.val(date);
updateCalendar();
};
Hopefully this will help :)
I know you are using Datepicker, but for some people who are just using HTML5 input date like me, there is an example how you can do the same: JSFiddle Link
$('#start_date').change(function(){
var start_date = $(this).val();
$('#end_date').prop({
min: start_date
});
});
/* prop() method works since jquery 1.6, if you are using a previus version, you can use attr() method.*/
Use the "minDate" option to restrict the earliest allowed date. The value "0" means today (0 days from today):
$(document).ready(function () {
$("#txtdate").datepicker({
minDate: 0,
// ...
});
});
Docs here: http://api.jqueryui.com/datepicker/#option-minDate
beforeShow: function(el) {
if ( el.getAttribute("readonly") !== null ) {
if ( (el.value == null) || (el.value == '') ) {
$(el).datepicker( "option", "minDate", +1 );
$(el).datepicker( "option", "maxDate", -1 );
} else {
$(el).datepicker( "option", "minDate", el.value );
$(el).datepicker( "option", "maxDate", el.value );
}
}
},
This is my edited version : you just need to add an extra argument "autoClose".
example :
$('input[name="fieldName"]').datepicker({ autoClose: true});
also you can specify a close callback if you want. :)
replace datepicker.js with this:
!function( $ ) {
// Picker object
var Datepicker = function(element, options , closeCallBack){
this.element = $(element);
this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||'dd/mm/yyyy');
this.autoClose = options.autoClose||this.element.data('date-autoClose')|| true;
this.closeCallback = closeCallBack || function(){};
this.picker = $(DPGlobal.template)
.appendTo('body')
.on({
click: $.proxy(this.click, this)//,
//mousedown: $.proxy(this.mousedown, this)
});
this.isInput = this.element.is('input');
this.component = this.element.is('.date') ? this.element.find('.add-on') : false;
if (this.isInput) {
this.element.on({
focus: $.proxy(this.show, this),
//blur: $.proxy(this.hide, this),
keyup: $.proxy(this.update, this)
});
} else {
if (this.component){
this.component.on('click', $.proxy(this.show, this));
} else {
this.element.on('click', $.proxy(this.show, this));
}
}
this.minViewMode = options.minViewMode||this.element.data('date-minviewmode')||0;
if (typeof this.minViewMode === 'string') {
switch (this.minViewMode) {
case 'months':
this.minViewMode = 1;
break;
case 'years':
this.minViewMode = 2;
break;
default:
this.minViewMode = 0;
break;
}
}
this.viewMode = options.viewMode||this.element.data('date-viewmode')||0;
if (typeof this.viewMode === 'string') {
switch (this.viewMode) {
case 'months':
this.viewMode = 1;
break;
case 'years':
this.viewMode = 2;
break;
default:
this.viewMode = 0;
break;
}
}
this.startViewMode = this.viewMode;
this.weekStart = options.weekStart||this.element.data('date-weekstart')||0;
this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
this.onRender = options.onRender;
this.fillDow();
this.fillMonths();
this.update();
this.showMode();
};
Datepicker.prototype = {
constructor: Datepicker,
show: function(e) {
this.picker.show();
this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
this.place();
$(window).on('resize', $.proxy(this.place, this));
if (e ) {
e.stopPropagation();
e.preventDefault();
}
if (!this.isInput) {
}
var that = this;
$(document).on('mousedown', function(ev){
if ($(ev.target).closest('.datepicker').length == 0) {
that.hide();
}
});
this.element.trigger({
type: 'show',
date: this.date
});
},
hide: function(){
this.picker.hide();
$(window).off('resize', this.place);
this.viewMode = this.startViewMode;
this.showMode();
if (!this.isInput) {
$(document).off('mousedown', this.hide);
}
//this.set();
this.element.trigger({
type: 'hide',
date: this.date
});
},
set: function() {
var formated = DPGlobal.formatDate(this.date, this.format);
if (!this.isInput) {
if (this.component){
this.element.find('input').prop('value', formated);
}
this.element.data('date', formated);
} else {
this.element.prop('value', formated);
}
},
setValue: function(newDate) {
if (typeof newDate === 'string') {
this.date = DPGlobal.parseDate(newDate, this.format);
} else {
this.date = new Date(newDate);
}
this.set();
this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
this.fill();
},
place: function(){
var offset = this.component ? this.component.offset() : this.element.offset();
this.picker.css({
top: offset.top + this.height,
left: offset.left
});
},
update: function(newDate){
this.date = DPGlobal.parseDate(
typeof newDate === 'string' ? newDate : (this.isInput ? this.element.prop('value') : this.element.data('date')),
this.format
);
this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
this.fill();
},
fillDow: function(){
var dowCnt = this.weekStart;
var html = '<tr>';
while (dowCnt < this.weekStart + 7) {
html += '<th class="dow">'+DPGlobal.dates.daysMin[(dowCnt++)%7]+'</th>';
}
html += '</tr>';
this.picker.find('.datepicker-days thead').append(html);
},
fillMonths: function(){
var html = '';
var i = 0
while (i < 12) {
html += '<span class="month">'+DPGlobal.dates.monthsShort[i++]+'</span>';
}
this.picker.find('.datepicker-months td').append(html);
},
fill: function() {
var d = new Date(this.viewDate),
year = d.getFullYear(),
month = d.getMonth(),
currentDate = this.date.valueOf();
this.picker.find('.datepicker-days th:eq(1)')
.text(DPGlobal.dates.months[month]+' '+year);
var prevMonth = new Date(year, month-1, 28,0,0,0,0),
day = DPGlobal.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth());
prevMonth.setDate(day);
prevMonth.setDate(day - (prevMonth.getDay() - this.weekStart + 7)%7);
var nextMonth = new Date(prevMonth);
nextMonth.setDate(nextMonth.getDate() + 42);
nextMonth = nextMonth.valueOf();
var html = [];
var clsName,
prevY,
prevM;
while(prevMonth.valueOf() < nextMonth) {zs
if (prevMonth.getDay() === this.weekStart) {
html.push('<tr>');
}
clsName = this.onRender(prevMonth);
prevY = prevMonth.getFullYear();
prevM = prevMonth.getMonth();
if ((prevM < month && prevY === year) || prevY < year) {
clsName += ' old';
} else if ((prevM > month && prevY === year) || prevY > year) {
clsName += ' new';
}
if (prevMonth.valueOf() === currentDate) {
clsName += ' active';
}
html.push('<td class="day '+clsName+'">'+prevMonth.getDate() + '</td>');
if (prevMonth.getDay() === this.weekEnd) {
html.push('</tr>');
}
prevMonth.setDate(prevMonth.getDate()+1);
}
this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
var currentYear = this.date.getFullYear();
var months = this.picker.find('.datepicker-months')
.find('th:eq(1)')
.text(year)
.end()
.find('span').removeClass('active');
if (currentYear === year) {
months.eq(this.date.getMonth()).addClass('active');
}
html = '';
year = parseInt(year/10, 10) * 10;
var yearCont = this.picker.find('.datepicker-years')
.find('th:eq(1)')
.text(year + '-' + (year + 9))
.end()
.find('td');
year -= 1;
for (var i = -1; i < 11; i++) {
html += '<span class="year'+(i === -1 || i === 10 ? ' old' : '')+(currentYear === year ? ' active' : '')+'">'+year+'</span>';
year += 1;
}
yearCont.html(html);
},
click: function(e) {
e.stopPropagation();
e.preventDefault();
var target = $(e.target).closest('span, td, th');
if (target.length === 1) {
switch(target[0].nodeName.toLowerCase()) {
case 'th':
switch(target[0].className) {
case 'switch':
this.showMode(1);
break;
case 'prev':
case 'next':
this.viewDate['set'+DPGlobal.modes[this.viewMode].navFnc].call(
this.viewDate,
this.viewDate['get'+DPGlobal.modes[this.viewMode].navFnc].call(this.viewDate) +
DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1)
);
this.fill();
this.set();
break;
}
break;
case 'span':
if (target.is('.month')) {
var month = target.parent().find('span').index(target);
this.viewDate.setMonth(month);
} else {
var year = parseInt(target.text(), 10)||0;
this.viewDate.setFullYear(year);
}
if (this.viewMode !== 0) {
this.date = new Date(this.viewDate);
this.element.trigger({
type: 'changeDate',
date: this.date,
viewMode: DPGlobal.modes[this.viewMode].clsName
});
}
this.showMode(-1);
this.fill();
this.set();
break;
case 'td':
if (target.is('.day') && !target.is('.disabled')){
var day = parseInt(target.text(), 10)||1;
var month = this.viewDate.getMonth();
if (target.is('.old')) {
month -= 1;
} else if (target.is('.new')) {
month += 1;
}
var year = this.viewDate.getFullYear();
this.date = new Date(year, month, day,0,0,0,0);
this.viewDate = new Date(year, month, Math.min(28, day),0,0,0,0);
this.fill();
this.set();
this.element.trigger({
type: 'changeDate',
date: this.date,
viewMode: DPGlobal.modes[this.viewMode].clsName
});
if(this.autoClose === true){
this.hide();
this.closeCallback();
}
}
break;
}
}
},
mousedown: function(e){
e.stopPropagation();
e.preventDefault();
},
showMode: function(dir) {
if (dir) {
this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
}
this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
}
};
$.fn.datepicker = function ( option, val ) {
return this.each(function () {
var $this = $(this);
var datePicker = $this.data('datepicker');
var options = typeof option === 'object' && option;
if (!datePicker) {
if (typeof val === 'function')
$this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options),val)));
else{
$this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options))));
}
}
if (typeof option === 'string') datePicker[option](val);
});
};
$.fn.datepicker.defaults = {
onRender: function(date) {
return '';
}
};
$.fn.datepicker.Constructor = Datepicker;
var DPGlobal = {
modes: [
{
clsName: 'days',
navFnc: 'Month',
navStep: 1
},
{
clsName: 'months',
navFnc: 'FullYear',
navStep: 1
},
{
clsName: 'years',
navFnc: 'FullYear',
navStep: 10
}],
dates:{
days: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"],
daysShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"],
daysMin: ["D", "L", "Ma", "Me", "J", "V", "S", "D"],
months: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
monthsShort: ["Jan", "Fév", "Mar", "Avr", "Mai", "Jui", "Jul", "Aou", "Sep", "Oct", "Nov", "Déc"],
today: "Aujourd'hui",
clear: "Effacer",
weekStart: 1,
format: "dd/mm/yyyy"
},
isLeapYear: function (year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0))
},
getDaysInMonth: function (year, month) {
return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
},
parseFormat: function(format){
var separator = format.match(/[.\/\-\s].*?/),
parts = format.split(/\W+/);
if (!separator || !parts || parts.length === 0){
throw new Error("Invalid date format.");
}
return {separator: separator, parts: parts};
},
parseDate: function(date, format) {
var parts = date.split(format.separator),
date = new Date(),
val;
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
if (parts.length === format.parts.length) {
var year = date.getFullYear(), day = date.getDate(), month = date.getMonth();
for (var i=0, cnt = format.parts.length; i < cnt; i++) {
val = parseInt(parts[i], 10)||1;
switch(format.parts[i]) {
case 'dd':
case 'd':
day = val;
date.setDate(val);
break;
case 'mm':
case 'm':
month = val - 1;
date.setMonth(val - 1);
break;
case 'yy':
year = 2000 + val;
date.setFullYear(2000 + val);
break;
case 'yyyy':
year = val;
date.setFullYear(val);
break;
}
}
date = new Date(year, month, day, 0 ,0 ,0);
}
return date;
},
formatDate: function(date, format){
var val = {
d: date.getDate(),
m: date.getMonth() + 1,
yy: date.getFullYear().toString().substring(2),
yyyy: date.getFullYear()
};
val.dd = (val.d < 10 ? '0' : '') + val.d;
val.mm = (val.m < 10 ? '0' : '') + val.m;
var date = [];
for (var i=0, cnt = format.parts.length; i < cnt; i++) {
date.push(val[format.parts[i]]);
}
return date.join(format.separator);
},
headTemplate: '<thead>'+
'<tr>'+
'<th class="prev">‹</th>'+
'<th colspan="5" class="switch"></th>'+
'<th class="next">›</th>'+
'</tr>'+
'</thead>',
contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>'
};
DPGlobal.template = '<div class="datepicker dropdown-menu">'+
'<div class="datepicker-days">'+
'<table class=" table-condensed">'+
DPGlobal.headTemplate+
'<tbody></tbody>'+
'</table>'+
'</div>'+
'<div class="datepicker-months">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-years">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
'</table>'+
'</div>'+
'</div>';
}( window.jQuery );
$("#txtfromdate").datepicker({
numberOfMonths: 2,
maxDate: 0,
dateFormat: 'dd-M-yy'
}).attr('readonly', 'readonly');
add the readonly attribute in the jquery.
@David, thanks for the recommendation! @fluid_chelsea, I've just released Any+Time(TM) version 3.x which uses jQuery instead of Prototype and has a much-improved interface, so I hope it now meets your needs:
Any problems, please let me know via the comment link on my website!
what about that simple way)
$(document).ready ->
$('#datepicker').datepicker( dateFormat: 'yy-mm-dd', onSelect: (dateStr) ->
alert dateStr # yy-mm-dd
#OR
alert $("#datepicker").val(); # yy-mm-dd
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();
});
See http://www.eyecon.ro/bootstrap-datepicker/
$('.datepicker').datepicker({
format: 'dd/mm/yyyy'
});
To summarize the date inputs problem:
The solution I found to meet those requirements is to use the usual trick to style native form elements : ensure the element is displayed but not visible, and display its expected style through its associated label. Typically, the label will display as the input (including a placeholder), but over it.
So, an HTML like:
<div class="date-input>
<input id="myInput" type="date">
<label for="myInput">
<span class="place-holder">Enter a date</span>
</label>
</div>
Could be styled as:
.date-input {
display: inline-block;
position: relative;
}
/* Fields overriding */
input[type=date] + label {
position: absolute; /* Same origin as the input, to display over it */
background: white; /* Opaque background to hide the input behind */
left: 0; /* Start at same x coordinate */
}
/* Common input styling */
input[type=date], label {
/* Must share same size to display properly (focus, etc.) */
width: 15em;
height: 1em;
font-size: 1em;
}
Any event (click, focus) on such an associated label will be reflected on the field itself, and so trigger the date input UI.
Should you want to test such a solution live, you can run this Angular version from your tablet or mobile.
Make sure you put multiple properties in the same line (since you only showed 1 line of code, you may have had the same problem I did).
Mine would set the default date, but didn't gray out old dates. This doesn't work:
$('#date_end').datepicker({ defaultDate: +31 })
$('#date_end').datepicker({ minDate: 1 })
This does both:
$('#date_end').datepicker({ defaultDate: +31, minDate: 1 })
1 and +1 work the same (or 0 and +0 in your case).
Me: Windows 7 x64, Rails 3.2.3, Ruby 1.9.3
I would suggest you to checkout https://vlio20.github.io/angular-datepicker/
Just posting because the root cause for my case has not been described her.
In my case the problem was that "assets/js/fuelux/treeview/fuelux.min.js" was adding a constructor .datepicker(), so that was overriding the assets/js/datetime/bootstrap-datepicker.js
just moving the
to be just before the $('.date-picker') solved my problem.
$('.date-picker').datepicker({
autoclose : true,
todayHighlight : true,
clearBtn: true,
format: 'yyyy-mm-dd',
onSelect: function(value, date) {
alert(123);
},
todayBtn: "linked",
startView: 0, maxViewMode: 0,minViewMode:0
}).on('changeDate',function(ev){
//this is right events ,trust me
}
});
I got a perfect solution:
$('#Date_of_Birth').datepicker().on('changeDate', function (e) {
if(e.viewMode === 'days')
$(this).blur();
});
au, nz, ie, etc. are the country codes for the countries whose national days are being displayed (Australia, New Zealand, Ireland, ...). As seen in the code, these values are combined with '_day' and passed back to be applied to that day as a CSS style. The corresponding styles are of the form show below, which moves the text for that day out of the way and replaces it with an image of the country's flag.
.au_day {
text-indent: -9999px;
background: #eee url(au.gif) no-repeat center;
}
The 'false' value that is passed back with the new style indicates that these days may not be selected.
$('.date-pick').datePicker().val(new Date()).trigger('change')
finally, that what i look for the last few hours! I need initiate changes, not just setup date in text field!
you mean that you want to add DatePicker widget into your apps.
Global variable declaration into your activity class:
private Button mPickDate;
private int mYear;
private int mMonth;
private int mDay;
static final int DATE_DIALOG_ID = 0;
write down this code into onCreate() function:
//date picker presentation
mPickDate = (Button) findViewById(R.id.pickDate);//button for showing date picker dialog
mPickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { showDialog(DATE_DIALOG_ID); }
});
// get the current date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// display the current date
updateDisplay();
write down those function outside of onCreate() function:
//return date picker dialog
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
}
return null;
}
//update month day year
private void updateDisplay() {
mBodyText.setText(//this is the edit text where you want to show the selected date
new StringBuilder()
// Month is 0 based so add 1
.append(mYear).append("-")
.append(mMonth + 1).append("-")
.append(mDay).append(""));
//.append(mMonth + 1).append("-")
//.append(mDay).append("-")
//.append(mYear).append(" "));
}
// the call back received when the user "sets" the date in the dialog
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDisplay();
}
};
I found a short solution for it.
No extra code is needed just trigger the changeDate event. E.g.
$('.datepicker').datepicker().trigger('changeDate');
$('#scheduleDate').datepicker({ dateFormat : 'dd, MM, yy'});
var dateFormat = $('#scheduleDate').datepicker('option', 'dd, MM, yy');
$('#scheduleDate').datepicker('option', 'dateFormat', 'dd, MM, yy');
var result = $('#scheduleDate').val();
alert('result: ' + result);
result: 20, April, 2012
According to http://www.daterangepicker.com/ (options)
$('#dispatch_modal').on('shown.bs.modal', function() {
$('input:text:visible:first').focus();
// prepare datepicker
$('.form_datepicker').daterangepicker({
singleDatePicker: true,
showDropdowns: true,
parentEl: '#dispatch_modal'
});
});
`
parentEl solved my problem...
Change
dateFormat: 'dd/mm/yyyy'
to
format: 'dd/mm/yyyy'
Looks like you just misread some documentation!
$(".datepicker").datepicker().on("changeDate", function(e) {
console.log("Date changed: ", e.date);
});
To get rid of the bad looking datepicker you need to add jquery-ui css
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css">
interesting, datepicker default date is current date as I found,
but you can set date by
$("#yourinput").datepicker( "setDate" , "7/11/2011" );
don't forget to check you system date :)
The datepicker('setDate') sets the date in the datepicket not in the input.
You should add the date and set it in the input.
var date2 = $('.pickupDate').datepicker('getDate');
var nextDayDate = new Date();
nextDayDate.setDate(date2.getDate() + 1);
$('input').val(nextDayDate);
You can use the datepicker's onSelect
event.
$(".date").datepicker({
onSelect: function(dateText) {
console.log("Selected date: " + dateText + "; input's current value: " + this.value);
}
});
Live example:
$(".date")_x000D_
.datepicker({_x000D_
onSelect: function(dateText) {_x000D_
console.log("Selected date: " + dateText + "; input's current value: " + this.value);_x000D_
}_x000D_
})_x000D_
.on("change", function() {_x000D_
console.log("Got change event from field");_x000D_
});
_x000D_
<link href="http://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />_x000D_
<input type='text' class='date'>_x000D_
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>_x000D_
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
_x000D_
Unfortunately, onSelect
fires whenever a date is selected, even if it hasn't changed. This is a design flaw in the datepicker: It always fires onSelect
(even if nothing changed), and doesn't fire any event on the underlying input on change. (If you look in the code of that example, we're listening for changes, but they aren't being raised.) It should probably fire an event on the input when things change (possibly the usual change
event, or possibly a datepicker-specific one).
If you like, of course, you can make the change
event on the input
fire:
$(".date").datepicker({
onSelect: function() {
$(this).change();
}
});
That will fire change
on the underlying input
for any handler hooked up via jQuery. But again, it always fires it. If you want to only fire on a real change, you'll have to save the previous value (possibly via data
) and compare.
Live example:
$(".date")_x000D_
.datepicker({_x000D_
onSelect: function(dateText) {_x000D_
console.log("Selected date: " + dateText + "; input's current value: " + this.value);_x000D_
$(this).change();_x000D_
}_x000D_
})_x000D_
.on("change", function() {_x000D_
console.log("Got change event from field");_x000D_
});
_x000D_
<link href="http://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />_x000D_
<input type='text' class='date'>_x000D_
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>_x000D_
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
_x000D_
If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:
The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.
FYI, I needed to update the color of the calendar icon which didn't seem possible with properties like color
, fill
, etc.
I did eventually figure out that some filter
properties will adjust the icon so while i did not end up figuring out how to make it any color, luckily all I needed was to make it so the icon was visible on a dark background so I was able to do the following:
body { background: black; }_x000D_
_x000D_
input[type="date"] { _x000D_
background: transparent;_x000D_
color: white;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-calendar-picker-indicator {_x000D_
filter: invert(100%);_x000D_
}
_x000D_
<body>_x000D_
<input type="date" />_x000D_
</body>
_x000D_
Hopefully this helps some people as for the most part chrome even directly says this is impossible.
From what I've read on Mozilla's JS pages, getYear is deprecated. As pointed out many times, getFullYear()
is the way to go. If you're really wanting to use getYear()
add 1900 to it.
var now = new Date(),
year = now.getYear() + 1900;
I also use Stefan Petre’s http://www.eyecon.ro/bootstrap-datepicker and it does not work with Bootstrap 3 without modification. Note that http://eternicode.github.io/bootstrap-datepicker/ is a fork of Stefan Petre's code.
You have to change your markup (the sample markup will not work) to use the new CSS and form grid layout in Bootstrap 3. Also, you have to modify some CSS and JavaScript in the actual bootstrap-datepicker implementation.
Here is my solution:
<div class="form-group row">
<div class="col-xs-8">
<label class="control-label">My Label</label>
<div class="input-group date" id="dp3" data-date="12-02-2012" data-date-format="mm-dd-yyyy">
<input class="form-control" type="text" readonly="" value="12-02-2012">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
</div>
</div>
</div>
CSS changes in datepicker.css on lines 176-177:
.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {
Javascript change in datepicker-bootstrap.js on line 34:
this.component = this.element.is('.date') ? this.element.find('.input-group-addon') : false;
UPDATE
Using the newer code from http://eternicode.github.io/bootstrap-datepicker/ the changes are as follows:
CSS changes in datepicker.css on lines 446-447:
.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {
Javascript change in datepicker-bootstrap.js on line 46:
this.component = this.element.is('.date') ? this.element.find('.input-group-addon, .btn') : false;
Finally, the JavaScript to enable the datepicker (with some options):
$(".input-group.date").datepicker({ autoclose: true, todayHighlight: true });
Tested with Bootstrap 3.0 and JQuery 1.9.1. Note that this fork is better to use than the other as it is more feature rich, has localization support and auto-positions the datepicker based on the control position and window size, avoiding the picker going off the screen which was a problem with the older version.
In my case, it was solved by changing the import order of the following scripts: Before (Not work):
After (Working):
I believe you have to reference bootstrap.js before bootstrap-datepicker.js
Can't figure out why, but in some circumstances if you have bound DataTimePicker and BindingSource contol is postioned to a new record, setting to Value property doesn't affect to bound field, so when you try to commit changes via EndEdit() method of BindingSource, you receive Null value doesn't allowed error. I managed this problem setting direct DataRow field.
Use this plugin http://multidatespickr.sourceforge.net
<?php
if (isset($_POST['birthdate'])) {
$timestamp = strtotime($_POST['birthdate']);
$date=date('d',$timestamp);
$month=date('m',$timestamp);
$year=date('Y',$timestamp);
}
?>
I found the best anwser, it work for me. Clear the value of bootstrap-datepicker:
$('#datepicker').datepicker('setDate', null);
Add value for boostrap-datepicker:
$('#datepicker').datepicker('setDate', datePicker);
For the first case you propose you can use: '[[:blank:]]+[A-Z0-9]+[[:blank:]]+', for example:
echo "The thing P1 must connect to the J236 thing in the Foo position" | grep -oE '[[:blank:]]+[A-Z0-9]+[[:blank:]]+'
In the second case maybe you need to use something else and not a regex, maybe a script with a dictionary of technical words...
Cheers, Fernando
That depends on what you want to do, but as you said, getting an entity reference using find()
and then just updating that entity is the easiest way to do that.
I'd not bother about performance differences of the various methods unless you have strong indications that this really matters.
Move files with filter( using Path, os,shutil modules):
from pathlib import Path
import shutil
import os
src_path ='/media/shakil/New Volume/python/src'
trg_path ='/media/shakil/New Volume/python/trg'
for src_file in Path(src_path).glob('*.txt*'):
shutil.move(os.path.join(src_path,src_file),trg_path)
Quick answer : Add proxy configuration with parameter for both install/update
gem install --http-proxy http://host:port/ package_name
gem update --http-proxy http://host:port/ package_name
EDIT 2017-04-29: As pointed to by some of the commenters, the JoinTable
example does not need the mappedBy
annotation attribute. In fact, recent versions of Hibernate refuse to start up by printing the following error:
org.hibernate.AnnotationException:
Associations marked as mappedBy must not define database mappings
like @JoinTable or @JoinColumn
Let's pretend that you have an entity named Project
and another entity named Task
and each project can have many tasks.
You can design the database schema for this scenario in two ways.
The first solution is to create a table named Project
and another table named Task
and add a foreign key column to the task table named project_id
:
Project Task
------- ----
id id
name name
project_id
This way, it will be possible to determine the project for each row in the task table. If you use this approach, in your entity classes you won't need a join table:
@Entity
public class Project {
@OneToMany(mappedBy = "project")
private Collection<Task> tasks;
}
@Entity
public class Task {
@ManyToOne
private Project project;
}
The other solution is to use a third table, e.g. Project_Tasks
, and store the relationship between projects and tasks in that table:
Project Task Project_Tasks
------- ---- -------------
id id project_id
name name task_id
The Project_Tasks
table is called a "Join Table". To implement this second solution in JPA you need to use the @JoinTable
annotation. For example, in order to implement a uni-directional one-to-many association, we can define our entities as such:
Project
entity:
@Entity
public class Project {
@Id
@GeneratedValue
private Long pid;
private String name;
@JoinTable
@OneToMany
private List<Task> tasks;
public Long getPid() {
return pid;
}
public void setPid(Long pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Task> getTasks() {
return tasks;
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
}
Task
entity:
@Entity
public class Task {
@Id
@GeneratedValue
private Long tid;
private String name;
public Long getTid() {
return tid;
}
public void setTid(Long tid) {
this.tid = tid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
This will create the following database structure:
The @JoinTable
annotation also lets you customize various aspects of the join table. For example, had we annotated the tasks
property like this:
@JoinTable(
name = "MY_JT",
joinColumns = @JoinColumn(
name = "PROJ_ID",
referencedColumnName = "PID"
),
inverseJoinColumns = @JoinColumn(
name = "TASK_ID",
referencedColumnName = "TID"
)
)
@OneToMany
private List<Task> tasks;
The resulting database would have become:
Finally, if you want to create a schema for a many-to-many association, using a join table is the only available solution.
calculate the height of each link no do this
document.getElementById("products").style.height= height_of_each_link* no_of_link
For formatting the price in another currency than the current one:
Mage::app()->getLocale()->currency('EUR')->toCurrency($price);
You can download a library from http://json.org (Json-lib or org.json) and use it to parse/generate the JSON
I'm surprised that a lot of you seem to want to save files on the server. Solution to keep everything in memory is as follows:
[HttpPost("api/upload")]
public async Task<IHttpActionResult> Upload()
{
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var file in provider.Contents)
{
var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
var buffer = await file.ReadAsByteArrayAsync();
//Do whatever you want with filename and its binary data.
}
return Ok();
}
In Sql Server 2008 R2 database files you can connect with
Server=np:\\.\pipe\YourInstance\tsql\query;InitialCatalog=yourDataBase;Trusted_Connection=True;
only, but in sql Server 2012 you can use this:
Server=(localdb)\v11.0;Integrated Security=true;Database=DB1;
and it depended on your .mdf
.ldf
version.
for finding programmicaly i use this Method that explained in this post
List(1,2,3) :+ 4
Results in List[Int] = List(1, 2, 3, 4)
Note that this operation has a complexity of O(n). If you need this operation frequently, or for long lists, consider using another data type (e.g. a ListBuffer).
Multiple normal white space characters (space, tabulator and line break) are treated as one single white space character:
For all HTML elements except
PRE
, sequences of white space separate "words" (we use the term "word" here to mean "sequences of non-white space characters"). When formatting text, user agents should identify these words and lay them out according to the conventions of the particular written language (script) and target medium.
So
foo bar
is displayed as
foo bar
But no-break space is always displayed. So
foo&?nbsp;&?nbsp;&?nbsp;bar
is displayed as
foo bar
Background: Some answers suggested on this page (e.g., signif
, options(digits=...)
) do not guarantee that a certain number of decimals are displayed for an arbitrary number. I presume this is a design feature in R whereby good scientific practice involves showing a certain number of digits based on principles of "significant figures". However, in many domains (e.g., APA style, business reports) formatting requirements dictate that a certain number of decimal places are displayed. This is often done for consistency and standardisation purposes rather than being concerned with significant figures.
Solution:
The following code shows exactly two decimal places for the number x
.
format(round(x, 2), nsmall = 2)
For example:
format(round(1.20, 2), nsmall = 2)
# [1] "1.20"
format(round(1, 2), nsmall = 2)
# [1] "1.00"
format(round(1.1234, 2), nsmall = 2)
# [1] "1.12"
A more general function is as follows where x
is the number and k
is the number of decimals to show. trimws
removes any leading white space which can be useful if you have a vector of numbers.
specify_decimal <- function(x, k) trimws(format(round(x, k), nsmall=k))
E.g.,
specify_decimal(1234, 5)
# [1] "1234.00000"
specify_decimal(0.1234, 5)
# [1] "0.12340"
I was also having the same issue, and just now i got it solved. Please try the bellow steps to get it solved:
;extension=php_intl.dll
From
Xampp folder/php
To
Xampp folder/apache/bin
For windows 7 32 bit it is - C:\Windows\System32
Here are the steps to move a private Git repository:
Step 1: Create Github repository
First, create a new private repository on Github.com. It’s important to keep the repository empty, e.g. don’t check option Initialize this repository with a README when creating the repository.
Step 2: Move existing content
Next, we need to fill the Github repository with the content from our Bitbucket repository:
$ git clone https://[email protected]/USER/PROJECT.git
$ cd PROJECT
$ git remote add upstream https://github.com:USER/PROJECT.git
$ git push upstream master
$ git push --tags upstream
Step 3: Clean up old repository
Finally, we need to ensure that developers don’t get confused by having two repositories for the same project. Here is how to delete the Bitbucket repository:
Double-check that the Github repository has all content
Go to the web interface of the old Bitbucket repository
Select menu option Setting > Delete repository
Add the URL of the new Github repository as redirect URL
With that, the repository completely settled into its new home at Github. Let all the developers know!
Type:
pip install pygame
Here is an example:
C:\Users\user\AppData\Local\Programs\Python\Python36-32\Scripts>pip install pygame
There are apparently distributions or custom builds in which the ability to set Task Tags for non-Java files is not present. This post mentions that ColdFusion Builder (built on Eclipse) does not let you set non-Java Task Tags, but the beta version of CF Builder 2 does. (I know the OP wasn't using CF Builder, but I am, and I was wondering about this question myself ... because he didn't see the ability to set non-Java tags, I thought others might be in the same position.)
To solve this issue on my side, I had to use a combo of what was already proposed there
DECLARE
chunk1 CLOB; chunk2 CLOB; chunk3 CLOB;
BEGIN
chunk1 := 'very long literal part 1';
chunk2 := 'very long literal part 2';
chunk3 := 'very long literal part 3';
INSERT INTO table (MY_CLOB)
SELECT ( chunk1 || chunk2 || chunk3 ) FROM dual;
END;
Hope this helps.
There is something wrong with the accepted answer, it sometimes (randomly) brings a clipped response from server. I do not know why, I did not investigate the faulty cause of the accepted answer because this code worked perfectly for me:
import paramiko
ip='server ip'
port=22
username='username'
password='password'
cmd='some useful command'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)
stdin,stdout,stderr=ssh.exec_command(cmd)
outlines=stdout.readlines()
resp=''.join(outlines)
print(resp)
stdin,stdout,stderr=ssh.exec_command('some really useful command')
outlines=stdout.readlines()
resp=''.join(outlines)
print(resp)
It depends on the context, but here's an example of "-and" in action:
get-childitem | where-object { $_.Name.StartsWith("f") -and $_.Length -gt 10kb }
So that's getting all the files bigger than 10kb in a directory whose filename starts with "f".
Have a look at using something like
Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-sensitive. The return value indicates whether the conversion succeeded.
or
Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
Not having enough reputations, apparently I can not comment on Alexander's excellent link. - Lucene appears to be the only solution working in reasonably generic cases.
For those wanting a simple copy-paste solution, here it is, leveraging code in Lucene:
string testbed = "ÁÂÄÅÇÉÍÎÓÖØÚÜÞàáâãäåæçèéêëìíîïðñóôöøúüaacÐegiLlnOorSsšzž????";
Console.WriteLine(Lucene.latinizeLucene(testbed));
AAAACEIIOOOUUTHaaaaaaaeceeeeiiiidnoooouuaacDegiLlnOorSsszzsteu
//////////
public static class Lucene
{
// source: https://raw.githubusercontent.com/apache/lucenenet/master/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/ASCIIFoldingFilter.cs
// idea: https://stackoverflow.com/questions/249087/how-do-i-remove-diacritics-accents-from-a-string-in-net (scroll down, search for lucene by Alexander)
public static string latinizeLucene(string arg)
{
char[] argChar = arg.ToCharArray();
// latinizeLuceneImpl can expand one char up to four chars - e.g. Þ to TH, or æ to ae, or in fact ? to (10)
char[] resultChar = new String(' ', arg.Length * 4).ToCharArray();
int outputPos = Lucene.latinizeLuceneImpl(argChar, 0, ref resultChar, 0, arg.Length);
string ret = new string(resultChar);
ret = ret.Substring(0, outputPos);
return ret;
}
/// <summary>
/// Converts characters above ASCII to their ASCII equivalents. For example,
/// accents are removed from accented characters.
/// <para/>
/// @lucene.internal
/// </summary>
/// <param name="input"> The characters to fold </param>
/// <param name="inputPos"> Index of the first character to fold </param>
/// <param name="output"> The result of the folding. Should be of size >= <c>length * 4</c>. </param>
/// <param name="outputPos"> Index of output where to put the result of the folding </param>
/// <param name="length"> The number of characters to fold </param>
/// <returns> length of output </returns>
private static int latinizeLuceneImpl(char[] input, int inputPos, ref char[] output, int outputPos, int length)
{
int end = inputPos + length;
for (int pos = inputPos; pos < end; ++pos)
{
char c = input[pos];
// Quick test: if it's not in range then just keep current character
if (c < '\u0080')
{
output[outputPos++] = c;
}
else
{
switch (c)
{
case '\u00C0': // À [LATIN CAPITAL LETTER A WITH GRAVE]
case '\u00C1': // Á [LATIN CAPITAL LETTER A WITH ACUTE]
case '\u00C2': // Â [LATIN CAPITAL LETTER A WITH CIRCUMFLEX]
case '\u00C3': // Ã [LATIN CAPITAL LETTER A WITH TILDE]
case '\u00C4': // Ä [LATIN CAPITAL LETTER A WITH DIAERESIS]
case '\u00C5': // Å [LATIN CAPITAL LETTER A WITH RING ABOVE]
case '\u0100': // A [LATIN CAPITAL LETTER A WITH MACRON]
case '\u0102': // A [LATIN CAPITAL LETTER A WITH BREVE]
case '\u0104': // A [LATIN CAPITAL LETTER A WITH OGONEK]
case '\u018F': // ? http://en.wikipedia.org/wiki/Schwa [LATIN CAPITAL LETTER SCHWA]
case '\u01CD': // A [LATIN CAPITAL LETTER A WITH CARON]
case '\u01DE': // A [LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON]
case '\u01E0': // ? [LATIN CAPITAL LETTER A WITH DOT ABOVE AND MACRON]
case '\u01FA': // ? [LATIN CAPITAL LETTER A WITH RING ABOVE AND ACUTE]
case '\u0200': // ? [LATIN CAPITAL LETTER A WITH DOUBLE GRAVE]
case '\u0202': // ? [LATIN CAPITAL LETTER A WITH INVERTED BREVE]
case '\u0226': // ? [LATIN CAPITAL LETTER A WITH DOT ABOVE]
case '\u023A': // ? [LATIN CAPITAL LETTER A WITH STROKE]
case '\u1D00': // ? [LATIN LETTER SMALL CAPITAL A]
case '\u1E00': // ? [LATIN CAPITAL LETTER A WITH RING BELOW]
case '\u1EA0': // ? [LATIN CAPITAL LETTER A WITH DOT BELOW]
case '\u1EA2': // ? [LATIN CAPITAL LETTER A WITH HOOK ABOVE]
case '\u1EA4': // ? [LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND ACUTE]
case '\u1EA6': // ? [LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND GRAVE]
case '\u1EA8': // ? [LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE]
case '\u1EAA': // ? [LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND TILDE]
case '\u1EAC': // ? [LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND DOT BELOW]
case '\u1EAE': // ? [LATIN CAPITAL LETTER A WITH BREVE AND ACUTE]
case '\u1EB0': // ? [LATIN CAPITAL LETTER A WITH BREVE AND GRAVE]
case '\u1EB2': // ? [LATIN CAPITAL LETTER A WITH BREVE AND HOOK ABOVE]
case '\u1EB4': // ? [LATIN CAPITAL LETTER A WITH BREVE AND TILDE]
case '\u1EB6': // ? [LATIN CAPITAL LETTER A WITH BREVE AND DOT BELOW]
case '\u24B6': // ? [CIRCLED LATIN CAPITAL LETTER A]
case '\uFF21': // A [FULLWIDTH LATIN CAPITAL LETTER A]
output[outputPos++] = 'A';
break;
case '\u00E0': // à [LATIN SMALL LETTER A WITH GRAVE]
case '\u00E1': // á [LATIN SMALL LETTER A WITH ACUTE]
case '\u00E2': // â [LATIN SMALL LETTER A WITH CIRCUMFLEX]
case '\u00E3': // ã [LATIN SMALL LETTER A WITH TILDE]
case '\u00E4': // ä [LATIN SMALL LETTER A WITH DIAERESIS]
case '\u00E5': // å [LATIN SMALL LETTER A WITH RING ABOVE]
case '\u0101': // a [LATIN SMALL LETTER A WITH MACRON]
case '\u0103': // a [LATIN SMALL LETTER A WITH BREVE]
case '\u0105': // a [LATIN SMALL LETTER A WITH OGONEK]
case '\u01CE': // a [LATIN SMALL LETTER A WITH CARON]
case '\u01DF': // a [LATIN SMALL LETTER A WITH DIAERESIS AND MACRON]
case '\u01E1': // ? [LATIN SMALL LETTER A WITH DOT ABOVE AND MACRON]
case '\u01FB': // ? [LATIN SMALL LETTER A WITH RING ABOVE AND ACUTE]
case '\u0201': // ? [LATIN SMALL LETTER A WITH DOUBLE GRAVE]
case '\u0203': // ? [LATIN SMALL LETTER A WITH INVERTED BREVE]
case '\u0227': // ? [LATIN SMALL LETTER A WITH DOT ABOVE]
case '\u0250': // ? [LATIN SMALL LETTER TURNED A]
case '\u0259': // ? [LATIN SMALL LETTER SCHWA]
case '\u025A': // ? [LATIN SMALL LETTER SCHWA WITH HOOK]
case '\u1D8F': // ? [LATIN SMALL LETTER A WITH RETROFLEX HOOK]
case '\u1D95': // ? [LATIN SMALL LETTER SCHWA WITH RETROFLEX HOOK]
case '\u1E01': // ? [LATIN SMALL LETTER A WITH RING BELOW]
case '\u1E9A': // ? [LATIN SMALL LETTER A WITH RIGHT HALF RING]
case '\u1EA1': // ? [LATIN SMALL LETTER A WITH DOT BELOW]
case '\u1EA3': // ? [LATIN SMALL LETTER A WITH HOOK ABOVE]
case '\u1EA5': // ? [LATIN SMALL LETTER A WITH CIRCUMFLEX AND ACUTE]
case '\u1EA7': // ? [LATIN SMALL LETTER A WITH CIRCUMFLEX AND GRAVE]
case '\u1EA9': // ? [LATIN SMALL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE]
case '\u1EAB': // ? [LATIN SMALL LETTER A WITH CIRCUMFLEX AND TILDE]
case '\u1EAD': // ? [LATIN SMALL LETTER A WITH CIRCUMFLEX AND DOT BELOW]
case '\u1EAF': // ? [LATIN SMALL LETTER A WITH BREVE AND ACUTE]
case '\u1EB1': // ? [LATIN SMALL LETTER A WITH BREVE AND GRAVE]
case '\u1EB3': // ? [LATIN SMALL LETTER A WITH BREVE AND HOOK ABOVE]
case '\u1EB5': // ? [LATIN SMALL LETTER A WITH BREVE AND TILDE]
case '\u1EB7': // ? [LATIN SMALL LETTER A WITH BREVE AND DOT BELOW]
case '\u2090': // ? [LATIN SUBSCRIPT SMALL LETTER A]
case '\u2094': // ? [LATIN SUBSCRIPT SMALL LETTER SCHWA]
case '\u24D0': // ? [CIRCLED LATIN SMALL LETTER A]
case '\u2C65': // ? [LATIN SMALL LETTER A WITH STROKE]
case '\u2C6F': // ? [LATIN CAPITAL LETTER TURNED A]
case '\uFF41': // a [FULLWIDTH LATIN SMALL LETTER A]
output[outputPos++] = 'a';
break;
case '\uA732': // ? [LATIN CAPITAL LETTER AA]
output[outputPos++] = 'A';
output[outputPos++] = 'A';
break;
case '\u00C6': // Æ [LATIN CAPITAL LETTER AE]
case '\u01E2': // ? [LATIN CAPITAL LETTER AE WITH MACRON]
case '\u01FC': // ? [LATIN CAPITAL LETTER AE WITH ACUTE]
case '\u1D01': // ? [LATIN LETTER SMALL CAPITAL AE]
output[outputPos++] = 'A';
output[outputPos++] = 'E';
break;
case '\uA734': // ? [LATIN CAPITAL LETTER AO]
output[outputPos++] = 'A';
output[outputPos++] = 'O';
break;
case '\uA736': // ? [LATIN CAPITAL LETTER AU]
output[outputPos++] = 'A';
output[outputPos++] = 'U';
break;
// etc. etc. etc.
// see link above for complete source code
//
// unfortunately, postings are limited, as in
// "Body is limited to 30000 characters; you entered 136098."
[...]
case '\u2053': // ? [SWUNG DASH]
case '\uFF5E': // ~ [FULLWIDTH TILDE]
output[outputPos++] = '~';
break;
default:
output[outputPos++] = c;
break;
}
}
}
return outputPos;
}
}
I made use of sendkeys in shell scripting using a vbsscript file. Below is the code in vbs file,
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.SendKeys "C:\Demo.txt"
WshShell.SendKeys "{ENTER}"
Below is the selenium code line to run this vbs file,
driver.findElement(By.id("uploadname1")).click();
Thread.sleep(1000);
Runtime.getRuntime().exec( "wscript C:/script.vbs" );
There is problem with the input.nextInt() method - it only reads the int value.
So when reading the next line using input.nextLine() you receive "\n", i.e. the Enter key. So to skip this you have to add the input.nextLine().
Try it like that:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (it consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
The code you've posted has two problems:
First: <input type="buttom"
should be <input type="button"...
. This probably is just a typo but without button
your input will be treated as type="text"
as the default input type is text
.
Second: In your function f()
definition, you are using the form
parameter thinking it's already a jQuery
object by using form.attr("action")
. Then similarly in the $.post
method call, you're passing fname
and lname
which are HTMLInputElement
s. I believe what you want is form's action url and input element's values.
Try with the following changes:
HTML
<form action="/echo/json/" method="post">
<input type="text" name="lname" />
<input type="text" name="fname" />
<!-- change "buttom" to "button" -->
<input type="button" name="send" onclick="return f(this.form ,this.form.fname ,this.form.lname) " />
</form>
JavaScript
function f(form, fname, lname) {
att = form.action; // Use form.action
$.post(att, {
fname: fname.value, // Use fname.value
lname: lname.value // Use lname.value
}).done(function (data) {
alert(data);
});
return true;
}
git rm
will remove the file from the index and working directory ( only index if you used --cached
) so that the deletion is staged for next commit.
Try this:
if cookie and not cookie.isspace():
# the string is non-empty
else:
# the string is empty
The above takes in consideration the cases where the string is None
or a sequence of white spaces.
Just thought I'd add that you can do this in Chrome as well:
Ctrl + Shift + I (Developer Tools) > Sources> Event Listener Breakpoints (on the right).
You can also view all events that have already been attached by simply right clicking on the element and then browsing its properties (the panel on the right).
For example:
Not sure if it's quite as powerful as the firebug option, but has been enough for most of my stuff.
Another option that is a bit different but surprisingly awesome is Visual Event: http://www.sprymedia.co.uk/article/Visual+Event+2
It highlights all of the elements on a page that have been bound and has popovers showing the functions that are called. Pretty nifty for a bookmark! There's a Chrome plugin as well if that's more your thing - not sure about other browsers.
AnonymousAndrew has also pointed out monitorEvents(window);
here
First, I don't understand why you are adding all the keys and values count times, Index is never used.
I tried this example :
var source = new BindingSource();
List<MyStruct> list = new List<MyStruct> { new MyStruct("fff", "b"), new MyStruct("c","d") };
source.DataSource = list;
grid.DataSource = source;
and that work pretty well, I get two columns with the correct names. MyStruct type exposes properties that the binding mechanism can use.
class MyStruct
{
public string Name { get; set; }
public string Adres { get; set; }
public MyStruct(string name, string adress)
{
Name = name;
Adres = adress;
}
}
Try to build a type that takes one key and value, and add it one by one. Hope this helps.
[data-value] {
/* Attribute exists */
}
[data-value="foo"] {
/* Attribute has this exact value */
}
[data-value*="foo"] {
/* Attribute value contains this value somewhere in it */
}
[data-value~="foo"] {
/* Attribute has this value in a space-separated list somewhere */
}
[data-value^="foo"] {
/* Attribute value starts with this */
}
[data-value|="foo"] {
/* Attribute value starts with this in a dash-separated list */
}
[data-value$="foo"] {
/* Attribute value ends with this */
}
I had a similar problem with programmatically setting layout_gravity on buttons in a GridLayout.
The trick was to set gravity on the button layoutParams AFTER the button was added to a parent (GridLayout), otherwise the gravity would be ignored.
grid.addView(button)
((GridLayout.LayoutParams)button.getLayoutParams()).setGravity(int)
So how can I question a variable that is a NoneType?
Use is
operator, like this
if variable is None:
Why this works?
Since None
is the sole singleton object of NoneType
in Python, we can use is
operator to check if a variable has None
in it or not.
Quoting from is
docs,
The operators
is
andis not
test for object identity:x is y
is true if and only ifx
andy
are the same object.x is not y
yields the inverse truth value.
Since there can be only one instance of None
, is
would be the preferred way to check None
.
Hear it from the horse's mouth
Quoting Python's Coding Style Guidelines - PEP-008 (jointly defined by Guido himself),
Comparisons to singletons like
None
should always be done withis
oris not
, never the equality operators.
Aside from object initializers (usable only in constructor calls), the best you can get is:
var it = Stuff.Elements.Foo;
it.Name = "Bob Dylan";
it.Age = 68;
...
You don't add columns between other columns in SQL, you just add them. Where they're put is totally up to the DBMS. The right place to ensure that columns come out in the correct order is when you select
them.
In other words, if you want them in the order {name,colnew,qty,rate}
, you use:
select name, colnew, qty, rate from ...
With SQLite, you need to use alter table
, an example being:
alter table mytable add column colnew char(50)
To convert all Java files recursively in a directory to use 4 spaces instead of a tab:
find . -type f -name *.java -exec bash -c 'expand -t 4 {} > /tmp/stuff;mv /tmp/stuff {}' \;
Declare the Start and End date
DECLARE @SDATE AS DATETIME
TART_DATE AS DATETIME
DECLARE @END_-- Set Start and End date
SET @START_DATE = GETDATE()
SET @END_DATE = DATEADD(SECOND, 3910, GETDATE())
-- Get the Result in HH:MI:SS:MMM(24H) format
SELECT CONVERT(VARCHAR(12), DATEADD(MS, DATEDIFF(MS, @START_DATE, @END_DATE), 0), 114) AS TimeDiff
If you are able/willing to use a tiny component I wrote this Timepicker — https://github.com/jonataswalker/timepicker.js — for my own needs.
Usage is like this:
var timepicker = new TimePicker('time', {_x000D_
lang: 'en',_x000D_
theme: 'dark'_x000D_
});_x000D_
_x000D_
var input = document.getElementById('time');_x000D_
_x000D_
timepicker.on('change', function(evt) {_x000D_
_x000D_
var value = (evt.hour || '00') + ':' + (evt.minute || '00');_x000D_
evt.element.value = value;_x000D_
_x000D_
});
_x000D_
body {_x000D_
font: 1.2em/1.3 sans-serif;_x000D_
color: #222;_x000D_
font-weight: 400;_x000D_
padding: 5px;_x000D_
margin: 0;_x000D_
background: linear-gradient(#efefef, #999) fixed;_x000D_
}_x000D_
input {_x000D_
padding: 5px 0;_x000D_
font-size: 1.5em;_x000D_
font-family: inherit;_x000D_
width: 100px;_x000D_
}
_x000D_
<script src="http://cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.js"></script>_x000D_
<link href="http://cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div>_x000D_
<input type="text" id="time" placeholder="Time">_x000D_
</div>
_x000D_
You need to set a -D system property called java.library.path
that points at the directory containing the sqljdbc_auth.dll
.
<div>foo</div><div>bar</div><div>baz</div>
//solution 1
<style>
#div01, #div02, #div03 {
float:left;
width:2%;
}
</style>
<div id="div01">foo</div><div id="div02">bar</div><div id="div03">baz</div>
//solution 2
<style>
#div01, #div02, #div03 {
display:inline;
padding-left:5px;
}
</style>
<div id="div01">foo</div><div id="div02">bar</div><div id="div03">baz</div>
/* I think this would help but if you have any other thoughts just let me knw kk */
var b bytes.Buffer
b.ReadFrom(r)
// b.String()
For layering, Just change the version of targetFramework in web.config file only, the other things no need change.
You can use (mouseover)
and (mouseout)
events.
component.ts
changeText:boolean=true;
component.html
<div (mouseover)="changeText=true" (mouseout)="changeText=false">
<span [hidden]="changeText">Hide</span>
<span [hidden]="!changeText">Show</span>
</div>
package com.ofs;
public class ReverseWordsInString{
public static void main(String[] args) {
String str = "welcome to the new world and how are you feeling ?";
// Get the Java runtime
Runtime runtime = Runtime.getRuntime();
// Run the garbage collector
runtime.gc();
// Calculate the used memory
long firstUsageMemory = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Used memory in bytes: " + firstUsageMemory);
System.out.println(str);
str = new StringBuffer(str).reverse().toString();
int count = 0;
int preValue = 0;
int lastspaceIndexVal = str.lastIndexOf(" ");
int strLen = str.length();
for (int i = 0; i < strLen - 1; i++) {
if (Character.isWhitespace(str.charAt(i))) {
if (i - preValue == 1 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 2 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 3 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 4 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 5 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.substring(i - 2, i - 1) + str.charAt(i - 3)
+ str.charAt(i - 3) + str.charAt(i - 5)
+ str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 6 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.charAt(i - 5)
+ str.charAt(i - 6) + str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 7 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.charAt(i - 5)
+ str.charAt(i - 6) + str.charAt(i - 7)
+ str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 8 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.charAt(i - 5)
+ str.charAt(i - 6) + str.charAt(i - 7)
+ str.charAt(i - 8) + str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 2 && count != 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.substring(i, strLen);
preValue = i;
} else if (i - preValue == 3 && count != 0) {
str = str.substring(0, preValue + 1) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.substring(i, strLen);
preValue = i;
} else if (i - preValue == 4 && count != 0) {
str = str.substring(0, preValue + 1) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.substring(i, strLen);
preValue = i;
} else if (i - preValue == 5 && count != 0) {
str = str.substring(0, preValue + 1) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 6 && count != 0) {
str = str.substring(0, preValue + 1) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.charAt(i - 5)
+ str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 7 && count != 0) {
str = str.substring(0, preValue + 1) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.charAt(i - 5)
+ str.charAt(i - 6) + str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 8 && count != 0) {
str = str.substring(0, preValue + 1) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.charAt(i - 5)
+ str.charAt(i - 6) + str.charAt(i - 7)
+ str.substring(i, strLen);
preValue = i;
count++;
}
if (lastspaceIndexVal == preValue) {
if (strLen - lastspaceIndexVal == 2 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1);
preValue = i;
} else if (strLen - lastspaceIndexVal == 3 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1)
+ str.charAt(strLen - 2);
preValue = i;
} else if (strLen - lastspaceIndexVal == 4 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1)
+ str.charAt(strLen - 2)
+ str.charAt(strLen - 3);
preValue = i;
count++;
} else if (strLen - lastspaceIndexVal == 5 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1)
+ str.charAt(strLen - 2)
+ str.charAt(strLen - 3)
+ str.charAt(strLen - 4);
preValue = i;
} else if (strLen - lastspaceIndexVal == 6 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1)
+ str.charAt(strLen - 2)
+ str.charAt(strLen - 3)
+ str.charAt(strLen - 4)
+ str.charAt(strLen - 5);
preValue = i;
count++;
} else if (strLen - lastspaceIndexVal == 7 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1)
+ str.charAt(strLen - 2)
+ str.charAt(strLen - 3)
+ str.charAt(strLen - 4)
+ str.charAt(strLen - 5)
+ str.charAt(strLen - 6);
preValue = i;
} else if (strLen - lastspaceIndexVal == 8 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1)
+ str.charAt(strLen - 2)
+ str.charAt(strLen - 3)
+ str.charAt(strLen - 4)
+ str.charAt(strLen - 5)
+ str.charAt(strLen - 6)
+ str.charAt(strLen - 7);
preValue = i;
}
}
}
}
runtime.gc();
// Calculate the used memory
long SecondaryUsageMemory = runtime.totalMemory()
- runtime.freeMemory();
System.out.println("Used memory in bytes: " + SecondaryUsageMemory);
System.out.println(str);
}
}
If you are sure you want to remove all commit history, simply delete the .git
directory in your project root (note that it's hidden). Then initialize a new repository in the same folder and link it to the GitHub repository:
git init
git remote add origin [email protected]:user/repo
now commit your current version of code
git add *
git commit -am 'message'
and finally force the update to GitHub:
git push -f origin master
However, I suggest backing up the history (the .git
folder in the repository) before taking these steps!
The code looks strange because the printf are not in any function blocks.
I have implemented a tiny benchmark (please find the code on Gist) to evaluate the pandas' concat
and append
. I updated the code snippet and the results after the comment by ssk08
- thanks alot!
The benchmark ran on a Mac OS X 10.13 system with Python 3.6.2 and pandas 0.20.3.
+--------+---------------------------------+---------------------------------+ | | ignore_index=False | ignore_index=True | +--------+---------------------------------+---------------------------------+ | size | append | concat | append/concat | append | concat | append/concat | +--------+--------+--------+---------------+--------+--------+---------------+ | small | 0.4635 | 0.4891 | 94.77 % | 0.4056 | 0.3314 | 122.39 % | +--------+--------+--------+---------------+--------+--------+---------------+ | medium | 0.5532 | 0.6617 | 83.60 % | 0.3605 | 0.3521 | 102.37 % | +--------+--------+--------+---------------+--------+--------+---------------+ | large | 0.9558 | 0.9442 | 101.22 % | 0.6670 | 0.6749 | 98.84 % | +--------+--------+--------+---------------+--------+--------+---------------+
Using ignore_index=False
append
is slightly faster, with ignore_index=True
concat
is slightly faster.
tl;dr
No significant difference between concat
and append
.
This code works for a numpy 2D matrix array:
mat = np.array([[1, 3], [2, 5]]) # numpy matrix
n = 2 # n
n_largest_mat = np.sort(mat, axis=None)[-n:] # n_largest
tf_n_largest = np.zeros((2,2), dtype=bool) # all false matrix
for x in n_largest_mat:
tf_n_largest = (tf_n_largest) | (mat == x) # true-false
n_largest_elems = mat[tf_n_largest] # true-false indexing
This produces a true-false n_largest matrix indexing that also works to extract n_largest elements from a matrix array
As Svenmarim already stated, this mostly occurs because the ip adress is already in use.
This answer and its comments from the visualstudio developer community pointed me to the right direction. In my case i was trying to access my local IISExpress instance from my local network and therefore binded my ip adress with the same port which uses my IISExpress instance via
netsh http add urlacl url=http://192.168.1.42:58938/ user=everyone
After removing this binding via
netsh http delete urlacl url=http://192.168.1.42:58938/
it worked again.
Another option with Filter
Filter(function(x) !all(is.na(x)), df)
NOTE: Data from @Simon O'Hanlon's post.
Here is a solution as an extension of [https://stackoverflow.com/a/46644736/10249774]
Bottom panel is pushing main content upwards
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/my_button"
android:layout_marginTop="10dp"
android:onClick="onSlideViewButtonClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<LinearLayout
android:id="@+id/main_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="main "
android:textSize="70dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="main "
android:textSize="70dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="main "
android:textSize="70dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="main"
android:textSize="70dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="main"
android:textSize="70dp"/>
</LinearLayout>
<LinearLayout
android:id="@+id/footer_view"
android:background="#a6e1aa"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="footer content"
android:textSize="40dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="footer content"
android:textSize="40dp" />
</LinearLayout>
</RelativeLayout>
MainActivity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button myButton;
private View footerView;
private View mainView;
private boolean isUp;
private int anim_duration = 700;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
footerView = findViewById(R.id.footer_view);
mainView = findViewById(R.id.main_view);
myButton = findViewById(R.id.my_button);
// initialize as invisible (could also do in xml)
footerView.setVisibility(View.INVISIBLE);
myButton.setText("Slide up");
isUp = false;
}
public void slideUp(View mainView , View footer_view){
footer_view.setVisibility(View.VISIBLE);
TranslateAnimation animate_footer = new TranslateAnimation(
0, // fromXDelta
0, // toXDelta
footer_view.getHeight(), // fromYDelta
0); // toYDelta
animate_footer.setDuration(anim_duration);
animate_footer.setFillAfter(true);
footer_view.startAnimation(animate_footer);
mainView.setVisibility(View.VISIBLE);
TranslateAnimation animate_main = new TranslateAnimation(
0, // fromXDelta
0, // toXDelta
0, // fromYDelta
(0-footer_view.getHeight())); // toYDelta
animate_main.setDuration(anim_duration);
animate_main.setFillAfter(true);
mainView.startAnimation(animate_main);
}
public void slideDown(View mainView , View footer_view){
TranslateAnimation animate_footer = new TranslateAnimation(
0, // fromXDelta
0, // toXDelta
0, // fromYDelta
footer_view.getHeight()); // toYDelta
animate_footer.setDuration(anim_duration);
animate_footer.setFillAfter(true);
footer_view.startAnimation(animate_footer);
TranslateAnimation animate_main = new TranslateAnimation(
0, // fromXDelta
0, // toXDelta
(0-footer_view.getHeight()), // fromYDelta
0); // toYDelta
animate_main.setDuration(anim_duration);
animate_main.setFillAfter(true);
mainView.startAnimation(animate_main);
}
public void onSlideViewButtonClick(View view) {
if (isUp) {
slideDown(mainView , footerView);
myButton.setText("Slide up");
} else {
slideUp(mainView , footerView);
myButton.setText("Slide down");
}
isUp = !isUp;
}
}
You've got what rebase
does backwards. git rebase master
does what you're asking for — takes the changes on the current branch (since its divergence from master) and replays them on top of master
, then sets the head of the current branch to be the head of that new history. It doesn't replay the changes from master
on top of the current branch.
If the to-be-updated component is not inside the same NamingContainer
component (ui:repeat
, h:form
, h:dataTable
, etc), then you need to specify the "absolute" client ID. Prefix with :
(the default NamingContainer
separator character) to start from root.
<p:ajax process="@this" update="count :subTotal"/>
To be sure, check the client ID of the subTotal
component in the generated HTML for the actual value. If it's inside for example a h:form
as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.
<p:ajax process="@this" update="count :formId:subTotal"/>
Space separation of IDs is more recommended as <f:ajax>
doesn't support comma separation and starters would otherwise get confused.
The easiest option is to just use the list() command. However, if you don't want to use it or it dose not work for some bazaar reason, you can always use this method.
word = 'foo'
splitWord = []
for letter in word:
splitWord.append(letter)
print(splitWord) #prints ['f', 'o', 'o']
Since C++14 you can use two real string literals:
const string hello = "Hello"s;
const string message = hello + ",world"s + "!"s;
or
const string exclam = "!"s;
const string message = "Hello"s + ",world"s + exclam;
In addition to what Angular University said above you may want to use @Import to aggregate @Configuration classes to the other class (AuthenticationController in my case) :
@Import(SecurityConfig.class)
@RestController
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
//some logic
}
Spring doc about Aggregating @Configuration classes with @Import: link
You're getting the error because result
defined as Sequential()
is just a container for the model and you have not defined an input for it.
Given what you're trying to build set result
to take the third input x3
.
first = Sequential()
first.add(Dense(1, input_shape=(2,), activation='sigmoid'))
second = Sequential()
second.add(Dense(1, input_shape=(1,), activation='sigmoid'))
third = Sequential()
# of course you must provide the input to result which will be your x3
third.add(Dense(1, input_shape=(1,), activation='sigmoid'))
# lets say you add a few more layers to first and second.
# concatenate them
merged = Concatenate([first, second])
# then concatenate the two outputs
result = Concatenate([merged, third])
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
result.compile(optimizer=ada_grad, loss='binary_crossentropy',
metrics=['accuracy'])
However, my preferred way of building a model that has this type of input structure would be to use the functional api.
Here is an implementation of your requirements to get you started:
from keras.models import Model
from keras.layers import Concatenate, Dense, LSTM, Input, concatenate
from keras.optimizers import Adagrad
first_input = Input(shape=(2, ))
first_dense = Dense(1, )(first_input)
second_input = Input(shape=(2, ))
second_dense = Dense(1, )(second_input)
merge_one = concatenate([first_dense, second_dense])
third_input = Input(shape=(1, ))
merge_two = concatenate([merge_one, third_input])
model = Model(inputs=[first_input, second_input, third_input], outputs=merge_two)
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
model.compile(optimizer=ada_grad, loss='binary_crossentropy',
metrics=['accuracy'])
To answer the question in the comments:
Concatenation works like this:
a b c
a b c g h i a b c g h i
d e f j k l d e f j k l
i.e rows are just joined.
x1
is input to first, x2
is input into second and x3
input into third.You should implement an LRU cache manager when dealing with bitmap
http://developer.android.com/reference/android/util/LruCache.html http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html When should I recycle a bitmap using LRUCache?
OR
Use a tier library like Universal Image Loader :
https://github.com/nostra13/Android-Universal-Image-Loader
EDIT :
Now when dealing with images and most of the time with bitmap I use Glide which let you configure a Glide Module and a LRUCache
Do you really want to simply push your local repository (with its local branches, etc.) to the new remote or do you really want to mirror the old remote (with all its branches, tags, etc) on the new remote? If the latter here's a great blog on How to properly mirror a git repository.
I strongly encourage you to read the blog for some very important details, but the short version is this:
In a new directory run these commands:
git clone --mirror [email protected]/upstream-repository.git
cd upstream-repository.git
git push --mirror [email protected]/new-location.git
Inherit the tableview delegate and datasource. Implement delegates what you need.
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
And Finally implement this delegate
func tableView(_ tableView: UITableView, didSelectRowAt
indexPath: IndexPath) {
print("row selected : \(indexPath.row)")
}
Create a zip file, then download the file, by setting the header, read the zip contents and output the file.
http://www.php.net/manual/en/function.ziparchive-addfile.php
You could try changing the: SizeMode property of the PictureBox.
You could also set your image as the BackGroundImage of the PictureBox and try changing the BackGroundImageLayout to the correct mode.
Here is a simple example:
package main
import "fmt"
func plusTwo() (func(v int) (int)) {
return func(v int) (int) {
return v+2
}
}
func plusX(x int) (func(v int) (int)) {
return func(v int) (int) {
return v+x
}
}
func main() {
p := plusTwo()
fmt.Printf("3+2: %d\n", p(3))
px := plusX(3)
fmt.Printf("3+3: %d\n", px(3))
}
I kind of got things working by adding auto layout constraints:
But I am not happy with this. Took a lot of trial and error and couldn't understand why this worked.
Also I had to add to use titleLabel.numberOfLines = 0
in my ViewController
You do need to loop through it. C++ does not implement any simpler way to do this when you are dealing with primitive type arrays.
also see this answer: C++ check if element exists in array
I encountered this issue while trying to build an npm project. It was failing to install a node-sass package and this was the error it was printing. I solved it by setting my npm proxy correctly so that i
If you are trying to do this, it means you are doing something wrong. Consider using a dict
instead.
def show_val(vals, name):
print "Name:", name, "val:", vals[name]
vals = {'a': 1, 'b': 2}
show_val(vals, 'b')
Output:
Name: b val: 2
use spawn
import os
os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
Also, some very interesting information further on lists vs. arrays in Python ~> Python List vs. Array - when to use?
It could be noted that once I convert my arrays into a list before saving it in a JSON file, in my deployment right now anyways, once I read that JSON file for use later, I can continue to use it in a list form (as opposed to converting it back to an array).
AND actually looks nicer (in my opinion) on the screen as a list (comma seperated) vs. an array (not-comma seperated) this way.
Using @travelingbones's .tolist() method above, I've been using as such (catching a few errors I've found too):
SAVE DICTIONARY
def writeDict(values, name):
writeName = DIR+name+'.json'
with open(writeName, "w") as outfile:
json.dump(values, outfile)
READ DICTIONARY
def readDict(name):
readName = DIR+name+'.json'
try:
with open(readName, "r") as infile:
dictValues = json.load(infile)
return(dictValues)
except IOError as e:
print(e)
return('None')
except ValueError as e:
print(e)
return('None')
Hope this helps!
See Encoding and decoding base 64 with C++.
Here is the implementation from that page:
/*
base64.cpp and base64.h
Copyright (C) 2004-2008 René Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
René Nyffenegger [email protected]
*/
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
std::string base64_decode(std::string const& encoded_string) {
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i ==4) {
for (i = 0; i <4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <4; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
hey I understand this is an old thread but I have a query in regards to apachebenchmarking. how do you collect the metrics from apache benchmarking. P.S: I have to do it via telegraf and put it to influxdb . any suggestions/advice/help would be appreciated. Thanks a ton.
To copy conditional formatting from google spreadsheet (doc1) to another (doc2) you need to do the following:
For those on Azure, follow these modified instructions from Virus:
You will certainly be able to do that using WITH clause, or use analytic functions available in Oracle SQL.
With some effort you'd be able to get anything out of them in terms of cycles as in ordinary procedural languages. Both approaches are pretty powerful compared to ordinary SQL.
http://www.dba-oracle.com/t_with_clause.htm
It requires some effort though. Don't be afraid to post a concrete example.
Using simple pseudo table DUAL helps too.
<a href="download.php?file=path/<?=$row['file_name']?>">Download</a>
download.php:
<?php
$file = $_GET['file'];
download_file($file);
function download_file( $fullPath ){
// Must be fresh start
if( headers_sent() )
die('Headers Sent');
// Required for some browsers
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
// File Exists?
if( file_exists($fullPath) ){
// Parse Info / Get Extension
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
// Determine Content Type
switch ($ext) {
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/force-download";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$fsize);
ob_clean();
flush();
readfile( $fullPath );
} else
die('File Not Found');
}
?>
Following redsquare: You should not use in href attribute javascript code like "javascript:void();" - it is wrong. Better use for example href="#" and then in Your event handler as a last command: "return false;". And even better - use in href correct link - if user have javascript disabled, web browser follows the link - in this case Your webpage should reload with input filled with value of that link.
Daniel Hilgarth's answer above leads to a System.NotSupported
exception With Entity-Framework. With Entity-Framework, it has to be:
table1.GroupBy(x => x.Text).Select(x => x.FirstOrDefault());
Unfortunately, ­
's support is so inconsistent between browsers that it can't really be used.
QuirksMode is right -- there's no good way to use soft hyphens in HTML right now. See what you can do to go without them.
2013 edit: According to QuirksMode, ­
now works/is supported on all major browsers.
Answer provided by Nicholas Krasnov
SELECT *
FROM BOOKING_SESSION
WHERE TO_CHAR(T_SESSION_DATETIME, 'DD-MM-YYYY') ='20-03-2012';
in my case, some characters like " , :"'{}[] " maybe corrupt the JSON format, so use try json.loads(str) except to check your input
But the problem with this code is that, I cannot change the content popup content from "Please enter your name" to my html form.
Umm. Just change the string passed to the prompt()
function.
While searching, I found that there we CANNOT change the content of popup Prompt Box
You can't change the title. You can change the content, it is the first argument passed to the prompt()
function.
You can check all the config settings using
git config --global --list
You can remove the setting for example username
git config --global --unset user.name
You can edit the configuration or remove the config setting manually by hand using:
git config --global --edit
There are many ways to filter for element ancestors.
if ($elem.closest('.parentClass').length /* > 0*/) {/*...*/}
if ($elem.parents('.parentClass').length /* > 0*/) {/*...*/}
if ($elem.parents().hasClass('parentClass')) {/*...*/}
if ($('.parentClass').has($elem).length /* > 0*/) {/*...*/}
if ($elem.is('.parentClass *')) {/*...*/}
Beware, closest()
method includes element itself while checking for selector.
Alternatively, if you have a unique selector matching the $elem
, e.g #myElem
, you can use:
if ($('.parentClass:has(#myElem)').length /* > 0*/) {/*...*/}
if(document.querySelector('.parentClass #myElem')) {/*...*/}
If you want to match an element depending any of its ancestor class for styling purpose only, just use a CSS rule:
.parentClass #myElem { /* CSS property set */ }
This answer may be late but I hope it helps someone.
For me, these 2 lines of code worked:
textView.isScrollEnabled = false
textView.sizeToFit()
But don't set height constraint for your Textview
This SP looks very strange. It does not modify what is passed to @b. And nowhere in the SP you assign anything to @b. And @Password is not defined, so this SP will not work at all.
I would guess you actually want to return @Password, or to have SET @b = (SELECT...)
Much simpler will be if you modify your SP to (note, no OUTPUT parameter):
set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go
ALTER PROCEDURE [dbo].[Validate] @a varchar(50)
AS
SELECT TOP 1 Password FROM dbo.tblUser WHERE Login = @a
Then, your code can use cmd.ExecuteScalar, and receive the result.
In pthread_exit
, ret
is an input parameter. You are simply passing the address of a variable to the function.
In pthread_join
, ret
is an output parameter. You get back a value from the function. Such value can, for example, be set to NULL
.
Long explanation:
In pthread_join
, you get back the address passed to pthread_exit
by the finished thread. If you pass just a plain pointer, it is passed by value so you can't change where it is pointing to. To be able to change the value of the pointer passed to pthread_join, it must be passed as a pointer itself, that is, a pointer to a pointer.
<div style="width: 100%; height: 100vh; max-height: 20px; max-width: 100%; background: url('https://kajabi-storefronts-production.global.ssl.fastly.net/kajabi-storefronts-production/themes/853636/settings_images/Ei2yf3t7TvyRpFaLQZiX_dot.jpg') #000; background-repeat: repeat;"> </div>
this is what I did - use an image enter image description here
You can use backslash to quote "funny" characters in your jQuery selectors:
$('#input\\[23\\]')
For attribute values, you can use quotes:
$('input[name="weirdName[23]"]')
Now, I'm a little confused by your example; what exactly does your HTML look like? Where does the string "inputName" show up, in particular?
edit fixed bogosity; thanks @Dancrumb
Check output of console.log(req)
or console.log(req.headers);
For those using the Symfony framework, the phpseclib can also be used to connect via SSH. It can be installed using composer:
composer require phpseclib/phpseclib
Next, simply use it as follows:
use phpseclib\Net\SSH2;
// Within a controller for example:
$ssh = new SSH2('hostname or ip');
if (!$ssh->login('username', 'password')) {
// Login failed, do something
}
$return_value = $ssh->exec('command');
SELECT TABLE_NAME AS table_name,
table_rows AS QuantofRows,
ROUND((data_length + index_length) /1024, 2 ) AS total_size_kb
FROM information_schema.TABLES
WHERE information_schema.TABLES.table_schema = 'db'
ORDER BY (data_length + index_length) DESC;
all 2 above is tested on mysql
If I understand your question correctly, I've made a fiddle that has this working correctly. This issue is with how you're assigning the event handlers and as others have said you have over riding event handlers. The current jQuery best practice is to use on()
to register event handlers. Here's a link to the jQuery docs about on
: link
Your original solution was pretty close but the way you added the event handlers is a bit confusing. It's considered best practice to not add events to HTML elements. I recommend reading up on Unobstrusive JavaScript.
Here's the JavaScript code. I added a counter variable so you can see that it is working correctly.
$('#answer').on('click', function() {
feedback('hey there');
});
var counter = 0;
function feedback(message) {
$('#feedback').remove();
$('.answers').append('<div id="feedback">' + message + ' ' + counter + '</div>');
counter++;
}
import
statements are supported in the stable release of Node since version 14.x LTS.
All you need to do is specify "type": "module"
in package.json
.
Using Retrofit 2.0 you may use this:
@Multipart
@POST("uploadImage")
Call<ResponseBody> uploadImage(@Part("file\"; fileName=\"myFile.png\" ")RequestBody requestBodyFile, @Part("image") RequestBody requestBodyJson);
Make a request:
File imgFile = new File("YOUR IMAGE FILE PATH");
RequestBody requestBodyFile = RequestBody.create(MediaType.parse("image/*"), imgFile);
RequestBody requestBodyJson = RequestBody.create(MediaType.parse("text/plain"),
retrofitClient.getJsonObject(uploadRequest));
//make sync call
Call<ResponseBody> uploadBundle = uploadImpl.uploadImage(requestBodyFile, requestBodyJson);
Response<BaseResponse> response = uploadBundle.execute();
please refer https://square.github.io/retrofit/
terrific answer from DuckPuncher, for Python3 make sure you install pdfminer2 and do:
import io
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
def convert_pdf_to_txt(path):
rsrcmgr = PDFResourceManager()
retstr = io.StringIO()
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
fp = open(path, 'rb')
interpreter = PDFPageInterpreter(rsrcmgr, device)
password = ""
maxpages = 0
caching = True
pagenos = set()
for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages,
password=password,
caching=caching,
check_extractable=True):
interpreter.process_page(page)
fp.close()
device.close()
text = retstr.getvalue()
retstr.close()
return text
Hello...I have created a java client server application in swing for caesar cipher...I have created a new formula that can decrypt the text properly... sorry only for lower case..!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class ceasarserver extends JFrame implements ActionListener {
static String cs = "abcdefghijklmnopqrstuvwxyz";
static JLabel l1, l2, l3, l5, l6;
JTextField t1;
JButton close, b1;
static String en;
int num = 0;
JProgressBar progress;
ceasarserver() {
super("SERVER");
JPanel p = new JPanel(new GridLayout(10, 1));
l1 = new JLabel("");
l2 = new JLabel("");
l3 = new JLabel("");
l5 = new JLabel("");
l6 = new JLabel("Enter the Key...");
t1 = new JTextField(30);
progress = new JProgressBar(0, 20);
progress.setValue(0);
progress.setStringPainted(true);
close = new JButton("Close");
close.setMnemonic('C');
close.setPreferredSize(new Dimension(300, 25));
close.addActionListener(this);
b1 = new JButton("Decrypt");
b1.setMnemonic('D');
b1.addActionListener(this);
p.add(l1);
p.add(l2);
p.add(l3);
p.add(l6);
p.add(t1);
p.add(b1);
p.add(progress);
p.add(l5);
p.add(close);
add(p);
setVisible(true);
pack();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == close)
System.exit(0);
else if (e.getSource() == b1) {
int key = Integer.parseInt(t1.getText());
String d = "";
int i = 0, j, k;
while (i < en.length()) {
j = cs.indexOf(en.charAt(i));
k = (j + (26 - key)) % 26;
d = d + cs.charAt(k);
i++;
}
while (num < 21) {
progress.setValue(num);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
progress.setValue(num);
Rectangle progressRect = progress.getBounds();
progressRect.x = 0;
progressRect.y = 0;
progress.paintImmediately(progressRect);
num++;
}
l5.setText("Decrypted text: " + d);
}
}
public static void main(String args[]) throws IOException {
new ceasarserver();
String strm = new String();
ServerSocket ss = new ServerSocket(4321);
l1.setText("Secure data transfer Server Started....");
Socket s = ss.accept();
l2.setText("Client Connected !");
while (true) {
Scanner br1 = new Scanner(s.getInputStream());
en = br1.nextLine();
l3.setText("Client:" + en);
}
}
The client class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class ceasarclient extends JFrame {
String cs = "abcdefghijklmnopqrstuvwxyz";
static JLabel l1, l2, l3, l4, l5;
JButton b1, b2, b3;
JTextField t1, t2;
JProgressBar progress;
int num = 0;
String en = "";
ceasarclient(final Socket s) {
super("CLIENT");
JPanel p = new JPanel(new GridLayout(10, 1));
setSize(500, 500);
t1 = new JTextField(30);
b1 = new JButton("Send");
b1.setMnemonic('S');
b2 = new JButton("Close");
b2.setMnemonic('C');
l1 = new JLabel("Welcome to Secure Data transfer!");
l2 = new JLabel("Enter the word here...");
l3 = new JLabel("");
l4 = new JLabel("Enter the Key:");
b3 = new JButton("Encrypt");
b3.setMnemonic('E');
t2 = new JTextField(30);
progress = new JProgressBar(0, 20);
progress.setValue(0);
progress.setStringPainted(true);
p.add(l1);
p.add(l2);
p.add(t1);
p.add(l4);
p.add(t2);
p.add(b3);
p.add(progress);
p.add(b1);
p.add(l3);
p.add(b2);
add(p);
setVisible(true);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
pw.println(en);
} catch (Exception ex) {
}
;
l3.setText("Encrypted Text Sent.");
}
});
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String strw = t1.getText();
int key = Integer.parseInt(t2.getText());
int i = 0, j, k;
while (i < strw.length()) {
j = cs.indexOf(strw.charAt(i));
k = (j + key) % 26;
en = en + cs.charAt(k);
i++;
}
while (num < 21) {
progress.setValue(num);
try {
Thread.sleep(100);
} catch (InterruptedException exe) {
}
progress.setValue(num);
Rectangle progressRect = progress.getBounds();
progressRect.x = 0;
progressRect.y = 0;
progress.paintImmediately(progressRect);
num++;
}
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
pack();
}
public static void main(String args[]) throws IOException {
final Socket s = new Socket(InetAddress.getLocalHost(), 4321);
new ceasarclient(s);
}
}
HTML Code
<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload" class="send_upload" value="upload" />
jQuery Code using bind method
$(document).ready(function() {
$('#upload').bind("click",function()
{ if(!$('#uploadImage').val()){
alert("empty");
return false;} }); });
django raw sql query in view
"SELECT * FROM VendorReport_vehicledamage WHERE requestdate BETWEEN '{0}' AND '{1}'".format(date_from, date_to)
models.py
class VehicleDamage(models.Model):
requestdate = models.DateTimeField("requestdate")
vendor_name = models.CharField("vendor_name", max_length=50)
class Meta:
managed=False
views.py
def location_damageReports(request):
#static date for testing
date_from = '2019-11-01'
date_to = '2019-21-01'
vehicle_damage_reports = VehicleDamage.objects.raw("SELECT * FROM VendorReport_vehicledamage WHERE requestdate BETWEEN '{0}' AND '{1}'".format(date_from, date_to))
damage_report = DashboardDamageReportSerializer(vehicle_damage_reports, many=True)
data={"data": damage_report.data}
return HttpResponse(json.dumps(data), content_type="application/json")
Note: using python 3.5 and django 1.11
I've disabled all unused options in Windows > Preferences > General and it has a huge positive impact on performance, eclipse is still slow when switching tabs, I don't want to increase memory, but it's a lot faster when scrolling. Thx for the tips.
It is slightly similar to the answer by fab but not exactly the same.
The singleton contract does not require that we be able to call the constructor multiple times. As a singleton should be created once and once only, shouldn't it be seen to be created just once? "Spoofing" the constructor arguably impairs legibility.
So my suggestion is just this:
class Elvis():
def __init__(self):
if hasattr(self.__class__, 'instance'):
raise Exception()
self.__class__.instance = self
# initialisation code...
@staticmethod
def the():
if hasattr(Elvis, 'instance'):
return Elvis.instance
return Elvis()
This does not rule out the use of the constructor or the field instance
by user code:
if Elvis() is King.instance:
... if you know for sure that Elvis
has not yet been created, and that King
has.
But it encourages users to use the the
method universally:
Elvis.the().leave(Building.the())
To make this complete you could also override __delattr__()
to raise an Exception if an attempt is made to delete instance
, and override __del__()
so that it raises an Exception (unless we know the program is ending...)
My thanks to those who have helped with comments and edits, of which more are welcome. While I use Jython, this should work more generally, and be thread-safe.
try:
# This is jython-specific
from synchronize import make_synchronized
except ImportError:
# This should work across different python implementations
def make_synchronized(func):
import threading
func.__lock__ = threading.Lock()
def synced_func(*args, **kws):
with func.__lock__:
return func(*args, **kws)
return synced_func
class Elvis(object): # NB must be subclass of object to use __new__
instance = None
@classmethod
@make_synchronized
def __new__(cls, *args, **kwargs):
if cls.instance is not None:
raise Exception()
cls.instance = object.__new__(cls, *args, **kwargs)
return cls.instance
def __init__(self):
pass
# initialisation code...
@classmethod
@make_synchronized
def the(cls):
if cls.instance is not None:
return cls.instance
return cls()
Points of note:
__new__
__new__
you must decorate with @classmethod or __new__
will be an unbound instance methodthe
a class-level property, possibly renaming it to instance
You can also use react router dom library useHistory;
`
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
`
The correct scheme should be:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/Sport"
xmlns:tns="http://www.example.org/Sport"
elementFormDefault="qualified"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
jaxb:version="2.0">
<complexType name="sportType">
<simpleContent>
<extension base="string">
<attribute name="type" type="string" />
<attribute name="gender" type="string" />
</extension>
</simpleContent>
</complexType>
<element name="sports">
<complexType>
<sequence>
<element name="sport" minOccurs="0" maxOccurs="unbounded"
type="tns:sportType" />
</sequence>
</complexType>
</element>
Code generated for SportType will be:
package org.example.sport;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sportType")
public class SportType {
@XmlValue
protected String value;
@XmlAttribute
protected String type;
@XmlAttribute
protected String gender;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String value) {
this.type = value;
}
public String getGender() {
return gender;
}
public void setGender(String value) {
this.gender = value;
}
}
Here:
html,body{
height:100%;
}
body{
margin:0;
padding:0
background:blue;
}
It is easy to check for removable devices. However, there's no guarantee that it is a USB device:
var drives = DriveInfo.GetDrives()
.Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable);
This will return a list of all removable devices that are currently accessible. More information:
DriveInfo
class (msdn documentation)DriveType
enumeration (msdn documentation)It is going to write the value of your property model.Destination
This is by design. You'll want to populate your Destination property with the value you want in your controller before returning your view.
in pure Ruby:
{:a => 1, :b => 2}.tap{|x| x.delete(:a)} # => {:b=>2}
You may use Upsert with $setOnInsert operator.
db.Table.update({noExist: true}, {"$setOnInsert": {xxxYourDocumentxxx}}, {upsert: true})
$ kubectl replace --force -f <resource-file>
if all goes well, you should see something like:
<resource-type> <resource-name> deleted
<resource-type> <resource-name> replaced
details of this can be found in the Kubernetes documentation, "manage-deployment" and kubectl-cheatsheet pages at the time of writing.
By using the requestInterceptor, it worked for me:
const ui = SwaggerUIBundle({
...
requestInterceptor: (req) => {
req.headers.Authorization = "Bearer " + req.headers.Authorization;
return req;
},
...
});
All DECLAREs need to be at the top. ie.
delimiter //
CREATE TRIGGER pgl_new_user
AFTER INSERT ON users FOR EACH ROW
BEGIN
DECLARE m_user_team_id integer;
DECLARE m_projects_id integer;
DECLARE cur CURSOR FOR SELECT project_id FROM user_team_project_relationships WHERE user_team_id = m_user_team_id;
SET @m_user_team_id := (SELECT id FROM user_teams WHERE name = "pgl_reporters");
OPEN cur;
ins_loop: LOOP
FETCH cur INTO m_projects_id;
IF done THEN
LEAVE ins_loop;
END IF;
INSERT INTO users_projects (user_id, project_id, created_at, updated_at, project_access)
VALUES (NEW.id, m_projects_id, now(), now(), 20);
END LOOP;
CLOSE cur;
END//
The problem is probably somewhere else. Try this code for example:
Sub test()
origNum = "006260006"
creditOrDebit = "D"
If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
MsgBox "OK"
End If
End Sub
And you will see that your Or
works as expected. Are you sure that your ElseIf
statement is executed (it will not be executed if any of the if/elseif before is true)?
Below is some code from my BasePageObject class for waits:
public void waitForPageLoadAndTitleContains(int timeout, String pageTitle) {
WebDriverWait wait = new WebDriverWait(driver, timeout, 1000);
wait.until(ExpectedConditions.titleContains(pageTitle));
}
public void waitForElementPresence(By locator, int seconds) {
WebDriverWait wait = new WebDriverWait(driver, seconds);
wait.until(ExpectedConditions.presenceOfElementLocated(locator));
}
public void jsWaitForPageToLoad(int timeOutInSeconds) {
JavascriptExecutor js = (JavascriptExecutor) driver;
String jsCommand = "return document.readyState";
// Validate readyState before doing any waits
if (js.executeScript(jsCommand).toString().equals("complete")) {
return;
}
for (int i = 0; i < timeOutInSeconds; i++) {
TimeManager.waitInSeconds(3);
if (js.executeScript(jsCommand).toString().equals("complete")) {
break;
}
}
}
/**
* Looks for a visible OR invisible element via the provided locator for up
* to maxWaitTime. Returns as soon as the element is found.
*
* @param byLocator
* @param maxWaitTime - In seconds
* @return
*
*/
public WebElement findElementThatIsPresent(final By byLocator, int maxWaitTime) {
if (driver == null) {
nullDriverNullPointerExeption();
}
FluentWait<WebDriver> wait = new FluentWait<>(driver).withTimeout(maxWaitTime, java.util.concurrent.TimeUnit.SECONDS)
.pollingEvery(200, java.util.concurrent.TimeUnit.MILLISECONDS);
try {
return wait.until((WebDriver webDriver) -> {
List<WebElement> elems = driver.findElements(byLocator);
if (elems.size() > 0) {
return elems.get(0);
} else {
return null;
}
});
} catch (Exception e) {
return null;
}
}
Supporting methods:
/**
* Gets locator.
*
* @param fieldName
* @return
*/
public By getBy(String fieldName) {
try {
return new Annotations(this.getClass().getDeclaredField(fieldName)).buildBy();
} catch (NoSuchFieldException e) {
return null;
}
}
In ASP.NET MVC 3 You should do something like this:
// Say you have a bit of HTML like this in your controller:
ViewBag.Stuff = "<li>Menu</li>"
// Then you can do this in your view:
@MvcHtmlString.Create(ViewBag.Stuff)
Simplest way to set image as JPanel background
Don't use a JPanel. Just use a JLabel with an Icon then you don't need custom code.
See Background Panel for more information as well as a solution that will paint the image on a JPanel with 3 different painting options:
chmod +x foo.sh
#!/bin/sh
or some such.sudo pwd
As others wrote before me, at the end its what being used by your project/team/company.
Personally, I am not using cc
extension, I am trying to lower the number of extensions and not increase them, unless there's a clear value (in my opinion).
For what its worth, this is what I'm using:
c
- Pure C code only, no classes or structs with methods.
cpp
- C++ code
hpp
- Headers only code. Implementations are in the headers (like template classes)
h
- header files for both C/C++. I agree another distinction can be made, but as I wrote, I am trying to lower the number of extensions for simplicity. At least from the C++ projects I've worked in, h
files for pure-C are more rare, therefore I did not want to add another extension.
Delete Statement
Delete Statement delete table rows and return the number of rows is deleted from the table.in this statement, we use where clause to deleted data from the table
Truncate Statement
Truncate statement Deleted or removing all the rows from the table.
Drop statement
Drop statement deleted all records as well as the structure of the table
I found a solution, first, delete the ng file with
sudo rm /usr/bin/ng
then install nvm (you need to restart your terminal to use nvm).
then install and use node 6 via nvm
nvm install 6
nvm use 6
finally install angular cli
npm install -g @angular/cli
this worked for me, I wanted to update to v1.0 stable from 1.0.28 beta, but couldn't uninstall the beta version (same situation that you desrcibed). Hope this works
You should use python and pip in terminal or powershell terminal not in IDLE.
Examples:
pip install psycopg2
or
python -m pip install psycop2
Remember about add python to Windows PATH. I paste examples for Win7. I believe in Win10 this is similar.
Adding Python Path on Windows 7
python 2.7: cannot pip on windows "bash: pip: command not found"
Good luck:)
I know it a kind of obvious, but CharSequence is an interface whereas String is a concrete class :)
java.lang.String is an implementation of this interface...
You need to save the PID of the background process at the time you start it:
foo &
FOO_PID=$!
# do other stuff
kill $FOO_PID
You cannot use job control, since that is an interactive feature and tied to a controlling terminal. A script will not necessarily have a terminal attached at all so job control will not necessarily be available.
If order is not important and you don't need to worry about duplicates then you can use set intersection:
>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> list(set(a) & set(b))
[1, 3, 5]
Guava cache is easy to implementation.We can expires key on time base using guava cache. I have read fully post and below gives key of my study.
cache = CacheBuilder.newBuilder().refreshAfterWrite(2,TimeUnit.SECONDS).
build(new CacheLoader<String, String>(){
@Override
public String load(String arg0) throws Exception {
// TODO Auto-generated method stub
return addcache(arg0);
}
}
Reference : guava cache example
Dialect means "the variant of a language". Hibernate, as we know, is database agnostic. It can work with different databases. However, databases have proprietary extensions/native SQL variations, and set/sub-set of SQL standard implementations. Therefore at some point hibernate has to use database specific SQL. Hibernate uses "dialect" configuration to know which database you are using so that it can switch to the database specific SQL generator code wherever/whenever necessary.
If you want to avoid including the full path to awk, you need to update your PATH variable to include the path to the directory where awk is located, then you can just type
awk
to run your programs.
Go to Control Panel->System->Advanced and set your PATH environment variable to include "C:\Program Files (x86)\GnuWin32\bin" at the end (separated by a semi-colon) from previous entry.
Sometimes you can retreive the phonenumber with a USSD request to your operator. For example I can get my phonenumber by dialing *116# This can probably be done within an app, I guess, if the USSD responce somehow could be catched. Offcourse this is not a method I would recommend to use within an app that is to be distributed, the code may even differ between operators.
I suppose the easiest and the best solution is using OUTER APPLY
. You only use one field with DISTINCT
but to retrieve more data about that record, you utilize OUTER APPLY
.
To test the solution, execute following query which firstly creates a temp table then retrieves data:
DECLARE @tblFruit TABLE (tblFruit_ID int, tblFruit_FruitType varchar(10), tblFruit_FruitName varchar(50))
SET NOCOUNT ON
INSERT @tblFruit VALUES (1,'Citrus ','Orange')
INSERT @tblFruit VALUES (2,'Citrus','Lime')
INSERT @tblFruit VALUES (3,'Citrus','Lemon')
INSERT @tblFruit VALUES (4,'Seed','Cherry')
INSERT @tblFruit VALUES (5,'Seed','Banana')
SELECT DISTINCT (f.tblFruit_FruitType), outter_f.tblFruit_ID
FROM @tblFruit AS f
OUTER APPLY (
SELECT TOP(1) *
FROM @tblFruit AS inner_f
WHERE inner_f.tblFruit_FruitType = f.tblFruit_FruitType
) AS outter_f
The result will be:
Citrus 1
Seed 4
It seems that when this error appears it is an indication that the selenium-java plugin for maven is out-of-date.
Changing the version in the pom.xml should fix the problem
This is an additional way to find out the number of CPU cores (and a lot of other information), but this code requires an additional dependence:
Native Operating System and Hardware Information https://github.com/oshi/oshi
SystemInfo systemInfo = new SystemInfo();
HardwareAbstractionLayer hardwareAbstractionLayer = systemInfo.getHardware();
CentralProcessor centralProcessor = hardwareAbstractionLayer.getProcessor();
Get the number of logical CPUs available for processing:
centralProcessor.getLogicalProcessorCount();
the solution is simple if you importing
import org.junit.Test;
you have to run as junit 4
right click ->run as->Test config-> test runner-> as junit 4
I had a similar issue. The accepted answer did not work for me, until I made the change: @PrepareForTest(TheClassThatContainsStaticMethod.class)
, according to PowerMock's documentation for mockStatic.
And I don't have to use BDDMockito
.
My class:
public class SmokeRouteBuilder {
public static String smokeMessageId() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.error("Exception occurred while fetching localhost address", e);
return UUID.randomUUID().toString();
}
}
}
My test class:
@RunWith(PowerMockRunner.class)
@PrepareForTest(SmokeRouteBuilder.class)
public class SmokeRouteBuilderTest {
@Test
public void testSmokeMessageId_exception() throws UnknownHostException {
UUID id = UUID.randomUUID();
mockStatic(InetAddress.class);
mockStatic(UUID.class);
when(InetAddress.getLocalHost()).thenThrow(UnknownHostException.class);
when(UUID.randomUUID()).thenReturn(id);
assertEquals(id.toString(), SmokeRouteBuilder.smokeMessageId());
}
}
I know this is an old question, but I stumbled across it when I was having a similar issue, and just wanted to share how I ended achieving the results you requested so future people can pick what works best for their situation.
First, I utilize the onsubmit
event in the form, and pass this
to the function to make it easier to deal with this particular form.
<form action="/system/wpacert" onsubmit="return closeSelf(this);" method="post" enctype="multipart/form-data" name="certform">
<div>Certificate 1: <input type="file" name="cert1"/></div>
<div>Certificate 2: <input type="file" name="cert2"/></div>
<div>Certificate 3: <input type="file" name="cert3"/></div>
<div><input type="submit" value="Upload"/></div>
</form>
In our function, we'll submit the form data, and then we'll close the window. This will allow it to submit the data, and once it's done, then it'll close the window and return you to your original window.
<script type="text/javascript">
function closeSelf (f) {
f.submit();
window.close();
}
</script>
Hope this helps someone out. Enjoy!
Option 2: This option will let you submit via AJAX, and if it's successful, it'll close the window. This prevents windows from closing prior to the data being submitted. Credits to http://jquery.malsup.com/form/ for their work on the jQuery Form Plugin
First, remove your onsubmit/onclick events from the form/submit button. Place an ID on the form so AJAX can find it.
<form action="/system/wpacert" method="post" enctype="multipart/form-data" id="certform">
<div>Certificate 1: <input type="file" name="cert1"/></div>
<div>Certificate 2: <input type="file" name="cert2"/></div>
<div>Certificate 3: <input type="file" name="cert3"/></div>
<div><input type="submit" value="Upload"/></div>
</form>
Second, you'll want to throw this script at the bottom, don't forget to reference the plugin. If the form submission is successful, it'll close the window.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function () {
$('#certform').ajaxForm(function () {
window.close();
});
});
</script>
In addition to Roman's answer, something like this might be even simpler. Note that I haven't tested it because I do not have access to R right now.
# Note that I use a global variable here
# normally not advisable, but I liked the
# use here to make the code shorter
index <<- 0
new_column = sapply(df$h_no, function(x) {
if(x == 1) index = index + 1
return(index)
})
The function iterates over the values in n_ho
and always returns the categorie that the current value belongs to. If a value of 1
is detected, we increase the global variable index
and continue.
Though this is an old thread, i thought if someone is still searching for solution in the future.
HttpCookie mycookie = new HttpCookie("aa");
mycookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(mycookie1);
Thats what did the trick for me.
<?php
// Example 1 [Merging associative arrays. When two or more arrays have same key
// then the last array key value overrides the others one]
$array1 = array("a" => "JAVA", "b" => "ASP");
$array2 = array("c" => "C", "b" => "PHP");
echo " <br> Example 1 Output: <br>";
print_r(array_merge($array1,$array2));
// Example 2 [When you want to merge arrays having integer keys and
//want to reset integer keys to start from 0 then use array_merge() function]
$array3 =array(5 => "CSS",6 => "CSS3");
$array4 =array(8 => "JAVASCRIPT",9 => "HTML");
echo " <br> Example 2 Output: <br>";
print_r(array_merge($array3,$array4));
// Example 3 [When you want to merge arrays having integer keys and
// want to retain integer keys as it is then use PLUS (+) operator to merge arrays]
$array5 =array(5 => "CSS",6 => "CSS3");
$array6 =array(8 => "JAVASCRIPT",9 => "HTML");
echo " <br> Example 3 Output: <br>";
print_r($array5+$array6);
// Example 4 [When single array pass to array_merge having integer keys
// then the array return by array_merge have integer keys starting from 0]
$array7 =array(3 => "CSS",4 => "CSS3");
echo " <br> Example 4 Output: <br>";
print_r(array_merge($array7));
?>
Output:
Example 1 Output:
Array
(
[a] => JAVA
[b] => PHP
[c] => C
)
Example 2 Output:
Array
(
[0] => CSS
[1] => CSS3
[2] => JAVASCRIPT
[3] => HTML
)
Example 3 Output:
Array
(
[5] => CSS
[6] => CSS3
[8] => JAVASCRIPT
[9] => HTML
)
Example 4 Output:
Array
(
[0] => CSS
[1] => CSS3
)
I had challenge with users innocently entering € and some using double quotes to define their content. I tweaked a couple of answers from this page and others to finally define my small little work-around
$products = array($ofDirtyArray);
if($products !=null) {
header("Content-type: application/json");
header('Content-Type: charset=utf-8');
array_walk_recursive($products, function(&$val) {
$val = html_entity_decode(htmlentities($val, ENT_QUOTES, "UTF-8"));
});
echo json_encode($products, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
}
I hope it helps someone/someone improves it.
For a quick non-JQuery function...
function jsonToQueryString(json) {
return '?' +
Object.keys(json).map(function(key) {
return encodeURIComponent(key) + '=' +
encodeURIComponent(json[key]);
}).join('&');
}
Note this doesn't handle arrays or nested objects.
The KeyDown event only triggered at the standard TextBox or MaskedTextBox by "normal" input keys, not ENTER or TAB and so on.
One can get special keys like ENTER by overriding the IsInputKey method:
public class CustomTextBox : System.Windows.Forms.TextBox
{
protected override bool IsInputKey(Keys keyData)
{
if (keyData == Keys.Return)
return true;
return base.IsInputKey(keyData);
}
}
Then one can use the KeyDown event in the following way:
CustomTextBox ctb = new CustomTextBox();
ctb.KeyDown += new KeyEventHandler(tb_KeyDown);
private void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Enter key is down
//Capture the text
if (sender is TextBox)
{
TextBox txb = (TextBox)sender;
MessageBox.Show(txb.Text);
}
}
}
?????? window.performance.navigation.type
is deprecated, pls see ???? ????????'s answer
A better way to know that the page is actually reloaded is to use the navigator object that is supported by most modern browsers.
It uses the Navigation Timing API.
//check for Navigation Timing API support
if (window.performance) {
console.info("window.performance works fine on this browser");
}
console.info(performance.navigation.type);
if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {
console.info( "This page is reloaded" );
} else {
console.info( "This page is not reloaded");
}
_x000D_
source : https://developer.mozilla.org/en-US/docs/Web/API/Navigation_timing_API
This question is old and Carlos Rojas's answer is good, but I think I should post few things which should be kept in mind while trying to open the ports.
The first thing to remember is that Networking section is renamed to VPC Networking. So if you're trying to find out where Firewall Rules option is available, go look at VPC Networking.
The second thing is, if you're trying to open ports on a Linux VM, make sure under no circumstances should you try to open port using ufw
command. I tried using that and lost ssh access to the VM. So don't repeat my mistake.
The third thing is, if you're trying to open ports on a Windows VM, you'll need to create Firewall rules inside the VM also in Windows Firewall along with VPC Networking -> Firewall Rules. The port needs to be opened in both firewall rules, unlike Linux VM. So if you're not getting access to the port from outside the VM, check if you've opened the port in both GCP console and Windows Firewall.
The last (obvious) thing is, do not open ports unnecessarily. Close the ports, as soon as you no longer need it.
I hope this answer is useful.
Use PHP Manual - parse_url() to get the parts you need.
Edit (example usage for @Navi Gamage)
You can use it like this:
<?php
function reconstruct_url($url){
$url_parts = parse_url($url);
$constructed_url = $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'];
return $constructed_url;
}
?>
Edit (second full example):
Updated function to make sure scheme will be attached and none notice msgs appear:
function reconstruct_url($url){
$url_parts = parse_url($url);
$constructed_url = $url_parts['scheme'] . '://' . $url_parts['host'] . (isset($url_parts['path'])?$url_parts['path']:'');
return $constructed_url;
}
$test = array(
'http://www.mydomian.com/myurl.html?unwan=abc',
'http://www.mydomian.com/myurl.html',
'http://www.mydomian.com',
'https://mydomian.com/myurl.html?unwan=abc&ab=1'
);
foreach($test as $url){
print_r(parse_url($url));
}
Will return:
Array
(
[scheme] => http
[host] => www.mydomian.com
[path] => /myurl.html
[query] => unwan=abc
)
Array
(
[scheme] => http
[host] => www.mydomian.com
[path] => /myurl.html
)
Array
(
[scheme] => http
[host] => www.mydomian.com
)
Array
(
[path] => mydomian.com/myurl.html
[query] => unwan=abc&ab=1
)
This is the output from passing example urls through parse_url() with no second parameter (for explanation only).
And this is the final output after constructing url using:
foreach($test as $url){
echo reconstruct_url($url) . '<br/>';
}
Output:
http://www.mydomian.com/myurl.html
http://www.mydomian.com/myurl.html
http://www.mydomian.com
https://mydomian.com/myurl.html
For your question as asked
Columns(3).Insert
Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))
If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA
Apple's Technical Q&A QA1509 shows the following simple approach:
CFDataRef CopyImagePixels(CGImageRef inImage)
{
return CGDataProviderCopyData(CGImageGetDataProvider(inImage));
}
Use CFDataGetBytePtr
to get to the actual bytes (and various CGImageGet*
methods to understand how to interpret them).
In my case I had tried to make code more readable by putting:
"LONGTEXTSTRING " +
"LONGTEXTSTRING" +
"LONGTEXTSTRING"
Once I changed it to
LONGTEXTSTRING LONGTEXTSTRING LONGTEXTSTRING
Then it worked
I believe this is a more easy approach:
public class HibernateProxyTypeAdapter implements JsonSerializer<HibernateProxy>{
public JsonElement serialize(HibernateProxy object_,
Type type_,
JsonSerializationContext context_) {
return new GsonBuilder().create().toJsonTree(initializeAndUnproxy(object_)).getAsJsonObject();
// that will convert enum object to its ordinal value and convert it to json element
}
public static <T> T initializeAndUnproxy(T entity) {
if (entity == null) {
throw new
NullPointerException("Entity passed for initialization is null");
}
Hibernate.initialize(entity);
if (entity instanceof HibernateProxy) {
entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer()
.getImplementation();
}
return entity;
}
}
And then you will be able to call it like this:
Gson gson = new GsonBuilder()
.registerTypeHierarchyAdapter(HibernateProxy.class, new HibernateProxyTypeAdapter())
.create();
This way all the hibernate objects will be converted automatically.
The best approach I've found so far is to set a background view of the cell and clear background of cell subviews. Of course, this looks nice on tables with indexed style only, no matter with or without accessories.
Here is a sample where cell's background is panted yellow:
UIView* backgroundView = [ [ [ UIView alloc ] initWithFrame:CGRectZero ] autorelease ];
backgroundView.backgroundColor = [ UIColor yellowColor ];
cell.backgroundView = backgroundView;
for ( UIView* view in cell.contentView.subviews )
{
view.backgroundColor = [ UIColor clearColor ];
}
your varchar col C:
SELECT CONVERT(uniqueidentifier,LEFT(C, 8)
+ '-' +RIGHT(LEFT(C, 12), 4)
+ '-' +RIGHT(LEFT(C, 16), 4)
+ '-' +RIGHT(LEFT(C, 20), 4)
+ '-' +RIGHT(C, 12))
attr_accessor
is getter
, setter
method.
whereas attr_accessible
is to say that particular attribute is accessible or not. that's it.
I wish to add we should use Strong parameter instead of attr_accessible
to protect from mass asignment.
Cheers!
Another way, which I've been using for awhile in XCode3:
See steps 1-15 above.
The nice thing about this way is it will use the same environment to develop in that you would use to run in outside of XCode (as setup from your bash .profile).
It's also generic enough to let you develop/run any type of file, not just python.
PHP is run on a server, Your browser is a client. Once the server sends all the info to the client, nothing can be done on the server until another request is made.
To make another request without refreshing the page you are going to have to look into ajax. Look into jQuery as it makes ajax requests easy
The move
instruction copies a value from one register to another. The li
instruction loads a specific numeric value into that register.
For the specific case of zero, you can use either the constant zero or the zero register to get that:
move $s0, $zero
li $s0, 0
There's no register that generates a value other than zero, though, so you'd have to use li
if you wanted some other number, like:
li $s0, 12345678
Jenkins lets you set up multiple times, separated by line breaks.
If you need it to build daily at 7 am, along with every Sunday at 4 pm, the below works well.
H 7 * * *
H 16 * * 0
NOTE: while this is the accepted answer, it's worth noting that in PHP 5.6+ you can have const arrays - see Andrea Faulds' answer below.
You can also serialize your array and then put it into the constant:
# define constant, serialize array
define ("FRUITS", serialize (array ("apple", "cherry", "banana")));
# use it
$my_fruits = unserialize (FRUITS);
Loading that giant blob of data is not a great plan, but if you must, here's the outline of how you might do it using jQuery's $.ajax()
function.
<html><head>
<script src="jquery.js"></script>
<script>
getTxt = function (){
$.ajax({
url:'text.txt',
success: function (data){
//parse your data here
//you can split into lines using data.split('\n')
//an use regex functions to effectively parse it
}
});
}
</script>
</head><body>
<button type="button" id="btnGetTxt" onclick="getTxt()">Get Text</button>
</body></html>
creating local.properties
file in the root directory solved my issue
I somehow lost this file after pulling from GitHub
this is how my local.properties
file looks like now:
## This file is automatically generated by Android Studio.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#Sat Feb 06 11:53:03 EST 2016
sdk.dir=/Users/****/Library/Android/sdk
I would recommend that you have a look at SUDS
"Suds is a lightweight SOAP python client for consuming Web Services."
on Centos 7, this will do it, for Tomcat 7 : (my tomcat install dir: opt/apache-tomcat-7.0.79)
not sure the log link is necessary, the configuration is the critical one.
:
date("Y-m-d H:i:s"); // This should do it.
press ctrl +B and then You can use the Run button.
There is no concept of multiple inheritance in Java. Only multiple interfaces can be implemented.
PhiLho has mentioned AutoRuns in passing, but I think it deserves elaboration.
It doesn't scan the whole registry, just the parts containing references to things which get loaded automatically (EXEs, DLLs, drivers etc.) which is probably what you are interested in. It doesn't track changes but can export to a text file, so you can run it before and after installation and do a diff.
More simple than that.
List<Integer> arrayIntegers = new ArrayList<>(Arrays.asList(1,2,3));
arrayIntegers.get(1);
In the first line you create the object and in the constructor you pass an array parameter to List.
In the second line you have all the methods of the List class: .get (...)
Junit Rules work on the principle of AOP (aspect oriented programming). It intercepts the test method thus providing an opportunity to do some stuff before or after the execution of a particular test method.
Take the example of the below code:
public class JunitRuleTest {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@Test
public void testRule() throws IOException {
File newFolder = tempFolder.newFolder("Temp Folder");
assertTrue(newFolder.exists());
}
}
Every time the above test method is executed, a temporary folder is created and it gets deleted after the execution of the method. This is an example of an out-of-box rule provided by Junit.
Similar behaviour can also be achieved by creating our own rules. Junit provides the TestRule interface, which can be implemented to create our own Junit Rule.
Here is a useful link for reference:
The old school way ;)
public static void openit(string x) {
System.Diagnostics.Process.Start("cmd", "/C start" + " " + x);
}
Use: openit("www.google.com");
This can also be done in the following way:
JObject data = JObject.Parse(File.ReadAllText(MyFilePath));
time
is a built-in command in most shells that writes execution time information to the tty.
You could also try something like
start_time=`date +%s`
<command-to-execute>
end_time=`date +%s`
echo execution time was `expr $end_time - $start_time` s.
Or in bash
:
start_time=`date +%s`
<command-to-execute> && echo run time is $(expr `date +%s` - $start_time) s
Verified remedy from earlier postings:
1) Checked that the libhadoop.so.1.0.0
shipped with the Hadoop distribution was compiled for my machine architecture, which is x86_64:
[nova]:file /opt/hadoop-2.6.0/lib/native/libhadoop.so.1.0.0
/opt/hadoop-2.6.0/lib/native/libhadoop.so.1.0.0: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=3a80422c78d708c9a1666c1a8edd23676ed77dbb, not stripped
2) Added -Djava.library.path=<path>
to HADOOP_OPT
in hadoop-env.sh
:
export HADOOP_OPTS="$HADOOP_OPTS -Djava.net.preferIPv4Stack=true -Djava.library.path=/opt/hadoop-2.6.0/lib/native"
This indeed made the annoying warning disappear.
Use Integer.toString(tmpInt)
instead.
As of Java 8, some local variable name information is available through reflection. See the "Update" section below.
Complete information is often stored in class files. One compile-time optimization is to remove it, saving space (and providing some obsfuscation). However, when it is is present, each method has a local variable table attribute that lists the type and name of local variables, and the range of instructions where they are in scope.
Perhaps a byte-code engineering library like ASM would allow you to inspect this information at runtime. The only reasonable place I can think of for needing this information is in a development tool, and so byte-code engineering is likely to be useful for other purposes too.
Update: Limited support for this was added to Java 8. Parameter (a special class of local variable) names are now available via reflection. Among other purposes, this can help to replace @ParameterName
annotations used by dependency injection containers.
Thank you for all your answers, Whilst all were correct, none actually solved my problem. The solution for me was to create a second invisible div at the end of the content of unknown length, this invisible div is the same size as my absolutely positioned div, this ensures that there is always a space at the end of my content for the absolutely positioned div.
This answer was previously provided here: Prevent absolutely-positioned elements from overlapping with text However I didn't see (until now) how to apply it to a bottom right positioned div.
New structure is as follows:
<div id="outer" style="position: relative; width:450px; background-color:yellow;">
<p>Content of unknown length</p>
<div>Content of unknown height </div>
<div id="spacer" style="width: 200px; height: 25px; margin-right:0px;"></div>
<div style="position: absolute; right: 0; bottom: 0px; width: 200px; height: 20px; background-color:red;">bottom right</div>
</div>
_x000D_
This seems to solve the issue.
Here
$type='testing' //it's string
mysql_query("INSERT INTO contents (type, reporter, description) VALUES('$type', 'john', 'whatever')");//at that time u can use it(for string)
$type=12 //it's integer
mysql_query("INSERT INTO contents (type, reporter, description) VALUES($type, 'john', 'whatever')");//at that time u can use $type
<?php
$val1 = rand(1,4);
$val2=rand(1,4);
if ($pars[$last0] == "reviews" && $pars[$last] > 0) {
echo widget("Bootstrap Theme - Member Profile - Read Review",'',$w[website_id],$w);
} else { ?>
<div class="w100">
<div style="background:transparent!important;" class="w100 well" id="postreview">
<?php
$_GET[user_id] = $user[user_id];
$_GET[member_id] = $_COOKIE[userid];
$_GET[subaction] = "savereview";
$_GET[ip] = $_SERVER[REMOTE_ADDR];
$_GET[httpr] = $_ENV[requesturl];
echo form("member_review","",$w[website_id],$w);?>
</div></div>
ive replaced the 'else' with '&&' so both are placed ... argh
It acts as curly bracket. We have to keep the number of white spaces consistent through out the program.
Example 1:
def main():
print "we are in main function"
print "print 2nd line"
main()
Result:
We are in main function
print 2nd line
Example 2:
def main():
print "we are in main function"
print "print 2nd line"
main()
Result:
print 2nd line
We are in main function
Here, in the 1st program, both the statement comes under the main function since both have equal number of white spaces while in the 2nd program, the 1st line is printed later because the main function is called after the 2nd line Note - The 2nd line has no white space, so it is independent of the main function.
How about CryptoJS?
It's a solid crypto library, with a lot of functionality. It implements hashers, HMAC, PBKDF2 and ciphers. In this case ciphers is what you need. Check out the quick-start quide on the project's homepage.
You could do something like with the AES:
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
<script>
var encryptedAES = CryptoJS.AES.encrypt("Message", "My Secret Passphrase");
var decryptedBytes = CryptoJS.AES.decrypt(encryptedAES, "My Secret Passphrase");
var plaintext = decryptedBytes.toString(CryptoJS.enc.Utf8);
</script>
As for security, at the moment of my writing AES algorithm is thought to be unbroken
Edit :
Seems online URL is down & you can use the downloaded files for encryption from below given link & place the respective files in your root folder of the application.
https://code.google.com/archive/p/crypto-js/downloads
or used other CDN like https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/aes-min.js
You could use the TimeSpan constructor which takes a long for Ticks:
TimeSpan duration = new TimeSpan(endtime.Ticks - startTime.Ticks);
Ibrahim's comment on the other answer is the correct way to alter an existing user's home directory.
usermod -d /newhome/username username
usermod
is the command to edit an existing user.
-d
(abbreviation for --home
) will change the user's home directory.
usermod -m -d /newhome/username username
-m
(abbreviation for --move-home
) will move the content from the user's current directory to the new directory.
showInventory(player); // I get the error here.
void showInventory(player& obj) { // By Johnny :D
this means that player is an datatype and showInventory expect an referance to an variable of type player.
so the correct code will be
void showInventory(player& obj) { // By Johnny :D
for(int i = 0; i < 20; i++) {
std::cout << "\nINVENTORY:\n" + obj.getItem(i);
i++;
std::cout << "\t\t\t" + obj.getItem(i) + "\n";
i++;
}
}
players myPlayers[10];
std::string toDo() //BY KEATON
{
std::string commands[5] = // This is the valid list of commands.
{"help", "inv"};
std::string ans;
std::cout << "\nWhat do you wish to do?\n>> ";
std::cin >> ans;
if(ans == commands[0]) {
helpMenu();
return NULL;
}
else if(ans == commands[1]) {
showInventory(myPlayers[0]); // or any other index,also is not necessary to have an array
return NULL;
}
}
Adding to Dmitri Chebotarev's answer, as for Laravel 5+.
After requiring the doctrine/dbal package:
composer require doctrine/dbal
You can then make a migration with nullable columns, like so:
public function up()
{
Schema::table('users', function (Blueprint $table) {
// change() tells the Schema builder that we are altering a table
$table->integer('user_id')->unsigned()->nullable()->change();
});
}
To revert the operation, do:
public function down()
{
/* turn off foreign key checks for a moment */
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
/* set null values to 0 first */
DB::statement('UPDATE `users` SET `user_id` = 0 WHERE `user_id` IS NULL;');
/* alter table */
DB::statement('ALTER TABLE `users` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
/* finally turn foreign key checks back on */
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
}
I've spent few hours looking for a nice solution to make my eclipse UI dark, and I have finally found a way to do it. I am using Fedora 18 and Eclipse for PHP Developers (PDT v3.0.2).
The nicest solution is to download DeLorean Dark Theme then enabling it in Gnome Shell.
Installation procedure:
Here is what it looks like: http://i.stack.imgur.com/Xx7m6.png
This procedure is for Eclipse PHP and Aptana 3. If you are using Eclipse 4 and higher, I recommend DeLorean Dark Theme for eclipse: http:// goo [DOT] gl/wkjj8
You can change default options by using Chart.defaults.global
in your javascript file. So you want to change legend and tooltip options.
Chart.defaults.global.legend.display = false;
Chart.defaults.global.tooltips.enabled = false;
Here is a working fiddler.
There is a brilliant blog post from Taiseer Joudeh with a detailed step-by-step description.
Your sum
v1 + (incident edges) + v2 + (incident edges) + .... + vn + (incident edges)
can be rewritten as
(v1 + v2 + ... + vn) + [(incident_edges v1) + (incident_edges v2) + ... + (incident_edges vn)]
and the first group is O(N)
while the other is O(E)
.
Toolbar actionBar = (Toolbar)findViewById(R.id.toolbar);
actionBar.addView(view);
setSupportActionBar(actionBar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
take note of this line getSupportActionBar().setDisplayShowTitleEnabled(false);
First we install the Microsoft.EntityFrameworkCore.SqlServer NuGet Package:
PM > Install-Package Microsoft.EntityFrameworkCore.SqlServer
Then, after importing the namespace with
using Microsoft.EntityFrameworkCore;
we add the database context:
services.AddDbContext<AspDbContext>(options =>
options.UseSqlServer(config.GetConnectionString("optimumDB")));
You can use the package called substring
. Just install using the command pip install substring
. You can get the substring by just mentioning the start and end characters/indices.
For example:
import substring
s = substring.substringByChar("abcdefghijklmnop", startChar="d", endChar="n")
print(s)
Output:
# s = defghijklmn
Retrieve the ID of the current item in the WordPress Loop.
echo get_the_ID();
hence works for the product id too. #tested #woo-commerce
You could try qemu, which is what the Android emulator uses. I believe it actually emulates the ARM hardware.
You can target that div from your stylesheet in a number of ways.
Simply use
.col-md-6:first-child {
background-color: blue;
}
Another way is to assign a class to one div and then apply the style to that class.
<div class="col-md-6 blue"></div>
.blue {
background-color: blue;
}
There are also inline styles.
<div class="col-md-6" style="background-color: blue"></div>
Your example code works fine to me. I'm not sure if I undestand what you intend to do, but if you want a blue background on the second div just remove the bg-primary
class from the section and add you custom class to the div.
.blue {_x000D_
background-color: blue;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<section id="about">_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<!-- Columns are always 50% wide, on mobile and desktop -->_x000D_
<div class="col-xs-6">_x000D_
<h2 class="section-heading text-center">Title</h2>_x000D_
<p class="text-faded text-center">.col-md-6</p>_x000D_
</div>_x000D_
<div class="col-xs-6 blue">_x000D_
<h2 class="section-heading text-center">Title</h2>_x000D_
<p class="text-faded text-center">.col-md-6</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</section>
_x000D_
This might be a memmory issue on mysql try to increase max_allowed_packet in my.ini
If you have root, delete all of the folders on the path:
/data/app-lib/
And then restart your device.
I had this issue many times, and this fix worked for me each time. It even has an XDA thread.
I write all folders, because if there is a problem with one app, there is a good chance you have this issue with other apps too. Plus, it's annoying to find just the folders of the problematic app/s .
If you do not want the program to close even if a user presses anykey;
while (true) {
System.Console.ReadKey();
};//This wont stop app
Partly, because Go doesn't have generics (so you would need one set-type for every type, or fall back on reflection, which is rather inefficient).
Partly, because if all you need is "add/remove individual elements to a set" and "relatively space-efficient", you can get a fair bit of that simply by using a map[yourtype]bool
(and set the value to true
for any element in the set) or, for more space efficiency, you can use an empty struct as the value and use _, present = the_setoid[key]
to check for presence.
Here is a solution that works for me. It involves radio button binding--but not binding to business data, but instead, binding to the state of the radio button. It is probably NOT the best solution for new projects, but is appropriate for my project. My project has a ton of existing code written in a different technology which I am porting to Angular. The old code follows a pattern in which the code is very interested in examining each radio button to see if it is the selected one. The solution is a variation of the click handler solutions, some of which have already been mentioned on Stack Overflow. The value added of this solution may be:
- Works with the pattern of old code that I have to work with.
- I created a helper class to try to reduce the number of "if" statements in the click handler, and to handle any group of radio buttons.
This solution involves
- Using a different model for each radio button.
- Setting the "checked" attribute with the radio button's model.
- Passing the model of the clicked radio button to the helper class.
- The helper class makes sure the models are up-to-date.
- At "submit time" this allows the old code to examine the state of the radio buttons to see which one is selected by examining the models.
Example:
<input type="radio"
[checked]="maleRadioButtonModel.selected"
(click)="radioButtonGroupList.selectButton(maleRadioButtonModel)"
...
<input type="radio"
[checked]="femaleRadioButtonModel.selected"
(click)="radioButtonGroupList.selectButton(femaleRadioButtonModel)"
...
When the user clicks a radio button, the selectButton method of the helper class gets invoked. It is passed the model for the radio button that got clicked. The helper class sets the boolean "selected" field of the passed in model to true, and sets the "selected" field of all the other radio button models to false.
During initialization the component must construct an instance of the helper class with a list of all radio button models in the group. In the example, "radioButtonGroupList" would be an instance of the helper class whose code is:
import {UIButtonControlModel} from "./ui-button-control.model";
export class UIRadioButtonGroupListModel {
private readonly buttonList : UIButtonControlModel[];
private readonly debugName : string;
constructor(buttonList : UIButtonControlModel[], debugName : string) {
this.buttonList = buttonList;
this.debugName = debugName;
if (this.buttonList == null) {
throw new Error("null buttonList");
}
if (this.buttonList.length < 2) {
throw new Error("buttonList has less than 2 elements")
}
}
public selectButton(buttonToSelect : UIButtonControlModel) : void {
let foundButton : boolean = false;
for(let i = 0; i < this.buttonList.length; i++) {
let oneButton : UIButtonControlModel = this.buttonList[i];
if (oneButton === buttonToSelect) {
oneButton.selected = true;
foundButton = true;
} else {
oneButton.selected = false;
}
}
if (! foundButton) {
throw new Error("button not found in buttonList");
}
}
}
There is no need for any External libraries, the JRE System libraries provide all you need.
I am infering that you have a org.w3c.dom.Document
object you would like to write to a file
To do that, you use a javax.xml.transform.Transformer
:
import org.w3c.dom.Document
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class XMLWriter {
public static void writeDocumentToFile(Document document, File file) {
// Make a transformer factory to create the Transformer
TransformerFactory tFactory = TransformerFactory.newInstance();
// Make the Transformer
Transformer transformer = tFactory.newTransformer();
// Mark the document as a DOM (XML) source
DOMSource source = new DOMSource(document);
// Say where we want the XML to go
StreamResult result = new StreamResult(file);
// Write the XML to file
transformer.transform(source, result);
}
}
Source: http://docs.oracle.com/javaee/1.4/tutorial/doc/JAXPXSLT4.html
Professional Excel Development has a pretty good error handling scheme. If you're going to spend any time in VBA, it's probably worth getting the book. There are a number of areas where VBA is lacking and this book has good suggestions for managing those areas.
PED describes two error handling methods. The main one is a system where all entry point procedures are subprocedures and all other procedures are functions that return Booleans.
The entry point procedure use On Error statements to capture errors pretty much as designed. The non-entry point procedures return True if there were no errors and False if there were errors. Non-entry point procedures also use On Error.
Both types of procedures use a central error handling procedure to keep the error in state and to log the error.
n = eval(input('Num books: '))
books = {}
for i in range(n):
titlez = input("Enter Title: ")
copy = eval(input("Num of copies: "))
books[titlez] = copy
prob = input('Sell a book; enter YES or NO: ')
if prob == 'YES' or 'yes':
choice = input('Enter book title: ')
if choice in books:
init_num = books[choice]
init_num -= 1
books[choice] = init_num
print(books)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "USER_ID")
Long userId;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
List<Notification> sender;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
List<Notification> receiver;
}
public class Notification implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "NOTIFICATION_ID")
Long notificationId;
@Column(name = "TEXT")
String text;
@Column(name = "ALERT_STATUS")
@Enumerated(EnumType.STRING)
AlertStatus alertStatus = AlertStatus.NEW;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "SENDER_ID")
@JsonIgnore
User sender;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "RECEIVER_ID")
@JsonIgnore
User receiver;
}
What I understood from the answer. mappedy="sender" value should be the same in the notification model. I will give you an example..
User model:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "**sender**", cascade = CascadeType.ALL)
List<Notification> sender;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "**receiver**", cascade = CascadeType.ALL)
List<Notification> receiver;
Notification model:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
List<Notification> **sender**;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
List<Notification> **receiver**;
I gave bold font to user model and notification field. User model mappedBy="sender " should be equal to notification List sender; and mappedBy="receiver" should be equal to notification List receiver; If not, you will get error.