Check this out:
XAML:
<DataGrid Name="DataGrid1">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Click="ChangeText">Show/Hide</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Method:
private void ChangeText(object sender, RoutedEventArgs e)
{
DemoModel model = (sender as Button).DataContext as DemoModel;
model.DynamicText = (new Random().Next(0, 100).ToString());
}
Class:
class DemoModel : INotifyPropertyChanged
{
protected String _text;
public String Text
{
get { return _text; }
set { _text = value; RaisePropertyChanged("Text"); }
}
protected String _dynamicText;
public String DynamicText
{
get { return _dynamicText; }
set { _dynamicText = value; RaisePropertyChanged("DynamicText"); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(String propertyName)
{
PropertyChangedEventHandler temp = PropertyChanged;
if (temp != null)
{
temp(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Initialization Code:
ObservableCollection<DemoModel> models = new ObservableCollection<DemoModel>();
models.Add(new DemoModel() { Text = "Some Text #1." });
models.Add(new DemoModel() { Text = "Some Text #2." });
models.Add(new DemoModel() { Text = "Some Text #3." });
models.Add(new DemoModel() { Text = "Some Text #4." });
models.Add(new DemoModel() { Text = "Some Text #5." });
DataGrid1.ItemsSource = models;
You could simply return a value from the function:
var response = 0;
function doSomething() {
// some code
return 10;
}
response = doSomething();
The theoretical limit (on Windows) for the maximum size of a UDP packet is 65507 bytes. This is documented here:
The correct maximum UDP message size is 65507, as determined by the following formula: 0xffff - (sizeof(IP Header) + sizeof(UDP Header)) = 65535-(20+8) = 65507
That being said, most protocols limit to a much smaller size - usually either 512 or occasionally 8192. You can often go higher than 548 safely if you are on a reliable network - but if you're broadcasting across the internet at large, the larger you go, the more likely you'll be to run into packet transmission problems and loss.
Also, you can display current position by "drag" listener and write it to visible or hidden field. You may also need to store zoom. Here's copy&paste from working tool:
function map_init() {
var lt=48.451778;
var lg=31.646305;
var myLatlng = new google.maps.LatLng(lt,lg);
var mapOptions = {
center: new google.maps.LatLng(lt,lg),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'),mapOptions);
var marker = new google.maps.Marker({
position:myLatlng,
map:map,
draggable:true
});
google.maps.event.addListener(
marker,
'drag',
function() {
document.getElementById('lat1').innerHTML = marker.position.lat().toFixed(6);
document.getElementById('lng1').innerHTML = marker.position.lng().toFixed(6);
document.getElementById('zoom').innerHTML = mapObject.getZoom();
// Dynamically show it somewhere if needed
$(".x").text(marker.position.lat().toFixed(6));
$(".y").text(marker.position.lng().toFixed(6));
$(".z").text(map.getZoom());
}
);
}
Make a string criteria to search for, like this:
string searchExpression = "ID = 5"
Then use the .Select()
method of the DataTable
object, like this:
DataRow[] foundRows = YourDataTable.Select(searchExpression);
Now you can loop through the results, like this:
int numberOfCalls;
bool result;
foreach(DataRow dr in foundRows)
{
// Get value of Calls here
result = Int32.TryParse(dr["Calls"], out numberOfCalls);
// Optionally, you can check the result of the attempted try parse here
// and do something if you wish
if(result)
{
// Try parse to 32-bit integer worked
}
else
{
// Try parse to 32-bit integer failed
}
}
Use this to delete everything:
docker system prune -a --volumes
Remove all unused containers, volumes, networks and images
WARNING! This will remove:
- all stopped containers
- all networks not used by at least one container
- all volumes not used by at least one container
- all images without at least one container associated to them
- all build cache
https://docs.docker.com/engine/reference/commandline/system_prune/#extended-description
Ensure that Enhanced session mode settings are enabled on the Hyper-V host.
Start Hyper-V Manager, and in the Actions section, select "Hyper-V Settings".
Make sure that enhanced session mode is allowed in the Server section. Then, make sure that the enhanced session mode is available in the User section.
Enable Hyper-V Guest Services for your virtual machine
Right-click on Virtual Machine > Settings. Select the Integration Services in the left-lower corner of the menu. Check Guest Service and click OK.
Start a virtual machine and click Show Options in the pop-up windows.
Or click "Edit Session Settings..." in the Actions panel on the right
It may only appear when you're (able to get) connected to it. If it doesn't appear try Starting and then Connecting to the VM while paying close attention to the panel in the Hyper-V Manager.
View local resources. Then, select the "More..." menu.
From there, you can choose which devices to share. Removable drives are especially useful for file sharing.
Choose to "Save my settings for future connections to this virtual machine".
Click Connect. Drive sharing is now complete, and you will see the shared drive in this PC > Network Locations section of Windows Explorer after using the enhanced session mode to sigh to the VM. You should now be able to copy files from a physical machine and paste them into a virtual machine, and vice versa.
Source (and for more info): Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine
Auth::user()->products->sum('price');
The documentation is a little light for some of the Collection
methods but all the query builder aggregates are seemingly available besides avg()
that can be found at http://laravel.com/docs/queries#aggregates.
It's been some years since I last worked with Access but larger database files always used to have more problems and be more prone to corruption than smaller files.
Unless the database file is only being accessed by one person or stored on a robust network you may find this is a problem before the 2GB database size limit is reached.
The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:
$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
--forward-agent \
--disable-known-hosts deploy:$target; then
echo failed
else
echo succeeded
fi
$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed
Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.
[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr
option that you can set to make it carriage-return-tolerant.
If you run your code from an installed package, make sure template files are present in directory <python root>/lib/site-packages/your-package/templates
.
Some details:
In my case I was trying to run examples of project flask_simple_ui and jinja
would always say
jinja2.exceptions.TemplateNotFound: form.html
The trick was that sample program would import installed package flask_simple_ui
. And ninja
being used from inside that package is using as root directory for lookup the package path, in my case ...python/lib/site-packages/flask_simple_ui
, instead of os.getcwd()
as one would expect.
To my bad luck, setup.py
has a bug and doesn't copy any html files, including the missing form.html
. Once I fixed setup.py
, the problem with TemplateNotFound vanished.
I hope it helps someone.
From Stroustrup's speech at "Going Native 2012":
template<int M, int K, int S> struct Unit { // a unit in the MKS system
enum { m=M, kg=K, s=S };
};
template<typename Unit> // a magnitude with a unit
struct Value {
double val; // the magnitude
explicit Value(double d) : val(d) {} // construct a Value from a double
};
using Speed = Value<Unit<1,0,-1>>; // meters/second type
using Acceleration = Value<Unit<1,0,-2>>; // meters/second/second type
using Second = Unit<0,0,1>; // unit: sec
using Second2 = Unit<0,0,2>; // unit: second*second
constexpr Value<Second> operator"" s(long double d)
// a f-p literal suffixed by ‘s’
{
return Value<Second> (d);
}
constexpr Value<Second2> operator"" s2(long double d)
// a f-p literal suffixed by ‘s2’
{
return Value<Second2> (d);
}
Speed sp1 = 100m/9.8s; // very fast for a human
Speed sp2 = 100m/9.8s2; // error (m/s2 is acceleration)
Speed sp3 = 100/9.8s; // error (speed is m/s and 100 has no unit)
Acceleration acc = sp1/0.5s; // too fast for a human
If you wanna do with a button click and not the other way. You can do it by adding location.href
to your button. Here is how I'm using
<button class="btn btn-lg btn-primary" id="submit" onclick="location.href ='/dashboard'" >Go To Dashboard</button>
The button above uses bootstrap classes for styling. Without styling, the simplest code would be
<button onclick="location.href ='/dashboard'" >Go To Dashboard</button>
The /dashboard
is my JSP page, If you are using extension too then used /dashboard.jsp
I add the ",-std=c++0x" after "-c -fmessage-length=0",under Project Properties -> C/C++ Build -> Settings -> GCC C++ Compiler -> Miscellaneous. Dont't forget to add the comma "," as the seperator.
Just thought I would post something that I found quite useful and could be possible for someone who experiences similar needs.
The following method was a method I wrote for my JavaFX application to avoid having to cast and also avoid writing if object x instance of object b statements every time the controller was returned.
public <U> Optional<U> getController(Class<U> castKlazz){
try {
return Optional.of(fxmlLoader.<U>getController());
}catch (Exception e){
e.printStackTrace();
}
return Optional.empty();
}
The method declaration for obtaining the controller was
public <T> T getController()
By using type U passed into my method via the class object, it could be forwarded to the method get controller to tell it what type of object to return. An optional object is returned in case the wrong class is supplied and an exception occurs in which case an empty optional will be returned which we can check for.
This is what the final call to the method looked like (if present of the optional object returned takes a Consumer
getController(LoadController.class).ifPresent(controller->controller.onNotifyComplete());
Here is a robust function for using UTL_File.putline that includes the necessary error handling. It also handles headers, footers and a few other exceptional cases.
PROCEDURE usp_OUTPUT_ToFileAscii(p_Path IN VARCHAR2, p_FileName IN VARCHAR2, p_Input IN refCursor, p_Header in VARCHAR2, p_Footer IN VARCHAR2, p_WriteMode VARCHAR2) IS
vLine VARCHAR2(30000);
vFile UTL_FILE.file_type;
vExists boolean;
vLength number;
vBlockSize number;
BEGIN
UTL_FILE.fgetattr(p_path, p_FileName, vExists, vLength, vBlockSize);
FETCH p_Input INTO vLine;
IF p_input%ROWCOUNT > 0
THEN
IF vExists THEN
vFile := UTL_FILE.FOPEN_NCHAR(p_Path, p_FileName, p_WriteMode);
ELSE
--even if the append flag is passed if the file doesn't exist open it with W.
vFile := UTL_FILE.FOPEN(p_Path, p_FileName, 'W');
END IF;
--GET HANDLE TO FILE
IF p_Header IS NOT NULL THEN
UTL_FILE.PUT_LINE(vFile, p_Header);
END IF;
UTL_FILE.PUT_LINE(vFile, vLine);
DBMS_OUTPUT.PUT_LINE('Record count > 0');
--LOOP THROUGH CURSOR VAR
LOOP
FETCH p_Input INTO vLine;
EXIT WHEN p_Input%NOTFOUND;
UTL_FILE.PUT_LINE(vFile, vLine);
END LOOP;
IF p_Footer IS NOT NULL THEN
UTL_FILE.PUT_LINE(vFile, p_Footer);
END IF;
CLOSE p_Input;
UTL_FILE.FCLOSE(vFile);
ELSE
DBMS_OUTPUT.PUT_LINE('Record count = 0');
END IF;
EXCEPTION
WHEN UTL_FILE.INVALID_PATH THEN
DBMS_OUTPUT.PUT_LINE ('invalid_path');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_MODE THEN
DBMS_OUTPUT.PUT_LINE ('invalid_mode');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_FILEHANDLE THEN
DBMS_OUTPUT.PUT_LINE ('invalid_filehandle');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_OPERATION THEN
DBMS_OUTPUT.PUT_LINE ('invalid_operation');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.READ_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('read_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.WRITE_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('write_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INTERNAL_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('internal_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE ('other write error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
END;
If anyone else stuck on same point, following solved my problem.
In web.xml
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
In Session component
@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
In pom.xml
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.1</version>
</dependency>
Using your example dataframe, we could:
xtabs(value ~ name + numbers, data = dat1)
ARIA (Accessible Rich Internet Applications) defines a way to make Web content and Web applications more accessible to people with disabilities.
The hidden
attribute is new in HTML5 and tells browsers not to display the element. The aria-hidden
property tells screen-readers if they should ignore the element. Have a look at the w3 docs for more details:
https://www.w3.org/WAI/PF/aria/states_and_properties#aria-hidden
Using these standards can make it easier for disabled people to use the web.
Modern answer: use java.time, the modern Java date and time API, for your date and time work. Back in 2011 it was right to use the Timestamp
class, but since JDBC 4.2 it is no longer advised.
For your work we need a time zone and a couple of formatters. We may as well declare them static:
static ZoneId zone = ZoneId.of("America/Marigot");
static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm xx");
Now the code could be for example:
while(resultSet.next()) {
ZonedDateTime dtStart = resultSet.getObject("dtStart", OffsetDateTime.class)
.atZoneSameInstant(zone);
// I would like to then have the date and time
// converted into the formats mentioned...
String dateFormatted = dtStart.format(dateFormatter);
String timeFormatted = dtStart.format(timeFormatter);
System.out.format("Date: %s; time: %s%n", dateFormatted, timeFormatted);
}
Example output (using the time your question was asked):
Date: 09/20/2011; time: 18:13 -0400
In your database timestamp with time zone
is recommended for timestamps. If this is what you’ve got, retrieve an OffsetDateTime
as I am doing in the code. I am also converting the retrieved value to the user’s time zone before formatting date and time separately. As time zone I supplied America/Marigot as an example, please supply your own. You may also leave out the time zone conversion if you don’t want any, of course.
If the datatype in SQL is a mere timestamp
without time zone, retrieve a LocalDateTime
instead. For example:
ZonedDateTime dtStart = resultSet.getObject("dtStart", LocalDateTime.class)
.atZone(zone);
No matter the details I trust you to do similarly for dtEnd
.
I wasn’t sure what you meant by the xx
in HH:MM xx
. I just left it in the format pattern string, which yields the UTC offset in hours and minutes without colon.
Link: Oracle tutorial: Date Time explaining how to use java.time.
I'd do it this way:
grid1.DataContext = dt.AsEnumerable().Where(x => x < 10).AsEnumerable().CopyToDataTable().AsDataView();
and do whatever query i want between the two AsEnumerable(). If you don't need space for query, you can just do directly this:
grid1.DataContext = dt.AsDataView();
Modified @Surendra Jnawali' code. It fails
if current time is 23:40:00 i.e greater than start time and less than equals to 23:59:59.
All credit goes to the real owner
This is how it should be :This works perfect
public static boolean isTimeBetweenTwoTime(String argStartTime,
String argEndTime, String argCurrentTime) throws ParseException {
String reg = "^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
//
if (argStartTime.matches(reg) && argEndTime.matches(reg)
&& argCurrentTime.matches(reg)) {
boolean valid = false;
// Start Time
java.util.Date startTime = new SimpleDateFormat("HH:mm:ss")
.parse(argStartTime);
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(startTime);
// Current Time
java.util.Date currentTime = new SimpleDateFormat("HH:mm:ss")
.parse(argCurrentTime);
Calendar currentCalendar = Calendar.getInstance();
currentCalendar.setTime(currentTime);
// End Time
java.util.Date endTime = new SimpleDateFormat("HH:mm:ss")
.parse(argEndTime);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endTime);
//
if (currentTime.compareTo(endTime) < 0) {
currentCalendar.add(Calendar.DATE, 1);
currentTime = currentCalendar.getTime();
}
if (startTime.compareTo(endTime) < 0) {
startCalendar.add(Calendar.DATE, 1);
startTime = startCalendar.getTime();
}
//
if (currentTime.before(startTime)) {
System.out.println(" Time is Lesser ");
valid = false;
} else {
if (currentTime.after(endTime)) {
endCalendar.add(Calendar.DATE, 1);
endTime = endCalendar.getTime();
}
System.out.println("Comparing , Start Time /n " + startTime);
System.out.println("Comparing , End Time /n " + endTime);
System.out
.println("Comparing , Current Time /n " + currentTime);
if (currentTime.before(endTime)) {
System.out.println("RESULT, Time lies b/w");
valid = true;
} else {
valid = false;
System.out.println("RESULT, Time does not lies b/w");
}
}
return valid;
} else {
throw new IllegalArgumentException(
"Not a valid time, expecting HH:MM:SS format");
}
}
RESULT
Comparing , Start Time /n Thu Jan 01 23:00:00 IST 1970
Comparing , End Time /n Fri Jan 02 02:00:00 IST 1970
Comparing , Current Time /n Fri Jan 02 01:50:00 IST 1970
RESULT, Time lies b/w
The Guava library contains convenience methods for creating lists and other collections which makes this much prettier than using the standard library classes.
Example:
ArrayList<String> list = newArrayList("a", "b", "c");
(This assumes import static com.google.common.collect.Lists.newArrayList;
)
Here I am going to export 3 tables from database named myDB in an sql file named table.sql
mysqldump -u root -p myDB table1 table2 table3 > table.sql
First, you must know that you will never be able to get the source code of a page that is not on the same domain as your page in javascript. (See http://en.wikipedia.org/wiki/Same_origin_policy).
In PHP, this is how you do it:
file_get_contents($theUrl);
In javascript, there is three ways :
Firstly, by XMLHttpRequest : http://jsfiddle.net/635YY/1/
var url="../635YY",xmlhttp;//Remember, same domain
if("XMLHttpRequest" in window)xmlhttp=new XMLHttpRequest();
if("ActiveXObject" in window)xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open('GET',url,true);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)alert(xmlhttp.responseText);
};
xmlhttp.send(null);
Secondly, by iFrames : http://jsfiddle.net/XYjuX/1/
var url="../XYjuX";//Remember, same domain
var iframe=document.createElement("iframe");
iframe.onload=function()
{
alert(iframe.contentWindow.document.body.innerHTML);
}
iframe.src=url;
iframe.style.display="none";
document.body.appendChild(iframe);
Thirdly, by jQuery : [http://jsfiddle.net/edggD/2/
$.get('../edggD',function(data)//Remember, same domain
{
alert(data);
});
]4
I just used a snippet of jquery to solve this problem.
$("input[data-val-length-max]").each(function (index, element) {
var length = parseInt($(this).attr("data-val-length-max"));
$(this).prop("maxlength", length);
});
The selector finds all of the elements that have a data-val-length-max attribute set. This is the attribute that the StringLength validation attribute will set.
The each loop loops through these matches and will parse out the value for this attribute and assign it to the mxlength property that should have been set.
Just add this to you document ready function and you are good to go.
you can also just use return:
function outer() {
function inner() {
alert("hi");
}
return inner();
}
outer();
Go to your web.config/App.config to verify which .net runtime you are using
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
Here is the solution:
.NET 4.6 and above. You don’t need to do any additional work to support TLS 1.2, it’s supported by default.
.NET 4.5. TLS 1.2 is supported, but it’s not a default protocol. You need to opt-in to use it. The following code will make TLS 1.2 default, make sure to execute it before making a connection to secured resource:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
Use a white space to match all descendants of an element:
div.dropdown * {
color: red;
}
x y
matches every element y that is inside x, however deeply nested it may be - children, grandchildren and so on.
The asterisk *
matches any element.
Official Specification: CSS 2.1: Chapter 5.5: Descendant Selectors
Once you are able to parse those strings into a Date object comparing them is easy (Using the <
operator). Parsing the dates will depend on the format. You may take a look at Datejs which might simplify this task.
This looks like a CSV file, so you could use the python csv module to read it. For example:
import csv
crimefile = open(fileName, 'r')
reader = csv.reader(crimefile)
allRows = [row for row in reader]
Using the csv module allows you to specify how things like quotes and newlines are handled. See the documentation I linked to above.
If you have (or create) a single string, you can use np.fromstring:
import numpy as np
x = ["1.1", "2.2", "3.2"]
x = ','.join(x)
x = np.fromstring( x, dtype=np.float, sep=',' )
Note, x = ','.join(x)
transforms the x array to string '1.1, 2.2, 3.2'
. If you read a line from a txt file, each line will be already a string.
In a nutshell, three easy rules to remember PECS:
<? extends T>
wildcard if you need to retrieve object of
type T
from a collection.<? super T>
wildcard if you need to put objects of type T
in
a collection.You probably want to use kind_of()
.
>> s = "something"
=> "something"
>> s.kind_of?(Array)
=> false
>> s = ["something", "else"]
=> ["something", "else"]
>> s.kind_of?(Array)
=> true
It only seems to because that is what it is printing out. But actually, you shouldn't write the logic this way. This is equivalent:
insert into errortable (dateupdated, table1id)
values (sysdate, 1083);
It seems silly to convert the system date to a string just to convert it back to a date.
If you want to see the full date, then you can do:
select TO_CHAR(dateupdated, 'YYYY-MM-DD HH24:MI:SS'), table1id
from errortable;
You can run the following query to check for the existance of the user table.
SELECT * FROM information_schema.TABLES
WHERE TABLE_NAME LIKE '%user%'
See if you can find a row with the following values in
mysql user BASE TABLE MyISAM
If you cant find this table look at the following link to rebuild the database How to recover/recreate mysql's default 'mysql' database
Here is a solution in Scala:
def subsets[T](s : Set[T]) : Set[Set[T]] =
if (s.size == 0) Set(Set()) else {
val tailSubsets = subsets(s.tail);
tailSubsets ++ tailSubsets.map(_ + s.head)
}
In RatingBar
give attribute:
style="?android:attr/ratingBarStyleIndicator"
.Net 4.5 introduces a new Caller Information Attributes.
private void OnPropertyChanged<T>([CallerMemberName]string caller = null) {
// make sure only to call this if the value actually changes
var handler = PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs(caller));
}
}
It's probably a good idea to add a comparer to the function as well.
EqualityComparer<T>.Default.Equals
I'm using AWS Elasticbeanstalk + Docker + Supervisord.
Just add some code in Dockerfile
.
CMD echo 123.123.123.123 this_is_my.host >> /etc/hosts; supervisord -n;
I modified the solution by @Kalyani and so far it's been working beautifully!
$('selector').click(function(event) {
if(!event.detail || event.detail == 1){ return true; }
else { return false; }
});
Something like:
var line = "foo bar lol";
line.substring(0, 5) + '...' // gives "foo b..."
Check out http://www.odata.org/
It defines the MERGE method, so in your case it would be something like this:
MERGE /customer/123
<customer>
<status>DISABLED</status>
</customer>
Only the status
property is updated and the other values are preserved.
I found an easier solution that may help beginners to coding.
go to
C:\Users\'-your user-'\AppData\Roaming\jupyter\runtime
and find a file named
nbserver-6176-open.html
then
Right-click > open with > Choose default program...
Here, what ever you choose would be saved on your Windows to open all HTML files; therefore when you run Jupyter notebook, it would open in the program you want.
JPA specification contains a very precise description of semantics of these operations, better than in javadoc:
The semantics of the persist operation, applied to an entity X are as follows:
If X is a new entity, it becomes managed. The entity X will be entered into the database at or before transaction commit or as a result of the flush operation.
If X is a preexisting managed entity, it is ignored by the persist operation. However, the persist operation is cascaded to entities referenced by X, if the relationships from X to these other entities are annotated with the
cascade=PERSIST
orcascade=ALL
annotation element value or specified with the equivalent XML descriptor element.If X is a removed entity, it becomes managed.
If X is a detached object, the
EntityExistsException
may be thrown when the persist operation is invoked, or theEntityExistsException
or anotherPersistenceException
may be thrown at flush or commit time.For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value
cascade=PERSIST
orcascade=ALL
, the persist operation is applied to Y.
The semantics of the merge operation applied to an entity X are as follows:
If X is a detached entity, the state of X is copied onto a pre-existing managed entity instance X' of the same identity or a new managed copy X' of X is created.
If X is a new entity instance, a new managed entity instance X' is created and the state of X is copied into the new managed entity instance X'.
If X is a removed entity instance, an
IllegalArgumentException
will be thrown by the merge operation (or the transaction commit will fail).If X is a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been annotated with the cascade element value
cascade=MERGE
orcascade=ALL
annotation.For all entities Y referenced by relationships from X having the cascade element value
cascade=MERGE
orcascade=ALL
, Y is merged recursively as Y'. For all such Y referenced by X, X' is set to reference Y'. (Note that if X is managed then X is the same object as X'.)If X is an entity merged to X', with a reference to another entity Y, where
cascade=MERGE
orcascade=ALL
is not specified, then navigation of the same association from X' yields a reference to a managed object Y' with the same persistent identity as Y.
TL;DR
mysql_real_escape_string()
will provide no protection whatsoever (and could furthermore munge your data) if:
MySQL's
NO_BACKSLASH_ESCAPES
SQL mode is enabled (which it might be, unless you explicitly select another SQL mode every time you connect); andyour SQL string literals are quoted using double-quote
"
characters.This was filed as bug #72458 and has been fixed in MySQL v5.7.6 (see the section headed "The Saving Grace", below).
In homage to @ircmaxell's excellent answer (really, this is supposed to be flattery and not plagiarism!), I will adopt his format:
Starting off with a demonstration...
mysql_query('SET SQL_MODE="NO_BACKSLASH_ESCAPES"'); // could already be set
$var = mysql_real_escape_string('" OR 1=1 -- ');
mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');
This will return all records from the test
table. A dissection:
Selecting an SQL Mode
mysql_query('SET SQL_MODE="NO_BACKSLASH_ESCAPES"');
As documented under String Literals:
There are several ways to include quote characters within a string:
A “
'
” inside a string quoted with “'
” may be written as “''
”.A “
"
” inside a string quoted with “"
” may be written as “""
”.Precede the quote character by an escape character (“
\
”).A “
'
” inside a string quoted with “"
” needs no special treatment and need not be doubled or escaped. In the same way, “"
” inside a string quoted with “'
” needs no special treatment.
If the server's SQL mode includes NO_BACKSLASH_ESCAPES
, then the third of these options—which is the usual approach adopted by mysql_real_escape_string()
—is not available: one of the first two options must be used instead. Note that the effect of the fourth bullet is that one must necessarily know the character that will be used to quote the literal in order to avoid munging one's data.
The Payload
" OR 1=1 --
The payload initiates this injection quite literally with the "
character. No particular encoding. No special characters. No weird bytes.
mysql_real_escape_string()
$var = mysql_real_escape_string('" OR 1=1 -- ');
Fortunately, mysql_real_escape_string()
does check the SQL mode and adjust its behaviour accordingly. See libmysql.c
:
ulong STDCALL
mysql_real_escape_string(MYSQL *mysql, char *to,const char *from,
ulong length)
{
if (mysql->server_status & SERVER_STATUS_NO_BACKSLASH_ESCAPES)
return escape_quotes_for_mysql(mysql->charset, to, 0, from, length);
return escape_string_for_mysql(mysql->charset, to, 0, from, length);
}
Thus a different underlying function, escape_quotes_for_mysql()
, is invoked if the NO_BACKSLASH_ESCAPES
SQL mode is in use. As mentioned above, such a function needs to know which character will be used to quote the literal in order to repeat it without causing the other quotation character from being repeated literally.
However, this function arbitrarily assumes that the string will be quoted using the single-quote '
character. See charset.c
:
/*
Escape apostrophes by doubling them up
// [ deletia 839-845 ]
DESCRIPTION
This escapes the contents of a string by doubling up any apostrophes that
it contains. This is used when the NO_BACKSLASH_ESCAPES SQL_MODE is in
effect on the server.
// [ deletia 852-858 ]
*/
size_t escape_quotes_for_mysql(CHARSET_INFO *charset_info,
char *to, size_t to_length,
const char *from, size_t length)
{
// [ deletia 865-892 ]
if (*from == '\'')
{
if (to + 2 > to_end)
{
overflow= TRUE;
break;
}
*to++= '\'';
*to++= '\'';
}
So, it leaves double-quote "
characters untouched (and doubles all single-quote '
characters) irrespective of the actual character that is used to quote the literal! In our case $var
remains exactly the same as the argument that was provided to mysql_real_escape_string()
—it's as though no escaping has taken place at all.
The Query
mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');
Something of a formality, the rendered query is:
SELECT * FROM test WHERE name = "" OR 1=1 -- " LIMIT 1
As my learned friend put it: congratulations, you just successfully attacked a program using mysql_real_escape_string()
...
mysql_set_charset()
cannot help, as this has nothing to do with character sets; nor can mysqli::real_escape_string()
, since that's just a different wrapper around this same function.
The problem, if not already obvious, is that the call to mysql_real_escape_string()
cannot know with which character the literal will be quoted, as that's left to the developer to decide at a later time. So, in NO_BACKSLASH_ESCAPES
mode, there is literally no way that this function can safely escape every input for use with arbitrary quoting (at least, not without doubling characters that do not require doubling and thus munging your data).
It gets worse. NO_BACKSLASH_ESCAPES
may not be all that uncommon in the wild owing to the necessity of its use for compatibility with standard SQL (e.g. see section 5.3 of the SQL-92 specification, namely the <quote symbol> ::= <quote><quote>
grammar production and lack of any special meaning given to backslash). Furthermore, its use was explicitly recommended as a workaround to the (long since fixed) bug that ircmaxell's post describes. Who knows, some DBAs might even configure it to be on by default as means of discouraging use of incorrect escaping methods like addslashes()
.
Also, the SQL mode of a new connection is set by the server according to its configuration (which a SUPER
user can change at any time); thus, to be certain of the server's behaviour, you must always explicitly specify your desired mode after connecting.
So long as you always explicitly set the SQL mode not to include NO_BACKSLASH_ESCAPES
, or quote MySQL string literals using the single-quote character, this bug cannot rear its ugly head: respectively escape_quotes_for_mysql()
will not be used, or its assumption about which quote characters require repeating will be correct.
For this reason, I recommend that anyone using NO_BACKSLASH_ESCAPES
also enables ANSI_QUOTES
mode, as it will force habitual use of single-quoted string literals. Note that this does not prevent SQL injection in the event that double-quoted literals happen to be used—it merely reduces the likelihood of that happening (because normal, non-malicious queries would fail).
In PDO, both its equivalent function PDO::quote()
and its prepared statement emulator call upon mysql_handle_quoter()
—which does exactly this: it ensures that the escaped literal is quoted in single-quotes, so you can be certain that PDO is always immune from this bug.
As of MySQL v5.7.6, this bug has been fixed. See change log:
Functionality Added or Changed
Incompatible Change: A new C API function,
mysql_real_escape_string_quote()
, has been implemented as a replacement formysql_real_escape_string()
because the latter function can fail to properly encode characters when theNO_BACKSLASH_ESCAPES
SQL mode is enabled. In this case,mysql_real_escape_string()
cannot escape quote characters except by doubling them, and to do this properly, it must know more information about the quoting context than is available.mysql_real_escape_string_quote()
takes an extra argument for specifying the quoting context. For usage details, see mysql_real_escape_string_quote().Note
Applications should be modified to use
mysql_real_escape_string_quote()
, instead ofmysql_real_escape_string()
, which now fails and produces anCR_INSECURE_API_ERR
error ifNO_BACKSLASH_ESCAPES
is enabled.References: See also Bug #19211994.
Taken together with the bug explained by ircmaxell, the following examples are entirely safe (assuming that one is either using MySQL later than 4.1.20, 5.0.22, 5.1.11; or that one is not using a GBK/Big5 connection encoding):
mysql_set_charset($charset);
mysql_query("SET SQL_MODE=''");
$var = mysql_real_escape_string('" OR 1=1 /*');
mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');
...because we've explicitly selected an SQL mode that doesn't include NO_BACKSLASH_ESCAPES
.
mysql_set_charset($charset);
$var = mysql_real_escape_string("' OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");
...because we're quoting our string literal with single-quotes.
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(["' OR 1=1 /*"]);
...because PDO prepared statements are immune from this vulnerability (and ircmaxell's too, provided either that you're using PHP=5.3.6 and the character set has been correctly set in the DSN; or that prepared statement emulation has been disabled).
$var = $pdo->quote("' OR 1=1 /*");
$stmt = $pdo->query("SELECT * FROM test WHERE name = $var LIMIT 1");
...because PDO's quote()
function not only escapes the literal, but also quotes it (in single-quote '
characters); note that to avoid ircmaxell's bug in this case, you must be using PHP=5.3.6 and have correctly set the character set in the DSN.
$stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$param = "' OR 1=1 /*";
$stmt->bind_param('s', $param);
$stmt->execute();
...because MySQLi prepared statements are safe.
Thus, if you:
OR
OR
in addition to employing one of the solutions in ircmaxell's summary, use at least one of:
NO_BACKSLASH_ESCAPES
...then you should be completely safe (vulnerabilities outside the scope of string escaping aside).
The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.
The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.
Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.
Guava provides an onlyElement
Collector
, but only use it if you expect the collection to have exactly one element.
Collection<String> stringCollection = ...;
String string = collection.stream().collect(MoreCollectors.onlyElement())
If you are unsure of how many elements there are, use findFirst
.
Optional<String> optionalString = collection.stream().findFirst();
I found this on the Bootstrap website, but it really isn't a Bootstrap class, it's just HTML.
<strong>rendered as bold text</strong>
You could use a SUM
(not COUNT
!) combined with a CASE
statement, like this:
SELECT SUM(CASE WHEN myColumn=1 THEN 1 ELSE 0 END)
FROM AD_CurrentView
Note: in my own test NULL
s were not an issue, though this can be environment dependent. You could handle nulls such as:
SELECT SUM(CASE WHEN ISNULL(myColumn,0)=1 THEN 1 ELSE 0 END)
FROM AD_CurrentView
You could do something like this
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:6740/api/Membership/exist");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = 6;
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
And then strReponse should contain the values returned by your webservice
All the answers above show why statics are bad. The reason they are evil is because it gives the false impression that you are writing object oriented code, when in fact you are not. That is just plain evil.
I generally prefer to write regular non static classes and use a factory class to instantiate single ( sudo static ) instances of the object.
This way constructor and destructor work as per normal, and I can create additional non static instances if I wish ( for example a second DB connection )
I use this all the time and is especially useful for creating custom DB store session handlers, as when the page terminates the destructor will push the session to the database.
Another advantage is you can ignore the order you call things as everything will be setup on demand.
class Factory {
static function &getDB ($construct_params = null)
{
static $instance;
if( ! is_object($instance) )
{
include_once("clsDB.php");
$instance = new clsDB($construct_params); // constructor will be called
}
return $instance;
}
}
The DB class...
class clsDB {
$regular_public_variables = "whatever";
function __construct($construct_params) {...}
function __destruct() {...}
function getvar() { return $this->regular_public_variables; }
}
Anywhere you want to use it just call...
$static_instance = &Factory::getDB($somekickoff);
Then just treat all methods as non static ( because they are )
echo $static_instance->getvar();
private String getDay(Date date){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
//System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());
return simpleDateFormat.format(date).toUpperCase();
}
private String getDay(String dateStr){
//dateStr must be in DD-MM-YYYY Formate
Date date = null;
String day=null;
try {
date = new SimpleDateFormat("DD-MM-YYYY").parse(dateStr);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
//System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());
day = simpleDateFormat.format(date).toUpperCase();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return day;
}
It's not working because the entire for
loop (from the for
to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.
In other words, %count%
is replaced with its value 1
before running the loop.
What you need is something like:
setlocal enableextensions enabledelayedexpansion
set /a count = 1
for /f "tokens=*" %%a in (config.properties) do (
set /a count += 1
echo !count!
)
endlocal
Delayed expansion using !
instead of %
will give you the expected behaviour. See also here.
Also keep in mind that setlocal/endlocal
actually limit scope of things changed inside so that they don't leak out. If you want to use count
after the endlocal
, you have to use a "trick" made possible by the very problem you're having:
endlocal && set count=%count%
Let's say count
has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:
endlocal && set count=7
Then, when it's executed, the inner scope is closed off, returning count
to it's original value. But, since the setting of count
to seven happens in the outer scope, it's effectively leaking the information you need.
You can string together multiple sub-commands to leak as much information as you need:
endlocal && set count=%count% && set something_else=%something_else%
${varname}
is just a naming convention jQuery developers use to distinguish variables that are holding jQuery elements.
Plain {varname}
is used to store general stuffs like texts and strings.
${varname}
holds elements returned from jQuery.
You can use plain {varname}
to store jQuery elements as well, but as I said in the beginning this distinguishes it from the plain variables and makes it much easier to understand (imagine confusing it for a plain variable and searching all over to understand what it holds).
For example :
var $blah = $(this).parents('.blahblah');
Here, blah is storing a returned jQuery element.
So, when someone else see the $blah
in the code, they'll understand it's not just a string or a number, it's a jQuery element.
The rifle clip analogy posted by Oren A is pretty good, but I'll try another one and try to anticipate what the instructor was trying to get across.
A stack, as it's name suggests is an arrangement of "things" that has:
(think of it as a literal stack of books on your desk and you can only take something from the top)
Pushing something on the stack means "placing it on top". Popping something from the stack means "taking the top 'thing'" off the stack.
A simple usage is for reversing the order of words. Say I want to reverse the word: "popcorn". I push each letter from left to right (all 7 letters), and then pop 7 letters and they'll end up in reverse order. It looks like this was what he was doing with those expressions.
push(p) push(o) push(p) push(c) push(o) push(r) push(n)
after pushing the entire word, the stack looks like:
| n | <- top
| r |
| o |
| c |
| p |
| o |
| p | <- bottom (first "thing" pushed on an empty stack)
======
when I pop() seven times, I get the letters in this order:
n,r,o,c,p,o,p
conversion of infix/postfix/prefix is a pathological example in computer science when teaching stacks:
Post fix conversion to an infix expression is pretty straight forward:
(scan expression from left to right)
So if we have 53+2* we can convert that to infix in the following steps:
*When you reach the end of the expression, if it was formed correctly you stack should only contain one item.
By introducing 'x' and 'o' he may have been using them as temporary holders for the left and right operands of an infix expression: x + o, x - o, etc. (or order of x,o reversed).
There's a nice write up on wikipedia as well. I've left my answer as a wiki incase I've botched up any ordering of expressions.
This is the code to create dropdown in Angular 7, 8, 9
.html
file code
<div>
<label>Summary: </label>
<select (change)="SelectItem($event.target.value)" class="select">
<option value="0">--All--</option>
<option *ngFor="let item of items" value="{{item.Id.Value}}">
{{item.Name}}
</option>
</select>
</div>
.ts
file code
SelectItem(filterVal: any)
{
var id=filterVal;
//code
}
items
is an array which should be initialized in .ts
file.
FAT32
along with FAT16
and FAT12
are File System Types, but vfat
along with umsdos
and msdos
are drivers, used to mount the FAT file systems in Linux. The choosing of the driver determines how some of the features are applied to the file system, for example, systems mounted with msdos
driver don't have long filenames (they are 8.3 format). vfat
is the most common driver for mounting FAT32 file systems nowadays.
Source: this wikipedia article
Output of commands like df
and lsblk
indeed show vfat
as the File System Type. But sudo file -sL /dev/<partition>
shows FAT (32 bit)
if a File System is FAT32.
You can confirm vfat
is a module and not a File System Type by running modinfo vfat
.
You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run
ALTER USER <user> quota unlimited on <tablespace name>;
or
ALTER USER <user> quota 100M on <tablespace name>;
as a DBA user (depending on how much space you need / want to grant).
If you want to pass parameter value from cell to UIViewController using closure then
//Your Cell Class
class TheCell: UITableViewCell {
var callBackBlockWithParam: ((String) -> ()) = {_ in }
//Your Action on button
@IBAction func didTap(_ sender: Any) {
callBackBlockWithParam("Your Required Parameter like you can send button as sender or anything just change parameter type. Here I am passing string")
}
}
//Your Controller
extension TheController: UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TheCell.identifier, for: indexPath) as! TheCell {
cell.callBackBlockWithParam = { (passedParamter) in
//you will get string value from cell class
print(passedParamter)
}
return cell
}
}
While the accepted answer is correct, I'll add a more elegant version (in my opinion):
boolean idExists = tabPane.getTabs().stream()
.map(Tab::getId)
.anyMatch(idToCheck::equals);
Don't neglect using Stream#map() which allows to flatten the data structure before applying the Predicate
.
Like the other answer says, in the left hand side select Products and add product. Then select Facbook Login.
I then added http://localhost:3000/ to the field 'Valid OAuth redirect URIs', and then everything worked.
Here's a function I wrote for another answer: Javascript Image Url Verify. I don't know if it's exactly what you need, but it uses the various techniques that you would use which include handlers for onload
, onerror
, onabort
and a general timeout.
Because image loading is asynchronous, you call this function with your image and then it calls your callback sometime later with the result.
using ssh from java should not be as hard as jsch makes it. you might be better off with sshj.
A nice way to achieve this "if you have an office 365 account" is to use Office 365 outlook connector integrated with Azure Logic App,
Hope this helps someone!
On Windows, installation of easy_install is a little bit trickier, but still quite easy. The easiest way to do it is to download the distribute_setup.py file and run it. The easiest way to run the file is to open your downloads folder and double-click on the file.
Next, add the easy_install command and other Python scripts to the command search path, by adding your Python installation’s Scripts folder to the PATH environment variable. To do that, right-click on the “Computer” icon on the Desktop or in the Start menu, and choose “Properties”. Then click on “Advanced System settings” (in Windows XP, click on the “Advanced” tab instead). Then click on the “Environment variables” button. Finally, double-click on the “Path” variable in the “System variables” section, and add the path of your Python interpreter’s Scripts folder. Be sure to delimit it from existing values with a semicolon. Assuming you are using Python 2.7 on the default path, add the following value:
;C:\Python27\Scripts And you are done! To check that it worked, open the Command Prompt and execute easy_install. If you have User Account Control enabled on Windows Vista or Windows 7, it should prompt you for administrator privileges.
Now that you have easy_install, you can use it to install pip:
easy_install pip
If you are using c# on the desktop, you can use SimpleMapi. That way it will be sent using the default mail client, and the user has the option of reviewing the message before sending, just like mailto:
.
To use it you add the Simple-MAPI.NET package (it's 13Kb), and run:
var mapi = new SimpleMapi();
mapi.AddRecipient(null, address, false);
mapi.Attach(path);
//mapi.Logon(ParentForm.Handle); //not really necessary
mapi.Send(subject, body, true);
You need to include "Main class" attribute in Manisfest.mf file in Jar
For example: Main-Class: MyClassName
Second thing, To add Manifest file in Your jar, You can manually create file in your workspace folder, and refresh in Eclipse Project explorer.
While exporting, Eclipse will create a Jar which will include your manifest.
Cheers !!
Make your variables work for you, this will allow access t
Define your PATH in /etc/profile.d/*.sh
System-wide environment variables
Files with the .sh extension in the /etc/profile.d directory get executed whenever a bash login shell is entered (e.g. when logging in from the console or over ssh), as well as by the DisplayManager when the desktop session loads.
You can for instance create the file /etc/profile.d/myenvvars.sh and set variables like this:
export JAVA_HOME=/usr/lib/jvm/jdk1.7.0
export PATH=$PATH:$JAVA_HOME/bin
Execute crontab with login option!
CRONTAB run script or command with Environment Variables
0 9 * * * cd /var/www/vhosts/foo/crons/; bash -l -c 'php -f ./download.php'
0 9 * * * cd /var/www/vhosts/foo/crons/; bash -l -c download.sh
Try in yourbatch
set "batchisin=%~dp0"
which should set the variable to your batch's location.
Use parseFloat
it will convert string to number including decimal values.
function myFunction() {
var y = document.getElementById("txt1").value;
var z = document.getElementById("txt2").value;
var x = parseFloat(y) + parseFloat(z);
document.getElementById("demo").innerHTML = x;
}
<p>
Click the button to calculate x.
<button onclick="myFunction()">Try it</button>
</p>
<p>
Enter first number:
<input type="text" id="txt1" name="text1" value="1">
Enter second number:
<input type="text" id="txt2" name="text2" value="2">
</p>
<p id="demo"></p>
try this
$(this).parent().css("backgroundImage", "url('../images/r-srchbg_white.png') no-repeat");
Try this...
You don't need to override onCreateOptionsMenu() in your Fragment class again. Menu items visibility can be changed by overriding onPrepareOptionsMenu() method available in Fragment class.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.action_search).setVisible(false);
super.onPrepareOptionsMenu(menu);
}
I use a crazy way to do this is using this command
$firstDay=date('Y-m-d',strtotime("first day of this month"));
$lastDay=date('Y-m-d',strtotime("last day of this month"));
Thats all
In my case, it was solved by changing the import order of the following scripts: Before (Not work):
After (Working):
Use Map interface and an implementation like HashMap
Ah, a tough one. On one side, a declaration is a contract and it really does not make sense to pass a const argument by value. On the other hand, if you look at the function implementation, you give the compiler more chances to optimize if you declare an argument constant.
You could use the PowerShell equivalent of String.Format - it's usually the easiest way to build up a string. Place {0}, {1}, etc. where you want the variables in the string, put a -f
immediately after the string and then the list of variables separated by commas.
Get-ChildItem c:\code|%{'{0}\{1}\{2}.dll' -f $_.fullname,$buildconfig,$_.name}
(I've also taken the dash out of the $buildconfig variable name as I have seen that causes issues before too.)
As mentioned above UIPickerView
is now resizable. I just want to add though that if you want to change the pickerView's height in a tableView Cell, I didn't have any success with setting the height anchor to a constant. However, using lessThanOrEqualToConstant
seems to work.
class PickerViewCell: UITableViewCell {
let pickerView = UIPickerView()
func setup() {
// call this from however you initialize your cell
self.contentView.addSubview(self.pickerView)
self.pickerView.translatesAutoresizingMaskIntoConstraints = false
let constraints: [NSLayoutConstraint] = [
// pin the pickerView to the contentView's layoutMarginsGuide
self.pickerView.leadingAnchor.constraint(equalTo: self.contentView.layoutMarginsGuide.leadingAnchor),
self.pickerView.topAnchor.constraint(equalTo: self.contentView.layoutMarginsGuide.topAnchor),
self.pickerView.trailingAnchor.constraint(equalTo: self.contentView.layoutMarginsGuide.trailingAnchor),
self.pickerView.bottomAnchor.constraint(equalTo: self.contentView.layoutMarginsGuide.bottomAnchor),
// set the height using lessThanOrEqualToConstant
self.pickerView.heightAnchor.constraint(lessThanOrEqualToConstant: 100)
]
NSLayoutConstraint.activate(constraints)
}
}
Could you do the following:
obj = {
"1":"aa",
"2":"bb"
};
var newNum = "3";
var newVal = "cc";
obj[newNum] = newVal;
alert(obj["3"]); // this would alert 'cc'
var txt;
var r = confirm("Press a button!");
if (r == true) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
var txt;_x000D_
var r = confirm("Press a button!");_x000D_
if (r == true) {_x000D_
txt = "You pressed OK!";_x000D_
} else {_x000D_
txt = "You pressed Cancel!";_x000D_
}
_x000D_
I got the same error when using %
as a percent character in my format string. The solution to this is to double up the %%
.
Java caches the primitive values from -128 to 127. When we compare two Long objects java internally type cast it to primitive value and compare it. But above 127 the Long object will not get type caste. Java caches the output by .valueOf() method.
This caching works for Byte, Short, Long from -128 to 127. For Integer caching works From -128 to java.lang.Integer.IntegerCache.high or 127, whichever is bigger.(We can set top level value upto which Integer values should get cached by using java.lang.Integer.IntegerCache.high).
For example:
If we set java.lang.Integer.IntegerCache.high=500;
then values from -128 to 500 will get cached and
Integer a=498;
Integer b=499;
System.out.println(a==b)
Output will be "true".
Float and Double objects never gets cached.
Character will get cache from 0 to 127
You are comparing two objects. so == operator will check equality of object references. There are following ways to do it.
1) type cast both objects into primitive values and compare
(long)val3 == (long)val4
2) read value of object and compare
val3.longValue() == val4.longValue()
3) Use equals() method on object comparison.
val3.equals(val4);
The 2018 specification provides the s flag (alias: dotAll), so that .
will match any character, including linebreaks:
const regExAll = /.*/s; //notice the 's'
let str = `
Everything
in this
string
will
be
matched. Including whitespace (even Linebreaks).
`;
console.log(`Match:`, regExAll.test(str)); //true
console.log(`Index Location:`, str.search(regExAll));
let newStr = str.replace(regExAll,"");
console.log(`Replaced with:`,newStr); //Index: 0
_x000D_
if you get an error as Parameter 'element' implicitly has an 'any' type.Vetur(7006) in vueJs
with the error:
exportColumns.forEach(element=> {
if (element.command !== undefined) {
let d = element.command.findIndex(x => x.name === "destroy");
you can fixed it by defining thoes variables as any as follow.
corrected code:
exportColumns.forEach((element: any) => {
if (element.command !== undefined) {
let d = element.command.findIndex((x: any) => x.name === "destroy");
Support, unfortunately, is brutal at best. Here's a post on the topic:
https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/
And the post content:
Yes, but the syntax is different than what you have
SELECT
<fields>
FROM
<table1>
LEFT JOIN <table2>
ON <criteria for join>
AND <other criteria for join>
LEFT JOIN <table3>
ON <criteria for join>
AND <other criteria for join>
I believe that in the book class all \part and \chapter are set to start on a recto page.
from book.cls:
\newcommand\part{%
\if@openright
\cleardoublepage
\else
\clearpage
\fi
\thispagestyle{plain}%
\if@twocolumn
\onecolumn
\@tempswatrue
\else
\@tempswafalse
\fi
\null\vfil
\secdef\@part\@spart}
you should be able to renew that command, and something similar for the \chapter.
Just give you some idea may help you, if you want fully control dialog, you can try to avoid use of default button options, and add buttons by yourself in your #dialog div. You also can put data into some dummy attribute of link, like Click. call attr("data") when you need it.
The results are ordered by the first column, then the second, and so on for as many columns as the ORDER BY clause includes. If you want any results sorted in descending order, your ORDER BY clause must use the DESC keyword directly after the name or the number of the relevant column.
Check out this Example
SELECT first_name, last_name, hire_date, salary
FROM employee
ORDER BY hire_date DESC,last_name ASC;
It will order in succession. Order the Hire_Date first, then LAST_NAME it by Hire_Date .
Minor refinement on KM's solution for those like me who've got collation fun on their DB server....
DECLARE @SQL varchar(max)=''
SELECT @SQL=@SQL+'UNION
select
'''+d.name +'.''+sh.name+''.''+o.name COLLATE SQL_Latin1_General_CP1_CI_AS,c.name COLLATE SQL_Latin1_General_CP1_CI_AS,c.column_id
from '+d.name +'.sys.columns c
inner join sys.objects o on c.object_id=o.object_id
INNER JOIN sys.schemas sh on o.schema_id=sh.schema_id
'
FROM sys.databases d
SELECT @SQL=RIGHT(@SQL,LEN(@SQL)-5)+'order by 1,3'
--print @SQL
EXEC (@SQL)
(Still living in hope that we'll find a way to do this that can be wrapped into a view.)
If MS SQL Server Express Edition is being used then SQL Server Agent is not available. I found the following worked for all editions:
USE Master
GO
IF EXISTS( SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[MyBackgroundTask]')
AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[MyBackgroundTask]
GO
CREATE PROCEDURE MyBackgroundTask
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- The interval between cleanup attempts
declare @timeToRun nvarchar(50)
set @timeToRun = '03:33:33'
while 1 = 1
begin
waitfor time @timeToRun
begin
execute [MyDatabaseName].[dbo].[MyDatabaseStoredProcedure];
end
end
END
GO
-- Run the procedure when the master database starts.
sp_procoption @ProcName = 'MyBackgroundTask',
@OptionName = 'startup',
@OptionValue = 'on'
GO
Some notes:
Here is another:
System.Reflection.Assembly.GetExecutingAssembly().Location
Just remove the width from both divs.
A div
is a block level element and will use all available space (unless you start floating or positioning them) so the outer div will automatically be 100% wide and the inner div will use all remaining space after setting the left margin.
I have added an example with a textarea
on jsfiddle.
Updated example with an input.
Here is a simple explanation about how to create a temp dir using templates.
PARENT_DIR=./temp_dirs # (optional) specify a dir for your tempdirs
mkdir $PARENT_DIR
TEMPLATE_PREFIX='tmp' # prefix of your new tempdir template
TEMPLATE_RANDOM='XXXX' # Increase the Xs for more random characters
TEMPLATE=${PARENT_DIR}/${TEMPLATE_PREFIX}.${TEMPLATE_RANDOM}
# create the tempdir using your custom $TEMPLATE, which may include
# a path such as a parent dir, and assign the new path to a var
NEW_TEMP_DIR_PATH=$(mktemp -d $TEMPLATE)
echo $NEW_TEMP_DIR_PATH
# create the tempdir in parent dir, using default template
# 'tmp.XXXXXXXXXX' and assign the new path to a var
NEW_TEMP_DIR_PATH=$(mktemp -p $PARENT_DIR)
echo $NEW_TEMP_DIR_PATH
# create a tempdir in your systems default tmp path e.g. /tmp
# using the default template 'tmp.XXXXXXXXXX' and assign path to var
NEW_TEMP_DIR_PATH=$(mktemp -d)
echo $NEW_TEMP_DIR_PATH
# Do whatever you want with your generated temp dir and var holding its path
I'm posting this because (to my surprise) there was no other place I could find that recommended this.
There's a really easy way to do this, without restricting you to browser-defined input dimensions. Just use the <label>
tag around a hidden file upload button. This allows for even more freedom in styling than the styling allowed via webkit's built-in styling[1].
The label tag was made for the exact purpose of directing any click events on it to the child inputs[2], so using that, you won't require any JavaScript to direct the click event to the input button for you anymore. You'd to use something like the following:
label.myLabel input[type="file"] {_x000D_
position:absolute;_x000D_
top: -1000px;_x000D_
}_x000D_
_x000D_
/***** Example custom styling *****/_x000D_
.myLabel {_x000D_
border: 2px solid #AAA;_x000D_
border-radius: 4px;_x000D_
padding: 2px 5px;_x000D_
margin: 2px;_x000D_
background: #DDD;_x000D_
display: inline-block;_x000D_
}_x000D_
.myLabel:hover {_x000D_
background: #CCC;_x000D_
}_x000D_
.myLabel:active {_x000D_
background: #CCF;_x000D_
}_x000D_
.myLabel :invalid + span {_x000D_
color: #A44;_x000D_
}_x000D_
.myLabel :valid + span {_x000D_
color: #4A4;_x000D_
}
_x000D_
<label class="myLabel">_x000D_
<input type="file" required/>_x000D_
<span>My Label</span>_x000D_
</label>
_x000D_
I've used a fixed position to hide the input, to make it work even in ancient versions of Internet Explorer (emulated IE8- refused to work on a visibility:hidden
or display:none
file-input). I've tested in emulated IE7 and up, and it worked perfectly.
<button>
s inside <label>
tags unfortunately, so you'll have to define the styles for the buttons yourself. To me, this is the only downside to this approach.for
attribute is defined, its value is used to trigger the input with the same id
as the for
attribute on the <label>
.In Oracle (For last 24 hours):
SELECT *
FROM my_table
WHERE date_column >= SYSDATE - 24/24
In case, for any reason, you have rows with future dates, you can use between, like this:
SELECT *
FROM my_table
WHERE date_column BETWEEN (SYSDATE - 24/24) AND SYSDATE
One could install Git for Windows and subsequently run ssh-add
:
Step 3: Add your key to the ssh-agent
To configure the ssh-agent program to use your SSH key:
If you have GitHub for Windows installed, you can use it to clone repositories and not deal with SSH keys. It also comes with the Git Bash tool, which is the preferred way of running git commands on Windows.
Ensure ssh-agent is enabled:
If you are using Git Bash, turn on ssh-agent:
# start the ssh-agent in the background ssh-agent -s # Agent pid 59566
If you are using another terminal prompt, such as msysgit, turn on ssh-agent:
# start the ssh-agent in the background eval $(ssh-agent -s) # Agent pid 59566
Add your SSH key to the ssh-agent:
ssh-add ~/.ssh/id_rsa
Building on what deb2fast said I would also pass in a couple of extra parameters to JSON.stringify() to get it to pretty format:
fs.writeFileSync('./data.json', JSON.stringify(obj, null, 2) , 'utf-8');
The second param is an optional replacer function which you don't need in this case so null
works.
The third param is the number of spaces to use for indentation. 2 and 4 seem to be popular choices.
Today there are four font container formats in use on the web: EOT, TTF, WOFF,
andWOFF2.
Unfortunately, despite the wide range of choices, there isn't a single universal format that works across all old and new browsers:
If you want your web app to have the same font across all browsers then you might want to provide all 4 font type in CSS
@font-face {
font-family: 'besom'; !important
src: url('fonts/besom/besom.eot');
src: url('fonts/besom/besom.eot?#iefix') format('embedded-opentype'),
url('fonts/besom/besom.woff2') format('woff2'),
url('fonts/besom/besom.woff') format('woff'),
url('fonts/besom/besom.ttf') format('truetype'),
url('fonts/besom/besom.svg#besom_2regular') format('svg');
font-weight: normal;
font-style: normal;
}
In my case what removed this message was (After updating everything) deleting the emulator and creating a new one. Manually updating the adb didn't solved this for. Nor updating via the Android studio Gui. In my case it seems that since the emulator was created with "old" components it keep showing the message. I had three emulators, just deleted them all and created a new one. For my surprise when it started the message was no more.
Cannot tell if performance is better or not. The message just didn't came up. Also I have everything updated to the latest (emulators and sdk).
I updated my android gradle plugin to 2.2.0-alpha4
and constraint layout dependency to 1.0.0-alpha3
and it seems to be working now
If you want to get the full path of the directory of the current rb file:
File.expand_path('../', __FILE__)
<?php
$current = strtotime(date("Y-m-d"));
$date = strtotime("2014-09-05");
$datediff = $date - $current;
$difference = floor($datediff/(60*60*24));
if($difference==0)
{
echo 'today';
}
else if($difference > 1)
{
echo 'Future Date';
}
else if($difference > 0)
{
echo 'tomorrow';
}
else if($difference < -1)
{
echo 'Long Back';
}
else
{
echo 'yesterday';
}
?>
Don't forget:
div.something.else {
// will only style a div with both, not just one or the other
}
How about
...
C() : arr{ {1,2,3} }
{}
...
?
Compiles fine on g++ 4.8
I to had a similar doubt what I got to know was getActivity()
returns the Activity
to which the fragment is associated.
The getActivity()
method is used generally in static fragment as the associated activity will not be static and non static member cannot be used in static member.
If you have more than one element with the same ID, then you have invalid HTML.
But you can acheive the same result using classes instead. That's what they're designed for.
<input class='b' ... >
You can give it an ID as well if you need to, but it should be unique.
Once you've got the class in there, you can reference it with a dot instead of the hash, like so:
var value = $('#a .b').val();
or
var value = $('#a input.b').val();
which will limit it to 'b' class elements that are inputs within the form (which seems to be close to what you're asking for).
Performance-Wise this probably might not be the best solution but it works.
var str = "filename:with&bad$separators.txt";
char[] charArray = new char[] { '#', '%', '&', '{', '}', '\\', '<', '>', '*', '?', '/', ' ', '$', '!', '\'', '"', ':', '@' };
foreach (var singleChar in charArray)
{
str = str.Replace(singleChar, '_');
}
From Oracle documentation page on ScheduledThreadPoolExecutor
A ThreadPoolExecutor that can additionally schedule commands to run after a given delay, or to execute periodically. This class is preferable to Timer when multiple worker threads are needed, or when the additional flexibility or capabilities of ThreadPoolExecutor (which this class extends) are required.
ExecutorService/ThreadPoolExecutor
or ScheduledThreadPoolExecutor
is obvious choice when you have multiple worker threads.
Pros of ExecutorService
over Timer
Timer
can't take advantage of available CPU cores unlike ExecutorService
especially with multiple tasks using flavours of ExecutorService
like ForkJoinPoolExecutorService
provides collaborative API if you need coordination between multiple tasks. Assume that you have to submit N number of worker tasks and wait for completion of all of them. You can easily achieve it with invokeAll API. If you want to achieve the same with multiple Timer
tasks, it would be not simple. ThreadPoolExecutor provides better API for management of Thread life cycle.
Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks
Few advantages:
a. You can create/manage/control life cycle of Threads & optimize thread creation cost overheads
b. You can control processing of tasks ( Work Stealing, ForkJoinPool, invokeAll) etc.
c. You can monitor the progress and health of threads
d. Provides better exception handling mechanism
The keyword exists, but it is not implemented.
The only good reason to use goto that I can think of is this:
for (int i = 0; i < MAX_I; i++) {
for (int j = 0; j < MAX_J; j++) {
// do stuff
goto outsideloops; // to break out of both loops
}
}
outsideloops:
In Java you can do this like this:
loops:
for (int i = 0; i < MAX_I; i++) {
for (int j = 0; j < MAX_J; j++) {
// do stuff
break loops;
}
}
Q: What's the difference between __str__()
and __repr__()
?
LONG
This question has been around a long time, and there are a variety of answers of which most are correct (not to mention from several Python community legends[!]). However when it comes down to the nitty-gritty, this question is analogous to asking for the difference between the str()
and repr()
built-in functions. I'm going to describe the differences in my own words (which means I may be "borrowing" liberally from Core Python Programming so pls forgive me).
Both str()
and repr()
have the same basic job: their goal is to return a string representation of a Python object. What kind of string representation is what differentiates them.
str()
& __str()__
return a printable string representation of
an object... something human-readable/for human consumptionrepr()
& __repr()__
return a string representation of an object that is a
valid Python object, something you can pass to eval()
or type into the Python shell without getting an error.For example, let's assign a string to x
and an int
to y
:
>>> x, y = 'foo', 123
>>> str(x), str(y)
('foo', '123')
Can we take what's inside the quotes and enter them verbatim into the Python interpreter?
>>> 123
123
>>> foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
Clearly you can for an int
but not necessarily for a str
. While I can pass '123'
to eval()
, that doesn't work for 'foo'
:
>>> eval('123')
123
>>> eval('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'foo' is not defined
Now let's try repr()
; again, dump what's in the pair of quotes for each string:
>>> repr(x), repr(y)
("'foo'", '123')
>>> 123
123
>>> 'foo'
'foo'
Wow, they both work? That's because 'foo'
, while a printable string representation of that string, it's not evaluatable, but "'foo'"
is. 123
is a valid Python int
called by either str()
or repr()
. What happens when we call eval()
with these?
>>> eval('123')
123
>>> eval("'foo'")
'foo'
It works because 123
and 'foo'
are valid Python objects. Another key takeaway is that while sometimes both return the same thing (the same string representation), that's not always the case. (And yes, yes, I can go create a variable foo
where the eval()
works, but that's not the point.)
More factoids about both pairs
str()
and repr()
are called implicitly, meaning they're called on behalf of users: when users execute print
(Py1/Py2) or call print()
(Py3+), even if users don't call str()
explicitly, such a call is made on their behalf before the object is displayed.>>>
prompt and press RETURN, the interpreter displays the results of repr()
implicitly called on that object.str()
and repr()
to __str__()
and __repr__()
, realize that calls to the built-in functions, i.e., str(x)
or repr(y)
result in calling their object's corresponding special methods: x.__str__()
or y.__repr()__
__str__()
and __repr__()
for your Python classes, you overload the built-in functions (str()
and repr()
), allowing instances of your classes to be passed in to str()
and repr()
. When such calls are made, they turn around and call the class' __str__()
and __repr__()
(per #3).On smaller screen's like laptop the dialog will shrink. To auto-fix, try the following option
Additional Reading https://material.angular.io/cdk/layout/overview
Thanks to the solution in answersicouldntfindanywhereelse (2nd para). it worked for me.
Following is needed
import { Breakpoints, BreakpointObserver } from '@angular/cdk/layout'
I was getting the same error. I was using Intellij IDEA and I wanted to run Spring boot application. So, solution from my side is as follow.
Go to Run menu -> Run configuration -> Click on Add button from the left panel and select maven -> In parameters add this text -> spring-boot:run
Now press Ok and Run.
setInterval()
setInterval is a time interval based code execution method that has the native ability to repeatedly run specified script when the interval is reached. It should not be nested into its callback function by the script author to make it loop, since it loops by default. It will keep firing at the interval unless you call clearInterval().
if you want to loop code for animations or clocks Then use setInterval.
function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setInterval(doStuff, 5000);
setTimeout()
setTimeout is a time based code execution method that will execute script only one time when the interval is reached, and not repeat again unless you gear it to loop the script by nesting the setTimeout object inside of the function it calls to run. If geared to loop, it will keep firing at the interval unless you call clearTimeout().
function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setTimeout(doStuff, 5000);
if you want something to happen one time after some seconds Then use setTimeout... because it only executes one time when the interval is reached.
You have to parse the string as JSON (data[0] == "["
is an indication that data
is actually a string, not an object):
data = $.parseJSON(data);
$.each(data, function(i, item) {
alert(item);
});
Also have a look into the built-in DataFrame.filter
function.
Minimalistic but greedy approach (sufficient for the given df):
df.filter(regex="[^BD]")
Conservative/lazy approach (exact matches only):
df.filter(regex="^(?!(B|D)$).*$")
Conservative and generic:
exclude_cols = ['B','C']
df.filter(regex="^(?!({0})$).*$".format('|'.join(exclude_cols)))
To @Cerebrus solution: for H2 for strings "+" is not supported. So:
REPLACE(string, CHAR(13) || CHAR(10), 'replacementString')
By default, the docker daemon will use the unix socket unix:///var/run/docker.sock
(you can check this is the case for you by doing a sudo netstat -tunlp
and note that there is no docker daemon process listening on any ports). It's recommended to keep this setting for security reasons but it sounds like Riak requires the daemon to be running on a TCP socket.
To start the docker daemon with a TCP socket that anybody can connect to, use the -H
option:
sudo docker -H 0.0.0.0:2375 -d &
Warning: This means machines that can talk to the daemon through that TCP socket can get root access to your host machine.
Related docs:
Using @joran's sample data,
ggplot(dat, aes(x=xx, fill=yy)) + geom_histogram(alpha=0.2, position="identity")
note that the default position of geom_histogram
is "stack."
see "position adjustment" of this page:
Images can be selected too.
There are limits to using JavaScript to deselect text, as it might happen even in places where you want to select. To ensure a rich and successful career, steer clear of all requirements that need ability to influence or manage the browser beyond the ordinary... unless, of course, they are paying you extremely well.
This can be done more easily? This is how I did it:
Create a temporary database (e.g. restore):
mysqladmin -u root -p create restore
Restore the full dump in the temp database:
mysql -u root -p restore < fulldump.sql
Dump the table you want to recover:
mysqldump restore mytable > mytable.sql
Import the table in another database:
mysql -u root -p database < mytable.sql
Python don't have a great support for recursion because of it's lack of TRE (Tail Recursion Elimination).
This means that each call to your recursive function will create a function call stack and because there is a limit of stack depth (by default is 1000) that you can check out by sys.getrecursionlimit
(of course you can change it using sys.setrecursionlimit but it's not recommended) your program will end up by crashing when it hits this limit.
As other answer has already give you a much nicer way for how to solve this in your case (which is to replace recursion by simple loop) there is another solution if you still want to use recursion which is to use one of the many recipes of implementing TRE in python like this one.
N.B: My answer is meant to give you more insight on why you get the error, and I'm not advising you to use the TRE as i already explained because in your case a loop will be much better and easy to read.
To keep line breaks when pasting in notepad, replace this line in the macro:
strTemp = ActiveCell.Value
by:
strTemp = Replace(ActiveCell.Value, Chr(10), vbCrLf)
I had a similar issue and based on this and other comments here's what happened and worked:
? brew update && brew upgrade && brew install openssl
remote: Repository not found.
fatal: repository 'https://github.com/Homebrew/homebrew-dupes/' not found
Error: homebrew/homebrew-dupes does not exist! Run `brew untap homebrew/homebrew-dupes` to remove it.
...
? brew untap homebrew/homebrew-dupes
? brew update && brew upgrade && brew install openssl
This was after working on it for hours, but first time I saw the homebrew-dupes. Not sure how Homebrew knew what to install, but it seemed to install everything from scratch. macOS Catalina, zsh. I think the initial problem came because of Catalina
The error I was getting was:
dlopen(/Users/gscar/.gem/ruby/2.7.0/gems/pg-1.2.2/lib/pg_ext.bundle, 9): Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib (LoadError)
Referenced from: /usr/local/opt/postgresql/lib/libpq.5.dylib
Reason: image not found - /Users/gscar/.gem/ruby/2.7.0/gems/pg-1.2.2/lib/pg_ext.bundle
After reading lots of answers finally I figured out.
First, I added 3 different routes into WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ApiById",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"^[0-9]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiByName",
routeTemplate: "api/{controller}/{action}/{name}",
defaults: null,
constraints: new { name = @"^[a-z]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiByAction",
routeTemplate: "api/{controller}/{action}",
defaults: new { action = "Get" }
);
}
Then, removed ActionName, Route, etc.. from the controller functions. So basically this is my controller;
// GET: api/Countries/5
[ResponseType(typeof(Countries))]
//[ActionName("CountryById")]
public async Task<IHttpActionResult> GetCountries(int id)
{
Countries countries = await db.Countries.FindAsync(id);
if (countries == null)
{
return NotFound();
}
return Ok(countries);
}
// GET: api/Countries/tur
//[ResponseType(typeof(Countries))]
////[Route("api/CountriesByName/{anyString}")]
////[ActionName("CountriesByName")]
//[HttpGet]
[ResponseType(typeof(Countries))]
//[ActionName("CountryByName")]
public async Task<IHttpActionResult> GetCountriesByName(string name)
{
var countries = await db.Countries
.Where(s=>s.Country.ToString().StartsWith(name))
.ToListAsync();
if (countries == null)
{
return NotFound();
}
return Ok(countries);
}
Now I am able to run with following url samples(with name and with id);
http://localhost:49787/api/Countries/GetCountriesByName/France
Employee emp1 = new Employee() { ID = 1, Name = "Narendra1", Salary = 11111, Experience = 3, Age = 30 };Employee emp2 = new Employee() { ID = 2, Name = "Narendra2", Salary = 21111, Experience = 10, Age = 38 };
Employee emp3 = new Employee() { ID = 3, Name = "Narendra3", Salary = 31111, Experience = 4, Age = 33 };
Employee emp4 = new Employee() { ID = 3, Name = "Narendra4", Salary = 41111, Experience = 7, Age = 33 };
List<Employee> lstEmployee = new List<Employee>();
lstEmployee.Add(emp1);
lstEmployee.Add(emp2);
lstEmployee.Add(emp3);
lstEmployee.Add(emp4);
var eemmppss=lstEmployee.Select(cc=>new {cc.ID,cc.Age}).Distinct();
I think instead of downloading .ttf file we can use Google fonts. It's very easy to implements. only you have to follow these steps. step 1) Open layout.xml of your project and the select font family of text view in attributes (for reference screen shot is attached)
step 2) The in font family select More fonts.. option if your font is not there. then you will see a new window will open, there you can type your required font & select the desired font from that list i.e) Regular, Bold, Italic etc.. as shown in below image.
step 3) Then you will observe a font folder will be auto generated in /res folder having your selected fonts xml file.
Then you can directly use this font family in xml as
android:fontFamily="@font/josefin_sans_bold"
or pro grammatically you can achieve this by using
Typeface typeface = ResourcesCompat.getFont(this, R.font.app_font);
fontText.setTypeface(typeface);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Try this :
width:auto;
margin-right:50px;
I wrote a very tiny plugin called "once" which do that:
$.fn.once = function(a, b) {
return this.each(function() {
$(this).off(a).on(a,b);
});
};
And simply:
$(element).once('click', function(){
});
The command in the keyboard shortcuts menu/editor is editor.action.jumpToBracket
there you can set it to whatever you like. There is also one called editor.action.selectToBracket
which has no shortcut by default (at least on Mac).
On the Mac editor.action.jumpToBracket
starts out as Cmd+Shift+\
and I changed it to Ctrl+] because I didn't want a Shift in there and to be in line with what others here say works on Linux/Win. I did so in the hopes that I could use Ctrl+Shift+] to "Extend selection to matching bracket". That is what lead me to discover the details above. I set editor.action.selectToBracket
to Ctrl+Shift+] and got exactly the behavior I wanted.
First of all check your windows update by searching "Windows Update"
or
Download updates from microsoft windows site (i had windows 7 x64 updated to service pack 1 full) windows 7 Service pack 1 download
Now there are some more downloads that support WAMP for installing time
From the readme.txt
BEFORE proceeding with the installation of Wampserver, you must ensure that certain elements are installed on your system, otherwise Wampserver will absolutely not run, and in addition, the installation will be faulty and you need to remove Wampserver BEFORE installing the elements that were missing.
Make sure you are "up to date" in the redistributable packages VC9, VC10, VC11, VC13 and VC14 Even if you think you are up to date, install each package as administrator and if message "Already installed", validate Repair.
The following packages (VC9, VC10, VC11) are imperatively required to Wampserver 2.4, 2.5 and 3.0, even if you use only Apache and PHP versions VC11 and VC14 is required for PHP 7 and Apache 2.4.17
VC9 Packages (Visual C++ 2008 SP1) https://www.microsoft.com/en-us/download/details.aspx?id=5582 https://www.microsoft.com/en-us/download/details.aspx?id=2092
VC10 Packages (Visual C++ 2010 SP1) https://www.microsoft.com/en-us/download/details.aspx?id=8328 https://www.microsoft.com/en-us/download/details.aspx?id=13523
VC11 Packages (Visual C++ 2012 Update 4) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page: http://www.microsoft.com/en-us/download/details.aspx?id=30679
VC13 Packages[/b] (Visual C++ 2013) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe
VC14 Packages (Visual C++ 2015) The two files vcredist_x86.exe and vcredist_x64.exe to be download are on the same page: https://www.microsoft.com/en-us/download/details.aspx?id=52685
VC Packages x64 (Visual C++ 2017)
https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads
Generally speaking, for boolean
or bit
data types, you would use 0
or 1
like so:
UPDATE tbl SET bitCol = 1 WHERE bitCol = 0
See also:
I've tried a lot of things but finally, including uninstall with the automated tools. So, I've uninstalled manually scikit-learn.
sudo rm -R /home/ubuntu/.local/lib/python3.6/site-packages/sklearn
sudo rm -R /home/ubuntu/.local/lib/python3.6/site-packages/scikit_learn-0.20.0-py3.6.egg-info
And re-install using pip
sudo pip3.6 install -U scikit-learn
Hope that can help someone else!
I was in a process of switching from one version control service to another and needed to clone all repositories including all branches, tags and history.
To achieve above I did next:
git push origin '*:*'
.sh script used to checkout all branches to local repository:
for branch in `git branch -a | grep remotes | grep -v HEAD | grep -v master `; do
git branch --track ${branch#remotes/origin/} $branch
done
Full working solution :
HTML:
<form id="myform">
<button>erase</button>
<select id="fs">
<option value="Arial">Arial</option>
<option value="Verdana ">Verdana </option>
<option value="Impact ">Impact </option>
<option value="Comic Sans MS">Comic Sans MS</option>
</select>
<select id="size">
<option value="7">7</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</select>
</form>
<br/>
<textarea class="changeMe">Text into textarea</textarea>
<div id="container" class="changeMe">
<div id="float">
<p>
Text into container
</p>
</div>
</div>
jQuery:
$("#fs").change(function() {
//alert($(this).val());
$('.changeMe').css("font-family", $(this).val());
});
$("#size").change(function() {
$('.changeMe').css("font-size", $(this).val() + "px");
});
Fiddle here: http://jsfiddle.net/AaT9b/
GetLogicalDrives() enumerates all mounted disk partitions, not physical drives.
You can enumerate the drive letters with (or without) GetLogicalDrives, then call QueryDosDevice() to find out which physical drive the letter is mapped to.
Alternatively, you can decode the information in the registry at HKEY_LOCAL_MACHINE\SYSTEM\MountedDevices. The binary data encodings there are not obvious, however. If you have a copy of Russinovich and Solomon's book Microsoft Windows Internals, this registry hive is discussed in Chapter 10.
Well, most other answers here refer to
sort -n
However, I'm not sure this works for negative numbers. Here are the results I get with sort version 6.10 on Fedora 9.
Input file:
-0.907928466796875
-0.61614990234375
1.135406494140625
0.48614501953125
-0.4140167236328125
Output:
-0.4140167236328125
0.48614501953125
-0.61614990234375
-0.907928466796875
1.135406494140625
Which is obviously not ordered by numeric value.
Then, I guess that a more precise answer would be to use sort -n
but only if all the values are positive.
P.S.: Using sort -g
returns just the same results for this example
Edit:
Looks like the locale settings affect how the minus sign affects the order (see here). In order to get proper results I just did:
LC_ALL=C sort -n filename.txt
called_from
must be null
. Add a test against that condition like
if (called_from != null && called_from.equalsIgnoreCase("add")) {
or you could use Yoda conditions (per the Advantages in the linked Wikipedia article it can also solve some types of unsafe null
behavior they can be described as placing the constant portion of the expression on the left side of the conditional statement)
if ("add".equalsIgnoreCase(called_from)) { // <-- safe if called_from is null
I was looking for a solution for this for a while and found most of the answers are not working or not suitable for my situation, so I wrote a simple solution with jQuery.
This is the solution outline:
Below is the code in a runnable demo.
function scrolify(tblAsJQueryObject, height) {_x000D_
var oTbl = tblAsJQueryObject;_x000D_
_x000D_
// for very large tables you can remove the four lines below_x000D_
// and wrap the table with <div> in the mark-up and assign_x000D_
// height and overflow property _x000D_
var oTblDiv = $("<div/>");_x000D_
oTblDiv.css('height', height);_x000D_
oTblDiv.css('overflow', 'scroll');_x000D_
oTbl.wrap(oTblDiv);_x000D_
_x000D_
// save original width_x000D_
oTbl.attr("data-item-original-width", oTbl.width());_x000D_
oTbl.find('thead tr td').each(function() {_x000D_
$(this).attr("data-item-original-width", $(this).width());_x000D_
});_x000D_
oTbl.find('tbody tr:eq(0) td').each(function() {_x000D_
$(this).attr("data-item-original-width", $(this).width());_x000D_
});_x000D_
_x000D_
_x000D_
// clone the original table_x000D_
var newTbl = oTbl.clone();_x000D_
_x000D_
// remove table header from original table_x000D_
oTbl.find('thead tr').remove();_x000D_
// remove table body from new table_x000D_
newTbl.find('tbody tr').remove();_x000D_
_x000D_
oTbl.parent().parent().prepend(newTbl);_x000D_
newTbl.wrap("<div/>");_x000D_
_x000D_
// replace ORIGINAL COLUMN width _x000D_
newTbl.width(newTbl.attr('data-item-original-width'));_x000D_
newTbl.find('thead tr td').each(function() {_x000D_
$(this).width($(this).attr("data-item-original-width"));_x000D_
});_x000D_
oTbl.width(oTbl.attr('data-item-original-width'));_x000D_
oTbl.find('tbody tr:eq(0) td').each(function() {_x000D_
$(this).width($(this).attr("data-item-original-width"));_x000D_
});_x000D_
}_x000D_
_x000D_
$(document).ready(function() {_x000D_
scrolify($('#tblNeedsScrolling'), 160); // 160 is height_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>_x000D_
_x000D_
<div style="width:300px;border:6px green solid;">_x000D_
<table border="1" width="100%" id="tblNeedsScrolling">_x000D_
<thead>_x000D_
<tr><th>Header 1</th><th>Header 2</th></tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr><td>row 1, cell 1</td><td>row 1, cell 2</td></tr>_x000D_
<tr><td>row 2, cell 1</td><td>row 2, cell 2</td></tr>_x000D_
<tr><td>row 3, cell 1</td><td>row 3, cell 2</td></tr>_x000D_
<tr><td>row 4, cell 1</td><td>row 4, cell 2</td></tr> _x000D_
<tr><td>row 5, cell 1</td><td>row 5, cell 2</td></tr>_x000D_
<tr><td>row 6, cell 1</td><td>row 6, cell 2</td></tr>_x000D_
<tr><td>row 7, cell 1</td><td>row 7, cell 2</td></tr>_x000D_
<tr><td>row 8, cell 1</td><td>row 8, cell 2</td></tr> _x000D_
</tbody>_x000D_
</table>_x000D_
</div>
_x000D_
This solution works in Chrome and IE. Since it is based on jQuery, this should work in other jQuery supported browsers as well.
Shelving has many uses. The main ones are:
Any other uses?
I solved this issue following the indication provided in the article http://blog.dev-area.net/2015/08/13/android-4-1-enable-tls-1-1-and-tls-1-2/ with little changes.
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, null, null);
SSLSocketFactory noSSLv3Factory = null;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
noSSLv3Factory = new TLSSocketFactory(sslContext.getSocketFactory());
} else {
noSSLv3Factory = sslContext.getSocketFactory();
}
connection.setSSLSocketFactory(noSSLv3Factory);
This is the code of the custom TLSSocketFactory:
public static class TLSSocketFactory extends SSLSocketFactory {
private SSLSocketFactory internalSSLSocketFactory;
public TLSSocketFactory(SSLSocketFactory delegate) throws KeyManagementException, NoSuchAlgorithmException {
internalSSLSocketFactory = delegate;
}
@Override
public String[] getDefaultCipherSuites() {
return internalSSLSocketFactory.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return internalSSLSocketFactory.getSupportedCipherSuites();
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(s, host, port, autoClose));
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port));
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port, localHost, localPort));
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port));
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(address, port, localAddress, localPort));
}
/*
* Utility methods
*/
private static Socket enableTLSOnSocket(Socket socket) {
if (socket != null && (socket instanceof SSLSocket)
&& isTLSServerEnabled((SSLSocket) socket)) { // skip the fix if server doesn't provide there TLS version
((SSLSocket) socket).setEnabledProtocols(new String[]{TLS_v1_1, TLS_v1_2});
}
return socket;
}
private static boolean isTLSServerEnabled(SSLSocket sslSocket) {
System.out.println("__prova__ :: " + sslSocket.getSupportedProtocols().toString());
for (String protocol : sslSocket.getSupportedProtocols()) {
if (protocol.equals(TLS_v1_1) || protocol.equals(TLS_v1_2)) {
return true;
}
}
return false;
}
}
Edit: Thank's to ademar111190 for the kotlin implementation (link)
class TLSSocketFactory constructor(
private val internalSSLSocketFactory: SSLSocketFactory
) : SSLSocketFactory() {
private val protocols = arrayOf("TLSv1.2", "TLSv1.1")
override fun getDefaultCipherSuites(): Array<String> = internalSSLSocketFactory.defaultCipherSuites
override fun getSupportedCipherSuites(): Array<String> = internalSSLSocketFactory.supportedCipherSuites
override fun createSocket(s: Socket, host: String, port: Int, autoClose: Boolean) =
enableTLSOnSocket(internalSSLSocketFactory.createSocket(s, host, port, autoClose))
override fun createSocket(host: String, port: Int) =
enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port))
override fun createSocket(host: String, port: Int, localHost: InetAddress, localPort: Int) =
enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port, localHost, localPort))
override fun createSocket(host: InetAddress, port: Int) =
enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port))
override fun createSocket(address: InetAddress, port: Int, localAddress: InetAddress, localPort: Int) =
enableTLSOnSocket(internalSSLSocketFactory.createSocket(address, port, localAddress, localPort))
private fun enableTLSOnSocket(socket: Socket?) = socket?.apply {
if (this is SSLSocket && isTLSServerEnabled(this)) {
enabledProtocols = protocols
}
}
private fun isTLSServerEnabled(sslSocket: SSLSocket) = sslSocket.supportedProtocols.any { it in protocols }
}
This could be faced in Visual Studio 2015 as well when you use the Azure AD with a MVC project. Here it create the startup file as Startup.Auth.cs in App_Start folder but it will be missing the
[assembly: OwinStartup(typeof(MyWebApp.Startup))]
So add it and you should be good to go. This goes before the namespace start.
Just a notice for a sharing hosting server or added on domains =
For your settings to work you must have a different save session dir for added domain by using php_value session.save_path folderA/sessionsA
.
So create a folder to your root server, not into the public_html
and not to be publicity accessed from outside. For my cpanel/server worked fine the folder permissions 0700
. Give a try...
# Session timeout, 2628000 sec = 1 month, 604800 = 1 week, 57600 = 16 hours, 86400 = 1 day
ini_set('session.save_path', '/home/server/.folderA_sessionsA');
ini_set('session.gc_maxlifetime', 57600);
ini_set('session.cookie_lifetime', 57600);
# session.cache_expire is in minutes unlike the other settings above
ini_set('session.cache_expire', 960);
ini_set('session.name', 'MyDomainA');
before session_start();
or put this in your .htaccess
file.
php_value session.save_path /home/server/.folderA_sessionsA
php_value session.gc_maxlifetime 57600
php_value session.cookie_lifetime 57600
php_value session.cache_expire 57600
php_value session.name MyDomainA
After many researching and testing this worked fine for shared cpanel/php7 server. Many thanks to: NoiS
#
is an id selector, used to target a single specific element with a unique id, but . is a class selector used to target multiple elements with a particular class. To put it another way:
#foo {}
will style the single element declared with an attribute id="foo"
.foo {}
will style all elements with an attribute class="foo"
(you can have multiple classes assigned to an element too, just separate them with spaces, e.g. class="foo bar"
)Generally speaking, you use # for styling something you know is only going to appear once, for example, things like high level layout divs such sidebars, banner areas etc.
Classes are used where the style is repeated, e.g. say you head a special form of header for error messages, you could create a style h1.error {}
which would only apply to <h1 class="error">
Another aspect where selectors differ is in their specificity - an id selector is deemed to be more specific than class selector. This means that where styles conflict on an element, the ones defined with the more specific selector will override less specific selectors. For example, given <div id="sidebar" class="box">
any rules for #sidebar
with override conflicting rules for .box
See Selectutorial for more great primers on CSS selectors - they are incredibly powerful, and if your conception is simply that "# is used for DIVs" you'd do well to read up on exactly how to use CSS more effectively.
EDIT: Looks like Selectutorial might have gone to the big website in the sky, so try this archive link instead.
Angular expressions do not support the ternary operator before 1.1.5, but it can be emulated like this:
condition && (answer if true) || (answer if false)
So in example, something like this would work:
<div ng-repeater="item in items">
<div>{{item.description}}</div>
<div>{{isExists(item) && 'available' || 'oh no, you don't have it'}}</div>
</div>
UPDATE: Angular 1.1.5 added support for ternary operators:
{{myVar === "two" ? "it's true" : "it's false"}}
Try : java -version , then if you see java 11
try to delete with terminal : cd /Library/Java/JavaVirtualMachines rm -rf openjdk-11.0.1.jdk
if it doesn't try delete manually: 1) click on finder 2) go to folder 3) post /Library/Java/JavaVirtualMachines 4) delete java 11 .
then try java version and you will see : java version "1.8.0_191"
public table2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 485, 218);
setTitle("jtable");
getContentPane().setLayout(null);
String data[][] = { { "Row1/1", "Row1/2", "Row1/3" },
{ "Row2/1", "Row2/2", "Row2/3" },
{ "Row3/1", "Row3/2", "Row3/3" },
{ "Row4/1", "Row4/2", "Row4/3" }, };
String header[] = { "Column 1", "Column 2", "Column 3" };
// Table
JTable table = new JTable(data,header);
// ScrollPane
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(36, 37, 407, 79);
getContentPane().add(scrollPane);
}
}
try this!!
System.String is a reference type and already "nullable".
Nullable<T> and the ? suffix are for value types such as Int32, Double, DateTime, etc.
How to change multiple "dogsss" to "dollsss":
$('#id1 p').each(function() {
var text = $(this).text();
// Use global flag i.e. g in the regex to replace all occurrences
$(this).text(text.replace(/dog/g, 'doll'));
});
SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS
(SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)
or
SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN
(SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)
or
SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B
ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL
Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.
var classname=$('#div1').attr('class')
personally I favor validating without a callback:
public bool ValidateSchema(string xmlPath, string xsdPath)
{
XmlDocument xml = new XmlDocument();
xml.Load(xmlPath);
xml.Schemas.Add(null, xsdPath);
try
{
xml.Validate(null);
}
catch (XmlSchemaValidationException)
{
return false;
}
return true;
}
(see Timiz0r's post in Synchronous XML Schema Validation? .NET 3.5)
You can simply use .toString()
.
var result = require('child_process').execSync('rsync -avAXz --info=progress2 "/src" "/dest"').toString();
console.log(result);
This has been tested on Node v8.5.0
, I'm not sure about previous versions. According to @etov, it doesn't work on v6.3.1
- I'm not sure about in-between.
Edit: Looking back on this, I've realised that it doesn't actually answer the specific question because it doesn't show the output to you 'live' — only once the command has finished running.
However, I'm leaving this answer here because I know quite a few people come across this question just looking for how to print the result of the command after execution.
I got this error because of the file was opened in another instance.
when i closed the file and again re-build the solution, it was successfully copied.
You could also use
data2 <- data[data$sum_points == 2500, ]
This will make a dataframe with the values where sum_points = 2500
It gives :
airfoils sum_points field_points init_t contour_t field_t
...
491 5 2500 5625 0.000086 0.004272 6.321774
498 5 2500 5625 0.000087 0.004507 6.325083
504 5 2500 5625 0.000088 0.004370 6.336034
603 5 250 10000 0.000072 0.000525 1.111278
577 5 250 10000 0.000104 0.000559 1.111431
587 5 250 10000 0.000072 0.000528 1.111524
606 5 250 10000 0.000079 0.000538 1.111685
....
> data2 <- data[data$sum_points == 2500, ]
> data2
airfoils sum_points field_points init_t contour_t field_t
108 5 2500 625 0.000082 0.004329 0.733109
106 5 2500 625 0.000102 0.004564 0.733243
117 5 2500 625 0.000087 0.004321 0.733274
112 5 2500 625 0.000081 0.004428 0.733587
Use,
String s="0.01";
int i= new Double(s).intValue();
[self dismissModalViewControllerAnimated:NO];
has been deprecated.
Use [self dismissViewControllerAnimated:NO completion:nil];
instead.
If you're using .NET 4 or above and you don't want to reference System.Web
, you can use WebUtility.HtmlEncode
from System
var encoded = WebUtility.HtmlEncode(unencoded);
This has the same effect as HttpUtility.HtmlEncode
and should be preferred over System.Security.SecurityElement.Escape
.
The -Contains
operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections.
From the documentation you linked to:
-Contains Description: Containment operator. Tells whether a collection of reference values includes a single test value.
In the example you provided you're working with a collection containing just one string item.
If you read the documentation you linked to you'll see an example that demonstrates this behaviour:
Examples:
PS C:\> "abc", "def" -Contains "def"
True
PS C:\> "Windows", "PowerShell" -Contains "Shell"
False #Not an exact match
I think what you want is the -Match
operator:
"12-18" -Match "-"
Which returns True
.
Important: As pointed out in the comments and in the linked documentation, it should be noted that the -Match
operator uses regular expressions to perform text matching.
Why don't you just use CopyToDataTable
DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = new DataTable();
DataTable orderRows = dt.Select("CustomerID = 2").CopyToDataTable();
If you're already normalizing the inputs to booleans, then != is xor.
bool(a) != bool(b)
if you have null value then in doing mathematical operation you will get this error to resolve it use df[~df['x'].isnull()]df[['x']].astype(int)
if you want your dataset to be unchangeable.
Apart from the previous answers, I would like to add several functions. These are results while you use them:
public static void main(String[] args) {
System.out.println(parseIntOrDefault("123", 0)); // 123
System.out.println(parseIntOrDefault("aaa", 0)); // 0
System.out.println(parseIntOrDefault("aaa456", 3, 0)); // 456
System.out.println(parseIntOrDefault("aaa789bbb", 3, 6, 0)); // 789
}
Implementation:
public static int parseIntOrDefault(String value, int defaultValue) {
int result = defaultValue;
try {
result = Integer.parseInt(value);
}
catch (Exception e) {
}
return result;
}
public static int parseIntOrDefault(String value, int beginIndex, int defaultValue) {
int result = defaultValue;
try {
String stringValue = value.substring(beginIndex);
result = Integer.parseInt(stringValue);
}
catch (Exception e) {
}
return result;
}
public static int parseIntOrDefault(String value, int beginIndex, int endIndex, int defaultValue) {
int result = defaultValue;
try {
String stringValue = value.substring(beginIndex, endIndex);
result = Integer.parseInt(stringValue);
}
catch (Exception e) {
}
return result;
}
Callable
interface declares call()
method and you need to provide generics as type of Object call() should return -
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
Runnable
on the other hand is interface that declares run()
method that is called when you create a Thread with the runnable and call start() on it. You can also directly call run() but that just executes the run() method is same thread.
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
To summarize few notable Difference are
Runnable
object does not return a result whereas a Callable
object returns a result.Runnable
object cannot throw a checked exception wheras a Callable
object can throw an
exception.Runnable
interface has been around since Java 1.0 whereas Callable
was only introduced
in Java 1.5.Few similarities include
Methods in ExecutorService interface are
<T> Future<T> submit(Callable<T> task);
Future<?> submit(Runnable task);
<T> Future<T> submit(Runnable task, T result);
After instaling the package you need to add the newtonsoft.json.dll into assemble path by runing the flowing command.
Before we can use our assembly, we have to add it to the global assembly cache (GAC). Open the Visual Studio 2008 Command Prompt again (for Vista/Windows7/etc. open it as Administrator). And execute the following command. gacutil /i d:\myMethodsForSSIS\myMethodsForSSIS\bin\Release\myMethodsForSSIS.dll
flow this link for more informATION http://microsoft-ssis.blogspot.com/2011/05/referencing-custom-assembly-inside.html
You should add this import in your file:
import * as fetch from 'node-fetch';
And then, run this code to add the node-fetch
:
yarn add node-fetch
If you want to see data updates you could use this technique with required permissions:
SELECT OBJECT_NAME(OBJECT_ID) AS DatabaseName, last_user_update,*
FROM sys.dm_db_index_usage_stats
WHERE database_id = DB_ID( 'DATABASE')
AND OBJECT_ID=OBJECT_ID('TABLE')
You can do
display/i $pc
and every time GDB stops, it will display the disassembly of the next instruction.
GDB-7.0
also supports set disassemble-next-line on
, which will disassemble the entire next line, and give you more of the disassembly context.
This is possible with CSS3. Just use position: sticky
, as seen here.
position: -webkit-sticky; /* Safari & IE */
position: sticky;
top: 0;
An image with an empty "src" attribute generates this error under Windows-Chrome:
<img src="">
... whereas ...
<img>
... does not.
I arrived here because my ajax resultset was returning "src" data which was empty yet the img was still being inserted into the page.
If you're just looking for a syntactically simple way to assign/return a string or numeric based on a boolean condition, you can use the multiplication operator like this:
"Condition is "+("true"*$condition)+("false"*!$condition)
(12.34*$condition)+(56.78*!$condition)
If you're only ever interested in the result when something is true, you can just omit the false part entirely (or vice versa), e.g. a simple scoring system:
$isTall = $true
$isDark = $false
$isHandsome = $true
$score = (2*$isTall)+(4*$isDark)+(10*$isHandsome)
"Score = $score"
# or
# "Score = $((2*$isTall)+(4*$isDark)+(10*$isHandsome))"
Note that the boolean value should not be the leading term in the multiplication, i.e. $condition*"true" etc. won't work.
Both the data import function (here: read.csv()
) as well as a global option offer you to say stringsAsFactors=FALSE
which should fix this.
One way is that In case of Session Expire, in every action you have to check its session and if it is null then redirect to Login page.
But this is very hectic method
To over come this you need to create your own ActionFilterAttribute
which will do this, you just need to add this attribute in every action method.
Here is the Class which overrides ActionFilterAttribute.
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
// check if session is supported
CurrentCustomer objCurrentCustomer = new CurrentCustomer();
objCurrentCustomer = ((CurrentCustomer)SessionStore.GetSessionValue(SessionStore.Customer));
if (objCurrentCustomer == null)
{
// check if a new session id was generated
filterContext.Result = new RedirectResult("~/Users/Login");
return;
}
base.OnActionExecuting(filterContext);
}
}
Then in action just add this attribute like so:
[SessionExpire]
public ActionResult Index()
{
return Index();
}
This will do you work.
Just a little background/update on the bean concept. Many other answers actually have the what but not so much why of them.
They were invented early on in Java as part of building GUIs. They followed patterns that were easy for tools to pull apart letting them create a properties panel so you could edit the attributes of the Bean. In general, the Bean properties represented a control on the screen (Think x,y,width,height,text,..)
You can also think of it as a strongly typed data structure.
Over time these became useful for lots of tools that used the same type of access (For example, Hibernate to persist data structures to the database)
As the tools evolved, they moved more towards annotations and away from pulling apart the setter/getter names. Now most systems don't require beans, they can take any plain old Java object with annotated properties to tell them how to manipulate them.
Now I see beans as annotated property balls--they are really only useful for the annotations they carry.
Beans themselves are not a healthy pattern. They destroy encapsulation by their nature since they expose all their properties to external manipulation and as they are used there is a tendency (by no means a requirement) to create code to manipulate the bean externally instead of creating code inside the bean (violates "don't ask an object for its values, ask an object to do something for you"). Using annotated POJOs with minimal getters and no setters is much more OO restoring encapsulation and with the possibility of immutability.
By the way, as all this stuff was happening someone extended the concept to something called Enterprise Java Beans. These are... different. and they are complicated enough that many people felt they didn't understand the entire Bean concept and stopped using the term. This is, I think, why you generally hear beans referred to as POJOs (since every Java object is a POJO this is technically OK, but when you hear someone say POJO they are most often thinking about something that follows the bean pattern)
Check whether your app has the needed permissions.I was also getting the same error and I checked the logcat debug log which showed this:
04-15 13:38:25.387: E/AndroidRuntime(694): java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:555-555-5555 cmp=com.android.phone/.OutgoingCallBroadcaster } from ProcessRecord{44068640 694:rahulserver.test/10055} (pid=694, uid=10055) requires android.permission.CALL_PHONE
I then gave the needed permission in my android-manifest which worked for me.
You can use this command,
jmeter -n -t /path to the script.jmx -l /path to save results with file name file.jtl
But if you really want to run a load test in a remote machine, you should be able to make it run eventhough you close the window. So we can use nohup to ignore the HUP (hangup) signal. So you can use this command as below.
nohup sh jmeter.sh -n -t /path to the script.jmx -l /path to save results with file name file.jtl &
The easiest way is to hard code the columns yourself to better control the output file:
SELECT 'ColName1', 'ColName2', 'ColName3'
UNION ALL
SELECT ColName1, ColName2, ColName3
FROM YourTable
INTO OUTFILE '/path/outfile'
SELECT
main.CustomerID,
f.Data AS FirstName,
m.Data AS MiddleName,
l.Data AS LastName,
d.Data AS Date
FROM table main
INNER JOIN table f on f.CustomerID = main.CustomerID
INNER JOIN table m on m.CustomerID = main.CustomerID
INNER JOIN table l on l.CustomerID = main.CustomerID
INNER JOIN table d on d.CustomerID = main.CustomerID
WHERE f.DBColumnName = 'FirstName'
AND m.DBColumnName = 'MiddleName'
AND l.DBColumnName = 'LastName'
AND d.DBColumnName = 'Date'
Edit: I have written this without an editor & have not run the SQL. I hope, you get the idea.
From personal experience, the System.Diagnostics.Stopwatch
class can be used to measure the execution time of a method, however, BEWARE: It is not entirely accurate!
Consider the following example:
Stopwatch sw;
for(int index = 0; index < 10; index++)
{
sw = Stopwatch.StartNew();
DoSomething();
Console.WriteLine(sw.ElapsedMilliseconds);
}
sw.Stop();
Example results
132ms
4ms
3ms
3ms
2ms
3ms
34ms
2ms
1ms
1ms
Now you're wondering; "well why did it take 132ms the first time, and significantly less the rest of the time?"
The answer is that Stopwatch
does not compensate for "background noise" activity in .NET, such as JITing. Therefore the first time you run your method, .NET JIT's it first. The time it takes to do this is added to the time of the execution. Equally, other factors will also cause the execution time to vary.
What you should really be looking for absolute accuracy is Performance Profiling!
Take a look at the following:
RedGate ANTS Performance Profiler is a commercial product, but produces very accurate results. - Boost the performance of your applications with .NET profiling
Here is a StackOverflow article on profiling: - What Are Some Good .NET Profilers?
I have also written an article on Performance Profiling using Stopwatch that you may want to look at - Performance profiling in .NET
Use hypertext reference and the ID tag,
Some paragraph text
Target Text<h1><a href="#target">Target Text Title</a></h1>
<p id="target">Target Text</p>
You have to call DataReader.Read
to fetch the result:
SqlDataReader dr = cmd10.ExecuteReader();
if (dr.Read())
{
// read data for first record here
}
DataReader.Read()
returns a bool
indicating if there are more blocks of data to read, so if you have more than 1 result, you can do:
while (dr.Read())
{
// read data for each record here
}
Provide the full path of the file openfile.exe
and remember not to put forward slash /
in the path such as
c:/users/username/etc....
instead of that use
c:\\Users\\username\etc
(for windows)
May be this will help you.
It depends on how the data was initially put into the column. Try either of these as one should work:
SELECT CONVERT(NVarChar(40), BLOBTextToExtract)
FROM [NavisionSQL$Customer];
Or if it was just varchar
...
SELECT CONVERT(VarChar(40), BLOBTextToExtract)
FROM [NavisionSQL$Customer];
I used this script to verify and test on SQL Server 2K8 R2:
DECLARE @blob VarBinary(MAX) = CONVERT(VarBinary(MAX), 'test');
-- show the binary representation
SELECT @blob;
-- this doesn't work
SELECT CONVERT(NVarChar(100), @blob);
-- but this does
SELECT CONVERT(VarChar(100), @blob);
Here's another solution. This uses:
For the following input string:
"This is\, a value",Hello,4,-123,3.1415,'This is also\, possible',true
The code outputs:
[
"This is, a value",
"Hello",
4,
-123,
3.1415,
"This is also, possible",
true
]
Here's my implementation of parseCSVLine() in a runnable code snippet:
function parseCSVLine(text) {
return text.match( /\s*(\".*?\"|'.*?'|[^,]+)\s*(,|$)/g ).map( function (text) {
let m;
if (m = text.match(/^\s*\"(.*?)\"\s*,?$/)) return m[1]; // Double Quoted Text
if (m = text.match(/^\s*'(.*?)'\s*,?$/)) return m[1]; // Single Quoted Text
if (m = text.match(/^\s*(true|false)\s*,?$/)) return m[1] === "true"; // Boolean
if (m = text.match(/^\s*((?:\+|\-)?\d+)\s*,?$/)) return parseInt(m[1]); // Integer Number
if (m = text.match(/^\s*((?:\+|\-)?\d*\.\d*)\s*,?$/)) return parseFloat(m[1]); // Floating Number
if (m = text.match(/^\s*(.*?)\s*,?$/)) return m[1]; // Unquoted Text
return text;
} );
}
let data = `"This is\, a value",Hello,4,-123,3.1415,'This is also\, possible',true`;
let obj = parseCSVLine(data);
console.log( JSON.stringify( obj, undefined, 2 ) );
_x000D_
If you want to call something like this NSString.newLine;
from objective c, and you want it to be static constant, you can create something like this in swift:
public extension NSString {
@objc public static let newLine = "\n"
}
And you have nice readable constant definition, and available from within a type of your choice while stile bounded to context of type.
userListComboBox.DataSource = userCache.ToList();
userListComboBox.DisplayMember = "Key";
You can use something like this
<div class="row">
<div class="col-xs-2">
<select id="info_type" class="form-control">
<option>College</option>
<option>Exam</option>
</select>
</div>
</div>
BigDecimal b = new BigDecimal(c).setScale(2,BigDecimal.ROUND_HALF_UP);
We have just uploaded AmbilWarna color picker to Maven:
https://github.com/yukuku/ambilwarna
It can be used either as a dialog or as a Preference entry.
LinkedList<String>list = new LinkedList<String>();
list.add("abc");
list.add("Bcd");
list.add("aAb");
list.sort(String::compareToIgnoreCase);
Another option would be using lambda expressions:
list.sort((o1, o2) -> o1.compareToIgnoreCase(o2));
Set the items into display: inline
and use :after
:
.text span { display: inline }
.break-after:after { content: '\A'; white-space:pre; }
and add the class into your html spans:
<span class="medium break-after">We</span>
Since PHP 5.4 there are constants which can be used by json_encode()
to format the json reponse how you want.
To remove backslashes use: JSON_UNESCAPED_SLASHES
. Like so:
json_encode($response, JSON_UNESCAPED_SLASHES);
View the PHP documentation for more constants and further information:
http://php.net/manual/en/function.json-encode.php
List of JSON constants:
og_date = "2012-10-01";
console.log(og_date); // => "2012-10-01"
console.log(og_date.split('-')); // => [ '2012', '10', '01' ]
og_date.value
would only work if the date were stored as a property on the og_date object.
Such as: var og_date = {}; og_date.value="2012-10-01";
In that case, your original console.log would work.
MySQL 8.0/MariaDB supports windowed SUM(col) OVER()
:
SELECT *, SUM(cnt) OVER(ORDER BY id) AS cumulative_sum
FROM tab;
Output:
+-----------------------------+
¦ id ¦ cnt ¦ cumulative_sum ¦
+-----+------+----------------¦
¦ 1 ¦ 100 ¦ 100 ¦
¦ 2 ¦ 50 ¦ 150 ¦
¦ 3 ¦ 10 ¦ 160 ¦
+-----------------------------+
Assuming you are using Eclipse, on a MAC you can:
Eclipse.app
Eclipse -> Preferences
Java -> Installed JREs
Add...
buttonMacOS X VM
as the JRE type. Press Next./Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home
JDK 1.7
. Click Finish.File -> New -> Java Project
.Use default JRE (currently JDK 1.7)
Hope this helps
yourPictureBox.ImageLocation = "http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG"