The java.net.URI class can help; in the documentation of URL you find
Note, the URI class does perform escaping of its component fields in certain circumstances. The recommended way to manage the encoding and decoding of URLs is to use an URI
Use one of the constructors with more than one argument, like:
URI uri = new URI(
"http",
"search.barnesandnoble.com",
"/booksearch/first book.pdf",
null);
URL url = uri.toURL();
//or String request = uri.toString();
(the single-argument constructor of URI does NOT escape illegal characters)
Only illegal characters get escaped by above code - it does NOT escape non-ASCII characters (see fatih's comment).
The toASCIIString
method can be used to get a String only with US-ASCII characters:
URI uri = new URI(
"http",
"search.barnesandnoble.com",
"/booksearch/é",
null);
String request = uri.toASCIIString();
For an URL with a query like http://www.google.com/ig/api?weather=São Paulo
, use the 5-parameter version of the constructor:
URI uri = new URI(
"http",
"www.google.com",
"/ig/api",
"weather=São Paulo",
null);
String request = uri.toASCIIString();
You can just use top
It will display everything running on your OSX
Resharper is good for this like others have stated. Be careful though, these tools don't find you code that is used by reflection, e.g. cannot know if some code is NOT used by reflection.
Here is my answer:
services.msc
, Enter"D:/Program Files/MySQL/MySQL Server 5.6/bin\mysqld" --defaults-file="D:\ProgramData\MySQL\MySQL Server 5.6\my.ini" MySQL56
Full answer here: https://stackoverflow.com/a/20136523/1316649
For inner joins I have not really noticed a difference (but as with all performance tuning, you need to check against your database under your conditions).
However where you put the condition makes a huge difference if you are using left or right joins. For instance consider these two queries:
SELECT *
FROM dbo.Customers AS CUS
LEFT JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
WHERE ORD.OrderDate >'20090515'
SELECT *
FROM dbo.Customers AS CUS
LEFT JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
AND ORD.OrderDate >'20090515'
The first will give you only those records that have an order dated later than May 15, 2009 thus converting the left join to an inner join.
The second will give those records plus any customers with no orders. The results set is very different depending on where you put the condition. (Select * is for example purposes only, of course you should not use this in production code.)
The exception to this is when you want to see only the records in one table but not the other. Then you use the where clause for the condition not the join.
SELECT *
FROM dbo.Customers AS CUS
LEFT JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
WHERE ORD.OrderID is null
Another possible way, in order to make the colors a bit more intense, is this one:
<span class="badge progress-bar-info">10</span>
<span class="badge progress-bar-success">20</span>
<span class="badge progress-bar-warning">30</span>
<span class="badge progress-bar-danger">40</span>
See Bootply
Here's the simple, built-in way:
<span title="My tip">text</span>
That gives you plain text tooltips. If you want rich tooltips, with formatted HTML in them, you'll need to use a library to do that. Fortunately there are loads of those.
Cast it to its real type if you now the type for example it is oriented from class named abc. You can call your function in this way :
(abc)(obj)).MyFunction();
if you don't know the function it can be done in a different way. Not easy always. But you can find it in some way by it's signature. If this is your case, you should let us know.
That can be done by using some/every methods of Array and RegEx.
To check whether ALL of words from list(array) are present in the string:
const multiSearchAnd = (text, searchWords) => (
searchWords.every((el) => {
return text.match(new RegExp(el,"i"))
})
)
multiSearchAnd("Chelsey Dietrich Engineer 2018-12-11 Hire", ["cle", "hire"]) //returns false
multiSearchAnd("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "hire"]) //returns true
To check whether ANY of words from list(array) are present in the string:
const multiSearchOr = (text, searchWords) => (
searchWords.some((el) => {
return text.match(new RegExp(el,"i"))
})
)
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "hire"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["aaa", "hire"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "zzzz"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["aaa", "1111"]) //returns false
You can use sessionStorage it is similar to localStorage but sessionStorage gets clear when the page session ends while localStorage has no expiration set.
See https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
Similar to @Piotr Lewandowski's answer, but within a forEach
:
const config: MyConfig = { ... };
Object.keys(config)
.forEach((key: keyof MyConfig) => {
if (config[key]) {
// ...
}
});
If the answer from falsetru didn't work you could also try:
>>> b'a string'.decode('utf-8')
'a string'
You must use the labels index you have, here what I do for text classification:
# data labels = [1, 2, 1...]
labels_index = { "website" : 0, "money" : 1 ....}
# to feed model
label_categories = to_categorical(np.asarray(labels))
Then, for predictions:
texts = ["hello, rejoins moi sur skype", "bonjour comment ça va ?", "tu me donnes de l'argent"]
sequences = tokenizer.texts_to_sequences(texts)
data = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH)
predictions = model.predict(data)
t = 0
for text in texts:
i = 0
print("Prediction for \"%s\": " % (text))
for label in labels_index:
print("\t%s ==> %f" % (label, predictions[t][i]))
i = i + 1
t = t + 1
This gives:
Prediction for "hello, rejoins moi sur skype":
website ==> 0.759483
money ==> 0.037091
under ==> 0.010587
camsite ==> 0.114436
email ==> 0.075975
abuse ==> 0.002428
Prediction for "bonjour comment ça va ?":
website ==> 0.433079
money ==> 0.084878
under ==> 0.048375
camsite ==> 0.036674
email ==> 0.369197
abuse ==> 0.027798
Prediction for "tu me donnes de l'argent":
website ==> 0.006223
money ==> 0.095308
under ==> 0.003586
camsite ==> 0.003115
email ==> 0.884112
abuse ==> 0.007655
Your script is right. But by default is of None type. So it considers true of any other value other than None is assigned to args.argument_name variable.
I would suggest you to add a action="store_true". This would make the True/False type of flag. If used its True else False.
import argparse
parser = argparse.ArgumentParser('parser-name')
parser.add_argument("-f","--flag",action="store_true",help="just a flag argument")
usage
$ python3 script.py -f
After parsing when checked with args.f it returns true,
args = parser.parse_args()
print(args.f)
>>>true
By default Wampserver comes configured as securely as it can, so Apache is set to only allow access from the machine running wamp. Afterall it is supposed to be a development server and not a live server.
Also there was a little error released with WAMPServer 2.4 where it used the old Apache 2.2 syntax instead of the new Apache 2.4 syntax for access rights.
You need to change the security setting on Apache to allow access from anywhere else, so edit your httpd.conf
file.
Change this section from :
# onlineoffline tag - don't remove
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
To :
# onlineoffline tag - don't remove
Require local
Require ip 192.168.0
The Require local
allows access from these ip's 127.0.0.1 & localhost & ::1
.
The statement Require ip 192.168.0
will allow you to access the Apache server from any ip on your internal network. Also it will allow access using the server mechines actual ip address from the server machine, as you are trying to do.
In version 3 and > of WAMPServer there is a Virtual Hosts pre defined for localhost
so you have to make the access privilage amendements in the Virtual Host definition config file
First dont amend the httpd.conf
file at all, leave it as you found it.
Using the menus, edit the httpd-vhosts.conf
file.
It should look like this :
<VirtualHost *:80>
ServerName localhost
DocumentRoot D:/wamp/www
<Directory "D:/wamp/www/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
Amend it to
<VirtualHost *:80>
ServerName localhost
DocumentRoot D:/wamp/www
<Directory "D:/wamp/www/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
Hopefully you will have created a Virtual Host for your project and not be using the wamp\www
folder for your site. In that case leave the localhost definition alone and make the change only to your Virtual Host.
Dont forget to restart Apache after making this change
This error happens if you did not set the password on install, in this case the mysql using unix-socket plugin.
But if delete the plugin link from settings (table mysql.user) will other problem. This does not fix the problem and creates another problem. To fix the deleted link and set password ("PWD") do:
1) Run with --skip-grant-tables as said above.
If it doesnt works then add the string skip-grant-tables in section [mysqld] of /etc/mysql/mysql.conf.d/mysqld.cnf. Then do sudo service mysql restart.
2) Run mysql -u root -p, then (change "PWD"):
update mysql.user
set authentication_string=PASSWORD("PWD"), plugin="mysql_native_password"
where User='root' and Host='localhost';
flush privileges;
quit
then sudo service mysql restart. Check: mysql -u root -p.
Before restart remove that string from file mysqld.cnf, if you set it there.
@bl79 is the author of this answer, i've just reposted it, because it does help!
I'm surprised no one has mentioned the obvious bash
solution utilizing only while
and read
.
while read -n1 character; do
echo "$character"
done < <(echo -n "$words")
Note the use of echo -n
to avoid the extraneous newline at the end. printf
is another good option and may be more suitable for your particular needs. If you want to ignore whitespace then replace "$words"
with "${words// /}"
.
Another option is fold
. Please note however that it should never be fed into a for loop. Rather, use a while loop as follows:
while read char; do
echo "$char"
done < <(fold -w1 <<<"$words")
The primary benefit to using the external fold
command (of the coreutils package) would be brevity. You can feed it's output to another command such as xargs
(part of the findutils package) as follows:
fold -w1 <<<"$words" | xargs -I% -- echo %
You'll want to replace the echo
command used in the example above with the command you'd like to run against each character. Note that xargs
will discard whitespace by default. You can use -d '\n'
to disable that behavior.
I just tested fold
with some of the Asian characters and realized it doesn't have Unicode support. So while it is fine for ASCII needs, it won't work for everyone. In that case there are some alternatives.
I'd probably replace fold -w1
with an awk array:
awk 'BEGIN{FS=""} {for (i=1;i<=NF;i++) print $i}'
Or the grep
command mentioned in another answer:
grep -o .
FYI, I benchmarked the 3 aforementioned options. The first two were fast, nearly tying, with the fold loop slightly faster than the while loop. Unsurprisingly xargs
was the slowest... 75x slower.
Here is the (abbreviated) test code:
words=$(python -c 'from string import ascii_letters as l; print(l * 100)')
testrunner(){
for test in test_while_loop test_fold_loop test_fold_xargs test_awk_loop test_grep_loop; do
echo "$test"
(time for (( i=1; i<$((${1:-100} + 1)); i++ )); do "$test"; done >/dev/null) 2>&1 | sed '/^$/d'
echo
done
}
testrunner 100
Here are the results:
test_while_loop
real 0m5.821s
user 0m5.322s
sys 0m0.526s
test_fold_loop
real 0m6.051s
user 0m5.260s
sys 0m0.822s
test_fold_xargs
real 7m13.444s
user 0m24.531s
sys 6m44.704s
test_awk_loop
real 0m6.507s
user 0m5.858s
sys 0m0.788s
test_grep_loop
real 0m6.179s
user 0m5.409s
sys 0m0.921s
You were close. You can do:
var element = $("#parentDiv").find(".myClassNameOfInterest");
.find()
- http://api.jquery.com/findAlternatively, you can do:
var element = $(".myClassNameOfInterest", "#parentDiv");
...which sets the context of the jQuery object to the #parentDiv
.
EDIT:
Additionally, it may be faster in some browsers if you do div.myClassNameOfInterest
instead of just .myClassNameOfInterest
.
Take your image into an image editor, turn down the opacity, save it as a .png and use that instead.
Since FFT is symmetric over it's centre, half the values are just enough.
import numpy as np
import matplotlib.pyplot as plt
fs = 30.0
t = np.arange(0,10,1/fs)
x = np.cos(2*np.pi*10*t)
xF = np.fft.fft(x)
N = len(xF)
xF = xF[0:N/2]
fr = np.linspace(0,fs/2,N/2)
plt.ion()
plt.plot(fr,abs(xF)**2)
How to Use TempTable in Stored Procedure?
Here are the steps:
CREATE TEMP TABLE
-- CREATE TEMP TABLE
Create Table #MyTempTable (
EmployeeID int
);
INSERT TEMP SELECT DATA INTO TEMP TABLE
-- INSERT COMMON DATA
Insert Into #MyTempTable
Select EmployeeID from [EmployeeMaster] Where EmployeeID between 1 and 100
SELECT TEMP TABLE (You can now use this select query)
Select EmployeeID from #MyTempTable
FINAL STEP DROP THE TABLE
Drop Table #MyTempTable
I hope this will help. Simple and Clear :)
As long as you specify a width on the element, it should wrap itself without needing anything else.
For anyone else arriving here from Google search on how to do a string replacement on all columns (for example, if one has multiple columns like the OP's 'range' column):
Pandas has a built in replace
method available on a dataframe object.
df.replace(',', '-', regex=True)
Source: Docs
The beta version of Sencha Touch has drag and drop support.
You can refer to their DnD Example. This only works on webkit browsers by the way.
Retrofitting that logic into a web page is probably going to be difficult. As I understand it they disable all browser panning and implement panning events entirely in javascript, allowing correct interpretation of drag and drop.
Update: the original example link is dead, but I found this alternative:
https://github.com/kostysh/Drag-Drop-example-for-Sencha-Touch
This plagued me for over an hour.
If you're using the dataSrc option and column defs option, make sure they are in the correct locations. I had nested column defs in the ajax settings and lost way too much time figuring that out.
This is good:
This is not good:
Subtle difference, but real enough to cause hair loss.
Simple answer:
COUNT(*)
Notes:
COUNT(1) = COUNT(*) = COUNT(PrimaryKey) just in case
Edit:
SQL Server example (1.4 billion rows, 12 columns)
SELECT COUNT(*) FROM MyBigtable WITH (NOLOCK)
-- NOLOCK here is for me only to let me test for this answer: no more, no less
1 runs, 5:46 minutes, count = 1,401,659,700
--Note, sp_spaceused uses this DMV
SELECT
Total_Rows= SUM(st.row_count)
FROM
sys.dm_db_partition_stats st
WHERE
object_name(object_id) = 'MyBigtable' AND (index_id < 2)
2 runs, both under 1 second, count = 1,401,659,670
The second one has less rows = wrong. Would be the same or more depending on writes (deletes are done out of hours here)
Yes, it is correct. Its just a helper function to have a simpler way to access your state properties
Imagine you have a posts
key in your App state.posts
state.posts //
/*
{
currentPostId: "",
isFetching: false,
allPosts: {}
}
*/
And component Posts
By default connect()(Posts)
will make all state props available for the connected Component
const Posts = ({posts}) => (
<div>
{/* access posts.isFetching, access posts.allPosts */}
</div>
)
Now when you map the state.posts
to your component it gets a bit nicer
const Posts = ({isFetching, allPosts}) => (
<div>
{/* access isFetching, allPosts directly */}
</div>
)
connect(
state => state.posts
)(Posts)
mapDispatchToProps
normally you have to write dispatch(anActionCreator())
with bindActionCreators
you can do it also more easily like
connect(
state => state.posts,
dispatch => bindActionCreators({fetchPosts, deletePost}, dispatch)
)(Posts)
Now you can use it in your Component
const Posts = ({isFetching, allPosts, fetchPosts, deletePost }) => (
<div>
<button onClick={() => fetchPosts()} />Fetch posts</button>
{/* access isFetching, allPosts directly */}
</div>
)
An example of an actionCreator: deletePost
const deletePostAction = (id) => ({
action: 'DELETE_POST',
payload: { id },
})
So, bindActionCreators
will just take your actions, wrap them into dispatch
call. (I didn't read the source code of redux, but the implementation might look something like this:
const bindActionCreators = (actions, dispatch) => {
return Object.keys(actions).reduce(actionsMap, actionNameInProps => {
actionsMap[actionNameInProps] = (...args) => dispatch(actions[actionNameInProps].call(null, ...args))
return actionsMap;
}, {})
}
You can do this:
Declare @dbName nvarchar(max);
SET @dbName = 'TESTDB';
Declare @SQL nvarchar(max);
select @SQL = 'USE ' + @dbName +'; {can put command(s) here}';
EXEC (@SQL);
{but not here!}
This means you can do a recursive select like the following:
Declare @dbName nvarchar(max);
SET @dbName = 'TESTDB';
Declare @SQL nvarchar(max);
SELECT @SQL = 'USE ' + @dbName + '; ' +(Select ... {query here}
For XML Path(''),Type)
.value('text()[1]','nvarchar(max)');
Exec (@SQL)
Since the question Something like `this.class` instead of `ClassName.class`? is marked as a duplicate for this one (which is arguable because that question is about the class rather than class name), I'm posting the answer here:
class MyService {
private static Class thisClass = MyService.class;
// or:
//private static Class thisClass = new Object() { }.getClass().getEnclosingClass();
...
static void startService(Context context) {
Intent i = new Intent(context, thisClass);
context.startService(i);
}
}
It is important to define thisClass
as private because:
1) it must not be inherited: derived classes must either define their own thisClass
or produce an error message
2) references from other classes should be done as ClassName.class
rather than ClassName.thisClass
.
With thisClass
defined, access to the class name becomes:
thisClass.getName()
You should not need to add this back in. This was removed purposefully. The documentation has changed somewhat and the CSS class that is necessary ("nav-stacked") is only mentioned under the pills component, but should work for tabs as well.
This tutorial shows how to use the Bootstrap 3 setup properly to do vertical tabs:
tutsme-webdesign.info/bootstrap-3-toggable-tabs-and-pills
The shortest way in ES6:
array.forEach(e => {delete e.someKey});
So 4 years later, Microsoft has open sourced their JDBC driver on Github. I got a notification about this question today, and went and had a look, and I believe I have found the culprit here, mssql-jdbc/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java:1713
.
Basically, the driver tries to understand what SQL Server sends back if it is not a definite result set. According to the comments, it goes like this:
Check for errors first. (ln 1669)
Not an error. Is it a result set? (ln 1680)
Not an error or a result set. Maybe a result from a T-SQL statement? That is, one of the following:
- a positive count of the number of rows affected (from INSERT, UPDATE, or DELETE),
- a zero indicating no rows affected, or the statement was DDL, or
- a -1 indicating the statement succeeded, but there is no update count information available (translates to Statement.SUCCESS_NO_INFO in batch update count arrays). (ln 1706)
None of the above. Last chance here... Going into the parser above, we know moreResults was initially true. If we come out with moreResults false, the we hit a DONE token (either DONE (FINAL) or DONE (RPC in batch)) that indicates that the batch succeeded overall, but that there is no information on individual statements' update counts. This is similar to the last case above, except that there is no update count. That is: we have a successful result (return true), but we have no other information about it (updateCount = -1). (ln 1693)
Only way to get here (moreResults is still true, but no apparent results of any kind) is if the TDSParser didn't actually parse anything. That is, we are at EOF in the response. In that case, there truly are no more results. We're done. (ln 1717)
(Emphasis mine)
So you guys were right in the end. SQL simply can't tell how many rows are affected, and defaults to -1
. :)
I've used OAuth a few times, and also used some other methods (BASIC/DIGEST). I wholeheartedly suggest OAuth. The following link is the best tutorial I've seen on using OAuth:
Yes, you can.
https://plus.google.com/share?url=YOUR_URL_HERE
Edit: It works only with eff.org.
Edit: As of March 2012 it works on all sites.
Documentation for this sharing method is available on the Google Developers site.
Read about the super keyword (Scroll down the Subclass Constructors). If I understand your question, you probably want to call a superclass constructor?
It is worth noting that the Java compiler will automatically put in a no-arg constructor call to the superclass if you do not explicitly invoke a superclass constructor.
I like SQuirreL SQL Client, and NetBeans is very useful; but more often, I just fire up the built-in org.h2.tools.Server
and browse port 8082:
$ java -cp /opt/h2/bin/h2.jar org.h2.tools.Server -help Starts the H2 Console (web-) server, TCP, and PG server. Usage: java org.h2.tools.Server When running without options, -tcp, -web, -browser and -pg are started. Options are case sensitive. Supported options are: [-help] or [-?] Print the list of options [-web] Start the web server with the H2 Console [-webAllowOthers] Allow other computers to connect - see below [-webPort ] The port (default: 8082) [-webSSL] Use encrypted (HTTPS) connections [-browser] Start a browser and open a page to connect to the web server [-tcp] Start the TCP server [-tcpAllowOthers] Allow other computers to connect - see below [-tcpPort ] The port (default: 9092) [-tcpSSL] Use encrypted (SSL) connections [-tcpPassword ] The password for shutting down a TCP server [-tcpShutdown ""] Stop the TCP server; example: tcp://localhost:9094 [-tcpShutdownForce] Do not wait until all connections are closed [-pg] Start the PG server [-pgAllowOthers] Allow other computers to connect - see below [-pgPort ] The port (default: 5435) [-baseDir ] The base directory for H2 databases; for all servers [-ifExists] Only existing databases may be opened; for all servers [-trace] Print additional trace information; for all servers
You can use this command:
grep -rn "string" *
n for showing line number with the filename r for recursive
If you're using SQLite version 3.3+ you can easily create a table with:
create table if not exists TableName (col1 typ1, ..., colN typN)
In the same way, you can remove a table only if it exists by using:
drop table if exists TableName
I actually created an empty OSX Source Objective C file under the project (where all my swift files are).
I added the imports and then deleted the .m file.
Something to add ...
The package unbuffer has support issues with some packages under fedora and redhat unix releases.
Setting aside the troubles
Following worked for me
bash myscript.sh 2>&1 | tee output.log
Plain and simple, to fetch the submodules:
git submodule update --init --recursive
And now proceed updating them to the latest master branch (for example):
git submodule foreach git pull origin master
Why don't you simply use
grep -c '^username:' /etc/passwd
It will return 1 (since a user has max. 1 entry) if the user exists and 0 if it doesn't.
It's because your statement does not produce output.
Besides all the warnings of Darin and lazy (they are right); the question still offerst something to learn.
If you want to execute methods that don't directly produce output, you do:
@{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}
This is also true for rendering partials like:
@{ Html.RenderPartial("_MyPartial"); }
If you just want to experiment, there's an Objective-C compiler for .NET (Windows) here: qckapp
You may want to read this page of the MySQL manual. How a table gets locked is dependent on what type of table it is.
MyISAM uses table locks to achieve a very high read speed, but if you have an UPDATE statement waiting, then future SELECTS will queue up behind the UPDATE.
InnoDB tables use row-level locking, and you won't have the whole table lock up behind an UPDATE. There are other kind of locking issues associated with InnoDB, but you might find it fits your needs.
When you use DISTINCT
think of it as a distinct row, not column. It will return only rows where the columns do not match exactly the same.
SELECT DISTINCT ID, Email, ProductName, ProductModel
FROM Products
----------------------
1 | [email protected] | ProductName1 | ProductModel1
2 | [email protected] | ProductName1 | ProductModel1
The query would return both rows because the ID
column is different. I'm assuming that the ID
column is an IDENTITY
column that is incrementing, if you want to return the last then I recommend something like this:
SELECT DISTINCT TOP 1 ID, Email, ProductName, ProductModel
FROM Products
ORDER BY ID DESC
The TOP 1
will return only the first record, by ordering it by the ID
descending it will return the results with the last row first. This will give you the last record.
I don't know if leaving hibernate
off the front makes a difference.
The reference suggests it should be hibernate.hbm2ddl.auto
A value of create
will create your tables at sessionFactory creation, and leave them intact.
A value of create-drop
will create your tables, and then drop them when you close the sessionFactory.
Perhaps you should set the javax.persistence.Table
annotation explicitly?
Hope this helps.
I dont think you should use the tag on the news item summary (lines 67, 80, 93). You could use section or just have the enclosing div.
An article needs to be able to stand on its own & still make sense or be complete. As its incomplete or just an extract it cannot be an article, its more a section.
When you click 'read more' the subsequent page can
This should work:
$tmpfile = $_FILES['image']['tmp_name'];
$filename = basename($_FILES['image']['name']);
$data = array(
'uploaded_file' => '@'.$tmpfile.';filename='.$filename,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// set your other cURL options here (url, etc.)
curl_exec($ch);
In the receiving script, you would have:
print_r($_FILES);
/* which would output something like
Array (
[uploaded_file] => Array (
[tmp_name] => /tmp/f87453hf
[name] => myimage.jpg
[error] => 0
[size] => 12345
[type] => image/jpeg
)
)
*/
Then, if you want to properly handle the file upload, you would do something like this:
if (move_uploaded_file($_FILES['uploaded_file'], '/path/to/destination/file.zip')) {
// do stuff
}
To get the version of Redis server
redis-server -v
To get the version of Redis client
redis-cli -v
This will do what you want, uses an input file and is super fast
#!/bin/bash
IFS=$'\n'
file=/path/to/input.txt
lines=$(cat ${file})
for line in ${lines}; do
curl "${line}"
done
IFS=""
exit ${?}
one entry per line on your input file, it will follow the order of your input file
save it as whatever.sh and make it executable
You can now use css flexbox to align divs horizontally and vertically if you need to. general formula goes like this
parent-div {
display: flex;
flex-wrap: wrap;
/* for horizontal aligning of child divs */
justify-content: center;
/* for vertical aligning */
align-items: center;
}
child-div {
width: /* yoursize for each div */
;
}
Using a closure
let button: UIButton = {
let button = UIButton(type: .system)
button.titleLabel?.font = UIFont.systemFont(ofSize: 20)
...
return button
}()
If your find
handles this syntax, you can use it:
find -maxdepth 1 -name "file.txt" -size -90k
This will output file.txt
to stdout if and only if the size of file.txt
is less than 90k. To execute a script script
if file.txt
has a size less than 90k:
find -maxdepth 1 -name "file.txt" -size -90k -exec script \;
You can create a UIView with the desired height (the width should be that of the UITableView), and inside it you can place a UIImageView with the picture of the proper dimensions: they won't stretch automatically.
You can also give margin above and below the inner UIImageView, by giving a higher height to the container view.
Additionally, you can assign a Translation transform in order to place the image in the middle of its container header view, for example.
My approach was:
openssl version
OpenSSL 1.0.1e 11 Feb 2013
wget https://www.openssl.org/source/openssl-1.0.2a.tar.gz
wget http://www.linuxfromscratch.org/patches/blfs/svn/openssl-1.0.2a-fix_parallel_build-1.patch
tar xzf openssl-1.0.2a.tar.gz
cd openssl-1.0.2a
patch -Np1 -i ../openssl-1.0.2a-fix_parallel_build-1.patch
./config --prefix=/usr --openssldir=/etc/ssl --libdir=lib shared zlib-dynamic
make
make install
openssl version
OpenSSL 1.0.2a 19 Mar 2015
The approach I suggest is a bit verbose but I found it to scale pretty well into complex apps. When you want to show a modal, fire an action describing which modal you'd like to see:
this.props.dispatch({
type: 'SHOW_MODAL',
modalType: 'DELETE_POST',
modalProps: {
postId: 42
}
})
(Strings can be constants of course; I’m using inline strings for simplicity.)
Then make sure you have a reducer that just accepts these values:
const initialState = {
modalType: null,
modalProps: {}
}
function modal(state = initialState, action) {
switch (action.type) {
case 'SHOW_MODAL':
return {
modalType: action.modalType,
modalProps: action.modalProps
}
case 'HIDE_MODAL':
return initialState
default:
return state
}
}
/* .... */
const rootReducer = combineReducers({
modal,
/* other reducers */
})
Great! Now, when you dispatch an action, state.modal
will update to include the information about the currently visible modal window.
At the root of your component hierarchy, add a <ModalRoot>
component that is connected to the Redux store. It will listen to state.modal
and display an appropriate modal component, forwarding the props from the state.modal.modalProps
.
// These are regular React components we will write soon
import DeletePostModal from './DeletePostModal'
import ConfirmLogoutModal from './ConfirmLogoutModal'
const MODAL_COMPONENTS = {
'DELETE_POST': DeletePostModal,
'CONFIRM_LOGOUT': ConfirmLogoutModal,
/* other modals */
}
const ModalRoot = ({ modalType, modalProps }) => {
if (!modalType) {
return <span /> // after React v15 you can return null here
}
const SpecificModal = MODAL_COMPONENTS[modalType]
return <SpecificModal {...modalProps} />
}
export default connect(
state => state.modal
)(ModalRoot)
What have we done here? ModalRoot
reads the current modalType
and modalProps
from state.modal
to which it is connected, and renders a corresponding component such as DeletePostModal
or ConfirmLogoutModal
. Every modal is a component!
There are no general rules here. They are just React components that can dispatch actions, read something from the store state, and just happen to be modals.
For example, DeletePostModal
might look like:
import { deletePost, hideModal } from '../actions'
const DeletePostModal = ({ post, dispatch }) => (
<div>
<p>Delete post {post.name}?</p>
<button onClick={() => {
dispatch(deletePost(post.id)).then(() => {
dispatch(hideModal())
})
}}>
Yes
</button>
<button onClick={() => dispatch(hideModal())}>
Nope
</button>
</div>
)
export default connect(
(state, ownProps) => ({
post: state.postsById[ownProps.postId]
})
)(DeletePostModal)
The DeletePostModal
is connected to the store so it can display the post title and works like any connected component: it can dispatch actions, including hideModal
when it is necessary to hide itself.
It would be awkward to copy-paste the same layout logic for every “specific” modal. But you have components, right? So you can extract a presentational <Modal>
component that doesn’t know what particular modals do, but handles how they look.
Then, specific modals such as DeletePostModal
can use it for rendering:
import { deletePost, hideModal } from '../actions'
import Modal from './Modal'
const DeletePostModal = ({ post, dispatch }) => (
<Modal
dangerText={`Delete post ${post.name}?`}
onDangerClick={() =>
dispatch(deletePost(post.id)).then(() => {
dispatch(hideModal())
})
})
/>
)
export default connect(
(state, ownProps) => ({
post: state.postsById[ownProps.postId]
})
)(DeletePostModal)
It is up to you to come up with a set of props that <Modal>
can accept in your application but I would imagine that you might have several kinds of modals (e.g. info modal, confirmation modal, etc), and several styles for them.
The last important part about modals is that generally we want to hide them when the user clicks outside or presses Escape.
Instead of giving you advice on implementing this, I suggest that you just don’t implement it yourself. It is hard to get right considering accessibility.
Instead, I would suggest you to use an accessible off-the-shelf modal component such as react-modal
. It is completely customizable, you can put anything you want inside of it, but it handles accessibility correctly so that blind people can still use your modal.
You can even wrap react-modal
in your own <Modal>
that accepts props specific to your applications and generates child buttons or other content. It’s all just components!
There is more than one way to do it.
Some people don’t like the verbosity of this approach and prefer to have a <Modal>
component that they can render right inside their components with a technique called “portals”. Portals let you render a component inside yours while actually it will render at a predetermined place in the DOM, which is very convenient for modals.
In fact react-modal
I linked to earlier already does that internally so technically you don’t even need to render it from the top. I still find it nice to decouple the modal I want to show from the component showing it, but you can also use react-modal
directly from your components, and skip most of what I wrote above.
I encourage you to consider both approaches, experiment with them, and pick what you find works best for your app and for your team.
Using the java.time
framework built into Java 8 and later.
import java.time.Instant;
Instant.now().toEpochMilli(); //Long = 1450879900184
Instant.now().getEpochSecond(); //Long = 1450879900
This works in UTC because Instant.now()
is really call to Clock.systemUTC().instant()
https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html
When you use a TemplateField and bind literal text to it like you are doing, asp.net will actually insert a control FOR YOU! It gets put into a DataBoundLiteralControl. You can see this if you look in the debugger near your line of code that is getting the empty text.
So, to access the information without changing your template to use a control, you would cast like this:
string percentage = ((DataBoundLiteralControl)e.Row.Cells[7].Controls[0]).Text;
That will get you your text!
Seeing as there isn't a pretty one, here's a simple and reusable ES6 function.
const removeArrayItem = (arr, itemToRemove) => {
return arr.filter(item => item !== itemToRemove)
}
Usage:
const items = ['orange', 'purple', 'orange', 'brown', 'red', 'orange']
removeArrayItem(items, 'orange')
Add these lines of code in your htaccess file. I hope it will solve your problem.
<IfModule mod_php5.c>
php_value max_execution_time 259200
</IfModule>
This solution is based on the one proposed by fei0x but it has the advantages that there is no need to join the value list of constants in the query and constants can be easily listed at the start of the query. It also works in recursive queries.
Basically, every constant is a single-value table declared in a WITH clause which can then be called anywhere in the remaining part of the query.
WITH
constant_1_str AS (VALUES ('Hello World')),
constant_2_int AS (VALUES (100))
SELECT *
FROM some_table
WHERE table_column = (table constant_1_str)
LIMIT (table constant_2_int)
Alternatively you can use SELECT * FROM constant_name
instead of TABLE constant_name
which might not be valid for other query languages different to postgresql.
When you float those two divs, the content div collapses to zero height. Just add
<br style="clear:both;"/>
after the #right div but inside the content div. That will force the content div to surround the two internal, floating divs.
Here is a small code snippet that does the job:
double a = 34.51234;
NumberFormat df = DecimalFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(4);
df.setRoundingMode(RoundingMode.DOWN);
System.out.println(df.format(a));
Based on Martín Marconcinis answer (thanks!) I finally found a reliable (and very simple) solution.
public class ApplicationLifecycleHandler implements Application.ActivityLifecycleCallbacks, ComponentCallbacks2 {
private static final String TAG = ApplicationLifecycleHandler.class.getSimpleName();
private static boolean isInBackground = false;
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
if(isInBackground){
Log.d(TAG, "app went to foreground");
isInBackground = false;
}
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
@Override
public void onConfigurationChanged(Configuration configuration) {
}
@Override
public void onLowMemory() {
}
@Override
public void onTrimMemory(int i) {
if(i == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN){
Log.d(TAG, "app went to background");
isInBackground = true;
}
}
}
Then add this to your onCreate() of your Application class
public class MyApp extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
ApplicationLifeCycleHandler handler = new ApplicationLifeCycleHandler();
registerActivityLifecycleCallbacks(handler);
registerComponentCallbacks(handler);
}
}
Solution 1: Sometimes the build fails because, the target folder cannot be deleted. (It might be open in the backend due to the previous builds.)
-> Open Task Manager
-> In the Process tab
-> Do "End Process" for the running "java.exe" processess
Solution 2:
-> Restart eclipse
-> Perform Maven Build with command : clean install -DSkipTests
youmap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentlocation, 16));
16 is the zoom level
You have two typing errors in your code:
struct timeval,
should be
struct timeval
and after the printf()
parenthesis you need a semicolon.
Also, depending on the compiler, so simple a cycle might just be optimized out, giving you a time of 0 microseconds whatever you do.
Finally, the time calculation is wrong. You only take into accounts the seconds, ignoring the microseconds. You need to get the difference between seconds, multiply by one million, then add "after" tv_usec
and subtract "before" tv_usec
. You gain nothing by casting an integer number of seconds to a float.
I'd suggest checking out the man page for struct timeval
.
This is the code:
#include <stdio.h>
#include <sys/time.h>
int main (int argc, char** argv) {
struct timeval tvalBefore, tvalAfter; // removed comma
gettimeofday (&tvalBefore, NULL);
int i =0;
while ( i < 10000) {
i ++;
}
gettimeofday (&tvalAfter, NULL);
// Changed format to long int (%ld), changed time calculation
printf("Time in microseconds: %ld microseconds\n",
((tvalAfter.tv_sec - tvalBefore.tv_sec)*1000000L
+tvalAfter.tv_usec) - tvalBefore.tv_usec
); // Added semicolon
return 0;
}
getTitle
is a function, so you need to put ()
after it.
string t = obj.getTitle();
Also, be sure, that two-factor authentication is off, otherwise use personal access tokens
Details here : Can I use GitHub's 2-Factor Authentication with TortoiseGit?
echo "foo<br />bar";
Create a .o file:
g++ -c header.cpp
add this file to a library, creating library if necessary:
ar rvs header.a header.o
use library:
g++ main.cpp header.a
You can iterate over the index values if your dataframe has already been created.
df = df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
for name in df.index:
print name
print df.loc[name]
You can add either -DskipTests
or -Dmaven.test.skip=true
to any mvn
command for skipping tests. In your case it would be like below:
mvn package -DskipTests
OR
mvn package -Dmaven.test.skip=true
Since link to this question shows up on very top of returned results when you search for "php MSVCR110.dll" (not to mention it got 100k+ views and growing), here're some additional notes that you may find handy in your quest to solve MSVCR110.dll mistery...
The approach described in the answer is valid not only for MSVCR110.dll case but also applies when you are looking for other versions, like newer MSVCR71.dll
and I updated the answer to include VC15 even it's beyond scope of the original question.
On http://windows.php.net/ you can read:
VC9, VC11 and VC15
More recent versions of PHP are built with VC9, VC11 or VC15 (Visual Studio 2008, 2012 or 2015 compiler respectively) and include improvements in performance and stability.
The VC9 builds require you to have the Visual C++ Redistributable for Visual Studio 2008 SP1 x86 or x64 installed.
The VC11 builds require to have the Visual C++ Redistributable for Visual Studio 2012 x86 or x64 installed.
The VC15 builds require to have the Visual C++ Redistributable for Visual Studio 2015 x86 or x64 installed.
This is quite crucial as you not only need to get Visual C++ Redistributable installed but you also need the right version of it, and which one is right and correct, depends on what PHP build you are actually going to use. Pay attention to what version of PHP for Windows you are fetching, especially pay attention to this "VCxx" suffix, because if you install PHP that requires VC9 while having redistributables VC11 installed it is not going to work as run-time dependency is simply not fulfilled. Contrary to what some may think, you need exactly the version required, as newer (higher) releases does NOT cover older (lower) versions. so i.e. VC11 is not providing VC9 compatibility. Also VC15 is neither fulfilling VC11 nor VC9 dependency. It is just VC15 and NOTHING ELSE. Deal with it :)
For example, archive name php-5.6.4-nts-Win32-VC11-x86
tells us the following
Most searches I did lead to VC9 of redistributables, so in case of constant failures to make thing works, if possible, try installing different PHP build, to see if you by any chance do not face mismatching versions.
Download links
Note that you are using 32-bit version of PHP, so you need 32-bit redistributable (x86) even if your version of Windows is 64-bit!
private Color FromHex(string hex)
{
if (hex.StartsWith("#"))
hex = hex.Substring(1);
if (hex.Length != 6) throw new Exception("Color not valid");
return Color.FromArgb(
int.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
int.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
int.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.HexNumber));
}
You could also, in another directory:
/*working only in ipad portrait device*/
@media only screen and (width: 768px) and (height: 1024px) and (orientation:portrait) {
body{
background: red !important;
}
}
/*working only in ipad landscape device*/
@media all and (width: 1024px) and (height: 768px) and (orientation:landscape){
body{
background: green !important;
}
}
In the media query of specific devices, please use '!important' keyword to override the default CSS. Otherwise that does not change your webpage view on that particular devices.
I prefer Python 3.x way.
cal = 123.4567
print(f"result {cal:.4E}")
4
indicates how many digits are shown shown in the floating part.
cal = 123.4567
totalDigitInFloatingPArt = 4
print(f"result {cal:.{totalDigitInFloatingPArt}E} ")
From now onwards after API 24, Uri.parse(filePath)
won't work. You need to use this
final File videoFile = new File("path to your video file");
Uri fileUri = FileProvider.getUriForFile(mContext, "{yourpackagename}.fileprovider", videoFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(fileUri, "video/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//DO NOT FORGET THIS EVER
startActivity(intent);
But before using this you need to understand how file provider works. Go to official document link to understand file provider better.
scanf
uses any whitespace as a delimiter, so if you just say scanf("%d", &var)
it will skip any whitespace and then read an integer (digits up to the next non-digit) and nothing more.
Note that whitespace is any whitespace -- spaces, tabs, newlines, or carriage returns. Any of those are whitespace and any one or more of them will serve to delimit successive integers.
It seems that the extension cannot be found anymore using "Visual Studio Team Services". Instead, by following the link in Using Visual Studio Code & Team Foundation Version Control on "Get the TFVC plugin working in Visual Studio Code" you get to the Azure Repos Extension for Visual Studio Code GitHub. There it is explained that you now have to look for "Team Azure Repos".
Also, please note, that with the new Settings editor in Visual Studio Code the additional slashes do not have to be added. The path to tf.exe for VS 2017 - if specified using the "user friendly" Settings editor - would be just
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe
using System.Windows.Interop; ...
private BitmapImage Bitmap2BitmapImage(Bitmap bitmap)
{
BitmapSource i = Imaging.CreateBitmapSourceFromHBitmap(
bitmap.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
return (BitmapImage)i;
}
Liam's link looks great, but also check out pandas.Timedelta
- looks like it plays nicely with NumPy's and Python's time deltas.
https://pandas.pydata.org/pandas-docs/stable/timedeltas.html
pd.date_range('2014-01-01', periods=10) + pd.Timedelta(days=1)
The other answers posted here will work, but the clearest and most efficient function to use is numpy.any()
:
>>> all_zeros = not np.any(a)
or
>>> all_zeros = not a.any()
numpy.all(a==0)
because it uses less RAM. (It does not require the temporary array created by the a==0
term.)numpy.count_nonzero(a)
because it can return immediately when the first nonzero element has been found.np.any()
no longer uses "short-circuit" logic, so you won't see a speed benefit for small arrays.Alternatively you can try below.
$(window).bind("load", function() {
// code here });
This works in all the case. This will trigger only when the entire page is loaded.
Make sure the following lines are not in your wp.config
define( 'FORCE_SSL_LOGIN', true );
define( 'FORCE_SSL_ADMIN', true );
define( 'DISALLOW_FILE_EDIT', true );
I got locked out after deactivating iThemes security plugin
I use the following (stripped-down code) in Firefox 69.0 (on Ubuntu) to read a directory and show the image as part of a digital photo frame. The page is made in HTML, CSS, and JavaScript, and it is located on the same machine where I run the browser. The images are located on the same machine as well, so there is no viewing from "outside".
var directory = <path>;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', directory, false); // false for synchronous request
xmlHttp.send(null);
var ret = xmlHttp.responseText;
var fileList = ret.split('\n');
for (i = 0; i < fileList.length; i++) {
var fileinfo = fileList[i].split(' ');
if (fileinfo[0] == '201:') {
document.write(fileinfo[1] + "<br>");
document.write('<img src=\"' + directory + fileinfo[1] + '\"/>');
}
}
This requires the policy security.fileuri.strict_origin_policy
to be disabled. This means it might not be a solution you want to use. In my case I deemed it ok.
In Android Studio 1.1.0: File - Project Structure - Tab Flavors - Select Min SDK Version which is higher than in Manifest
Actually, the HTML 4.01 spec says that these attributes do not require values. I haven't personally encountered a situation where providing a value rendered these controls as unselected.
Here are the respective links to the spec document for selected and checked.
Edit: Firebug renders the checkbox as checked regardless of any values I put in quotes for the checked attribute (including just typing "checked" with no values whatsoever), and IE 8's Developer Tools forces checked="checked". I'm not sure if any similar tools exist for other browsers that might alter the rendered state of a checkbox, however.
As @Felix Kling suggested use action='store_true'
:
>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True
Making a function static
hides it from other translation units, which helps provide encapsulation.
helper_file.c
int f1(int); /* prototype */
static int f2(int); /* prototype */
int f1(int foo) {
return f2(foo); /* ok, f2 is in the same translation unit */
/* (basically same .c file) as f1 */
}
int f2(int foo) {
return 42 + foo;
}
main.c:
int f1(int); /* prototype */
int f2(int); /* prototype */
int main(void) {
f1(10); /* ok, f1 is visible to the linker */
f2(12); /* nope, f2 is not visible to the linker */
return 0;
}
if number >= 10000 and number <= 30000:
print ("you have to pay 5% taxes")
It's better to use PathVariable annotation if you still want to get the uri which was called.
@PostMapping("/pub/{action:a|b|c}")
public JSONObject handlexxx(@PathVariable String action, @RequestBody String reqStr){
...
}
or parse it from request object.
the simplest solution
I wanted a very quick way to convert my set to List and return it, so in one line I did
return new ArrayList<Long>(mySetVariable);
Change:
<!-- ANT4X -->
<dependency>
<groupId>net.sourceforge</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
To:
<!-- ANT4X -->
<dependency>
<groupId>net.sourceforge.ant4x</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
The groupId
of net.sourceforge
was incorrect. The correct value is net.sourceforge.ant4x
.
The other methods described assume a binary mask. If you want to use a real-valued single-channel grayscale image as a mask (e.g. from an alpha channel), you can expand it to three channels and then use it for interpolation:
assert len(mask.shape) == 2 and issubclass(mask.dtype.type, np.floating)
assert len(foreground_rgb.shape) == 3
assert len(background_rgb.shape) == 3
alpha3 = np.stack([mask]*3, axis=2)
blended = alpha3 * foreground_rgb + (1. - alpha3) * background_rgb
Note that mask
needs to be in range 0..1
for the operation to succeed. It is also assumed that 1.0
encodes keeping the foreground only, while 0.0
means keeping only the background.
If the mask may have the shape (h, w, 1)
, this helps:
alpha3 = np.squeeze(np.stack([np.atleast_3d(mask)]*3, axis=2))
Here np.atleast_3d(mask)
makes the mask (h, w, 1)
if it is (h, w)
and np.squeeze(...)
reshapes the result from (h, w, 3, 1)
to (h, w, 3)
.
AFAIK there is no possibility beside from using keys or expect if you are using the command line version ssh
. But there are library bindings for the most programming languages like C, python, php, ... . You could write a program in such a language. This way it would be possible to pass the password automatically. But note this is of course a security problem as the password will be stored in plain text in that program
Answers here seem outdated. Pandas now has a factorize()
function and you can create categories as:
df.col.factorize()
Function signature:
pandas.factorize(values, sort=False, na_sentinel=- 1, size_hint=None)
In the latest Bootstrap 3 version (bootstrap-datepicker.js) beforeShowDay
expects a result in this format:
{ enabled: false, classes: "class-name", tooltip: "Holiday!" }
Alternatively, if you don't care about the CSS and tooltip then simply return a boolean false
to make the date unselectable.
Also, there is no $.datepicker.noWeekends
, so you need to do something along the lines of this:
var HOLIDAYS = { // Ontario, Canada holidays
2017: {
1: { 1: "New Year's Day"},
2: { 20: "Family Day" },
4: { 17: "Easter Monday" },
5: { 22: "Victoria Day" },
7: { 1: "Canada Day" },
8: { 7: "Civic Holiday" },
9: { 4: "Labour Day" },
10: { 9: "Thanksgiving" },
12: { 25: "Christmas", 26: "Boxing Day"}
}
};
function filterNonWorkingDays(date) {
// Is it a weekend?
if ([ 0, 6 ].indexOf(date.getDay()) >= 0)
return { enabled: false, classes: "weekend" };
// Is it a holiday?
var h = HOLIDAYS;
$.each(
[ date.getYear() + 1900, date.getMonth() + 1, date.getDate() ],
function (i, x) {
h = h[x];
if (typeof h === "undefined")
return false;
}
);
if (h)
return { enabled: false, classes: "holiday", tooltip: h };
// It's a regular work day.
return { enabled: true };
}
$("#datePicker").datepicker({ beforeShowDay: filterNonWorkingDays });
This example get token thouth HttpWebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pathapi);
request.Method = "POST";
string postData = "grant_type=password";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byte1.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(byte1, 0, byte1.Length);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
getreaderjson = reader.ReadToEnd();
}
Restarted worked! I found the same error to add new table to my database diagram on sql server 2016, restarted sql server management studio, finally solved.
I know this has already been answered, but still, this is a good way to do it:
if ($("#checkbox").is(":checked")==false) {
//Do stuff here like: $(".span").html("<span>Lorem</span>");
}
I had a similar mistake, I use the spring boot and velocity, my solution is to check the file application.properties, spring.velocity.toolbox-config-location found that this property is wrong
You have to make sure that "Dependency Management" is enabled. To do so, right click on the project name, go to the "Gradle" sub-menu and click on "Enable Dependency Management". Once you do that, Gradle should load all the dependencies for you.
adding to scotty's answer:
Option 1: Either include this in your JS file:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
Option 2: or just use the URL to download 'angular-route.min.js' to your local.
and then (whatever option you choose) add this 'ngRoute' as dependency.
explained:
var app = angular.module('myapp', ['ngRoute']);
Cheers!!!
Try like this.
On change event,
$('input[type=checkbox]').on('change', function (e) {
if ($('input[type=checkbox]:checked').length > 3) {
$(this).prop('checked', false);
alert("allowed only 3");
}
});
Check this in JSFiddle
Yes, Google Custom Search has now replaced the old Search API, but you can still use Google Custom Search to search the entire web, although the steps are not obvious from the Custom Search setup.
To create a Google Custom Search engine that searches the entire web:
Now your custom search engine will search the entire web.
Pricing
Source: https://developers.google.com/custom-search/json-api/v1/overview#Pricing
We're using Jira 6.2 and I use this query:
updatedDate > startOfDay(-1d) AND updatedDate < endOfDay(-1)
to return all of the issues that were updated from the previous day. You can combine with whichever queries you want to return the appropriate issues for the previous day.
You need to stop the submission if an error occured:
HTML
<form name ="myform" onsubmit="return validation();">
JS
if (document.myform.username.value == "") {
document.getElementById('errors').innerHTML="*Please enter a username*";
return false;
}
You can use data:
URL in the src
:
var html = 'Hello from <img src="http://stackoverflow.com/favicon.ico" alt="SO">';_x000D_
var iframe = document.querySelector('iframe');_x000D_
iframe.src = 'data:text/html,' + encodeURIComponent(html);
_x000D_
<iframe></iframe>
_x000D_
Difference between srcdoc=“…” and src=“data:text/html,…” in an iframe.
Stegmenn nalied it for me but I had one change for when you have an IEnumerbale instead of a string = message like in his example.
private static string GetRoles(IEnumerable<External.Role> roles)
{
string[] switchStrings = { "Staff", "Board Member" };
switch (switchStrings.FirstOrDefault<string>(s => roles.Select(t => t.RoleName).Contains(s)))
{
case
"Staff":
roleNameValues += "Staff,";
break;
case
"Board Member":
roleNameValues += "Director,";
break;
default:
break;
}
From the official documentation:
It is also convenient to have a ~/.pgpass file to avoid regularly having to type in passwords. See Section 30.13 for more information.
...
This file should contain lines of the following format:
hostname:port:database:username:password
The password field from the first line that matches the current connection parameters will be used.
you can put everything in a block and easily write any code that you wish in that block just exactly the below code :
@{
bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);
if (isUserConnected)
{ // meaning that the viewing user has not been saved
<div>
<div> click to join us </div>
<a id="login" href="javascript:void(0);" style="display: inline; ">join</a>
</div>
}
}
it helps you to have at first a cleaner code and also you can prevent your page from loading many times different blocks of codes
Just using max-width: 0
in the display: table-cell
element worked for me:
.table {_x000D_
display: table;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.table-cell {_x000D_
display: table-cell;_x000D_
max-width: 0px;_x000D_
border: 1px solid gray;_x000D_
}
_x000D_
<div class="table">_x000D_
<div class="table-cell">short</div>_x000D_
<div class="table-cell">loooooong</div>_x000D_
<div class="table-cell">Veeeeeeery loooooong</div>_x000D_
</div>
_x000D_
This may happen if there is any read and write permission denial to the user. Like C:\Windows\System32\ have restricted access and you are cloned and trying to make from such restricted directory.
This is the long form of the Java commands that can be run from a Windows command prompt:
"C:\Program Files\Java\jdk1.6.0_18\bin\javac.exe" -classpath "C:\Users\Scott\workspace\myproject" com\mycompany\myapp\HelloWorld.java
"C:\Program Files\Java\jdk1.6.0_18\bin\java.exe" -classpath "C:\Users\Scott\workspace\myproject" com.mycompany.myapp.HelloWorld
Notice the classpath has no slash at the end. The javac.exe commands expects the file to end with ".java". The java.exe command expects the full class name and does not end with ".class".
There are a few ways to simplify these commands:
You don't have to enter the entire classpath (ie, you can just use -classpath "."). Enter the directory you will be working in:
cd "C:\Users\Scott\workspace\myproject\"
You can use the default package (put the HelloWorld.java file directory in your working directory and don't use the Java package directive)
If you make these changes you would run something like this (and you might be able to leave out -classpath "."):
cd "C:\Users\Scott\workspace\myproject\"
javac -classpath "." HelloWorld.java
java -classpath "." HelloWorld
I looked into this a bit more and the actual problem seems to be with assigning initial
to page width
under the print
media rule. It seems like in Chrome width: initial
on the .page
element results in scaling of the page content if no specific length value is defined for width
on any of the parent elements (width: initial
in this case resolves to width: auto
... but actually any value smaller than the size defined under the @page
rule causes the same issue).
So not only the content is now too long for the page (by about 2cm
), but also the page padding will be slightly more than the initial 2cm
and so on (it seems to render the contents under width: auto
to the width of ~196mm
and then scale the whole content up to the width of 210mm
~ but strangely exactly the same scaling factor is applied to contents with any width smaller than 210mm
).
To fix this problem you can simply in the print
media rule assign the A4 paper width and hight to html, body
or directly to .page
and in this case avoid the initial
keyword.
@page {
size: A4;
margin: 0;
}
@media print {
html, body {
width: 210mm;
height: 297mm;
}
/* ... the rest of the rules ... */
}
This seems to keep everything else the way it is in your original CSS and fix the problem in Chrome (tested in different versions of Chrome under Windows, OS X and Ubuntu).
This should work in your case without removing namespaces:
XmlNode idNode = myXmlDoc.GetElementsByTagName("id")[0];
I am not going to pretend I know why this particular function works, however window.getComputedStyle works 100% of the time for me whenever I need to access DOM elements with a Ref in a useEffect — I can only presume it will work with componentDidMount as well.
I put it at the top of the code in a useEffect and it appears as if it forces the effect to wait for the elements to be painted before it continues with the next line of code, but without any noticeable delay such as using a setTimeout or an async sleep function. Without this, the Ref element returns as undefined when I try to access it.
const ref = useRef(null);
useEffect(()=>{
window.getComputedStyle(ref.current);
// Next lines of code to get element and do something after getComputedStyle().
});
return(<div ref={ref}></div>);
Using an in
can have a performance impact. Joining two subqueries will not have the same performance impact and can be accomplished like this:
SELECT *
FROM (SELECT msisdn
,callid
,Change_color
,play_file_name
,date_played
FROM insert_log
WHERE play_file_name NOT IN('Prompt1','Conclusion_Prompt_1','silent')
ORDER BY callid ASC) t1
JOIN (SELECT MAX(date_played) AS date_played
FROM insert_log GROUP BY callid) t2
ON t1.date_played = t2.date_played
org.postgresql.util.PSQLException: FATAL: sorry, too many clients already.
Summary:
You opened up more than the allowed limit of connections to the database. You ran something like this: Connection conn = myconn.Open();
inside of a loop, and forgot to run conn.close();
. Just because your class is destroyed and garbage collected does not release the connection to the database. The quickest fix to this is to make sure you have the following code with whatever class that creates a connection:
protected void finalize() throws Throwable
{
try { your_connection.close(); }
catch (SQLException e) {
e.printStackTrace();
}
super.finalize();
}
Place that code in any class where you create a Connection. Then when your class is garbage collected, your connection will be released.
Run this SQL to see postgresql max connections allowed:
show max_connections;
The default is 100. PostgreSQL on good hardware can support a few hundred connections at a time. If you want to have thousands, you should consider using connection pooling software to reduce the connection overhead.
Take a look at exactly who/what/when/where is holding open your connections:
SELECT * FROM pg_stat_activity;
The number of connections currently used is:
SELECT COUNT(*) from pg_stat_activity;
Debugging strategy
You could give different usernames/passwords to the programs that might not be releasing the connections to find out which one it is, and then look in pg_stat_activity to find out which one is not cleaning up after itself.
Do a full exception stack trace when the connections could not be created and follow the code back up to where you create a new Connection
, make sure every code line where you create a connection ends with a connection.close();
How to set the max_connections higher:
max_connections in the postgresql.conf sets the maximum number of concurrent connections to the database server.
SHOW config_file;
/var/lib/pgsql/data/postgresql.conf
max_connections=100
.What's the maximum max_connections?
Use this query:
select min_val, max_val from pg_settings where name='max_connections';
I get the value 8388607
, in theory that's the most you are allowed to have, but then a runaway process can eat up thousands of connections, and surprise, your database is unresponsive until reboot. If you had a sensible max_connections like 100. The offending program would be denied a new connection.
If you tried everything above and it still doesn’t work in IE, check your IIS settings if you are using a Windows Server. Make sure that the HTTP Headers > “Enable content expiration” setting, IS NOT SET to “Expire immediately”
Getting the ball rolling with this community wiki answer. Feel free to edit me with your improvements.
ws WebSocket server and client for node.js. One of the fastest libraries if not the fastest one.
websocket-node WebSocket server and client for node.js
websocket-driver-node WebSocket server and client protocol parser node.js - used in faye-websocket-node
faye-websocket-node WebSocket server and client for node.js - used in faye and sockjs
socket.io WebSocket server and client for node.js + client for browsers + (v0 has newest to oldest fallbacks, v1 of Socket.io uses engine.io) + channels - used in stack.io. Client library tries to reconnect upon disconnection.
sockjs WebSocket server and client for node.js and others + client for browsers + newest to oldest fallbacks
faye WebSocket server and client for node.js and others + client for browsers + fallbacks + support for other server-side languages
deepstream.io clusterable realtime server that handles WebSockets & TCP connections and provides data-sync, pub/sub and request/response
socketcluster WebSocket server cluster which makes use of all CPU cores on your machine. For example, if you were to use an xlarge Amazon EC2 instance with 32 cores, you would be able to handle almost 32 times the traffic on a single instance.
primus Provides a common API for most of the libraries above for easy switching + stability improvements for all of them.
When to use:
use the basic WebSocket servers when you want to use the native WebSocket implementations on the clientside, beware of the browser incompatabilities
use the fallback libraries when you care about browser fallbacks
use the full featured libraries when you care about channels
use primus when you have no idea about what to use, are not in the mood for rewriting your application when you need to switch frameworks because of changing project requirements or need additional connection stability.
Where to test:
Firecamp is a GUI testing environment for SocketIO, WS and all major real-time technology. Debug the real-time events while you're developing it.
In my application which calls two services, I compared both Task.Run and Task.Factory.StartNew. I found that in my case both of them work fine. However, the second one is faster.
First cast your Edit text like this:
TextView tekst = (TextView) findViewById(R.id.editText1);
tekst.setText(text);
And after that close the DB not befor this line...
myDataBaseHelper.close();
You can use query string to pass value from one page to another..
1.pass the value using querystring
Response.Redirect("Default3.aspx?value=" + txt.Text + "& number="+n);
2.Retrive the value in the page u want by using any of these methods..
Method1:
string v = Request.QueryString["value"];
string n=Request.QueryString["number"];
Method2:
NameValueCollection v = Request.QueryString;
if (v.HasKeys())
{
string k = v.GetKey(0);
string n = v.Get(0);
if (k == "value")
{
lbltext.Text = n.ToString();
}
if (k == "value1")
{
lbltext.Text = "error occured";
}
}
NOTE:Method 2 is the fastest method.
According to Transact-SQL Syntax Conventions (Transact-SQL) (MSDN)
Transact-SQL statement terminator. Although the semicolon is not required for most statements in this version of SQL Server, it will be required in a future version.
(also see @gerryLowry 's comment)
In this case it is just coding style.
Use of var
is only necessary when dealing with anonymous types.
In other situations it's a matter of taste.
Container(
width: yourWidth,
height: yourHeight ,
decoration: BoxDecoration(
borderRadius: radius,
gradient: yourGradient,
border: yourBorder),
child: FlatButton(
onPressed: {} (),
shape: RoundedRectangleBorder(borderRadius: radius),
.......
and use the same radius.
Stream is just an abstraction (or a wrapper) over a physical
stream of bytes. This physical
stream is called the base stream
. So there is always a base stream over which a stream wrapper is created and thus the wrapper is named after the base stream type ie FileStream
, MemoryStream
etc.
The advantage of the stream wrapper is that you get a unified api to interact with streams of any underlying type usb, file
etc.
Why would you treat data as stream - because data chunks are loaded on-demand, we can inspect/process the data as chunks rather than loading the entire data into memory. This is how most of the programs deal with big files, for eg encrypting an OS image file.
When I was to get yesterday with just the date in the format Year/Month/Day
I use:
$Variable = Get-Date((get-date ).AddDays(-1)) -Format "yyyy-MM-dd"
To answer the question, getApplication() returns an Application object and getApplicationContext() returns a Context object. Based on your own observations, I would assume that the Context of both are identical (i.e. behind the scenes the Application class calls the latter function to populate the Context portion of the base class or some equivalent action takes place). It shouldn't really matter which function you call if you just need a Context.
give this style to td: width: 1%;
You can also use the jQuery .siblings()
method:
HTML
<div class="content">
<a href="#">A</a>
<a href="#">B</a>
<a href="#">C</a>
</div>
Javascript
$(".content").on('click', 'a', function(e) {
e.preventDefault();
$(this).siblings().hide('slow');
});
Working demo: http://jsfiddle.net/wTm5f/
From the Finder menu, click Go->Go to Folder. Type in /Applications/XAMPP
I think there is no out-of-the-box support for that in VS Code.
You can install a plugin to give you similar functionality. Eg.:
https://marketplace.visualstudio.com/items?itemName=micnil.vscode-checkpoints
Or the more famous:
https://marketplace.visualstudio.com/items?itemName=xyz.local-history
Some details may need to be configured: The VS Code search gets confused sometimes because of additional folders created by this type of plugins. You can configure it to ignore such folders or change their locations (adding such folders to your .gitignore
file also solves this problem).
If its ubuntu then go ahead with this, already tested.:--
first, installing dependencies
sudo aptitude install openssl build-essential xorg libssl-dev
for 64bits OS
wget http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.9.9-static-amd64.tar.bz2
tar xvjf wkhtmltopdf-0.9.9-static-amd64.tar.bz2
mv wkhtmltopdf-amd64 /usr/local/bin/wkhtmltopdf
chmod +x /usr/local/bin/wkhtmltopdf
for 32bits OS
wget http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.9.9-static-i386.tar.bz2
tar xvjf wkhtmltopdf-0.9.9-static-i386.tar.bz2
mv wkhtmltopdf-i386 /usr/local/bin/wkhtmltopdf
chmod +x /usr/local/bin/wkhtmltopdf
In the case of a non blocking socket that has no data available, recv will throw the socket.error exception and the value of the exception will have the errno of either EAGAIN or EWOULDBLOCK. Example:
import sys
import socket
import fcntl, os
import errno
from time import sleep
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
fcntl.fcntl(s, fcntl.F_SETFL, os.O_NONBLOCK)
while True:
try:
msg = s.recv(4096)
except socket.error, e:
err = e.args[0]
if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
sleep(1)
print 'No data available'
continue
else:
# a "real" error occurred
print e
sys.exit(1)
else:
# got a message, do something :)
The situation is a little different in the case where you've enabled non-blocking behavior via a time out with socket.settimeout(n)
or socket.setblocking(False)
. In this case a socket.error is stil raised, but in the case of a time out, the accompanying value of the exception is always a string set to 'timed out'. So, to handle this case you can do:
import sys
import socket
from time import sleep
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
s.settimeout(2)
while True:
try:
msg = s.recv(4096)
except socket.timeout, e:
err = e.args[0]
# this next if/else is a bit redundant, but illustrates how the
# timeout exception is setup
if err == 'timed out':
sleep(1)
print 'recv timed out, retry later'
continue
else:
print e
sys.exit(1)
except socket.error, e:
# Something else happened, handle error, exit, etc.
print e
sys.exit(1)
else:
if len(msg) == 0:
print 'orderly shutdown on server end'
sys.exit(0)
else:
# got a message do something :)
As indicated in the comments, this is also a more portable solution since it doesn't depend on OS specific functionality to put the socket into non-blockng mode.
See recv(2) and python socket for more details.
Not sure why this isn't implemented directly in R, but this answer is essentially the same as Andrii's and Wordsforthewise, I just turned into a function for the sake of convenience if somebody uses it a lot like me.
r2_general <-function(preds,actual){
return(1- sum((preds - actual) ^ 2)/sum((actual - mean(actual))^2))
}
CODE
HTML:
<div class="flex-container">
<div class="rows">
<div class="row">
<span class="flex-item">1</span>
</div>
<div class="row">
<span class="flex-item">2</span>
</div>
<div class="row">
<span class="flex-item">3</span>
</div>
<div class="row">
<span class="flex-item">4</span>
</div>
</div>
</div>
CSS:
html, body {
height: 100%;
}
.flex-container {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
.rows {
display: flex;
flex-direction: column;
}
where flex-container
div is used to center vertically and horizontally your rows
div, and rows
div is used to group your "items" and ordering them in a column based one.
To add on to what Egon said, simply create your blob called "folder/1.txt", and it will work. No need to create a directory.
I was wondering if it would be a good idea to have progressive attempts at a process, so you pass this func a process name func_terminate_process "firefox" and it tires things more nicely first, then moves on to kill.
# -- NICE: try to use killall to stop process(s)
killall ${1} > /dev/null 2>&1 ;sleep 10
# -- if we do not see the process, just end the function
pgrep ${1} > /dev/null 2>&1 || return
# -- UGLY: Step trough every pid and use kill -9 on them individually
for PID in $(pidof ${1}) ;do
echo "Terminating Process: [${1}], PID [${PID}]"
kill -9 ${PID} ;sleep 10
# -- NASTY: If kill -9 fails, try SIGTERM on PID
if ps -p ${PID} > /dev/null ;then
echo "${PID} is still running, forcefully terminating with SIGTERM"
kill -SIGTERM ${PID} ;sleep 10
fi
done
# -- If after all that, we still see the process, report that to the screen.
pgrep ${1} > /dev/null 2>&1 && echo "Error, unable to terminate all or any of [${1}]" || echo "Terminate process [${1}] : SUCCESSFUL"
In the Documentation it says there are no import statements in Swift.
Simply use:
let primNumber = PrimeNumberModel()
Perhaps you're trying to catch all exceptions and this is catching the SystemExit
exception raised by sys.exit()
?
import sys
try:
sys.exit(1) # Or something that calls sys.exit()
except SystemExit as e:
sys.exit(e)
except:
# Cleanup and reraise. This will print a backtrace.
# (Insert your cleanup code here.)
raise
In general, using except:
without naming an exception is a bad idea. You'll catch all kinds of stuff you don't want to catch -- like SystemExit
-- and it can also mask your own programming errors. My example above is silly, unless you're doing something in terms of cleanup. You could replace it with:
import sys
sys.exit(1) # Or something that calls sys.exit().
If you need to exit without raising SystemExit
:
import os
os._exit(1)
I do this, in code that runs under unittest and calls fork()
. Unittest gets when the forked process raises SystemExit
. This is definitely a corner case!
If you want to make a diff with more than one file, with the method specified by @mipadi:
E.g. diff between HEAD
and your master
, to find all .coffee
files:
git diff master..HEAD -- `find your_search_folder/ -name '*.coffee'`
This will recursively search your your_search_folder/
for all .coffee
files and make a diff between them and their master
versions.
In psql that would be
\dx
See the manual for details: http://www.postgresql.org/docs/current/static/app-psql.html
Doing it in plain SQL it would be a select on pg_extension
:
SELECT *
FROM pg_extension
http://www.postgresql.org/docs/current/static/catalog-pg-extension.html
Firstly, if you are doing this just to prevent people viewing the source of your page - it won't work, because they can always use a keyboard shortcut to view it.
Secondly, you will have to use JavaScript to accomplish this. If the user has JS disabled, you cannot prevent the right click.
That said, add this to your body tag to disable right clicks.
<body oncontextmenu="return false;">
Read from sys.stdin
, but to read binary data on Windows, you need to be extra careful, because sys.stdin
there is opened in text mode and it will corrupt \r\n
replacing them with \n
.
The solution is to set mode to binary if Windows + Python 2 is detected, and on Python 3 use sys.stdin.buffer
.
import sys
PY3K = sys.version_info >= (3, 0)
if PY3K:
source = sys.stdin.buffer
else:
# Python 2 on Windows opens sys.stdin in text mode, and
# binary data that read from it becomes corrupted on \r\n
if sys.platform == "win32":
# set sys.stdin to binary mode
import os, msvcrt
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
source = sys.stdin
b = source.read()
function foo(Array $array)
{
return $array;
}
Is this what you're looking for?
if (request instanceof HttpServletRequest) {
String url = ((HttpServletRequest)request).getRequestURL().toString();
String queryString = ((HttpServletRequest)request).getQueryString();
}
To Reconstruct:
System.out.println(url + "?" + queryString);
Info on HttpServletRequest.getRequestURL()
and HttpServletRequest.getQueryString()
.
df = data.frame(date=c("2012-02-01", "2012-02-01", "2012-02-02"))
df$day <- weekdays(as.Date(df$date))
df
## date day
## 1 2012-02-01 Wednesday
## 2 2012-02-01 Wednesday
## 3 2012-02-02 Thursday
Edit: Just to show another way...
The wday
component of a POSIXlt
object is the numeric weekday (0-6 starting on Sunday).
as.POSIXlt(df$date)$wday
## [1] 3 3 4
which you could use to subset a character vector of weekday names
c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday")[as.POSIXlt(df$date)$wday + 1]
## [1] "Wednesday" "Wednesday" "Thursday"
In general, a developer should never throw a NullPointerException. This exception is thrown by the runtime when code attempts to dereference a variable who's value is null. Therefore, if your method wants to explicitly disallow null, as opposed to just happening to have a null value raise a NullPointerException, you should throw an IllegalArgumentException.
Add { } while importing and exporting:
export { ... };
|
import { ... } from './Template';
export → import { ... } from './Template'
export default → import ... from './Template'
Here is a working example:
// ExportExample.js
import React from "react";
function DefaultExport() {
return "This is the default export";
}
function Export1() {
return "Export without default 1";
}
function Export2() {
return "Export without default 2";
}
export default DefaultExport;
export { Export1, Export2 };
// App.js
import React from "react";
import DefaultExport, { Export1, Export2 } from "./ExportExample";
export default function App() {
return (
<>
<strong>
<DefaultExport />
</strong>
<br />
<Export1 />
<br />
<Export2 />
</>
);
}
??Working sandbox to play around: https://codesandbox.io/s/export-import-example-react-jl839?fontsize=14&hidenavigation=1&theme=dark
The reason people often suggest writing
VAR=value
export VAR
instead of the shorter
export VAR=value
is that the longer form works in more different shells than the short form. If you know you're dealing with bash
, either works fine, of course.
I was able to get past this by using the Array keyword instead of empty brackets:
const enhancers: Array<any> = [];
Use:
if (typeof devToolsExtension === 'function') {
enhancers.push(devToolsExtension())
}
The symbol you posted is the placeholder symbol for a broken byte sequence. Basically, it's not a real symbol but an error in your string.
What is the exact byte value of the symbol? Blindly applying utf8_encode is not a good idea, it's better to find out first where the byte(s) came from and what they mean.
Wouldn't it be more pythonic to use slicing?
For example, to pad a string with spaces on the right until it's 10 characters long:
>>> x = "string"
>>> (x + " " * 10)[:10]
'string '
To pad it with spaces on the left until it's 15 characters long:
>>> (" " * 15 + x)[-15:]
' string'
It requires knowing how long you want to pad to, of course, but it doesn't require measuring the length of the string you're starting with.
I had also problems in finding something simple to satisfy my needs so I decided to write my own library (with MIT license). It's mainly based on composite and builder pattern.
A basic declarative example is:
import static com.github.manliogit.javatags.lang.HtmlHelper.*;
html5(attr("lang -> en"),
head(
meta(attr("http-equiv -> Content-Type", "content -> text/html; charset=UTF-8")),
title("title"),
link(attr("href -> xxx.css", "rel -> stylesheet"))
)
).render();
A fluent example is:
ul()
.add(li("item 1"))
.add(li("item 2"))
.add(li("item 3"))
You can check more examples here
I also created an on line converter to transform every html snippet (from complex bootstrap template to simple single snippet) on the fly (i.e. html -> javatags)
A polyfill is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively.
Newer versions of MongoDB support bulk operations:
var col = db.collection('people');
var batch = col.initializeUnorderedBulkOp();
batch.insert({name: "John"});
batch.insert({name: "Jane"});
batch.insert({name: "Jason"});
batch.insert({name: "Joanne"});
batch.execute(function(err, result) {
if (err) console.error(err);
console.log('Inserted ' + result.nInserted + ' row(s).');
}
It is not possible to get HTTP Response code by using Selenium WebDriver directly. The code can be got by using Java code and that can be used in Selenium WebDriver.
To get HTTP Response code by java:
public static int getResponseCode(String urlString) throws MalformedURLException, IOException{
URL url = new URL(urlString);
HttpURLConnection huc = (HttpURLConnection)url.openConnection();
huc.setRequestMethod("GET");
huc.connect();
return huc.getResponseCode();
}
Now you can write your Selenium WebDriver code as below:
private static int statusCode;
public static void main(String... args) throws IOException{
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
List<WebElement> links = driver.findElements(By.tagName("a"));
for(int i = 0; i < links.size(); i++){
if(!(links.get(i).getAttribute("href") == null) && !(links.get(i).getAttribute("href").equals(""))){
if(links.get(i).getAttribute("href").contains("http")){
statusCode= getResponseCode(links.get(i).getAttribute("href").trim());
if(statusCode == 403){
System.out.println("HTTP 403 Forbidden # " + i + " " + links.get(i).getAttribute("href"));
}
}
}
}
}
Swift 3 version
import UIKit
protocol PhoneCalling {
func call(phoneNumber: String)
}
extension PhoneCalling {
func call(phoneNumber: String) {
let cleanNumber = phoneNumber.replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "-", with: "")
guard let number = URL(string: "telprompt://" + cleanNumber) else { return }
UIApplication.shared.open(number, options: [:], completionHandler: nil)
}
}
$url = 'http://.../.../yoururl/...';
$obj = json_decode(file_get_contents($url), true);
echo $obj['access_token'];
Php also can use properties with dashes:
garex@ustimenko ~/src/ekapusta/deploy $ psysh
Psy Shell v0.4.4 (PHP 5.5.3-1ubuntu2.6 — cli) by Justin Hileman
>>> $q = new stdClass;
=> <stdClass #000000005f2b81c80000000076756fef> {}
>>> $q->{'qwert-y'} = 123
=> 123
>>> var_dump($q);
class stdClass#174 (1) {
public $qwert-y =>
int(123)
}
=> null
It's not that hard...
Check out this forum post:
http://www.pcreview.co.uk/forums/excel-not-recognizing-dates-dates-t3139469.html
The steps in short:
For a div-Element you could just set the opacity via a class to enable or disable the effect.
.mute-all {
opacity: 0.4;
}
No you don't need to call the base destructor, a base destructor is always called for you by the derived destructor. Please see my related answer here for order of destruction.
To understand why you want a virtual destructor in the base class, please see the code below:
class B
{
public:
virtual ~B()
{
cout<<"B destructor"<<endl;
}
};
class D : public B
{
public:
virtual ~D()
{
cout<<"D destructor"<<endl;
}
};
When you do:
B *pD = new D();
delete pD;
Then if you did not have a virtual destructor in B, only ~B() would be called. But since you have a virtual destructor, first ~D() will be called, then ~B().
Modules Preconditions:
The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (
precondition="managedHandler"
) only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />
If you remove the attribute
precondition="managedHandler"
, Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "
managedHandler
" precondition.To enable all managed modules to run for all requests without configuring each module entry to remove the "
managedHandler
" precondition, use therunAllManagedModulesForAllRequests
property in the<modules>
section:<modules runAllManagedModulesForAllRequests="true" />
When you use this property, the "
managedHandler
" precondition has no effect and all managed modules run for all requests.
Copied from IIS Modules Overview: Preconditions
I know this has been answered but I have a slightly more elegant way to copy from asset directory to a file on the sdcard. It requires no "for" loop but instead uses File Streams and Channels to do the work.
(Note) If using any type of compressed file, APK, PDF, ... you may want to rename the file extension before inserting into asset and then rename once you copy it to SDcard)
AssetManager am = context.getAssets();
AssetFileDescriptor afd = null;
try {
afd = am.openFd( "MyFile.dat");
// Create new file to copy into.
File file = new File(Environment.getExternalStorageDirectory() + java.io.File.separator + "NewFile.dat");
file.createNewFile();
copyFdToFile(afd.getFileDescriptor(), file);
} catch (IOException e) {
e.printStackTrace();
}
A way to copy a file without having to loop through it.
public static void copyFdToFile(FileDescriptor src, File dst) throws IOException {
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
You can turn on wifi : - connect usb on pc; - will show alert dialog "connect UMS mode or KIES" - do not click, do not cancel - pull notification bar and turn on wifi.
//------------------code is return in typescript
const updateMyData1 = (rowIndex:any, columnId:any, value:any) => {
setItems(old => old.map((row, index) => {
if (index === rowIndex) {
return Object.assign(Object.assign({}, old[rowIndex]), { [columnId]: value });
}
return row;
}));
I had just this problem and I found a similar answer here.
The method is to set top
the way you want it and then press W
(capital W).
This saves top
's current layout to a configuration file in $HOME/.toprc
Although this might not work if you want to run multiple top
's with different configurations.
So via what I consider a work around you can write to different config files / use different config files by doing one of the following...
1) Rename the binary
ln -s /usr/bin/top top2
./top2
Now .top2rc
is going to be written to your $HOME
2) Set $HOME to some alternative path, since it will write its config file to the $HOME/.binary-name.rc file
HOME=./
top
Now .toprc
is going to be written to the current folder.
Via use of other peoples comments to add the various usage accounting in top you can create a batch output for that information and latter coalesces the information via a script. Maybe not quite as simple as you script but I found top to provide me ALL processes so that later I can recap and capture a state during a long run that I might have missed otherwise (unexplained sudden CPU usage due to stray processes)
Use this:
<script type="text/javascript">
$(document).ready(function(){
// Check if the current URL contains '#'
if(document.URL.indexOf("#")==-1)
{
// Set the URL to whatever it was plus "#".
url = document.URL+"#";
location = "#";
//Reload the page
location.reload(true);
}
});
</script>
Due to the if
condition, the page will reload only once.
Oldie but goldie...
Since user is asking for jQuery, I'm going to keep it simple:
var html = $('#container').clone();
console.log(html);
Try the following, no extra headers
wget -qO- www.google.com
Note the trailing -
. This is part of the normal command argument for -O
to cat out to a file, but since we don't use >
to direct to a file, it goes out to the shell. You can use -qO-
or -qO -
.
To allow user ec2-user
(Amazon AWS) write access to the public web directory (/var/www/html),
enter this command via Putty or Terminal, as the root user sudo
:
chown -R ec2-user /var/www/html
Make sure permissions on that entire folder were correct:
chmod -R 755 /var/www/html
Doc's:
Setting up amazon ec2-instances
Connect to Amazon EC2 file directory using Filezilla and SFTP (Video)
it should be like that,
$this->db->select('*');
$this->db->from('table1');
$this->db->join('table2', 'table1.id = table2.id');
$this->db->join('table3', 'table1.id = table3.id');
$query = $this->db->get();
as per CodeIgniters active record framework
You can use Google Translate API v2 Java. It has a core module that you can call from your Java code and also a command line interface module.
Firstly, the level name to use is FINE
, not DEBUG
. Let's assume for a minute that DEBUG
is actually valid, as it makes the following explanation make a bit more sense...
In the Handler specific properties
section, you're setting the logging level for those handlers to DEBUG
. This means the handlers will handle any log messages with the DEBUG
level or higher. It doesn't necessarily mean any DEBUG
messages are actually getting passed to the handlers.
In the Facility specific properties
section, you're setting the logging level for a few explicitly-named loggers to DEBUG
. For those loggers, anything at level DEBUG
or above will get passed to the handlers.
The default logging level is INFO
, and apart from the loggers mentioned in the Facility specific properties
section, all loggers will have that level.
If you want to see all FINE
messages, add this:
.level = FINE
However, this will generate a vast quantity of log messages. It's probably more useful to set the logging level for your code:
your.package.level = FINE
See the Tomcat 6/Tomcat 7 logging documentation for more information. The example logging.properties file shown there uses FINE
instead of DEBUG
:
...
1catalina.org.apache.juli.FileHandler.level = FINE
...
and also gives you examples of setting additional logging levels:
# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
#org.apache.catalina.startup.ContextConfig.level = FINE
#org.apache.catalina.startup.HostConfig.level = FINE
#org.apache.catalina.session.ManagerBase.level = FINE
Just a recommendation:
I'd recommend using the DOM table implementation, it's very straight forward and easy to use, you really don't need jQuery for this task.
var table = document.getElementById('tblOne');
var rowLength = table.rows.length;
for(var i=0; i<rowLength; i+=1){
var row = table.rows[i];
//your code goes here, looping over every row.
//cells are accessed as easy
var cellLength = row.cells.length;
for(var y=0; y<cellLength; y+=1){
var cell = row.cells[y];
//do something with every cell here
}
}
In case you couldn't find "Import code" button on github, you can:
url
. It will look like: Public
or Private
repoBegin Import
UPDATE: Recently, Github announced the ability to "Import repositories with large files"
The functions* quit()
, exit()
, and sys.exit()
function in the same way: they raise the SystemExit
exception. So there is no real difference, except that sys.exit()
is always available but exit()
and quit()
are only available if the site
module is imported.
The os._exit()
function is special, it exits immediately without calling any cleanup functions (it doesn't flush buffers, for example). This is designed for highly specialized use cases... basically, only in the child after an os.fork()
call.
Use exit()
or quit()
in the REPL.
Use sys.exit()
in scripts, or raise SystemExit()
if you prefer.
Use os._exit()
for child processes to exit after a call to os.fork()
.
All of these can be called without arguments, or you can specify the exit status, e.g., exit(1)
or raise SystemExit(1)
to exit with status 1. Note that portable programs are limited to exit status codes in the range 0-255, if you raise SystemExit(256)
on many systems this will get truncated and your process will actually exit with status 0.
* Actually, quit()
and exit()
are callable instance objects, but I think it's okay to call them functions.
In VS2008, when I click on the service reference and select "Configure Service Reference", there is an option to choose how the client de-serializes lists returned from the service.
Notably, I can choose between System.Array, System.Collections.ArrayList and System.Collections.Generic.List
Another option is to create a separate LayoutModel class with all the properties you will need in the layout, and then stuff an instance of this class into ViewBag. I use Controller.OnActionExecuting method to populate it. Then, at the start of layout you can pull this object back from ViewBag and continue to access this strongly typed object.
extends
implements
abstract classes also act like class, with extends and implements
In general use serialize()
on the form element.
Please be mindful that multiple <select> options are serialized under the same key, e.g.
<select id="foo" name="foo" multiple="multiple">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
will result in a query string that includes multiple occurences of the same query parameter:
[path]?foo=1&foo=2&foo=3&someotherparams...
which may not be what you want in the backend.
I use this JS code to reduce multiple parameters to a comma-separated single key (shamelessly copied from a commenter's response in a thread over at John Resig's place):
function compress(data) {
data = data.replace(/([^&=]+=)([^&]*)(.*?)&\1([^&]*)/g, "$1$2,$4$3");
return /([^&=]+=).*?&\1/.test(data) ? compress(data) : data;
}
which turns the above into:
[path]?foo=1,2,3&someotherparams...
In your JS code you'd call it like this:
var inputs = compress($("#your-form").serialize());
Hope that helps.
You can use Jquery's on method and listen for the scroll
event.
We follow the guidelines listed on this page: C++ Programming Style Guidelines
I'd also recommend you read The Elements of C++ Style by Misfeldt et al, which is quite an excellent book on this topic.
As a really simple example,
SYNCHRONOUS
Imagine 3 school students instructed to run a relay race on a road.
1st student runs her given distance, stops and passes the baton to the 2nd. No one else has started to run.
1------>
2.
3.
When the 2nd student retrieves the baton, she starts to run her given distance.
1.
2------>
3.
The 2nd student got her shoelace untied. Now she has stopped and tying up again. Because of this, 2nd's end time has got extended and the 3rd's starting time has got delayed.
1.
--2.--->
3.
This pattern continues on till the 3rd retrieves the baton from 2nd and finishes the race.
ASYNCHRONOUS
Just Imagine 10 random people walking on the same road. They're not on a queue of course, just randomly walking on different places on the road in different paces.
2nd person's shoelace got untied. She stopped to get it tied up again.
But nobody is waiting for her to get it tied up. Everyone else is still walking the same way they did before, in that same pace of theirs.
10--> 9-->
8--> 7--> 6-->
5--> 4-->
1--> 2. 3-->
((EditText) findViewById(R.id.User)).setText("");
((EditText) findViewById(R.id.Password)).setText("");
The cunningly-named urlencode() and urldecode().
However, you shouldn't need to use urldecode()
on variables that appear in $_POST
and $_GET
.
Based on "MirekE" answer here is a code that i tested now and its working:
var activityIndicator: UIActivityIndicatorView!
var viewActivityIndicator: UIView!
override func viewDidLoad()
{
super.viewDidLoad()
let width: CGFloat = 200.0
let height: CGFloat = 50.0
let x = self.view.frame.width/2.0 - width/2.0
let y = self.view.frame.height/2.0 - height/2.0
self.viewActivityIndicator = UIView(frame: CGRect(x: x, y: y, width: width, height: height))
self.viewActivityIndicator.backgroundColor = UIColor(red: 255.0/255.0, green: 204.0/255.0, blue: 51.0/255.0, alpha: 0.5)
self.viewActivityIndicator.layer.cornerRadius = 10
self.activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
self.activityIndicator.color = UIColor.blackColor()
self.activityIndicator.hidesWhenStopped = false
let titleLabel = UILabel(frame: CGRect(x: 60, y: 0, width: 200, height: 50))
titleLabel.text = "Processing..."
self.viewActivityIndicator.addSubview(self.activityIndicator)
self.viewActivityIndicator.addSubview(titleLabel)
self.view.addSubview(self.viewActivityIndicator)
}
func doSometing()
{
self.activityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
//do something here that will taking time
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
self.viewActivityIndicator.removeFromSuperview()
}
Chain both class selectors (without a space in between):
.foo.bar {
/* Styles for element(s) with foo AND bar classes */
}
If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar
in this case) instead, regardless of what other classes you list.
To illustrate how other browsers and IE6 interpret this, consider this CSS:
* {
color: black;
}
.foo.bar {
color: red;
}
Output on supported browsers is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Not selected, black text [3] -->
Output on IE6 is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Selected, red text [2] -->
Footnotes:
foo
.foo
and bar
.bar
.
bar
.bar
, regardless of any other classes listed.Simple way
@{
Model.CRN = ViewBag.CRN;
}
@Html.HiddenFor(x => x.CRN)
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Style1.java
*
* Created on May 5, 2011, 6:31:16 AM
*/
package Test;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
/**
*
* @author Sameera
*/
public class Style2 extends javax.swing.JFrame {
/** Creates new form Style1 */
public Style2() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
cmd_SH = new javax.swing.JButton();
pnl_2 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
cmd_SH.setText("Hide");
cmd_SH.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmd_SHActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(558, Short.MAX_VALUE)
.addComponent(cmd_SH)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(236, Short.MAX_VALUE)
.addComponent(cmd_SH)
.addContainerGap())
);
pnl_2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
javax.swing.GroupLayout pnl_2Layout = new javax.swing.GroupLayout(pnl_2);
pnl_2.setLayout(pnl_2Layout);
pnl_2Layout.setHorizontalGroup(
pnl_2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 621, Short.MAX_VALUE)
);
pnl_2Layout.setVerticalGroup(
pnl_2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 270, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(pnl_2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(pnl_2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(17, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void cmd_SHActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(evt.getActionCommand());
if (evt.getActionCommand().equals("Hide")) {
pnl_2.setVisible(false);
cmd_SH.setText("Show");
this.setSize(643, 294);
this.pack();
}
if (evt.getActionCommand().equals("Show")) {
pnl_2.setVisible(true);
cmd_SH.setText("Hide");
this.setSize(643, 583);
this.pack();
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Style1().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton cmd_SH;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel pnl_2;
// End of variables declaration
}
As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract:
A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T)((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.
An example cited from §15.26.2
[...] the following code is correct:
short x = 3; x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3; x = (short)(x + 4.6);
In other words, your assumption is correct.
You can get the ListView first, and then get the Selected ListViewItem. I have an example for ListBox, but ListView should be similar.
private void listBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
ListBox box = sender as ListBox;
if (box == null) {
return;
}
MyInfo info = box.SelectedItem as MyInfo;
if (info == null)
return;
/* your code here */
}
e.Handled = true;
}