You can only use the window.close
function when you have opened the window using window.open()
, so I use the following function:
function close_window(url){
var newWindow = window.open('', '_self', ''); //open the current window
window.close(url);
}
You are not allowed to have div
tags between tr
tags. You have to look for some other strategies like creating a CSS class with display: none
and adding it to concerning rows or adding inline style display: none
to concerning rows.
.hidden
{
display:none;
}
<table>
<tr><td>I am visible</td><tr>
<tr class="hidden"><td>I am hidden using CSS class</td><tr>
<tr class="hidden"><td>I am hidden using CSS class</td><tr>
<tr class="hidden"><td>I am hidden using CSS class</td><tr>
<tr class="hidden"><td>I am hidden using CSS class</td><tr>
</table>
or
<table>
<tr><td>I am visible</td><tr>
<tr style="display:none"><td>I am hidden using inline style</td><tr>
<tr style="display:none"><td>I am hidden using inline style</td><tr>
<tr style="display:none"><td>I am hidden using inline style</td><tr>
</table>
I came across the same error, and could easily find what was the problem by logging the exception:
documentBuilder.setErrorHandler(new ErrorHandler() {
@Override
public void warning(SAXParseException exception) throws SAXException {
log.warn(exception.getMessage());
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
log.error("Fatal error ", exception);
}
@Override
public void error(SAXParseException exception) throws SAXException {
log.error("Exception ", exception);
}
});
Or, instead of logging the error, you can throw
it and catch
it where you handle the entries, so you can print the entry itself to get a better indication on the error.
It is good to understand with a Venn diagramm.
here is the link to the source. There is a good description.
You have mixed indentation formatting (spaces and tabs)
Go to Settings -> Preferences -> Tab Settings -> Replace by spaces
Select everything CTRL+A
Click TAB once, to add an indentation everywhere
Run SHIFT + TAB to remove the extra indentation, it will replace all TAB characters to 4 spaces.
We to faced similar issue while setting spring.profiles.active
in java.
This is what we figured out in the end, after trying four different ways of providing spring.profiles.active
.
In java-8
$ java --spring.profiles.active=dev -jar my-service.jar
Gives unrecognized --spring.profiles.active option.
$ java -jar my-service.jar --spring.profiles.active=dev
# This works fine
$ java -Dspring.profiles.active=dev -jar my-service.jar
# This works fine
$ java -jar my-service.jar -Dspring.profiles.active=dev
# This doesn't works
In java-11
$ java --spring.profiles.active=dev -jar my-service.jar
Gives unrecognized --spring.profiles.active option.
$ java -jar my-service.jar --spring.profiles.active=dev
# This doesn't works
$ java -Dspring.profiles.active=dev -jar my-service.jar
# This works fine
$ java -jar my-service.jar -Dspring.profiles.active=dev
# This doesn't works
NOTE: If you're specifying spring.profiles.active
in your application.properties
file then make sure you provide spring.config.location
or spring.config.additional-location
option to java accordingly as mentioned above.
Don't type python test.py
from inside the Python interpreter. Type it at the command prompt, like so:
First get the pid:
ps ax | grep [process name]
And then:
top -p PID
You can watch various processes in the same time:
top -p PID1 -p PID2
one url to the same view! like so!
urls.py
url(r'^$', views.landing.as_view(), name = 'landing'),
views.py
class landing(View):
template_name = '/home.html'
form_class1 = forms.pynamehere1
form_class2 = forms.pynamehere2
def get(self, request):
form1 = self.form_class1(None)
form2 = self.form_class2(None)
return render(request, self.template_name, { 'register':form1, 'login':form2,})
def post(self, request):
if request.method=='POST' and 'htmlsubmitbutton1' in request.POST:
## do what ever you want to do for first function ####
if request.method=='POST' and 'htmlsubmitbutton2' in request.POST:
## do what ever you want to do for second function ####
## return def post###
return render(request, self.template_name, {'form':form,})
/home.html
<!-- #### form 1 #### -->
<form action="" method="POST" >
{% csrf_token %}
{{ register.as_p }}
<button type="submit" name="htmlsubmitbutton1">Login</button>
</form>
<!--#### form 2 #### -->
<form action="" method="POST" >
{% csrf_token %}
{{ login.as_p }}
<button type="submit" name="htmlsubmitbutton2">Login</button>
</form>
Simply mark any method you need to fake as virtual
(and not private). Then you will be able to create a fake that can override the method.
If you use new Mock<Type>
and you don't have a parameterless constructor then you can pass the parameters as the arguments of the above call as it takes a type of param Objects
Check out Apache Commons FileUtils (listFiles, iterateFiles, etc.). Nice convenience methods for doing what you want and also applying filters.
http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html
WARNING:
git clean -f
will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.
Try this and see git clean -f
.
git reset --hard
will not remove untracked files, where as git-clean
will remove any files from the tracked root directory that are not under Git tracking.
Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)
git clean -df
git clean -xdf
CAUTION! This will also delete ignored filesPlease be aware that the warning on iTunes Connect does not say anything about the limit being only for over-the-air delivery. It would be preferable if the warning mentioned this.
References are not pointers.
8.3.2/1:
A reference shall be initialized to refer to a valid object or function. [Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bit-field. ]
1.9/4:
Certain other operations are described in this International Standard as undefined (for example, the effect of dereferencing the null pointer)
As Johannes says in a deleted answer, there's some doubt whether "dereferencing a null pointer" should be categorically stated to be undefined behavior. But this isn't one of the cases that raise doubts, since a null pointer certainly does not point to a "valid object or function", and there is no desire within the standards committee to introduce null references.
Did you try
for line in open("masters", "r").readlines(): print line
?
readline()
only reads "a line", on the other hand
readlines()
reads whole lines and gives you a list of all lines.
I had almost the same problem, but with the following variation:
That's quite odd behavour, I cannot completely understand it. Hope It'll help somebody. too.
Using Accept header is really easy to get the format json or xml from the REST service.
This is my Controller, take a look produces section.
@RequestMapping(value = "properties", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, method = RequestMethod.GET)
public UIProperty getProperties() {
return uiProperty;
}
In order to consume the REST service we can use the code below where header can be MediaType.APPLICATION_JSON_VALUE or MediaType.APPLICATION_XML_VALUE
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", header);
HttpEntity entity = new HttpEntity(headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/properties", HttpMethod.GET, entity,String.class);
return response.getBody();
Edit 01:
In order to work with application/xml
, add this dependency
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
As JavaScript is a client-side language and PHP is a server-side language you would need to physically push the variable to the PHP script, by either including the variable on the page load of the PHP script (script.php?var=test), which really has nothing to do with JavaScript, or by passing the variable to the PHP via an AJAX/AHAH call each time the variable is changed.
If you did want to go down the second path, you'd be looking at XMLHttpRequest, or my preference, jQuerys Ajax calls: http://docs.jquery.com/Ajax
You can also use matches with regular expression like this:
boolean bool = List.matches("(?i).*SOME STRING HERE.*")
Since none of the answers are up to date with the last version of Pandas, I am writing another solution for this problem:
In [1]:
import pandas as pd
# Set exemple
df2 = pd.DataFrame({'X' : ['X1', 'X1', 'X1', 'X1'], 'Y' : ['Y2','Y1','Y1','Y1'], 'Z' : ['Z3','Z1','Z1','Z2']})
# Pivot
pd.crosstab(index=df2['Y'], columns=df2['Z'], values=df2['X'], aggfunc=pd.Series.nunique)
Out [1]:
Z Z1 Z2 Z3
Y
Y1 1.0 1.0 NaN
Y2 NaN NaN 1.0
I was plagued by this error message despite using async: true. It turns out the actual problem was using the success
method. I changed this to done
and warning is gone.
success: function(response) { ... }
replaced with:
done: function(response) { ... }
Awesome tutorial: 3 Different Ways to Display Progress in an ASP.NET AJAX Application
How about something like this ...
var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 };
var g = l1.GroupBy( i => i );
foreach( var grp in g )
{
Console.WriteLine( "{0} {1}", grp.Key, grp.Count() );
}
Edit per comment: I will try and do this justice. :)
In my example, it's a Func<int, TKey>
because my list is ints. So, I'm telling GroupBy how to group my items. The Func takes a int and returns the the key for my grouping. In this case, I will get an IGrouping<int,int>
(a grouping of ints keyed by an int). If I changed it to (i => i.ToString()
) for example, I would be keying my grouping by a string. You can imagine a less trivial example than keying by "1", "2", "3" ... maybe I make a function that returns "one", "two", "three" to be my keys ...
private string SampleMethod( int i )
{
// magically return "One" if i == 1, "Two" if i == 2, etc.
}
So, that's a Func that would take an int and return a string, just like ...
i => // magically return "One" if i == 1, "Two" if i == 2, etc.
But, since the original question called for knowing the original list value and it's count, I just used an integer to key my integer grouping to make my example simpler.
DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, Locale);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, Locale);
Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()
it returns how many days between given two dates, where DateTime
is from joda library
Have you looked at angular-ui bootstrap? There's a Dialog (ui.bootstrap.dialog) directive that works quite well. You can close the dialog during the call back the angular way (per the example):
$scope.close = function(result){
dialog.close(result);
};
Update:
The directive has since been renamed Modal.
You may try this:
public static void main(String[] args) {
BigDecimal a = new BigDecimal("10.12345");
System.out.println(toPrecision(a, 2));
}
private static BigDecimal toPrecision(BigDecimal dec, int precision) {
String plain = dec.movePointRight(precision).toPlainString();
return new BigDecimal(plain.substring(0, plain.indexOf("."))).movePointLeft(precision);
}
OUTPUT:
10.12
Array(n).map((value, index) ....) is 80% of the way there. But for some odd reason it does not work. But there is a workaround.
Array(n).map((v,i) => i) // does not work
Array(n).fill().map((v,i) => i) // does dork
For a range
Array(end-start+1).fill().map((v,i) => i + start) // gives you a range
Odd, these two iterators return the same result: Array(end-start+1).entries()
and Array(end-start+1).fill().entries()
Late, but can be done by using Object.keys like,
var a={key1:'value1',key2:'value2',key3:'value3',key4:'value4'},_x000D_
ulkeys=document.getElementById('object-keys'),str='';_x000D_
var keys = Object.keys(a);_x000D_
for(i=0,l=keys.length;i<l;i++){_x000D_
str+= '<li>'+keys[i]+' : '+a[keys[i]]+'</li>';_x000D_
}_x000D_
ulkeys.innerHTML=str;
_x000D_
<ul id="object-keys"></ul>
_x000D_
Try this, should work.
val list = List(1,2,4,2,4,7,3,2,4)
list.count(_==2)
It will return 3
You can easily restart your MySql service. This kicks the error off.
It is not bad practice because something is 'wrong' about PrintStackTrace(), but because it's 'code smell'. Most of the time the PrintStackTrace() call is there because somebody failed to properly handle the exception. Once you deal with the exception in a proper way you generally don't care about the StackTrace any more.
Additionally, displaying the stacktrace on stderr is generally only useful when debugging, not in production because very often stderr goes nowhere. Logging it makes more sense. But just replacing PrintStackTrace() with logging the exception still leaves you with an application which failed but keeps running like nothing happened.
For those starting with an existing IDEA installation (IDEA 15 in my case) to which they're adding the Android SDK (and not starting formally speaking with Android Studio), ...
Download (just) the SDK to your filesystem (somewhere convenient to you; it doesn't matter where).
When creating your first project and you get to the Project SDK: bit (or adding the Android SDK ahead of time as you wish), navigate (New) to the root of what you exploded into the filesystem as suggested by some of the other answers here.
At that point you'll get a tiny dialog to confirm with:
Java SDK: 1.7 (e.g.)
Build target: Android 6.0 (e.g.)
You can click OK whereupon you'll see what you did as an option in the Project SDK: drop-down, e.g.:
Android API 23 Platform (java version "1.7.0_67")
Type type = pi.PropertyType;
if(type.IsGenericType && type.GetGenericTypeDefinition()
== typeof(List<>))
{
Type itemType = type.GetGenericArguments()[0]; // use this...
}
More generally, to support any IList<T>
, you need to check the interfaces:
foreach (Type interfaceType in type.GetInterfaces())
{
if (interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition()
== typeof(IList<>))
{
Type itemType = type.GetGenericArguments()[0];
// do something...
break;
}
}
Here's the fix that worked for me. Firefox has a file origin policy that causes this. To fix do the following steps:
Details: http://stuffandnonsense.co.uk/blog/about/firefoxs_file_uri_origin_policy_and_web_fonts
You will only see this issue when accessing a file using file:/// protocol
The idea is to have equal size of message being sent from Kafka Producer to Kafka Broker and then received by Kafka Consumer i.e.
Kafka producer --> Kafka Broker --> Kafka Consumer
Suppose if the requirement is to send 15MB of message, then the Producer, the Broker and the Consumer, all three, needs to be in sync.
Kafka Producer sends 15 MB --> Kafka Broker Allows/Stores 15 MB --> Kafka Consumer receives 15 MB
The setting therefore should be:
a) on Broker:
message.max.bytes=15728640
replica.fetch.max.bytes=15728640
b) on Consumer:
fetch.message.max.bytes=15728640
Below, is the most clean, comprehensible way of merging multiple dataframe if complex queries aren't involved.
Just simply merge with DATE as the index and merge using OUTER method (to get all the data).
import pandas as pd
from functools import reduce
df1 = pd.read_table('file1.csv', sep=',')
df2 = pd.read_table('file2.csv', sep=',')
df3 = pd.read_table('file3.csv', sep=',')
Now, basically load all the files you have as data frame into a list. And, then merge the files using merge
or reduce
function.
# compile the list of dataframes you want to merge
data_frames = [df1, df2, df3]
Note: you can add as many data-frames inside the above list. This is the good part about this method. No complex queries involved.
To keep the values that belong to the same date you need to merge it on the DATE
df_merged = reduce(lambda left,right: pd.merge(left,right,on=['DATE'],
how='outer'), data_frames)
# if you want to fill the values that don't exist in the lines of merged dataframe simply fill with required strings as
df_merged = reduce(lambda left,right: pd.merge(left,right,on=['DATE'],
how='outer'), data_frames).fillna('void')
Then write the merged data to the csv file if desired.
pd.DataFrame.to_csv(df_merged, 'merged.txt', sep=',', na_rep='.', index=False)
This should give you
DATE VALUE1 VALUE2 VALUE3 ....
The solution (which other answers don't mention—at least at the time of my originally writing this) is that when PHP refers to delimiters, it's not referring to the delimiters you see in your code (which are quote marks) but the next characters inside the string. (In fact I've never seen this stated anywhere in any documentation: you have to see it in examples.) So instead of having a regular expression syntax like what you may be accustomed to from many other languages:
/something/
PHP uses strings, and then looks inside the string for another delimiter:
'/something/'
The delimiter PHP is referring to is the pair of /
characters, instead of the pair of '
characters. So if you write 'something'
, PHP will take s
as the intended delimiter and complain that you're not allowed to use alphanumeric characters as your delimiter.
So if you want to pass (for instance) an i
to show that you want a case-insensitve match, you pass it inside the string but outside of the regex delimiters:
'/something/i'
If you want to use something other than /
as your delimiter, you can, such as if you're matching a URL and don't want to have to escape all the slashes:
'~something~'
IntelliJ needs the subversion command(svn) added into Subversion settings. Here are the steps: 1. Download and Install subversion. 2. check on the command line prompt on windows(cmd) for the same command - svn.
You should set your RecyclerView
LayoutManager
to Gridlayout mode. Just change your code when you want to set your RecyclerView
LayoutManager
:
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), numberOfColumns));
You can't checkout a single directory of a repository because the entire repository is handled by the single .git folder in the root of the project instead of subversion's myriad of .svn directories.
The problem with working on plugins in a single repository is that making a commit to, e.g., mytheme will increment the revision number for myplugin, so even in subversion it is better to use separate repositories.
The subversion paradigm for sub-projects is svn:externals which translates somewhat to submodules in git (but not exactly in case you've used svn:externals before.)
If %x%==1 (
If %y%==1 (
:: both are equal to 1.
)
)
That's for checking if multiple variables equal value. Here's for either variable.
If %x%==1 (
:: true
)
If %x%==0 (
If %y%==1 (
:: true
)
)
If %x%==0 (
If %y%==0 (
:: False
)
)
I just thought of that off the top if my head. I could compact it more.
I also have the similar problem, and later on I found it is because I changed my hostname (not localhost
).
Therefore I get it resolved by specifying the --host=127.0.0.1
mysql -p mydatabase --host=127.0.0.1
I don't exactly understand what's the problem. Incomplete type is not the type that's "missing". Incompete type is a type that is declared but not defined (in case of struct types). To find the non-defining declaration is easy. As for the finding the missing definition... the compiler won't help you here, since that is what caused the error in the first place.
A major reason for incomplete type errors in C are typos in type names, which prevent the compiler from matching one name to the other (like in matching the declaration to the definition). But again, the compiler cannot help you here. Compiler don't make guesses about typos.
Here's what you can do using font-awesome library.
button.btn.add::before {_x000D_
font-family: fontAwesome;_x000D_
content: "\f067\00a0";_x000D_
}_x000D_
_x000D_
button.btn.edit::before {_x000D_
font-family: fontAwesome;_x000D_
content: "\f044\00a0";_x000D_
}_x000D_
_x000D_
button.btn.save::before {_x000D_
font-family: fontAwesome;_x000D_
content: "\f00c\00a0";_x000D_
}_x000D_
_x000D_
button.btn.cancel::before {_x000D_
font-family: fontAwesome;_x000D_
content: "\f00d\00a0";_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<!--FA unicodes here: http://astronautweb.co/snippet/font-awesome/-->_x000D_
<h4>Buttons with text</h4>_x000D_
<button class="btn cancel btn-default">Close</button>_x000D_
<button class="btn add btn-primary">Add</button>_x000D_
<button class="btn add btn-success">Insert</button>_x000D_
<button class="btn save btn-primary">Save</button>_x000D_
<button class="btn save btn-warning">Submit Changes</button>_x000D_
<button class="btn cancel btn-link">Delete</button>_x000D_
<button class="btn edit btn-info">Edit</button>_x000D_
<button class="btn edit btn-danger">Modify</button>_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
<h4>Buttons without text</h4>_x000D_
<button class="btn edit btn-primary" />_x000D_
<button class="btn cancel btn-danger" />_x000D_
<button class="btn add btn-info" />_x000D_
<button class="btn save btn-success" />_x000D_
<button class="btn edit btn-link"/>_x000D_
<button class="btn cancel btn-link"/>
_x000D_
If you want to export it as a file just do Any Collection (...) -> Export. There you should be able to choose collection version format and it will be exported in JSN file.
This link goes to the best comparison chart around, directly from the Microsoft. It compares ALL aspects of all MS SQL server editions. To compare three editions you are asking about, just focus on the last three columns of every table in there.
Summary compiled from the above document:
* = contains the feature SQLEXPR SQLEXPRWT SQLEXPRADV ---------------------------------------------------------------------------- > SQL Server Core * * * > SQL Server Management Studio - * * > Distributed Replay – Admin Tool - * * > LocalDB - * * > SQL Server Data Tools (SSDT) - - * > Full-text and semantic search - - * > Specification of language in query - - * > some of Reporting services features - - *
Another simple PHP example of using cURL:
<?php
$ch = curl_init(); // Initiate cURL
$url = "http://www.somesite.com/curl_example.php"; // Where you want to post data
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true); // Tell cURL you want to post something
curl_setopt($ch, CURLOPT_POSTFIELDS, "var1=value1&var2=value2&var_n=value_n"); // Define what you want to post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the output in string format
$output = curl_exec ($ch); // Execute
curl_close ($ch); // Close cURL handle
var_dump($output); // Show output
?>
Example found here: http://devzone.co.in/post-data-using-curl-in-php-a-simple-example/
Instead of using curl_setopt
you can use curl_setopt_array
.
Something like the standard Collection.toArray(T[]) should do what you need (note that ArrayList
implements Collection
):
TypeA[] array = a.toArray(new TypeA[a.size()]);
On a side note, you should consider defining a
to be of type List<TypeA>
rather than ArrayList<TypeA>
, this avoid some implementation specific definition that may not really be applicable for your application.
Also, please see this question about the use of a.size()
instead of 0
as the size of the array passed to a.toArray(TypeA[])
Example downloader class without Alamofire:
class Downloader {
class func load(URL: NSURL) {
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = "GET"
let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if (error == nil) {
// Success
let statusCode = (response as NSHTTPURLResponse).statusCode
println("Success: \(statusCode)")
// This is your file-variable:
// data
}
else {
// Failure
println("Failure: %@", error.localizedDescription);
}
})
task.resume()
}
}
This is how to use it in your own code:
class Foo {
func bar() {
if var URL = NSURL(string: "http://www.mywebsite.com/myfile.pdf") {
Downloader.load(URL)
}
}
}
Swift 3 Version
Also note to download large files on disk instead instead in memory. see `downloadTask:
class Downloader {
class func load(url: URL, to localUrl: URL, completion: @escaping () -> ()) {
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = try! URLRequest(url: url, method: .get)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Success: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: localUrl)
completion()
} catch (let writeError) {
print("error writing file \(localUrl) : \(writeError)")
}
} else {
print("Failure: %@", error?.localizedDescription);
}
}
task.resume()
}
}
Thanks @rofly, the full conversion from string to string is as follows:
time.strftime("%Y-%m-%d %H:%M:%S",
time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00",
"%Y-%m-%d %H:%M:%S"))))
My summary of the time
/calendar
functions:
time.strptime
string --> tuple (no timezone applied, so matches string)
time.mktime
local time tuple --> seconds since epoch (always local time)
time.gmtime
seconds since epoch --> tuple in UTC
and
calendar.timegm
tuple in UTC --> seconds since epoch
time.localtime
seconds since epoch --> tuple in local timezone
setInterval(moveItem, 2000);
is the way to execute the function moveItem
every 2 seconds. The main problem in your code is that you're calling setInterval
inside of, rather than outside of, the callback. If I understand what you're trying to do, you can use this:
function moveItem() {
jQuery('.stripTransmitter ul li a').trigger('click');
}
setInterval(moveItem, 2000);
N.B.:Don't pass strings to setTimeout
or setInterval
- best practice is to pass an anonymous function or a function identifier (as I did above). Also, be careful to not mix single and double quotes. Pick one and stick with it.
I am completely rewriting my answer (again). This time it is because I have become a fan of the guard
statement and early return. It makes for much cleaner code.
Check for zero length.
let myString: String = ""
if myString.isEmpty {
print("String is empty.")
return // or break, continue, throw
}
// myString is not empty (if this point is reached)
print(myString)
If the if
statement passes, then you can safely use the string knowing that it isn't empty. If it is empty then the function will return early and nothing after it matters.
Check for nil or zero length.
let myOptionalString: String? = nil
guard let myString = myOptionalString, !myString.isEmpty else {
print("String is nil or empty.")
return // or break, continue, throw
}
// myString is neither nil nor empty (if this point is reached)
print(myString)
This unwraps the optional and checks that it isn't empty at the same time. After passing the guard
statement, you can safely use your unwrapped nonempty string.
You could use input type image.
<input type="image" src="http://example.com/path/to/image.png" />
It works as a button and can have the event handlers attached to it.
Alternatively, you can use css to style your button with a background image, and set the borders, margins and the like appropriately.
<button style="background: url(myimage.png)" ... />
Your sys.path is kind of unusual, as each entry is prefixed with /usr/intel. I guess numpy is installed in the usual non-prefixed place, e.g. it. /usr/share/pyshared/numpy on my Ubuntu system.
Try find / -iname '*numpy*'
I've converted the http://html5pattern.com/Dates Full Date Validation (YYYY-MM-DD) to DD/MM/YYYY Brazilian format:
pattern='(?:((?:0[1-9]|1[0-9]|2[0-9])\/(?:0[1-9]|1[0-2])|(?:30)\/(?!02)(?:0[1-9]|1[0-2])|31\/(?:0[13578]|1[02]))\/(?:19|20)[0-9]{2})'
It's HTTP Activation feature of .NET framework Windows Process Activation feature is required too
Here you can use my method for generating Random String
protected String getSaltString() {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String saltStr = salt.toString();
return saltStr;
}
The above method from my bag using to generate a salt string for login purpose.
You can just use the normal termios header and normal termios structure (it's the same as the termios2 when using header asm/termios).
So, you open the device using open() and get a file descriptor, then use it in tcgetattr()
to fill your termios structure.
Then clear CBAUD
and set CBAUDEX
on c_cflag
.
CBAUDEX
has the same value as BOTHER.
After setting this, you can set a custom baud rate using normal functions, like cfsetspeed()
, specifying the desired baud rate as an integer.
132 is outside the range of a byte which is -128 to 127 (Byte.MIN_VALUE to Byte.MAX_VALUE) Instead the top bit of the 8-bit value is treated as the signed which indicates it is negative in this case. So the number is 132 - 256 = -124.
The problem mainly occurs after updating OS X to El Capitan (OS X 10.11) or macOS Sierra (macOS 10.12).
This is because of file permission issues with El Capitan’s or later macOS's new SIP process. Try changing the permissions for the /usr/local
directory:
$ sudo chown -R $(whoami):admin /usr/local
If it still doesn't work, use these steps inside a terminal session and everything will be fine:
cd /usr/local/Library/Homebrew
git reset --hard
git clean -df
brew update
This may be because homebrew is not updated.
In codeigniter doc if you update specific field just do this
$data = array(
'yourfieldname' => value,
'name' => $name,
'date' => $date
);
$this->db->where('yourfieldname', yourfieldvalue);
$this->db->update('yourtablename', $data);
It should be:
document.getElementById("placehere").appendChild(elem);
And place your div before your javascript, because if you don't, the javascript executes before the div exists. Or wait for it to load. So your code looks like this:
<html>
<body>
<script type="text/javascript">
window.onload=function(){
var elem = document.createElement("img");
elem.setAttribute("src", "http://img.zohostatic.com/discussions/v1/images/defaultPhoto.png");
elem.setAttribute("height", "768");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "Flower");
document.getElementById("placehere").appendChild(elem);
}
</script>
<div id="placehere">
</div>
</body>
</html>
To prove my point, see this with the onload and this without the onload. Fire up the console and you'll find an error stating that the div doesn't exist or cannot find appendChild method of null.
Since the fragment property still doesn't provide anchor scrolling, this workaround did the trick for me:
<div [routerLink]="['somepath']" fragment="Test">
<a href="#Test">Jump to 'Test' anchor </a>
</div>
To completely remove the style attribute of the voltaic_holder
span, do this:
$("#voltaic_holder").removeAttr("style");
To add an attribute, do this:
$("#voltaic_holder").attr("attribute you want to add", "value you want to assign to attribute");
To remove only the top style, do this:
$("#voltaic_holder").css("top", "");
You could do this various different ways. It could be a subtle as a small status on the page saying "Loading...", or as loud as an entire element graying out the page while the new data is loading. The approach I'm taking below will show you how to accomplish both methods.
Let's start by getting us a nice "loading" animation from http://ajaxload.info I'll be using
Let's create an element that we can show/hide anytime we're making an ajax request:
<div class="modal"><!-- Place at bottom of page --></div>
Next let's give it some flair:
/* Start by setting display:none to make this hidden.
Then we position it in relation to the viewport window
with position:fixed. Width, height, top and left speak
for themselves. Background we set to 80% white with
our animation centered, and no-repeating */
.modal {
display: none;
position: fixed;
z-index: 1000;
top: 0;
left: 0;
height: 100%;
width: 100%;
background: rgba( 255, 255, 255, .8 )
url('http://i.stack.imgur.com/FhHRx.gif')
50% 50%
no-repeat;
}
/* When the body has the loading class, we turn
the scrollbar off with overflow:hidden */
body.loading .modal {
overflow: hidden;
}
/* Anytime the body has the loading class, our
modal element will be visible */
body.loading .modal {
display: block;
}
Alright, on to the jQuery. This next part is actually really simple:
$body = $("body");
$(document).on({
ajaxStart: function() { $body.addClass("loading"); },
ajaxStop: function() { $body.removeClass("loading"); }
});
That's it! We're attaching some events to the body element anytime the ajaxStart
or ajaxStop
events are fired. When an ajax event starts, we add the "loading" class to the body. and when events are done, we remove the "loading" class from the body.
See it in action: http://jsfiddle.net/VpDUG/4952/
In case that it serves to someone, I leave here the Windows 10 base register for Python 3.4.4 - 64 bit:
Por si alguien lo necesita todavía, este es el registro base de Windows 10 para Python 3.4.4:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4]
"DisplayName"="Python 3.4 (64-bit)"
"SupportUrl"="http://www.python.org/"
"Version"="3.4.4"
"SysVersion"="3.4"
"SysArchitecture"="64bit"
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\Help]
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\Help\Main Python Documentation]
@="C:\\Python34\\Doc\\python364.chm"
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\Idle]
@="C:\\Python34\\Lib\\idlelib\\idle.pyw"
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\IdleShortcuts]
@=dword:00000001
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstalledFeatures]
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstallPath]
@="C:\\Python34\\"
"ExecutablePath"="C:\\Python34\\python.exe"
"WindowedExecutablePath"="C:\\Python34\\pythonw.exe"
[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\PythonPath]
@="C:\\Python34\\Lib\\;C:\\Python34\\DLLs\\"
int main() {
int sum = 0;
cout << "enter number" << endl;
int i = 0;
while (true) {
cin >> i;
sum += i;
//cout << i << endl;
if (cin.peek() == '\n') {
break;
}
}
cout << "result: " << sum << endl;
return 0;
}
I think this code works, you may enter any int numbers and spaces, it will calculate the sum of input ints
Here is my solution for mac users I think it work for window also:
First go to your Android Studio toolbar
Build > Make Project (while you guys are online let it to download the files) and then
Build > Compile Module "your app name is shown here" (still online let the files are
download and finish) and then
Run your app that is done it will launch your emulator and configure it then run it!
That is it!!! Happy Coding guys!!!!!!!
You should use something like this:
SELECT *
FROM (select salary2.*, rownum rnum from
(select * from salary ORDER BY salary_amount DESC) salary2
where rownum <= 2 )
WHERE rnum >= 2;
When you do not want to have the emails in the list that are in the database you'll can do the following:
select u.name
, u.EMAIL
, a.emailadres
, case when a.emailadres is null then 'Not exists'
else 'Exists'
end as 'Existence'
from users u
left join ( select 'email1' as emailadres
union all select 'email2'
union all select 'email3') a
on a.emailadres = u.EMAIL)
this way you'll get a result like
name | email | emailadres | existence
-----|--------|------------|----------
NULL | NULL | [email protected] | Not exists
Jan | [email protected] | [email protected] | Exists
Using the IN or EXISTS operators are more heavy then the left join in this case.
Good luck :)
Simplest example to making any function in jQuery is
jQuery.fn.extend({
exists: function() { return this.length }
});
if($(selector).exists()){/*do something here*/}
Whenever you're confused, I would suggest consulting the Javadoc as the first place for your clarification.
From the javadoc about System
, here's what the doc says:
public final class System
extends Object
The System class contains several useful class fields and methods. It cannot be instantiated.
Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Since:
JDK1.0
Regarding System.out
public static final PrintStream out
The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.
For simple stand-alone Java applications, a typical way to write a line of output data is:
System.out.println(data)
To complete the previous answers, one may need a collection of objects from his CSV File, either parsed by the TextFieldParser
or the string.Split
method, and then each line converted to an object via Reflection. You obviously first need to define a class that matches the lines of the CSV file.
I used the simple CSV Serializer from Michael Kropat found here: Generic class to CSV (all properties) and reused his methods to get the fields and properties of the wished class.
I deserialize my CSV file with the following method:
public static IEnumerable<T> ReadCsvFileTextFieldParser<T>(string fileFullPath, string delimiter = ";") where T : new()
{
if (!File.Exists(fileFullPath))
{
return null;
}
var list = new List<T>();
var csvFields = GetAllFieldOfClass<T>();
var fieldDict = new Dictionary<int, MemberInfo>();
using (TextFieldParser parser = new TextFieldParser(fileFullPath))
{
parser.SetDelimiters(delimiter);
bool headerParsed = false;
while (!parser.EndOfData)
{
//Processing row
string[] rowFields = parser.ReadFields();
if (!headerParsed)
{
for (int i = 0; i < rowFields.Length; i++)
{
// First row shall be the header!
var csvField = csvFields.Where(f => f.Name == rowFields[i]).FirstOrDefault();
if (csvField != null)
{
fieldDict.Add(i, csvField);
}
}
headerParsed = true;
}
else
{
T newObj = new T();
for (int i = 0; i < rowFields.Length; i++)
{
var csvFied = fieldDict[i];
var record = rowFields[i];
if (csvFied is FieldInfo)
{
((FieldInfo)csvFied).SetValue(newObj, record);
}
else if (csvFied is PropertyInfo)
{
var pi = (PropertyInfo)csvFied;
pi.SetValue(newObj, Convert.ChangeType(record, pi.PropertyType), null);
}
else
{
throw new Exception("Unhandled case.");
}
}
if (newObj != null)
{
list.Add(newObj);
}
}
}
}
return list;
}
public static IEnumerable<MemberInfo> GetAllFieldOfClass<T>()
{
return
from mi in typeof(T).GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
where new[] { MemberTypes.Field, MemberTypes.Property }.Contains(mi.MemberType)
let orderAttr = (ColumnOrderAttribute)Attribute.GetCustomAttribute(mi, typeof(ColumnOrderAttribute))
orderby orderAttr == null ? int.MaxValue : orderAttr.Order, mi.Name
select mi;
}
Instead of imageElement.src = myImage;
you should use window.location = myImage;
And even after that the browser will display the image itself. You can right click and use "Save Link" for downloading the image.
Check this link for more information.
Rather than using booleans, why not just set the button to false when its clicked, so you do that in your actionPerformed method. Its more efficient..
if (command.equals("w"))
{
FileConverter fc = new FileConverter();
btnConvertDocuments.setEnabled(false);
}
Be sure to check out verilog-mode and especially verilog-auto. http://www.veripool.org/wiki/verilog-mode/ It is a verilog mode for emacs, but plugins exist for vi(m?) for example.
An instantiation can be automated with AUTOINST. The comment is expanded with M-x verilog-auto
and can afterwards be manually edited.
subcomponent subcomponent_instance_name(/*AUTOINST*/);
Expanded
subcomponent subcomponent_instance_name (/*AUTOINST*/
//Inputs
.clk, (clk)
.rst_n, (rst_n)
.data_rx (data_rx_1[9:0]),
//Outputs
.data_tx (data_tx[9:0])
);
Implicit wires can be automated with /*AUTOWIRE*/
. Check the link for further information.
Here are 2 radio buttons namely rd1 and Radio1
<input type="radio" name="rd" id="rd1" />
<input type="radio" name="rd" id="Radio1" />
The simplest wayt to check which radio button is checked ,by checking individual is(":checked") property
if ($("#rd1").is(":checked")) {
alert("rd1 checked");
}
else {
alert("rd1 not checked");
}
Assuming that pwd
is just an example, this is how you can do it:
import subprocess
p = subprocess.Popen("pwd", stdout=subprocess.PIPE)
result = p.communicate()[0]
print result
See the subprocess documentation for another example and more information.
Instance of a class when compared with == comes to non-equal. The best way is to ass the cmp function to your class which will do the stuff.
If you want to do comparison by the content you can simply use cmp(obj1,obj2)
In your case cmp(doc1,doc2) It will return -1 if the content wise they are same.
You have to create custom pipe.
import { Injectable, Pipe } from '@angular/core';
@Pipe({
name: 'keyobject'
})
@Injectable()
export class Keyobject {
transform(value, args:string[]):any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]});
}
return keys;
}}
And then use it in your *ngFor
*ngFor="let item of data | keyobject"
Try this following program for 2d array in java:
public class ArrayTwo2 {
public static void main(String[] args) throws IOException,NumberFormatException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int[][] a;
int sum=0;
a=new int[3][2];
System.out.println("Enter array with 5 elements");
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[0].length;j++)
{
a[i][j]=Integer.parseInt(br.readLine());
}
}
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[0].length;j++)
{
System.out.print(a[i][j]+" ");
sum=sum+a[i][j];
}
System.out.println();
//System.out.println("Array Sum: "+sum);
sum=0;
}
}
}
I was having issue with connecting to MS SQL 2005 using Windows Authentication. I was able to solve the issue with help from this and other forums. Here is what I did:
My environment: Windows XP clinet hosting Apache Tomcat 6 with MS SQL 2005 backend on Windows 2003
First cast your Edit text like this:
TextView tekst = (TextView) findViewById(R.id.editText1);
tekst.setText(text);
And after that close the DB not befor this line...
myDataBaseHelper.close();
Try This...
Go to your notification area in the taskbar.
Right click on Bluestacks Agent>Rotate Portrait Apps>Enabled.
There are several options available..
a. Automatic - Selected By Default - It will rotate the app player in portrait mode for portrait apps.
b. Disabled - It will force the portrait apps to work in landscape mode.
c. Enabled - It will force the portrait apps to work in portrait mode only.
This May help you..
Use some javascript!
xmlhttp=new XMLHttpRequest(); xmlhttp.open('PUT',http://www.mydomain.org/documents/standards/browsers/supportlist) xmlhttp.send("page content goes here");
The function below will return the x86 Program Files
directory in all of these three Windows configurations:
static string ProgramFilesx86()
{
if( 8 == IntPtr.Size
|| (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"))))
{
return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
}
return Environment.GetEnvironmentVariable("ProgramFiles");
}
IIF
is not a standard SQL construct, but if it's supported by your database, you can achieve a more elegant statement producing the same result:
SELECT JobId, JobName,
COUNT(IIF (Priority=1, 1, NULL)) AS Priority1,
COUNT(IIF (Priority=2, 1, NULL)) AS Priority2,
COUNT(IIF (Priority=3, 1, NULL)) AS Priority3,
COUNT(IIF (Priority=4, 1, NULL)) AS Priority4,
COUNT(IIF (Priority=5, 1, NULL)) AS Priority5
FROM TableName
GROUP BY JobId, JobName
Use Hosts Commander. It's simple and powerful. Translated description (from russian) here.
hosts add another.dev 192.168.1.1 # Remote host
hosts add test.local # 127.0.0.1 used by default
hosts set myhost.dev # new comment
hosts rem *.local
hosts enable local*
hosts disable localhost
...and many others...
Usage:
hosts - run hosts command interpreter
hosts <command> <params> - execute hosts command
Commands:
add <host> <aliases> <addr> # <comment> - add new host
set <host|mask> <addr> # <comment> - set ip and comment for host
rem <host|mask> - remove host
on <host|mask> - enable host
off <host|mask> - disable host
view [all] <mask> - display enabled and visible, or all hosts
hide <host|mask> - hide host from 'hosts view'
show <host|mask> - show host in 'hosts view'
print - display raw hosts file
format - format host rows
clean - format and remove all comments
rollback - rollback last operation
backup - backup hosts file
restore - restore hosts file from backup
recreate - empty hosts file
open - open hosts file in notepad
$string = "producturl.php?id=736375493?=tm";
$number = preg_replace("/[^0-9]/", '', $string);
Sometimes when it is destroyed, an object must make an action. For example, if an object has a non-java resource such as a file handle or a font, you can verify that these resources are released before destroying an object. To manage such situations, java offers a mechanism called "finalizing". By finalizing it, you can define specific actions that occur when an object is about to be removed from the garbage collector. To add a finalizer to a class simply define the finalize() method. Java execution time calls this method whenever it is about to delete an object of that class. Within the finalize method() you specify actions to be performed before destroying an object. The garbage collector is periodically searched for objects that no longer refer to any running state or indirectly any other object with reference. Before an asset is released, the Java runtime calls the finalize() method on the object. The finalize() method has the following general form:
protected void finalize(){
// This is where the finalization code is entered
}
With the protected keyword, access to finalize() by code outside its class is prevented. It is important to understand that finalize() is called just just before the garbage collection. It is not called when an object leaves the scope, for example. It means you can not know when, or if, finalize() will be executed. As a result, the program must provide other means to free system resources or other resources used by the object. You should not rely on finalize() for normal running of the program.
In some cases it's very useful to change font-size with relative font sizing units. For example:
.btn {font-size: 3vw;}
Demo: http://www.bootply.com/7VN5OCVhhF
1vw is 1% of the viewport width. More info: http://www.sitepoint.com/new-css3-relative-font-size/
Damir is correct,
Your subquery needs to ensure that dps_user.id equals um.profile_id, otherwise it will grab the top row which might, but probably not equal your id of 'u162231993'
Your query should look like this:
SELECT u.id, mbg.marker_value
FROM dps_user u
LEFT JOIN
(SELECT TOP 1 m.marker_value, um.profile_id
FROM dps_usr_markers um (NOLOCK)
INNER JOIN dps_markers m (NOLOCK)
ON m.marker_id= um.marker_id AND
m.marker_key = 'moneyBackGuaranteeLength'
WHERE u.id = um.profile_id
ORDER BY m.creation_date
) MBG ON MBG.profile_id=u.id
WHERE u.id = 'u162231993'
Alright so I know this answer is old, but I found out how to do this for version 3.1.4. So for me this error occurs whenever I put in a new item into the hierarchy, so I knew I needed a solution. After tinkering around for a little bit I found how to do it by following these steps:
Provided that that method still works, after step two you should see squiggly lines going horizontally across where the item is, and after step three, both horizontally and vertically. After step three, the error will go away!
The curl installed by default in Debian supports HTTPS since a great while back. (a long time ago there were two separate packages, one with and one without SSL but that's not the case anymore)
You can send an OPTIONS request with curl like this:
curl -i -X OPTIONS http://example.org/path
You may also use -v
instead of -i
to see more output.
To send a plain * (instead of the path, see RFC 7231) with the OPTIONS method, you need curl 7.55.0 or later as then you can run a command line like:
curl -i --request-target "*" -X OPTIONS http://example.org
The quick answer is to use innerHTML (or prototype's update method which pretty much the same thing). The problem with innerHTML is you need to escape the content being assigned. Depending on your targets you will need to do that with other code OR
in IE:-
document.getElementById("field_name").innerText = newText;
in FF:-
document.getElementById("field_name").textContent = newText;
(Actually of FF have the following present in by code)
HTMLElement.prototype.__defineGetter__("innerText", function () { return this.textContent; })
HTMLElement.prototype.__defineSetter__("innerText", function (inputText) { this.textContent = inputText; })
Now I can just use innerText if you need widest possible browser support then this is not a complete solution but neither is using innerHTML in the raw.
I wrote a quick program to find these seeds:
import java.lang.*;
import java.util.*;
import java.io.*;
public class RandomWords {
public static void main (String[] args) {
Set<String> wordSet = new HashSet<String>();
String fileName = (args.length > 0 ? args[0] : "/usr/share/dict/words");
readWordMap(wordSet, fileName);
System.err.println(wordSet.size() + " words read.");
findRandomWords(wordSet);
}
private static void readWordMap (Set<String> wordSet, String fileName) {
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim().toLowerCase();
if (isLowerAlpha(line)) wordSet.add(line);
}
}
catch (IOException e) {
System.err.println("Error reading from " + fileName + ": " + e);
}
}
private static boolean isLowerAlpha (String word) {
char[] c = word.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] < 'a' || c[i] > 'z') return false;
}
return true;
}
private static void findRandomWords (Set<String> wordSet) {
char[] c = new char[256];
Random r = new Random();
for (long seed0 = 0; seed0 >= 0; seed0++) {
for (int sign = -1; sign <= 1; sign += 2) {
long seed = seed0 * sign;
r.setSeed(seed);
int i;
for (i = 0; i < c.length; i++) {
int n = r.nextInt(27);
if (n == 0) break;
c[i] = (char)((int)'a' + n - 1);
}
String s = new String(c, 0, i);
if (wordSet.contains(s)) {
System.out.println(s + ": " + seed);
wordSet.remove(s);
}
}
}
}
}
I have it running in the background now, but it's already found enough words for a classic pangram:
import java.lang.*;
import java.util.*;
public class RandomWordsTest {
public static void main (String[] args) {
long[] a = {-73, -157512326, -112386651, 71425, -104434815,
-128911, -88019, -7691161, 1115727};
for (int i = 0; i < a.length; i++) {
Random r = new Random(a[i]);
StringBuilder sb = new StringBuilder();
int n;
while ((n = r.nextInt(27)) > 0) sb.append((char)('`' + n));
System.out.println(sb);
}
}
}
Ps. -727295876, -128911, -1611659, -235516779
.
If you don't want the HTML to be escaped, look at the safe
filter and the autoescape
tag:
safe
:
{{ myhtml |safe }}
{% autoescape off %}
{{ myhtml }}
{% endautoescape %}
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
*
* @author Xiao Ma
* mail : [email protected]
*
*/
public class SimilarityUtil {
public static double consineTextSimilarity(String[] left, String[] right) {
Map<String, Integer> leftWordCountMap = new HashMap<String, Integer>();
Map<String, Integer> rightWordCountMap = new HashMap<String, Integer>();
Set<String> uniqueSet = new HashSet<String>();
Integer temp = null;
for (String leftWord : left) {
temp = leftWordCountMap.get(leftWord);
if (temp == null) {
leftWordCountMap.put(leftWord, 1);
uniqueSet.add(leftWord);
} else {
leftWordCountMap.put(leftWord, temp + 1);
}
}
for (String rightWord : right) {
temp = rightWordCountMap.get(rightWord);
if (temp == null) {
rightWordCountMap.put(rightWord, 1);
uniqueSet.add(rightWord);
} else {
rightWordCountMap.put(rightWord, temp + 1);
}
}
int[] leftVector = new int[uniqueSet.size()];
int[] rightVector = new int[uniqueSet.size()];
int index = 0;
Integer tempCount = 0;
for (String uniqueWord : uniqueSet) {
tempCount = leftWordCountMap.get(uniqueWord);
leftVector[index] = tempCount == null ? 0 : tempCount;
tempCount = rightWordCountMap.get(uniqueWord);
rightVector[index] = tempCount == null ? 0 : tempCount;
index++;
}
return consineVectorSimilarity(leftVector, rightVector);
}
/**
* The resulting similarity ranges from -1 meaning exactly opposite, to 1
* meaning exactly the same, with 0 usually indicating independence, and
* in-between values indicating intermediate similarity or dissimilarity.
*
* For text matching, the attribute vectors A and B are usually the term
* frequency vectors of the documents. The cosine similarity can be seen as
* a method of normalizing document length during comparison.
*
* In the case of information retrieval, the cosine similarity of two
* documents will range from 0 to 1, since the term frequencies (tf-idf
* weights) cannot be negative. The angle between two term frequency vectors
* cannot be greater than 90°.
*
* @param leftVector
* @param rightVector
* @return
*/
private static double consineVectorSimilarity(int[] leftVector,
int[] rightVector) {
if (leftVector.length != rightVector.length)
return 1;
double dotProduct = 0;
double leftNorm = 0;
double rightNorm = 0;
for (int i = 0; i < leftVector.length; i++) {
dotProduct += leftVector[i] * rightVector[i];
leftNorm += leftVector[i] * leftVector[i];
rightNorm += rightVector[i] * rightVector[i];
}
double result = dotProduct
/ (Math.sqrt(leftNorm) * Math.sqrt(rightNorm));
return result;
}
public static void main(String[] args) {
String left[] = { "Julie", "loves", "me", "more", "than", "Linda",
"loves", "me" };
String right[] = { "Jane", "likes", "me", "more", "than", "Julie",
"loves", "me" };
System.out.println(consineTextSimilarity(left,right));
}
}
This issue may be because of the incompatibility of firefox driver and your firefox browser version. Download the latest version of firefox driver which is compatible with the updated Firefox browser version.
Not a direct answer to the OP's question, but inspired by and perhaps useful for some.. I've created an object-based solution using the internal __dict__
(In no way optimized code)
payload = {
"name": "John",
"location": {
"lat": 53.12312312,
"long": 43.21345112
},
"numbers": [
{
"role": "home",
"number": "070-12345678"
},
{
"role": "office",
"number": "070-12345679"
}
]
}
class Map(object):
"""
Dot style access to object members, access raw values
with an underscore e.g.
class Foo(Map):
def foo(self):
return self.get('foo') + 'bar'
obj = Foo(**{'foo': 'foo'})
obj.foo => 'foobar'
obj._foo => 'foo'
"""
def __init__(self, *args, **kwargs):
for arg in args:
if isinstance(arg, dict):
for k, v in arg.iteritems():
self.__dict__[k] = v
self.__dict__['_' + k] = v
if kwargs:
for k, v in kwargs.iteritems():
self.__dict__[k] = v
self.__dict__['_' + k] = v
def __getattribute__(self, attr):
if hasattr(self, 'get_' + attr):
return object.__getattribute__(self, 'get_' + attr)()
else:
return object.__getattribute__(self, attr)
def get(self, key):
try:
return self.__dict__.get('get_' + key)()
except (AttributeError, TypeError):
return self.__dict__.get(key)
def __repr__(self):
return u"<{name} object>".format(
name=self.__class__.__name__
)
class Number(Map):
def get_role(self):
return self.get('role')
def get_number(self):
return self.get('number')
class Location(Map):
def get_latitude(self):
return self.get('lat') + 1
def get_longitude(self):
return self.get('long') + 1
class Item(Map):
def get_name(self):
return self.get('name') + " Doe"
def get_location(self):
return Location(**self.get('location'))
def get_numbers(self):
return [Number(**n) for n in self.get('numbers')]
# Tests
obj = Item({'foo': 'bar'}, **payload)
assert type(obj) == Item
assert obj._name == "John"
assert obj.name == "John Doe"
assert type(obj.location) == Location
assert obj.location._lat == 53.12312312
assert obj.location._long == 43.21345112
assert obj.location.latitude == 54.12312312
assert obj.location.longitude == 44.21345112
for n in obj.numbers:
assert type(n) == Number
if n.role == 'home':
assert n.number == "070-12345678"
if n.role == 'office':
assert n.number == "070-12345679"
Similar in spirit to the Haskell-style solution by @crl, but working with reduce
:
function permutations( base ) {
if (base.length == 0) return [[]]
return permutations( base.slice(1) ).reduce( function(acc,perm) {
return acc.concat( base.map( function(e,pos) {
var new_perm = perm.slice()
new_perm.splice(pos,0,base[0])
return new_perm
}))
},[])
}
There is no built in function with this capability. The close would be to save the file in a folder named for the current date and use the =INFO("directory") function.
shell("C:\Users\USERNAME\AppData\Local\Google\Chrome\Application\Chrome.exe -url http:google.ca")
Another way to effectively guard against a null in a for loop is to wrap your collection with Google Guava's Optional<T>
as this, one hopes, makes the possibility of an effectively empty collection clear since the client would be expected to check if the collection is present with Optional.isPresent()
.
You can use that form:
return returnValue.Equals("1") ? true : false;
Or more simply (thanks to Jurijs Kastanovs):
return returnValue.Equals("1");
Maybe something like this:
connected = False
while not connected:
try:
try_connect()
connected = True
except ...:
pass
If the command that you are trying to execute fails, it would write the output onto the error stream and would then be printed out to the console.
To avoid it, you must redirect the error stream:
result=$(ls -l something_that_does_not_exist 2>&1)
All of these three solutions give the same results if the input is a string:
1.
def reverse(text):
result = ""
for i in range(len(text),0,-1):
result += text[i-1]
return (result)
2.
text[::-1]
3.
"".join(reversed(text))
Numeric defines the TOTAL number of digits, and then the number after the decimal.
A numeric(3,2) can only hold up to 9.99.
This is a side note if one still can't access localhost from another devices after following through the step above. This might be due to the apache ports.conf has been configured to serve locally (127.0.0.1) and not to outside.
check the following, (for ubuntu apache2)
$ cat /etc/apache2/ports.conf
if the following is set,
NameVirtualHost *:80
Listen 127.0.0.1:80
then change it back to default value
NameVirtualHost *:80
Listen 80
The below solution worked for me for the core-plot 2.3 version. Do the below changes under other linker flags section.
1.Add $(inherited) and drag this item to top position 2.Remove "Pods-" prefix from -l"Pods-fmemopen”, l"Pods-NSAttributedStringMarkdownParser” and -l"Pods-MagicalRecord”.
if still issue persists, Finally see if PODS_ROOT is set or not. You can check it under user defined section.
Old question but this answer might help someone.
If you are trying to display the contents of the container outside of the boundaries of the container, make sure that it doesn't have overflow:hidden
, otherwise anything outside of it will be cut off.
I used this command to activate cron job for this.
/usr/bin/php -q /home/username/public_html/yourfilename.php
on godaddy server, and its working fine.
Try adding the following to your JS on bootply
$('#myModal2').on('show.bs.modal', function () {
$('#myModal').css('z-index', 1030); })
$('#myModal2').on('hidden.bs.modal', function () {
$('#myModal').css('z-index', 1040); })
Explanation:
After playing around with the attributes(using Chrome's dev tool), I have realized that any z-index
value below 1031
will put things behind the backdrop.
So by using bootstrap's modal event handles I set the z-index
to 1030
. If #myModal2
is shown and set the z-index
back to 1040
if #myModal2
is hidden.
Java's Double
class has members containing the Min and Max value for the type.
2^-1074 <= x <= (2-2^-52)·2^1023 // where x is the double.
Check out the Min_VALUE
and MAX_VALUE
static final members of Double
.
(some)People will suggest against using floating point types for things where accuracy and precision are critical because rounding errors can throw off calculations by measurable (small) amounts.
IntelliJ IDEA detects errors and warnings in the current file on the fly (unless Power Save Mode is activated in the File
menu).
Errors in other files and in the project view will be shown after Build
| Make
and listed in the Messages tool window.
For Bazel users: Project errors will show on Bazel Problems tool window after running Compile Project
(Ctrl/Cmd+F9)
To navigate between errors use Navigate
| Next Highlighted Error
(F2) / Previous Highlighted Error
(Shift+F2).
Error Stripe Mark color can be changed here:
object.__del__(self)
is called when the instance is about to be destroyed.
>>> class Test:
... def __del__(self):
... print "deleted"
...
>>> test = Test()
>>> del test
deleted
Object is not deleted unless all of its references are removed(As quoted by ethan)
Also, From Python official doc reference:
del x doesn’t directly call x.del() — the former decrements the reference count for x by one, and the latter is only called when x‘s reference count reaches zero
You don't need initialization lists for that:
std::vector<int> vector1(length, 0);
std::vector<double> vector2(length, 0.0);
Try
import sys
print(sys.version)
This prints the full version information string. If you only want the python version number, then Bastien Léonard's solution is the best. You might want to examine the full string and see if you need it or portions of it.
Based on @Martin Wantke answer, but with some recommended improvements/adjusts...
// NOTE: Check JavaScript type. By Questor
function getJSType(valToChk) {
function isUndefined(valToChk) { return valToChk === undefined; }
function isNull(valToChk) { return valToChk === null; }
function isArray(valToChk) { return valToChk.constructor == Array; }
function isBoolean(valToChk) { return valToChk.constructor == Boolean; }
function isFunction(valToChk) { return valToChk.constructor == Function; }
function isNumber(valToChk) { return valToChk.constructor == Number; }
function isString(valToChk) { return valToChk.constructor == String; }
function isObject(valToChk) { return valToChk.constructor == Object; }
if(isUndefined(valToChk)) { return "undefined"; }
if(isNull(valToChk)) { return "null"; }
if(isArray(valToChk)) { return "array"; }
if(isBoolean(valToChk)) { return "boolean"; }
if(isFunction(valToChk)) { return "function"; }
if(isNumber(valToChk)) { return "number"; }
if(isString(valToChk)) { return "string"; }
if(isObject(valToChk)) { return "object"; }
}
NOTE: I found this approach very didactic, so I submitted this answer.
In my experience, printf()
hauls in more code than puts()
regardless of the format string.
If I don't need the formatting, I don't use printf
. However, fwrite
to stdout
works a lot faster than puts
.
static const char my_text[] = "Using fwrite.\n";
fwrite(my_text, 1, sizeof(my_text) - sizeof('\0'), stdout);
Note: per comments, '\0' is an integer constant. The correct expression should be sizeof(char)
as indicated by the comments.
To me it happened in DogController
that autowired DogService
that autowired DogRepository
. Dog
class used to have field name
but I changed it to coolName
, but didn't change methods in DogRepository
: Dog findDogByName(String name)
. I change that method to Dog findDogByCoolName(String name)
and now it works.
Try
function readFile(file) {
return new Promise((resolve, reject) => {
let fr = new FileReader();
fr.onload = x=> resolve(fr.result);
fr.readAsText(file);
})}
but user need to take action to choose file
function readFile(file) {_x000D_
return new Promise((resolve, reject) => {_x000D_
let fr = new FileReader();_x000D_
fr.onload = x=> resolve(fr.result);_x000D_
fr.readAsText(file);_x000D_
})}_x000D_
_x000D_
async function read(input) {_x000D_
msg.innerText = await readFile(input.files[0]);_x000D_
}
_x000D_
<input type="file" onchange="read(this)"/>_x000D_
<h3>Content:</h3><pre id="msg"></pre>
_x000D_
If you want to retrieve the display text of the item, use the GetItemText
method:
string text = listBox1.GetItemText(listBox1.SelectedItem);
One trick you can use to increase the number of concurrent connections is to host your images from a different sub domain. These will be treated as separate requests, each domain is what will be limited to the concurrent maximum.
IE6, IE7 - have a limit of two. IE8 is 6 if you have a broadband - 2 (if it's a dial up).
JFrame.dispose() affects only to this frame (release all of the native screen resources used by this component, its subcomponents, and all children). System.exit() affects to entire JVM.
If you want to close all JFrame or all Window (since Frames extend Windows) to terminate the application in an ordered mode, you can do some like this:
Arrays.asList(Window.getWindows()).forEach(e -> e.dispose()); // or JFrame.getFrames()
start "" "%SYSTEMDRIVE%\Program Files (x86)\Git\bin\sh.exe" --login -i
Git bash will get open.
There is also some simple way to control minification (and other features) manually. It's new CssMinify() transformer using, like this:
// this is in case when BundleTable.EnableOptimizations = false;
var myBundle = new StyleBundle("~/Content/themes/base/css")
.Include("~/Content/themes/base/jquery.ui.core.css" /* , ... and so on */);
myBundle.Transforms.Add(new CssMinify());
bundles.Add(myBundle);
// or you can remove that transformer in opposite situation
myBundle.Transforms.Clear();
That's convenient when you want to have some bundles special part only to be minified. Let's say, you are using some standard (jQuery) styles, which are getting under your feet (taking lots of excessive browser requests to them), but you want to keep unminified your own stylesheet. (The same - with javascript).
I felt the below approach is very easy.
I have declared an interface for callback
public interface AsyncResponse {
void processFinish(Object output);
}
Then created asynchronous Task for responding all type of parallel requests
public class MyAsyncTask extends AsyncTask<Object, Object, Object> {
public AsyncResponse delegate = null;//Call back interface
public MyAsyncTask(AsyncResponse asyncResponse) {
delegate = asyncResponse;//Assigning call back interfacethrough constructor
}
@Override
protected Object doInBackground(Object... params) {
//My Background tasks are written here
return {resutl Object}
}
@Override
protected void onPostExecute(Object result) {
delegate.processFinish(result);
}
}
Then Called the asynchronous task when clicking a button in activity Class.
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
Button mbtnPress = (Button) findViewById(R.id.btnPress);
mbtnPress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyAsyncTask asyncTask =new MyAsyncTask(new AsyncResponse() {
@Override
public void processFinish(Object output) {
Log.d("Response From Asynchronous task:", (String) output);
mbtnPress.setText((String) output);
}
});
asyncTask.execute(new Object[] { "Youe request to aynchronous task class is giving here.." });
}
});
}
}
Thanks
For anyone needs to change the options of the menu dynamically:
private Menu menu;
// ...
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
this.menu = menu;
getMenuInflater().inflate(R.menu.options, menu);
return true;
}
// ...
private void hideOption(int id)
{
MenuItem item = menu.findItem(id);
item.setVisible(false);
}
private void showOption(int id)
{
MenuItem item = menu.findItem(id);
item.setVisible(true);
}
private void setOptionTitle(int id, String title)
{
MenuItem item = menu.findItem(id);
item.setTitle(title);
}
private void setOptionIcon(int id, int iconRes)
{
MenuItem item = menu.findItem(id);
item.setIcon(iconRes);
}
If you like 'Mike Sherrill' solution but don't want to use psql, I used this query to get the missing information:
select column_name,
case
when domain_name is not null then domain_name
when data_type='character varying' THEN 'varchar('||character_maximum_length||')'
when data_type='numeric' THEN 'numeric('||numeric_precision||','||numeric_scale||')'
else data_type
end as myType
from information_schema.columns
where table_name='test'
with result:
column_name | myType
-------------+-------------------
test_id | test_domain
test_vc | varchar(15)
test_n | numeric(15,3)
big_n | bigint
ip_addr | inet
The problem here was a typo error in the password used, which was not easily identified due to the characters / letters used in the password.
I created a PS script to check idle time and jiggle the mouse to prevent the screensaver.
There are two parameters you can control how it works.
$checkIntervalInSeconds
: the interval in seconds to check if the idle time exceeds the limit
$preventIdleLimitInSeconds
: the idle time limit in seconds. If the idle time exceeds the idle time limit, jiggle the mouse to prevent the screensaver
Here we go. Save the script in preventIdle.ps1
. For preventing the 4-min screensaver, I
set $checkIntervalInSeconds = 30
and $preventIdleLimitInSeconds = 180
.
Add-Type @'
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace PInvoke.Win32 {
public static class UserInput {
[DllImport("user32.dll", SetLastError=false)]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
[StructLayout(LayoutKind.Sequential)]
private struct LASTINPUTINFO {
public uint cbSize;
public int dwTime;
}
public static DateTime LastInput {
get {
DateTime bootTime = DateTime.UtcNow.AddMilliseconds(-Environment.TickCount);
DateTime lastInput = bootTime.AddMilliseconds(LastInputTicks);
return lastInput;
}
}
public static TimeSpan IdleTime {
get {
return DateTime.UtcNow.Subtract(LastInput);
}
}
public static double IdleSeconds {
get {
return IdleTime.TotalSeconds;
}
}
public static int LastInputTicks {
get {
LASTINPUTINFO lii = new LASTINPUTINFO();
lii.cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO));
GetLastInputInfo(ref lii);
return lii.dwTime;
}
}
}
}
'@
Add-Type @'
using System;
using System.Runtime.InteropServices;
namespace MouseMover
{
public class MouseSimulator
{
[DllImport("user32.dll", SetLastError = true)]
static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetCursorPos(out POINT lpPoint);
[StructLayout(LayoutKind.Sequential)]
struct INPUT
{
public SendInputEventType type;
public MouseKeybdhardwareInputUnion mkhi;
}
[StructLayout(LayoutKind.Explicit)]
struct MouseKeybdhardwareInputUnion
{
[FieldOffset(0)]
public MouseInputData mi;
[FieldOffset(0)]
public KEYBDINPUT ki;
[FieldOffset(0)]
public HARDWAREINPUT hi;
}
[StructLayout(LayoutKind.Sequential)]
struct KEYBDINPUT
{
public ushort wVk;
public ushort wScan;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
struct HARDWAREINPUT
{
public int uMsg;
public short wParamL;
public short wParamH;
}
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
this.X = x;
this.Y = y;
}
}
struct MouseInputData
{
public int dx;
public int dy;
public uint mouseData;
public MouseEventFlags dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[Flags]
enum MouseEventFlags : uint
{
MOUSEEVENTF_MOVE = 0x0001
}
enum SendInputEventType : int
{
InputMouse
}
public static void MoveMouseBy(int x, int y) {
INPUT mouseInput = new INPUT();
mouseInput.type = SendInputEventType.InputMouse;
mouseInput.mkhi.mi.dwFlags = MouseEventFlags.MOUSEEVENTF_MOVE;
mouseInput.mkhi.mi.dx = x;
mouseInput.mkhi.mi.dy = y;
SendInput(1, ref mouseInput, Marshal.SizeOf(mouseInput));
}
}
}
'@
$checkIntervalInSeconds = 30
$preventIdleLimitInSeconds = 180
while($True) {
if (([PInvoke.Win32.UserInput]::IdleSeconds -ge $preventIdleLimitInSeconds)) {
[MouseMover.MouseSimulator]::MoveMouseBy(10,0)
[MouseMover.MouseSimulator]::MoveMouseBy(-10,0)
}
Start-Sleep -Seconds $checkIntervalInSeconds
}
Then, open Windows PowerShell and run
powershell -ExecutionPolicy ByPass -File C:\SCRIPT-DIRECTORY-PATH\preventIdle.ps1
The difference between List and LinkedList lies in their underlying implementation. List is array based collection (ArrayList). LinkedList is node-pointer based collection (LinkedListNode). On the API level usage, both of them are pretty much the same since both implement same set of interfaces such as ICollection, IEnumerable, etc.
The key difference comes when performance matter. For example, if you are implementing the list that has heavy "INSERT" operation, LinkedList outperforms List. Since LinkedList can do it in O(1) time, but List may need to expand the size of underlying array. For more information/detail you might want to read up on the algorithmic difference between LinkedList and array data structures. http://en.wikipedia.org/wiki/Linked_list and Array
Hope this help,
Look at the following example code:
public class MyWorker
{
public SharedData state;
public void DoWork(SharedData someData)
{
this.state = someData;
while (true) ;
}
}
public class SharedData {
X myX;
public getX() { etc
public setX(anX) { etc
}
public class Program
{
public static void Main()
{
SharedData data = new SharedDate()
MyWorker work1 = new MyWorker(data);
MyWorker work2 = new MyWorker(data);
Thread thread = new Thread(new ThreadStart(work1.DoWork));
thread.Start();
Thread thread2 = new Thread(new ThreadStart(work2.DoWork));
thread2.Start();
}
}
In this case, the thread class MyWorker
has a variable state
. We initialise it with the same object. Now you can see that the two workers access the same SharedData object. Changes made by one worker are visible to the other.
You have quite a few remaining issues. How does worker 2 know when changes have been made by worker 1 and vice-versa? How do you prevent conflicting changes? Maybe read: this tutorial.
LDAP is trying to authenticate with AD when sending a transaction to another server DB. This authentication fails because the user has recently changed her password, although this transaction was generated using the previous credentials. This authentication will keep failing until ... unless you change the transaction status to Complete or Cancel in which case LDAP will stop sending these transactions.
From the error, I infer that referenceElement
is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).
>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'
You probably meant either for element in referenceElement.keys()
or for element in json['referenceElement'].keys()
. With more context on what types json
and referenceElement
are and what they contain, we will be able to better help you if neither solution works.
I believe you need to create a file called __init__.py
in the Models directory so that python treats it as a module.
Then you can do:
from Models.user import User
You can include code in the __init__.py
(for instance initialization code that a few different classes need) or leave it blank. But it must be there.
I think you means the difference between DELETE TABLE and TRUNCATE TABLE.
DROP TABLE
remove the table from the database.
DELETE TABLE
without a condition delete all rows. If there are trigger and references then this will process for every row. Also a index will be modify if there one.
TRUNCATE TABLE
set the row count zero and without logging each row. That it is many faster as the other both.
The Heap is divided into young and old generations as follows :
Young Generation: It is a place where an object lived for a short period and it is divided into two spaces:
Old Generation: This pool basically contains tenured and virtual (reserved) space and will be holding those objects which survived after garbage collection from the Young Generation.
Explanation
Let's imagine our application has just started.
So at this point all three of these spaces are empty (Eden, S0, S1).
Whenever a new object is created it is placed in the Eden space.
When the Eden space gets full then the garbage collection process (minor GC) will take place on the Eden space and any surviving objects are moved into S0.
Our application then continues running add new objects are created in the Eden space the next time that the garbage collection process runs it looks at everything in the Eden space and in S0 and any objects that survive get moved into S1.
PS: Based on the configuration that how much time object should survive in Survivor space, the object may also move back and forth to S0 and S1 and then reaching the threshold objects will be moved to old generation heap space.
The JavaScript Object()
constructor makes an Object that you can assign members to.
myObj = new Object()
myObj.key = value;
myObj[key2] = value2; // Alternative
Another thing you can try (based on tvanfosson's answer) is this:
<div class="renderaction fade-in"
data-actionurl="@Url.Action("details","user", new { id = Model.ID } )"></div>
And then in the scripts section of your page:
<script type="text/javascript">
$(function () {
$(".renderaction").each(function (i, n) {
var $n = $(n),
url = $n.attr('data-actionurl'),
$this = $(this);
$.get(url, function (data) {
$this.html(data);
});
});
});
</script>
This renders your @Html.RenderAction using ajax.
And to make it all fansy sjmansy you can add a fade-in effect using this css:
/* make keyframes that tell the start state and the end state of our object */
@-webkit-keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
@-moz-keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
@keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
.fade-in {
opacity: 0; /* make things invisible upon start */
-webkit-animation: fadeIn ease-in 1; /* call our keyframe named fadeIn, use animattion ease-in and repeat it only 1 time */
-moz-animation: fadeIn ease-in 1;
-o-animation: fadeIn ease-in 1;
animation: fadeIn ease-in 1;
-webkit-animation-fill-mode: forwards; /* this makes sure that after animation is done we remain at the last keyframe value (opacity: 1)*/
-o-animation-fill-mode: forwards;
animation-fill-mode: forwards;
-webkit-animation-duration: 1s;
-moz-animation-duration: 1s;
-o-animation-duration: 1s;
animation-duration: 1s;
}
Man I love mvc :-)
Copy the downloaded DLL file in a custom folder on your dev drive, then add the reference to your project using the Browse button in the Add Reference
dialog.
Be sure that the new reference has the Copy Local = True
.
The Add Reference
dialog could be opened right-clicking on the References item in your project in Solution Explorer
UPDATE AFTER SOME YEARS
At the present time the best way to resolve all those problems is through the
Manage NuGet packages menu command of Visual Studio 2017/2019.
You can right click on the References node of your project and select that command. From the Browse tab search for the library you want to use in the NuGet repository, click on the item if found and then Install it. (Of course you need to have a package for that DLL and this is not guaranteed to exist)
Have you tried:
ifconfig 10:35978f0 down
As the physical interface is 10
and the virtual aspect is after the colon :
.
See also https://www.cyberciti.biz/faq/linux-command-to-remove-virtual-interfaces-or-network-aliases/
I found that the useful getResources().getColor(R.color.color_name) is deprecated.
It is not deprecated in API Level 21, according to the documentation.
It is deprecated in the M Developer Preview. However, the replacement method (a two-parameter getColor()
that takes the color resource ID and a Resources.Theme
object) is only available in the M Developer Preview.
Hence, right now, continue using the single-parameter getColor()
method. Later this year, consider using the two-parameter getColor()
method on Android M devices, falling back to the deprecated single-parameter getColor()
method on older devices.
If you or some other fox who need to have link with Icon Image and text as link text beside the image see bellow code:
CSS
.linkWithImageIcon{
Display:inline-block;
}
.MyLink{
Background:#FF3300;
width:200px;
height:70px;
vertical-align:top;
display:inline-block; font-weight:bold;
}
.MyLinkText{
/*---The margin depends on how the image size is ---*/
display:inline-block; margin-top:5px;
}
HTML
<a href="#" class="MyLink"><img src="./yourImageIcon.png" /><span class="MyLinkText">SIGN IN</span></a>
if you see the image the white portion is image icon and other is style this way you can create different buttons with any type of Icons you want to design
if val is not None:
# ...
is the Pythonic idiom for testing that a variable is not set to None
. This idiom has particular uses in the case of declaring keyword functions with default parameters. is
tests identity in Python. Because there is one and only one instance of None
present in a running Python script/program, is
is the optimal test for this. As Johnsyweb points out, this is discussed in PEP 8 under "Programming Recommendations".
As for why this is preferred to
if not (val is None):
# ...
this is simply part of the Zen of Python: "Readability counts." Good Python is often close to good pseudocode.
Based on ARS81's answer (that only matches class names beginning with), here's a more flexible version. Also a hasClass()
regex version.
Usage: $('.selector').removeClassRegex('\\S*-foo[0-9]+')
$.fn.removeClassRegex = function(name) {
return this.removeClass(function(index, css) {
return (css.match(new RegExp('\\b(' + name + ')\\b', 'g')) || []).join(' ');
});
};
$.fn.hasClassRegex = function(name) {
return this.attr('class').match(new RegExp('\\b(' + name + ')\\b', 'g')) !== null;
};
The onselect
must be onclick
. This will work for keyboard users.
I would also recommend adding <label>
tags to the text of "Day", "Month", and "Year" to make them easier to click on. Example code:
<input id="day" name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')"/><label for="day">Day</label>
I would also recommend removing the spaces between the attribute onclick
and the value, although it can be parsed by browsers:
<input name="calendarSelection" type="radio" onclick = "go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')"/>Day
Should be:
<input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')"/>Day
20090320093349
SELECT CONVERT(VARCHAR,@date,112) +
LEFT(REPLACE(CONVERT(VARCHAR,@date,114),':',''),6)
The simplest and least verbose way to autowire your Hibernate SessionFactory is:
This is the solution for Spring Boot 1.x with Hibernate 4:
application.properties:
spring.jpa.properties.hibernate.current_session_context_class=
org.springframework.orm.hibernate4.SpringSessionContext
Configuration class:
@Bean
public HibernateJpaSessionFactoryBean sessionFactory() {
return new HibernateJpaSessionFactoryBean();
}
Then you can autowire the SessionFactory
in your services as usual:
@Autowired
private SessionFactory sessionFactory;
As of Spring Boot 1.5 with Hibernate 5, this is now the preferred way:
application.properties:
spring.jpa.properties.hibernate.current_session_context_class=
org.springframework.orm.hibernate5.SpringSessionContext
Configuration class:
@EnableAutoConfiguration
...
...
@Bean
public HibernateJpaSessionFactoryBean sessionFactory(EntityManagerFactory emf) {
HibernateJpaSessionFactoryBean fact = new HibernateJpaSessionFactoryBean();
fact.setEntityManagerFactory(emf);
return fact;
}
self.tableView.tableHeaderView = segmentedControl;
If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.
// This is the exact code for search facility in datagridview.
private void buttonSearch_Click(object sender, EventArgs e)
{
string searchValue=textBoxSearch.Text;
int rowIndex = 1; //this one is depending on the position of cell or column
//string first_row_data=dataGridView1.Rows[0].Cells[0].Value.ToString() ;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
bool valueResulet = true;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[rowIndex].Value.ToString().Equals(searchValue))
{
rowIndex = row.Index;
dataGridView1.Rows[rowIndex].Selected = true;
rowIndex++;
valueResulet = false;
}
}
if (valueResulet != false)
{
MessageBox.Show("Record is not avalable for this Name"+textBoxSearch.Text,"Not Found");
return;
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
The solution to this is actually easier than I thought. You can simply add in your custom adapter's getView()
method a setOnClickListener() for the buttons you're using.
Any data associated with the button has to be added with myButton.setTag()
in the getView()
and can be accessed in the onClickListener via view.getTag()
I posted a detailed solution on my blog as a tutorial.
I had the same problem, and I was using the following plugin for tests:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<useFile>true</useFile>
<includes>
<include>**/*Tests.java</include>
<include>**/*Test.java</include>
</includes>
<excludes>
<exclude>**/Abstract*.java</exclude>
</excludes>
<junitArtifactName>junit:junit</junitArtifactName>
<parallel>methods</parallel>
<threadCount>10</threadCount>
</configuration>
</plugin>
The test were running fine in the IDE (eclipse sts), but failed when using command mvn test.
After a lot of trial and error, I figured the solution was to remove parallel testing, the following two lines from the plugin configuration above:
<parallel>methods</parallel>
<threadCount>10</threadCount>
Hope that this helps someone out!
In
x ? "yes" : "no"
the ? declares an if sentence. Here: x represents the boolean condition; The part before the : is the then sentence and the part after is the else sentence.
In, for example,
int?
the ? declares a nullable type, and means that the type before it may have a null value.
The method which you are using is rendering login button from the Facebook Javascript code. However, you can write your own Javascript code function to mimic the functionality. Here is how to do it -
onclick
method on anchor tag which would actually do the real job.<a href="#" onclick="fb_login();"><img src="images/fb_login_awesome.jpg" border="0" alt=""></a>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID',
oauth : true,
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
function fb_login(){
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
//console.log(response); // dump complete info
access_token = response.authResponse.accessToken; //get access token
user_id = response.authResponse.userID; //get FB UID
FB.api('/me', function(response) {
user_email = response.email; //get user email
// you can store this data into your database
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'public_profile,email'
});
}
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
Please note that the above function is fully tested and works. You just need to put your facebook APP ID and it will work.
To make reading of this page more valuable (for future search results) I made a list of libraries known to me.. As @CommonsWare mentioned there are super-similar questions/answers.. Anyway some libraries that can be used for making charts are:
Open Source:
Paid:
** - means I didn't try those so I can't really recommend it but other users suggested it..
I use this:
git log --name-status <branch>..<branch> | grep -E '^[A-Z]\b' | sort | uniq
which outputs a list of files only and their state (added, modified, deleted):
A sites/api/branding/__init__.py
M sites/api/branding/wtv/mod.py
...
An example of an IF Statement that can be used to add a calculation into the cell you wish to hide if value = 0 but displayed upon another cell value reference.
=IF(/Your reference cell/=0,"",SUM(/Here you put your SUM/))
Use getattr
to get an attribute from a name in a string. In other words, get the instance as
instance = getattr(modul, class_name)()
It looks like you want to use a list instead:
group=[]
for i in range(3):
group[i]=self.getGroup(selected, header+i)
Here is complete demo code to understand client side and server side process. you can copy paste it and just replace google site key and google secret key.
<?php
if(!empty($_REQUEST))
{
// echo '<pre>'; print_r($_REQUEST); die('END');
$post = [
'secret' => 'Your Secret key',
'response' => $_REQUEST['g-recaptcha-response'],
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
echo '<pre>'; print_r($server_output); die('ss');
}
?>
<html>
<head>
<title>reCAPTCHA demo: Explicit render for multiple widgets</title>
<script type="text/javascript">
var site_key = 'Your Site key';
var verifyCallback = function(response) {
alert(response);
};
var widgetId1;
var widgetId2;
var onloadCallback = function() {
// Renders the HTML element with id 'example1' as a reCAPTCHA widget.
// The id of the reCAPTCHA widget is assigned to 'widgetId1'.
widgetId1 = grecaptcha.render('example1', {
'sitekey' : site_key,
'theme' : 'light'
});
widgetId2 = grecaptcha.render(document.getElementById('example2'), {
'sitekey' : site_key
});
grecaptcha.render('example3', {
'sitekey' : site_key,
'callback' : verifyCallback,
'theme' : 'dark'
});
};
</script>
</head>
<body>
<!-- The g-recaptcha-response string displays in an alert message upon submit. -->
<form action="javascript:alert(grecaptcha.getResponse(widgetId1));">
<div id="example1"></div>
<br>
<input type="submit" value="getResponse">
</form>
<br>
<!-- Resets reCAPTCHA widgetId2 upon submit. -->
<form action="javascript:grecaptcha.reset(widgetId2);">
<div id="example2"></div>
<br>
<input type="submit" value="reset">
</form>
<br>
<!-- POSTs back to the page's URL upon submit with a g-recaptcha-response POST parameter. -->
<form action="?" method="POST">
<div id="example3"></div>
<br>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
</body>
</html>
works
scp localhost:"f/a\ b\ c" .
scp localhost:'f/a\ b\ c' .
does not work
scp localhost:'f/a b c' .
The reason is that the string is interpreted by the shell before the path is passed to the scp command. So when it gets to the remote the remote is looking for a string with unescaped quotes and it fails
To see this in action, start a shell with the -vx options ie bash -vx
and it will display the interpolated version of the command as it runs it.
Recursive function :
function getElementInsideElement(baseElement, wantedElementID) {
var elementToReturn;
for (var i = 0; i < baseElement.childNodes.length; i++) {
elementToReturn = baseElement.childNodes[i];
if (elementToReturn.id == wantedElementID) {
return elementToReturn;
} else {
return getElementInsideElement(elementToReturn, wantedElementID);
}
}
}
You can use IIF for a similar result.
Note that you can nest the IIF statements to handle multiple cases. There is an example here: http://forums.devshed.com/database-management-46/query-ms-access-iif-statement-multiple-conditions-358130.html
SELECT IIf([Combinaison] = "Mike", 12, IIf([Combinaison] = "Steve", 13)) As Answer
FROM MyTable;
Here's a quick example:
termList = []
termList.append(('term1', [1,2,3,4]))
termList.append(('term2', [5,6,7,8]))
termList.append(('term3', [9,10,11,12]))
result = [x[1] for x in termList if x[0] == 'term3']
print(result)
On the other hand, the following is a valid comment, pulled directly from a working application:
render () {
return <DeleteResourceButton
//confirm
onDelete={this.onDelete.bind(this)}
message="This file will be deleted from the server."
/>
}
Apparantly, when inside the angle brackets of a JSX element, the //
syntax is valid, but the {/**/}
is invalid. The following breaks:
render () {
return <DeleteResourceButton
{/*confirm*/}
onDelete={this.onDelete.bind(this)}
message="This file will be deleted from the server."
/>
}
I know this is an old question but here is my answer that solved it for me. I had gone through all of the articles I could find and tried everything. It would not work for me on a mac or PC.
Solution: Use another USB cable.
I must have grabbed a poor quality cable that did not support file transfers. I used a different USB cable and immediately got prompted for ptp mode and authorization for remote debugging.
This is my solution, HTML & CSS only for a back to top button, also my first post.
Fixed header of two lines at top of page, when scrolled 2nd line (with links) moves to top and is fixed. Links are Home, another page, Back, Top
<h1 class="center italic fixedheader">
Some Text <span class="small">- That describes your site or page</span>
<br>
<a href="index.htm">🏠 Home</a> <a href=
"gen.htm">👪 Gen</a> <a href="#"
onclick="history.go(-1);return false;">👈 Back</a> <a href=
enter code here "#">👆 Top</a>
</h1>
<style>
.fixedheader {
margin: auto;
overflow: hidden;
background-color: inherit;
position: sticky;
top: -1.25em;
width: 100%;
border: .65em hidden inherit;
/* white solid border hides any bleed through at top and lowers text */
}
</style>
80 % of the times, this would due to wrong input by in soapRequest.xml file
To see non-staged (non-added) changes to existing files
git diff
Note that this does not track new files. To see staged, non-commited changes
git diff --cached
Just in case you don't want to use stored proc, here's a simple query version
select *
from information_schema.columns
where table_name = 'aspnet_Membership'
order by ordinal_position
It is disappointing that many databases do not stick to the standard rules and add extra characters, or incorrectly enable ESCAPE with a default value of ‘\’ when it is missing. Like we don't already have enough trouble with ‘\’!
It's impossible to write DBMS-independent code here, because you don't know what characters you're going to have to escape, and the standard says you can't escape things that don't need to be escaped. (See section 8.5/General Rules/3.a.ii.)
Thank you SQL! gnnn
Your examples, I think, answer the question very well. The first function can be done as a single select, and is a good reason to use the inline style. The second could probably be done as a single statement (using a sub-query to get the max date), but some coders may find it easier to read or more natural to do it in multiple statements as you have done. Some functions just plain can't get done in one statement, and so require the multi-statement version.
I suggest using the simplest (inline) whenever possible, and using multi-statements when necessary (obviously) or when personal preference/readability makes it wirth the extra typing.
You can also use LocalDate.parse()
or LocalDateTime.parse()
on a String
without providing it with a pattern, if the String
is in ISO-8601 format.
for example,
String strDate = "2015-08-04";
LocalDate aLD = LocalDate.parse(strDate);
System.out.println("Date: " + aLD);
String strDatewithTime = "2015-08-04T10:11:30";
LocalDateTime aLDT = LocalDateTime.parse(strDatewithTime);
System.out.println("Date with Time: " + aLDT);
Output,
Date: 2015-08-04
Date with Time: 2015-08-04T10:11:30
and use DateTimeFormatter
only if you have to deal with other date patterns.
For instance, in the following example, dd MMM uuuu represents the day of the month (two digits), three letters of the name of the month (Jan, Feb, Mar,...), and a four-digit year:
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd MMM uuuu");
String anotherDate = "04 Aug 2015";
LocalDate lds = LocalDate.parse(anotherDate, dTF);
System.out.println(anotherDate + " parses to " + lds);
Output
04 Aug 2015 parses to 2015-08-04
also remember that the DateTimeFormatter
object is bidirectional; it can both parse input and format output.
String strDate = "2015-08-04";
LocalDate aLD = LocalDate.parse(strDate);
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd MMM uuuu");
System.out.println(aLD + " formats as " + dTF.format(aLD));
Output
2015-08-04 formats as 04 Aug 2015
(see complete list of Patterns for Formatting and Parsing DateFormatter)
Symbol Meaning Presentation Examples
------ ------- ------------ -------
G era text AD; Anno Domini; A
u year year 2004; 04
y year-of-era year 2004; 04
D day-of-year number 189
M/L month-of-year number/text 7; 07; Jul; July; J
d day-of-month number 10
Q/q quarter-of-year number/text 3; 03; Q3; 3rd quarter
Y week-based-year year 1996; 96
w week-of-week-based-year number 27
W week-of-month number 4
E day-of-week text Tue; Tuesday; T
e/c localized day-of-week number/text 2; 02; Tue; Tuesday; T
F week-of-month number 3
a am-pm-of-day text PM
h clock-hour-of-am-pm (1-12) number 12
K hour-of-am-pm (0-11) number 0
k clock-hour-of-am-pm (1-24) number 0
H hour-of-day (0-23) number 0
m minute-of-hour number 30
s second-of-minute number 55
S fraction-of-second fraction 978
A milli-of-day number 1234
n nano-of-second number 987654321
N nano-of-day number 1234000000
V time-zone ID zone-id America/Los_Angeles; Z; -08:30
z time-zone name zone-name Pacific Standard Time; PST
O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00;
X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15;
x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;
Z zone-offset offset-Z +0000; -0800; -08:00;
p pad next pad modifier 1
' escape for text delimiter
'' single quote literal '
[ optional section start
] optional section end
# reserved for future use
{ reserved for future use
} reserved for future use
In the DRF version 3.6.3 this worked for me
class ItemSerializer(serializers.ModelSerializer):
category_name = serializers.CharField(source='category.name')
class Meta:
model = Item
fields = ('id', 'name', 'category_name')
More info can be found here: Serializer Fields core arguments
Now Junit5 provides a way to assert the exceptions
You can test both general exceptions and customized exceptions
A general exception scenario:
ExpectGeneralException.java
public void validateParameters(Integer param ) {
if (param == null) {
throw new NullPointerException("Null parameters are not allowed");
}
}
ExpectGeneralExceptionTest.java
@Test
@DisplayName("Test assert NullPointerException")
void testGeneralException(TestInfo testInfo) {
final ExpectGeneralException generalEx = new ExpectGeneralException();
NullPointerException exception = assertThrows(NullPointerException.class, () -> {
generalEx.validateParameters(null);
});
assertEquals("Null parameters are not allowed", exception.getMessage());
}
You can find a sample to test CustomException here : assert exception code sample
ExpectCustomException.java
public String constructErrorMessage(String... args) throws InvalidParameterCountException {
if(args.length!=3) {
throw new InvalidParameterCountException("Invalid parametercount: expected=3, passed="+args.length);
}else {
String message = "";
for(String arg: args) {
message += arg;
}
return message;
}
}
ExpectCustomExceptionTest.java
@Test
@DisplayName("Test assert exception")
void testCustomException(TestInfo testInfo) {
final ExpectCustomException expectEx = new ExpectCustomException();
InvalidParameterCountException exception = assertThrows(InvalidParameterCountException.class, () -> {
expectEx.constructErrorMessage("sample ","error");
});
assertEquals("Invalid parametercount: expected=3, passed=2", exception.getMessage());
}
Try this one:
Actions builder = new Actions(fDriver);
builder.keyDown(Keys.CONTROL)
.click(element)
.dragAndDrop(element, elementDropped)
.keyUp(Keys.CONTROL);
Action selected = builder.build();
selected.perform();
Decision tree between ES5, ES6 and TypeScript
Do you mind having a build step?
Do you want to use types?
ES5 is the JavaScript you know and use in the browser today it is what it is and does not require a build step to transform it into something that will run in today's browsers
ES6 (also called ES2015) is the next iteration of JavaScript, but it does not run in today's browsers. There are quite a few transpilers that will export ES5 for running in browsers. It is still a dynamic (read: untyped) language.
TypeScript provides an optional typing system while pulling in features from future versions of JavaScript (ES6 and ES7).
Note: a lot of the transpilers out there (i.e. babel, TypeScript) will allow you to use features from future versions of JavaScript today and exporting code that will still run in today's browsers.
Change secret_string += str(chr(char + 7429146))
To secret_string += chr(ord(char) + 7429146)
ord()
converts the character to its Unicode integer equivalent. chr()
then converts this integer into its Unicode character equivalent.
Also, 7429146 is too big of a number, it should be less than 1114111
It's top google stackoverflow question, but all answers are not jQuery related!
$(".someclass").click(
function(event)
{
console.log(event, this);
}
);
'event' contains 2 important values:
event.currentTarget - element to which event is triggered ('.someclass' element)
event.target - element clicked (in case when inside '.someclass' [div] are other elements and you clicked on of them)
this - is set to triggered element ('.someclass'), but it's JavaScript element, not jQuery element, so if you want to use some jQuery function on it, you must first change it to jQuery element: $(this)
When your refresh the page and reload the scripts again; this method not work. You have to use jquery "unbind" method.
AFAIK there's no built in method in the framework that will allow you to do this. You could check this post for a suggestion on determining framework version by reading windows registry values.
<< Mean any given number will be multiply by 2the power
for exp:- 2<<2=2*2'1=4
6<<2'4=6*2*2*2*2*2=64
=>
is used in associative array key value assignment. Take a look at:
http://php.net/manual/en/language.types.array.php.
->
is used to access an object method or property. Example: $obj->method()
.
The objects in the std::set
are stored as const StudentT
. So when you try to call getId()
with the const
object the compiler detects a problem, mainly you're calling a non-const member function on const object which is not allowed because non-const member functions make NO PROMISE not to modify the object; so the compiler is going to make a safe assumption that getId()
might attempt to modify the object but at the same time, it also notices that the object is const; so any attempt to modify the const object should be an error. Hence compiler generates an error message.
The solution is simple: make the functions const as:
int getId() const {
return id;
}
string getName() const {
return name;
}
This is necessary because now you can call getId()
and getName()
on const objects as:
void f(const StudentT & s)
{
cout << s.getId(); //now okay, but error with your versions
cout << s.getName(); //now okay, but error with your versions
}
As a sidenote, you should implement operator<
as :
inline bool operator< (const StudentT & s1, const StudentT & s2)
{
return s1.getId() < s2.getId();
}
Note parameters are now const
reference.
In addition to return false as Jason Cohen mentioned. You may have to also preventDefault
e.preventDefault();
First of all, Thanks to code author!
I found the below link while googling and it is very simple and works best. Would never fail unless SVG is deprecated.
https://codepen.io/moistpaint/pen/ywFDe/
There is some js loading error in the code here but its perfectly working on the codepen.io link provided.
var mapOptions = {_x000D_
zoom: 16,_x000D_
center: new google.maps.LatLng(-37.808846, 144.963435)_x000D_
};_x000D_
map = new google.maps.Map(document.getElementById('map-canvas'),_x000D_
mapOptions);_x000D_
_x000D_
_x000D_
var pinz = [_x000D_
{_x000D_
'location':{_x000D_
'lat' : -37.807817,_x000D_
'lon' : 144.958377_x000D_
},_x000D_
'lable' : 2_x000D_
},_x000D_
{_x000D_
'location':{_x000D_
'lat' : -37.807885,_x000D_
'lon' : 144.965415_x000D_
},_x000D_
'lable' : 42_x000D_
},_x000D_
{_x000D_
'location':{_x000D_
'lat' : -37.811377,_x000D_
'lon' : 144.956596_x000D_
},_x000D_
'lable' : 87_x000D_
},_x000D_
{_x000D_
'location':{_x000D_
'lat' : -37.811293,_x000D_
'lon' : 144.962883_x000D_
},_x000D_
'lable' : 145_x000D_
},_x000D_
{_x000D_
'location':{_x000D_
'lat' : -37.808089,_x000D_
'lon' : 144.962089_x000D_
},_x000D_
'lable' : 999_x000D_
},_x000D_
];_x000D_
_x000D_
_x000D_
_x000D_
for(var i = 0; i <= pinz.length; i++){_x000D_
var image = 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2238%22%20height%3D%2238%22%20viewBox%3D%220%200%2038%2038%22%3E%3Cpath%20fill%3D%22%23808080%22%20stroke%3D%22%23ccc%22%20stroke-width%3D%22.5%22%20d%3D%22M34.305%2016.234c0%208.83-15.148%2019.158-15.148%2019.158S3.507%2025.065%203.507%2016.1c0-8.505%206.894-14.304%2015.4-14.304%208.504%200%2015.398%205.933%2015.398%2014.438z%22%2F%3E%3Ctext%20transform%3D%22translate%2819%2018.5%29%22%20fill%3D%22%23fff%22%20style%3D%22font-family%3A%20Arial%2C%20sans-serif%3Bfont-weight%3Abold%3Btext-align%3Acenter%3B%22%20font-size%3D%2212%22%20text-anchor%3D%22middle%22%3E' + pinz[i].lable + '%3C%2Ftext%3E%3C%2Fsvg%3E';_x000D_
_x000D_
_x000D_
var myLatLng = new google.maps.LatLng(pinz[i].location.lat, pinz[i].location.lon);_x000D_
var marker = new google.maps.Marker({_x000D_
position: myLatLng,_x000D_
map: map,_x000D_
icon: image_x000D_
});_x000D_
}
_x000D_
html, body, #map-canvas {_x000D_
height: 100%;_x000D_
margin: 0px;_x000D_
padding: 0px_x000D_
}
_x000D_
<div id="map-canvas"></div>_x000D_
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDtc3qowwB96ObzSu2vvjEoM2pVhZRQNSA&signed_in=true&callback=initMap&libraries=drawing,places"></script>
_x000D_
You just need to uri-encode your SVG html and replace the one in the image variable after "data:image/svg+xml" in the for loop.
For uri encoding you can use uri-encoder-decoder
You can decode the existing svg code first to get a better understanding of what is written.
What do you want to validate? The email address?
The email address can only be checked for its format conformance. See the standard: RFC2822. Best way to do that is a regular expression. You will never know if really exists without sending an email.
I checked the commons validator. It contains an org.apache.commons.validator.EmailValidator class. Seems to be a good starting point.
Somehow after 45 posts and 10 years, no one has posted the correct answer for my case.
@Data //Lombok
public class MyClass {
private int foo;
private int bar;
@JsonIgnore
public int getFoobar() {
return foo + bar;
}
}
In my case, we have a method called getFoobar()
, but no foobar
property (because it's computed from other properties). @JsonIgnoreProperties
on the class does not work.
The solution is to annotate the method with @JsonIgnore
The finite repetition syntax uses {m,n}
in place of star/plus/question mark.
From java.util.regex.Pattern
:
X{n} X, exactly n times
X{n,} X, at least n times
X{n,m} X, at least n but not more than m times
All repetition metacharacter have the same precedence, so just like you may need grouping for *
, +
, and ?
, you may also for {n,m}
.
ha*
matches e.g. "haaaaaaaa"
ha{3}
matches only "haaa"
(ha)*
matches e.g. "hahahahaha"
(ha){3}
matches only "hahaha"
Also, just like *
, +
, and ?
, you can add the ?
and +
reluctant and possessive repetition modifiers respectively.
System.out.println(
"xxxxx".replaceAll("x{2,3}", "[x]")
); "[x][x]"
System.out.println(
"xxxxx".replaceAll("x{2,3}?", "[x]")
); "[x][x]x"
Essentially anywhere a *
is a repetition metacharacter for "zero-or-more", you can use {...}
repetition construct. Note that it's not true the other way around: you can use finite repetition in a lookbehind, but you can't use *
because Java doesn't officially support infinite-length lookbehind.
.*
and .*?
for regexregex{n,}?
== regex{n}
?a{1}b{0,1}
instead of ab?
list_1.insert(0,ur_data)
make sure that ur_data is of string type
so if u have data= int(5)
convert it to ur_data = str(data)
Some explanation ignore a condition about the retain cycle [If a group of objects is connected by a circle of strong relationships, they keep each other alive even if there are no strong references from outside the group.] For more information, read the document
I just got exactly this error when doing "git pull" when my disk was full. Created some space and it all started working fine again.
new Guid(string)
You could also look at using a TypeConverter
.
Doing
logEvent.timeStamp / (1000*60*60)
will give you hours, not minutes. Try:
logEvent.timeStamp / (1000*60)
and you will end up with the same answer as
TimeUnit.MILLISECONDS.toMinutes(logEvent.timeStamp)
For separation of concern, I would suggest you use action filter for model validation, so you don't need to care much how to do validation in your api controller:
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace System.Web.Http.Filters
{
public class ValidationActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var modelState = actionContext.ModelState;
if (!modelState.IsValid)
actionContext.Response = actionContext.Request
.CreateErrorResponse(HttpStatusCode.BadRequest, modelState);
}
}
}
Interestingly none of the answers mentioned that And
and Or
in VB.NET are bit operators whereas OrElse
and AndAlso
are strictly Boolean operators.
Dim a = 3 OR 5 ' Will set a to the value 7, 011 or 101 = 111
Dim a = 3 And 5 ' Will set a to the value 1, 011 and 101 = 001
Dim b = 3 OrElse 5 ' Will set b to the value true and not evaluate the 5
Dim b = 3 AndAlso 5 ' Will set b to the value true after evaluating the 5
Dim c = 0 AndAlso 5 ' Will set c to the value false and not evaluate the 5
Note: a non zero integer is considered true
; Dim e = not 0
will set e
to -1
demonstrating Not
is also a bit operator.
||
and &&
(the C# versions of OrElse
and AndAlso
) return the last evaluated expression which would be 3
and 5
respectively. This lets you use the idiom v || 5
in C# to give 5
as the value of the expression when v
is null
or (0
and an integer) and the value of v
otherwise. The difference in semantics can catch a C# programmer dabbling in VB.NET off guard as this "default value idiom" doesn't work in VB.NET.
So, to answer the question: Use Or
and And
for bit operations (integer or Boolean). Use OrElse
and AndAlso
to "short circuit" an operation to save time, or test the validity of an evaluation prior to evaluating it. If valid(evaluation) andalso evaluation then
or if not (unsafe(evaluation) orelse (not evaluation)) then
Bonus: What is the value of the following?
Dim e = Not 0 And 3