For Ubuntu 14.04 with
PHP 7.0.13-1+deb.sury.org~trusty+1 (cli) ( NTS )
sudo apt-get install php-xml
worked for me.
This won't show you the DOM path, but it will output a string representation of what you see in eg chrome debugger, when viewing an object.
$('.mybtn').click( function(event){
console.log("%s", this); // output: "button.mybtn"
});
https://developer.chrome.com/devtools/docs/console-api#consolelogobject-object
File outputfile = new File("image.jpg");
ImageIO.write(bufferedImage, "jpg", outputfile);
The correct way, as SAM write before is:
reg Query "HKLM\Hardware\Description\System\CentralProcessor\0" /v "Identifier" | find /i "x86" > NUL && set OS=32BIT || set OS=64BIT
but with /v "Identifier" a little bit correct.
Why not try IS?
$('selector').is(':checked') /* result true or false */
Look a FAQ: jQuery .is() enjoin us ;-)
Form1
from the code. Form1
.NotifyIcon
class to create your system tray icon (assign an icon to it).NotifyIcon
's mouseclick and differenciate between Right and Left click, setting your contextmenu and showing it for which ever button (right/left) was pressed.Application.Run()
to keep the app running with Application.Exit()
to quit. Or a bool bRunning = true; while(bRunning){Application.DoEvents(); Thread.Sleep(10);}
. Then set bRunning = false;
to exit the app.In the model, do not pass the value:
timezone.now()
Rather, remove the parenthesis, and pass:
timezone.now
If you continue to get a runtime error warning, consider changing the model field from DateTimeField to DateField.
I guess it's just because the onblur event is called as a result of the input losing focus, there isn't a blur action associated with an input, like there is a click action associated with a button
All of the example above should work just add a document ready action and change the order of how you perform the updates to the texts, also make sure your using Script manager alternatively non of this will work for you. Here is the text within the code behind.
aspx
<div class="modal fade" id="myModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<asp:UpdatePanel ID="upModal" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"><asp:Label ID="lblModalTitle" runat="server" Text=""></asp:Label></h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<asp:Label ID="lblModalBody" runat="server" Text=""></asp:Label>
</div>
<div class="modal-footer">
<button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
Code Behind
lblModalTitle.Text = "Validation Errors";
lblModalBody.Text = form.Error;
upModal.Update();
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myModal", "$(document).ready(function () {$('#myModal').modal();});", true);
Navigate to Window > Preferences > General > Editors > Text Editors
Click on the CheckBox "Show whitespace characters".
Thats all.!!!
I would install PowerShell. It understands .NET objects and has an Format-Table and Export-Csv that would do exactly what you are looking for. If you do any sort of console work it is a great complement/replacement to C# console apps.
When I started using it, I rewrote my console apps as libraries and import the libraries into Powershell. The built-in commandlets make console work so nice.
You can use the index of the array element to remove it from the array, the next time you use the $list
variable, you will see that the array is changed.
Try something like this
foreach($list as $itemIndex => &$item) {
if($item['status'] === false) {
unset($list[$itemIndex]);
}
}
The heap memory is the runtime data area from which the Java VM allocates memory for all class instances and arrays. The heap may be of a fixed or variable size. The garbage collector is an automatic memory management system that reclaims heap memory for objects.
Eden Space: The pool from which memory is initially allocated for most objects.
Survivor Space: The pool containing objects that have survived the garbage collection of the Eden space.
Tenured Generation or Old Gen: The pool containing objects that have existed for some time in the survivor space.
Non-heap memory includes a method area shared among all threads and memory required for the internal processing or optimization for the Java VM. It stores per-class structures such as a runtime constant pool, field and method data, and the code for methods and constructors. The method area is logically part of the heap but, depending on the implementation, a Java VM may not garbage collect or compact it. Like the heap memory, the method area may be of a fixed or variable size. The memory for the method area does not need to be contiguous.
Permanent Generation: The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
Code Cache: The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.
The key function helped me and is very simple:
The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns NULL.
Example:
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'<br />';
}
next($array);
}
?>
The above example will output:
fruit1<br />
fruit4<br />
fruit5<br />
Spring beans are classes. Instead of instantiating a class (using new
), you get an instance as a bean
cast to your class type from the application context, where the bean is what you configured in the application context configuration. This way, the whole application maintains singleton-scope instance throughout the application. All beans are initialized following their configuration order right after the application context is instantiated. Even if you don't get any beans in your application, all beans instances are already created the moment after you created the application context.
The most convenient way according to me is:
(Val in X[:, col_num])
where Val is the value that you want to check for and X is the array. In your example, suppose you want to check if the value 8 exists in your the third column. Simply write
(8 in X[:, 2])
This will return True if 8 is there in the third column, else False.
BufferedReader
has significantly larger buffer memory than Scanner. Use BufferedReader
if you want to get long strings from a stream, and use Scanner
if you want to parse specific type of token from a stream.
Scanner
can use tokenize using custom delimiter and parse the stream into primitive types of data, while BufferedReader
can only read and store String.
BufferedReader
is synchronous while Scanner
is not. Use BufferedReader
if you're working with multiple threads.
Scanner
hides IOException while BufferedReader
throws it immediately.
Actually you have to Do Like below Example, which will help to Solve the Issue...
drop table ABC_table
create table ABC_table
(
names varchar(20),
age int
)
ALTER TABLE ABC_table
ADD CONSTRAINT MyConstraintName
DEFAULT 'This is not NULL' FOR names
insert into ABC(age) values(10)
select * from ABC
Just one space or all consecutive spaces? If the second, then strings already have a .strip()
method:
>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'
>>> ' Hello '.strip() # ALL consecutive spaces at both ends removed
'Hello'
If you only need to remove one space however, you could do it with:
def strip_one_space(s):
if s.endswith(" "): s = s[:-1]
if s.startswith(" "): s = s[1:]
return s
>>> strip_one_space(" Hello ")
' Hello'
Also, note that str.strip()
removes other whitespace characters as well (e.g. tabs and newlines). To remove only spaces, you can specify the character to remove as an argument to strip
, i.e.:
>>> " Hello\n".strip(" ")
'Hello\n'
Undoubtedly, for your purposes (which I assume is just a programming exercise), the best thing is to check your results against any of the listings of the digits of pi on the web.
And how do we know that those values are correct? Well, I could say that there are computer-science-y ways to prove that an implementation of an algorithm is correct.
More pragmatically, if different people use different algorithms, and they all agree to (pick a number) a thousand (million, whatever) decimal places, that should give you a warm fuzzy feeling that they got it right.
Historically, William Shanks published pi to 707 decimal places in 1873. Poor guy, he made a mistake starting at the 528th decimal place.
Very interestingly, in 1995 an algorithm was published that had the property that would directly calculate the nth digit (base 16) of pi without having to calculate all the previous digits!
Finally, I hope your initial algorithm wasn't pi/4 = 1 - 1/3 + 1/5 - 1/7 + ...
That may be the simplest to program, but it's also one of the slowest ways to do so. Check out the pi article on Wikipedia for faster approaches.
Check whether the jars are imported properly. I imported them using build path. But it didn't recognise the jar in WAR/lib folder. Later, I copied the same jar to war/lib folder. It works fine now. You can refresh / clean your project.
My own experience has been that it's best to stick to one of two kinds of assembly references:
I've found (much like you've described) other methods to either be too easily broken or have annoying maintenance requirements.
Any assembly I don't want to GAC, has to live in the execution directory. Any assembly that isn't or can't be in the execution directory I GAC (managed by automatic build events).
This hasn't given me any problems so far. While I'm sure there's a situation where it won't work, the usual answer to any problem has been "oh, just GAC it!". 8 D
Hope that helps!
I had a same problem with scrolling in chrome. So i removed this lines of codes from my style file.
html{height:100%;}
body{height:100%;}
Now i can play with scroll and it works:
var pos = 500;
$("html,body").animate({ scrollTop: pos }, "slow");
Besides the previous post instructions, I had to install the package Microsoft.jQuery.Unobtrusive.Ajax and add to the view the following line
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
Disclaimer: This answer works, but is intended for educational purposes only. :) James Jones' solution is probably the best here and certainly the one I'd go with.
C# 4.0's dynamic
keyword makes this even easier, if less safe:
public static dynamic GetNullableValue(this IDataRecord record, string columnName)
{
var val = reader[columnName];
return (val == DBNull.Value ? null : val);
}
Now you don't need the explicit type hinting on the RHS:
int? value = myDataReader.GetNullableValue("MyColumnName");
In fact, you don't need it anywhere!
var value = myDataReader.GetNullableValue("MyColumnName");
value
will now be an int, or a string, or whatever type was returned from the DB.
The only problem is that this does not prevent you from using non-nullable types on the LHS, in which case you'll get a rather nasty runtime exception like:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot convert null to 'int' because it is a non-nullable value type
As with all code that uses dynamic
: caveat coder.
As far as I know there's no way to do a blanket delete of any cookie set on the domain. You can clear a cookie if you know the name and if the script is on the same domain as the cookie.
You can set the value to empty and the expiration date to somewhere in the past:
var mydate = new Date();
mydate.setTime(mydate.getTime() - 1);
document.cookie = "username=; expires=" + mydate.toGMTString();
There's an excellent article here on manipulating cookies using javascript.
First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.
But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.
For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used
CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN
INSERT hospitals ([Hospital ID], Email, Description)
VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid)));
SET @hid = @hid + 1;
END
And result would be
ID Hospital ID Email Description
---- ----------- ---------------- ---------------------
1 16 [email protected] Sample Description16
2 17 [email protected] Sample Description17
...
84 99 [email protected] Sample Description99
create a new class called ComboKeyValue.java
public class ComboKeyValue {
private String key;
private String value;
public ComboKeyValue(String key, String value) {
this.key = key;
this.value = value;
}
@Override
public String toString(){
return key;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
}
when you want to add a new item, just write the code as below
DefaultComboBoxModel model = new DefaultComboBoxModel();
model.addElement(new ComboKeyValue("key", "value"));
properties.setModel(model);
Using Java 8 this worked for me:
@Override
public void start(Stage stage) {
Scene scene = new Scene(new Region());
stage.setScene(scene);
/* ... OTHER STUFF ... */
stage.setOnCloseRequest(e -> {
Platform.exit();
System.exit(0);
});
}
You can attach an event listener as below. It will trigger whenever the div having selector #my-id
loads completely to DOM.
$(document).on('EventName', '#my-id', function() {
// do something
});
Inthis case EventName may be 'load' or 'click'
To store the third line into a variable, use below syntax:
variable=`echo "$1" | sed '3q;d' urfile`
To store the changed line into a variable, use below syntax:
variable=echo 'overflow' | sed -e "s/over/"OVER"/g"
output:OVERflow
i also faced this problem,
i found password field was blank in config file of phpmyadmin. i put that password which i filled in database settings. now it is working fine
In the CMakeLists.txt file, create a cache variable, as documented here:
SET(FAB "po" CACHE STRING "Some user-specified option")
Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#command:set
Then, either use the GUI (ccmake or cmake-gui) to set the cache variable, or specify the value of the variable on the cmake command line:
cmake -DFAB:STRING=po
Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#opt:-Dvar:typevalue
Modify your cache variable to a boolean if, in fact, your option is boolean.
It's also worth noting that ActiveX controls only work in Windows, whereas Form Controls will work on both Windows and MacOS versions of Excel.
Without checking your code, I think what you are describing is that your pages are out of sync and you have stale data.
You say you are changing the number of pages, then crashing because you are accessing the old set of pages. This sounds to me like you are not calling pageAdapter.notifyDataSetChanged()
after changing your data.
When your viewPager
is showing page 3 of a set of 10 pages, and you change to a set with only 5, then call notifyDataSetChanged()
, what you'll find is you are now viewing page 3 of the new set. If you were previously viewing page 8 of the old set, after putting in the new set and calling notifyDataSetChanged()
you will find you are now viewing the last page of the new set without crashing.
If you simply change your current page, you may just be masking the problem.
Both these will give you the first child node:
console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);
If you need the first child that is an element node then use:
console.log(parentElement.children[0]);
Edit
Ah, I see your problem now; parentElement
is an array.
If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0]
to dearray (yes, I made that word up) the element:
var parentElement = document.getElementsByClassName("uniqueClassName")[0];
As shown here, the second argument to substr
is the length, not the ending position:
string substr ( size_t pos = 0, size_t n = npos ) const;
Generate substring
Returns a string object with its contents initialized to a substring of the current object. This substring is the character sequence that starts at character position
pos
and has a length ofn
characters.
Your line b = a.substr(i,i+1);
will generate, for values of i
:
substr(0,1) = 1
substr(1,2) = 23
substr(2,3) = 345
substr(3,4) = 45 (since your string stops there).
What you need is b = a.substr(i,2);
You should also be aware that your output will look funny for a number like 12045. You'll get 12 20 4 45
due to the fact that you're using atoi()
on the string section and outputting that integer. You might want to try just outputing the string itself which will be two characters long:
b = a.substr(i,2);
cout << b << " ";
In fact, the entire thing could be more simply written as:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string a;
cin >> a;
for (int i = 0; i < a.size() - 1; i++)
cout << a.substr(i,2) << " ";
cout << endl;
return 0;
}
Properties support asymmetric access, i.e. you can have either a getter and a setter or just one of the two. Similarly properties support individual accessibility for getter/setter. Fields are always symmetric, i.e. you can always both get and set the value. Exception to this is readonly fields which obviously cannot be set after initialization.
Properties may run for a very long time, have side effects, and may even throw exceptions. Fields are fast, with no side effects, and will never throw exceptions. Due to side effects a property may return a different value for each call (as may be the case for DateTime.Now, i.e. DateTime.Now is not always equal to DateTime.Now). Fields always return the same value.
Fields may be used for out / ref parameters, properties may not. Properties support additional logic – this could be used to implement lazy loading among other things.
Properties support a level of abstraction by encapsulating whatever it means to get/set the value.
Use properties in most / all cases, but try to avoid side effects.
If you want to do that yourself, without using any external library, a clean way would be to create a template.html
file with all the static content, like for example:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>$title</title>
</head>
<body>$body
</body>
</html>
Put a tag like $tag
for any dynamic content and then do something like this:
File htmlTemplateFile = new File("path/template.html");
String htmlString = FileUtils.readFileToString(htmlTemplateFile);
String title = "New Page";
String body = "This is Body";
htmlString = htmlString.replace("$title", title);
htmlString = htmlString.replace("$body", body);
File newHtmlFile = new File("path/new.html");
FileUtils.writeStringToFile(newHtmlFile, htmlString);
Note: I used org.apache.commons.io.FileUtils for simplicity.
In order to access the users location in iOS. You need to add two keys
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
into the Info.plist file.
<key>NSLocationWhenInUseUsageDescription</key>
<string>Because I want to know where you are!</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Want to know where you are!</string>
See this below image.
Trust me, this will work for you:
npm config set registry http://registry.npmjs.org/
Rename filename by searching the last character of name. For example,
Original Filename: TestFile.txt_001
Begin Character need to be removed: _
Result: TestFile.txt
Option Explicit
Dim oWSH
Dim vbsInterpreter
Dim arg1 'As String
Dim arg2 'As String
Dim newFilename 'As string
Set oWSH = CreateObject("WScript.Shell")
vbsInterpreter = "cscript.exe"
ForceConsole()
arg1 = WScript.Arguments(0)
arg2 = WScript.Arguments(1)
WScript.StdOut.WriteLine "This is a test script."
Dim result
result = InstrRev(arg1, arg2, -1)
If result > 0 then
newFilename = Mid(arg1, 1, result - 1)
Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
Fso.MoveFile arg1, newFilename
WScript.StdOut.WriteLine newFilename
End If
Function ForceConsole()
If InStr(LCase(WScript.FullName), vbsInterpreter) = 0 Then
oWSH.Run vbsInterpreter & " //NoLogo " & Chr(34) & WScript.ScriptFullName & Chr(34)
WScript.Quit
End If
End Function
@Baba's answer is great. But you don't need to use explode
because fputcsv
takes an array as a parameter
For instance, if you have a three columns, four lines document, here's a more straight version:
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$user_CSV[0] = array('first_name', 'last_name', 'age');
// very simple to increment with i++ if looping through a database result
$user_CSV[1] = array('Quentin', 'Del Viento', 34);
$user_CSV[2] = array('Antoine', 'Del Torro', 55);
$user_CSV[3] = array('Arthur', 'Vincente', 15);
$fp = fopen('php://output', 'wb');
foreach ($user_CSV as $line) {
// though CSV stands for "comma separated value"
// in many countries (including France) separator is ";"
fputcsv($fp, $line, ',');
}
fclose($fp);
in Mono Android you can use filter like this:
your_button.Background.SetColorFilter(new Android.Graphics.PorterDuffColorFilter(Android.Graphics.Color.Red, Android.Graphics.PorterDuff.Mode.Multiply));
Applying the text-align:center
style to an element containing elements will center those elements.
<div id="method-one" style="text-align:center">
CSS `text-align:center`
</div>
Thomas Shields mentions this method
Applying the margin:0 auto
style to a block element will center it within the element it is in.
<div id="method-two" style="background-color:green">
<div style="margin:0 auto;width:50%;background-color:lightblue">
CSS `margin:0 auto` to have left and right margin set to center a block element within another element.
</div>
</div>
user1468562 mentions this method
My original answer was that you can use the <center></center>
tag. To do this, just place the content you want centered between the tags. As of HTML4, this tag has been deprecated, though. <center>
is still technically supported today (9 years later at the time of updating this), but I'd recommend the CSS alternatives I've included above.
<h3>Method 3</h1>
<div id="method-three">
<center>Center tag (not recommended and deprecated in HTML4)</center>
</div>
You can see these three code samples in action in this jsfiddle.
I decided I should revise this answer as the previous one I gave was outdated. It was already deprecated when I suggested it as a solution and that's all the more reason to avoid it now 9 years later.
You used wrong letter case for year in line:
@JsonFormat(pattern = "YYYY-MM-dd HH:mm")
Should be:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
With this change everything is working as expected.
You're getting the error because result
defined as Sequential()
is just a container for the model and you have not defined an input for it.
Given what you're trying to build set result
to take the third input x3
.
first = Sequential()
first.add(Dense(1, input_shape=(2,), activation='sigmoid'))
second = Sequential()
second.add(Dense(1, input_shape=(1,), activation='sigmoid'))
third = Sequential()
# of course you must provide the input to result which will be your x3
third.add(Dense(1, input_shape=(1,), activation='sigmoid'))
# lets say you add a few more layers to first and second.
# concatenate them
merged = Concatenate([first, second])
# then concatenate the two outputs
result = Concatenate([merged, third])
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
result.compile(optimizer=ada_grad, loss='binary_crossentropy',
metrics=['accuracy'])
However, my preferred way of building a model that has this type of input structure would be to use the functional api.
Here is an implementation of your requirements to get you started:
from keras.models import Model
from keras.layers import Concatenate, Dense, LSTM, Input, concatenate
from keras.optimizers import Adagrad
first_input = Input(shape=(2, ))
first_dense = Dense(1, )(first_input)
second_input = Input(shape=(2, ))
second_dense = Dense(1, )(second_input)
merge_one = concatenate([first_dense, second_dense])
third_input = Input(shape=(1, ))
merge_two = concatenate([merge_one, third_input])
model = Model(inputs=[first_input, second_input, third_input], outputs=merge_two)
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
model.compile(optimizer=ada_grad, loss='binary_crossentropy',
metrics=['accuracy'])
To answer the question in the comments:
Concatenation works like this:
a b c
a b c g h i a b c g h i
d e f j k l d e f j k l
i.e rows are just joined.
x1
is input to first, x2
is input into second and x3
input into third.You get the error because if
can only evaluate a logical
vector of length 1.
Maybe you miss the difference between &
(|
) and &&
(||
). The shorter version works element-wise and the longer version uses only the first element of each vector, e.g.:
c(TRUE, TRUE) & c(TRUE, FALSE)
# [1] TRUE FALSE
# c(TRUE, TRUE) && c(TRUE, FALSE)
[1] TRUE
You don't need the if
statement at all:
mut1 <- trip$Ref.y=='G' & trip$Variant.y=='T'|trip$Ref.y=='C' & trip$Variant.y=='A'
trip[mut1, "mutType"] <- "G:C to T:A"
You could use cURL:
<?php
//The url you wish to send the POST request to
$url = $file_name;
//The data you want to send via POST
$fields = [
'__VIEWSTATE ' => $state,
'__EVENTVALIDATION' => $valid,
'btnSubmit' => 'Submit'
];
//url-ify the data for the POST
$fields_string = http_build_query($fields);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//So that curl_exec returns the contents of the cURL; rather than echoing it
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
//execute post
$result = curl_exec($ch);
echo $result;
?>
From the wampserver 3.x onwards, changing the listening port number of Apache does not require any particular Apache skills (http.conf, virtualhost,...), you just have to click button - assuming you're running Windows OS! :
NB: For alternative port: check official IANA Service Name and Transport Protocol Port Number Registry
Intent promptInstall = new Intent(android.content.Intent.ACTION_VIEW);
promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
promptInstall.setDataAndType(Uri.parse("http://10.0.2.2:8081/MyAPPStore/apk/Teflouki.apk"), "application/vnd.android.package-archive" );
startActivity(promptInstall);
Let's assume you have the following simple filter, which converts a string to uppercase, with a parameter for the first character only.
app.filter('uppercase', function() {
return function(string, firstCharOnly) {
return (!firstCharOnly)
? string.toUpperCase()
: string.charAt(0).toUpperCase() + string.slice(1);
}
});
Directly through $filter
app.controller('MyController', function($filter) {
// HELLO
var text = $filter('uppercase')('hello');
// Hello
var text = $filter('uppercase')('hello', true);
});
Note: this gives you access to all your filters.
Assign $filter
to a variable
This option allows you to use the $filter
like a function
.
app.controller('MyController', function($filter) {
var uppercaseFilter = $filter('uppercase');
// HELLO
var text = uppercaseFilter('hello');
// Hello
var text = uppercaseFilter('hello', true);
});
Load only a specific Filter
You can load only a specific filter by appending the filter name with Filter
.
app.controller('MyController', function(uppercaseFilter) {
// HELLO
var text = uppercaseFilter('hello');
// Hello
var text = uppercaseFilter('hello', true);
});
Which one you use comes to personal preference, but I recommend using the third, because it's the most readable option.
For your property example do:
mvn install "-Dmyproperty=my property from command line"
Note quotes around whole property definition. You'll need them if your property contains spaces.
The solution provided by Reuben Scratton and Kachi seems to rely on the pixel density of the devices, if you have a high density device the height difference can be bigger than 100 even with the keyboard down. A little work around that would be to see the initial height difference (with keyboard down) and then compare with the current difference.
boolean isOpened = false;
int firstHeightDiff = -1;
public void setListenerToRootView(){
final View activityRootView = getActivity().getWindow().getDecorView().findViewById(android.R.id.content);
Rect r = new Rect();
activityRootView.getWindowVisibleDisplayFrame(r);
firstHeightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (isAdded()) {
Rect r = new Rect();
activityRootView.getWindowVisibleDisplayFrame(r);
int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
isOpened = heightDiff>firstHeightDiff+100;
if (isAdded())
if(isOpened) {
//TODO stuff for when it is up
} else {
//TODO stuf for when it is down
}
}
}
});
}
You can create a stored procedure passing 2 dates
CREATE PROCEDURE SELECTALLDATES
(
@StartDate as date,
@EndDate as date
)
AS
Declare @Current as date = DATEADD(DD, 1, @BeginDate);
Create table #tmpDates
(displayDate date)
WHILE @Current < @EndDate
BEGIN
insert into #tmpDates
VALUES(@Current);
set @Current = DATEADD(DD, 1, @Current) -- add 1 to current day
END
Select *
from #tmpDates
drop table #tmpDates
After doing some research, it seems I cannot have two connections opened to the same database with the TransactionScope block. I needed to modify my code to look like this:
public void MyAddUpdateMethod()
{
using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
using(SQLServer Sql = new SQLServer(this.m_connstring))
{
//do my first add update statement
}
//removed the method call from the first sql server using statement
bool DoesRecordExist = this.SelectStatementCall(id)
}
}
public bool SelectStatementCall(System.Guid id)
{
using(SQLServer Sql = new SQLServer(this.m_connstring))
{
//create parameters
}
}
'So from this discussion i am thinking this should be the code then.
Sub Button1_Click()
Dim excel As excel.Application
Dim wb As excel.Workbook
Dim sht As excel.Worksheet
Dim f As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = False
f.Show
Set excel = CreateObject("excel.Application")
Set wb = excel.Workbooks.Open(f.SelectedItems(1))
Set sht = wb.Worksheets("Data")
sht.Activate
sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
wb.Close
End Sub
'Let me know if this is correct or a step was missed. Thx.
Use :
FileInfo fInfo = new FileInfo('FilePath');
var fFirstTime = fInfo.CreationTime;
var fLastTime = fInfo.LastWriteTime;
The issue is due to incompatibility of unity with latest Android build tools. For MacOS here's a one liner that will get it working for you:
cd $ANDROID_HOME; rm -rf tools; wget http://dl-ssl.google.com/android/repository/tools_r25.2.5-ma??cosx.zip; unzip tools_r25.2.5-macosx.zip
I've had this same issue but have now found the resolution for it.
The trick is to create a wallpaper image of 1920*1200. When you then apply this wallpaper to the different machines, Windows 7 automatically resizes for best fit.
Hope this helps you all
I'd like expand on @JustAGuy's answer. The method I prefer is to use AWS CLI
to create a config file. The reason is, with the config file, the CLI
or the SDK
will automatically look for credentials in the ~/.aws
folder. And the good thing is that AWS CLI
is written in python.
You can get cli from pypi if you don't have it already. Here are the steps to get cli set up from terminal
$> pip install awscli #can add user flag
$> aws configure
AWS Access Key ID [****************ABCD]:[enter your key here]
AWS Secret Access Key [****************xyz]:[enter your secret key here]
Default region name [us-west-2]:[enter your region here]
Default output format [None]:
After this you can access boto
and any of the api without having to specify keys (unless you want to use a different credentials).
Have been using this one for a message overlay that can be closed immediately on click or it does an autoclose after 10 seconds.
button = $('.status-button a', whatever);
if(button.hasClass('close')) {
button.delay(10000).queue(function() {
$(this).click().dequeue();
});
}
I think this link is pretty good.
Sample output from that link:
mysql> SELECT cate_id,COUNT(DISTINCT(pub_lang)), ROUND(AVG(no_page),2)
-> FROM book_mast
-> GROUP BY cate_id;
+---------+---------------------------+-----------------------+
| cate_id | COUNT(DISTINCT(pub_lang)) | ROUND(AVG(no_page),2) |
+---------+---------------------------+-----------------------+
| CA001 | 2 | 264.33 |
| CA002 | 1 | 433.33 |
| CA003 | 2 | 256.67 |
| CA004 | 3 | 246.67 |
| CA005 | 3 | 245.75 |
+---------+---------------------------+-----------------------+
5 rows in set (0.00 sec)
I am new to all this, but for me a simple alias worked:
alias node='env NODE_NO_READLINE=1 rlwrap nodejs'
at least for running things directly in bash and executing .js files.
var randomNums = function(amount, limit) {
var result = [],
memo = {};
while(result.length < amount) {
var num = Math.floor((Math.random() * limit) + 1);
if(!memo[num]) { memo[num] = num; result.push(num); };
}
return result; }
This seems to work, and its constant lookup for duplicates.
You can also use .reverse(). It's a native array function
<div ng-repeat="friend in friends.reverse()">{{friend.name}}</div>
You must add the declaration
At the top of your document.
Without it, jquery tends to put the dialog on the bottom of the page and errors may occur when trying to drag it.
Dealing with GET parameters I iterated on Andrea Motto' solution.
The problem was that Volley called GetUrl
several times and his solution, using an Iterator, destroyed original Map object. The subsequent Volley internal calls had an empty params object.
I added also the encode of parameters.
This is an inline usage (no subclass).
public void GET(String url, Map<String, String> params, Response.Listener<String> response_listener, Response.ErrorListener error_listener, String API_KEY, String stringRequestTag) {
final Map<String, String> mParams = params;
final String mAPI_KEY = API_KEY;
final String mUrl = url;
StringRequest stringRequest = new StringRequest(
Request.Method.GET,
mUrl,
response_listener,
error_listener
) {
@Override
protected Map<String, String> getParams() {
return mParams;
}
@Override
public String getUrl() {
StringBuilder stringBuilder = new StringBuilder(mUrl);
int i = 1;
for (Map.Entry<String,String> entry: mParams.entrySet()) {
String key;
String value;
try {
key = URLEncoder.encode(entry.getKey(), "UTF-8");
value = URLEncoder.encode(entry.getValue(), "UTF-8");
if(i == 1) {
stringBuilder.append("?" + key + "=" + value);
} else {
stringBuilder.append("&" + key + "=" + value);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
String url = stringBuilder.toString();
return url;
}
@Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
if (!(mAPI_KEY.equals(""))) {
headers.put("X-API-KEY", mAPI_KEY);
}
return headers;
}
};
if (stringRequestTag != null) {
stringRequest.setTag(stringRequestTag);
}
mRequestQueue.add(stringRequest);
}
This function uses headers to pass an APIKEY and sets a TAG to the request useful to cancel it before its completion.
Hope this helps.
I seem to be having success doing
org.jboss.logmanager.Logger logger = org.jboss.logmanager.Logger.getLogger("");
logger.setLevel(java.util.logging.Level.ALL);
Then to get detailed logging from netty, the following has done it
org.slf4j.impl.SimpleLogger.setLevel(org.slf4j.impl.SimpleLogger.TRACE);
For me the simple solution works to set cookies in HttpRequestMessage object.
protected async Task<HttpResponseMessage> SendRequest(HttpRequestMessage requestMessage, CancellationToken cancellationToken = default(CancellationToken))
{
requestMessage.Headers.Add("Cookie", $"<Cookie Name 1>=<Cookie Value 1>;<Cookie Name 2>=<Cookie Value 2>");
return await _httpClient.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false);
}
CREATE OR REPLACE function f_add_col(_tbl regclass, _col text, _type regtype)
RETURNS bool AS
$func$
BEGIN
IF EXISTS (SELECT 1 FROM pg_attribute
WHERE attrelid = _tbl
AND attname = _col
AND NOT attisdropped) THEN
RETURN FALSE;
ELSE
EXECUTE format('ALTER TABLE %s ADD COLUMN %I %s', _tbl, _col, _type);
RETURN TRUE;
END IF;
END
$func$ LANGUAGE plpgsql;
Call:
SELECT f_add_col('public.kat', 'pfad1', 'int');
Returns TRUE
on success, else FALSE
(column already exists).
Raises an exception for invalid table or type name.
This could be done with a DO
statement, but DO
statements cannot return anything. And if it's for repeated use, I would create a function.
I use the object identifier types regclass
and regtype
for _tbl
and _type
which a) prevents SQL injection and b) checks validity of both immediately (cheapest possible way). The column name _col
has still to be sanitized for EXECUTE
with quote_ident()
. More explanation in this related answer:
format()
requires Postgres 9.1+. For older versions concatenate manually:
EXECUTE 'ALTER TABLE ' || _tbl || ' ADD COLUMN ' || quote_ident(_col) || ' ' || _type;
You can schema-qualify your table name, but you don't have to.
You can double-quote the identifiers in the function call to preserve camel-case and reserved words (but you shouldn't use any of this anyway).
I query pg_catalog
instead of the information_schema
. Detailed explanation:
Blocks containing an EXCEPTION
clause like the currently accepted answer are substantially slower. This is generally simpler and faster. The documentation:
Tip: A block containing an
EXCEPTION
clause is significantly more expensive to enter and exit than a block without one. Therefore, don't useEXCEPTION
without need.
The best way to do this is define a css style:
.centered-text {
text-align:center
}
Then where ever you need centered text you add it like so:
<div class="row">
<div class="span12 centered-text">
<h1>Bootstrap starter template</h1>
<p>Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
</div>
</div>
or if you just want the p tag centered:
<div class="row">
<div class="span12 centered-text">
<h1>Bootstrap starter template</h1>
<p class="centered-text">Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
</div>
</div>
The less inline css you use the better.
How does it work if you only are using visible-md at Col4 instead? Do you use the -lg at all? If not this might work.
<div class="container">
<div class="row">
<div class="col-xs-4 col-sm-2 col-md-1" align="center">
Col1
</div>
<div class="col-xs-4 col-sm-2" align="center">
Col2
</div>
<div class="hidden-xs col-sm-6 col-md-5" align="center">
Col3
</div>
<div class="visible-md col-md-3 " align="center">
Col4
</div>
<div class="col-xs-4 col-sm-2 col-md-1" align="center">
Col5
</div>
</div>
</div>
You can use Record
for this:
https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkt
Example (A mapping between AppointmentStatus enum and some meta data):
const iconMapping: Record<AppointmentStatus, Icon> = {
[AppointmentStatus.Failed]: { Name: 'calendar times', Color: 'red' },
[AppointmentStatus.Canceled]: { Name: 'calendar times outline', Color: 'red' },
[AppointmentStatus.Confirmed]: { Name: 'calendar check outline', Color: 'green' },
[AppointmentStatus.Requested]: { Name: 'calendar alternate outline', Color: 'orange' },
[AppointmentStatus.None]: { Name: 'calendar outline', Color: 'blue' }
}
Now with interface as value:
interface Icon {
Name: string
Color: string
}
Usage:
const icon: SemanticIcon = iconMapping[appointment.Status]
This is where the window function row_number()
comes in handy:
SELECT s.siteName, s.siteIP, h.date
FROM sites s INNER JOIN
(select h.*, row_number() over (partition by siteName order by date desc) as seqnum
from history h
) h
ON s.siteName = h.siteName and seqnum = 1
ORDER BY s.siteName, h.date
DECLARE @String NVARCHAR(MAX);
USE Databse Name;
SELECT @String
=
(
SELECT 'ALTER INDEX [' + dbindexes.[name] + '] ON [' + db.name + '].[' + dbschemas.[name] + '].[' + dbtables.[name]
+ '] REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = PAGE);' + CHAR(10) AS [text()]
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
INNER JOIN sys.tables dbtables
ON dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas
ON dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes
ON dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
INNER JOIN sys.databases AS db
ON db.database_id = indexstats.database_id
WHERE dbindexes.name IS NOT NULL
AND indexstats.database_id = DB_ID()
AND indexstats.avg_fragmentation_in_percent >= 10
ORDER BY indexstats.page_count DESC
FOR XML PATH('')
);
EXEC (@String);
The easiest way I have found to use two different background images in one div is with this line of code:
body {
background:url(image1.png) repeat-x, url(image2.png) repeat;
}
Obviously, that does not have to be for only the body of the website, you can use that for any div you want.
Hope that helps! There is a post on my blog that talks about this a little more in depth if anyone needs further instructions or help - http://blog.thelibzter.com/css-tricks-use-two-background-images-for-one-div.
Remove "strictNullChecks": true from "compilerOptions" or set it to false in the tsconfig.json file of your Ng app. These errors will go away like anything and your app would compile successfully.
Disclaimer: This is just a workaround. This error appears only when the null checks are not handled properly which in any case is not a good way to get things done.
I prefer not to put source/Javadoc download settings into the project pom.xml
file as I feel these are user preferences, not project properties. Instead, I place them in a profile in my settings.xml
file:
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<profiles>
<profile>
<id>sources-and-javadocs</id>
<properties>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</properties>
</profile>
</profiles>
<activeProfiles>
<activeProfile>sources-and-javadocs</activeProfile>
</activeProfiles>
</settings>
First of all you need to remove the data-toggle attribute. We will use some JQuery, so make sure you include it.
<ul class='nav nav-tabs'>
<li class='active'><a href='#home'>Home</a></li>
<li><a href='#menu1'>Menu 1</a></li>
<li><a href='#menu2'>Menu 2</a></li>
<li><a href='#menu3'>Menu 3</a></li>
</ul>
<div class='tab-content'>
<div id='home' class='tab-pane fade in active'>
<h3>HOME</h3>
<div id='menu1' class='tab-pane fade'>
<h3>Menu 1</h3>
</div>
<div id='menu2' class='tab-pane fade'>
<h3>Menu 2</h3>
</div>
<div id='menu3' class='tab-pane fade'>
<h3>Menu 3</h3>
</div>
</div>
</div>
<script>
$(document).ready(function(){
// Handling data-toggle manually
$('.nav-tabs a').click(function(){
$(this).tab('show');
});
// The on tab shown event
$('.nav-tabs a').on('shown.bs.tab', function (e) {
alert('Hello from the other siiiiiide!');
var current_tab = e.target;
var previous_tab = e.relatedTarget;
});
});
</script>
Direct download:
Go to the project repository from the dashboard of bitbucket. Select downloads from the left menu. Choose Download repository.
Same issue on Windows 10 64 Bit, running Git Bash version 2.9.0.windows1 Using Atom as my editor.
This worked for me: I added the Git software folder (for me, this was C:\Program Files\Git) to the exclusions for Windows Defender.
After the exclusion was added, git checkout 'file'
worked fine.
if you want to use str
outside looop also; declare it outside. otherwise, 2nd version is fine.
The Angular microsyntax lets you configure a directive in a compact, friendly string. The microsyntax parser translates that string into attributes on the <ng-template>
. The let keyword declares a template input variable that you reference within the template.
Here, Erik explains every way pass an array by reference: https://stackoverflow.com/a/5724184/5090928.
Similarly, you can create an array reference variable like so:
int arr1[] = {1, 2, 3, 4, 5};
int(&arr2)[5] = arr1;
You say in a comment you want to get "15.09.2016".
For this, use Date
and DateFormatter
:
let date = Date()
let formatter = DateFormatter()
Give the format you want to the formatter:
formatter.dateFormat = "dd.MM.yyyy"
Get the result string:
let result = formatter.string(from: date)
Set your label:
label.text = result
Result:
15.09.2016
I've used the inputParser
object to deal with setting default options. Matlab won't accept the python-like format you specified in the question, but you should be able to call the function like this:
wave(a,b,n,k,T,f,flag,'fTrue',inline('0'))
After you define the wave
function like this:
function wave(a,b,n,k,T,f,flag,varargin)
i_p = inputParser;
i_p.FunctionName = 'WAVE';
i_p.addRequired('a',@isnumeric);
i_p.addRequired('b',@isnumeric);
i_p.addRequired('n',@isnumeric);
i_p.addRequired('k',@isnumeric);
i_p.addRequired('T',@isnumeric);
i_p.addRequired('f',@isnumeric);
i_p.addRequired('flag',@isnumeric);
i_p.addOptional('ftrue',inline('0'),1);
i_p.parse(a,b,n,k,T,f,flag,varargin{:});
Now the values passed into the function are available through i_p.Results
. Also, I wasn't sure how to validate that the parameter passed in for ftrue
was actually an inline
function so left the validator blank.
cd /driveName driveName:\pathNamw
Have you tried GoogleMap.getMyLocation()
?
I have used both JXL (now "JExcel") and Apache POI. At first I used JXL, but now I use Apache POI.
First, here are the things where both APIs have the same end functionality:
However, there are many differences:
Additionally, POI contains not just the main "usermodel" API, but also an event-based API if all you want to do is read the spreadsheet content.
In conclusion, because of the better documentation, more features, active development, and Excel 2007+ format support, I use Apache POI.
Here is the detailed answer to the question:
Pass data into the HTTP header from the Angular side (Please note I am using Angular4.0+ in the application).
There is more than one way we can pass data into the headers. The syntax is different but all means the same.
// Option 1
const httpOptions = {
headers: new HttpHeaders({
'Authorization': 'my-auth-token',
'ID': emp.UserID,
})
};
// Option 2
let httpHeaders = new HttpHeaders();
httpHeaders = httpHeaders.append('Authorization', 'my-auth-token');
httpHeaders = httpHeaders.append('ID', '001');
httpHeaders.set('Content-Type', 'application/json');
let options = {headers:httpHeaders};
// Option 1
return this.http.post(this.url + 'testMethod', body,httpOptions)
// Option 2
return this.http.post(this.url + 'testMethod', body,options)
In the call you can find the field passed as a header as shown in the image below :
Still, if you are facing the issues like.. (You may need to change the backend/WebAPI side)
Response to preflight request doesn't pass access control check: No ''Access-Control-Allow-Origin'' header is present on the requested resource. Origin ''http://localhost:4200'' is therefore not allowed access
Response for preflight does not have HTTP ok status.
Find my detailed answer at https://stackoverflow.com/a/52620468/3454221
\r
= CR (Carriage Return) → Used as a new line character in Mac OS before X\n
= LF (Line Feed) → Used as a new line character in Unix/Mac OS X\r\n
= CR + LF → Used as a new line character in WindowsTry format
function:
> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"
I tried Fiddler with its reverse proxy ability which is mentioned by @marxidad and it seems to be working fine, since Fiddler is a familiar UI for me and has the ability to show request/responses in various formats (i.e. Raw, XML, Hex), I accept it as an answer to this question. One thing though. I use WCF and I got the following exception with reverse proxy thing:
The message with To 'http://localhost:8000/path/to/service' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's EndpointAddresses agree
I have figured out (thanks Google, erm.. I mean Live Search :p) that this is because my endpoint addresses on server and client differs by port number. If you get the same exception consult to the following MSDN forum message:
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2302537&SiteID=1
which recommends to use clientVia Endpoint Behavior explained in following MSDN article:
The event generated is bubbling up until it is handled.
This xaml portion below triggers ui_Tab_Changed
after ui_A_Changed
when the item selected in the ListView
changes, regardless of TabItem
change in the TabControl
.
<TabControl SelectionChanged="ui_Tab_Changed">
<TabItem>
<ListView SelectionChanged="ui_A_Changed" />
</TabItem>
<TabItem>
<ListView SelectionChanged="ui_B_Changed" />
</TabItem>
</TabControl>
We need to consume the event in ui_A_Changed
(and ui_B_Changed
, and so on):
private void ui_A_Changed(object sender, SelectionChangedEventArgs e) {
// do what you need to do
...
// then consume the event
e.Handled = true;
}
I had faced this problem today while setting up ssh between name node and data node in fully distributed mode between two VMs in CentOS.
The problem was faced because I ran the below command from data node instead of name node ssh-copy-id -i /home/hduser/.ssh/id_ras.pub hduser@HadoopBox2
Since the public key file did not exist in data node it threw the error.
This is the code that works for me to create a sticky thead on a table with a scrollable tbody:
table ,tr td{
border:1px solid red
}
tbody {
display:block;
height:50px;
overflow:auto;
}
thead, tbody tr {
display:table;
width:100%;
table-layout:fixed;/* even columns width , fix width of table too*/
}
thead {
width: calc( 100% - 1em )/* scrollbar is average 1em/16px width, remove it from thead width */
}
table {
width:400px;
}
success
only fires if the AJAX call is successful, i.e. ultimately returns a HTTP 200 status. error
fires if it fails and complete
when the request finishes, regardless of success.
In jQuery 1.8 on the jqXHR
object (returned by $.ajax
) success
was replaced with done
, error
with fail
and complete
with always
.
However you should still be able to initialise the AJAX request with the old syntax. So these do similar things:
// set success action before making the request
$.ajax({
url: '...',
success: function(){
alert('AJAX successful');
}
});
// set success action just after starting the request
var jqxhr = $.ajax( "..." )
.done(function() { alert("success"); });
This change is for compatibility with jQuery 1.5's deferred object. Deferred (and now Promise
, which has full native browser support in Chrome and FX) allow you to chain asynchronous actions:
$.ajax("parent").
done(function(p) { return $.ajax("child/" + p.id); }).
done(someOtherDeferredFunction).
done(function(c) { alert("success: " + c.name); });
This chain of functions is easier to maintain than a nested pyramid of callbacks you get with success
.
However, please note that done
is now deprecated in favour of the Promise
syntax that uses then
instead:
$.ajax("parent").
then(function(p) { return $.ajax("child/" + p.id); }).
then(someOtherDeferredFunction).
then(function(c) { alert("success: " + c.name); }).
catch(function(err) { alert("error: " + err.message); });
This is worth adopting because async
and await
extend promises improved syntax (and error handling):
try {
var p = await $.ajax("parent");
var x = await $.ajax("child/" + p.id);
var c = await someOtherDeferredFunction(x);
alert("success: " + c.name);
}
catch(err) {
alert("error: " + err.message);
}
If you use MyISAM tables, then you can recover any data you deleted, just
open file: mysql/data/[your_db]/[your_table].MYD
with any text editor
Its not right to set default value in View. The View should perform display work, not more. This action breaks ideology of MVC pattern. So the right place to set defaults - create method of controller class.
From the documentation page
To set the page type pass the value in constructor
jsPDF(orientation, unit, format)
Creates new jsPDF document objectinstance Parameters:
orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")
unit Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"
format One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal'
To set font size
setFontSize(size)
Sets font size for upcoming text elements.
Parameters:
{Number} size Font size in points.
Just in case it helps someone, here's what caused this error for me: I needed a procedure to return json but I left out the for json path:
set @jsonout = (SELECT ID, SumLev, Census_GEOID, AreaName, Worksite
from CS_GEO G (nolock)
join @allids a on g.ID = a.[value]
where g.Worksite = @worksite)
When I tried to save the stored procedure, it threw the error. I fixed it by adding for json path to the code at the end of the procedure:
set @jsonout = (SELECT ID, SumLev, Census_GEOID, AreaName, Worksite
from CS_GEO G (nolock)
join @allids a on g.ID = a.[value]
where g.Worksite = @worksite for json path)
if object_id('FUNCTION_NAME') is not NULL
DROP FUNCTION <name>
You can also look the name up in sysobjects
IF EXISTS (SELECT *
FROM sysobjects
WHERE name='<function name>' and xtype='FN'
Actually, if the function could be a table function, you need to use
xtype in ('FN','TF')
You can use Directory.GetFiles to replace your method.
Directory.GetFiles(dirPath, "*", SearchOption.AllDirectories)
If you would like to combine the matrix with some visualisations I can recommend (I am using the built in iris
dataset):
library(psych)
pairs.panels(iris[1:4]) # select columns 1-4
The Performance Analytics basically does the same but includes significance indicators by default.
library(PerformanceAnalytics)
chart.Correlation(iris[1:4])
Or this nice and simple visualisation:
library(corrplot)
x <- cor(iris[1:4])
corrplot(x, type="upper", order="hclust")
If you are like me whose Java Control Panel does not show Security slider under Security Tab to change security level from High to Medium then follow these instructions: Java known bug: security slider not visible.
After installation, the checkbox to enable/disable Java and the security level slider do not appear in the Java Control Panel Security tab. This can occur with 7u10 and above.
This is due to a conflict that Java 7u10 and above have with standalone installations of JavaFX. Example: If Java 7u5 and JavaFX 2.1.1 are installed and if Java is updated to 7u11, the Java Control Panel does not show the checkbox or security slider.
It is recommended to uninstall all versions of Java and JavaFX before installing Java 7u10 and above.
Please follow the steps below for resolving this issue.
1. Remove all versions of Java and JavaFX through the Windows Uninstall Control Panel. Instructions on uninstalling Java.
2. Run the Microsoft uninstall utility to repair corrupted registry keys that prevents programs from being completely uninstalled or blocking new installations and updates.
3. Download and install the Windows offline installer package.
Remove last comma. Working example
function truncateText() {_x000D_
var str= document.getElementById('input').value;_x000D_
str = str.replace(/,\s*$/, "");_x000D_
console.log(str);_x000D_
}
_x000D_
<input id="input" value="address line one,"/>_x000D_
<button onclick="truncateText()">Truncate</button>
_x000D_
python
Here is a pure python method for simple strings, left here for posterity.
def string2bits(s=''):
return [bin(ord(x))[2:].zfill(8) for x in s]
def bits2string(b=None):
return ''.join([chr(int(x, 2)) for x in b])
s = 'Hello, World!'
b = string2bits(s)
s2 = bits2string(b)
print 'String:'
print s
print '\nList of Bits:'
for x in b:
print x
print '\nString:'
print s2
String:
Hello, World!
List of Bits:
01001000
01100101
01101100
01101100
01101111
00101100
00100000
01010111
01101111
01110010
01101100
01100100
00100001
String:
Hello, World!
You don't need to use arrays.
JSON values can be arrays, objects, or primitives (numbers or strings).
You can write JSON like this:
{
"stuff": {
"onetype": [
{"id":1,"name":"John Doe"},
{"id":2,"name":"Don Joeh"}
],
"othertype": {"id":2,"company":"ACME"}
},
"otherstuff": {
"thing": [[1,42],[2,2]]
}
}
You can use it like this:
obj.stuff.onetype[0].id
obj.stuff.othertype.id
obj.otherstuff.thing[0][1] //thing is a nested array or a 2-by-2 matrix.
//I'm not sure whether you intended to do that.
<
one-way binding
=
two-way binding
&
function binding
@
pass only strings
The short answer is "yes". A sample ldapsearch
command to query an Active Directory server is:
ldapsearch \
-x -h ldapserver.mydomain.com \
-D "[email protected]" \
-W \
-b "cn=users,dc=mydomain,dc=com" \
-s sub "(cn=*)" cn mail sn
This would connect to an AD server at hostname ldapserver.mydomain.com
as user [email protected]
, prompt for the password on the command line and show name and email details for users in the cn=users,dc=mydomain,dc=com
subtree.
See Managing LDAP from the Command Line on Linux for more samples. See LDAP Query Basics for Microsoft Exchange documentation for samples using LDAP queries with Active Directory.
I have faced same issue and sorted using below step.
C:\xampp\mysql\bin\my.ini
)innodb_data_file_path = ibdata1:10M:autoextend
ibdata1
file exist under C:/xampp/mysql/data/
ibdata1
file from location C:\xampp\mysql\backup\ibdata1
hope it helps to someone.
For me Visual Studio had created a projectname.v11 of type "Visual Studio Solution User Options". I deleted this file and restarted and everything was fine.
No need to start, it would automatically executed while you startup your mac terminal / bash. Whenever you do a change, you may need to restart the terminal.
~ is the default path for .bash_profile
Just to answer the add()
vs offer()
question (since the other one is perfectly answered imo, and this might not be):
According to JavaDoc on interface Queue, "The offer method inserts an element if possible, otherwise returning false. This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or "bounded") queues."
That means if you can add the element (which should always be the case in a PriorityQueue), they work exactly the same. But if you can't add the element, offer()
will give you a nice and pretty false
return, while add()
throws a nasty unchecked exception that you don't want in your code. If failure to add means code is working as intended and/or it is something you'll check normally, use offer()
. If failure to add means something is broken, use add()
and handle the resulting exception thrown according to the Collection interface's specifications.
They are both implemented this way to fullfill the contract on the Queue interface that specifies offer()
fails by returning a false
(method preferred in capacity-restricted queues) and also maintain the contract on the Collection interface that specifies add()
always fails by throwing an exception.
Anyway, hope that clarifies at least that part of the question.
I recommend that you use jQuery for this, as it makes the process much easier. Here are some examples using jQuery:
$("div#id").append('<a href="' + url + '">' + text + '</a>');
If you need a list though, as in a <ul>
, you can do this:
$("div#id").append('<ul>');
var ul = $("div#id > ul");
ul.append('<li><a href="' + url + '">' + text + '</a></li>');
Use one way flow syntax property binding:
<div [innerHTML]="comment"></div>
From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script>
tag but keeps safe content such as the <b>
element."
I would do:
select DBMS_CRYPTO.HASH(rawtohex('foo') ,2) from dual;
output:
DBMS_CRYPTO.HASH(RAWTOHEX('FOO'),2)
--------------------------------------------------------------------------------
ACBD18DB4CC2F85CEDEF654FCCC4A4D8
OK, I am a Ruby noob, but I did get this fixed slightly differently than the answers here, so hopefully this helps someone else (tl;dr: I used RVM to switch the system Ruby version to the same one expected by rubygems).
First off, listing all Rubies as mentioned by Eimantas was a great starting point:
> which -a ruby
/opt/local/bin/ruby
/Users/Brian/.rvm/rubies/ruby-1.9.2-p290/bin/ruby
/Users/Brian/.rvm/bin/ruby
/usr/bin/ruby
/opt/local/bin/ruby
The default Ruby instance in use by the system appeared to be 1.8.7:
> ruby -v
ruby 1.8.7 (2010-06-23 patchlevel 299) [i686-darwin10]
while the version in use by Rubygems was the 1.9.2 version managed by RVM:
> gem env | grep 'RUBY EXECUTABLE'
- RUBY EXECUTABLE: /Users/Brian/.rvm/rubies/ruby-1.9.2-p290/bin/ruby
So that was definitely the issue. I don't actively use Ruby myself (this is simply a dependency of a build system script I'm trying to run) so I didn't care which version was active for other purposes. Since rubygems expected the 1.9.2 that was already managed by RVM, I simply used RVM to switch the system to use the 1.9.2 version as the default:
> rvm use 1.9.2
Using /Users/Brian/.rvm/gems/ruby-1.9.2-p290
> ruby -v
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin11.3.0]
After doing that my "no such file" issue went away and my script started working.
I think you can use SeriesGroupBy.nunique
:
print (df.groupby('param')['group'].nunique())
param
a 2
b 1
Name: group, dtype: int64
Another solution with unique
, then create new df
by DataFrame.from_records
, reshape to Series
by stack
and last value_counts
:
a = df[df.param.notnull()].groupby('group')['param'].unique()
print (pd.DataFrame.from_records(a.values.tolist()).stack().value_counts())
a 2
b 1
dtype: int64
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());
}
);
}
How does @Autowired
work internally?
Example:
class EnglishGreeting {
private Greeting greeting;
//setter and getter
}
class Greeting {
private String message;
//setter and getter
}
.xml file it will look alike if not using @Autowired
:
<bean id="englishGreeting" class="com.bean.EnglishGreeting">
<property name="greeting" ref="greeting"/>
</bean>
<bean id="greeting" class="com.bean.Greeting">
<property name="message" value="Hello World"/>
</bean>
If you are using @Autowired
then:
class EnglishGreeting {
@Autowired //so automatically based on the name it will identify the bean and inject.
private Greeting greeting;
//setter and getter
}
.xml file it will look alike if not using @Autowired
:
<bean id="englishGreeting" class="com.bean.EnglishGreeting"></bean>
<bean id="greeting" class="com.bean.Greeting">
<property name="message" value="Hello World"/>
</bean>
If still have some doubt then go through below live demo
my good friend Alessandro have a nice post regarding bit operators in C#, you should read about it so you know what to do.
It's pretty easy. If you break down the IP given to you to binary, the network address is the ip address where all of the host bits (the 0's in the subnet mask) are 0,and the last address, the broadcast address, is where all the host bits are 1.
For example:
ip 192.168.33.72 mask 255.255.255.192
11111111.11111111.11111111.11000000 (subnet mask)
11000000.10101000.00100001.01001000 (ip address)
The bolded parts is the HOST bits (the rest are network bits). If you turn all the host bits to 0 on the IP, you get the first possible IP:
11000000.10101000.00100001.01000000 (192.168.33.64)
If you turn all the host bits to 1's, then you get the last possible IP (aka the broadcast address):
11000000.10101000.00100001.01111111 (192.168.33.127)
So for my example:
the network is "192.168.33.64/26":
Network address: 192.168.33.64
First usable: 192.168.33.65 (you can use the network address, but generally this is considered bad practice)
Last useable: 192.168.33.126
Broadcast address: 192.168.33.127
In this case , this code
{<td><span onClick={this.toggle()}>Details</span></td>}
causes toggle function to call immediately and re render it again and again thus making infinite calls.
so passing only the reference to that toggle method will solve the problem.
so ,
{<td><span onClick={this.toggle}>Details</span></td>}
will be the solution code.
If you want to use the () , you should use an arrow function like this
{<td><span onClick={()=> this.toggle()}>Details</span></td>}
In case you want to pass parameters you should choose the last option and you can pass parameters like this
{<td><span onClick={(arg)=>this.toggle(arg)}>Details</span></td>}
In the last case it doesn't call immediately and don't cause the re render of the function, hence avoiding infinite calls.
add this code to your ApplicationController
def reset_session
@_request.reset_session
end
( Dont know why no one above just mention this code as it fixed my problem ) http://apidock.com/rails/ActionController/RackDelegation/reset_session
Use CharField
for phone field in the model and the localflavor
app for form validation:
The best solution is to create a new branch with --orphan
option as shown below
git checkout --orphan <branch name>
By this you will be able to create a new branch and directly checkout to the new branch. It will be a parentless branch.
By default the --orphan
option doesn't remove the files in the working directory, so you can delete the working directory files by this:
git rm --cached -r
--orphan
does:
--orphan <new_branch>
Create a new orphan branch, named<new_branch>
, started from<start_point>
and switch to it. The first commit made on this new branch will have no parents and it will be the root of a new history totally disconnected from all the other branches and commits.
The index and the working tree are adjusted as if you had previously run git checkout <start_point>. This allows you to start a new history that records a set of paths similar to <start_point> by easily running git commit -a to make the root commit.
This can be useful when you want to publish the tree from a commit without exposing its full history. You might want to do this to publish an open source branch of a project whose current tree is "clean", but whose full history contains proprietary or otherwise encumbered bits of code.
If you want to start a disconnected history that records a set of paths that is totally different from the one of <start_point>, then you should clear the index and the working tree right after creating the orphan branch by running git rm -rf . from the top level of the working tree. Afterwards you will be ready to prepare your new files, repopulating the working tree, by copying them from elsewhere, extracting a tarball, etc.
Other way is with:
np.vectorize(lambda x: 6 <= x <= 10)(a)
which returns:
array([False, False, False, True, True, True, False, False, False])
It is sometimes useful for masking time series, vectors, etc.
Use SSIS to extract and process the information. That way you will have the processing of the XML files separated from SQL Server. You can also do the SSIS transformations on a separate server if needed. Store the phone numbers in a standard format using VARCHAR. NVARCHAR would be unnecessary since we are talking about numbers and maybe a couple of other chars, like '+', ' ', '(', ')' and '-'.
If you want to get the last day of the current month you can do it with the following code.
$last_day_this_month = date('F jS Y', strtotime(date('F t Y')));
Toastr is a very nice component, and you can show messages with theses commands:
// for success - green box
toastr.success('Success messages');
// for errors - red box
toastr.error('errors messages');
// for warning - orange box
toastr.warning('warning messages');
// for info - blue box
toastr.info('info messages');
If you want to provide a title on the toastr message, just add a second argument:
// for info - blue box
toastr.success('The process has been saved.', 'Success');
you also can change the default behaviour using something like this:
toastr.options.timeOut = 3000; // 3s
See more on the github of the project.
A sample of use:
$(document).ready(function() {
// show when page load
toastr.info('Page Loaded!');
$('#linkButton').click(function() {
// show when the button is clicked
toastr.success('Click Button');
});
});
and a html:
<a id='linkButton'>Show Message</a>
$("#mycheckbox")[0].checked = true;
$("#mycheckbox").attr('checked', true);
$("#mycheckbox").click();
The last one will fire the click event for the checkbox, the others will not. So if you have custom code in the onclick event for the checkbox that you want to fire, use the last one.
It's a double-edged sword. It is sometimes very useful, but often dangerous.
When is it good? When you want 10 cases all processed the same way...
switch (c) {
case 1:
case 2:
... Do some of the work ...
/* FALLTHROUGH */
case 17:
... Do something ...
break;
case 5:
case 43:
... Do something else ...
break;
}
The one rule I like is that if you ever do anything fancy where you exclude the break, you need a clear comment /* FALLTHROUGH */ to indicate that was your intention.
You can see in this List of useful HTTP headers.
X-XSS-Protection: This header enables the Cross-site scripting (XSS) filter built into most recent web browsers. It's usually enabled by default anyway, so the role of this header is to re-enable the filter for this particular website if it was disabled by the user. This header is supported in IE 8+, and in Chrome (not sure which versions). The anti-XSS filter was added in Chrome 4. Its unknown if that version honored this header.
You are out of luck, I think. THe problem is not a SQL level problem as all other answers seem to focus on, but simply one of the user interface. Management Studio is not meant to be a general purpose / generic data access interface. It is not there to be your interface, but your administrative area, and it has serious limitations handling binary data and large test data - because people using it within the specified usage profile will not run into this problem.
Presenting large text data is simply not the planned usage.
Your only choice would be a table valued function that takes the text input and cuts it rows for every line, so that Management Studio gets a list of rows, not a single row.
Another approach I would try is by using #map
clients.map{ |key, _| key if clients[key] == {"client_id"=>"2180"} }.compact
#=> ["orange"]
This will return all occurences of given value. The underscore means that we don't need key's value to be carried around so that way it's not being assigned to a variable. The array will contain nils if the values doesn't match - that's why I put #compact
at the end.
Yes: simply press and hold the Alt key, click and drag to select the lines whose columns you wish to edit, and begin typing.
You can also go to Settings > Preferences..., and in the Editing tab, turn on multi-editing, to enable selection of multiple separate regions or columns of text to edit at once.
It's much more intuitive, as you can see your edits live as you type.
<div id="one">first text for one</div>_x000D_
<div id="one">second text for one</div>_x000D_
_x000D_
var ids = document.getElementById('one');
_x000D_
ids contain only first div element. So even if there are multiple elements with the same id, the document object will return only first match.
From my HomeController I want to call this Method and convert Json response to List
No you don't. You really don't want to add the overhead of an HTTP call and (de)serialization when the code is within reach. It's even in the same assembly!
Your ApiController goes against (my preferred) convention anyway. Let it return a concrete type:
public IEnumerable<QDocumentRecord> GetAllRecords()
{
listOfFiles = ...
return listOfFiles;
}
If you don't want that and you're absolutely sure you need to return HttpResponseMessage
, then still there's absolutely no need to bother with calling JsonConvert.SerializeObject()
yourself:
return Request.CreateResponse<List<QDocumentRecord>>(HttpStatusCode.OK, listOfFiles);
Then again, you don't want business logic in a controller, so you extract that into a class that does the work for you:
public class FileListGetter
{
public IEnumerable<QDocumentRecord> GetAllRecords()
{
listOfFiles = ...
return listOfFiles;
}
}
Either way, then you can call this class or the ApiController directly from your MVC controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var listOfFiles = new DocumentsController().GetAllRecords();
// OR
var listOfFiles = new FileListGetter().GetAllRecords();
return View(listOfFiles);
}
}
But if you really, really must do an HTTP request, you can use HttpWebRequest
, WebClient
, HttpClient
or RestSharp
, for all of which plenty of tutorials exist.
try this:
but.onclick = callJavascriptFunction;
or create the button by wrapping it with another element and use innerHTML:
var span = document.createElement('span');
span.innerHTML = '<button id="but' + inc +'" onclick="callJavascriptFunction()" />';
IF you want to derive usg Boolean true False need to add "[]" around value
<form [formGroup]="form">
<input type="radio" [value]=true formControlName="gender" >Male
<input type="radio" [value]=false formControlName="gender">Female
</form>
The only code that have worked for me:
childFrame.setAlwaysOnTop(true);
This code should be called on the main/parent frame before making the child/modal frame visible. Your child/modal frame should also have this code:
parentFrame.setFocusableWindowState(false);
this.mainFrame.setEnabled(false);
you pretty much answered your own question - hashset doesn't allow duplicate values. it would be trivial to build a hashset using a backing hashmap (and just a check to see if the value already exists). i guess the various java implementations either do that, or implement some custom code to do it more efficiently.
Although ANSI C does not have this mechanism, it is possible to use itoa() as a shortcut:
char buffer [33];
itoa (i,buffer,2);
printf ("binary: %s\n",buffer);
Here's the origin:
It is non-standard C, but K&R mentioned the implementation in the C book, so it should be quite common. It should be in stdlib.h.
You can format containers as well as ranges and tuples using the {fmt} library. For example:
#include <vector>
#include <fmt/ranges.h>
int main() {
std::vector<char> path;
for (int c = 'a'; c <= 'z'; ++c)
path.push_back(c);
fmt::print("{}", path);
}
prints
{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}
to stdout
(godbolt).
Alternatively you can iterate over the elements and print them individually.
Disclaimer: I'm the author of {fmt}.
Extra Tips:
Multiple "nots", input that is NOT hidden and NOT disabled:
:not([type="hidden"]):not([disabled])
Also did you know you can do this:
node.parentNode.querySelectorAll('div');
This is equivelent to jQuery's:
$(node).parent().find('div');
Which will effectively find all divs in "node" and below recursively, HOT DAMN!
IF
is a PL/SQL construct. If you are executing a query, you are using SQL not PL/SQL.
In SQL, you can use a CASE
statement in the query itself
SELECT DISTINCT a.item,
(CASE WHEN b.salesman = 'VIKKIE'
THEN 'ICKY'
ELSE b.salesman
END),
NVL(a.manufacturer,'Not Set') Manufacturer
FROM inv_items a,
arv_sales b
WHERE a.co = '100'
AND a.co = b.co
AND A.ITEM_KEY = b.item_key
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
and to_date('011713','mmddrr')
ORDER BY a.item
Since you aren't doing any aggregation, you don't want a GROUP BY
in your query. Are you really sure that you need the DISTINCT
? People often throw that in haphazardly or add it when they are missing a join condition rather than considering whether it is really necessary to do the extra work to identify and remove duplicates.
I don't know if Boost has more specific functions, but you can do it with the standard library.
Given std::vector<double> v
, this is the naive way:
#include <numeric>
double sum = std::accumulate(v.begin(), v.end(), 0.0);
double mean = sum / v.size();
double sq_sum = std::inner_product(v.begin(), v.end(), v.begin(), 0.0);
double stdev = std::sqrt(sq_sum / v.size() - mean * mean);
This is susceptible to overflow or underflow for huge or tiny values. A slightly better way to calculate the standard deviation is:
double sum = std::accumulate(v.begin(), v.end(), 0.0);
double mean = sum / v.size();
std::vector<double> diff(v.size());
std::transform(v.begin(), v.end(), diff.begin(),
std::bind2nd(std::minus<double>(), mean));
double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
double stdev = std::sqrt(sq_sum / v.size());
UPDATE for C++11:
The call to std::transform
can be written using a lambda function instead of std::minus
and std::bind2nd
(now deprecated):
std::transform(v.begin(), v.end(), diff.begin(), [mean](double x) { return x - mean; });
Using String format will help but you must be care full with the locale. In germany float will be separates with in comma instead an point.
Using String.format("geo:%f,%f",5.1,2.1);
on locale english the result will be "geo:5.1,2.1"
but with locale german you will get "geo:5,1,2,1"
You should use the English locale to prevent this behavior.
String uri = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);
To set an label to the geo point you can extend your geo uri by using:
!!! but be carefull with this the geo-uri is still under develoment http://tools.ietf.org/html/draft-mayrhofer-geo-uri-00
String uri = String.format(Locale.ENGLISH, "geo:%f,%f?z=%d&q=%f,%f (%s)",
latitude, longitude, zoom, latitude, longitude, label);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);
You can use jsdom
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { document } = (new JSDOM(`...`)).window;
or, take a look at cheerio, it may more suitable in your case.
in my experince the problem using result()
and result_array()
in my JSON
if using result()
there no problem its works but if using result_array()
i got error "Trying to get property of non-object"
so im not search into deep the problem so i just using result()
if using JSON
and using result_array()
if not using JSON
I wanted a simple example of the use of case that I could play with, this doesn't even need a table. This returns odd or even depending whether seconds is odd or even
SELECT CASE MOD(SECOND(NOW()),2) WHEN 0 THEN 'odd' WHEN 1 THEN 'even' END;
I would have thought that something like this would be much better, since you're adding a variable, so why not restrict access and make it cleaner? Your getter/setters should do what they say on the tin.
public abstract class ExternalScript extends Script {
private String source;
public void setSource(String file) {
source = file;
}
public String getSource() {
return source;
}
}
Bringing this back to the question, do you ever bother looking at where the getter/setter code is when reading it? If they all do getting and setting then you don't need to worry about what the function 'does' when reading the code. There are a few other reasons to think about too:
Always think whether your class is really a different thing or not, and that should help decide whether you need anything more.
for me, it didn't work without specifying the MIME in web.config, under <system.webServer><staticContent>
<mimeMap fileExtension=".ico" mimeType="image/ico" />
We can make class dynamic by using following syntax. In Angular 2 plus, you can do this in various ways:
[ngClass]="{'active': arrayData.length && arrayData[0]?.booleanProperty}"
[ngClass]="{'active': step}"
[ngClass]="step== 'step1'?'active':''"
[ngClass]="step? 'active' : ''"
from numpy.lib.scimath import logn
from math import e
#using: x - var
logn(e, x)
You can use this function to add an child to a DOM element.
function addElement(parentId, elementTag, elementId, html)
{
// Adds an element to the document
var p = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.setAttribute('id', elementId);
newElement.innerHTML = html;
p.appendChild(newElement);
}
function removeElement(elementId)
{
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
It sounds like something like the below will suit your needs:
With Sheets("Sheet1")
.Rows( X & ":" & .Rows.Count).Delete
End With
Where X is a variable that = the row number ( 415 )
Adding <validation validateIntegratedModeConfiguration="false"/>
addresses the symptom, but is not appropriate for all circumstances. Having ran around this issue a few times, I hope to help others not only overcome the problem but understand it. (Which becomes more and more important as IIS 6 fades into myth and rumor.)
Background:
This issue and the confusion surrounding it started with the introduction of ASP.NET 2.0 and IIS 7. IIS 6 had and continues to have only one pipeline mode, and it is equivalent to what IIS 7+ calls "Classic" mode. The second, newer, and recommended pipeline mode for all applications running on IIS 7+ is called "Integrated" mode.
So, what's the difference? The key difference is how ASP.NET interacts with IIS.
Classic mode is limited to an ASP.NET pipeline that cannot interact with the IIS pipeline. Essentially a request comes in and if IIS 6/Classic has been told, through server configuration, that ASP.NET can handle it then IIS hands off the request to ASP.NET and moves on. The significance of this can be gleaned from an example. If I were to authorize access to static image files, I would not be able to do it with an ASP.NET module because the IIS 6 pipeline will handle those requests itself and ASP.NET will never see those requests because they were never handed off.* On the other hand, authorizing which users can access a .ASPX page such as a request for Foo.aspx is trivial even in IIS 6/Classic because IIS always hands those requests off to the ASP.NET pipeline. In Classic mode ASP.NET does not know what it hasn't been told and there is a lot that IIS 6/Classic may not be telling it.
Integrated mode is recommended because ASP.NET handlers and modules can interact directly with the IIS pipeline. No longer does the IIS pipeline simply hand off the request to the ASP.NET pipeline, now it allows ASP.NET code to hook directly into the IIS pipeline and all the requests that hit it. This means that an ASP.NET module can not only observe requests to static image files, but can intercept those requests and take action by denying access, logging the request, etc.
Overcoming the error:
Then again maybe you are giving your application a face-lift or it was chugging along just fine until you installed a 3rd party library via NuGet, manually, or by some other means. In that case it is entirely possible httpHandlers
or httpModules
have been added to system.web
. The outcome is the error that you are seeing because validateIntegratedModeConfiguration
defaults true
. Now you have two choices:
httpHandlers
and httpModules
elements from system.web
. There are a couple possible outcomes from this:
httpHandlers
and httpModules
that NuGet packages keep adding to system.web
, hey do what you need to.validateIntegratedModeConfiguration
to false
, but at least you know what you're doing and why it matters.Good reads:
*Of course there are ways to get all kind of strange things into the ASP.NET pipeline from IIS 6/Classic via incantations like wildcard mappings, if you like that sort of thing.
Although MSDN says that "s" and "o" formats reflect the standard, they seem to be able to parse only a limited subset of it. Especially it is a problem if the string contains time zone specification. (Neither it does for basic ISO8601 formats, or reduced precision formats - however this is not exactly your case.) That is why I make use of custom format strings when it comes to parsing ISO8601. Currently my preferred snippet is:
static readonly string[] formats = {
// Basic formats
"yyyyMMddTHHmmsszzz",
"yyyyMMddTHHmmsszz",
"yyyyMMddTHHmmssZ",
// Extended formats
"yyyy-MM-ddTHH:mm:sszzz",
"yyyy-MM-ddTHH:mm:sszz",
"yyyy-MM-ddTHH:mm:ssZ",
// All of the above with reduced accuracy
"yyyyMMddTHHmmzzz",
"yyyyMMddTHHmmzz",
"yyyyMMddTHHmmZ",
"yyyy-MM-ddTHH:mmzzz",
"yyyy-MM-ddTHH:mmzz",
"yyyy-MM-ddTHH:mmZ",
// Accuracy reduced to hours
"yyyyMMddTHHzzz",
"yyyyMMddTHHzz",
"yyyyMMddTHHZ",
"yyyy-MM-ddTHHzzz",
"yyyy-MM-ddTHHzz",
"yyyy-MM-ddTHHZ"
};
public static DateTime ParseISO8601String ( string str )
{
return DateTime.ParseExact ( str, formats,
CultureInfo.InvariantCulture, DateTimeStyles.None );
}
If you don't mind parsing TZ-less strings (I do), you can add an "s" line to greatly extend the number of covered format alterations.
It seems that you catch not the exception you wanna catch out there :)
if the s
is a socket.socket()
object, then the right way to call .connect
would be:
import socket
s = socket.socket()
address = '127.0.0.1'
port = 80 # port number is a number, not string
try:
s.connect((address, port))
# originally, it was
# except Exception, e:
# but this syntax is not supported anymore.
except Exception as e:
print("something's wrong with %s:%d. Exception is %s" % (address, port, e))
finally:
s.close()
Always try to see what kind of exception is what you're catching in a try-except loop.
You can check what types of exceptions in a socket module represent what kind of errors (timeout, unable to resolve address, etc) and make separate except
statement for each one of them - this way you'll be able to react differently for different kind of problems.
The accepted answer of this post will cause error in the case when the string length is lest than 5. So i have a better solution. We can use this simple code :
If(str.Length <= 5, str, str.Substring(str.Length - 5))
You can test it with variable length string.
Dim str, result As String
str = "11!"
result = If(str.Length <= 5, str, str.Substring(str.Length - 5))
MessageBox.Show(result)
str = "I will be going to school in 2011!"
result = If(str.Length <= 5, str, str.Substring(str.Length - 5))
MessageBox.Show(result)
Another simple but efficient solution i found :
str.Substring(str.Length - Math.Min(5, str.Length))
you can do:
A = randi(10, [3 4]); %# a random matrix
any( A(:)==5 ) %# does A contain 5?
To do the above in a vectorized way, use:
any( bsxfun(@eq, A(:), [5 7 11] )
or as @woodchips suggests:
ismember([5 7 11], A)
For changing application name only (that will display along with app icon) in xcode 4 or later:
Click on your project file icon from Groups & Files panel, choose Target -> Build Settings -> Packaging -> Product Name. Click on the row, a pop-up will come, type your new app name here.
For changing Project name only (that will display along with project icon) in xcode 4 or later:
Click on your project file icon from Groups & Files panel, choose Project(above targets) from right pane, just see at the far right pane(it will be visible only if you have enabled "Hide or show utilities").Look for project name.Edit it to new name you want to give your project.
Delete your app from simulator/device, clean and run.Changes should reflect.
That's it
Style the td
and th
instead
td, th {
border: 1px solid black;
}
And also to make it so there is no spacing between cells use:
table {
border-collapse: collapse;
}
(also note, you have border-style: none;
which should be border-style: solid;
)
See an example here: http://jsfiddle.net/KbjNr/
Here are tests for a few methods:
%timeit np.where(np.isnan(df['b']))[0]
%timeit pd.isnull(df['b']).nonzero()[0]
%timeit np.where(df['b'].isna())[0]
%timeit df.loc[pd.isna(df['b']), :].index
And their corresponding timings:
333 µs ± 9.95 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
280 µs ± 220 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
313 µs ± 128 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
6.84 ms ± 1.59 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
It would appear that pd.isnull(df['DRGWeight']).nonzero()[0]
wins the day in terms of timing, but that any of the top three methods have comparable performance.
For me, it was happening because I had switched over to "Run as Administrator". Just one instance of VS was running, but running it as admin threw this error. Switching back fixed me right up.
You could set the width of the abbrev column to a fixed pixel width, then set the width of the description column to the width of the DataGridView, minus the sum of the widths of the other columns and some extra margin (if you want to prevent a horizontal scrollbar from appearing on the DataGridView):
dataGridView1.Columns[1].Width = 108; // or whatever width works well for abbrev
dataGridView1.Columns[2].Width =
dataGridView1.Width
- dataGridView1.Columns[0].Width
- dataGridView1.Columns[1].Width
- 72; // this is an extra "margin" number of pixels
If you wanted the description column to always take up the "remainder" of the width of the DataGridView, you could put something like the above code in a Resize
event handler of the DataGridView.
W3C doc says regarding "border-radius" property: "supported in IE9+, Firefox, Chrome, Safari, and Opera".
Hence I assume you're testing on IE8 or below.
For "regular elements" there is a solution compatible with IE8 & other old/poor browsers. See below.
HTML:
<div class="myWickedClass">
<span class="myCoolItem">Some text</span> <span class="myCoolItem">Some text</span> <span class="myCoolItem"> Some text</span> <span class="myCoolItem">Some text</span>
</div>
CSS:
.myWickedClass{
padding: 0 5px 0 0;
background: #F7D358 url(../img/roundedCorner_right.png) top right no-repeat scroll;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
font: normal 11px Verdana, Helvetica, sans-serif;
color: #A4A4A4;
}
.myWickedClass > .myCoolItem:first-child {
padding-left: 6px;
background: #F7D358 url(../img/roundedCorner_left.png) 0px 0px no-repeat scroll;
}
.myWickedClass > .myCoolItem {
padding-right: 5px;
}
You need to create both roundedCorner_right.png & roundedCorner_left.png. These are work around for IE8 (& below) to fake the rounded corner feature.
So in this example above we apply the left rounded corner to the first span element in the containing div, & we apply the right rounded corner to the containing div. These images overlap the browser-provided "squary corners" & give the illusion of being part of a rounded element.
The idea for inputs would be to do the same logic. However, input is an empty element, " element is empty, it contains attributes only", in other word, you cannot wrap a span into an input such as <input><span class="myCoolItem"></span></input>
to then use background images like in the previous example.
Hence the solution seems to be to do the opposite: wrap the input into another element. see this answer rounded corners of input elements in IE
You can achieve this directly in Xcode:
The very last checkbox, make sure secure
is checked .
Or you can do it using code:
Identifies whether the text object should hide the text being entered.
Declaration
optional var secureTextEntry: Bool { get set }
Discussion
This property is set to false
by default. Setting this property to true
creates a password-style text object, which hides the text being entered.
example:
texfield.secureTextEntry = true
Doing the same in declarative pipeline syntax, below are few examples:
stage('master-branch-stuff') {
when {
branch 'master'
}
steps {
echo 'run this stage - ony if the branch = master branch'
}
}
stage('feature-branch-stuff') {
when {
branch 'feature/*'
}
steps {
echo 'run this stage - only if the branch name started with feature/'
}
}
stage('expression-branch') {
when {
expression {
return env.BRANCH_NAME != 'master';
}
}
steps {
echo 'run this stage - when branch is not equal to master'
}
}
stage('env-specific-stuff') {
when {
environment name: 'NAME', value: 'this'
}
steps {
echo 'run this stage - only if the env name and value matches'
}
}
More effective ways coming up -
https://issues.jenkins-ci.org/browse/JENKINS-41187
Also look at -
https://jenkins.io/doc/book/pipeline/syntax/#when
The directive beforeAgent true
can be set to avoid spinning up an agent to run the conditional, if the conditional doesn't require git state to decide whether to run:
when { beforeAgent true; expression { return isStageConfigured(config) } }
Release post and docs
UPDATE
New WHEN Clause
REF: https://jenkins.io/blog/2018/04/09/whats-in-declarative
equals - Compares two values - strings, variables, numbers, booleans - and returns true if they’re equal. I’m honestly not sure how we missed adding this earlier! You can do "not equals" comparisons using the not { equals ... } combination too.
changeRequest - In its simplest form, this will return true if this Pipeline is building a change request, such as a GitHub pull request. You can also do more detailed checks against the change request, allowing you to ask "is this a change request against the master branch?" and much more.
buildingTag - A simple condition that just checks if the Pipeline is running against a tag in SCM, rather than a branch or a specific commit reference.
tag - A more detailed equivalent of buildingTag, allowing you to check against the tag name itself.
For SQL 2000 I would use:
SELECT name, crdate, refdate
FROM sysobjects
WHERE type = 'P'
ORDER BY refdate desc
In addition to Benjamin's answer - in case if you are using Spring Security, placing the CharacterEncodingFilter in web.xml might not always work. In this case you need to create a custom filter and add it to the filter chain as the first filter. To make sure it's the first filter in the chain, you need to add it before ChannelProcessingFilter, using addFilterBefore
in your WebSecurityConfigurerAdapter:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//add your custom encoding filter as the first filter in the chain
http.addFilterBefore(new EncodingFilter(), ChannelProcessingFilter.class);
http.authorizeRequests()
.and()
// your code here ...
}
}
The ordering of all filters in Spring Security is available here: HttpSecurityBuilder - addFilter()
Your custom UTF-8 encoding filter can look like following:
public class EncodingFilter extends GenericFilterBean {
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
}
Don't forget to add in your jsp files:
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
And remove the CharacterEncodingFilter from web.xml if it's there.
Swift version:
myLabel.layer.borderWidth = 0.5
myLabel.layer.borderColor = UIColor.greenColor().CGColor
For Swift 3:
myLabel.layer.borderWidth = 0.5
myLabel.layer.borderColor = UIColor.green.cgColor
Sounds like you executed another statement in the same connection before traversing the result set from the first statement. If you're nesting the processing of two result sets from the same database, you're doing something wrong. The combination of those sets should be done on the database side.
This means the remote vm is not listening to current port i solved this by adding the port in the vm server
i have used following method to use input data from excel sheet: Need to import following as well
import jxl.Workbook;
then
Workbook wBook = Workbook.getWorkbook(new File("E:\\Testdata\\ShellData.xls"));
//get sheet
jxl.Sheet Sheet = wBook.getSheet(0);
//Now in application i have given my Username and Password input in following way
driver.findElement(By.xpath("//input[@id='UserName']")).sendKeys(Sheet.getCell(0, i).getContents());
driver.findElement(By.xpath("//input[@id='Password']")).sendKeys(Sheet.getCell(1, i).getContents());
driver.findElement(By.xpath("//input[@name='Login']")).click();
it will Work
One additional comment regarding Vineet Reynolds answer.
I found out that I had to set -XX:+UseParallelGC
in eclipse.ini
I setup the virtual machine (vm) arguments as follows
-vmargs
-Dosgi.requiredJavaVersion=1.7
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=512M
that solved the issue.
http://php.net/manual/en/language.types.string.php says:
Note: As of PHP 7.0.0, there are no particular restrictions regarding the length of a string on 64-bit builds. On 32-bit builds and in earlier versions, a string can be as large as up to 2GB (2147483647 bytes maximum)
In PHP 5.x, strings were limited to 231-1 bytes, because internal code recorded the length in a signed 32-bit integer.
You can slurp in the contents of an entire file, for instance using file_get_contents()
However, a PHP script has a limit on the total memory it can allocate for all variables in a given script execution, so this effectively places a limit on the length of a single string variable too.
This limit is the memory_limit
directive in the php.ini configuration file. The memory limit defaults to 128MB in PHP 5.2, and 8MB in earlier releases.
If you don't specify a memory limit in your php.ini file, it uses the default, which is compiled into the PHP binary. In theory you can modify the source and rebuild PHP to change this default value.
If you specify -1
as the memory limit in your php.ini file, it stop checking and permits your script to use as much memory as the operating system will allocate. This is still a practical limit, but depends on system resources and architecture.
Re comment from @c2:
Here's a test:
<?php
// limit memory usage to 1MB
ini_set('memory_limit', 1024*1024);
// initially, PHP seems to allocate 768KB for basic operation
printf("memory: %d\n", memory_get_usage(true));
$str = str_repeat('a', 255*1024);
echo "Allocated string of 255KB\n";
// now we have allocated all of the 1MB of memory allowed
printf("memory: %d\n", memory_get_usage(true));
// going over the limit causes a fatal error, so no output follows
$str = str_repeat('a', 256*1024);
echo "Allocated string of 256KB\n";
printf("memory: %d\n", memory_get_usage(true));
The error says "The index is out of range". That means you were trying to index an object with a value that was not valid. If you have two books, and I ask you to give me your third book, you will look at me funny. This is the computer looking at you funny. You said - "create a collection". So it did. But initially the collection is empty: not only is there nothing in it - it has no space to hold anything. "It has no hands".
Then you said "the first element of the collection is now 'ItemID'". And the computer says "I never was asked to create space for a 'first item'." I have no hands to hold this item you are giving me.
In terms of your code, you created a view, but never specified the size. You need a
dataGridView1.ColumnCount = 5;
Before trying to access any columns. Modify
DataGridView dataGridView1 = new DataGridView();
dataGridView1.Columns[0].Name = "ItemID";
to
DataGridView dataGridView1 = new DataGridView();
dataGridView1.ColumnCount = 5;
dataGridView1.Columns[0].Name = "ItemID";
See http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.columncount.aspx
if a device has an SD card, you use:
Environment.getExternalStorageState()
if you don't have an SD card, you use:
Environment.getDataDirectory()
if there is no SD card, you can create your own directory on the device locally.
//if there is no SD card, create new directory objects to make directory on device
if (Environment.getExternalStorageState() == null) {
//create new file directory object
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii <= dirFiles.length; ii++) {
dirFiles[ii].delete();
}
}
}
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}
// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length > 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
dirFiles[ii].delete();
}
dirFiles = null;
}
}
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}// end of SD card checking
add permissions on your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Happy coding..
Thx to @Alexander.Iljushkin for:
gem update --system --source http://rubygems.org/
After that bundler still failed and the solution to that was:
gem install bundler
A backreference to the whole match value is \g<0>
, see re.sub
documentation:
The backreference
\g<0>
substitutes in the entire substring matched by the RE.
See the Python demo:
import re
method = 'images/:id/huge'
print(re.sub(r':[a-z]+', r'<span>\g<0></span>', method))
# => images/<span>:id</span>/huge
You can convert .jar file to .exe on these ways:
(source: viralpatel.net)
1- JSmooth .exe wrapper:
JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself. When no VM is available, the wrapper can automatically download and install a suitable JVM, or simply display a message or redirect the user to a web site.
JSmooth provides a variety of wrappers for your java application, each of them having their own behaviour: Choose your flavour!
Download: http://jsmooth.sourceforge.net/
2- JarToExe 1.8
Jar2Exe is a tool to convert jar files into exe files.
Following are the main features as describe in their website:
Download: http://www.brothersoft.com/jartoexe-75019.html
3- Executor
Package your Java application as a jar, and Executor will turn the jar into a Windows exe file, indistinguishable from a native application. Simply double-clicking the exe file will invoke the Java Runtime Environment and launch your application.
Download: http://mpowers.net/executor/
EDIT: The above link is broken, but here is the page (with working download) from the Internet Archive. http://web.archive.org/web/20090316092154/http://mpowers.net/executor/
4- Advanced Installer
Advanced Installer lets you create Windows MSI installs in minutes. This also has Windows Vista support and also helps to create MSI packages in other languages.
Download: http://www.advancedinstaller.com/
Let me know other tools that you have used to convert JAR to EXE.
Try this:
>>> f = open('goodlines.txt')
>>> mylist = f.readlines()
open()
function returns a file object. And for file object, there is no method like splitlines()
or split()
. You could use dir(f)
to see all the methods of file object.
There is a command
svn revert -R .
OR
you can use the --depth=infinity, which is actually same as above:
svn revert --depth=infinity
svn revert
is inherently dangerous, since its entire purpose is to throw away data—namely, your uncommitted changes. Once you've reverted, Subversion provides no way to get back those uncommitted changes
Absolutely. Try this:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
Don't forget also to create the constant PICK_IMAGE, so you can recognize when the user comes back from the image gallery Activity:
public static final int PICK_IMAGE = 1;
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PICK_IMAGE) {
//TODO: action
}
}
That's how I call the image gallery. Put it in and see if it works for you.
EDIT:
This brings up the Documents app. To allow the user to also use any gallery apps they might have installed:
Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});
startActivityForResult(chooserIntent, PICK_IMAGE);
substring() method returns a new String that contains a subsequence of characters currently contained in this sequence.
The substring begins at the specified start
and extends to the character at index end - 1
.
It has two forms. The first is
String substring(int FirstIndex)
Here, FirstIndex specifies the index at which the substring will begin. This form returns a copy of the substring that begins at FirstIndex and runs to the end of the invoking string.
String substring(int FirstIndex, int endIndex)
Here, FirstIndex specifies the beginning index, and endIndex specifies the stopping point. The string returned contains all the characters from the beginning index, up to, but not including, the ending index.
String str = "Amiyo";
// prints substring from index 3
System.out.println("substring is = " + str.substring(3)); // Output 'yo'
I don't see php file, but that could be that -
replace in your php file:
$query_age = $_GET['query_age'];
with:
$query_age = (isset($_GET['query_age']) ? $_GET['query_age'] : null);
Most probably, at first time you running your script without ?query_age=[something]
and $_GET
has no key like query_age
.
If all you need is mousedown, you may be able to make do with the document.elementFromPoint
method, by:
x
and y
coordinates from the event to the document.elementFromPoint
method to get the element underneath, and thenA JavaBean is just a standard
Serializable
.That's it. It's just a convention. Lots of libraries depend on it though.
With respect to Serializable
, from the API documentation:
Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.
In other words, serializable objects can be written to streams, and hence files, object databases, anything really.
Also, there is no syntactic difference between a JavaBean and another class -- a class is a JavaBean if it follows the standards.
There is a term for it, because the standard allows libraries to programmatically do things with class instances you define in a predefined way. For example, if a library wants to stream any object you pass into it, it knows it can because your object is serializable (assuming the library requires your objects be proper JavaBeans).
You are mixing the 2 different CASE
syntaxes inappropriately.
Use this style (Searched)
CASE
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Or this style (Simple)
CASE u.nnmu
WHEN '0' THEN mu.naziv_mesta
WHEN '1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Not This (Simple but with boolean search predicates)
CASE u.nnmu
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
In MySQL this will end up testing whether u.nnmu
is equal to the value of the boolean expression u.nnmu ='0'
itself. Regardless of whether u.nnmu
is 1
or 0
the result of the case expression itself will be 1
For example if nmu = '0'
then (nnmu ='0'
) evaluates as true
(1) and (nnmu ='1'
) evaluates as false
(0). Substituting these into the case expression gives
SELECT CASE '0'
WHEN 1 THEN '0'
WHEN 0 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
if nmu = '1'
then (nnmu ='0'
) evaluates as false
(0) and (nnmu ='1'
) evaluates as true
(1). Substituting these into the case expression gives
SELECT CASE '1'
WHEN 0 THEN '0'
WHEN 1 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
Thanks jbaliuka for the suggestion. I opened the registry editor (by typing regedit in cmd) and going to HKEY_CLASSES_ROOT > jarfile > shell > open > command, then opening (Default) and changing the value from
"C:\Program Files\Java\jre7\bin\javaw.exe" -jar "%1" %*
to
"C:\Program Files\Java\jre7\bin\java.exe" -jar "%1" %*
(I just removed the w in javaw.exe.) After that you have to right click a jar -> open with -> choose default program -> navigate to your java folder and open \jre7\bin\java.exe (or any other java.exe file in you java folder). If it doesn't work, try switching to javaw.exe, open a jar file with it, then switch back.
I don't know anything about editing the registry except that it's dangerous, so you might wanna back it up before doing this (in the top bar, File>Export).
You can do it without modifying the XML stream: Tell the XmlReader to not be so picky.
Setting the XmlReaderSettings.ConformanceLevel
to ConformanceLevel.Fragment
will let the parser ignore the fact that there is no root node.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlReader reader = XmlReader.Create(tr,settings))
{
...
}
Now you can parse something like this (which is an real time XML stream, where it is impossible to wrap with a node).
<event>
<timeStamp>1354902435238</timeStamp>
<eventId>7073822</eventId>
</event>
<data>
<time>1354902435341</time>
<payload type='80'>7d1300786a0000000bf9458b0518000000000000000000000000000000000c0c030306001b</payload>
</data>
<data>
<time>1354902435345</time>
<payload type='80'>fd1260780912ff3028fea5ffc0387d640fa550f40fbdf7afffe001fff8200fff00f0bf0e000042201421100224ff40312300111400004f000000e0c0fbd1e0000f10e0fccc2ff0000f0fe00f00f0eed00f11e10d010021420401</payload>
</data>
<data>
<time>1354902435347</time>
<payload type='80'>fd126078ad11fc4015fefdf5b042ff1010223500000000000000003007ff00f20e0f01000e0000dc0f01000f000000000000004f000000f104ff001000210f000013010000c6da000000680ffa807800200000000d00c0f0</payload>
</data>
You can't use IF like that. You can do what you want with AND and OR:
SELECT t.first_name,
t.last_name,
t.employid,
t.status
FROM employeetable t
WHERE ((status_flag = STATUS_ACTIVE AND t.status = 'A')
OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
OR (source_flag = SOURCE_USER AND t.business_unit = 'users'))
AND t.first_name LIKE firstname
AND t.last_name LIKE lastname
AND t.employid LIKE employeeid;
@balalakshmi mentioned about the correct authentication settings. Authentication is only half of the problem, the other half is authorization.
If you're using Forms Authentication and standard controls like <asp:Login>
there are a couple of things you'll need to do to ensure that only your authenticated users can access secured pages.
In web.config
, under the <system.web>
section you'll need to disable anonymous access by default:
<authorization>
<deny users="?" />
</authorization>
Any pages that will be accessed anonymously (such as the Login.aspx page itself) will need to have an override that re-allows anonymous access. This requires a <location>
element and must be located at the <configuration>
level (outside the <system.web>
section), like this:
<!-- Anonymous files -->
<location path="Login.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
Note that you'll also need to allow anonymous access to any style sheets or scripts that are used by the anonymous pages:
<!-- Anonymous folders -->
<location path="styles">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
Be aware that the location's path
attribute is relative to the web.config
folder and cannot have a ~/
prefix, unlike most other path-type configuration attributes.
If all you want to do is authenticate against AD using Kerberos, then a simple http://spnego.sourceforge.net/HelloKDC.java program should do it.
Take a look at the project's "pre-flight" documentation which talks about the HelloKDC.java program.
private String temp = "mahesh.hiren.darshan";
String s_temp[] = temp.split("[.]");
Log.e("1", ""+s_temp[0]);