Yes, datepicker supports max date property.
$("#datepickeraddcustomer").datepicker({
dateFormat: "yy-mm-dd",
maxDate: new Date()
});
this worked for me.
$(document).ready(function () {
$("#datePicker").datetimepicker({
format: 'DD/MM/YYYY HH:mm:ss',
defaultDate: new Date(),
});
}
here are the CDN links
<!-- datetime picker -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/3.1.4/css/bootstrap-datetimepicker.min.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/3.1.4/js/bootstrap-datetimepicker.min.js"></script>
Here's what I'm using:
$('input.date').datepicker({
beforeShow: function(input, inst) {
inst.dpDiv.css({
marginTop: -input.offsetHeight + 'px',
marginLeft: input.offsetWidth + 'px'
});
}
});
You may also want to add a bit more to the left margin so it's not right up against the input field.
$('div#someID').datepicker({
onSelect: function(dateText, inst) { alert(dateText); }
});
you must bind it to input element only
Note: When you pass setDate, you are calling a method which assumes the datepicker has already been initialized on that object.
$(function() {
$('#date').datepicker();
$('#date').datepicker('setDate', '04/23/2014');
});
Instead of parsing day, month and year you can specify date formats directly using datepicker's formatDate function. In my example I am using "yy-mm-dd", but you can use any format of your choice.
$("#datepicker").datepicker({
dateFormat: 'yy-mm-dd',
inline: true,
minDate: new Date(2010, 1 - 1, 1),
maxDate: new Date(2010, 12 - 1, 31),
altField: '#datepicker_value',
onSelect: function(){
var fullDate = $.datepicker.formatDate("yy-mm-dd", $(this).datepicker('getDate'));
var str_output = "<h1><center><img src=\"/images/a" + fullDate +".png\"></center></h1><br/><br>";
$('#page_output').html(str_output);
}
});
Seeing that:
Set the date to highlight on first opening if the field is blank. Specify either an actual date via a Date object or as a string in the current dateFormat, or a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null for today.
If the current dateFormat is not recognized, you can still use the Date object using new Date(year, month, day)
In your example, this should work (I didn't test it) :
<script type="text/javascript">
$(function() {
$("#birthdate" ).datepicker({
changeMonth: true,
changeYear: true,
yearRange: '1920:2010',
dateFormat : 'dd-mm-yy',
defaultDate: new Date(1985,01,01)
});
});
</script>
If you want to disable particular date(s) in jquery datepicker then here is the simple demo for you.
<script type="text/javascript">
var arrDisabledDates = {};
arrDisabledDates[new Date("08/28/2017")] = new Date("08/28/2017");
arrDisabledDates[new Date("12/23/2017")] = new Date("12/23/2017");
$(".datepicker").datepicker({
dateFormat: "dd/mm/yy",
beforeShowDay: function (date) {
var day = date.getDay(),
bDisable = arrDisabledDates[date];
if (bDisable)
return [false, "", ""]
}
});
</script>
I was stuck on an issue where datepicker() appeared to be doing nothing. It turned out that the issue was that the input was inside a Bootstrap "input-group" div. Simply taking the input out of the input-group resolved the issue.
Waht about: http://www.mattkruse.com/javascript/calendarpopup/
Select the month-select example
You can use the minDate
property, like this:
$("input.DateFrom").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd',
minDate: 0, // 0 days offset = today
maxDate: 'today',
onSelect: function(dateText) {
$sD = new Date(dateText);
$("input#DateTo").datepicker('option', 'minDate', min);
}
});
You can also specify a date, like this:
minDate: new Date(), // = today
Code:
var date = new Date('2011', '01', '02');_x000D_
alert('the original date is ' + date);_x000D_
var newdate = new Date(date);_x000D_
_x000D_
newdate.setDate(newdate.getDate() - 7); // minus the date_x000D_
_x000D_
var nd = new Date(newdate);_x000D_
alert('the new date is ' + nd);
_x000D_
Using Datepicker:
$("#in").datepicker({
minDate: 0,
onSelect: function(dateText, inst) {
var actualDate = new Date(dateText);
var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+1);
$('#out').datepicker('option', 'minDate', newDate );
}
});
$("#out").datepicker();?
Extra stuff that might come handy:
getDate() Returns the day of the month (from 1-31)
getDay() Returns the day of the week (from 0-6)
getFullYear() Returns the year (four digits)
getHours() Returns the hour (from 0-23)
getMilliseconds() Returns the milliseconds (from 0-999)
getMinutes() Returns the minutes (from 0-59)
getMonth() Returns the month (from 0-11)
getSeconds() Returns the seconds (from 0-59)
Good link: MDN Date
In case you are looking for datepicker in spanish (datepicker en español)
<script type="text/javascript">
$.datepicker.regional['es'] = {
monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
dayNames: ['Domingo', 'Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'Sabado'],
dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'Sab'],
dayNamesMin: ['Do', 'Lu', 'Ma', 'Mc', 'Ju', 'Vi', 'Sa']
}
$.datepicker.setDefaults($.datepicker.regional['es']);
</script>
The string $.datepicker.regional['it']
not translate all words.
For translate the datepicker you must specify some variables:
$.datepicker.regional['it'] = {
closeText: 'Chiudi', // set a close button text
currentText: 'Oggi', // set today text
monthNames: ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno', 'Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'], // set month names
monthNamesShort: ['Gen','Feb','Mar','Apr','Mag','Giu','Lug','Ago','Set','Ott','Nov','Dic'], // set short month names
dayNames: ['Domenica','Lunedì','Martedì','Mercoledì','Giovedì','Venerdì','Sabato'], // set days names
dayNamesShort: ['Dom','Lun','Mar','Mer','Gio','Ven','Sab'], // set short day names
dayNamesMin: ['Do','Lu','Ma','Me','Gio','Ve','Sa'], // set more short days names
dateFormat: 'dd/mm/yy' // set format date
};
$.datepicker.setDefaults($.datepicker.regional['it']);
$(".datepicker").datepicker();
In this case your datepicker is properly translated.
For Saturday and Sunday You can do something like this
$('#orderdate').datepicker({
daysOfWeekDisabled: [0,6]
});
Check that the date you are trying to set it to lies within the allowed date range if the minDate or maxDate options are set.
Here's one specific for your code:
var date = $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' }).val();
More general info available here:
Are u using this datepicker http://jqueryui.com/demos/datepicker/ ? if yes there are options to set the default Date.If you didn't change anything , by default it will show the current date.
any way this will gives current date
$( ".selector" ).datepicker({ defaultDate: new Date() });
Getting Started Install from npm:
npm install imask And import or require:
import IMask from 'imask';
or use CDN:
var dateMask = IMask(element, {
mask: Date, // enable date mask
// other options are optional
pattern: 'Y-`m-`d', // Pattern mask with defined blocks, default is 'd{.}`m{.}`Y'
// you can provide your own blocks definitions, default blocks for date mask are:
blocks: {
d: {
mask: IMask.MaskedRange,
from: 1,
to: 31,
maxLength: 2,
},
m: {
mask: IMask.MaskedRange,
from: 1,
to: 12,
maxLength: 2,
},
Y: {
mask: IMask.MaskedRange,
from: 1900,
to: 9999,
}
},
// define date -> str convertion
format: function (date) {
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (day < 10) day = "0" + day;
if (month < 10) month = "0" + month;
return [year, month, day].join('-');
},
// define str -> date convertion
parse: function (str) {
var yearMonthDay = str.split('-');
return new Date(yearMonthDay[0], yearMonthDay[1] - 1, yearMonthDay[2]);
},
// optional interval options
min: new Date(2000, 0, 1), // defaults to `1900-01-01`
max: new Date(2020, 0, 1), // defaults to `9999-01-01`
autofix: true, // defaults to `false`
// also Pattern options can be set
lazy: false,
// and other common options
overwrite: true // defaults to `false`
});
I had the same problem using JQuery-UI 1.8.21, and JQuery-UI 1.8.22.
Problem was because I had two DatePicker script, one embedded with jquery-ui-1.8.22.custom.min.js and another one in jquery.ui.datepicker.js (an old version before I upgrade to 1.8.21).
Deleting the duplicate jquery.ui.datepicker.js, resolve problem for both 1.8.21 and 1.8.22.
This is a bit late in the day for suggesting this, given how long ago the original question was posted, but this is what I did.
I needed a range of 70 years, which, while not as much as 100, is still too many years for the visitor to scroll through. (jQuery does step through year in groups, but that's a pain in the patootie for most people.)
The first step was to modify the JavaScript for the datepicker widget: Find this code in jquery-ui.js or jquery-ui-min.js (where it will be minimized):
for (a.yearshtml+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+y+".datepicker._selectMonthYear('#"+
a.id+"', this, 'Y');\" onclick=\"DP_jQuery_"+y+".datepicker._clickMonthYear('#"+a.id+"');\">";b<=g;b++)
a.yearshtml+='<option value="'+b+'"'+(b==c?' selected="selected"':"")+">"+b+"</option>";
a.yearshtml+="</select>";
And replace it with this:
a.yearshtml+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+y+
".datepicker._selectMonthYear('#"+a.id+"', this, 'Y');
\" onclick=\"DP_jQuery_"+y+".datepicker._clickMonthYear('#"+a.id+"');
\">";
for(opg=-1;b<=g;b++) {
a.yearshtml+=((b%10)==0 || opg==-1 ?
(opg==1 ? (opg=0, '</optgroup>') : '')+
(b<(g-10) ? (opg=1, '<optgroup label="'+b+' >">') : '') : '')+
'<option value="'+b+'"'+(b==c?' selected="selected"':"")+">"+b+"</option>";
}
a.yearshtml+="</select>";
This surrounds the decades (except for the current) with OPTGROUP tags.
Next, add this to your CSS file:
.ui-datepicker OPTGROUP { font-weight:normal; }
.ui-datepicker OPTGROUP OPTION { display:none; text-align:right; }
.ui-datepicker OPTGROUP:hover OPTION { display:block; }
This hides the decades until the visitor mouses over the base year. Your visitor can scroll through any number of years quickly.
Feel free to use this; just please give proper attribution in your code.
you have to declare current date into variables like this
$(function() {
var date = new Date();
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var currentYear = date.getFullYear();
$('#datepicker').datepicker({
minDate: new Date(currentYear, currentMonth, currentDate)
});
})
$(function()
{
$('.date-pick').datePicker().val(new Date().asString()).trigger('change');
});
Source: http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/datePickerDefaultToday.html
Just in case if for example you need to put a min date, the last 3 months and max date next 3 months
$('#id_your_date').datepicker({
maxDate: '+3m',
minDate: '-3m'
});
$(".datepicker").datepicker({maxDate: '0'});
This will set the maxDate to +0 days from the current date (i.e. today). See:
<script type="text/javascript">
$(document).ready(function () {
$("#txtDate").datepicker({ dateFormat: 'yy/mm/dd' }).datepicker("setDate", "0");
$("#txtDate2").datepicker({ dateFormat: 'yy/mm/dd', }).datepicker("setDate", new Date().getDay+15); }); </script>
Destroy the datepicker's instance when you don't want it and create new instance whenever necessary.
I know this is ugly but only this seems to be working...
$("#ddlSearchType").change(function () {
if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date") {
$("#txtSearch").datepicker();
}
else {
$("#txtSearch").datepicker("destroy");
}
});
Using bootstrap multi select
Ajax
function() { $.ajax({
type : "get",
url : "OperatorController",
data : "input=" + $('#province').val(),
success : function(msg) {
var arrayOfObjects = eval(msg);
$("#operators").multiselect('dataprovider',
arrayOfObjects);
// $('#output').append(obj);
},
dataType : 'text'
});}
}
In Servlet
request.getParameter("input")
If you want to display links coming from your state or store in Vue 2.0, you can do like this:
<a v-bind:href="''">
{{ url_link }}
</a>
If Bool1 And Bool2 Then
Evaluates both Bool1 and Bool2
If Bool1 AndAlso Bool2 Then
Evaluates Bool2 if and only if Bool1 is true.
The function JSON.stringify will turn your json object into a string:
var jsonAsString = JSON.stringify(obj);
In case the browser does not implement it (IE6/IE7), use the JSON2.js script. It's safe as it uses the native implementation if it exists.
No, there are no dictionaries in php. The closest thing you have is an array. However, an array is different than a dictionary in that arrays have both an index and a key. Dictionaries only have keys and no index. What do I mean by that?
$array = array(
"foo" => "bar",
"bar" => "foo"
);
// as of PHP 5.4
$array = [
"foo" => "bar",
"bar" => "foo",
];
The following line is allowed with the above array but would give an error if it was a dictionary.
print $array[0]
Python has both arrays and dictionaries.
If you are using a UNIX system, you could do
git log|grep "Author"|wc -l
There are two solutions posted on that page. The one with lower votes I would recommend if possible.
If you are using HTML5 then it is perfectly valid to put a div
inside of a
. As long as the div doesn't also contain some other specific elements like other link tags.
<a href="Music.html">
<div id="music" class="nav">
Music I Like
</div>
</a>
The solution you are confused about actually makes the link as big as its container div. To make it work in your example you just need to add position: relative
to your div. You also have a small syntax error which is that you have given the span a class instead of an id. You also need to put your span inside the link because that is what the user is clicking on. I don't think you need the z-index
at all from that example.
div { position: relative; }
.hyperspan {
position:absolute;
width:100%;
height:100%;
left:0;
top:0;
}
<div id="music" class="nav">Music I Like
<a href="http://www.google.com">
<span class="hyperspan"></span>
</a>
</div>
When you give absolute
positioning to an element it bases its location and size after the first parent it finds that is relatively positioned. If none, then it uses the document. By adding relative
to the parent div you tell the span to only be as big as that.
Don't run with a space between the directory and the filename:
python /root/Desktop/1 hello.py
Use a /
instead:
python /root/Desktop/1/hello.py
Yes.
It is a good practice since an element can be a part of different groups, and you may want specific elements to be a part of more than one group. The element can hold an infinite number of classes in HTML5, while in HTML4 you are limited by a specific length.
The following example will show you the use of multiple classes.
The first class makes the text color
red.
The second class makes the background-color
blue.
See how the DOM Element with multiple classes will behave, it will wear both CSS statements at the same time.
Result: multiple CSS statements in different classes will stack up.
You can read more about CSS Specificity.
.class1 {
color:red;
}
.class2 {
background-color:blue;
}
<div class="class1">text 1</div>
<div class="class2">text 2</div>
<div class="class1 class2">text 3</div>
Not sure what you table structure is like but see below.
public NamePriceModel[] AllProducts()
{
try
{
using (UserDataDataContext db = new UserDataDataContext())
{
return db.mrobProducts
.Where(x => x.Status == 1)
.Select(x => new NamePriceModel {
Name = x.Name,
Id = x.Id,
Price = x.Price
})
.OrderBy(x => x.Id)
.ToArray();
}
}
catch
{
return null;
}
}
This would return an array of type anonymous with the members you require.
Update:
Create a new class.
public class NamePriceModel
{
public string Name {get; set;}
public decimal? Price {get; set;}
public int Id {get; set;}
}
I've modified the query above to return this as well and you should change your method from returning string[]
to returning NamePriceModel[]
.
@article = user.articles.build(:title => "MainTitle")
@article.save
You have various possibilies. The most simple and the most ugly is:
XAML
<Button Name="cmdCommand" Click="Button_Clicked" Content="Command"/>
Code Behind
private void Button_Clicked(object sender, RoutedEventArgs e) {
FrameworkElement fe=sender as FrameworkElement;
((YourClass)fe.DataContext).DoYourCommand();
}
Another solution (better) is to provide a ICommand-property on your YourClass
. This command will have already a reference to your YourClass
-object and therefore can execute an action on this class.
XAML
<Button Name="cmdCommand" Command="{Binding YourICommandReturningProperty}" Content="Command"/>
Because during writing this answer, a lot of other answers were posted, I stop writing more. If you are interested in one of the ways I showed or if you think I have made a mistake, make a comment.
More of a comment link for suggested further reading...A really good blog article which benchmarks various ways of accomplishing this task can be found here.
They use a few techniques: "Insert Where Not Exists", "Merge" statement, "Insert Except", and your typical "left join" to see which way is the fastest to accomplish this task.
The example code used for each technique is as follows (straight copy/paste from their page) :
INSERT INTO #table1 (Id, guidd, TimeAdded, ExtraData)
SELECT Id, guidd, TimeAdded, ExtraData
FROM #table2
WHERE NOT EXISTS (Select Id, guidd From #table1 WHERE #table1.id = #table2.id)
-----------------------------------
MERGE #table1 as [Target]
USING (select Id, guidd, TimeAdded, ExtraData from #table2) as [Source]
(id, guidd, TimeAdded, ExtraData)
on [Target].id =[Source].id
WHEN NOT MATCHED THEN
INSERT (id, guidd, TimeAdded, ExtraData)
VALUES ([Source].id, [Source].guidd, [Source].TimeAdded, [Source].ExtraData);
------------------------------
INSERT INTO #table1 (id, guidd, TimeAdded, ExtraData)
SELECT id, guidd, TimeAdded, ExtraData from #table2
EXCEPT
SELECT id, guidd, TimeAdded, ExtraData from #table1
------------------------------
INSERT INTO #table1 (id, guidd, TimeAdded, ExtraData)
SELECT #table2.id, #table2.guidd, #table2.TimeAdded, #table2.ExtraData
FROM #table2
LEFT JOIN #table1 on #table1.id = #table2.id
WHERE #table1.id is null
It's a good read for those who are looking for speed! On SQL 2014, the Insert-Except method turned out to be the fastest for 50 million or more records.
Use a Comparator:
List<CustomObject> list = new ArrayList<CustomObject>();
Comparator<CustomObject> comparator = new Comparator<CustomObject>() {
@Override
public int compare(CustomObject left, CustomObject right) {
return left.getId() - right.getId(); // use your logic
}
};
Collections.sort(list, comparator); // use the comparator as much as u want
System.out.println(list);
Additionally, if CustomObject
implements Comparable
, then just use Collections.sort(list)
List<CustomObject> list = getCustomObjectList();
Collections.sort(list, (left, right) -> left.getId() - right.getId());
System.out.println(list);
Much simplier
List<CustomObject> list = getCustomObjectList();
list.sort((left, right) -> left.getId() - right.getId());
System.out.println(list);
Simplest
List<CustomObject> list = getCustomObjectList();
list.sort(Comparator.comparing(CustomObject::getId));
System.out.println(list);
Obviously the initial code can be used for JDK 8 too.
The basic difference :
Linear regression is basically a regression model which means its will give a non discreet/continuous output of a function. So this approach gives the value. For example : given x what is f(x)
For example given a training set of different factors and the price of a property after training we can provide the required factors to determine what will be the property price.
Logistic regression is basically a binary classification algorithm which means that here there will be discreet valued output for the function . For example : for a given x if f(x)>threshold classify it to be 1 else classify it to be 0.
For example given a set of brain tumour size as training data we can use the size as input to determine whether its a benine or malignant tumour. Therefore here the output is discreet either 0 or 1.
*here the function is basically the hypothesis function
API's are a published interface which defines how component A communicates with component B.
For example, Doubleclick have a published Java API which allows users to interrogate the database tables to get information about their online advertising campaign.
e.g. call GetNumberClicks (user name)
To implement the API, you have to add the Doubleclick .jar file to your class path. The call is local.
A web service is a form of API where the interface is defined by means of a WSDL. This allows remote calling of an interface over HTTP.
If Doubleclick implemented their interface as a web service, they would use something like Axis2 running inside Tomcat.
The remote user would call the web service
e.g. call GetNumberClicksWebService (user name)
and the GetNumberClicksWebService service would call GetNumberClicks locally.
If you are using Perforce (imported the project as a Perforce project), then .cproject and .project will be located under the root of the PERFORCE project, not on the workspace folder.
Hope this helps :)
$( "#dialogueForm" ).dialog({
autoOpen: false,
height: "auto",
width: "auto",
modal: true,
my: "center",
at: "center",
of: window,
close : function(){
// functionality goes here
}
});
"close" property of dialog gives the close event for the same.
In addition, for those looking to replace more than one character in a column, you can do it using regular expressions:
import re
chars_to_remove = ['.', '-', '(', ')', '']
regular_expression = '[' + re.escape (''. join (chars_to_remove)) + ']'
df['string_col'].str.replace(regular_expression, '', regex=True)
@Repository @Service and @Controller are serves as specialization of @Component for more specific use on that basis you can replace @Service to @Component but in this case you loose the specialization.
1. **@Repository** - Automatic exception translation in your persistence layer.
2. **@Service** - It indicates that the annotated class is providing a business service to other layers within the application.
x<-quantile(retentiondata$sum_dec_incr,c(0.01,0.99))
data_clean <- data[data$attribute >=x[1] & data$attribute<=x[2],]
I find this very easy to remove outliers. In the above example I am just extracting 2 percentile to 98 percentile of attribute values.
raw_input
returns a string (a sequence of characters). In Python, multiplying a string and a float makes no defined meaning (while multiplying a string and an integer has a meaning: "AB" * 3
is "ABABAB"
; how much is "L" * 3.14
? Please do not reply "LLL|"
). You need to parse the string to a numerical value.
You might want to try:
salesAmount = float(raw_input("Insert sale amount here\n"))
That's a case where you should use if
clauses.
You need to do this:
OleDbConnection connection = new OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Inventar.accdb");
DataSet DS = new DataSet();
connection.Open();
string query =
@"SELECT tbl_Computer.*, tbl_Besitzer.*
FROM tbl_Computer
INNER JOIN tbl_Besitzer ON tbl_Computer.FK_Benutzer = tbl_Besitzer.ID
WHERE (((tbl_Besitzer.Vorname)='ma'))";
OleDbDataAdapter DBAdapter = new OleDbDataAdapter();
DBAdapter.SelectCommand = new OleDbCommand(query, connection);
DBAdapter.Fill(DS);
By the way, what is this DataSet1? This should be "DataSet".
You just need to add proper name space in your root tag . xmlns:android="http://schemas.android.com/apk/res/android" Android elemets are declared in this name space.Its same as importing class or package.
Does document.getElementById("blue") exist? if it doesn't then blue_box will be equal to null. you can't set a onclick on something that's null
For all those recommending using table variables, be cautious in doing so. Table variable cannot be indexed whereas a temp table can be. A table variable is best when working with small amounts of data but if you are working on larger sets of data (e.g. 50k records) a temp table will be much faster than a table variable.
Also keep in mind that you can't rely on a try/catch to force a cleanup within the stored procedure. certain types of failures cannot be caught within a try/catch (e.g. compile failures due to delayed name resolution) if you want to be really certain you may need to create a wrapper stored procedure that can do a try/catch of the worker stored procedure and do the cleanup there.
e.g. create proc worker AS BEGIN -- do something here END
create proc wrapper AS
BEGIN
Create table #...
BEGIN TRY
exec worker
exec worker2 -- using same temp table
-- etc
END TRY
END CATCH
-- handle transaction cleanup here
drop table #...
END CATCH
END
One place where table variables are always useful is they do not get rolled back when a transaction is rolled back. This can be useful for capturing debug data that you want to commit outside the primary transaction.
To add to all the Awesome work started by Luke I am posting one more that takes a css class value and treats class and alt as optional parameters (valid under ASP.NET 3.5+). This will allow more functionality but reduct the number of overloaded methods needed.
// Extension method
public static MvcHtmlString ActionImage(this HtmlHelper html, string action,
string controllerName, object routeValues, string imagePath, string alt = null, string cssClass = null)
{
var url = new UrlHelper(html.ViewContext.RequestContext);
// build the <img> tag
var imgBuilder = new TagBuilder("img");
imgBuilder.MergeAttribute("src", url.Content(imagePath));
if(alt != null)
imgBuilder.MergeAttribute("alt", alt);
if (cssClass != null)
imgBuilder.MergeAttribute("class", cssClass);
string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);
// build the <a> tag
var anchorBuilder = new TagBuilder("a");
anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(anchorHtml);
}
If you're comparing different branches, you need to use --
to separate a Git revision from a filesystem path. For example, with two local branches, master
and bryan-working
:
$ git diff master -- AFolderOfCode/ bryan-working -- AFolderOfCode/
Or from a local branch to a remote:
$ git diff master -- AFolderOfCode/ origin/master -- AFolderOfCode/
In my case I have moved plugins folder mistakenly to another folder while taking backup of my unnecessary projects. Then while I was trying to run the eclipse.exe I was getting the error-
The Eclipse executable launcher was unable to locate its companion shared library.
I have simply copied the plugins folder to eclipse root directory, and it was working fine for me.
If you have the folders backup in your computer then just copy and paste the folders on eclipse directory, you don't need to reinstall or change the ini file so far I realized.
It would be nice if CheckStyle could verify that the serialVersionUID on a class that implements Serializable has a good value, i.e. that it matches what the serial version id generator would produce. If you have a project with lots of serializable DTOs, for example, remembering to delete the existing serialVersionUID and regenerate it is a pain, and currently the only way (that I know of) to verify this is to regenerate for each class and compare to the old one. This is very very painful.
According to pyodbc documentation, connections to the SQL server are not closed by default. Some database drivers do not close connections when close() is called in order to save round-trips to the server.
To close your connection when you call close() you should set pooling to False:
import pyodbc
pyodbc.pooling = False
Here I am Considering multiple cases through which you can clearify the concept
1. ArrayList<String> arr = new ArrayList<String>();
2. ArrayList<String> arr = new ArrayList();
3. ArrayList arr = new ArrayList<String>();
ArrayList<String> arr
it is a ArrayList
reference variable with type String
which reference to a ArralyList
Object of Type String
. It means it can hold only String type Object.
It is a Strict to String
not a Raw Type so, It will never raise an warning .
arr.add("hello");// alone statement will compile successfully and no warning.
arr.add(23); //prone to compile time error.
//error: no suitable method found for add(int)
In this case ArrayList<String> arr
is a strict type but your Object new ArrayList();
is a raw type.
arr.add("hello"); //alone this compile but raise the warning.
arr.add(23); //again prone to compile time error.
//error: no suitable method found for add(int)
here arr
is a Strict type. So, It will raise compile time error when adding a integer
.
Warning :- A
Raw
Type Object is referenced to aStrict
type Referenced Variable ofArrayList
.
In this case ArrayList arr
is a raw type but your Object new ArrayList<String>();
is a Strict type.
arr.add("hello");
arr.add(23); //compiles fine but raise the warning.
It will add any type of Object into it because arr
is a Raw Type.
Warning :- A
Strict
Type Object is referenced to araw
type referenced Variable.
If your input always has a time zone of "zulu" ("Z" = UTC), then you can use DateTimeFormatter.ISO_INSTANT
(implicitly):
final Instant parsed = Instant.parse(dateTime);
If time zone varies and has the form of "+01:00" or "+01:00:00" (when not "Z"), then you can use DateTimeFormatter.ISO_OFFSET_DATE_TIME
:
DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final ZonedDateTime parsed = ZonedDateTime.parse(dateTime, formatter);
If neither is the case, you can construct a DateTimeFormatter
in the same manner as DateTimeFormatter.ISO_OFFSET_DATE_TIME
is constructed.
Your current pattern has several problems:
ResolverStyle.STRICT
);yyyy
instead of uuuu
(yyyy
will not work in strict mode);hh
instead of 24-hour HH
;S
for fractional seconds, but input has three.If you are managing the Hibernate session manually, you may want to look into sessionFactory.getCurrentSession() and associated docs here:
http://www.hibernate.org/hib_docs/v3/reference/en/html/architecture-current-session.html
maven-compiler-plugin it's already present in plugins hierarchy dependency in pom.xml. Check in Effective POM.
For short you can use properties like this:
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
I'm using Maven 3.2.5.
File
--> Setting
project
section --> Project interpreter
Project interpreter
[NOTE]:
Tested on Pycharm 2018 and 2017.
I get the same error in Chrome after pasting code copied from jsfiddle.
If you select all the code from a panel in jsfiddle and paste it into the free text editor Notepad++, you should be able to see the problem character as a question mark "?" at the very end of your code. Delete this question mark, then copy and paste the code from Notepad++ and the problem will be gone.
I would use
def example(arg1, arg2, arg3):
if arg1 == 1 and arg2 == 2 and arg3 == 3:
print("Example Text")
The and
operator is identical to the logic gate with the same name; it will return 1 if and only if all of the inputs are 1. You can also use or
operator if you want that logic gate.
EDIT: Actually, the code provided in your post works fine with me. I don't see any problems with that. I think that this might be a problem with your Python, not the actual language.
Sorry I've not tested this but I think it's done like this:
var filemap = new System.Configuration.ExeConfigurationFileMap();
System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(filemap, System.Configuration.ConfigurationUserLevel.None);
//usage: config.AppSettings["xxx"]
Type "set" and you will get a list of all the current variables. If you want something to persist put it in ~/.bashrc or ~/.bash_profile (if you're using bash)
Use cin.get()
to read the next character.
However, for this problem, it is very inefficient to read a character at a time. Use the istream::read()
instead.
int main()
{
char a[10];
cin.read(a, sizeof(a));
for(int i = 0; i < 10; i++)
{
if(a[i] == ' ')
cout<<"It is a space!!!"<<<endl;
}
return 0;
}
And use ==
to check equality, not =
.
Give this a try:
success: function(json) {
console.log(JSON.stringify(json.topics));
$.each(json.topics, function(idx, topic){
$("#nav").html('<a href="' + topic.link_src + '">' + topic.link_text + "</a>");
});
},
I normally only disable foreign key constraints when I want to truncate a table, and since I keep coming back to this answer this is for future me:
SET FOREIGN_KEY_CHECKS=0;
TRUNCATE TABLE table;
SET FOREIGN_KEY_CHECKS=1;
The answers above are still using the old Python 3.4 style coroutines. Here is what you would write if you got Python 3.5+.
aiohttp
supports http proxy now
import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
urls = [
'http://python.org',
'https://google.com',
'http://yifei.me'
]
tasks = []
async with aiohttp.ClientSession() as session:
for url in urls:
tasks.append(fetch(session, url))
htmls = await asyncio.gather(*tasks)
for html in htmls:
print(html[:100])
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Per Caching SHA-2 Pluggable Authentication
In MySQL 8.0,
caching_sha2_password
is the default authentication plugin rather thanmysql_native_password
.
You're using mysql_native_password
, which is no longer the default. Assuming you're using the correct connector for your version you need to specify the auth_plugin
argument when instantiating your connection object
cnx = mysql.connector.connect(user='lcherukuri', password='password',
host='127.0.0.1', database='test',
auth_plugin='mysql_native_password')
From those same docs:
The
connect()
method supports anauth_plugin
argument that can be used to force use of a particular plugin. For example, if the server is configured to usesha256_password
by default and you want to connect to an account that authenticates usingmysql_native_password
, either connect using SSL or specifyauth_plugin='mysql_native_password'
.
Indeed, in the latest version of Spring Data, findOne returns an optional. If you want to retrieve the object from the Optional, you can simply use get() on the Optional. First of all though, a repository should return the optional to a service, which then handles the case in which the optional is empty. afterwards, the service should return the object to the controller.
This works for me:
psql -h localhost -U postgres
You could try to use:
C:\PROGRA~1
Change #form to your form's ID
$('#form input').keydown(function(e) {
if (e.keyCode == 13) {
$('#form').submit();
}
});
Or alternatively
$('input').keydown(function(e) {
if (e.keyCode == 13) {
$(this).closest('form').submit();
}
});
The example provided by @tster shows how to create a list of list. I will provide an example for iterating over such a list.
Iterator<List<String>> iter = listOlist.iterator();
while(iter.hasNext()){
Iterator<String> siter = iter.next().iterator();
while(siter.hasNext()){
String s = siter.next();
System.out.println(s);
}
}
if ( $('#myfav').children().length > 0 ) {
// do something
}
This should work. The children()
function returns a JQuery object that contains the children. So you just need to check the size and see if it has at least one child.
Read from the controlling terminal device:
read input </dev/tty
more info: http://compgroups.net/comp.unix.shell/Fixing-stdin-inside-a-redirected-loop
Another possibility is using tidyr::expand
:
library(dplyr)
library(tidyr)
df %>% group_by_at(vars(-freq)) %>% expand(temp = 1:freq) %>% select(-temp)
#> # A tibble: 6 x 2
#> # Groups: var1, var2 [3]
#> var1 var2
#> <fct> <fct>
#> 1 a d
#> 2 b e
#> 3 b e
#> 4 c f
#> 5 c f
#> 6 c f
One-liner version of vonjd's answer:
library(data.table)
setDT(df)[ ,list(freq=rep(1,freq)),by=c("var1","var2")][ ,freq := NULL][]
#> var1 var2
#> 1: a d
#> 2: b e
#> 3: b e
#> 4: c f
#> 5: c f
#> 6: c f
Created on 2019-05-21 by the reprex package (v0.2.1)
This is because str.index(ch)
will return the index where ch
occurs the first time. Try:
def find(s, ch):
return [i for i, ltr in enumerate(s) if ltr == ch]
This will return a list of all indexes you need.
P.S. Hugh's answer shows a generator function (it makes a difference if the list of indexes can get large). This function can also be adjusted by changing []
to ()
.
If you are using twitter Bootstrap add the class text-center to your code.
<div class='login-icon'><i class="icon-lock text-center"></i></div>
I know it is an old question, but I had a similar trouble recently. On VMware Workstation 12.+ go to Edit -> Virtual Network Editor...
Select a network used by the problematic VM and make sure that "Connect a host virtual adapter to this network"
checkbox is set for this network. In my case, it was not. After it was set, the host was able to ping the guest and guests were able to talk to each other.
For the sake of completeness, here is an example command for a fresh checkout:
git clone --branch gh-pages --single-branch git://github.com/user/repo
As mentioned in other answers, it sets remote.origin.fetch
like this:
[remote "origin"]
url = git://github.com/user/repo
fetch = +refs/heads/gh-pages:refs/remotes/origin/gh-pages
Abstraction : Abstraction means to show What
part of functionality.
Encapsulation : Encapsulation means to hide the How
part of the functionality.
Lets take a very simple example
/// <summary>
/// We have an Employee class having two properties EmployeeName and EmployeeCode
/// </summary>
public class Employee
{
public string EmplpyeeName { get; set; }
public string EmployeeCode { get; set; }
// Add new employee to DB is the main functionality, so are making it public so that we can expose it to external environment
// This is ABSTRACTION
public void AddEmployee(Employee obj)
{
// "Creation of DB connection" and "To check if employee exists" are internal details which we have hide from external environment
// You can see that these methods are private, external environment just need "What" part only
CreateDBConnection();
CheckIfEmployeeExists();
}
// ENCAPLUSATION using private keyword
private bool CheckIfEmployeeExists()
{
// Here we can validate if the employee already exists
return true;
}
// ENCAPLUSATION using private keyword
private void CreateDBConnection()
{
// Create DB connection code
}
}
Program class of Console Application
class Program
{
static void Main(string[] args)
{
Employee obj = new Employee();
obj.EmplpyeeName = "001";
obj.EmployeeCode = "Raj";
// We have exposed only what part of the functionality
obj.AddEmployee(obj);
}
}
I had the same issue and added to this, i needed to check if iframe is loaded irrespective of cross-domain policy. I was developing a chrome extension which injects certain script on a webpage and displays some content from the parent page in an iframe. I tried following approach and this worked perfect for me.
P.S.: In my case, i do have control over content in iframe but not on the parent site. (Iframe is hosted on my own server)
First:
Create an iframe with a data-
attribute in it like (this part was in injected script in my case)
<iframe id="myiframe" src="http://anyurl.com" data-isloaded="0"></iframe>
Now in the iframe code, use :
var sourceURL = document.referrer;
window.parent.postMessage('1',sourceURL);
Now back to the injected script as per my case:
setTimeout(function(){
var myIframe = document.getElementById('myiframe');
var isLoaded = myIframe.prop('data-isloaded');
if(isLoaded != '1')
{
console.log('iframe failed to load');
} else {
console.log('iframe loaded');
}
},3000);
and,
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
if(event.origin !== 'https://someWebsite.com') //check origin of message for security reasons
{
console.log('URL issues');
return;
}
else {
var myMsg = event.data;
if(myMsg == '1'){
//8-12-18 changed from 'data-isload' to 'data-isloaded
$("#myiframe").prop('data-isloaded', '1');
}
}
}
It may not exactly answer the question but it indeed is a possible case of this question which i solved by this method.
If I want to delete all the tables in my database
Then it's a lot easier to drop the entire database:
DROP DATABASE WorkerPensions
I use this JS snippet code :
First of all, I reach all the classes then according to index of my target class, I set className = "".
Target = document.getElementsByClassName("yourClass")[1];
Target.className="";
The AlexFTPS library used in the question seems to be dead (was not updated since 2011).
You can try to implement this without any external library. But unfortunately, neither the .NET Framework nor PowerShell have any explicit support for downloading all files in a directory (let only recursive file downloads).
You have to implement that yourself:
Tricky part is to identify files from subdirectories. There's no way to do that in a portable way with the .NET framework (FtpWebRequest
or WebClient
). The .NET framework unfortunately does not support the MLSD
command, which is the only portable way to retrieve directory listing with file attributes in FTP protocol. See also Checking if object on FTP server is file or directory.
Your options are:
ListDirectory
method (NLST
FTP command) and simply download all the "names" as files.LIST
command = ListDirectoryDetails
method) and try to parse a server-specific listing. Many FTP servers use *nix-style listing, where you identify a directory by the d
at the very beginning of the entry. But many servers use a different format. The following example uses this approach (assuming the *nix format)function DownloadFtpDirectory($url, $credentials, $localPath)
{
$listRequest = [Net.WebRequest]::Create($url)
$listRequest.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
$listRequest.Credentials = $credentials
$lines = New-Object System.Collections.ArrayList
$listResponse = $listRequest.GetResponse()
$listStream = $listResponse.GetResponseStream()
$listReader = New-Object System.IO.StreamReader($listStream)
while (!$listReader.EndOfStream)
{
$line = $listReader.ReadLine()
$lines.Add($line) | Out-Null
}
$listReader.Dispose()
$listStream.Dispose()
$listResponse.Dispose()
foreach ($line in $lines)
{
$tokens = $line.Split(" ", 9, [StringSplitOptions]::RemoveEmptyEntries)
$name = $tokens[8]
$permissions = $tokens[0]
$localFilePath = Join-Path $localPath $name
$fileUrl = ($url + $name)
if ($permissions[0] -eq 'd')
{
if (!(Test-Path $localFilePath -PathType container))
{
Write-Host "Creating directory $localFilePath"
New-Item $localFilePath -Type directory | Out-Null
}
DownloadFtpDirectory ($fileUrl + "/") $credentials $localFilePath
}
else
{
Write-Host "Downloading $fileUrl to $localFilePath"
$downloadRequest = [Net.WebRequest]::Create($fileUrl)
$downloadRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
$downloadRequest.Credentials = $credentials
$downloadResponse = $downloadRequest.GetResponse()
$sourceStream = $downloadResponse.GetResponseStream()
$targetStream = [System.IO.File]::Create($localFilePath)
$buffer = New-Object byte[] 10240
while (($read = $sourceStream.Read($buffer, 0, $buffer.Length)) -gt 0)
{
$targetStream.Write($buffer, 0, $read);
}
$targetStream.Dispose()
$sourceStream.Dispose()
$downloadResponse.Dispose()
}
}
}
Use the function like:
$credentials = New-Object System.Net.NetworkCredential("user", "mypassword")
$url = "ftp://ftp.example.com/directory/to/download/"
DownloadFtpDirectory $url $credentials "C:\target\directory"
The code is translated from my C# example in C# Download all files and subdirectories through FTP.
If you want to avoid troubles with parsing the server-specific directory listing formats, use a 3rd party library that supports the MLSD
command and/or parsing various LIST
listing formats. And ideally with a support for downloading all files from a directory or even recursive downloads.
For example with WinSCP .NET assembly you can download whole directory with a single call to Session.GetFiles
:
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Ftp
HostName = "ftp.example.com"
UserName = "user"
Password = "mypassword"
}
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Download files
$session.GetFiles("/directory/to/download/*", "C:\target\directory\*").Check()
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
Internally, WinSCP uses the MLSD
command, if supported by the server. If not, it uses the LIST
command and supports dozens of different listing formats.
The Session.GetFiles
method is recursive by default.
(I'm the author of WinSCP)
Reading an html page with urllib is fairly simple to do. Since you want to read it as a single string I will show you.
Import urllib.request:
#!/usr/bin/python3.5
import urllib.request
Prepare our request
request = urllib.request.Request('http://www.w3schools.com')
Always use a "try/except" when requesting a web page as things can easily go wrong. urlopen() requests the page.
try:
response = urllib.request.urlopen(request)
except:
print("something wrong")
Type is a great function that will tell us what 'type' a variable is. Here, response is a http.response object.
print(type(response))
The read function for our response object will store the html as bytes to our variable. Again type() will verify this.
htmlBytes = response.read()
print(type(htmlBytes))
Now we use the decode function for our bytes variable to get a single string.
htmlStr = htmlBytes.decode("utf8")
print(type(htmlStr))
If you do want to split up this string into separate lines, you can do so with the split() function. In this form we can easily iterate through to print out the entire page or do any other processing.
htmlSplit = htmlStr.split('\n')
print(type(htmlSplit))
for line in htmlSplit:
print(line)
Hopefully this provides a little more detailed of an answer. Python documentation and tutorials are great, I would use that as a reference because it will answer most questions you might have.
Passsing bitmap as parceable in bundle between activity is not a good idea because of size limitation of Parceable(1mb). You can store the bitmap in a file in internal storage and retrieve the stored bitmap in several activities. Here's some sample code.
To store bitmap in a file myImage in internal storage:
public String createImageFromBitmap(Bitmap bitmap) {
String fileName = "myImage";//no .png or .jpg needed
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
fo.write(bytes.toByteArray());
// remember close file output
fo.close();
} catch (Exception e) {
e.printStackTrace();
fileName = null;
}
return fileName;
}
Then in the next activity you can decode this file myImage to a bitmap using following code:
//here context can be anything like getActivity() for fragment, this or MainActivity.this
Bitmap bitmap = BitmapFactory.decodeStream(context.openFileInput("myImage"));
Note A lot of checking for null and scaling bitmap's is ommited.
The Array has declared without intializing the values and if you want to insert values by itterating the loop this code will work.
Public Class Program
{
public static void main(String args[])
{
//Array Intialization
int my[] = new int[6];
for(int i=0;i<=5;i++)
{
//Storing array values in array
my[i]= i;
//Printing array values
System.out.println(my[i]);
}
}
}
Try this:
Function UserNameWindows() As String
UserName = Environ("USERNAME")
End Function
With user input and fancy output formatting:
[CmdletBinding(SupportsShouldProcess=$True)]
Param(
[Parameter(Mandatory = $True)]
[String]$UserName
)
Import-Module ActiveDirectory
If ($UserName) {
$UserName = $UserName.ToUpper().Trim()
$Res = (Get-ADPrincipalGroupMembership $UserName | Measure-Object).Count
If ($Res -GT 0) {
Write-Output "`n"
Write-Output "$UserName AD Group Membership:"
Write-Output "==========================================================="
Get-ADPrincipalGroupMembership $UserName | Select-Object -Property Name, GroupScope, GroupCategory | Sort-Object -Property Name | FT -A
}
}
The solution posted here does not work for me. Therefore, I am posting this answer to help someone facing similar issue.
OS: Ubuntu 18
PostgreSQL: 9.5 (Hosted on Ubuntu)
Docker: Server Application (which connects to PostgreSQL)
I am using docker-compose.yml to build application.
STEP 1: Please add host.docker.internal:<docker0 IP>
version: '3'
services:
bank-server:
...
depends_on:
....
restart: on-failure
ports:
- 9090:9090
extra_hosts:
- "host.docker.internal:172.17.0.1"
To find IP of docker i.e. 172.17.0.1 (in my case)
you can use:
$> ifconfig docker0
docker0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
inet 172.17.0.1 netmask 255.255.0.0 broadcast 172.17.255.255
OR
$> ip a
1: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
valid_lft forever preferred_lft forever
STEP 2: In postgresql.conf, change listen_addresses to listen_addresses = '*'
STEP 3: In pg_hba.conf, add this line
host all all 0.0.0.0/0 md5
STEP 4: Now restart postgresql service using, sudo service postgresql restart
STEP 5: Please use host.docker.internal
hostname to connect database from Server Application.
Ex: jdbc:postgresql://host.docker.internal:5432/bankDB
Enjoy!!
The above solutions didn't work for me. Here is what I finally came up with:
$( "#ddl" ).find( "option:selected" ).text(); // Text
$( "#ddl" ).find( "option:selected" ).prop("value"); // Value
On Error Statement - Specifies that when a run-time error occurs, control goes to the statement immediately following the statement. How ever Err object got populated.(Err.Number, Err.Count etc)
There are a couple of methods for full mysql FULL [OUTER] JOIN.
UNION a left join and right join. UNION will remove duplicates by performing an ORDER BY operation. So depending on your data, it may not be performant.
SELECT * FROM A
LEFT JOIN B ON A.key = B.key
UNION
SELECT * FROM A
RIGHT JOIN B ON A.key = B.key
UNION ALL a left join and right EXCLUDING join (that's the lower right figure in the diagram). UNION ALL will not remove duplicates. Sometimes this might be the behaviour that you want. You also want to use RIGHT EXCLUDING to avoid duplicating common records from selection A and selection B - i.e Left join has already included common records from selection B, lets not repeat that again with the right join.
SELECT * FROM A
LEFT JOIN B ON A.key = B.key
UNION ALL
SELECT * FROM A
RIGHT JOIN B ON A.key = B.key
WHERE A.key IS NULL
@CaptSolo, I tried your example, but it didn't work.
from itertools import groupby
[(c,len(list(cs))) for c,cs in groupby('Pedro Manoel')]
Output:
[('P', 1), ('e', 1), ('d', 1), ('r', 1), ('o', 1), (' ', 1), ('M', 1), ('a', 1), ('n', 1), ('o', 1), ('e', 1), ('l', 1)]
As you can see, there are two o's and two e's, but they got into separate groups. That's when I realized you need to sort the list passed to the groupby function. So, the correct usage would be:
name = list('Pedro Manoel')
name.sort()
[(c,len(list(cs))) for c,cs in groupby(name)]
Output:
[(' ', 1), ('M', 1), ('P', 1), ('a', 1), ('d', 1), ('e', 2), ('l', 1), ('n', 1), ('o', 2), ('r', 1)]
Just remembering, if the list is not sorted, the groupby function will not work!
The Web Developer plugin for Firefox and Chrome is able to do this
Once you have installed the plugin the option is available in the CSS menu. For example, CSS > Disable Styles > Disable All Styles
Alternatively with the developer toolbar enabled you can press Alt+Shift+A
.
Just a small tip for setting custom padding without extra table elements. Just use this way, it works (TCPDF 6.2.11)
<table border="0" style="padding-left: 10px; padding-bottom: 15px;">
<tr>
<td style="border: 1px solid grey;"> One two three </td>
<td style="border: 1px solid grey;"> Four five six </td>
</tr>
</table>
Implement repr for every class you implement. There should be no excuse. Implement str for classes which you think readability is more important of non-ambiguity.
Refer this link: https://www.pythoncentral.io/what-is-the-difference-between-str-and-repr-in-python/
Following code uses a third-party ZIP component from Rebex:
// add content of the local directory C:\Data\
// to the root directory in the ZIP archive
// (ZIP archive C:\archive.zip doesn't have to exist)
Rebex.IO.Compression.ZipArchive.Add(@"C:\archive.zip", @"C:\Data\*", "");
Or if you want to add more folders without need to open and close archive multiple times:
using Rebex.IO.Compression;
...
// open the ZIP archive from an existing file
ZipArchive zip = new ZipArchive(@"C:\archive.zip", ArchiveOpenMode.OpenOrCreate);
// add first folder
zip.Add(@"c:\first\folder\*","\first\folder");
// add second folder
zip.Add(@"c:\second\folder\*","\second\folder");
// close the archive
zip.Close(ArchiveSaveAction.Auto);
You can download the ZIP component here.
Using a free, LGPL licensed SharpZipLib is a common alternative.
Disclaimer: I work for Rebex
How about:
mySwitchFunction = (param) => {
switch (param) {
case 'A':
return ([
<div />,
]);
// etc...
}
}
render() {
return (
<div>
<div>
// removed for brevity
</div>
{ this.mySwitchFunction(param) }
<div>
// removed for brevity
</div>
</div>
);
}
I had the same issue and I resolved it with MySQL workbench, as shown in the attached screenshot:
Hope that helps!
I generally map :noh
to the backslash key. To reenable the highlighting, just hit n, and it will highlight again.
You may change the pg_hba.conf and then reload the postgresql. something in the pg_hba.conf may be like below:
# "local" is for Unix domain socket connections only
local all all trust
# IPv4 local connections:
host all all 127.0.0.1/32 trust
then you change your user to postgresql, you may login successfully.
su postgresql
Re the solution for SqlBulkCopy:
I used the StreamReader to convert and process the text file. The result was a list of my object.
I created a class than takes Datatable
or a List<T>
and a Buffer size (CommitBatchSize
). It will convert the list to a data table using an extension (in the second class).
It works very fast. On my PC, I am able to insert more than 10 million complicated records in less than 10 seconds.
Here is the class:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL
{
public class BulkUploadToSql<T>
{
public IList<T> InternalStore { get; set; }
public string TableName { get; set; }
public int CommitBatchSize { get; set; }=1000;
public string ConnectionString { get; set; }
public void Commit()
{
if (InternalStore.Count>0)
{
DataTable dt;
int numberOfPages = (InternalStore.Count / CommitBatchSize) + (InternalStore.Count % CommitBatchSize == 0 ? 0 : 1);
for (int pageIndex = 0; pageIndex < numberOfPages; pageIndex++)
{
dt= InternalStore.Skip(pageIndex * CommitBatchSize).Take(CommitBatchSize).ToDataTable();
BulkInsert(dt);
}
}
}
public void BulkInsert(DataTable dt)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
// make sure to enable triggers
// more on triggers in next post
SqlBulkCopy bulkCopy =
new SqlBulkCopy
(
connection,
SqlBulkCopyOptions.TableLock |
SqlBulkCopyOptions.FireTriggers |
SqlBulkCopyOptions.UseInternalTransaction,
null
);
// set the destination table name
bulkCopy.DestinationTableName = TableName;
connection.Open();
// write the data in the "dataTable"
bulkCopy.WriteToServer(dt);
connection.Close();
}
// reset
//this.dataTable.Clear();
}
}
public static class BulkUploadToSqlHelper
{
public static DataTable ToDataTable<T>(this IEnumerable<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
}
}
Here is an example when I want to insert a List of my custom object List<PuckDetection>
(ListDetections
):
var objBulk = new BulkUploadToSql<PuckDetection>()
{
InternalStore = ListDetections,
TableName= "PuckDetections",
CommitBatchSize=1000,
ConnectionString="ENTER YOU CONNECTION STRING"
};
objBulk.Commit();
The BulkInsert
class can be modified to add column mapping if required. Example you have an Identity key as first column.(this assuming that the column names in the datatable are the same as the database)
//ADD COLUMN MAPPING
foreach (DataColumn col in dt.Columns)
{
bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
}
My attempt at adding ToVerbatim to Hallgrim's accepted answer above:
private static string ToLiteral(string input)
{
using (var writer = new StringWriter())
{
using (var provider = CodeDomProvider.CreateProvider("CSharp"))
{
provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, new CodeGeneratorOptions { IndentString = "\t" });
var literal = writer.ToString();
literal = literal.Replace(string.Format("\" +{0}\t\"", Environment.NewLine), "");
return literal;
}
}
}
private static string ToVerbatim( string input )
{
string literal = ToLiteral( input );
string verbatim = "@" + literal.Replace( @"\r\n", Environment.NewLine );
return verbatim;
}
In TortoiseSVN, you can also Shift + right-click to get a menu that includes "Delete (keep local)".
In IE9, it is possible with purely a hack as advised by @Spudley. Since you've customized height and width of the div and select, you need to change div:before
css to match yours.
In case if it is IE10 then using below css3 it is possible
select::-ms-expand {
display: none;
}
However if you're interested in jQuery plugin, try Chosen.js
or you can create your own in js.
Representing complex HTML documents will be difficult and full of corner cases, but I just wanted to share a couple techniques to show how to get this kind of program started. This answer differs in that it uses data abstraction and the toJSON
method to recursively build the result
Below, html2json
is a tiny function which takes an HTML node as input and it returns a JSON string as the result. Pay particular attention to how the code is quite flat but it's still plenty capable of building a deeply nested tree structure – all possible with virtually zero complexity
// data Elem = Elem Node_x000D_
_x000D_
const Elem = e => ({_x000D_
toJSON : () => ({_x000D_
tagName: _x000D_
e.tagName,_x000D_
textContent:_x000D_
e.textContent,_x000D_
attributes:_x000D_
Array.from(e.attributes, ({name, value}) => [name, value]),_x000D_
children:_x000D_
Array.from(e.children, Elem)_x000D_
})_x000D_
})_x000D_
_x000D_
// html2json :: Node -> JSONString_x000D_
const html2json = e =>_x000D_
JSON.stringify(Elem(e), null, ' ')_x000D_
_x000D_
console.log(html2json(document.querySelector('main')))
_x000D_
<main>_x000D_
<h1 class="mainHeading">Some heading</h1>_x000D_
<ul id="menu">_x000D_
<li><a href="/a">a</a></li>_x000D_
<li><a href="/b">b</a></li>_x000D_
<li><a href="/c">c</a></li>_x000D_
</ul>_x000D_
<p>some text</p>_x000D_
</main>
_x000D_
In the previous example, the textContent
gets a little butchered. To remedy this, we introduce another data constructor, TextElem
. We'll have to map over the childNodes
(instead of children
) and choose to return the correct data type based on e.nodeType
– this gets us a littler closer to what we might need
// data Elem = Elem Node | TextElem Node_x000D_
_x000D_
const TextElem = e => ({_x000D_
toJSON: () => ({_x000D_
type:_x000D_
'TextElem',_x000D_
textContent:_x000D_
e.textContent_x000D_
})_x000D_
})_x000D_
_x000D_
const Elem = e => ({_x000D_
toJSON : () => ({_x000D_
type:_x000D_
'Elem',_x000D_
tagName: _x000D_
e.tagName,_x000D_
attributes:_x000D_
Array.from(e.attributes, ({name, value}) => [name, value]),_x000D_
children:_x000D_
Array.from(e.childNodes, fromNode)_x000D_
})_x000D_
})_x000D_
_x000D_
// fromNode :: Node -> Elem_x000D_
const fromNode = e => {_x000D_
switch (e.nodeType) {_x000D_
case 3: return TextElem(e)_x000D_
default: return Elem(e)_x000D_
}_x000D_
}_x000D_
_x000D_
// html2json :: Node -> JSONString_x000D_
const html2json = e =>_x000D_
JSON.stringify(Elem(e), null, ' ')_x000D_
_x000D_
console.log(html2json(document.querySelector('main')))
_x000D_
<main>_x000D_
<h1 class="mainHeading">Some heading</h1>_x000D_
<ul id="menu">_x000D_
<li><a href="/a">a</a></li>_x000D_
<li><a href="/b">b</a></li>_x000D_
<li><a href="/c">c</a></li>_x000D_
</ul>_x000D_
<p>some text</p>_x000D_
</main>
_x000D_
Anyway, that's just two iterations on the problem. Of course you'll have to address corner cases where they come up, but what's nice about this approach is that it gives you a lot of flexibility to encode the HTML however you wish in JSON – and without introducing too much complexity
In my experience, you could keep iterating with this technique and achieve really good results. If this answer is interesting to anyone and would like me to expand upon anything, let me know ^_^
Related: Recursive methods using JavaScript: building your own version of JSON.stringify
When trying the accepted answer, I was getting an installation error: A failure was detected for a previous installation, patch, or repair blah, blah, blah...
To fix this, in my registry, I changed all DWORD values to 1 in the following Keys: (As always be careful modifying the registry and create a backup of the key before changing anything)
HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\100\ConfigurationState HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\MSAS10_50.MSSQLSERVER\ConfigurationState HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\ConfigurationState HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.SQLEXPRESS\ConfigurationState HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\ConfigurationState
See my full post about Fixing Intellisense issue in SSMS.
Note that you could as well plot directly from ce
(after the comma removing) using the column name :
hist(ce$Weight)
(As opposed to using hist(ce[1])
, which would lead to the same "must be numeric" error.)
This also works for a database query result.
First you have to
Remove cache
in your browser
Then open terminal and run the following command:
sudo apt-get install php-gettext
sudo nano /etc/nginx/sites-available/default
Then add the following code in the default
file:
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
root /usr/share/nginx/html;
index index.php index.html index.htm;
server_name localhost;
location / {
try_files $uri $uri/ =404;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
If any mismatch just correction and restart Nginx from terminal by the following command
sudo systemctl restart nginx
Then go to browser and Enjoy ...
Add the following -vm D:/Java/jdk1.6.0_30/bin/javaw.exe in the begin of eclipse.ini like this :
-vm
D:/Java/jdk1.6.0_30/bin/javaw.exe
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20130807-1835
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
1024M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
1024m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms1024m
-Xmx2048m
As theMarko suggests:
BASEDIR=$(dirname $0)
echo $BASEDIR
This works unless you execute the script from the same directory where the script resides, in which case you get a value of '.'
To get around that issue use:
current_dir=$(pwd)
script_dir=$(dirname $0)
if [ $script_dir = '.' ]
then
script_dir="$current_dir"
fi
You can now use the variable current_dir throughout your script to refer to the script directory. However this may still have the symlink issue.
if you have this kind of problem with ispconfig3 and got an error like this
open_basedir restriction in effect. File(/var/www/clients/client7/web15) is not within the allowed path(s):.........
To solve it (in my case) , just set PHP to SuPHP in the Website's panel of ispconfig3
Hope it helps someone :)
OneToOneField: if second table is related with
table2_col1 = models.OneToOneField(table1,on_delete=models.CASCADE, related_name='table1_id')
table2 will contains only one record corresponding to table1's pk value, i.e table2_col1 will have unique value equal to pk of table
table2_col1 == models.ForeignKey(table1, on_delete=models.CASCADE, related_name='table1_id')
table2 may contains more than one record corresponding to table1's pk value.
This is working Oracle example but it should work in MySQL too.
You are missing smth - see IN after END Replace 'IN' with '=' sign for a single value.
SELECT empno, ename, job
FROM scott.emp
WHERE (CASE WHEN job = 'MANAGER' THEN '1'
WHEN job = 'CLERK' THEN '2'
ELSE '0' END) IN (1, 2)
Since the last update of the xmlhttprequest module was around 2 years ago, in some cases it does not work as expected.
So instead, you can use the xhr2 module. In other words:
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
becomes:
var XMLHttpRequest = require('xhr2');
var xhr = new XMLHttpRequest();
But ... of course, there are more popular modules like Axios, because -for example- uses promises:
// Make a request for a user with a given ID
axios.get('/user?ID=12345').then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
You must specify that the friend is a template function:
MyClass<T>& operator+=<>(const MyClass<T>& classObj);
See this C++ FAQ Lite answer for details.
Personally i wouldnt store the image in the database, Instead put it in a folder not accessable from outside, and use the database for keeping track of its location. keeps database size down and you can just include it by using PHP. There would be no way without PHP to access that image then
If you're interested, there's a well-established package out there that you can add to your Codeigniter project that will handle this:
https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/
Modular Extensions makes the CodeIgniter PHP framework modular. Modules are groups of independent components, typically model, controller and view, arranged in an application modules sub-directory, that can be dropped into other CodeIgniter applications.
OK, so the big change is that now you'd be using a modular structure - but to me this is desirable. I have used CI for about 3 years now, and can't imagine life without Modular Extensions.
Now, here's the part that deals with directly calling controllers for rendering view partials:
// Using a Module as a view partial from within a view is as easy as writing:
<?php echo modules::run('module/controller/method', $param1, $params2); ?>
That's all there is to it. I typically use this for loading little "widgets" like:
Typically I build a "widget" controller for each module and use it only for this purpose.
Your question was also one of my first questions when I started with Codeigniter. I hope this helps you out, even though it may be a bit more than you were looking for. I've been using MX ever since and haven't looked back.
Make sure to read the docs and check out the multitude of information regarding this package on the Codeigniter forums. Enjoy!
In my case, the service account running the application did not have permission to access the private key. Once I gave this permission, the error went away
@if(request()->path()=='/path/another_path/*')
@endif
If you look at the down arrow in environment tab. The attached file can appear multiple times. You may need to highlight and run detach(filename)
several times until all cases are gone then attach(newfilename)
should have no output message.
Nice article for elevation options - http://www.novell.com/support/kb/doc.php?id=7010269
Configuring Applications to Always Request Elevated Rights:
Programs can be configured to always request elevation on the user level via registry settings under HKCU
. These registry settings are effective on the fly, so they can be set immediately prior to launching a particular application and even removed as soon as the application is launched, if so desired. Simply create a "String Value"
under "HKCU\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers"
for the full path to an executable with a value of "RUN AS ADMIN"
. Below is an example for CMD.
Windows Registry Editor Version 5.00
[HKEY_Current_User\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers]
"c:\\windows\\system32\\cmd.exe"="RUNASADMIN"
if you want to display "None" when value is "0", you can use as:
<span> {{ $scope.amount === "0" ? $scope.amount : "None" }} </span>
or true false in angular js
<span> {{ $scope.amount === "0" ? "False" : "True" }} </span>
Your idea of an hidden form element is solid. Something like this
<form action="script.php" method="post">
<input type="hidden" name="total" id="total">
</form>
<script type="text/javascript">
var element = document.getElementById("total");
element.value = getTotalFromSomewhere;
element.form.submit();
</script>
Of course, this will change the location to script.php
. If you want to do this invisibly to the user, you'll want to use AJAX. Here's a jQuery example (for brevity). No form or hidden inputs required
$.post("script.php", { total: getTotalFromSomewhere });
This is because you have not compiled it. Click 'Project > compile'. Then, either click 'start debugging', or 'start without debugging'.
A container exits when its main process exits. Doing something like:
docker run -itd debian
to hold the container open is frankly a hack that should only be used for quick tests and examples. If you just want a container for testing for a few minutes, I would do:
docker run -d debian sleep 300
Which has the advantage that the container will automatically exit if you forget about it. Alternatively, you could put something like this in a while
loop to keep it running forever, or just run an application such as top
. All of these should be easy to do in Kubernetes.
The real question is why would you want to do this? Your container should be providing a service, whose process will keep the container running in the background.
Here’s the modern answer.
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
DateTimeFormatter displayFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.forLanguageTag("zh-SG"));
String dateString = "31/05/2011";
LocalDate date = LocalDate.parse(dateString, sourceFormatter);
System.out.println(date.format(displayFormatter));
Output from this snippet is:
31/05/11
See if you can live with the 2-digit year. Or use FormatStyle.MEDIUM
to obtain 2011?5?31?
. I recommend you use Java’s built-in date and time formats when you can. It’s easier and lends itself very well to internationalization.
If you need the exact format you gave, just use the source formatter as display formatter too:
System.out.println(date.format(sourceFormatter));
31/05/2011
I recommend you don’t use SimpleDateFormat
. It’s notoriously troublesome and long outdated. Instead I use java.time, the modern Java date and time API.
To obtain a specific format you need to format the parsed date back into a string. Netiher an old-fashioned Date
nor a modern LocalDate
can have a format in it.
Link: Oracle tutorial: Date Time explaining how to use java.time.
Resource-Only DLL is an option for you. But it is not required necessarily unless you want to modify resources without recompiling applications. Have just one common ResourceDictionary file is also an option. It depends how often you change resources and etc.
<ResourceDictionary Source="pack://application:,,,/
<MyAssembly>;component/<FolderStructureInAssembly>/<ResourceFile.xaml>"/>
MyAssembly - Just assembly name without extension
FolderStructureInAssembly - If your resources are in a folde, specify folder structure
When you are doing this it's better to aware of siteOfOrigin as well.
WPF supports two authorities: application:/// and siteoforigin:///. The application:/// authority identifies application data files that are known at compile time, including resource and content files. The siteoforigin:/// authority identifies site of origin files. The scope of each authority is shown in the following figure.
Delete the line /*# sourceMappingURL=bootstrap.css.map */
from bootstrap.css
maybe this is what u want?
<a href="#" id="bottle" onclick="document.location=this.id+'.html';return false;" >
<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" />
</a>
edit: keep in mind that anyone who does not have javascript enabled will not be able to navaigate to the image page....
Maybe
df <- do.call("cbind", list(df, rep(list(NA),length(namevector))))
colnames(df)[-1*(1:(ncol(df) - length(namevector)))] <- namevector
If you pass the -v
flag to ansible-playbook on the command line, you'll see the stdout and stderr for each task executed:
$ ansible-playbook -v playbook.yaml
Ansible also has built-in support for logging. Add the following lines to your ansible configuration file:
[defaults]
log_path=/path/to/logfile
Ansible will look in several places for the config file:
ansible.cfg
in the current directory where you ran ansible-playbook
~/.ansible.cfg
/etc/ansible/ansible.cfg
Although in most general cases the error is quite clearly that file handles have not been closed, I just encountered an instance with JDK7 on Linux that well... is sufficiently ****ed up to explain here.
The program opened a FileOutputStream (fos), a BufferedOutputStream (bos) and a DataOutputStream (dos). After writing to the dataoutputstream, the dos was closed and I thought everything went fine.
Internally however, the dos, tried to flush the bos, which returned a Disk Full error. That exception was eaten by the DataOutputStream, and as a consequence the underlying bos was not closed, hence the fos was still open.
At a later stage that file was then renamed from (something with a .tmp) to its real name. Thereby, the java file descriptor trackers lost track of the original .tmp, yet it was still open !
To solve this, I had to first flush the DataOutputStream myself, retrieve the IOException and close the FileOutputStream myself.
I hope this helps someone.
If you are just looking for the text which you can then split up but don't want to use the API take a look at en.wikipedia.org/w/index.php?title=Elephant&action=raw
If you are unaware of the position to replace, use list iterator to find and replace element ListIterator.set(E e)
ListIterator<String> iterator = list.listIterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (next.equals("Two")) {
//Replace element
iterator.set("New");
}
}
The methods viewWillLayoutSubviews
and viewDidLayoutSubviews
aren't mentioned in the diagrams, but these are called between viewWillAppear
and viewDidAppear
. They can be called multiple times.
Why not use relative units?
.cropText {
max-width: 20em;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
If you don't want to add a new column, and you can guarantee that your current int column is unique, you could select all of the data out into a temporary table, drop the table and recreate with the IDENTITY column specified. Then using SET IDENTITY INSERT ON
you can insert all of your data in the temporary table into the new table.
Any of the below three options works for you:
echo[
echo(
echo.
For example:
@echo off
echo There will be a blank line below
echo[
echo Above line is blank
echo(
echo The above line is also blank.
echo.
echo The above line is also blank.
Open command line cmd and run this: adb backup -f C:\Intel\xxx.ab -noapk your.app.package. Do not enter password and click on Backup my data. Make sure not to save on drive C root. You may be denied. This is why I saved on C:\Intel.
I my case it was just because mysql was stopped because of the missing /var/log/mysql
folder defined in /etc/mysql/my.cnf
. After creating it I could start mysql and it ran as usual.
Thread dumps are javacore show snapshot of threads running in JVM, it is useful to debug hang issues, it will provide info about java level dead locks and also IBm version of javacores provides much more useful information, such as heap usage, CPU usage of each thread and overall heap usage along with number of classes laded by the JVM.
Heapdumps, provides information about Java heap usage by an JVM, which can be used to debug memory leaks. Heapdumps are generated by IBM JVMs when a JVM is runs into outofmemoryerror, Heapdumps are only for heap leaks in java, native out of memory error may result system dumps usually with an "GPF" General protection Fault.
Step.1
$ git submodule update
Step.2
To be commented out the dependences of classpass
In python
3.6.3 with pandas
0.22.0 you can also use concat
as long as you set as index the columns you want to use for the joining
pd.concat(
(iDF.set_index('name') for iDF in [df1, df2, df3]),
axis=1, join='inner'
).reset_index()
where df1
, df2
, and df3
are defined as in John Galt's answer
import pandas as pd
df1 = pd.DataFrame(np.array([
['a', 5, 9],
['b', 4, 61],
['c', 24, 9]]),
columns=['name', 'attr11', 'attr12']
)
df2 = pd.DataFrame(np.array([
['a', 5, 19],
['b', 14, 16],
['c', 4, 9]]),
columns=['name', 'attr21', 'attr22']
)
df3 = pd.DataFrame(np.array([
['a', 15, 49],
['b', 4, 36],
['c', 14, 9]]),
columns=['name', 'attr31', 'attr32']
)
You need to do encode
on tmp[0]
, not on tmp
.
tmp
is not a string. It contains a (Unicode) string.
Try running type(tmp)
and print dir(tmp)
to see it for yourself.
The Set statement is only used for object variables (like Range
, Cell
or Worksheet
in Excel), while the simple equal sign '=' is used for elementary datatypes like Integer
. You can find a good explanation for when to use set here.
The other problem is, that your variable g1val
isn't actually declared as Integer
, but has the type Variant
. This is because the Dim statement doesn't work the way you would expect it, here (see example below). The variable has to be followed by its type right away, otherwise its type will default to Variant
. You can only shorten your Dim statement this way:
Dim intColumn As Integer, intRow As Integer 'This creates two integers
For this reason, you will see the "Empty" instead of the expected "0" in the Watches window.
Try this example to understand the difference:
Sub Dimming()
Dim thisBecomesVariant, thisIsAnInteger As Integer
Dim integerOne As Integer, integerTwo As Integer
MsgBox TypeName(thisBecomesVariant) 'Will display "Empty"
MsgBox TypeName(thisIsAnInteger ) 'Will display "Integer"
MsgBox TypeName(integerOne ) 'Will display "Integer"
MsgBox TypeName(integerTwo ) 'Will display "Integer"
'By assigning an Integer value to a Variant it becomes Integer, too
thisBecomesVariant = 0
MsgBox TypeName(thisBecomesVariant) 'Will display "Integer"
End Sub
Two further notices on your code:
First remark: Instead of writing
'If g1val is bigger than the value in the current cell
If g1val > Cells(33, i).Value Then
g1val = g1val 'Don't change g1val
Else
g1val = Cells(33, i).Value 'Otherwise set g1val to the cell's value
End If
you could simply write
'If g1val is smaller or equal than the value in the current cell
If g1val <= Cells(33, i).Value Then
g1val = Cells(33, i).Value 'Set g1val to the cell's value
End If
Since you don't want to change g1val
in the other case.
Second remark: I encourage you to use Option Explicit when programming, to prevent typos in your program. You will then have to declare all variables and the compiler will give you a warning if a variable is unknown.
It's go to newline then add spaces to start second line at end of first line
Output
Hello
Goodbye
The NotificationCompat.Builder is the most easy way to create Notifications
on all Android versions. You can even use features that are available with Android 4.1. If your app runs on devices with Android >=4.1 the new features will be used, if run on Android <4.1 the notification will be an simple old notification.
To create a simple Notification just do (see Android API Guide on Notifications):
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setContentIntent(pendingIntent); //Required on Gingerbread and below
You have to set at least smallIcon
, contentTitle
and contentText
. If you miss one the Notification will not show.
Beware: On Gingerbread and below you have to set the content intent, otherwise a IllegalArgumentException
will be thrown.
To create an intent that does nothing, use:
final Intent emptyIntent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, NOT_USED, emptyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
You can add sound through the builder, i.e. a sound from the RingtoneManager:
mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
The Notification is added to the bar through the NotificationManager:
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(mId, mBuilder.build());
I find the solution in spring.io,like this:
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
If this class is only a utility class, you should make the class final and define a private constructor:
public final class FilePathHelper {
private FilePathHelper() {
//not called
}
}
This prevents the default parameter-less constructor from being used elsewhere in your code. Additionally, you can make the class final, so that it can't be extended in subclasses, which is a best practice for utility classes. Since you declared only a private constructor, other classes wouldn't be able to extend it anyway, but it is still a best practice to mark the class as final.
POJOS
with certain conventions (getter/setter,public no-arg constructor ,private variables) and are in action(ex. being used for reading data by form) are JAVABEANS
.
You can access the index attribute of a df using df.index[i]
>> import pandas as pd
>> import numpy as np
>> df = pd.DataFrame({'a':np.arange(5), 'b':np.random.randn(5)})
a b
0 0 1.088998
1 1 -1.381735
2 2 0.035058
3 3 -2.273023
4 4 1.345342
>> df.index[1] ## Second index
>> df.index[-1] ## Last index
>> for i in xrange(len(df)):print df.index[i] ## Using loop
...
0
1
2
3
4
Although Martijin's answer is prob best. Here is a more intuitive way to process large csv files for beginners. This allows you to process groups of rows, or chunks, at a time.
import pandas as pd
chunksize = 10 ** 8
for chunk in pd.read_csv(filename, chunksize=chunksize):
process(chunk)
Also, (related) check the order of your handler mappings. We had a .ashx with a .svc (e.g. /foo.asmx/bar.svc/path) in the path after it. The .svc mapping was first so 404 for the .svc path which matched before the .asmx. Havn't thought too much but maybe url encodeing the path would take care of this.
From the dojo API documentation:
dojo.html._emptyNode(node);
To call a sub inside another sub you only need to do:
Call Subname()
So where you have CalculateA(Nc,kij, xi, a1, a)
you need to have call CalculateA(Nc,kij, xi, a1, a)
As the which runs first problem it's for you to decide, when you want to run a sub you can go to the macro list select the one you want to run and run it, you can also give it a key shortcut, therefore you will only have to press those keys to run it. Although, on secondary subs, I usually do it as Private sub CalculateA(...)
cause this way it does not appear in the macro list and it's easier to work
Hope it helps, Bruno
PS: If you have any other question just ask, but this isn't a community where you ask for code, you come here with a question or a code that isn't running and ask for help, not like you did "It would be great if you could write it in the Excel VBA format."
On windows, you can print with this command in your CLI
C:\Users\dir\env | more
You can view all environment variables set on your system with the env command. The list is long, so pipe the output through more to make it easier to read.
Check out this post, it gives a really nice code snippet for what to do when touch devices are detected or what to do if touchstart event is called:
$(function(){
if(window.Touch) {
touch_detect.auto_detected();
} else {
document.ontouchstart = touch_detect.surface;
}
}); // End loaded jQuery
var touch_detect = {
auto_detected: function(event){
/* add everything you want to do onLoad here (eg. activating hover controls) */
alert('this was auto detected');
activateTouchArea();
},
surface: function(event){
/* add everything you want to do ontouchstart here (eg. drag & drop) - you can fire this in both places */
alert('this was detected by touching');
activateTouchArea();
}
}; // touch_detect
function activateTouchArea(){
/* make sure our screen doesn't scroll when we move the "touchable area" */
var element = document.getElementById('element_id');
element.addEventListener("touchstart", touchStart, false);
}
function touchStart(event) {
/* modularize preventing the default behavior so we can use it again */
event.preventDefault();
}
You may try;
$('#save_value').click(function(){
var final = '';
$('.ads_Checkbox:checked').each(function(){
var values = $(this).val();
final += values;
});
alert(final);
});
This will return all checkbox values in a single instance.
Here is a working Live Demo.
1) If a DataFrame has got Nan and Non Null values and you want to find whether the DataFrame is empty or not then try this code. 2) when this situation can happen? This situation happens when a single function is used to plot more than one DataFrame which are passed as parameter.In such a situation the function try to plot the data even when a DataFrame is empty and thus plot an empty figure!. It will make sense if simply display 'DataFrame has no data' message. 3) why? if a DataFrame is empty(i.e. contain no data at all.Mind you DataFrame with Nan values is considered non empty) then it is desirable not to plot but put out a message : Suppose we have two DataFrames df1 and df2. The function myfunc takes any DataFrame(df1 and df2 in this case) and print a message if a DataFrame is empty(instead of plotting):
df1 df2
col1 col2 col1 col2
Nan 2 Nan Nan
2 Nan Nan Nan
and the function:
def myfunc(df):
if (df.count().sum())>0: ##count the total number of non Nan values.Equal to 0 if DataFrame is empty
print('not empty')
df.plot(kind='barh')
else:
display a message instead of plotting if it is empty
print('empty')
if (value == "") {
// it is empty
}
I have modified @skafandri answer to avoid re-apply the datepicker
constructor to all inputs with .datepicker_recurring_start
class.
Here's the HTML:
<div id="content"></div>
<button id="cmd">add a datepicker</button>
Here's the JS:
$('#cmd').click(function() {
var new_datepicker = $('<input type="text">').datepicker();
$('#content').append('<br>a datepicker ').append(new_datepicker);
});
here's a working demo
Lazy exceptions occur when you fetch an object typically containing a collection which is lazily loaded, and try to access that collection.
You can avoid this problem by
Hibernate.initialize(obj);
Fetch profiles
to select lazy/non-lazy fetching runtimeFurther I would recommend looking at the related
links to your right where this question has been answered many times before. Also see Hibernate lazy-load application design.
You could use a StringReader and convert the reader to an input stream using the solution in this other stackoverflow post.
If you want to use @Html.EditorFor() you have to use jQuery ui and update your Asp.net Mvc to 5.2.6.0 with NuGet Package Manager.
@Html.EditorFor(m => m.EntryDate, new { htmlAttributes = new { @class = "datepicker" } })
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script>
$(document).ready(function(){
$('.datepicker').datepicker();
});
</script>
}
If you hava a fact png (1MB for 400x400 etc.):
__import__("importlib").import_module("PIL.Image").open("out.png").save("out.png")
Not sure if this is valid but it worked for me.
The code :
<div style='position:relative;background-color:#000000;width:600px;height:30px;border:solid;'>_x000D_
<p style='display:inline;color:#ffffff;float:left;'> Whatever </p> _x000D_
<a style='position:absolute;top:0px;left:0px;width:100%;height:100%;display:inline;' href ='#'></a>_x000D_
</div>
_x000D_
You can call the stat() function and use the S_ISREG()
macro on the st_mode
field of the stat structure in order to determine if your path points to a regular file:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int is_regular_file(const char *path)
{
struct stat path_stat;
stat(path, &path_stat);
return S_ISREG(path_stat.st_mode);
}
Note that there are other file types besides regular and directory, like devices, pipes, symbolic links, sockets, etc. You might want to take those into account.
Also see:
core.whitespace = cr-at-eol
or equivalently,
[core]
whitespace = cr-at-eol
where whitespace
is preceded by a tab character.
The -nc
, --no-clobber
option isn't the best solution as newer files will not be downloaded. One should use -N
instead which will download and overwrite the file only if the server has a newer version, so the correct answer is:
wget -N http://www.example.com/images/misc/pic.png
Then running Wget with -N, with or without
-r
or-p
, the decision as to whether or not to download a newer copy of a file depends on the local and remote timestamp and size of the file.-nc
may not be specified at the same time as-N
.
-N
,--timestamping
: Turn on time-stamping.
"How can I directly (without saving the file on 2nd server) download the file from 1st server to client's machine?"
Just use the Client
API and get the InputStream
from the response
Client client = ClientBuilder.newClient();
String url = "...";
final InputStream responseStream = client.target(url).request().get(InputStream.class);
There are two flavors to get the InputStream
. You can also use
Response response = client.target(url).request().get();
InputStream is = (InputStream)response.getEntity();
Which one is the more efficient? I'm not sure, but the returned InputStream
s are different classes, so you may want to look into that if you care to.
From 2nd server I can get a ByteArrayOutputStream to get the file from 1st server, can I pass this stream further to the client using the REST service?
So most of the answers you'll see in the link provided by @GradyGCooper seem to favor the use of StreamingOutput
. An example implementation might be something like
final InputStream responseStream = client.target(url).request().get(InputStream.class);
System.out.println(responseStream.getClass());
StreamingOutput output = new StreamingOutput() {
@Override
public void write(OutputStream out) throws IOException, WebApplicationException {
int length;
byte[] buffer = new byte[1024];
while((length = responseStream.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
out.flush();
responseStream.close();
}
};
return Response.ok(output).header(
"Content-Disposition", "attachment, filename=\"...\"").build();
But if we look at the source code for StreamingOutputProvider, you'll see in the writeTo
, that it simply writes the data from one stream to another. So with our implementation above, we have to write twice.
How can we get only one write? Simple return the InputStream
as the Response
final InputStream responseStream = client.target(url).request().get(InputStream.class);
return Response.ok(responseStream).header(
"Content-Disposition", "attachment, filename=\"...\"").build();
If we look at the source code for InputStreamProvider, it simply delegates to ReadWriter.writeTo(in, out)
, which simply does what we did above in the StreamingOutput
implementation
public static void writeTo(InputStream in, OutputStream out) throws IOException {
int read;
final byte[] data = new byte[BUFFER_SIZE];
while ((read = in.read(data)) != -1) {
out.write(data, 0, read);
}
}
Asides:
Client
objects are expensive resources. You may want to reuse the same Client
for request. You can extract a WebTarget
from the client for each request.
WebTarget target = client.target(url);
InputStream is = target.request().get(InputStream.class);
I think the WebTarget
can even be shared. I can't find anything in the Jersey 2.x documentation (only because it is a larger document, and I'm too lazy to scan through it right now :-), but in the Jersey 1.x documentation, it says the Client
and WebResource
(which is equivalent to WebTarget
in 2.x) can be shared between threads. So I'm guessing Jersey 2.x would be the same. but you may want to confirm for yourself.
You don't have to make use of the Client
API. A download can be easily achieved with the java.net
package APIs. But since you're already using Jersey, it doesn't hurt to use its APIs
The above is assuming Jersey 2.x. For Jersey 1.x, a simple Google search should get you a bunch of hits for working with the API (or the documentation I linked to above)
I'm such a dufus. While the OP and I are contemplating ways to turn a ByteArrayOutputStream
to an InputStream
, I missed the simplest solution, which is simply to write a MessageBodyWriter
for the ByteArrayOutputStream
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
@Provider
public class OutputStreamWriter implements MessageBodyWriter<ByteArrayOutputStream> {
@Override
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return ByteArrayOutputStream.class == type;
}
@Override
public long getSize(ByteArrayOutputStream t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return -1;
}
@Override
public void writeTo(ByteArrayOutputStream t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
throws IOException, WebApplicationException {
t.writeTo(entityStream);
}
}
Then we can simply return the ByteArrayOutputStream
in the response
return Response.ok(baos).build();
D'OH!
Here are the tests I used (
Resource class
@Path("test")
public class TestResource {
final String path = "some_150_mb_file";
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response doTest() throws Exception {
InputStream is = new FileInputStream(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[4096];
while ((len = is.read(buffer, 0, buffer.length)) != -1) {
baos.write(buffer, 0, len);
}
System.out.println("Server size: " + baos.size());
return Response.ok(baos).build();
}
}
Client test
public class Main {
public static void main(String[] args) throws Exception {
Client client = ClientBuilder.newClient();
String url = "http://localhost:8080/api/test";
Response response = client.target(url).request().get();
String location = "some_location";
FileOutputStream out = new FileOutputStream(location);
InputStream is = (InputStream)response.getEntity();
int len = 0;
byte[] buffer = new byte[4096];
while((len = is.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
out.close();
is.close();
}
}
So the final solution for this particular use case was for the OP to simply pass the OutputStream
from the StreamingOutput
's write
method. Seems the third-party API, required a OutputStream
as an argument.
StreamingOutput output = new StreamingOutput() {
@Override
public void write(OutputStream out) {
thirdPartyApi.downloadFile(.., .., .., out);
}
}
return Response.ok(output).build();
Not quite sure, but seems the reading/writing within the resource method, using ByteArrayOutputStream`, realized something into memory.
The point of the downloadFile
method accepting an OutputStream
is so that it can write the result directly to the OutputStream
provided. For instance a FileOutputStream
, if you wrote it to file, while the download is coming in, it would get directly streamed to the file.
It's not meant for us to keep a reference to the OutputStream
, as you were trying to do with the baos
, which is where the memory realization comes in.
So with the way that works, we are writing directly to the response stream provided for us. The method write
doesn't actually get called until the writeTo
method (in the MessageBodyWriter
), where the OutputStream
is passed to it.
You can get a better picture looking at the MessageBodyWriter
I wrote. Basically in the writeTo
method, replace the ByteArrayOutputStream
with StreamingOutput
, then inside the method, call streamingOutput.write(entityStream)
. You can see the link I provided in the earlier part of the answer, where I link to the StreamingOutputProvider
. This is exactly what happens
I had issues with spaces showing in between my output and there was no answer online at all to fix this issue. I literally spend many hours trying to find a solution and found one from playing around with the code to the point that I almost did not even know what I typed in at the time that I got it to work. Here is my fix for the issue: [System.Text.Encoding]::UTF8.GetString(([System.Convert]::FromBase64String($base64string)|?{$_}))
To add to rcs' answer, if you want to use position_dodge() with geom_bar() when x is a POSIX.ct date, you must multiply the width by 86400, e.g.,
ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) +
geom_bar(position = "dodge", stat = 'identity') +
geom_text(aes(label=Number), position=position_dodge(width=0.9*86400), vjust=-0.25)
Find below code to get database connection from your web app server. Just create datasource in app server and use following code to get connection :
// To Get DataSource
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("jdbc/abcd");
// Get Connection and Statement
Connection c = ds.getConnection();
stmt = c.createStatement();
Import naming and sql classes. No need to add any xml file or to edit anything in project.
That's it..
this is a good sample for understand directive phases http://codepen.io/anon/pen/oXMdBQ?editors=101
var app = angular.module('myapp', [])
app.directive('slngStylePrelink', function() {
return {
scope: {
drctvName: '@'
},
controller: function($scope) {
console.log('controller for ', $scope.drctvName);
},
compile: function(element, attr) {
console.log("compile for ", attr.name)
return {
post: function($scope, element, attr) {
console.log('post link for ', attr.name)
},
pre: function($scope, element, attr) {
$scope.element = element;
console.log('pre link for ', attr.name)
// from angular.js 1.4.1
function ngStyleWatchAction(newStyles, oldStyles) {
if (oldStyles && (newStyles !== oldStyles)) {
forEach(oldStyles, function(val, style) {
element.css(style, '');
});
}
if (newStyles) element.css(newStyles);
}
$scope.$watch(attr.slngStylePrelink, ngStyleWatchAction, true);
// Run immediately, because the watcher's first run is async
ngStyleWatchAction($scope.$eval(attr.slngStylePrelink));
}
};
}
};
});
html
<body ng-app="myapp">
<div slng-style-prelink="{height:'500px'}" drctv-name='parent' style="border:1px solid" name="parent">
<div slng-style-prelink="{height:'50%'}" drctv-name='child' style="border:1px solid red" name='child'>
</div>
</div>
</body>
I was able to work it out only after adding those two TOGETHER:
dependencies {
...
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.android.support:cardview-v7:27.1.1'
...
}
in my build.gradle (Module:app) file
and then press the sync now button
You can use the REGEXP_LIKE
function as:
SELECT X
FROM myTable
WHERE REGEXP_LIKE(X, '^[[:digit:]]+$');
Sample run:
SQL> SELECT X FROM SO;
X
--------------------
12c
123
abc
a12
SQL> SELECT X FROM SO WHERE REGEXP_LIKE(X, '^[[:digit:]]+$');
X
--------------------
123
SQL>
Use the random
module: http://docs.python.org/library/random.html
import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)
This samples the two values without replacement (so the two values are different).
Copy the table structure:-
select * into newtable from oldtable where 1=2;
Copy the table structure along with table data:-
select * into newtable from oldtable where 1=1;
The params object is included in $stateParams, but won't be part of the url.
1) In the route configuration:
$stateProvider.state('edit_user', {
url: '/users/:user_id/edit',
templateUrl: 'views/editUser.html',
controller: 'editUserCtrl',
params: {
paramOne: { objectProperty: "defaultValueOne" }, //default value
paramTwo: "defaultValueTwo"
}
});
2) In the controller:
.controller('editUserCtrl', function ($stateParams, $scope) {
$scope.paramOne = $stateParams.paramOne;
$scope.paramTwo = $stateParams.paramTwo;
});
3A) Changing the State from a controller
$state.go("edit_user", {
user_id: 1,
paramOne: { objectProperty: "test_not_default1" },
paramTwo: "from controller"
});
3B) Changing the State in html
<div ui-sref="edit_user({ user_id: 3, paramOne: { objectProperty: 'from_html1' }, paramTwo: 'fromhtml2' })"></div>
If someone wants to implement using directives then, identify (or create) a div in the index.html (just under the body tag, or at same DOM level)
<div class="google-analytics"/>
and then add the following code in the directive
myApp.directive('googleAnalytics', function ( $location, $window ) {
return {
scope: true,
link: function (scope) {
scope.$on( '$routeChangeSuccess', function () {
$window._gaq.push(['_trackPageview', $location.path()]);
});
}
};
});
Try putting your php into an html document:
Note: your file is not saved as index.html but it is saved as index.php or your php wont work!
//dont inline your style
<link rel="stylesheet" type="text/css" href="mystyle.css"> //<--this is the proper way!
//save a separate style sheet (i.e. cascading style sheet aka: css)
If it is the first element, i.e. $array[0]
, you can try:
echo key($array);
If it is the second element, i.e. $array[1]
, you can try:
next($array);
echo key($array);
I think this method is should be used when required element is the first, second or at most third element of the array. For other cases, loops should be used otherwise code readability decreases.
I had the same problem and tried all the suggestions above. My dates were formatted mm/dd/yyyy. In desperation I tried the following:
I hope this helps.
In addition to the other troubleshooting steps above, I would also like to add that if you have enabled two-factor authentication (also known as two-step verification) on your GMail account, you must generate an application-specific password and use that newly generated password to authenticate via SMTP.
To create one, visit: https://www.google.com/settings/ and choose Authorizing applications & sites to generate the password.
You can do it like that but storing a DataSet object in Session is not very efficient. If you have a web app with lots of users it will clog your server memory really fast.
If you really must do it like that I suggest removing it from the session as soon as you don't need the DataSet.
You could use the same mechanism as git submodule init
uses itself, namely, look at .gitmodules
. This files enumerates each submodule path and the URL it refers to.
For example, from root of repository, cat .gitmodules
will print contents to the screen (assuming you have cat
).
Because .gitmodule files have the Git configuration format, you can use git config to parse those files:
git config --file .gitmodules --name-only --get-regexp path
Would show you all submodule entries, and with
git config --file .gitmodules --get-regexp path | awk '{ print $2 }'
you would only get the submodule path itself.
An image may say more than a thousand words:
* Figure describing the complexity of a modern multi-processor, multi-core system.
Source:
If you want to use test
instead of []
, then you can use !
to get the negation:
if ! test "$FILE"; then
echo "does not exist"
fi
Use Commons' DefaultedMap if you don't feel like reinventing the wheel, e.g.,
Map<String, String> map = new DefaultedMap<>("[NO ENTRY FOUND]");
String surname = map.get("Surname");
// surname == "[NO ENTRY FOUND]"
You can also pass in an existing map if you're not in charge of creating the map in the first place.
You should check out scipy.sparse. You can apply operations on those sparse matrices just like how you use a normal matrix.
var key = "Name_radio";
var val = "value_radio";
var rdo = $('*[name="' + key + '"]');
if (rdo.attr('type') == "radio") {
$.each(rdo, function (keyT, valT){
if ((valT.value == $.trim(val)) && ($.trim(val) != '') && ($.trim(val) != null))
{
$('*[name="' + key + '"][value="' + (val) + '"]').prop('checked', true);
}
})
}
"À la" Scala way (but I think is the most Pythonic way as the OP demands):
description = """
| The intention of this module is to provide a method to
| pass meta information in markdown_ header files for
| using it in jinja_ templates.
|
| Also, to provide a method to use markdown files as jinja
| templates. Maybe you prefer to see the code than
| to install it.""".replace('\n | \n','\n').replace(' | ',' ')
If you want final str without jump lines, just put \n
at the start of the first argument of the second replace:
.replace('\n | ',' ')`.
Note: the white line between "...templates." and "Also, ..." requires a white space after the |
.
SQL is primarily a set-orientated language - it's generally a bad idea to use a loop in it.
In this case, a similar result could be achieved using a recursive CTE:
with cte as
(select 1 i union all
select i+1 i from cte where i < 5)
select dateadd(d, i-1, '2010-01-01') from cte
You can also try and provide an Id for the main layout and change the background of that through basic manipulation and retrieval. E.g:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/hello"
Which can then be followed by accessing through R.id.hello.... Pretty basic and I hope this does help :)
NPM shrinkwrap offers a nice solution to this problem. It allows us to override that version of a particular dependency of a particular sub-module.
Essentially, when you run npm install, npm will first look in your root directory to see whether a npm-shrinkwrap.json file exists. If it does, it will use this first to determine package dependencies, and then falling back to the normal process of working through the package.json files.
To create an npm-shrinkwrap.json, all you need to do is
npm shrinkwrap --dev
code:
{
"dependencies": {
"grunt-contrib-connect": {
"version": "0.3.0",
"from": "[email protected]",
"dependencies": {
"connect": {
"version": "2.8.1",
"from": "connect@~2.7.3"
}
}
}
}
}
You should design your table WITHOUT considering the views.
Apart from saving joins and conditions, Views do have a performance advantage: SQL Server may calculate and save its execution plan in the view, and therefore make it faster than "on the fly" SQL statements.
View may also ease your work regarding user access at field level.
Try changing every occurence of .\Release into .\x64\Release in the x64 properties. At least this worked for me...
public String lastChars(String a) {
if(a.length()>=1{
String str1 =a.substring(b.length()-1);
}
return str1;
}
In addition to Peter's answer:
#element::-webkit-scrollbar {
display: none;
}
This will work the same for Internet Explorer 10:
#element {
-ms-overflow-style: none;
}
How is this different from the following?
This line of code here:
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
constructs a new String object (i.e. a copy of oldString
), while this line of code:
String newString = oldString;
declares a new variable of type java.lang.String
and initializes it to refer to the same String object as the variable oldString
.
Is there any scenario in which the two lines will have different outputs?
Absolutely:
String newString = oldString;
boolean isSameInstance = newString == oldString; // isSameInstance == true
vs.
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
// isSameInstance == false (in most cases)
boolean isSameInstance = newString == oldString;
a_horse_with_no_name (see comment) is right of course. The equivalent of
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
is
String newString = new String(oldString);
minus the subtle difference wrt the encoding that Peter Lawrey explains in his answer.
It looks like there is no difference, for
uses each
underneath.
$ irb
>> for x in nil
>> puts x
>> end
NoMethodError: undefined method `each' for nil:NilClass
from (irb):1
>> nil.each {|x| puts x}
NoMethodError: undefined method `each' for nil:NilClass
from (irb):4
Like Bayard says, each is more idiomatic. It hides more from you and doesn't require special language features. Per Telemachus's Comment
for .. in ..
sets the iterator outside the scope of the loop, so
for a in [1,2]
puts a
end
leaves a
defined after the loop is finished. Where as each
doesn't. Which is another reason in favor of using each
, because the temp variable lives a shorter period.
If you really need to use a secure foreach interface to iterate an object and make it reusable and clean with a npm module, then use this, https://www.npmjs.com/package/foreach-object
Ex:
import each from 'foreach-object';
const object = {
firstName: 'Arosha',
lastName: 'Sum',
country: 'Australia'
};
each(object, (value, key, object) => {
console.log(key + ': ' + value);
});
// Console log output will be:
// firstName: Arosha
// lastName: Sum
// country: Australia
Try:
which( !is.na(p), arr.ind=TRUE)
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3
[[2]]
[1] 4 7
[[3]]
integer(0)
[[4]]
[1] 5
[[5]]
integer(0)
Or even with smushing together with paste:
lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
The output from which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:
> which( !is.na(p), arr.ind=TRUE)
row col
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 4 5
[5,] 2 7
Without the arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".
> which( !is.na(p) )
[1] 6 11 17 24 32
Python 3.7: introduction of defaults
param in namedtuple definition.
Example as shown in the documentation:
>>> Account = namedtuple('Account', ['type', 'balance'], defaults=[0])
>>> Account._fields_defaults
{'balance': 0}
>>> Account('premium')
Account(type='premium', balance=0)
Read more here.
Note: I know this is a hack, but it was useful for Angular 1.2 and earlier that didn't provide a simple mechanism.
The validation kicks in on the change event, so some things like changing the values programmatically won't trigger it. But triggering the change event will trigger the validation. For example, with jQuery:
$('#formField1, #formField2').trigger('change');
You can use :
-XX:MaxPermSize=128m
to increase the space. But this usually only postpones the inevitable.
You can also enable the PermGen to be garbage collected
-XX:+UseConcMarkSweepGC -XX:+CMSPermGenSweepingEnabled -XX:+CMSClassUnloadingEnabled
Usually this occurs when doing lots of redeploys. I am surprised you have it using something like indexing. Use virtualvm or jconsole to monitor the Perm gen space and check it levels off after warming up the indexing.
Maybe you should consider changing to another JVM like the IBM JVM. It does not have a Permanent Generation and is immune to this issue.
Just use the 'Rebuild Project' from the 'Build' menu from the top menu bar.
// Initiate set interval and assign it to intervalListener
var intervalListener = self.setInterval(function () {someProcess()}, 1000);
function someProcess() {
console.log('someProcess() has been called');
// If some condition is true clear the interval
if (stopIntervalIsTrue) {
window.clearInterval(intervalListener);
}
}
I got error sometimes when using $(`code`)
constructor.
Finally i got some approach to that here: https://stackoverflow.com/a/7902174/2480481
Basically, using Tee to read again the ouput and putting it into a variable. Theres how you see the normal output then read it from the ouput.
is not? I guess your current task genhash will output just that, a single string hash so might work for you.
Im so neewbie and still looking for full output & save into 1 command. Regards.
Btw "date" is usually tagged as "obsolete / deprecated" (I dont know exactly why) - something about it is wrote there Java: Why is the Date constructor deprecated, and what do I use instead?
It looks like it's a problem of the constructor only- way via new Date(int year, int month, int day), recommended way is via Calendar and set params separately .. (Calendar cal = Calendar.getInstance(); )
Well. Not long ago I also met this question. And finally I get the solutions which really address this issue.
My problem symptoms are also the pages not loading and find the json data was be randomly truncated.
Here are the solutions which I summary could help to solve this problem
1.Kill the anti-virus software process
2.Close chrome's Prerendering Instant pages feature
3.Try to close all the apps in your browser
4.Try to define your Content-Length header
<?php
header('Content-length: ' . strlen($output));
?>
5.Check your nginx fastcgi buffer is right
6.Check your nginx gzip is open
You can compile with either Cygwin's g++
or MinGW (via stand-alone or using Cygwin package). However, in order to run it, you need to add the Cygwin1.dll
(and others) PATH to the system Windows PATH, before any cygwin style paths.
Thus add: ;C:\cygwin64\bin
to the end of your Windows system PATH
variable.
Also, to compile for use in CMD or PowerShell, you may need to use:
x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe
(This invokes the cross-compiler, if installed.)
You can use NumericUpDown control for WPF written by me as a part of WPFControls library.
Go to Run type services.msc.
Check whether or not MySQL services are running. If not, start it manually. Once it is started, type MySQL Show
to test the service.
Though you already have an accepted answer, I figured I'd add this for anyone else interested in a different solution-
An implementation could be as follows:
import csv
with open('C:/mypath/to/csvfile.csv', 'r') as f:
d_reader = csv.DictReader(f)
#get fieldnames from DictReader object and store in list
headers = d_reader.fieldnames
for line in d_reader:
#print value in MyCol1 for each row
print(line['MyCol1'])
In the above, d_reader.fieldnames returns a list of your headers (assuming the headers are in the top row). Which allows...
>>> print(headers)
['MyCol1', 'MyCol2', 'MyCol3']
If your headers are in, say the 2nd row (with the very top row being row 1), you could do as follows:
import csv
with open('C:/mypath/to/csvfile.csv', 'r') as f:
#you can eat the first line before creating DictReader.
#if no "fieldnames" param is passed into
#DictReader object upon creation, DictReader
#will read the upper-most line as the headers
f.readline()
d_reader = csv.DictReader(f)
headers = d_reader.fieldnames
for line in d_reader:
#print value in MyCol1 for each row
print(line['MyCol1'])