The suggested answer only works for certain versions of ruby. Some commenters suggest using ruby-dev; that didn't work for me either.
sudo apt-get install ruby-all-dev
worked for me.
On rails 3, the simpliest way is rails s
.
In rails 2, you can use ./script/server start
.
You can also use another servers, like thin or unicorn, that also provide more performance.
I use unicorn, you can easily start it with unicorn_rails
.
BTW, if you use another things, like a worker (sidekiq, resque, etc), I strongly recommend you to use foreman, so you can start all your jobs in one terminal windows with one command and get a unified log.
I had the same problem, ruby-1.8.7-p357, and tried loads of things in vain...
I finally realised that it happens only on multiple calls using the same XMLRPC::Client instance!
So now I'm re-instantiating my client at each call and it just works:|
$(document).ready(function(){
$('#ckbCheckAll').click(function(event) {
if($(this).is(":checked")) {
$('.checkBoxClass').each(function(){
$(this).prop("checked",true);
});
}
else{
$('.checkBoxClass').each(function(){
$(this).prop("checked",false);
});
}
});
});
Another way:
x=$'Some\nstring'
readarray -t y <<<"$x"
Or, if you don't have bash 4, the bash 3.2 equivalent:
IFS=$'\n' read -rd '' -a y <<<"$x"
You can also do it the way you were initially trying to use:
y=(${x//$'\n'/ })
This, however, will not function correctly if your string already contains spaces, such as 'line 1\nline 2'
. To make it work, you need to restrict the word separator before parsing it:
IFS=$'\n' y=(${x//$'\n'/ })
...and then, since you are changing the separator, you don't need to convert the \n
to space
anymore, so you can simplify it to:
IFS=$'\n' y=($x)
This approach will function unless $x
contains a matching globbing pattern (such as "*
") - in which case it will be replaced by the matched file name(s). The read
/readarray
methods require newer bash versions, but work in all cases.
If you need (for example) a two digit approximation for A, then
int(A*100+0.5)/100.0
will do what you are looking for.
If you need three digit approximation multiply and divide by 1000 and so on.
Bas Brekelmans's answer is very elegant in its simplicity. But, I found that for an actual application a little more is needed such as:
The class here handles these limitations: http://www.codeproject.com/Articles/31315/Getting-User-Input-With-Dialogs-Part-1
I just downloaded source and copied InputBox.cs into my project.
Surprised there isn't something even better though... My only real complaint is it caption text doesn't support newlines in it since it uses a label control.
For someone who doesn't want to use inline JS.
<select data-select-name>
<option value="">Select...</option>
<option value="http://google.com">Google</option>
<option value="http://yahoo.com">Yahoo</option>
</select>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('select[data-select-name]').onchange=changeEventHandler;
},false);
function changeEventHandler(event) {
window.location.href = this.options[this.selectedIndex].value;
}
</script>
To Answer your first question, Jenkins variables are case sensitive. However, if you are writing a windows batch script, they are case insensitive, because Windows doesn't care about the case.
Since you are not very clear about your setup, let's make the assumption that you are using an ant build step to fire up your ant task. Have a look at the Jenkins documentation (same page that Adarsh gave you, but different chapter) for an example on how to make Jenkins variables available to your ant task.
EDIT:
Hence, I will need to access the environmental variable ${BUILD_NUMBER} to construct the URL.
Why don't you use $BUILD_URL
then? Isn't it available in the extended email plugin?
I prefer to use git-bash.exe instead of sh.exe.
start "" "%ProgramFiles%\Git\git-bash.exe" -c "tail -f /c/Windows/win.ini"
You can stop closing the window when call /usr/bin/bash --login -i
in the end;
start "" "%ProgramFiles%\Git\git-bash.exe" -c "echo 1 && echo 2 && /usr/bin/bash --login -i"
Note: I'm not sure this is a good way :)
If you want to be able access the matrix like so matrix[i][j]
I find it the most convinient to init it in a loop.
var matrix = [],
cols = 3;
//init the grid matrix
for ( var i = 0; i < cols; i++ ) {
matrix[i] = [];
}
this will give you [ [], [], [] ]
so matrix[0][0] matrix[1][0] return undefined and not the error "Uncaught TypeError: Cannot set property '0' of undefined"
I had the same issue after having upgraded go1.2 to go1.4.
I renamed src to _src in my GOPATH then did a go get -v
It worked then I deleted _src.
Hope it helps.
$("#singlechatpanel-1").is(':visible');
$("#singlechatpanel-1").is(':hidden');
The "string to long" (strtol
) function is standard for this ("long" can hold numbers much larger than "int"). This is how to use it:
#include <stdlib.h>
long arg = strtol(argv[1], NULL, 10);
// string to long(string, endpointer, base)
Since we use the decimal system, base is 10. The endpointer
argument will be set to the "first invalid character", i.e. the first non-digit. If you don't care, set the argument to NULL
instead of passing a pointer, as shown.
If you don't want non-digits to occur, you should make sure it's set to the "null terminator", since a \0
is always the last character of a string in C:
#include <stdlib.h>
char* p;
long arg = strtol(argv[1], &p, 10);
if (*p != '\0') // an invalid character was found before the end of the string
As the man page mentions, you can use errno
to check that no errors occurred (in this case overflows or underflows).
#include <stdlib.h>
#include <errno.h>
char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
return 1; // In main(), returning non-zero means failure
}
// Everything went well, print it as 'long decimal'
printf("%ld", arg);
So now we are stuck with this long
, but we often want to work with integers. To convert a long
into an int
, we should first check that the number is within the limited capacity of an int
. To do this, we add a second if-statement, and if it matches, we can just cast it.
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
return 1; // In main(), returning non-zero means failure
}
if (arg < INT_MIN || arg > INT_MAX) {
return 1;
}
int arg_int = arg;
// Everything went well, print it as a regular number
printf("%d", arg_int);
To see what happens if you don't do this check, test the code without the INT_MIN
/MAX
if-statement. You'll see that if you pass a number larger than 2147483647 (231), it will overflow and become negative. Or if you pass a number smaller than -2147483648 (-231-1), it will underflow and become positive. Values beyond those limits are too large to fit in an integer.
#include <stdio.h> // for printf()
#include <stdlib.h> // for strtol()
#include <errno.h> // for errno
#include <limits.h> // for INT_MIN and INT_MAX
int main(int argc, char** argv) {
char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
return 1; // In main(), returning non-zero means failure
}
if (arg < INT_MIN || arg > INT_MAX) {
return 1;
}
int arg_int = arg;
// Everything went well, print it as a regular number plus a newline
printf("Your value was: %d\n", arg_int);
return 0;
}
In Bash, you can test this with:
cc code.c -o example # Compile, output to 'example'
./example $((2**31-1)) # Run it
echo "exit status: $?" # Show the return value, also called 'exit status'
Using 2**31-1
, it should print the number and 0
, because 231-1 is just in range. If you pass 2**31
instead (without -1
), it will not print the number and the exit status will be 1
.
Beyond this, you can implement custom checks: test whether the user passed an argument at all (check argc
), test whether the number is in the range that you want, etc.
Doesn't have to be; "64-bit machine" can mean many things, but typically means that the CPU has registers that big. The sizeof a type is determined by the compiler, which doesn't have to have anything to do with the actual hardware (though it typically does); in fact, different compilers on the same machine can have different values for these.
Once you have the file-loader configured in the webpack.config, whenever you use import/require it tests the path against all loaders, and in case there is a match it passes the contents through that loader. In your case, it matched
{
test: /\.(jpe?g|png|gif|svg)$/i,
loader: "file-loader?name=/public/icons/[name].[ext]"
}
// For newer versions of Webpack it should be
{
test: /\.(jpe?g|png|gif|svg)$/i,
loader: 'file-loader',
options: {
name: '/public/icons/[name].[ext]'
}
}
and therefore you see the image emitted to
dist/public/icons/imageview_item_normal.png
which is the wanted behavior.
The reason you are also getting the hash file name, is because you are adding an additional inline file-loader. You are importing the image as:
'file!../../public/icons/imageview_item_normal.png'.
Prefixing with file!
, passes the file into the file-loader again, and this time it doesn't have the name configuration.
So your import should really just be:
import img from '../../public/icons/imageview_item_normal.png'
Update
As noted by @cgatian, if you actually want to use an inline file-loader, ignoring the webpack global configuration, you can prefix the import with two exclamation marks (!!):
import '!!file!../../public/icons/imageview_item_normal.png'.
After importing the png, the img
variable only holds the path the file-loader "knows about", which is public/icons/[name].[ext]
(aka "file-loader? name=/public/icons/[name].[ext]"
). Your output dir "dist" is unknown.
You could solve this in two ways:
publicPath
property to your output config, that points to your output directory (in your case ./dist).Example:
output: {
path: PATHS.build,
filename: 'app.bundle.js',
publicPath: PATHS.build
},
In the current order? I'd say array_slice(). Since it's a built in function it will be faster than looping through the array while keeping track of an incrementing index until N.
This is working i Angular 8 without setTimeout:
import {AfterContentChecked, Directive, ElementRef} from '@angular/core';
@Directive({
selector: 'input[inputAutoFocus]'
})
export class InputFocusDirective implements AfterContentChecked {
constructor(private element: ElementRef<HTMLInputElement>) {}
ngAfterContentChecked(): void {
this.element.nativeElement.focus();
}
}
Explanation: Ok so this works because of: Change detection. It's the same reason that setTimout works, but when running a setTimeout in Angular it will bypass Zone.js and run all checks again, and it works because when the setTimeout is complete all changes are completed. With the correct lifecycle hook (AfterContentChecked) the same result can be be reached, but with the advantage that the extra cycle won't be run. The function will fire when all changes are checked and passed, and runs after the hooks AfterContentInit and DoCheck. If i'm wrong here please correct me.
More one lifecycles and change detection on https://angular.io/guide/lifecycle-hooks
UPDATE: I found an even better way to do this if one is using Angular Material CDK, the a11y-package. First import A11yModule in the the module declaring the component you have the input-field in. Then use cdkTrapFocus and cdkTrapFocusAutoCapture directives and use like this in html and set tabIndex on the input:
<div class="dropdown" cdkTrapFocus cdkTrapFocusAutoCapture>
<input type="text tabIndex="0">
</div>
We had some issues with our dropdowns regarding positioning and responsiveness and started using the OverlayModule from the cdk instead, and this method using A11yModule works flawlessly.
Here is how to add inline code:
You can add inline code with {\tt code }
or \texttt{ code }
. If you want to format the inline code, then it would be best to make your own command
\newcommand{\code}[1]{\texttt{#1}}
Also, note that code blocks can be loaded from other files with
\lstinputlisting[breaklines]{source.c}
breaklines
isn't required, but I find it useful. Be aware that you'll have to specify \usepackage{
listings }
for this one.
Update: The listings package also includes the \lstinline
command, which has the same syntax highlighting features as the \lstlisting
and \lstinputlisting
commands (see Cloudanger's answer for configuration details). As mentioned in a few other answers, there's also the minted package, which provides the \mintinline
command. Like \lstinline
, \mintinline
provides the same syntax highlighting as a regular minted code block:
\documentclass{article}
\usepackage{minted}
\begin{document}
This is a sentence with \mintinline{python}{def inlineCode(a="ipsum)}
\end{document}
Remember that the US date format is different from the UK. Using the UK format, it needs to be, e.g.
-- dd/mm/ccyy hh:mm:ss
dbo.no_time(at.date_stamp) between '22/05/2016 00:00:01' and '22/07/2016 23:59:59'
None of the listed solutions even attempt to parse a complex cron schedule string. So, here is my version, using croniter. Basic gist:
schedule = "*/5 * * * *" # Run every five minutes
nextRunTime = getNextCronRunTime(schedule)
while True:
roundedDownTime = roundDownTime()
if (roundedDownTime == nextRunTime):
####################################
### Do your periodic thing here. ###
####################################
nextRunTime = getNextCronRunTime(schedule)
elif (roundedDownTime > nextRunTime):
# We missed an execution. Error. Re initialize.
nextRunTime = getNextCronRunTime(schedule)
sleepTillTopOfNextMinute()
Helper routines:
from croniter import croniter
from datetime import datetime, timedelta
# Round time down to the top of the previous minute
def roundDownTime(dt=None, dateDelta=timedelta(minutes=1)):
roundTo = dateDelta.total_seconds()
if dt == None : dt = datetime.now()
seconds = (dt - dt.min).seconds
rounding = (seconds+roundTo/2) // roundTo * roundTo
return dt + timedelta(0,rounding-seconds,-dt.microsecond)
# Get next run time from now, based on schedule specified by cron string
def getNextCronRunTime(schedule):
return croniter(schedule, datetime.now()).get_next(datetime)
# Sleep till the top of the next minute
def sleepTillTopOfNextMinute():
t = datetime.utcnow()
sleeptime = 60 - (t.second + t.microsecond/1000000.0)
time.sleep(sleeptime)
You need to change from queue import Queue
to from multiprocessing import Queue
.
The root reason is the former Queue is designed for threading module Queue while the latter is for multiprocessing.Process module.
For details, you can read some source code or contact me!
Mark, this is already answered in your previous topic. But OK, here it is again:
Suppose ${list}
points to a List<Object>
, then the following
<c:forEach items="${list}" var="item">
${item}<br>
</c:forEach>
does basically the same as as following in "normal Java":
for (Object item : list) {
System.out.println(item);
}
If you have a List<Map<K, V>>
instead, then the following
<c:forEach items="${list}" var="map">
<c:forEach items="${map}" var="entry">
${entry.key}<br>
${entry.value}<br>
</c:forEach>
</c:forEach>
does basically the same as as following in "normal Java":
for (Map<K, V> map : list) {
for (Entry<K, V> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
The key
and value
are here not special methods or so. They are actually getter methods of Map.Entry
object (click at the blue Map.Entry
link to see the API doc). In EL (Expression Language) you can use the .
dot operator to access getter methods using "property name" (the getter method name without the get
prefix), all just according the Javabean specification.
That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".
As mentioned in the comments, the Starting Guide is the place to start with Java 11 and JavaFX 11.
The key to work as you did before Java 11 is to understand that:
JavaFX project
If you create a regular JavaFX default project in IntelliJ (without Maven or Gradle) I'd suggest you download the SDK from here. Note that there are jmods as well, but for a non modular project the SDK is preferred.
These are the easy steps to run the default project:
/Users/<user>/Downloads/javafx-sdk-11/lib/
. Once you do this you will notice that the JavaFX classes are now recognized in the editor.Before you run the default project, you just need to add these to the VM options:
--module-path /Users/<user>/Downloads/javafx-sdk-11/lib --add-modules=javafx.controls,javafx.fxml
Run
Maven
If you use Maven to build your project, follow these steps:
Add the JavaFX 11 dependencies.
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>11</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>11</version>
</dependency>
</dependencies>
Once you do this you will notice that the JavaFX classes are now recognized in the editor.
You will notice that Maven manages the required dependencies for you: it will add javafx.base and javafx.graphics for javafx.controls, but most important, it will add the required classifier based on your platform. In my case, Mac.
This is why your jars org.openjfx:javafx-controls:11
are empty, because there are three possible classifiers (windows, linux and mac platforms), that contain all the classes and the native implementation.
In case you still want to go to your .m2 repo and take the dependencies from there manually, make sure you pick the right one (for instance .m2/repository/org/openjfx/javafx-controls/11/javafx-controls-11-mac.jar
)
Replace default maven plugins with those from here.
Run mvn compile javafx:run
, and it should work.
Similar works as well for Gradle projects, as explained in detail here.
EDIT
The mentioned Getting Started guide contains updated documentation and sample projects for IntelliJ:
JavaFX 11 without Maven/Gradle, see non-modular sample or modular sample projects.
JavaFX 11 with Maven, see non-modular sample or modular sample projects.
JavaFX 11 with Gradle, see non-modular sample or modular sample projects.
If you use jQuery you can write:
$( _checkbox ).click( function( e ){ /*process event here*/ } )
Another way to list only the files is to use:
git diff-tree --no-commit-id --name-only -r HEAD^..HEAD
Or you can use any two commit IDs
You can adding a +
before the string without using parseInt and parseFloat and radix, Simply
sample:
var votevalue = +$('button').data('votevalue');
alert(typeof(votevalue));
Unfortunately, vars files do not have include statements.
You can either put all the vars into the definitions
dictionary, or add the variables as another dictionary in the same file.
If you don't want to have them in the same file, you can include them at the playbook level by adding the vars file at the start of the play:
---
- hosts: myhosts
vars_files:
- default_step.yml
or in a task:
---
- hosts: myhosts
tasks:
- name: include default step variables
include_vars: default_step.yml
The last line was creating a problem. lastIndex
would never be at -1, so there would be an infinite loop. This can be fixed by moving the last line of code into the if block.
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){
lastIndex = str.indexOf(findStr,lastIndex);
if(lastIndex != -1){
count ++;
lastIndex += findStr.length();
}
}
System.out.println(count);
This tool xsd2wsdl part of the Apache CXF project which will generate a minimalist WSDL.
.dex file
Compiled Android application code file.
Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created automatically by Android, by translating the compiled applications written in the Java programming language.
but watch out for this....
Long nullLong = null;
preparedStatement.setLong( nullLong );
-thows null pointer exception-
because the protype is
setLong( long )
NOT
setLong( Long )
nice one to catch you out eh.
Suppose you have defined your route name like this:
https://localhost:3000/user/:userid
which will become:
https://localhost:3000/user/5896544
Here, if you will print: request.params
{
userId : 5896544
}
so
request.params.userId = 5896544
so request.params is an object containing properties to the named route
and request.query comes from query parameters in the URL eg:
https://localhost:3000/user?userId=5896544
request.query
{
userId: 5896544
}
so
request.query.userId = 5896544
The legacy solution, before 1.6, was to use .attr
and handle the returned value as a bool
. The main problem is that the returned type of .attr
has changed to string
, and therefore the comparison with == true
is broken (see http://jsfiddle.net/2vene/1/ (and switch the jquery-version)).
With 1.6 .prop
was introduced, which returns a bool
.
Nevertheless, I suggest to use .is()
, as the returned type is intrinsically bool
, like:
$('#dropUnit').is(':disabled');
$('#dropUnit').is(':enabled');
Furthermore .is()
is much more natural (in terms of "natural language") and adds more conditions than a simple attribute-comparison (eg: .is(':last')
, .is(':visible')
, ... please see documentation on selectors).
"C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Binn\Sqlservr.exe"
or if you feel brave, locate the alias in the registry and delete it there.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo\
You can put the Link component inside the Router componet. Something like this:
<Router>
<Route path='/complete-profiles' component={Profiles} />
<Link to='/complete-profiles'>
<div>Completed Profiles</div>
</Link>
</Router>
Select mymethod()
and press ctrl+alt+h.
To see some detailed Information about any method you can use this by selecting that particular Object or method and right click. you can see the "OpenCallHierarchy" (Ctrl+Alt+H). Like that many tools are there to make your work Easier like "Quick Outline" (Ctrl+O) to view the Datatypes and methods declared in a particular .java file.
To know more about this, refer this eclipse Reference
You will either have to document.write
it or use the Document Object Model:
document.write
<script type="text/javascript">
if(document.getElementById('number1').checked) {
document.write("<h1>Hello member</h1>");
}
</script>
<h1></h1> <!-- We are targeting this tag with JS. See code below -->
<input type="checkbox" id="number1" checked /><label for="number1">Agree</label>
<div id="container"> <p>Content</p> </div>
<script type="text/javascript">
window.onload = function() {
if( document.getElementById('number1').checked ) {
var h1 = document.createElement("h1");
h1.appendChild(document.createTextNode("Hello member"));
document.getElementById("container").appendChild(h1);
}
}
</script>
In MomentJs We can declare it like :
const start = moment().format('YYYY-MM-DD 00:00:01');
const end = moment().format('YYYY-MM-DD 23:59:59');
I try to avoid floating elements unless the design really needs it. Because you have floated the <li>
they are out of normal flow.
If you add .navigation { text-align:center; }
and change .navigation li { float: left; }
to .navigation li { display: inline-block; }
then entire navigation will be centred.
One caveat to this approach is that display: inline-block;
is not supported in IE6 and needs a workaround to make it work in IE7.
You can call it like that:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var person = { name: 'Joe Blow' };
function myfunction() {
document.write(person.name);
}
</script>
</head>
<body>
<script type="text/javascript">
myfunction();
</script>
</body>
</html>
The result should be page with the only content: Joe Blow
Look here: http://jsfiddle.net/HWreP/
Best regards!
Add bottom:100%
to your #menu:hover ul li:hover ul
rule
#menu:hover ul li:hover ul {
position: absolute;
margin-top: 1px;
font: 10px;
bottom: 100%; /* added this attribute */
}
Or better yet to prevent the submenus from having the same effect, just add this rule
#menu>ul>li:hover>ul {
bottom:100%;
}
source: http://jsfiddle.net/W5FWW/4/
And to get back the border you can add the following attribute
#menu>ul>li:hover>ul {
bottom:100%;
border-bottom: 1px solid transparent
}
You have to "revert the revert". Depending on you how did the original revert, it may not be as easy as it sounds. Look at the official document on this topic.
---o---o---o---M---x---x---W---x---Y
/
---A---B-------------------C---D
to allow:
---o---o---o---M---x---x-------x-------*
/ /
---A---B-------------------C---D
But does it all work? Sure it does. You can revert a merge, and from a purely technical angle, git did it very naturally and had no real troubles.
It just considered it a change from "state before merge" to "state after merge", and that was it.
Nothing complicated, nothing odd, nothing really dangerous. Git will do it without even thinking about it.So from a technical angle, there's nothing wrong with reverting a merge, but from a workflow angle it's something that you generally should try to avoid.
If at all possible, for example, if you find a problem that got merged into the main tree, rather than revert the merge, try really hard to:
- bisect the problem down into the branch you merged, and just fix it,
- or try to revert the individual commit that caused it.
Yes, it's more complex, and no, it's not always going to work (sometimes the answer is: "oops, I really shouldn't have merged it, because it wasn't ready yet, and I really need to undo all of the merge"). So then you really should revert the merge, but when you want to re-do the merge, you now need to do it by reverting the revert.
Try something like this
select Cast((SPGI09_EARLY_OVER_T – (SPGI09_OVER_WK_EARLY_ADJUST_T) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T + SPGR99_ON_TIME_Q)) as varchar(20) + '%' as percentageAmount
from CSPGI09_OVERSHIPMENT
I presume the value is a representation in percentage - if not convert it to a valid percentage total, then add the % sign and convert the column to varchar.
Try using the duplicated function in combination with the negation operator "!".
Example:
wdups <- rep(1:5,5)
wodups <- wdups[which(!duplicated(wdups))]
Hope that helps.
Add items:
arr[0] = "product_1";
arr[1] = "100";
arr[2] = "10";
itm = new ListViewItem(arr);
listView1.Items.Add(itm);
Retrieve items:
productName = listView1.SelectedItems[0].SubItems[0].Text;
price = listView1.SelectedItems[0].SubItems[1].Text;
quantity = listView1.SelectedItems[0].SubItems[2].Text;
Adding android:gravity="center"
in your TextView will do the trick (be the parent layout is Relative/Linear
)!
Also, you should avoid using dp for font size. Use sp instead.
Here's my own implementation of singletons. All you have to do is decorate the class; to get the singleton, you then have to use the Instance
method. Here's an example:
@Singleton
class Foo:
def __init__(self):
print 'Foo created'
f = Foo() # Error, this isn't how you get the instance of a singleton
f = Foo.instance() # Good. Being explicit is in line with the Python Zen
g = Foo.instance() # Returns already created instance
print f is g # True
And here's the code:
class Singleton:
"""
A non-thread-safe helper class to ease implementing singletons.
This should be used as a decorator -- not a metaclass -- to the
class that should be a singleton.
The decorated class can define one `__init__` function that
takes only the `self` argument. Also, the decorated class cannot be
inherited from. Other than that, there are no restrictions that apply
to the decorated class.
To get the singleton instance, use the `instance` method. Trying
to use `__call__` will result in a `TypeError` being raised.
"""
def __init__(self, decorated):
self._decorated = decorated
def instance(self):
"""
Returns the singleton instance. Upon its first call, it creates a
new instance of the decorated class and calls its `__init__` method.
On all subsequent calls, the already created instance is returned.
"""
try:
return self._instance
except AttributeError:
self._instance = self._decorated()
return self._instance
def __call__(self):
raise TypeError('Singletons must be accessed through `instance()`.')
def __instancecheck__(self, inst):
return isinstance(inst, self._decorated)
To add to @DennisWilliamson comment above:
@VaibhavBajpai: Try this: response=$(curl --write-out \n%{http_code} --silent --output - servername) - the last line in the result will be the response code
You can then parse the response code from the response using something like the following, where X can signify a regex to mark the end of the response (using a json example here)
X='*\}'
code=$(echo ${response##$X})
See Substring Removal: http://tldp.org/LDP/abs/html/string-manipulation.html
I realize that this is an old question and that by now the original posters have each found a solution that works for them, but I ran across this issue and found that VML tags do not fall victim to this IE bug. Animated GIFs still move during page unload when placed on the IE browser using VML tags.
Notice I detected VML first before making the decision to use VML tags so this is working in FireFox and other browsers using normal animated GIF behavior.
Here's how I solved this.
<input class="myExitButton" type="button" value="Click me" />
<div class="loadingNextPage" style="display:none" >
<span style="left:-24px; POSITION: relative; WIDTH: 48px; DISPLAY: inline-block; HEIGHT: 48px" class="spinnerImageVml"><?xml:namespace prefix="rvml" ns = "urn:schemas-microsoft-com:vml" /><rvml:group style="POSITION: absolute; WIDTH: 48px; HEIGHT: 48px; rotation: 1deg" class="rvml" coordsize = "47,47"><rvml:image style="POSITION: absolute; WIDTH: 48px; HEIGHT: 48px; TOP: 0px; LEFT: 0px" class="rvml" src="/images/loading_gray.gif" coordsize="21600,21600"></rvml:image></rvml:group></span>
<img class="spinnerImage" src="/images/loading_gray.gif" alt="loading..." />
<div>Just one moment while we access this information...</div>
</div>
<script language="javascript" type="text/javascript">
window.LoadProgress = (function (progress, $) {
var getdialogHeight = function (height) {
var isIE = navigator.userAgent.toLowerCase().indexOf('msie') > -1;
if (isIE) {
return height + 'px';
}
return height;
};
var isVmlSupported = function () {
var a = document.body.appendChild(document.createElement('div'));
a.innerHTML = '<v:shape id="vml_flag1" adj="1" />';
var b = a.firstChild;
b.style.behavior = "url(#default#VML)";
var supported = b ? typeof b.adj == "object" : true;
a.parentNode.removeChild(a);
return supported;
};
var showAnimationDuringPageUnload = function () {
if (isVmlSupported()) {
$(".loadingNextPage > .spinnerImage").hide();
}
else {
$(".loadingNextPage > .spinnerImageVml").hide();
}
};
var openLoadingMessage = function () {
$(".loadingNextPage").dialog({
modal: true,
closeOnEscape: true,
title: 'Please wait...',
closeText: 'x',
height: getdialogHeight(200),
buttons: {
"Close": function () {
$(this).dialog("close");
}
}
});
};
$('.myExitButton').click(function () {
openLoadingMessage();
showAnimationDuringPageUnload();
window.location.href = 'http://www.stackoverflow.com';
});
return progress;
})(window.LoadProgress || {}, window.jQuery);
</script>
Naturally, this relies on jQuery, jQueryUI and requires an animated GIF of some type ("/images/loading_gray.gif").
replace(/[^a-z0-9\s]/gi, '')
will filter the string down to just alphanumeric values and replace(/[_\s]/g, '-')
will replace underscores and spaces with hyphens:
str.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-')
Source for Regex: RegEx for Javascript to allow only alphanumeric
Here is a demo: http://jsfiddle.net/vNfrk/
You have to use the escaped unicode :
Like
.breadcrumbs a:before {
content: '\0000a0';
}
More info on : http://www.evotech.net/blog/2007/04/named-html-entities-in-numeric-order/
Yes, consider some of these examples:
package main
import "fmt"
// convert types take an int and return a string value.
type convert func(int) string
// value implements convert, returning x as string.
func value(x int) string {
return fmt.Sprintf("%v", x)
}
// quote123 passes 123 to convert func and returns quoted string.
func quote123(fn convert) string {
return fmt.Sprintf("%q", fn(123))
}
func main() {
var result string
result = value(123)
fmt.Println(result)
// Output: 123
result = quote123(value)
fmt.Println(result)
// Output: "123"
result = quote123(func(x int) string { return fmt.Sprintf("%b", x) })
fmt.Println(result)
// Output: "1111011"
foo := func(x int) string { return "foo" }
result = quote123(foo)
fmt.Println(result)
// Output: "foo"
_ = convert(foo) // confirm foo satisfies convert at runtime
// fails due to argument type
// _ = convert(func(x float64) string { return "" })
}
Play: http://play.golang.org/p/XNMtrDUDS0
Tour: https://tour.golang.org/moretypes/25 (Function Closures)
Thanks to all for the posts but unfortunatley none of the above solved my problem. Eventually what got it all working for me was to download eclipse indigo 3.7.2 and (this is very important) EXTRACT IT DIRECTLY INTO MY PROGRAMS FOLDER. Before I would extract it to my desktop and copy into the programs folder (C:\Program Files) but I would jus get an error message saying "The Eclipse executable launcher was unable to locate its companion shared library" when trying to run eclipse.
After extracting eclipse directly to my programs folder I ran it and added the ADT plugin the way reccomended in on the android site and so far all is working well :)
I'm on a windows 7 x64 machine and had jre-7u2-windows-x64.exe, jdk-7u2-windows-x64.exe and installer_r16-windows.exe installed before extracting eclipse.
I hope this can help someone else too :)
The Mockito javadoc seems to tell why use doReturn()
instead of when()
Use doReturn() in those rare occasions when you cannot use Mockito.when(Object).
Beware that Mockito.when(Object) is always recommended for stubbing because it is argument type-safe and more readable (especially when stubbing consecutive calls).
Here are those rare occasions when doReturn() comes handy:
1. When spying real objects and calling real methods on a spy brings side effects
List list = new LinkedList(); List spy = spy(list);
//Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
when(spy.get(0)).thenReturn("foo");
//You have to use doReturn() for stubbing:
doReturn("foo").when(spy).get(0);
2. Overriding a previous exception-stubbing:
when(mock.foo()).thenThrow(new RuntimeException());
//Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
when(mock.foo()).thenReturn("bar");
//You have to use doReturn() for stubbing:
doReturn("bar").when(mock).foo();
Above scenarios shows a tradeoff of Mockito's elegant syntax. Note that the scenarios are very rare, though. Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general overridding stubbing is a potential code smell that points out too much stubbing.
I'd like to clarify a few things:
pandas.Series.tolist()
. I'm not sure why the top voted answer
leads off with using pandas.Series.values.tolist()
since as far as I can tell, it adds syntax/confusion with no added benefit.tst[lookupValue][['SomeCol']]
is a dataframe (as stated in the
question), not a series (as stated in a comment to the question). This is because tst[lookupValue]
is a dataframe, and slicing it with [['SomeCol']]
asks for
a list of columns (that list that happens to have a length of 1), resulting in a dataframe being returned. If you
remove the extra set of brackets, as in
tst[lookupValue]['SomeCol']
, then you are asking for just that one
column rather than a list of columns, and thus you get a series back.pandas.Series.tolist()
, so you should
definitely skip the second set of brackets in this case. FYI, if you
ever end up with a one-column dataframe that isn't easily avoidable
like this, you can use pandas.DataFrame.squeeze()
to convert it to
a series.tst[lookupValue]['SomeCol']
is getting a subset of a particular column via
chained slicing. It slices once to get a dataframe with only certain rows
left, and then it slices again to get a certain column. You can get
away with it here since you are just reading, not writing, but
the proper way to do it is tst.loc[lookupValue, 'SomeCol']
(which returns a series).ID = tst.loc[tst['SomeCol'] == 'SomeValue', 'SomeCol'].tolist()
Demo Code:
import pandas as pd
df = pd.DataFrame({'colA':[1,2,1],
'colB':[4,5,6]})
filter_value = 1
print "df"
print df
print type(df)
rows_to_keep = df['colA'] == filter_value
print "\ndf['colA'] == filter_value"
print rows_to_keep
print type(rows_to_keep)
result = df[rows_to_keep]['colB']
print "\ndf[rows_to_keep]['colB']"
print result
print type(result)
result = df[rows_to_keep][['colB']]
print "\ndf[rows_to_keep][['colB']]"
print result
print type(result)
result = df[rows_to_keep][['colB']].squeeze()
print "\ndf[rows_to_keep][['colB']].squeeze()"
print result
print type(result)
result = df.loc[rows_to_keep, 'colB']
print "\ndf.loc[rows_to_keep, 'colB']"
print result
print type(result)
result = df.loc[df['colA'] == filter_value, 'colB']
print "\ndf.loc[df['colA'] == filter_value, 'colB']"
print result
print type(result)
ID = df.loc[rows_to_keep, 'colB'].tolist()
print "\ndf.loc[rows_to_keep, 'colB'].tolist()"
print ID
print type(ID)
ID = df.loc[df['colA'] == filter_value, 'colB'].tolist()
print "\ndf.loc[df['colA'] == filter_value, 'colB'].tolist()"
print ID
print type(ID)
Result:
df
colA colB
0 1 4
1 2 5
2 1 6
<class 'pandas.core.frame.DataFrame'>
df['colA'] == filter_value
0 True
1 False
2 True
Name: colA, dtype: bool
<class 'pandas.core.series.Series'>
df[rows_to_keep]['colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df[rows_to_keep][['colB']]
colB
0 4
2 6
<class 'pandas.core.frame.DataFrame'>
df[rows_to_keep][['colB']].squeeze()
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[rows_to_keep, 'colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[df['colA'] == filter_value, 'colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[rows_to_keep, 'colB'].tolist()
[4, 6]
<type 'list'>
df.loc[df['colA'] == filter_value, 'colB'].tolist()
[4, 6]
<type 'list'>
LocalDate // Represents an entire day, without time-of-day and without time zone.
.now( // Capture the current date.
ZoneId.of( "Asia/Tokyo" ) // Returns a `ZoneId` object.
) // Returns a `LocalDate` object.
.atStartOfDay( // Determines the first moment of the day as seen on that date in that time zone. Not all days start at 00:00!
ZoneId.of( "Asia/Tokyo" )
) // Returns a `ZonedDateTime` object.
Get the full length of the today as seen in a time zone.
Using Half-Open approach, where the beginning is inclusive while the ending is exclusive. This approach solves the flaw in your code that fails to account for the very last second of the day.
ZoneId zoneId = ZoneId.of( "Africa/Tunis" ) ;
LocalDate today = LocalDate.now( zoneId ) ;
ZonedDateTime zdtStart = today.atStartOfDay( zoneId ) ;
ZonedDateTime zdtStop = today.plusDays( 1 ).atStartOfDay( zoneId ) ;
zdtStart.toString() = 2020-01-30T00:00+01:00[Africa/Tunis]
zdtStop.toString() = 2020-01-31T00:00+01:00[Africa/Tunis]
See the same moments in UTC.
Instant start = zdtStart.toInstant() ;
Instant stop = zdtStop.toInstant() ;
start.toString() = 2020-01-29T23:00:00Z
stop.toString() = 2020-01-30T23:00:00Z
If you want the entire day of a date as seen in UTC rather than in a time zone, use OffsetDateTime
.
LocalDate today = LocalDate.now( ZoneOffset.UTC ) ;
OffsetDateTime odtStart = today.atTime( OffsetTime.MIN ) ;
OffsetDateTime odtStop = today.plusDays( 1 ).atTime( OffsetTime.MIN ) ;
odtStart.toString() = 2020-01-30T00:00+18:00
odtStop.toString() = 2020-01-31T00:00+18:00
These OffsetDateTime
objects will already be in UTC, but you can call toInstant
if you need such objects which are always in UTC by definition.
Instant start = odtStart.toInstant() ;
Instant stop = odtStop.toInstant() ;
start.toString() = 2020-01-29T06:00:00Z
stop.toString() = 2020-01-30T06:00:00Z
Tip: You may be interested in adding the ThreeTen-Extra library to your project to use its Interval
class to represent this pair of Instant
objects. This class offers useful methods for comparison such as abuts
, overlaps
, contains
, and more.
Interval interval = Interval.of( start , stop ) ;
interval.toString() = 2020-01-29T06:00:00Z/2020-01-30T06:00:00Z
The answer by mprivat is correct. His point is to not try to obtain end of a day, but rather compare to "before start of next day". His idea is known as the "Half-Open" approach where a span of time has a beginning that is inclusive while the ending is exclusive.
Joda-Time 2.3 offers a method for this very purpose, to obtain first moment of the day: withTimeAtStartOfDay()
. Similarly in java.time, LocalDate::atStartOfDay
.
Search StackOverflow for "joda half-open" to see more discussion and examples.
See this post, Time intervals and other ranges should be half-open, by Bill Schneider.
The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them.
Use java.time classes. The java.time framework is the official successor of the highly successful Joda-Time library.
The java.time framework is built into Java 8 and later. Back-ported to Java 6 & 7 in the ThreeTen-Backport project, further adapted to Android in the ThreeTenABP project.
An Instant
is a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = Instant.now();
Apply a time zone to get the wall-clock time for some locality.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
To get the first moment of the day go through the LocalDate
class and its atStartOfDay
method.
ZonedDateTime zdtStart = zdt.toLocalDate().atStartOfDay( zoneId );
Using Half-Open approach, get first moment of following day.
ZonedDateTime zdtTomorrowStart = zdtStart.plusDays( 1 );
Currently the java.time framework lacks an Interval
class as described below for Joda-Time. However, the ThreeTen-Extra project extends java.time with additional classes. This project is the proving ground for possible future additions to java.time. Among its classes is Interval
. Construct an Interval
by passing a pair of Instant
objects. We can extract an Instant
from our ZonedDateTime
objects.
Interval today = Interval.of( zdtStart.toInstant() , zdtTomorrowStart.toInstant() );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
UPDATE: The Joda-Time project is now in maintenance-mode, and advises migration to the java.time classes. I am leaving this section intact for history.
Joda-Time has three classes to represent a span of time in various ways: Interval
, Period
, and Duration
. An Interval
has a specific beginning and ending on the timeline of the Universe. This fits our need to represent "a day".
We call the method withTimeAtStartOfDay
rather than set time of day to zeros. Because of Daylight Saving Time and other anomalies the first moment of the day may not be 00:00:00
.
Example code using Joda-Time 2.3.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( timeZone );
DateTime todayStart = now.withTimeAtStartOfDay();
DateTime tomorrowStart = now.plusDays( 1 ).withTimeAtStartOfDay();
Interval today = new Interval( todayStart, tomorrowStart );
If you must, you can convert to a java.util.Date.
java.util.Date date = todayStart.toDate();
using a simple, yet generic, helper method like this:
public static <T> T last(T[] array) {
return array[array.length - 1];
}
you can rewrite:
lastone = one.split("-")[..];
as:
lastone = last(one.split("-"));
SELECT *
FROM tbl
WHERE myDate BETWEEN #date one# AND #date two#;
Pointers generally have a fixed size, for ex. on a 32-bit executable they're usually 32-bit. There are some exceptions, like on old 16-bit windows when you had to distinguish between 32-bit pointers and 16-bit... It's usually pretty safe to assume they're going to be uniform within a given executable on modern desktop OS's.
Edit: Even so, I would strongly caution against making this assumption in your code. If you're going to write something that absolutely has to have a pointers of a certain size, you'd better check it!
Function pointers are a different story -- see Jens' answer for more info.
Open app/build.gradle file
Change buildToolsVersion
to buildToolsVersion "26.0.2"
change compile 'com.android.support:appcompat
to compile 'com.android.support:appcompat-v7:26.0.2'
Ctrl + F5 is better, because you don't need additional lines. And you can, in the end, hit enter and exit running mode.
But, when you start a program with F5 and put a break-point, you can debug your application and that gives you other advantages.
Try this out. it works well for me. Make sure that before send email u need to give the access for less secure app in your gmail account. So go to the following link and try out with this java code.
Activate gmail for less secure app
You need to import javax.mail.jar file and activation.jar file to your project.
This is the full code for send email in java
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class SendEmail {
final String senderEmail = "your email address";
final String senderPassword = "your password";
final String emailSMTPserver = "smtp.gmail.com";
final String emailServerPort = "587";
String receiverEmail = null;
String emailSubject = null;
String emailBody = null;
public SendEmail(String receiverEmail, String Subject, String message) {
this.receiverEmail = receiverEmail;
this.emailSubject = Subject;
this.emailBody = message;
Properties props = new Properties();
props.put("mail.smtp.user", senderEmail);
props.put("mail.smtp.host", emailSMTPserver);
props.put("mail.smtp.port", emailServerPort);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", emailServerPort);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
SecurityManager security = System.getSecurityManager();
try {
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
Message msg = new MimeMessage(session);
msg.setText(emailBody);
msg.setSubject(emailSubject);
msg.setFrom(new InternetAddress(senderEmail));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(receiverEmail));
Transport.send(msg);
System.out.println("send successfully");
} catch (Exception ex) {
System.err.println("Error occurred while sending.!");
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(senderEmail, senderPassword);
}
}
public static void main(String[] args) {
SendEmail send = new SendEmail("receiver email address", "subject", "message");
}
}
Alternatively, in plain text: (also available as a a screenshot)
Bracket Matching -. .- Line Numbering
Smart Indent -. | | .- UML Editing / Viewing
Source Control Integration -. | | | | .- Code Folding
Error Markup -. | | | | | | .- Code Templates
Integrated Python Debugging -. | | | | | | | | .- Unit Testing
Multi-Language Support -. | | | | | | | | | | .- GUI Designer (Qt, Eric, etc)
Auto Code Completion -. | | | | | | | | | | | | .- Integrated DB Support
Commercial/Free -. | | | | | | | | | | | | | | .- Refactoring
Cross Platform -. | | | | | | | | | | | | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y | | | | |*many plugins
Editra |Y |F |Y |Y | | |Y |Y |Y |Y | |Y | | | | | |
Emacs |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
Eric Ide |Y |F |Y | |Y |Y | |Y | |Y | |Y | |Y | | | |
Geany |Y |F |Y*|Y | | | |Y |Y |Y | |Y | | | | | |*very limited
Gedit |Y |F |Y¹|Y | | | |Y |Y |Y | | |Y²| | | | |¹with plugin; ²sort of
Idle |Y |F |Y | |Y | | |Y |Y | | | | | | | | |
IntelliJ |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit |Y |F | |Y | | | | |Y |Y | |Y | | | | | |
KDevelop |Y |F |Y*|Y | | |Y |Y |Y |Y | |Y | | | | | |*no type inference
Komodo |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | |Y | |
NetBeans* |Y |F |Y |Y |Y | |Y |Y |Y |Y |Y |Y |Y |Y | | |Y |*pre-v7.0
Notepad++ |W |F |Y |Y | |Y*|Y*|Y*|Y |Y | |Y |Y*| | | | |*with plugin
Pfaide |W |C |Y |Y | | | |Y |Y |Y | |Y |Y | | | | |
PIDA |LW|F |Y |Y | | | |Y |Y |Y | |Y | | | | | |VIM based
PTVS |W |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y | | |Y*| |Y |*WPF bsed
PyCharm |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse) |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
PyScripter |W |F |Y | |Y |Y | |Y |Y |Y | |Y |Y |Y | | | |
PythonWin |W |F |Y | |Y | | |Y |Y | | |Y | | | | | |
SciTE |Y |F¹| |Y | |Y | |Y |Y |Y | |Y |Y | | | | |¹Mac version is
ScriptDev |W |C |Y |Y |Y |Y | |Y |Y |Y | |Y |Y | | | | | commercial
Spyder |Y |F |Y | |Y |Y | |Y |Y |Y | | | | | | | |
Sublime Text |Y |CF|Y |Y | |Y |Y |Y |Y |Y | |Y |Y |Y*| | | |extensible w/Python,
TextMate |M |F | |Y | | |Y |Y |Y |Y | |Y |Y | | | | | *PythonTestRunner
UliPad |Y |F |Y |Y |Y | | |Y |Y | | | |Y |Y | | | |
Vim |Y |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |
Visual Studio |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |*support for C
Zeus |W |C | | | | |Y |Y |Y |Y | |Y |Y | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Cross Platform -' | | | | | | | | | | | | | | | |
Commercial/Free -' | | | | | | | | | | | | | | '- Refactoring
Auto Code Completion -' | | | | | | | | | | | | '- Integrated DB Support
Multi-Language Support -' | | | | | | | | | | '- GUI Designer (Qt, Eric, etc)
Integrated Python Debugging -' | | | | | | | | '- Unit Testing
Error Markup -' | | | | | | '- Code Templates
Source Control Integration -' | | | | '- Code Folding
Smart Indent -' | | '- UML Editing / Viewing
Bracket Matching -' '- Line Numbering
Acronyms used:
L - Linux
W - Windows
M - Mac
C - Commercial
F - Free
CF - Commercial with Free limited edition
? - To be confirmed
I don't mention basics like syntax highlighting as I expect these by default.
This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.
PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?
We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
I agree with @adietisheim and the rest of people that suggest HttpClient.
I spent time trying to make a simple call to rest service with HttpURLConnection and it hadn't convinced me and after that I tried with HttpClient and it was really more easy, understandable and nice.
An example of code to make a put http call is as follows:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPut putRequest = new HttpPut(URI);
StringEntity input = new StringEntity(XML);
input.setContentType(CONTENT_TYPE);
putRequest.setEntity(input);
HttpResponse response = httpClient.execute(putRequest);
If any of the code in the try block can throw a checked exception, it has to appear in the throws clause of the method signature. If an unchecked exception is thrown, it's bubbled out of the method.
The finally block is always executed, whether an exception is thrown or not.
For MS SQL CEILING(your number) will round it up. FLOOR(your number) will round it down
The first part of your question can be solved with just HTML & CSS; you'll need to use Javascript for the second part.
I'm not sure what you mean by "next to": on the same line and near, or on separate lines? If you want all of the radio buttons on the same line, just use margins to push them apart. If you want each of them on their own line, you have two options (unless you want to venture into float:
territory):
<br />s
to split the options apart and some CSS to vertically align them:<style type='text/css'>
.input input
{
width: 20px;
}
</style>
<div class="input radio">
<fieldset>
<legend>What color is the sky?</legend>
<input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1" />
<label for="SubmitQuestion1">A strange radient green.</label>
<br />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2" />
<label for="SubmitQuestion2">A dark gloomy orange</label>
<br />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3" />
<label for="SubmitQuestion3">A perfect glittering blue</label>
</fieldset>
</div>
Styling the <label>
is why you'll need to resort to Javascript. A library like jQuery
is perfect for this:
<style type='text/css'>
.input label.focused
{
background-color: #EEEEEE;
font-style: italic;
}
</style>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$('.input :radio').focus(updateSelectedStyle);
$('.input :radio').blur(updateSelectedStyle);
$('.input :radio').change(updateSelectedStyle);
})
function updateSelectedStyle() {
$('.input :radio').removeClass('focused').next().removeClass('focused');
$('.input :radio:checked').addClass('focused').next().addClass('focused');
}
</script>
The focus
and blur
hooks are needed to make this work in IE.
There are a couple of ways to solve this. The least hackiest and almost what you want:
$client = new SoapClient(
null,
array(
'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL,
)
);
$params = new \SoapVar("<Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer>", XSD_ANYXML);
$result = $client->Echo($params);
This gets you the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://example.com/wsdl">
<SOAP-ENV:Body>
<ns1:Echo>
<Acquirer>
<Id>MyId</Id>
<UserId>MyUserId</UserId>
<Password>MyPassword</Password>
</Acquirer>
</ns1:Echo>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
That is almost exactly what you want, except for the namespace on the method name. I don't know if this is a problem. If so, you can hack it even further. You could put the <Echo>
tag in the XML string by hand and have the SoapClient not set the method by adding 'style' => SOAP_DOCUMENT,
to the options array like this:
$client = new SoapClient(
null,
array(
'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL,
'style' => SOAP_DOCUMENT,
)
);
$params = new \SoapVar("<Echo><Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer></Echo>", XSD_ANYXML);
$result = $client->MethodNameIsIgnored($params);
This results in the following request XML:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<Echo>
<Acquirer>
<Id>MyId</Id>
<UserId>MyUserId</UserId>
<Password>MyPassword</Password>
</Acquirer>
</Echo>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Finally, if you want to play around with SoapVar and SoapParam objects, you can find a good reference in this comment in the PHP manual: http://www.php.net/manual/en/soapvar.soapvar.php#104065. If you get that to work, please let me know, I failed miserably.
load the image by using following syntax:-
from keras.preprocessing import image
X_test=image.load_img('four.png',target_size=(28,28),color_mode="grayscale"); #loading image and then convert it into grayscale and with it's target size
X_test=image.img_to_array(X_test); #convert image into array
Try using Async instead to avoid blocking the only thread you have with NodeJS. Check this example:
const util = require('util');
const fs = require('fs');
const path = require('path');
const readFileAsync = util.promisify(fs.readFile);
const readContentFile = async (filePath) => {
// Eureka, you are using good code practices here!
const content = await readFileAsync(path.join(__dirname, filePath), {
encoding: 'utf8'
})
return content;
}
Later can use this async function with try/catch from any other function:
const anyOtherFun = async () => {
try {
const fileContent = await readContentFile('my-file.txt');
} catch (err) {
// Here you get the error when the file was not found,
// but you also get any other error
}
}
Happy Coding!
This maybe because the c compiler is designed to work in linux.I had this problem too and to fix it go to tools
and select compiler options
.In the box click on programs
Now you will see a tab with gcc
and make
and the respective path to it.Edit the gcc
and make
path to use mingw32-c++.exe
and mingw32-make.exe
respectively.Now it will work.
The reason was that you were using compilers built for linux.
Console.WriteLine(DateTime.UtcNow.ToString("o"));
Console.WriteLine(DateTime.Now.ToString("o"));
Outputs:
2012-07-09T19:22:09.1440844Z
2012-07-09T12:22:09.1440844-07:00
EDIT: http://jsfiddle.net/nCFGL/223/ My Example.
You should be able to like follows:
var pieData = [{
value: 30,
color: "#F38630",
label: 'Sleep',
labelColor: 'white',
labelFontSize: '16'
},
...
];
Include the Chart.js located at:
this query return last record for every Form_id:
SELECT m1.*
FROM messages m1 LEFT JOIN messages m2
ON (m1.Form_id = m2.Form_id AND m1.id < m2.id)
WHERE m2.id IS NULL;
I have found very quick & short workaround for this. Tested in many popular browsers (Chrome, Firefox, Safari);
First, you have to convert FileList to an Array
var newFileList = Array.from(event.target.files);
to delete the particular element use this
newFileList.splice(index,1);
You can use the built in xDocument.CreateReader() and an XmlNodeReader to convert back and forth.
Putting that into an Extension method to make it easier to work with.
using System;
using System.Xml;
using System.Xml.Linq;
namespace MyTest
{
internal class Program
{
private static void Main(string[] args)
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<Root><Child>Test</Child></Root>");
var xDocument = xmlDocument.ToXDocument();
var newXmlDocument = xDocument.ToXmlDocument();
Console.ReadLine();
}
}
public static class DocumentExtensions
{
public static XmlDocument ToXmlDocument(this XDocument xDocument)
{
var xmlDocument = new XmlDocument();
using(var xmlReader = xDocument.CreateReader())
{
xmlDocument.Load(xmlReader);
}
return xmlDocument;
}
public static XDocument ToXDocument(this XmlDocument xmlDocument)
{
using (var nodeReader = new XmlNodeReader(xmlDocument))
{
nodeReader.MoveToContent();
return XDocument.Load(nodeReader);
}
}
}
}
Sources:
If you want to simply escape a string, not an object or array, use this:
String escaped = JSONObject.valueToString(" Quotes \" ' ' \" ");
http://www.json.org/javadoc/org/json/JSONObject.html#valueToString(java.lang.Object)
This is exactly what you want. Try this:
{{ wpis.entry.lastChangeDate|date:'Y-m-d H:i' }}
Use:
sed -e **'s/^[ \t]*//'** name_of_file_from_which_you_want_to_remove_space > 'name _file_where_you_want_to_store_output'
For example:
sed -e 's/^[ \t]*//' file1.txt > output.txt
Note:
s/
: Substitute command ~ replacement for pattern (^[ \t]*
) on each addressed line
^[ \t]*
: Search pattern ( ^ – start of the line; [ \t]*
match one or more blank spaces including tab)
//
: Replace (delete) all matched patterns
For windows use Resource Hacker
Download and Install: :D
http://www.angusj.com/resourcehacker/
You should have build the app
InnoDB works slightly different that MyISAM and they both are viable options. You should use what you think it fits the project.
Some keypoints will be:
Notes:
Notes2: - I am reading this book "High performance MySQL", the author says "InnoDB loads data and creates indexes slower than MyISAM", this could also be a very important factor when deciding what to use.
You can run the top
command (to run non-interactively, type top -b -n 1
). To see applications which are leaking memory, look at the following columns:
We can create multidimensional array dynamically as follows,
Create 2 variables to read x and y from standard input:
print("Enter the value of x: ")
x=int(input())
print("Enter the value of y: ")
y=int(input())
Create an array of list with initial values filled with 0 or anything using the following code
z=[[0 for row in range(0,x)] for col in range(0,y)]
creates number of rows and columns for your array data.
Read data from standard input:
for i in range(x):
for j in range(y):
z[i][j]=input()
Display the Result:
for i in range(x):
for j in range(y):
print(z[i][j],end=' ')
print("\n")
or use another way to display above dynamically created array is,
for row in z:
print(row)
THE CORRECT WAY IS :
UPDATE test1
INNER JOIN test2 ON (test1.id = test2.id)
SET test1.data = test2.data
Python datetimes are a little clunky. Use arrow
.
> str(arrow.utcnow())
'2014-05-17T01:18:47.944126+00:00'
Arrow has essentially the same api as datetime, but with timezones and some extra niceties that should be in the main library.
A format compatible with Javascript can be achieved by:
arrow.utcnow().isoformat().replace("+00:00", "Z")
'2018-11-30T02:46:40.714281Z'
Javascript Date.parse
will quietly drop microseconds from the timestamp.
I know it's late, although there is a much more convenient way to solve this kind of problem! The other solutions are quite messy; this is how I would do it:
$protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === 0 ? 'https://' : 'http://';
...or even without condition if you prefer:
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,strpos( $_SERVER["SERVER_PROTOCOL"],'/'))).'://';
Have a look at $_SERVER["SERVER_PROTOCOL"]
I ignore all classes residing in target folder from git. add following line in open .gitignore file:
/.class
OR
*/target/**
It is working perfectly for me. try it.
To prevent users from resizing, set the FormBoderStyle to Fixed3D or FixedDialog from properties window or from code
frmYour.BorderStyle = System.WinForms.FormBorderStyle.Fixed3D
And set the WindowState property to Maximized, set the MaximizeBox and MinimizeBox properties to false.
To prevent the user from moving around, override WndProc
Protected Overrides Sub WndProc(ByRef m As Message)
Const WM_NCLBUTTONDOWN As Integer = 161
Const WM_SYSCOMMAND As Integer = 274
Const HTCAPTION As Integer = 2
Const SC_MOVE As Integer = 61456
If (m.Msg = WM_SYSCOMMAND) And (m.WParam.ToInt32() = SC_MOVE) Then
Return
End If
If (m.Msg = WM_NCLBUTTONDOWN) And (m.WParam.ToInt32() = HTCAPTION) Then
Return
End If
MyBase.WndProc(m)
End Sub
Partial dependence is solved for arriving to a relation in 2NF but 2NF is a "stepping stone" (C. Date) for solving any transitive dependency and arriving to a relation in 3NF (which is the operational target). However, the most interested thing on partial dependence is that it is a particular case of the own transitive dependency. This was demostrated by P. A. Berstein in 1976: IF {(x•y)?z but y?z} THEN {(x•y)?y & y?z}. The 3NF synthesizer algorithm of Berstein does not need doing distintions among these two type of relational defects.
>>> x = "2342.34"
>>> float(x)
2342.3400000000001
There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).
You can also use the SqlConnectionStringBuilder
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnectionString);
builder.ConnectTimeout = 10;
using (var connection = new SqlConnection(builder.ToString()))
{
// code goes here
}
In python a list knows its length, so you can just do len(sys.argv)
to get the number of elements in argv
.
I had to get rid of the NULL values before using the command recommended by Andy above. An example:
df = pd.DataFrame(index = [0, 1, 2], columns=['first', 'second', 'third'])
df.ix[:, 'first'] = 'myword'
df.ix[0, 'second'] = 'myword'
df.ix[2, 'second'] = 'myword'
df.ix[1, 'third'] = 'myword'
df
first second third
0 myword myword NaN
1 myword NaN myword
2 myword myword NaN
Now running the command:
~df["second"].str.contains(word)
I get the following error:
TypeError: bad operand type for unary ~: 'float'
I got rid of the NULL values using dropna() or fillna() first and retried the command with no problem.
Install and use the Android Drawable Importer plugin:
https://github.com/winterDroid/android-drawable-importer-intellij-plugin
Instructions on how to install the plugin are on that page. It's called "Android Drawable Importer" in the plugin search results.
Once installed:
Seems kind of ridiculous that Android Studio doesn't support this directly.
EDIT: But Xcode doesn't either so.... :-(
If you can manipulate the common interface, you could do add in an enum and have each class return a unique value. You won't need instanceof or a visitor pattern.
For me, the logic needed to be in the written in the switch statement, not the object itself. This was my solution:
ClassA, ClassB, and ClassC implement CommonClass
Interface:
public interface CommonClass {
MyEnum getEnumType();
}
Enum:
public enum MyEnum {
ClassA(0), ClassB(1), ClassC(2);
private int value;
private MyEnum(final int value) {
this.value = value;
}
public int getValue() {
return value;
}
Impl:
...
switch(obj.getEnumType())
{
case MyEnum.ClassA:
ClassA classA = (ClassA) obj;
break;
case MyEnum.ClassB:
ClassB classB = (ClassB) obj;
break;
case MyEnum.ClassC:
ClassC classC = (ClassC) obj;
break;
}
...
If you are on java 7, you can put string values for the enum and the switch case block will still work.
Here's UIImage extension for swift:
extension UIImage {
func fixOrientation() -> UIImage {
// No-op if the orientation is already correct
if ( self.imageOrientation == UIImageOrientation.Up ) {
return self;
}
// We need to calculate the proper transformation to make the image upright.
// We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
var transform: CGAffineTransform = CGAffineTransformIdentity
if ( self.imageOrientation == UIImageOrientation.Down || self.imageOrientation == UIImageOrientation.DownMirrored ) {
transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI))
}
if ( self.imageOrientation == UIImageOrientation.Left || self.imageOrientation == UIImageOrientation.LeftMirrored ) {
transform = CGAffineTransformTranslate(transform, self.size.width, 0)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2))
}
if ( self.imageOrientation == UIImageOrientation.Right || self.imageOrientation == UIImageOrientation.RightMirrored ) {
transform = CGAffineTransformTranslate(transform, 0, self.size.height);
transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2));
}
if ( self.imageOrientation == UIImageOrientation.UpMirrored || self.imageOrientation == UIImageOrientation.DownMirrored ) {
transform = CGAffineTransformTranslate(transform, self.size.width, 0)
transform = CGAffineTransformScale(transform, -1, 1)
}
if ( self.imageOrientation == UIImageOrientation.LeftMirrored || self.imageOrientation == UIImageOrientation.RightMirrored ) {
transform = CGAffineTransformTranslate(transform, self.size.height, 0);
transform = CGAffineTransformScale(transform, -1, 1);
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
var ctx: CGContextRef = CGBitmapContextCreate(nil, Int(self.size.width), Int(self.size.height),
CGImageGetBitsPerComponent(self.CGImage), 0,
CGImageGetColorSpace(self.CGImage),
CGImageGetBitmapInfo(self.CGImage));
CGContextConcatCTM(ctx, transform)
if ( self.imageOrientation == UIImageOrientation.Left ||
self.imageOrientation == UIImageOrientation.LeftMirrored ||
self.imageOrientation == UIImageOrientation.Right ||
self.imageOrientation == UIImageOrientation.RightMirrored ) {
CGContextDrawImage(ctx, CGRectMake(0,0,self.size.height,self.size.width), self.CGImage)
} else {
CGContextDrawImage(ctx, CGRectMake(0,0,self.size.width,self.size.height), self.CGImage)
}
// And now we just create a new UIImage from the drawing context and return it
return UIImage(CGImage: CGBitmapContextCreateImage(ctx))!
}
}
Based on MetalHeart2003's earlier work..
As of C++11, the memory-safe way to do this (still using a similar construction) is with std::unique_ptr
:
std::unique_ptr<int[]> array(new int[n]);
This creates a smart pointer to a memory block large enough for n
integers that automatically deletes itself when it goes out of scope. This automatic clean-up is important because it avoids the scenario where your code quits early and never reaches your delete [] array;
statement.
Another (probably preferred) option would be to use std::vector
if you need an array capable of dynamic resizing. This is good when you need an unknown amount of space, but it has some disadvantages (non-constant time to add/delete an element). You could create an array and add elements to it with something like:
std::vector<int> array;
array.push_back(1); // adds 1 to end of array
array.push_back(2); // adds 2 to end of array
// array now contains elements [1, 2]
global
members are not available by default in your <template>
's scope. But you can easily pass them on using computed
properties.
computed: {
moment: () => moment,
console: () => console,
window: () => window
}
Now you can use any of them in your template. i.e: console.log(moment(), window)
.
Note this doesn't add any overhead.
Always mention max-width and min-width in some unit like px or rem. This figured it out for me. If I write it without the unit and only the number value, browser can't read the media queries. example: this is wrong @media only screen and (max-width:950) and this is right @media only screen and (max-width:950px)
In addition to all differences described in the other answers:
If you are after a video explaining all the differences, you can check out Part 29 - C# Tutorial - Difference between classes and structs in C#.
Tensor flow has only support for python 2.7 3.4 3.5 Other python versions are not supported So you please install the supported python version and try it again. The official link is https://www.tensorflow.org/install/install_linux#InstallingAnaconda It provides how to install it with anaconda . This will help you
Jscript is a .NET language similar to C#, with the same capabilities and access to all the .NET functions.
JavaScript is run on the ASP Classic server. Use Classic ASP to run the same JavaScript that you have on the Client (excluding HTML5 capabilities). I only have one set of code this way for most of my code.
I run .ASPX JScript when I require Image and Binary File functions, (among many others) that are not in Classic ASP. This code is unique for the server, but extremely powerful.
You could use the **\**
character before the value you want to escape e.g
insert into msglog(recipient) values('Mr. O\'riely')
select * from msglog where recipient = 'Mr. O\'riely'
Just like Bruce Armstrong suggested in his answer. However I'd use FormData
:
$(function() {
$('form').submit(function() {
var formData = new FormData($(this)[0]);
$.ajax({
type: 'POST',
url: 'submit.php',
data: formData,
processData: false,
contentType: false,
});
return false;
});
})
I found this simple solution, PyMuPDF, output to png file. Note the library is imported as "fitz", a historical name for the rendering engine it uses.
import fitz
pdffile = "infile.pdf"
doc = fitz.open(pdffile)
page = doc.loadPage(0) # number of page
pix = page.getPixmap()
output = "outfile.png"
pix.writePNG(output)
Laravel supports aliases on tables and columns with AS
. Try
$users = DB::table('really_long_table_name AS t')
->select('t.id AS uid')
->get();
Let's see it in action with an awesome tinker
tool
$ php artisan tinker [1] > Schema::create('really_long_table_name', function($table) {$table->increments('id');}); // NULL [2] > DB::table('really_long_table_name')->insert(['id' => null]); // true [3] > DB::table('really_long_table_name AS t')->select('t.id AS uid')->get(); // array( // 0 => object(stdClass)( // 'uid' => '1' // ) // )
If the extension is not known, use this solution
pathinfo('D:/dir1/dir2/fname', PATHINFO_FILENAME); // return "fname"
pathinfo('D:/dir1/dir2/fname.php', PATHINFO_FILENAME); // return "fname"
pathinfo('D:/dir1/dir2/fname.jpg', PATHINFO_FILENAME); // return "fname"
pathinfo('D:/dir1/dir2/fname.jpg', PATHINFO_DIRNAME) . '/' . pathinfo('D:/dir1/dir2/fname.jpg', PATHINFO_FILENAME); // return "D:/dir1/dir2/fname"
In Java you can only import class Names, or static methods/fields.
To import class use
import full.package.name.of.SomeClass;
We can also import static methods/fields in Java and this is how to import
import static full.package.nameOfClass.staticMethod;
import static full.package.nameOfClass.staticField;
Remove Padding: 10%;
or use px instead of percent for .wrap
see the example : http://jsfiddle.net/C93mk/493/
HTML :
<div id="wrapper">
<div id="wrap">
Some relative item placed item
<div id="fixed"></div>
</div>
</div>
CSS:
body{ height:20000px }
#wrapper {padding:10%;}
#wrap{
float: left;
position: relative;
width: 200px;
background:#ccc;
}
#fixed{
position:fixed;
width:inherit;
padding:0px;
height:10px;
background-color:#333;
}
Please use below code for complete example of simple notification, in this code you can open application after clicking on Notification, it will solve your problem.
public class AndroidNotifications extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button notificationButton = (Button) findViewById(R.id.notificationButton);
notificationButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// Notification Title and Message
Notification("Dipak Keshariya (Android Developer)",
"This is Message from Dipak Keshariya (Android Developer)");
}
}, 0);
}
});
}
// Notification Function
private void Notification(String notificationTitle,
String notificationMessage) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
android.app.Notification notification = new android.app.Notification(
R.drawable.ic_launcher, "Message from Dipak Keshariya! (Android Developer)",
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, AndroidNotifications.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(AndroidNotifications.this,
notificationTitle, notificationMessage, pendingIntent);
notificationManager.notify(10001, notification);
}
}
And see below link for more information.
You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:
@(deletedView ? "Deleted" : "Created by")
Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.
You cannot directly use a SQL statement in a PL/SQL expression:
SQL> begin
2 if (select count(*) from dual) >= 1 then
3 null;
4 end if;
5 end;
6 /
if (select count(*) from dual) >= 1 then
*
ERROR at line 2:
ORA-06550: line 2, column 6:
PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:
...
...
You must use a variable instead:
SQL> set serveroutput on
SQL>
SQL> declare
2 v_count number;
3 begin
4 select count(*) into v_count from dual;
5
6 if v_count >= 1 then
7 dbms_output.put_line('Pass');
8 end if;
9 end;
10 /
Pass
PL/SQL procedure successfully completed.
Of course, you may be able to do the whole thing in SQL:
update my_table
set x = y
where (select count(*) from other_table) >= 1;
It's difficult to prove that something is not possible. Other than the simple test case above, you can look at the syntax diagram for the IF
statement; you won't see a SELECT
statement in any of the branches.
There are two types of contexts we are dealing with:
1: root context (parent context. Typically include all jdbc(ORM, Hibernate) initialisation and other spring security related configuration)
2: individual servlet context (child context.Typically Dispatcher Servlet Context and initialise all beans related to spring-mvc (controllers , URL Mapping etc)).
Here is an example of web.xml which includes multiple application context file
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<web-app xmlns="http://java.sun.com/xml/ns/javaee"_x000D_
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"_x000D_
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee_x000D_
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">_x000D_
_x000D_
<display-name>Spring Web Application example</display-name>_x000D_
_x000D_
<!-- Configurations for the root application context (parent context) -->_x000D_
<listener>_x000D_
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>_x000D_
</listener>_x000D_
<context-param>_x000D_
<param-name>contextConfigLocation</param-name>_x000D_
<param-value>_x000D_
/WEB-INF/spring/jdbc/spring-jdbc.xml <!-- JDBC related context -->_x000D_
/WEB-INF/spring/security/spring-security-context.xml <!-- Spring Security related context -->_x000D_
</param-value>_x000D_
</context-param>_x000D_
_x000D_
<!-- Configurations for the DispatcherServlet application context (child context) -->_x000D_
<servlet>_x000D_
<servlet-name>spring-mvc</servlet-name>_x000D_
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>_x000D_
<init-param>_x000D_
<param-name>contextConfigLocation</param-name>_x000D_
<param-value>_x000D_
/WEB-INF/spring/mvc/spring-mvc-servlet.xml_x000D_
</param-value>_x000D_
</init-param>_x000D_
</servlet>_x000D_
<servlet-mapping>_x000D_
<servlet-name>spring-mvc</servlet-name>_x000D_
<url-pattern>/admin/*</url-pattern>_x000D_
</servlet-mapping>_x000D_
_x000D_
</web-app>
_x000D_
If you need async: false
in your ajax, you should use success
instead of .done
. Else you better to use .done
.
This is from jQuery official site:
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().
Thank you Phil for your solution; in case someone ever gets in the same situation as me, here is a (more complex) variant:
---
# this is just to avoid a call to |default on each iteration
- set_fact:
postconf_d: {}
- name: 'get postfix default configuration'
command: 'postconf -d'
register: command
# the answer of the command give a list of lines such as:
# "key = value" or "key =" when the value is null
- name: 'set postfix default configuration as fact'
set_fact:
postconf_d: >
{{
postconf_d |
combine(
dict([ item.partition('=')[::2]|map('trim') ])
)
with_items: command.stdout_lines
This will give the following output (stripped for the example):
"postconf_d": {
"alias_database": "hash:/etc/aliases",
"alias_maps": "hash:/etc/aliases, nis:mail.aliases",
"allow_min_user": "no",
"allow_percent_hack": "yes"
}
Going even further, parse the lists in the 'value':
- name: 'set postfix default configuration as fact'
set_fact:
postconf_d: >-
{% set key, val = item.partition('=')[::2]|map('trim') -%}
{% if ',' in val -%}
{% set val = val.split(',')|map('trim')|list -%}
{% endif -%}
{{ postfix_default_main_cf | combine({key: val}) }}
with_items: command.stdout_lines
...
"postconf_d": {
"alias_database": "hash:/etc/aliases",
"alias_maps": [
"hash:/etc/aliases",
"nis:mail.aliases"
],
"allow_min_user": "no",
"allow_percent_hack": "yes"
}
A few things to notice:
in this case it's needed to "trim" everything (using the >-
in YAML and -%}
in Jinja), otherwise you'll get an error like:
FAILED! => {"failed": true, "msg": "|combine expects dictionaries, got u\" {u'...
obviously the {% if ..
is far from bullet-proof
in the postfix case, val.split(',')|map('trim')|list
could have been simplified to val.split(', ')
, but I wanted to point out the fact you will need to |list
otherwise you'll get an error like:
"|combine expects dictionaries, got u\"{u'...': <generator object do_map at ...
Hope this can help.
I'm posting this answer because the one with the most votes led me astray. To redirect from a servlet, you simply do this:
response.sendRedirect("simpleList.do")
In this particular question, I think @M-D is correctly explaining why the asker is having his problem, but since this is the first result on google when you search for "Redirect from Servlet" I think it's important to have an answer that helps most people, not just the original asker.
If you want them on separate lines do what Balon said. If you want them on the same lines, do:
<td>
<div style="float:left;width:50%;">this is left</div>
<div style="float:right;width:50%;">this is right</div>
</td>
Provided you cannot use TreeMap
, in Java 8 we can make use of toMap() method in Collectors
which takes following parameters:
Java 8 Example
Map<String,String> sample = new HashMap<>(); // push some values to map
Map<String, String> newMapSortedByKey = sample.entrySet().stream()
.sorted(Map.Entry.<String,String>comparingByKey().reversed())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
Map<String, String> newMapSortedByValue = sample.entrySet().stream()
.sorted(Map.Entry.<String,String>comparingByValue().reversed())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1,e2) -> e1, LinkedHashMap::new));
We can modify the example to use custom comparator and to sort based on keys as:
Map<String, String> newMapSortedByKey = sample.entrySet().stream()
.sorted((e1,e2) -> e1.getKey().compareTo(e2.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1,e2) -> e1, LinkedHashMap::new));
To complete,
In a shell (bash) script, you can use \r
to send cursor, in front on line and, of course \n
to put cursor on a new line.
For example, try :
echo -en "AA--AA" ; echo -en "BB" ; echo -en "\rBB"
AA--AA
AA--AABB
BB--AABB
But don't forget to use -en
as parameters.
/bookstore/book[@location='US'][1]
works only with simple structure.
Add a bit more structure and things break.
With-
<bookstore>
<category>
<book location="US">A1</book>
<book location="FIN">A2</book>
</category>
<category>
<book location="FIN">B1</book>
<book location="US">B2</book>
</category>
</bookstore>
/bookstore/category/book[@location='US'][1]
yields
<book location="US">A1</book>
<book location="US">B2</book>
not "the first node that matches a more complicated condition". /bookstore/category/book[@location='US'][2]
returns nothing.
With parentheses you can get the result the original question was for:
(/bookstore/category/book[@location='US'])[1]
gives
<book location="US">A1</book>
and (/bookstore/category/book[@location='US'])[2]
works as expected.
I don't think there are any machine code decompilers that produce Pascal code. Most "Delphi decompilers" parse form and RTTI data, but do not actually decompile the machine code. I can only recommend using something like DeDe (or similar software) to extract symbol information in combination with a C decompiler, then translate the decompiled C code to Delphi (there are many source code converters out there).
Declare @date1 datetime
Declare @date2 datetime
Set @date1 = '11/20/2009 11:00:00 AM'
Set @date2 = '11/20/2009 12:00:00 PM'
Select Cast(DateDiff(hh, @date1, @date2) as decimal(3,2)) as HoursApart
Result = 1.00
(Taken from my comment)
pip
won't handle system level dependencies. You'll have to apt-get install libfreetype6-dev
before continuing. (It even says so right in your output. Try skimming over it for such errors next time, usually build outputs are very detailed)
I needeed to solve very similar problem, which is configuring Jackson Mapper to "Do not serialize null values for Christ's sake!!!".
I didn't want to leave fancy mvc:annotation-driven tag, so I found, how to configure Jackson's ObjectMapper without removing mvc:annotation-driven and adding not really fancy ContentNegotiatingViewResolver.
The beautiful thing is that you don't have to write any Java code yourself!
And here is the XML configuration (don't be confused with different namespaces of Jackson classes, I simply used new Jakson 2.x library ... the same should also work with Jackson 1.x libraries):
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="serializationInclusion">
<value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
Try this:
String numberStr = "3.5";
Float number = null;
try {
number = Float.parseFloat(numberStr);
} catch (NumberFormatException e) {
System.out.println("numberStr is not a number");
}
Tested on 4.5.4:
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (TrustStrategy) (arg0, arg1) -> true).build();
CloseableHttpClient httpClient = HttpClients
.custom()
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.setSSLContext(sslContext)
.build();
If you need to return a JSON object using a String, then the following should work:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.ResponseEntity;
...
@RestController
@RequestMapping("/student")
public class StudentController {
@GetMapping
@RequestMapping("/")
public ResponseEntity<JsonNode> get() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree("{\"id\": \"132\", \"name\": \"Alice\"}");
return ResponseEntity.ok(json);
}
...
}
Easy as pie:
Open Eclipse and go to Help-> Software Updates-> Find and Install Select "Search for new features to install" and click "Next" Create a New Remote Site with the following details:
Name: PDT
URL: http://download.eclipse.org/tools/pdt/updates/4.0.1
Get the latest above mentioned URLfrom -
http://www.eclipse.org/pdt/index.html#download
Check the PDT box and click "Next" to start the installation
Hope it helps
As already stated: closures, out of the box, cannot be serialized.
However, using the __sleep()
, __wakeup()
magic methods and reflection u CAN manually make closures serializable. For more details see extending-php-5-3-closures-with-serialization-and-reflection
This makes use of reflection and the php function eval. Do note this opens up the possibility of CODE injection, so please take notice of WHAT you are serializing.
Postgres hasn't implemented an equivalent to INSERT OR REPLACE
. From the ON CONFLICT
docs (emphasis mine):
It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.
Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE
applies more generally, since it lets you set new values based on preexisting data. For example:
INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;
If you want the table to still be 100% then set one of the columns to have a width:100%; That will extend that column to fill the extra space and allow the other columns to keep their auto width :)
Include the four lines written after the info for ellipsis to work
.app a
{
color: #fff;
font: bold 15px/18px Arial;
height: 18px;
margin: 0 5px 0 5px;
padding: 0;
position: relative;
text-align: center;
text-decoration: none;
width: 140px;
/*
Note: The Below 4 Lines are necessary for ellipsis to work.
*/
display: block;/* Change it as per your requirement. */
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
I've found the same thing, but only on emulators that have the Use Host GPU setting ticked. Try turning that off, you'll no longer see those warnings (and the emulator will run horribly, horribly slowly..)
In my experience those warnings are harmless. Notice that the "error" is EGL_SUCCESS, which would seem to indicate no error at all!
BigDecimal
, not double
The Answer by adatapost is right about using String::split
but wrong about using double
to represent your longitude-latitude values. The float
/Float
and double
/Double
types use floating-point technology which trades away accuracy for speed of execution.
Instead use BigDecimal
to correctly represent your lat-long values.
Also, best to let a library such as Apache Commons CSV perform the chore of reading and writing CSV or Tab-delimited files.
Here is a complete example app using that Commons CSV library. This app writes then reads a data file. It uses String::split
for the writing. And the app uses BigDecimal
objects to represent your lat-long values.
package work.basil.example;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class LatLong
{
//----------| Write |-----------------------------
public void write ( final Path path )
{
List < String > inputs =
List.of(
"28.515046280572285,77.38258838653564" ,
"28.51430151808072,77.38336086273193" ,
"28.513566177802456,77.38413333892822" ,
"28.512830832397192,77.38490581512451" ,
"28.51208605426073,77.3856782913208" ,
"28.511341270865113,77.38645076751709" );
// Use try-with-resources syntax to auto-close the `CSVPrinter`.
try ( final CSVPrinter printer = CSVFormat.RFC4180.withHeader( "latitude" , "longitude" ).print( path , StandardCharsets.UTF_8 ) ; )
{
for ( String input : inputs )
{
String[] fields = input.split( "," );
printer.printRecord( fields[ 0 ] , fields[ 1 ] );
}
} catch ( IOException e )
{
e.printStackTrace();
}
}
//----------| Read |-----------------------------
public void read ( Path path )
{
// TODO: Add a check for valid file existing.
try
{
// Read CSV file.
BufferedReader reader = Files.newBufferedReader( path );
Iterable < CSVRecord > records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse( reader );
for ( CSVRecord record : records )
{
BigDecimal latitude = new BigDecimal( record.get( "latitude" ) );
BigDecimal longitude = new BigDecimal( record.get( "longitude" ) );
System.out.println( "lat: " + latitude + " | long: " + longitude );
}
} catch ( IOException e )
{
e.printStackTrace();
}
}
//----------| Main |-----------------------------
public static void main ( String[] args )
{
LatLong app = new LatLong();
// Write
Path pathOutput = Paths.get( "/Users/basilbourque/lat-long.csv" );
app.write( pathOutput );
System.out.println( "Writing file: " + pathOutput );
// Read
Path pathInput = Paths.get( "/Users/basilbourque/lat-long.csv" );
app.read( pathInput );
System.out.println( "Done writing & reading lat-long data file. " + Instant.now() );
}
}
As mentioned above by @Ricky vue-router automatically applies two active classes, .router-link-active
and .router-link-exact-active
, to the component.
So, to change active link css use:
.router-link-exact-active{
//your desired design when link is clicked
font-weight: 700;
}
You can also run docker build with -f
option
docker build -t ubuntu-test:latest -f Dockerfile.custom .
In jquery you could try this $("#select_id>option:selected").text()
I find that one of the main reasons I need this is to split file paths on both /
and \
. It's a bit of a tricky regex so I'll post it here for reference:
var splitFilePath = filePath.split(/[\/\\]/);
You can customize the JsonSerializerSettings
by using the Formatters.JsonFormatter.SerializerSettings
property in the HttpConfiguration
object.
For example, you could do that in the Application_Start() method:
protected void Application_Start()
{
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.Formatting =
Newtonsoft.Json.Formatting.Indented;
}
For installing git
rpm -Uvh http://dl.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm
yum install git
try this
float rateX = (float)jpDisplayImagen.getWidth()/(float)img.getWidth();
float rateY = (float)jpDisplayImagen.getHeight()/(float)img.getHeight();
if (rateX>rateY){
int W=(int)(img.getWidth()*rateY);
int H=(int)(img.getHeight()*rateY);
jpDisplayImagen.getGraphics().drawImage(img, 0, 0,W,H, null);
}
else{
int W=(int)(img.getWidth()*rateX);
int H=(int)(img.getHeight()*rateX);
jpDisplayImagen.getGraphics().drawImage(img, 0, 0,W,H, null);
}
If you have newly upgraded your php version you might be forget to restart your webserver service.
In C++, Boost Variant implement a safe version of the union, designed to prevent undefined behavior as much as possible.
Its performances are identical to the enum + union
construct (stack allocated too etc) but it uses a template list of types instead of the enum
:)
When you want to show an URL of remote branches, try:
git remote -v
You could also use:
SELECT t.*
FROM
TABLENAME t
JOIN
( SELECT A, MAX(col_date) AS col_date
FROM TABLENAME
GROUP BY A
) m
ON m.A = t.A
AND m.col_date = t.col_date
You can do checks using lookarounds:
^(?=.*\bjack\b)(?=.*\bjames\b).*$
This approach has the advantage that you can easily specify multiple conditions.
^(?=.*\bjack\b)(?=.*\bjames\b)(?=.*\bjason\b)(?=.*\bjules\b).*$
You could follow this example:
#!/usr/bin/env python
"""
Use a pcolor or imshow with a custom colormap to make a contour plot.
Since this example was initially written, a proper contour routine was
added to matplotlib - see contour_demo.py and
http://matplotlib.sf.net/matplotlib.pylab.html#-contour.
"""
from pylab import *
delta = 0.01
x = arange(-3.0, 3.0, delta)
y = arange(-3.0, 3.0, delta)
X,Y = meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = Z2 - Z1 # difference of Gaussians
cmap = cm.get_cmap('PiYG', 11) # 11 discrete colors
im = imshow(Z, cmap=cmap, interpolation='bilinear',
vmax=abs(Z).max(), vmin=-abs(Z).max())
axis('off')
colorbar()
show()
which produces the following image:
According to the pytest docs, pytest --capture=sys
should work. If you want to capture standard out inside a test, refer to the capsys fixture.
You can sort a map by value as below, more example here
//Sort a Map by their Value.
Map<Integer, String> random = new HashMap<Integer, String>();
random.put(1,"z");
random.put(6,"k");
random.put(5,"a");
random.put(3,"f");
random.put(9,"c");
Map<Integer, String> sortedMap =
random.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(e1, e2) -> e2, LinkedHashMap::new));
System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray()));
To avoid escaping lot of characters:
echo <<<MYSCRIPT
... script here...
MYSCRIPT;
or just turn off php parsing for a while:
?>
...your script here
<?php
You're most likely looking at using a flash/silverlight/activeX control. The <input type="file" />
control doesn't handle that.
If you don't mind the user selecting a file as a means to getting its directory, you may be able to bind to that control's change
event then strip the filename portion and save the path somewhere--but that's about as good as it gets.
Keep in mind that webpages are designed to interact with servers. Nothing about providing a local directory to a remote server is "typical" (a server can't access it so why ask for it?); however files are a means to selectively passing information.
There is another way of performing the fit, which is by using the 'lmfit' package. It basically uses the cuve_fit but is much better in fitting and offers complex fitting as well. Detailed step by step instructions are given in the below link. http://cars9.uchicago.edu/software/python/lmfit/model.html#model.best_fit
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:buttonStyle">@style/Button</item>
</style>
<style name="Button" parent="Widget.AppCompat.Button">
<item name="android:textAllCaps">false</item>
</style>
For the sake of completion:
apply(people[,-1], 2, function(x) sum(x))
#Height Weight
# 199 425
The name
attribute on an input is used by its parent HTML <form>
s to include that element as a member of the HTTP form in a POST
request or the query string in a GET
request.
The id
should be unique as it should be used by JavaScript to select the element in the DOM for manipulation and used in CSS selectors.
BigInteger has a constructor where you can pass string as an argument.
try below,
private void sum(String newNumber) {
// BigInteger is immutable, reassign the variable:
this.sum = this.sum.add(new BigInteger(newNumber));
}
If you want to create a generic script you can do it with an Execute statement with a Replace with your username and database name
Declare @userName as varchar(50);
Declare @defaultDataBaseName as varchar(50);
Declare @LoginCreationScript as varchar(max);
Declare @UserCreationScript as varchar(max);
Declare @TempUserCreationScript as varchar(max);
set @defaultDataBaseName = 'data1';
set @userName = 'domain\userName';
set @LoginCreationScript ='CREATE LOGIN [{userName}]
FROM WINDOWS
WITH DEFAULT_DATABASE ={dataBaseName}'
set @UserCreationScript ='
USE {dataBaseName}
CREATE User [{userName}] for LOGIN [{userName}];
EXEC sp_addrolemember ''db_datareader'', ''{userName}'';
EXEC sp_addrolemember ''db_datawriter'', ''{userName}'';
Grant Execute on Schema :: dbo TO [{userName}];'
/*Login creation*/
set @LoginCreationScript=Replace(Replace(@LoginCreationScript, '{userName}', @userName), '{dataBaseName}', @defaultDataBaseName)
set @UserCreationScript =Replace(@UserCreationScript, '{userName}', @userName)
Execute(@LoginCreationScript)
/*User creation and role assignment*/
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', @defaultDataBaseName)
Execute(@TempUserCreationScript)
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', 'db2')
Execute(@TempUserCreationScript)
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', 'db3')
Execute(@TempUserCreationScript)
try this code it doesn't show “For development purposes only”
<iframe src="http://maps.google.com/maps?q=25.3076008,51.4803216&z=16&output=embed" height="450" width="600"></iframe>
Check if element's ID is exist
if ($('#id').attr('id') == 'id')_x000D_
{_x000D_
//OK_x000D_
}
_x000D_
In my case table was not created for the first time without last property listed below:
<properties>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hbm2ddl.auto" value="create-drop"/>
<!-- without below table was not created -->
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create" />
</properties>
used Wildfly's in-memory H2 database
In Vim, use :insert
. This will keep all your formatting and not do autoindenting. For more information help :insert
.
I just want to add that this nearly identical post provides the very useful alternative of using an echo pipe if no force or quiet switch is available. For instance, I think it's the only way to bypass the Y/N prompt in this example.
Echo y|NETDOM COMPUTERNAME WorkComp /Add:Work-Comp
In a general sense you should first look at your command switches for /f, /q, or some variant thereof (for example, Netdom RenameComputer uses /Force, not /f). If there is no switch available, then use an echo pipe.
If you pass a reference to the (concrete subclass of) fragment into the async task, you can then access the fragment directly.
Some ways of passing the fragment reference into the async task:
class FooTask extends AsyncTask
), then pass your fragment into the constructor.I would suggest you just evenly space them as shown in this answer here
.navbar ul {
list-style-type: none;
padding: 0;
display: flex;
flex-direction: row;
justify-content: space-around;
flex-wrap: nowrap; /* assumes you only want one row */
}
I've published a Python [3] tree implementation on my site: http://www.quesucede.com/page/show/id/python_3_tree_implementation.
Hope it is of use,
Ok, here's the code:
import uuid
def sanitize_id(id):
return id.strip().replace(" ", "")
(_ADD, _DELETE, _INSERT) = range(3)
(_ROOT, _DEPTH, _WIDTH) = range(3)
class Node:
def __init__(self, name, identifier=None, expanded=True):
self.__identifier = (str(uuid.uuid1()) if identifier is None else
sanitize_id(str(identifier)))
self.name = name
self.expanded = expanded
self.__bpointer = None
self.__fpointer = []
@property
def identifier(self):
return self.__identifier
@property
def bpointer(self):
return self.__bpointer
@bpointer.setter
def bpointer(self, value):
if value is not None:
self.__bpointer = sanitize_id(value)
@property
def fpointer(self):
return self.__fpointer
def update_fpointer(self, identifier, mode=_ADD):
if mode is _ADD:
self.__fpointer.append(sanitize_id(identifier))
elif mode is _DELETE:
self.__fpointer.remove(sanitize_id(identifier))
elif mode is _INSERT:
self.__fpointer = [sanitize_id(identifier)]
class Tree:
def __init__(self):
self.nodes = []
def get_index(self, position):
for index, node in enumerate(self.nodes):
if node.identifier == position:
break
return index
def create_node(self, name, identifier=None, parent=None):
node = Node(name, identifier)
self.nodes.append(node)
self.__update_fpointer(parent, node.identifier, _ADD)
node.bpointer = parent
return node
def show(self, position, level=_ROOT):
queue = self[position].fpointer
if level == _ROOT:
print("{0} [{1}]".format(self[position].name, self[position].identifier))
else:
print("\t"*level, "{0} [{1}]".format(self[position].name, self[position].identifier))
if self[position].expanded:
level += 1
for element in queue:
self.show(element, level) # recursive call
def expand_tree(self, position, mode=_DEPTH):
# Python generator. Loosly based on an algorithm from 'Essential LISP' by
# John R. Anderson, Albert T. Corbett, and Brian J. Reiser, page 239-241
yield position
queue = self[position].fpointer
while queue:
yield queue[0]
expansion = self[queue[0]].fpointer
if mode is _DEPTH:
queue = expansion + queue[1:] # depth-first
elif mode is _WIDTH:
queue = queue[1:] + expansion # width-first
def is_branch(self, position):
return self[position].fpointer
def __update_fpointer(self, position, identifier, mode):
if position is None:
return
else:
self[position].update_fpointer(identifier, mode)
def __update_bpointer(self, position, identifier):
self[position].bpointer = identifier
def __getitem__(self, key):
return self.nodes[self.get_index(key)]
def __setitem__(self, key, item):
self.nodes[self.get_index(key)] = item
def __len__(self):
return len(self.nodes)
def __contains__(self, identifier):
return [node.identifier for node in self.nodes if node.identifier is identifier]
if __name__ == "__main__":
tree = Tree()
tree.create_node("Harry", "harry") # root node
tree.create_node("Jane", "jane", parent = "harry")
tree.create_node("Bill", "bill", parent = "harry")
tree.create_node("Joe", "joe", parent = "jane")
tree.create_node("Diane", "diane", parent = "jane")
tree.create_node("George", "george", parent = "diane")
tree.create_node("Mary", "mary", parent = "diane")
tree.create_node("Jill", "jill", parent = "george")
tree.create_node("Carol", "carol", parent = "jill")
tree.create_node("Grace", "grace", parent = "bill")
tree.create_node("Mark", "mark", parent = "jane")
print("="*80)
tree.show("harry")
print("="*80)
for node in tree.expand_tree("harry", mode=_WIDTH):
print(node)
print("="*80)
I have tried the following command on Ubuntu and its working for me
sudo apt-get install php7.0-mysql
Thanks
In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.
You can try this sample code:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:id="@+id/rootLayout">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MOVE" android:layout_centerHorizontal="true"/>
<ImageView
android:id="@+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
<ImageView
android:id="@+id/img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
<ImageView
android:id="@+id/img3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">
<ImageView
android:id="@+id/img4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>
</LinearLayout>
</RelativeLayout>
Your activity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById( R.id.btn1 )).setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View v)
{
ImageView img = (ImageView) findViewById( R.id.img1 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img2 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img3 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img4 );
moveViewToScreenCenter( img );
}
});
}
private void moveViewToScreenCenter( View view )
{
RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics( dm );
int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();
int originalPos[] = new int[2];
view.getLocationOnScreen( originalPos );
int xDest = dm.widthPixels/2;
xDest -= (view.getMeasuredWidth()/2);
int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;
TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
anim.setDuration(1000);
anim.setFillAfter( true );
view.startAnimation(anim);
}
The method moveViewToScreenCenter
gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset
variable measures the status bar height.
I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.
On my Linux system (Centos 6.2), there is a significant difference between declaring the target .PHONY and creating a fake dependency on FORCE, when the rule actually does create a file matching the target. When the file must be regenerated every time, it required both the fake dependency FORCE on the file, and .PHONY for the fake dependency.
wrong:
date > $@
right:
FORCE
date > $@
FORCE:
.PHONY: FORCE
I want to share something that blocked us for a couple of days: the fileprovider code MUST be inserted between the application tags, not after it. It may be trivial, but it's never specified, and I thought that I could have helped someone! (thanks again to piolo94)
Issue could be that the Activity
have been finished
or in progress of finishing
.
Add a check isFinishing
, and dismiss dialog only when this is false
if (!YourActivity.this.isFinishing() && pDialog != null) {
pDialog.dismiss();
}
isFinishing : Check to see whether this activity is in the process of finishing,either because you called finish
on it or someone else has requested that it finished.
I had to remove packages folder close and re-open (VS2015) solution. I was not migrating and I did not have packages checked into source control. All I can say is something got messed up and this fixed it.
You can also achieve this using the backreference technique
sed -i.bak 's/\(.*\)/\1:80/' foo.txt
You can also use with awk like this
awk '{print $0":80"}' foo.txt > tmp && mv tmp foo.txt
Andrew Willem's solutions are not mobile device compatible.
Here's a modification of his second solution that works in Edge, IE, Opera, FF, Chrome, iOS Safari and mobile equivalents (that I could test):
Update 1: Removed "requestAnimationFrame" portion, as I agree it's not necessary:
var listener = function() {
// do whatever
};
slider1.addEventListener("input", function() {
listener();
slider1.addEventListener("change", listener);
});
slider1.addEventListener("change", function() {
listener();
slider1.removeEventListener("input", listener);
});
Update 2: Response to Andrew's 2nd Jun 2016 updated answer:
Thanks, Andrew - that appears to work in every browser I could find (Win desktop: IE, Chrome, Opera, FF; Android Chrome, Opera and FF, iOS Safari).
Update 3: if ("oninput in slider) solution
The following appears to work across all the above browsers. (I cannot find the original source now.) I was using this, but it subsequently failed on IE and so I went looking for a different one, hence I ended up here.
if ("oninput" in slider1) {
slider1.addEventListener("input", function () {
// do whatever;
}, false);
}
But before I checked your solution, I noticed this was working again in IE - perhaps there was some other conflict.
Type "msg /?" in the command prompt to get various ways of sending meessages to a user.
Type "net send /?" in the command prompt to get another variation of sending messages across.
<input onchange="readURL(this);" type="file" name="userfile" />
<img src="" id="viewImage"/>
<script>
function readURL(fileName) {
if (fileName.files && fileName.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#viewImage')
.attr('src', e.target.result)
.width(150).height(200);
};
reader.readAsDataURL(fileName.files[0]);
}
}
</script>
var selectoption = document.getElementById("dropdown");
var optionText = selectoption.options[selectoption.selectedIndex].text;
This is what I used to copy some resource files: the copy-files is an empty target to ignore errors
add_custom_target(copy-files ALL
COMMAND ${CMAKE_COMMAND} -E copy_directory
${CMAKE_BINARY_DIR}/SOURCEDIRECTORY
${CMAKE_BINARY_DIR}/DESTINATIONDIRECTORY
)
The simplest way to find the framework version of the current .NET project is:
We don't want to duplicate the entire data structure, or use an array where we need an associative array.
Here's another way to do the same thing as bonna:
var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};_x000D_
keysSorted = Object.keys(list).sort(function(a,b){return list[a]-list[b]})_x000D_
console.log(keysSorted); // bar,me,you,foo
_x000D_
Put quotes around the <?php echo $cname; ?>
to make sure Javascript accepts it as a string, also consider escaping.
Go to your Models and check, because you might have truncated a number of words for that particular column eg. max_length="150".
If the request calls are buried somewhere deep in the code and you do not want to install the server certificate, then, just for debug purposes only, it's possible to monkeypatch requests:
import requests.api
import warnings
def requestspatch(method, url, **kwargs):
kwargs['verify'] = False
return _origcall(method, url, **kwargs)
_origcall = requests.api.request
requests.api.request = requestspatch
warnings.warn('Patched requests: SSL verification disabled!')
Never use in production!
I installed python2.7 to solve this issue. I wish can help you.
You can use C++0x auto
keyword together with template specialization on for example a function named boost::make_array()
(similar to make_pair()
). For the case of where N
is either 1 or 2 arguments we can then write variant A as
namespace boost
{
/*! Construct Array from @p a. */
template <typename T>
boost::array<T,1> make_array(const T & a)
{
return boost::array<T,2> ({{ a }});
}
/*! Construct Array from @p a, @p b. */
template <typename T>
boost::array<T,2> make_array(const T & a, const T & b)
{
return boost::array<T,2> ({{ a, b }});
}
}
and variant B as
namespace boost {
/*! Construct Array from @p a. */
template <typename T>
boost::array<T,1> make_array(const T & a)
{
boost::array<T,1> x;
x[0] = a;
return x;
}
/*! Construct Array from @p a, @p b. */
template <typename T>
boost::array<T,2> make_array(const T & a, const T & b)
{
boost::array<T,2> x;
x[0] = a;
x[1] = b;
return x;
}
}
GCC-4.6 with -std=gnu++0x
and -O3
generates the exact same binary code for
auto x = boost::make_array(1,2);
using both A and B as it does for
boost::array<int, 2> x = {{1,2}};
For user defined types (UDT), though, variant B results in an extra copy constructor, which usually slow things down, and should therefore be avoided.
Note that boost::make_array
errors when calling it with explicit char array literals as in the following case
auto x = boost::make_array("a","b");
I believe this is a good thing as const char*
literals can be deceptive in their use.
Variadic templates, available in GCC since 4.5, can further be used reduce all template specialization boiler-plate code for each N
into a single template definition of boost::make_array()
defined as
/*! Construct Array from @p a, @p b. */
template <typename T, typename ... R>
boost::array<T,1+sizeof...(R)> make_array(T a, const R & ... b)
{
return boost::array<T,1+sizeof...(R)>({{ a, b... }});
}
This works pretty much as we expect. The first argument determines boost::array
template argument T
and all other arguments gets converted into T
. For some cases this may undesirable, but I'm not sure how if this is possible to specify using variadic templates.
Perhaps boost::make_array()
should go into the Boost Libraries?
I know this post is old but...
I was able to do this, my problem was that I forgot to make my property static.
public static class MyStaticClass
{
private static NonStaticObject _myObject = new NonStaticObject();
//property
public static NonStaticObject MyObject
{
get { return _myObject; }
set { _myObject = value; }
}
}
You can use CSS3 transitions with rotate()
to spin the image on hover.
img {_x000D_
border-radius: 50%;_x000D_
-webkit-transition: -webkit-transform .8s ease-in-out;_x000D_
transition: transform .8s ease-in-out;_x000D_
}_x000D_
img:hover {_x000D_
-webkit-transform: rotate(360deg);_x000D_
transform: rotate(360deg);_x000D_
}
_x000D_
<img src="https://i.stack.imgur.com/BLkKe.jpg" width="100" height="100"/>
_x000D_
Here is a fiddle DEMO
More info and references :
When passing an array as a parameter, this
void arraytest(int a[])
means exactly the same as
void arraytest(int *a)
so you are modifying the values in main.
For historical reasons, arrays are not first class citizens and cannot be passed by value.
I found this related question: Directory Listing in S3 Static Website
As it turns out, if you enable public read for the whole bucket, S3 can serve directory listings. Problem is they are in XML instead of HTML, so not very user-friendly.
There are three ways you could go for generating listings:
Generate index.html files for each directory on your own computer, upload them to s3, and update them whenever you add new files to a directory. Very low-tech. Since you're saying you're uploading build files straight from Travis, this may not be that practical since it would require doing extra work there.
Use a client-side S3 browser tool.
Use a server-side browser tool.
Can't be done as it stands... The code
def myMethod(pParm1='1', pParm2='2'){
println "${pParm1}${pParm2}"
}
Basically makes groovy create the following methods:
Object myMethod( pParm1, pParm2 ) {
println "$pParm1$pParm2"
}
Object myMethod( pParm1 ) {
this.myMethod( pParm1, '2' )
}
Object myMethod() {
this.myMethod( '1', '2' )
}
One alternative would be to have an optional Map as the first param:
def myMethod( Map map = [:], String mandatory1, String mandatory2 ){
println "${mandatory1} ${mandatory2} ${map.parm1 ?: '1'} ${map.parm2 ?: '2'}"
}
myMethod( 'a', 'b' ) // prints 'a b 1 2'
myMethod( 'a', 'b', parm1:'value' ) // prints 'a b value 2'
myMethod( 'a', 'b', parm2:'2nd') // prints 'a b 1 2nd'
Obviously, documenting this so other people know what goes in the magical map
and what the defaults are is left to the reader ;-)
I experienced the same issue.
To ensure that your Android Device is expecting the correct fingerprint from the system (e.g. after switching Android SDK installations -> different adb server running!), do the following (actually, this did the magic for me):
Width can be set to specific column as below: By percentages:
<asp:BoundField HeaderText="UserInfo" DataField="UserInfo"
SortExpression="UserInfo" ItemStyle-Width="100%"></asp:BoundField>
OR
By pixel:
<asp:BoundField HeaderText="UserInfo" DataField="UserInfo"
SortExpression="UserInfo" ItemStyle-Width="500px"></asp:BoundField>
There are three char types: (plain) char
, signed char
and unsigned char
. Any char is usually an 8-bit integer* and in that sense, a signed
and unsigned char
have a useful meaning (generally equivalent to uint8_t
and int8_t
). When used as a character in the sense of text, use a char
(also referred to as a plain char). This is typically a signed char
but can be implemented either way by the compiler.
* Technically, a char can be any size as long as sizeof(char)
is 1, but it is usually an 8-bit integer.
jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.
from pandas import DataFrame, concat
a = DataFrame([{'a':1, 'c':2,'d':3 }])
b = DataFrame([{'a':4,'b':5, 'd':6,'e':7}])
>>> concat([a,b],sort=False)
a c d b e
0 1 2.0 3 NaN NaN
0 4 NaN 6 5.0 7.0
>>> concat([a,b],sort=True)
a b c d e
0 1 NaN 2.0 3 NaN
0 4 5.0 NaN 6 7.0
Just press Ctrl + Shift + R and see...
In SQL Server Management Studio, Ctrl+Shift+R refreshes the local cache.
Try this,
IFS=''
while read line
do
echo $line
done < file.txt
EDIT:
From man bash
IFS - The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with the read builtin command. The default value is
``<space><tab><newline>''
You can also use:
driver.switch_to.frame(0)
(0)
being the first iframe on the html.
to switch back to the default content:
driver.switch_to.default_content()
If you have a browser that doesn't support the calc
expression, it's not hard to mimic with jQuery:
$('#yourEl').css('width', '100%').css('width', '-=100px');
It's much easier to let jQuery handle the relative calculation than doing it yourself.
Number((6.688689).toFixed(1)); // 6.7
var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;
Use toFixed()
function.
(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"
cat file.txt | grep "company_name" | cut -d '=' -f 2 | cut -d ';' -f 1
for Console you'll probably need
sys.stdout.flush()
to force update. I think using ,
in print will block stdout from flushing and somehow it won't update