How to create table using select query in SQL Server?
An example statement that uses a sub-select :
select * into MyNewTable
from
(
select
*
from
[SomeOtherTablename]
where
EventStartDatetime >= '01/JAN/2018'
)
) mysourcedata
;
note that the sub query must be given a name .. any name .. e.g. above example gives the subquery a name of mysourcedata. Without this a syntax error is issued in SQL*server 2012.
The database should reply with a message like:
(9999 row(s) affected)
How to stop the Timer in android?
We can schedule the timer to do the work.After the end of the time we set the message won't send.
This is the code.
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//here you can write the code for send the message
}
}, 10, 60000);
In here the method we are calling is,
public void scheduleAtFixedRate (TimerTask task, long delay, long period)
In here,
task : the task to schedule
delay: amount of time in milliseconds before first execution.
period: amount of time in milliseconds between subsequent executions.
For more information you can refer:
Android Developer
You can stop the timer by calling,
timer.cancel();
Find file in directory from command line
If you're looking to do something with a list of files, you can use find combined with the bash $()
construct (better than backticks since it's allowed to nest).
for example, say you're at the top level of your project directory and you want a list of all C files starting with "btree". The command:
find . -type f -name 'btree*.c'
will return a list of them. But this doesn't really help with doing something with them.
So, let's further assume you want to search all those file for the string "ERROR" or edit them all. You can execute one of:
grep ERROR $(find . -type f -name 'btree*.c')
vi $(find . -type f -name 'btree*.c')
to do this.
Converting float to char*
char buffer[64];
int ret = snprintf(buffer, sizeof buffer, "%f", myFloat);
if (ret < 0) {
return EXIT_FAILURE;
}
if (ret >= sizeof buffer) {
/* Result was truncated - resize the buffer and retry.
}
That will store the string representation of myFloat
in myCharPointer
. Make sure that the string is large enough to hold it, though.
snprintf
is a better option than sprintf
as it guarantees it will never write past the size of the buffer you supply in argument 2.
How to check if string contains Latin characters only?
I'm surprised that the answers here got so many upvotes when none of them really answer the question. Here's how to make sure that ONLY LATIN characters are in a given string.
const hasOnlyLetters = !!value.match(/^[a-z]*$/i);
The !!
takes transforms something that's not boolean into a boolean value. (It's exactly the same as applying a !
twice, and in fact you can use as many !
as you'd like to toggle the truthiness multiple times.)
As for the RegEx, here's the breakdown.
/.../i
The delimiter is a /
and the i
means to assess the statement in a case-insensitive fashion.
^...$
The ^
means to look at the very beginning of a string. The $
means to look at the end of the string, and when used together, it means to consider the entire string. You can add more to the RegEx outside of these boundaries for things like appending/prepending a required suffix or prefix.
[a-z]*
This part says to look for all lowercase letters. (The case-insensitive modifier means that we don't need to look at uppercase letters, too.) The *
at the end says that we should match whats in the brackets any number of times. That way "abc" will match instead of just "a" or "b", and so forth.
Can you use Microsoft Entity Framework with Oracle?
The answer is "mostly".
We've hit a problem using it where the EF generates code that uses the CROSS and OUTER APPLY operators. This link shows that MS knows its a problem with SQL Server previous to 2005 however, they forget to mention that these operators are not supported by Oracle either.
how to convert current date to YYYY-MM-DD format with angular 2
Here is a very nice and compact way to do this, you can also change this function as your case needs:
result: 03.11.2017
//get date now function
getNowDate() {
//return string
var returnDate = "";
//get datetime now
var today = new Date();
//split
var dd = today.getDate();
var mm = today.getMonth() + 1; //because January is 0!
var yyyy = today.getFullYear();
//Interpolation date
if (dd < 10) {
returnDate += `0${dd}.`;
} else {
returnDate += `${dd}.`;
}
if (mm < 10) {
returnDate += `0${mm}.`;
} else {
returnDate += `${mm}.`;
}
returnDate += yyyy;
return returnDate;
}
How to downgrade tensorflow, multiple versions possible?
You can try to use the options of --no-cache-dir
together with -I
to overwrite the cache of the previous version and install the new version. For example:
pip3 install --no-cache-dir -I tensorflow==1.1
Then use the following command to check the version of tensorflow:
python3 -c ‘import tensorflow as tf; print(tf.__version__)’
It should show the right version got installed.
Image resizing client-side with JavaScript before upload to the server
Here's a gist which does this:
https://gist.github.com/dcollien/312bce1270a5f511bf4a
(an es6 version, and a .js version which can be included in a script tag)
You can use it as follows:
<input type="file" id="select">
<img id="preview">
<script>
document.getElementById('select').onchange = function(evt) {
ImageTools.resize(this.files[0], {
width: 320, // maximum width
height: 240 // maximum height
}, function(blob, didItResize) {
// didItResize will be true if it managed to resize it, otherwise false (and will return the original file as 'blob')
document.getElementById('preview').src = window.URL.createObjectURL(blob);
// you can also now upload this blob using an XHR.
});
};
</script>
It includes a bunch of support detection and polyfills to make sure it works on as many browsers as I could manage.
(it also ignores gif images - in case they're animated)
Get integer value from string in swift
In Swift 3.0
Type 1: Convert NSString to String
let stringNumb:NSString = "1357"
let someNumb = Int(stringNumb as String) // 1357 as integer
Type 2: If the String has Integer only
let stringNumb = "1357"
let someNumb = Int(stringNumb) // 1357 as integer
Type 3: If the String has Float value
let stringNumb = "13.57"
if let stringToFloat = Float(stringNumb){
let someNumb = Int(stringToFloat)// 13 as Integer
}else{
//do something if the stringNumb not have digit only. (i.e.,) let stringNumb = "13er4"
}
How do you make a div tag into a link
So you want an element to be something it's not?
Generally speaking this isn't a good idea. If you need a link, use a link. Most of the time it's easier to just use the appropriate markup where it belongs.
That all said, sometimes you just have to break the rules. Now, the question doesn't have javascript, so I'm going to put the disclaimer here:
You can't have a <div>
act as a link without either using a link (or equivalent, such as a <form>
that only contains a submit button) or using JavaScript.
From here on out, this answer is going to assume that JavaScript is allowed, and furthermore that jQuery is being used (for brevity of example).
With that all said, lets dig into what makes a link a link.
Links are generally elements that you click on so that they navigate you to a new document.
It seems simple enough. Listen for a click event and change the location:
Don't do this
_x000D_
_x000D_
$('.link').on('click', function () {_x000D_
window.location = 'http://example.com';_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="link">Fake Link</div>
_x000D_
_x000D_
_x000D_
There you have it, the <div>
is now a link. Wait...what's that? What about accessibility? Oh right, screen readers and users of assistive technology won't be able to click on the link, especially if they're only using the keyboard.
Fixing that's pretty simple, let's allow keyboard only users to focus the <div>
, and trigger the click event when they press Enter:
Don't do this either
_x000D_
_x000D_
$('.link').on({_x000D_
'click': function () {_x000D_
window.location = 'http://example.com';_x000D_
},_x000D_
'keydown': function (e) {_x000D_
if (e.which === 13) {_x000D_
$(this).trigger('click');_x000D_
}_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="link" tabindex="0">Fake Link</div>
_x000D_
_x000D_
_x000D_
Again, there you have it, this <div>
is now a link. Wait...again? Still accessibility problems? Oh ok, so it turns out that the assistive technology doesn't know that the <div>
is a link yet, so even though you can get there via keyboard, users aren't being told what to do with it.
Fortunately, there's an attribute that can be used to override an HTML element's default role, so that screen readers and the like know how to categorize customized elements, like our <div>
here. The attribute is of course the [role]
attribute, and it nicely tells screen readers that our <div>
is a link:
Ugh, this is getting worse every minute
_x000D_
_x000D_
$('[role="link"]').on({_x000D_
'click': function () {_x000D_
window.location = 'http://example.com';_x000D_
},_x000D_
'keydown': function (e) {_x000D_
if (e.which === 13) {_x000D_
$(this).trigger('click');_x000D_
}_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div role="link" tabindex="0">Fake Link</div>
_x000D_
_x000D_
_x000D_
Finally, our <div>
is a lin---oh now the other devs are complaining. What now?
Ok, so the devs don't like the code. They tried to preventDefault
on the event, and it just keeps working. That's easy to fix:
I warned you this was bad
_x000D_
_x000D_
$(document).on({_x000D_
'click': function (e) {_x000D_
if (!e.isDefaultPrevented()) {_x000D_
window.location = 'http://example.com';_x000D_
}_x000D_
},_x000D_
'keydown': function (e) {_x000D_
if (e.which === 13 && !e.isDefaultPrevented()) {_x000D_
$(this).trigger('click');_x000D_
}_x000D_
}_x000D_
}, '[role="link"]');_x000D_
_x000D_
$('[aria-disabled="true"]').on('click', function (e) {_x000D_
e.preventDefault();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div role="link" tabindex="0">Fake Link</div>_x000D_
<div role="link" aria-disabled="true" tabindex="0">Fake disabled link</div>
_x000D_
_x000D_
_x000D_
There we have it---THERE'S MORE? What else don't I know? Tell me everything NOW so that I can fix it!
- Ok, so there's no way to specify target. We can fix that by updating to
window.open
.
- Click events and keyboard events are ignoring Ctrl, Alt, and Shift keys. That's easy enough, just need to check those values on the event object.
- There's no way to specify contextual data. Let's just add some
[data-*]
attributes, and call it a day with that one.
- The click event isn't obeying the mouse button that's being used, middle mouse should open in a new tab, right mouse shouldn't be triggering the event. Easy enough, just add some more checks to the event listeners.
- The styles look weird. WELL OF COURSE THE STYLES ARE WEIRD, IT'S A
<DIV>
NOT AN ANCHOR!
well, I'll address the first four issues, and NO MORE. I've had it with this stupid custom element garbage. I should have just used an <a>
element from the beginning.
Told you so
_x000D_
_x000D_
$(document).on({_x000D_
'click': function (e) {_x000D_
var target,_x000D_
href;_x000D_
if (!e.isDefaultPrevented() && (e.which === 1 || e.which === 2)) {_x000D_
target = $(this).data('target') || '_self';_x000D_
href = $(this).data('href');_x000D_
if (e.ctrlKey || e.shiftKey || e.which === 2) {_x000D_
target = '_blank'; //close enough_x000D_
}_x000D_
open(href, target);_x000D_
}_x000D_
},_x000D_
'keydown': function (e) {_x000D_
if (e.which === 13 && !e.isDefaultPrevented()) {_x000D_
$(this).trigger({_x000D_
type: 'click',_x000D_
ctrlKey: e.ctrlKey,_x000D_
altKey: e.altKey,_x000D_
shiftKey: e.shiftKey_x000D_
});_x000D_
}_x000D_
}_x000D_
}, '[role="link"]');_x000D_
_x000D_
$('[aria-disabled="true"]').on('click', function (e) {_x000D_
e.preventDefault();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div role="link" tabindex="0" data-href="http://example.com/">Fake Link</div>_x000D_
<div role="link" tabindex="0" data-href="http://example.com/" data-target="_blank">Fake Link With Target</div>_x000D_
<div role="link" aria-disabled="true" tabindex="0" data-href="http://example.com/">Fake disabled link</div>
_x000D_
_x000D_
_x000D_
Note that stack snippets won't open popup windows because of how they're sandboxed.
That's it. That's the end of this rabbit hole. All of that craziness when you could have simply had:
<a href="http://example.com/">
...your markup here...
</a>
The code I posted here probably has problems. It probably has bugs that even I don't realize as of yet. Trying to duplicate what browsers give you for free is tough. There are so many nuances that are easy to overlook that it's simply not worth trying to emulate it 99% of the time.
MySQL - Rows to Columns
Taking advantage of Matt Fenwick's idea that helped me to solve the problem (a lot of thanks), let's reduce it to only one query:
select
history.*,
coalesce(sum(case when itemname = "A" then itemvalue end), 0) as A,
coalesce(sum(case when itemname = "B" then itemvalue end), 0) as B,
coalesce(sum(case when itemname = "C" then itemvalue end), 0) as C
from history
group by hostid
How to upgrade R in ubuntu?
Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here
Open the sources.list
file:
sudo nano /etc/apt/sources.list
Add a line with the source from where the packages will be retrieved. For example:
deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
Replace https://cloud.r-project.org
with whatever mirror you would like to use, and replace
version/
with whatever version of Ubuntu you are using (eg, trusty/
, xenial/
, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/
and version/
.
Fetch the secure APT key:
gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
or
gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
Add it to keyring:
gpg -a --export E084DAB9 | sudo apt-key add -
Update your sources and upgrade your installation:
sudo apt-get update && sudo apt-get upgrade
Install the new version
sudo apt-get install r-base-dev
Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:
-- copy the packages from R-oldversion/library
to R-newversion/library
, (do not overwrite a package if it already exists in the new version!).
-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE)
.
How to commit to remote git repository
Have you tried git push? gitref.org has a nice section dealing with remote repositories.
You can also get help from the command line using the --help
option. For example:
% git push --help
GIT-PUSH(1) Git Manual GIT-PUSH(1)
NAME
git-push - Update remote refs along with associated objects
SYNOPSIS
git push [--all | --mirror | --tags] [-n | --dry-run] [--receive-pack=<git-receive-pack>]
[--repo=<repository>] [-f | --force] [-v | --verbose] [-u | --set-upstream]
[<repository> [<refspec>...]]
...
The given key was not present in the dictionary. Which key?
This exception is thrown when you try to index to something that isn't there, for example:
Dictionary<String, String> test = new Dictionary<String,String>();
test.Add("Key1","Value1");
string error = test["Key2"];
Often times, something like an object will be the key, which undoubtedly makes it harder to get. However, you can always write the following (or even wrap it up in an extension method):
if (test.ContainsKey(myKey))
return test[myKey];
else
throw new Exception(String.Format("Key {0} was not found", myKey));
Or more efficient (thanks to @ScottChamberlain)
T retValue;
if (test.TryGetValue(myKey, out retValue))
return retValue;
else
throw new Exception(String.Format("Key {0} was not found", myKey));
Microsoft chose not to do this, probably because it would be useless when used on most objects. Its simple enough to do yourself, so just roll your own!
Using Java generics for JPA findAll() query with WHERE clause
Hat tip to Adam Bien if you don't want to use createQuery
with a String
and want type safety:
@PersistenceContext
EntityManager em;
public List<ConfigurationEntry> allEntries() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<ConfigurationEntry> cq = cb.createQuery(ConfigurationEntry.class);
Root<ConfigurationEntry> rootEntry = cq.from(ConfigurationEntry.class);
CriteriaQuery<ConfigurationEntry> all = cq.select(rootEntry);
TypedQuery<ConfigurationEntry> allQuery = em.createQuery(all);
return allQuery.getResultList();
}
http://www.adam-bien.com/roller/abien/entry/selecting_all_jpa_entities_as
How do you print in Sublime Text 2
Still no print no native print function, but outside the installing the suggested package, you can go the autohotkey way, as the that app can actually help you run macros for other stuff as well. So you can do something like create a macro that with one click does:
- Select all the text
- Copies all the text
- Opens your other edit of choice
- pastes text
- Prints text
No the most glamorous of options but could also work if the receiving app has can accept code-formatting.
open link in iframe
Because the target of the link matches the name of the iframe, the link will open in the iframe.
Try this:
<iframe src="http://stackoverflow.com/" name="iframe_a">
<p>Your browser does not support iframes.</p>
</iframe>
<a href="http://www.cnn.com" target="iframe_a">www.cnn.com</a>
How do I show my global Git configuration?
To find all configurations, you just write this command:
git config --list
In my local i run this command .
Md Masud@DESKTOP-3HTSDV8 MINGW64 ~
$ git config --list
core.symlinks=false
core.autocrlf=true
core.fscache=true
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=true
help.format=html
rebase.autosquash=true
http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
http.sslbackend=openssl
diff.astextplain.textconv=astextplain
filter.lfs.clean=git-lfs clean -- %f
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
credential.helper=manager
[email protected]
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
filter.lfs.clean=git-lfs clean -- %f
Error # 1045 - Cannot Log in to MySQL server -> phpmyadmin
In mysql 5.7 the auth mechanism changed, documentation can be found in the official manual here.
Using the system root user (or sudo
) you can connect to the mysql database with the mysql 'root' user via CLI.
All other users will work, too.
In phpmyadmin however, all mysql users will work, but not the mysql 'root' user.
This comes from here:
$ mysql -Ne "select Host,User,plugin from mysql.user where user='root';"
+-----------+------+-----------------------+
| localhost | root | auth_socket |
| hostname | root | mysql_native_password |
+-----------+------+-----------------------+
To 'fix' this security feature, do:
mysql -Ne "update mysql.user set plugin='mysql_native_password' where User='root' and Host='localhost'; flush privileges;"
More on this can also be found here in the manual.
Aggregate a dataframe on a given column and display another column
A base R solution is to combine the output of aggregate()
with a merge()
step. I find the formula interface to aggregate()
a little more useful than the standard interface, partly because the names on the output are nicer, so I'll use that:
The aggregate()
step is
maxs <- aggregate(Score ~ Group, data = dat, FUN = max)
and the merge()
step is simply
merge(maxs, dat)
This gives us the desired output:
R> maxs <- aggregate(Score ~ Group, data = dat, FUN = max)
R> merge(maxs, dat)
Group Score Info
1 1 3 c
2 2 4 d
You could, of course, stick this into a one-liner (the intermediary step was more for exposition):
merge(aggregate(Score ~ Group, data = dat, FUN = max), dat)
The main reason I used the formula interface is that it returns a data frame with the correct names
for the merge step; these are the names of the columns from the original data set dat
. We need to have the output of aggregate()
have the correct names so that merge()
knows which columns in the original and aggregated data frames match.
The standard interface gives odd names, whichever way you call it:
R> aggregate(dat$Score, list(dat$Group), max)
Group.1 x
1 1 3
2 2 4
R> with(dat, aggregate(Score, list(Group), max))
Group.1 x
1 1 3
2 2 4
We can use merge()
on those outputs, but we need to do more work telling R which columns match up.
Javascript - sort array based on another array
I had to do this for a JSON payload I receive from an API, but it wasn't in the order I wanted it.
Array to be the reference array, the one you want the second array sorted by:
var columns = [
{last_name: "last_name"},
{first_name: "first_name"},
{book_description: "book_description"},
{book_id: "book_id"},
{book_number: "book_number"},
{due_date: "due_date"},
{loaned_out: "loaned_out"}
];
I did these as objects because these will have other properties eventually.
Created array:
var referenceArray= [];
for (var key in columns) {
for (var j in columns[key]){
referenceArray.push(j);
}
}
Used this with result set from database. I don't know how efficient it is but with the few number of columns I used, it worked fine.
result.forEach((element, index, array) => {
var tr = document.createElement('tr');
for (var i = 0; i < referenceArray.length - 1; i++) {
var td = document.createElement('td');
td.innerHTML = element[referenceArray[i]];
tr.appendChild(td);
}
tableBody.appendChild(tr);
});
How to check if spark dataframe is empty?
I would say to just grab the underlying RDD
. In Scala:
df.rdd.isEmpty
in Python:
df.rdd.isEmpty()
That being said, all this does is call take(1).length
, so it'll do the same thing as Rohan answered...just maybe slightly more explicit?
Efficient way to rotate a list in python
This also depends on if you want to shift the list in place (mutating it), or if you want the function to return a new list. Because, according to my tests, something like this is at least twenty times faster than your implementation that adds two lists:
def shiftInPlace(l, n):
n = n % len(l)
head = l[:n]
l[:n] = []
l.extend(head)
return l
In fact, even adding a l = l[:]
to the top of that to operate on a copy of the list passed in is still twice as fast.
Various implementations with some timing at http://gist.github.com/288272
Javascript require() function giving ReferenceError: require is not defined
Yes, require is a Node.JS function and doesn't work in client side scripting without certain requirements. If you're getting this error while writing electronJS code, try the following:
In your BrowserWindow declaration, add the following webPreferences field:
i.e, instead of plain mainWindow = new BrowserWindow()
, write
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
});
Java constructor/method with optional parameters?
Java doesn't have the concept of optional parameters with default values either in constructors or in methods. You're basically stuck with overloading. However, you chain constructors easily so you don't need to repeat the code:
public Foo(int param1, int param2)
{
this.param1 = param1;
this.param2 = param2;
}
public Foo(int param1)
{
this(param1, 2);
}
Display PDF within web browser
You can use the <embed>
tag with the source of the file in the src
attribute. This uses the native browser PDF viewer.
<embed src="your_pdf_src" style="position:absolute; left: 0; top: 0;" width="100%" height="100%" type="application/pdf">
Live example:
_x000D_
_x000D_
<embed src="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" style="position:absolute; left: 0; top: 0;" width="100%" height="100%" type="application/pdf">
_x000D_
_x000D_
_x000D_
Loading the PDF inside a snippet won't work, since the frame into which the plugin is loading is sandboxed.
Tested in Chrome and Firefox. See it in action.
text box input height
If you want to increase the height of the input field, you can specify line-height
css property for the input field.
input {
line-height: 2em; // 2em is (2 * default line height)
}
When is JavaScript synchronous?
JavaScript is always synchronous and single-threaded. If you're executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed.
JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls. The Ajax call will stop executing and other code will be able to execute until the call returns (successfully or otherwise), at which point the callback will run synchronously. No other code will be running at this point. It won't interrupt any other code that's currently running.
JavaScript timers operate with this same kind of callback.
Describing JavaScript as asynchronous is perhaps misleading. It's more accurate to say that JavaScript is synchronous and single-threaded with various callback mechanisms.
jQuery has an option on Ajax calls to make them synchronously (with the async: false
option). Beginners might be tempted to use this incorrectly because it allows a more traditional programming model that one might be more used to. The reason it's problematic is that this option will block all JavaScript on the page until it finishes, including all event handlers and timers.
Some projects cannot be imported because they already exist in the workspace error in Eclipse
My problem was a little bit different.
For example, the project name (what I see) was FooProject and in the imported project, I was looking for the FooProject but I could not. However, Eclipse does not let me import that project because he claims that it is already imported. And then, I have looked at the .project
file of the project and I have seen that the actual name of the project was not what I see (FooProject).
The conclusion;
The name of the project (what you see in Eclipse) may be different than the actual name of the project (what maven see). Because of this reason. Please be sure that they are the same name by checking .project
file of the project.
Linux - Install redis-cli only
In my case, I have to run some more steps to build it on RedHat or Centos.
# get system libraries
sudo yum install -y gcc wget
# get stable version and untar it
wget http://download.redis.io/redis-stable.tar.gz
tar xvzf redis-stable.tar.gz
cd redis-stable
# build dependencies too!
cd deps
make hiredis jemalloc linenoise lua geohash-int
cd ..
# compile it
make
# make it globally accesible
sudo cp src/redis-cli /usr/bin/
How to pass command line arguments to a shell alias?
I found that functions cannot be written in ~/.cshrc
file. Here in alias which takes arguments
for example, arguments passed to 'find' command
alias fl "find . -name '\!:1'"
Ex: >fl abc
where abc is the argument passed as !:1
Rename package in Android Studio
it will work fine for me
Change Following.
Step 1: Make sure ApplicationId And PackageName will Same.
example :
android {
defaultConfig {
applicationId "com.example.myapplication"
}
}
and package name the same. package="com.example.myapplication"
Step 2
delete iml file in my case :
Go To Project> >C:\Users\ashif\Documents\MyApplication .iml file // delete
if you forget Project Path Then Go To android Studio Right Click on app and go to Show in Explorer you get your Project and remove .iml file
Step 3
Close Project
Step 4
Now Copy Your old Project and Paste Any other Root or copy Project Folder and paste Any
other Dir.
Example C:\Users\ashif\Documents/MyApplication
Step 5
Now open Android Studio and open Existing Project
C:\Users\ashif\Documents/MyApplication
Try it will work
Disabled form fields not submitting data
We can also use the readonly only with below attributes -
readonly onclick='return false;'
This is because if we will only use the readonly then radio buttons will be editable. To avoid this situation we can use readonly with above combination. It will restrict the editing and element's values will also passed during form submission.
Does a TCP socket connection have a "keep alive"?
TCP sockets remain open till they are closed.
That said, it's very difficult to detect a broken connection (broken, as in a router died, etc, as opposed to closed) without actually sending data, so most applications do some sort of ping/pong reaction every so often just to make sure the connection is still actually alive.
How do I convert a list of ascii values to a string in python?
You are probably looking for 'chr()':
>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(chr(i) for i in L)
'hello, world'
MySQL select with CONCAT condition
Try this:
SELECT *
FROM (
SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast
FROM users
) a
WHERE firstlast = "Bob Michael Jones"
ASP.NET MVC View Engine Comparison
I think this list should also include samples of each view engine so users can get a flavour of each without having to visit every website.
Pictures say a thousand words and markup samples are like screenshots for view engines :) So here's one from my favourite Spark View Engine
<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
<li each="var p in products">${p.Name}</li>
</ul>
<else>
<p>No products available</p>
</else>
How to get `DOM Element` in Angular 2?
Angular 2.0.0 Final:
I have found that using a ViewChild
setter is most reliable way to set the initial form control focus:
@ViewChild("myInput")
set myInput(_input: ElementRef | undefined) {
if (_input !== undefined) {
setTimeout(() => {
this._renderer.invokeElementMethod(_input.nativeElement, "focus");
}, 0);
}
}
The setter is first called with an undefined
value followed by a call with an initialized ElementRef
.
Working example and full source here: http://plnkr.co/edit/u0sLLi?p=preview
Using TypeScript 2.0.3 Final/RTM, Angular 2.0.0 Final/RTM, and Chrome 53.0.2785.116 m (64-bit).
UPDATE for Angular 4+
Renderer
has been deprecated in favor of Renderer2
, but Renderer2
does not have the invokeElementMethod
. You will need to access the DOM directly to set the focus as in input.nativeElement.focus()
.
I'm still finding that the ViewChild setter approach works best. When using AfterViewInit
I sometimes get read property 'nativeElement' of undefined
error.
@ViewChild("myInput")
set myInput(_input: ElementRef | undefined) {
if (_input !== undefined) {
setTimeout(() => { //This setTimeout call may not be necessary anymore.
_input.nativeElement.focus();
}, 0);
}
}
How to update MySql timestamp column to current timestamp on PHP?
Use this query:
UPDATE `table` SET date_date=now();
Sample code can be:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("UPDATE `table` SET date_date=now()");
mysql_close($con);
?>
C++ Object Instantiation
There is an additional reason, which no one else has mentioned, why you might choose to create your object dynamically. Dynamic, heap based objects allow you to make use of polymorphism.
Making a Windows shortcut start relative to where the folder is?
Right click on your /bat/ folder and click Create Shortcut.
- On Windows 7 you will get
bat - Shortcut
in the current directory.
- On Windows XP you will get
Shortcut to bat
.
Right click on the shortcut you just created and click Properties.
Change Target (under the Shortcut tab on Windows 7) to the following:
%windir%\system32\cmd.exe /c start "" "%CD%\bat\bat\run.bat"
Make sure Start in is blank. That causes it to start in the current directory.
- Click OK. On Windows 7, the shortcut icon will change to the cmd.exe icon.
That's probably acceptable in the case of shortcutting to a .bat but if you want to change the icon, open the shortcut's properties again and click Change Icon... (again, under the Shortcut tab on Windows 7). At this point you can Browse... for an icon or bring up a list of default system icons by entering
%SystemRoot%\system32\SHELL32.dll
to the left of the Browse...
button and hitting Enter. This works on Windows 7 and Windows XP but the icons are different due to style updates (but are recognizably similar). Depending on the version of Windows the shortcut resides, the icon will will sometimes change accordingly.
More Info:
See Using the "start" command with parameters passed to the started program to better understand the empty double-quotes at the beginning of the first Target command.
Nested jQuery.each() - continue/break
return true not work
return false working
found = false;
query = "foo";
$('.items').each(function()
{
if($(this).text() == query)
{
found = true;
return false;
}
});
What command means "do nothing" in a conditional in Bash?
You can probably just use the true
command:
if [ "$a" -ge 10 ]; then
true
elif [ "$a" -le 5 ]; then
echo "1"
else
echo "2"
fi
An alternative, in your example case (but not necessarily everywhere) is to re-order your if/else:
if [ "$a" -le 5 ]; then
echo "1"
elif [ "$a" -lt 10 ]; then
echo "2"
fi
Laravel 5 – Clear Cache in Shared Hosting Server
You can do this if you are using Lumen
from Laravel
on your routes/web.php
file:
use Illuminate\Support\Facades\Artisan;
$app->get('/clear-cache', function () {
$code = Artisan::call('cache:clear');
return 'cache cleared';
});
Adding gif image in an ImageView in android
Gif's can also be displayed in web view with couple of lines of code and without any 3rd party libraries.
This way you can even load the gif from your SD card. No need to copy images to your Asset folder.
Take a web view.
<WebView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageWebView" />
Use can open a gif file from SD card not just from asset folder as shown in many examples.
WebView webView = (WebView) findViewById(R.id.imageWebView);
String data = "<body> <img src = \""+ filePath+"\"/></body>";
// 'filePath' is the path of your .GIF file on SD card.
webView.loadDataWithBaseURL("file:///android_asset/",data,"text/html","UTF-8",null);
How can I lock a file using java (if possible)
FileChannel.lock is probably what you want.
try (
FileInputStream in = new FileInputStream(file);
java.nio.channels.FileLock lock = in.getChannel().lock();
Reader reader = new InputStreamReader(in, charset)
) {
...
}
(Disclaimer: Code not compiled and certainly not tested.)
Note the section entitled "platform dependencies" in the API doc for FileLock.
Why do we check up to the square root of a prime number to determine if it is prime?
Let's say we have a number "a", which is not prime [not prime/composite number means - a number which can be divided evenly by numbers other than 1 or itself. For example, 6 can be divided evenly by 2, or by 3, as well as by 1 or 6].
6 = 1 × 6 or 6 = 2 × 3
So now if "a" is not prime then it can be divided by two other numbers and let's say those numbers are "b" and "c". Which means
a=b*c.
Now if "b" or "c" , any of them is greater than square root of "a "than multiplication of "b" & "c" will be greater than "a".
So, "b" or "c" is always <= square root of "a" to prove the equation "a=b*c".
Because of the above reason, when we test if a number is prime or not, we only check until square root of that number.
How to check if command line tools is installed
10.14 Mojave Update:
See Yosemite Update.
10.13 High Sierra Update:
See Yosemite Update.
10.12 Sierra Update:
See Yosemite Update.
10.11 El Capitan Update:
See Yosemite Update.
10.10 Yosemite Update:
Just enter in gcc
or make
on the command line! OSX will know that you do not have the command line tools and prompt you to install them!
To check if they exist, xcode-select -p
will print the directory. Alternatively, the return value will be 2
if they do NOT exist, and 0
if they do. To just print the return value (thanks @Andy):
xcode-select -p 1>/dev/null;echo $?
10.9 Mavericks Update:
Use pkgutil --pkg-info=com.apple.pkg.CLTools_Executables
10.8 Update:
Option 1: Rob Napier suggested to use pkgutil --pkg-info=com.apple.pkg.DeveloperToolsCLI
, which is probably cleaner.
Option 2: Check inside /var/db/receipts/com.apple.pkg.DeveloperToolsCLI.plist
for a reference to com.apple.pkg.DeveloperToolsCLI
and it will list the version 4.5.0
.
[Mar 12 17:04] [jnovack@yourmom ~]$ defaults read /var/db/receipts/com.apple.pkg.DeveloperToolsCLI.plist
{
InstallDate = "2012-12-26 22:45:54 +0000";
InstallPrefixPath = "/";
InstallProcessName = Xcode;
PackageFileName = "DeveloperToolsCLI.pkg";
PackageGroups = (
"com.apple.FindSystemFiles.pkg-group",
"com.apple.DevToolsBoth.pkg-group",
"com.apple.DevToolsNonRelocatableShared.pkg-group"
);
PackageIdentifier = "com.apple.pkg.DeveloperToolsCLI";
PackageVersion = "4.5.0.0.1.1249367152";
PathACLs = {
Library = "!#acl 1\\ngroup:ABCDEFAB-CDEF-ABCD-EFAB-CDEF0000000C:everyone:12:deny:delete\\n";
System = "!#acl 1\\ngroup:ABCDEFAB-CDEF-ABCD-EFAB-CDEF0000000C:everyone:12:deny:delete\\n";
};
}
Detect change to selected date with bootstrap-datepicker
_x000D_
_x000D_
$(function() {_x000D_
$('input[name="datetimepicker"]').datetimepicker({_x000D_
defaultDate: new Date()_x000D_
}).on('dp.change',function(event){_x000D_
$('#newDateSpan').html("New Date: " + event.date.format('lll'));_x000D_
$('#oldDateSpan').html("Old Date: " + event.oldDate.format('lll'));_x000D_
});_x000D_
_x000D_
});
_x000D_
<link href="http://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/e8bddc60e73c1ec2475f827be36e1957af72e2ea/build/css/bootstrap-datetimepicker.css" rel="stylesheet"/>_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://momentjs.com/downloads/moment.min.js"></script>_x000D_
<script src="http://getbootstrap.com/dist/js/bootstrap.min.js"></script>_x000D_
<script src="http://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/e8bddc60e73c1ec2475f827be36e1957af72e2ea/src/js/bootstrap-datetimepicker.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div class="col-xs-12">_x000D_
<input name="datetimepicker" />_x000D_
<p><span id="newDateSpan"></span><br><span id="oldDateSpan"></span></p>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
new DateTime() vs default(DateTime)
The answer is no. Keep in mind that in both cases, mdDate.Kind = DateTimeKind.Unspecified
.
Therefore it may be better to do the following:
DateTime myDate = new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc);
The myDate.Kind
property is readonly, so it cannot be changed after the constructor is called.
Collision Detection between two images in Java
Here's the main class from my collision detection program.
You can see it run at: http://www.youtube.com/watch?v=JIXhCvXgjsQ
/**
*
* @author Tyler Griffin
*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.GraphicsDevice.*;
import java.util.ArrayList;
import java.awt.Graphics;
import java.awt.geom.Line2D;
public class collision extends JFrame implements KeyListener, MouseMotionListener, MouseListener
{
ArrayList everything=new ArrayList<tile>();
int time=0, x, y, width, height, up=0, down=0, left=0, right=0, mouse1=0, mouse2=0;
int mouseX, mouseY;
GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice screen = environment.getDefaultScreenDevice();
DisplayMode displayMode = screen.getDisplayMode();
//private BufferStrategy strategy;
JLayeredPane pane = new JLayeredPane();
tile Tile;
circle Circle;
rectangle Rectangle;
textPane text;
public collision()
{
setUndecorated(screen.isFullScreenSupported());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLayout(null);
setResizable(false);
screen.setFullScreenWindow(this);
width=displayMode.getWidth();
height=displayMode.getHeight();
Circle=new circle(-(int)Math.round((double)height/7*2),-(int)Math.round((double)height/7*2),(int)Math.round((double)height/7*.85),this);
Rectangle=new rectangle(-(int)Math.round((double)height/7*1.5),-(int)Math.round((double)height/7*1.5),(int)Math.round((double)height/7*1.5),(int)Math.round((double)height/7*1.5),this);
Tile=Circle;
Tile.move(mouseX-Tile.width/2, mouseY-Tile.height/2);
text=new textPane(0,0,width,height,this);
everything.add(new circle((int)Math.round((double)width/100*75),(int)Math.round((double)height/100*15),(int)Math.round((double)width/100*10),this));
everything.add(new rectangle((int)Math.round((double)width/100*70),(int)Math.round((double)height/100*60),(int)Math.round((double)width/100*20),(int)Math.round((double)height/100*20),this));
//everything.add(new line(750,250,750,750,this));
/*everything.add(new line(width/700*419,height/700*68,width/700*495,height/700*345,this));
everything.add(new line(width/700*495,height/700*345,width/700*749,height/700*350,this));
everything.add(new line(width/700*749,height/700*350,width/700*549,height/700*519,this));
everything.add(new line(width/700*549,height/700*519,width/700*624,height/700*800,this));
everything.add(new line(width/700*624,height/700*800,width/700*419,height/700*638,this));
everything.add(new line(width/700*419,height/700*638,width/700*203,height/700*800,this));
everything.add(new line(width/700*203,height/700*800,width/700*279,height/700*519,this));
everything.add(new line(width/700*279,height/700*519,width/700*76,height/700*350,this));
everything.add(new line(width/700*76,height/700*350,width/700*333,height/700*345,this));
everything.add(new line(width/700*333,height/700*345,width/700*419,height/700*68,this));
everything.add(new line(width/950*419,height/700*68,width/950*624,height/700*800,this));
everything.add(new line(width/950*419,height/700*68,width/950*203,height/700*800,this));
everything.add(new line(width/950*76,height/700*350,width/950*624,height/700*800,this));
everything.add(new line(width/950*203,height/700*800,width/950*749,height/700*350,this));
everything.add(new rectangle(width/950*76,height/700*350,width/950*673,1,this));*/
everything.add(new line((int)Math.round((double)width/1350*419),(int)Math.round((double)height/1000*68),(int)Math.round((double)width/1350*624),(int)Math.round((double)height/1000*800),this));
everything.add(new line((int)Math.round((double)width/1350*419),(int)Math.round((double)height/1000*68),(int)Math.round((double)width/1350*203),(int)Math.round((double)height/1000*800),this));
everything.add(new line((int)Math.round((double)width/1350*76),(int)Math.round((double)height/1000*350),(int)Math.round((double)width/1350*624),(int)Math.round((double)height/1000*800),this));
everything.add(new line((int)Math.round((double)width/1350*203),(int)Math.round((double)height/1000*800),(int)Math.round((double)width/1350*749),(int)Math.round((double)height/1000*350),this));
everything.add(new rectangle((int)Math.round((double)width/1350*76),(int)Math.round((double)height/1000*350),(int)Math.round((double)width/1350*673),1,this));
addKeyListener(this);
addMouseMotionListener(this);
addMouseListener(this);
}
public void keyReleased(KeyEvent e)
{
Object source=e.getSource();
int released=e.getKeyCode();
if (released==KeyEvent.VK_A){left=0;}
if (released==KeyEvent.VK_W){up=0;}
if (released==KeyEvent.VK_D){right=0;}
if (released==KeyEvent.VK_S){down=0;}
}//end keyReleased
public void keyPressed(KeyEvent e)
{
Object source=e.getSource();
int pressed=e.getKeyCode();
if (pressed==KeyEvent.VK_A){left=1;}
if (pressed==KeyEvent.VK_W){up=1;}
if (pressed==KeyEvent.VK_D){right=1;}
if (pressed==KeyEvent.VK_S){down=1;}
if (pressed==KeyEvent.VK_PAUSE&&pressed==KeyEvent.VK_P)
{
//if (paused==0){paused=1;}
//else paused=0;
}
}//end keyPressed
public void keyTyped(KeyEvent e){}
//***********************************************************************************************
public void mouseDragged(MouseEvent e)
{
mouseX=(e.getX());
mouseY=(e.getY());
//run();
}
public void mouseMoved(MouseEvent e)
{
mouseX=(e.getX());
mouseY=(e.getY());
//run();
}
//***********************************************************************************************
public void mousePressed(MouseEvent e)
{
if(e.getX()==0 && e.getY()==0){System.exit(0);}
mouseX=(e.getX()+x);
mouseY=(e.getY()+y);
if(Tile instanceof circle)
{
Circle.move(0-Circle.width, 0-Circle.height);
Circle.setBounds(Circle.x, Circle.y, Circle.width, Circle.height);
Tile=Rectangle;
}
else
{
Rectangle.move(0-Rectangle.width, 0-Rectangle.height);
Rectangle.setBounds(Rectangle.x, Rectangle.y, Rectangle.width, Rectangle.height);
Tile=Circle;
}
Tile.move(mouseX-Tile.width/2, mouseY-Tile.height/2);
}
public void mouseReleased(MouseEvent e)
{
//run();
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseClicked(MouseEvent e){}
//***********************************************************************************************
public void run()//run collision detection
{
while (this == this)
{
Tile.move(Tile.x + ((mouseX - (Tile.x + (Tile.width / 2))) / 10), Tile.y + ((mouseY - (Tile.y + (Tile.height / 2))) / 10));
//Tile.move((mouseX - Tile.width / 2), mouseY - (Tile.height / 2));
for (int i = 0; i < everything.size(); i++)
{
tile Temp = (tile) everything.get(i);
if (Temp.x < (Tile.x + Tile.width) && (Temp.x + Temp.width) > Tile.x && Temp.y < (Tile.y + Tile.height) && (Temp.y + Temp.height) > Tile.y)//rectangles collided
{
if (Temp instanceof rectangle)
{
if (Tile instanceof rectangle){rectangleRectangle(Temp);}
else {circleRectangle(Temp);}//Tile instanceof circle
}
else
{
if (Temp instanceof circle)
{
if (Tile instanceof rectangle) {rectangleCircle(Temp);}
else {circleCircle(Temp);}
}
else//line
{
if (Tile instanceof rectangle){rectangleLine(Temp);}
else{circleLine(Temp);}
}
}
}//end if
}//end for
try {Thread.sleep(16L);}
catch (Exception e) {}
Tile.setBounds(Tile.x, Tile.y, Tile.width, Tile.height);
//Rectangle.setBounds(x, y, width, height);
//Circle.setBounds(x, y, width, height);
repaint();
text.out=" ";
}//end while loop
}//end run
//***************************************special collision detection/handling functions************************************************
void rectangleRectangle(tile Temp)
{
int lapTop, lapBot, lapLeft, lapRight, small, scootX=0, scootY=0;
lapTop=(Temp.y+Temp.height)-Tile.y;
lapBot=(Tile.y+Tile.height)-Temp.y;
lapLeft=(Temp.x+Temp.width)-Tile.x;
lapRight=(Tile.x+Tile.width)-Temp.x;
small=999999999;
if (lapTop<small){small=lapTop; scootX=0; scootY=lapTop;}
if (lapBot<small){small=lapBot; scootX=0; scootY=lapBot*-1;}
if (lapLeft<small){small=lapLeft; scootX=lapLeft; scootY=0;}
if (lapRight<small){small=lapRight; scootX=lapRight*-1; scootY=0;}
Tile.move(Tile.x+scootX, Tile.y+scootY);text.out="collision detected!";
}
void circleRectangle(tile Temp)
{
if((Tile.x+Tile.width/2<=Temp.x+Temp.width && Tile.x+Tile.width/2>=Temp.x)||(Tile.y+Tile.height/2>=Temp.y && Tile.y+Tile.height/2<=Temp.y+Temp.height))
{
rectangleRectangle(Temp);
}
else//push from nearest corner
{
int x,y;
if(Tile.x+Tile.width/2>Temp.x+Temp.width && Tile.y+Tile.height/2<Temp.y){x=Temp.x+Temp.width; y=Temp.y;}
else if(Tile.x+Tile.width/2<Temp.x && Tile.y+Tile.height/2<Temp.y){x=Temp.x; y=Temp.y;}
else if(Tile.x+Tile.width/2>Temp.x+Temp.width && Tile.y+Tile.height/2>Temp.y+Temp.height){x=Temp.x+Temp.width; y=Temp.y+Temp.height;}
else {x=Temp.x; y=Temp.y+Temp.height;}
double distance = Math.sqrt(Math.pow(Tile.x+(Tile.width/2) - x, 2) + Math.pow(Tile.y+(Tile.height/2) - y, 2));
if((int)Math.round(distance)<Tile.height/2)
{
double normY = ((Tile.y+(Tile.height/2) - y) / distance);
double normX = ((Tile.x+(Tile.width/2) - x) / distance);
Tile.move(x-Tile.width/2+(int)Math.round(normX*((Tile.width/2))) , y-Tile.height/2+(int)Math.round(normY*((Tile.height/2))));text.out="collision detected!";
}
}
}
void rectangleCircle(tile Temp)
{
if((Temp.x+Temp.width/2<=Tile.x+Tile.width && Temp.x+Temp.width/2>=Tile.x)||(Temp.y+Temp.height/2>=Tile.y && Temp.y+Temp.height/2<=Tile.y+Tile.height))
{
rectangleRectangle(Temp);
}
else//push from nearest corner
{
int x,y;
if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2<Tile.y){x=Tile.x+Tile.width; y=Tile.y;}
else if(Temp.x+Temp.width/2<Tile.x && Temp.y+Temp.height/2<Tile.y){x=Tile.x; y=Tile.y;}
else if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2>Tile.y+Tile.height){x=Tile.x+Tile.width; y=Tile.y+Tile.height;}
else {x=Tile.x; y=Tile.y+Tile.height;}
double distance = Math.sqrt(Math.pow(Temp.x+(Temp.width/2) - x, 2) + Math.pow(Temp.y+(Temp.height/2) - y, 2));
if((int)Math.round(distance)<Temp.height/2)
{
double normY = ((Temp.y+(Temp.height/2) - y) / distance);
double normX = ((Temp.x+(Temp.width/2) - x) / distance);
if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2<Tile.y){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2)))-Tile.width,(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2))));text.out="collision detected!";}
else if(Temp.x+Temp.width/2<Tile.x && Temp.y+Temp.height/2<Tile.y){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2))),(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2))));text.out="collision detected!";}
else if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2>Tile.y+Tile.height){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2)))-Tile.width,(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2)))-Tile.height);text.out="collision detected!";}
else {Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2))),(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2)))-Tile.height);text.out="collision detected!";}
}
}
}
void circleCircle(tile Temp)
{
double distance = Math.sqrt(Math.pow((Tile.x+(Tile.width/2)) - (Temp.x+(Temp.width/2)),2) + Math.pow((Tile.y+(Tile.height/2)) - (Temp.y+(Temp.height/2)), 2));
if((int)distance<(Tile.width/2+Temp.width/2))
{
double normX = ((Tile.x+(Tile.width/2)) - (Temp.x+(Temp.width/2))) / distance;
double normY = ((Tile.y+(Tile.height/2)) - (Temp.y+(Temp.height/2))) / distance;
Tile.move((Temp.x+(Temp.width/2))+(int)Math.round(normX*(Tile.width/2+Temp.width/2))-(Tile.width/2) , (Temp.y+(Temp.height/2))+(int)Math.round(normY*(Tile.height/2+Temp.height/2))-(Tile.height/2));text.out="collision detected!";
}
}
void circleLine(tile Temp)
{
line Line=(line)Temp;
if (Line.x1 < (Tile.x + Tile.width) && (Line.x1) > Tile.x && Line.y1 < (Tile.y + Tile.height) && Line.y1 > Tile.y)//circle may be hitting one of the end points
{
rectangle rec=new rectangle(Line.x1, Line.y1, 1, 1, this);
circleRectangle(rec);
remove(rec);
}
if (Line.x2 < (Tile.x + Tile.width) && (Line.x2) > Tile.x && Line.y2 < (Tile.y + Tile.height) && Line.y2 > Tile.y)//circle may be hitting one of the end points
{
rectangle rec=new rectangle(Line.x2, Line.y2, 1, 1, this);
circleRectangle(rec);
remove(rec);
}
int x1=0, y1=0, x2=Tile.x+(Tile.width/2), y2=Tile.y+(Tile.height/2);
x1=Tile.x+(Tile.width/2)-Line.height;//(int)Math.round(Line.xNorm*1000);
x2=Tile.x+(Tile.width/2)+Line.height;
if(Line.posSlope)
{
y1=Tile.y+(Tile.height/2)-Line.width;
y2=Tile.y+(Tile.height/2)+Line.width;
}
else
{
y1=Tile.y+(Tile.height/2)+Line.width;
y2=Tile.y+(Tile.height/2)-Line.width;
}
Point point=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection
if (point.x < (Line.x + Line.width) && point.x > Line.x && point.y < (Line.y + Line.height) && point.y > Line.y)//line intersects within line segment
{
//if(point!=null){System.out.println(point.x+","+point.y);}
double distance = Math.sqrt(Math.pow((Tile.x+(Tile.width/2)) - point.x,2) + Math.pow((Tile.y+(Tile.width/2)) - point.y, 2));
if((int)distance<Tile.width/2)
{
//System.out.println("hit");
double normX = ((Tile.x+(Tile.width/2)) - point.x) / distance;
double normY = ((Tile.y+(Tile.height/2)) - point.y) / distance;
Tile.move((point.x)+(int)Math.round(normX*(Tile.width/2))-(Tile.width/2) , (point.y)+(int)Math.round(normY*(Tile.height/2))-(Tile.height/2));text.out="collision detected!";
//System.out.println(point.x+","+point.y);
}
}
//new bullet(this, (int)Math.round(tryX), (int)Math.round(tryY));
}
void rectangleLine(tile Temp)
{
line Line=(line)Temp;
if(new Line2D.Double(Line.x1,Line.y1,Line.x2,Line.y2).intersects(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height)))
{
if (Line.x1 < (Tile.x + Tile.width) && (Line.x1) > Tile.x && Line.y1 < (Tile.y + Tile.height) && Line.y1 > Tile.y)//circle may be hitting one of the end points
{
rectangle rec=new rectangle(Line.x1, Line.y1, 1, 1, this);
rectangleRectangle(rec);
remove(rec);
}
if (Line.x2 < (Tile.x + Tile.width) && (Line.x2) > Tile.x && Line.y2 < (Tile.y + Tile.height) && Line.y2 > Tile.y)//circle may be hitting one of the end points
{
rectangle rec=new rectangle(Line.x2, Line.y2, 1, 1, this);
rectangleRectangle(rec);
remove(rec);
}
if(Line.posSlope)//positive sloped line
{
//first we'll do the top left corner
int x1=Tile.x-Line.height;
int x2=Tile.x+Line.height;
int y1=Tile.y-Line.width;
int y2=Tile.y+Line.width;
Point topPoint=new Point(-99,-99), botPoint=new Point(-99,-99);
double topDistance=0, botDistance=0;
topPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection
topDistance = Math.sqrt(Math.pow(Tile.x - topPoint.x,2) + Math.pow(Tile.y - topPoint.y, 2));
//new let's do the bottom right corner
x1=Tile.x+Tile.width-Line.height;
x2=Tile.x+Tile.width+Line.height;
y1=Tile.y+Tile.height-Line.width;
y2=Tile.y+Tile.height+Line.width;
botPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection
botDistance = Math.sqrt(Math.pow((Tile.x+Tile.width) - botPoint.x,2) + Math.pow((Tile.y+Tile.height) - botPoint.y, 2));
if(topDistance<botDistance)
{
if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(topPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(topPoint))
{
Tile.move(topPoint.x,topPoint.y);text.out="collision detected!";
}
}
else
{
if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(botPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(botPoint))
{
Tile.move(botPoint.x-Tile.width,botPoint.y-Tile.height);text.out="collision detected!";
}
}
}
else//negative sloped lne
{
//first we'll do the top right corner
int x1=Tile.x+Tile.width-Line.height;
int x2=Tile.x+Tile.width+Line.height;
int y1=Tile.y+Line.width;
int y2=Tile.y-Line.width;
Point topPoint=new Point(-99,-99), botPoint=new Point(-99,-99);
double topDistance=0, botDistance=0;
topPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection
topDistance = Math.sqrt(Math.pow(Tile.x + Tile.width - topPoint.x,2) + Math.pow(Tile.y - topPoint.y, 2));
//new let's do the bottom left corner
x1=Tile.x-Line.height;
x2=Tile.x+Line.height;
y1=Tile.y+Tile.height+Line.width;
y2=Tile.y+Tile.height-Line.width;
botPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection
botDistance = Math.sqrt(Math.pow(Tile.x - botPoint.x,2) + Math.pow((Tile.y+Tile.height) - botPoint.y, 2));
if(topDistance<botDistance)
{
if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(topPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(topPoint))
{
Tile.move(topPoint.x-Tile.width,topPoint.y);text.out="collision detected!";
}
}
else
{
if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(botPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(botPoint))
{
Tile.move(botPoint.x,botPoint.y-Tile.height);text.out="collision detected!";
}
}
}
}
}
public Point intersection(double x1, double y1, double x2, double y2,double x3, double y3, double x4, double y4)//I didn't write this. got it from http://www.ahristov.com/tutorial/geometry-games/intersection-lines.html (I altered it)
{
double d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
double xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d;
double yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d;
int x=(int)Math.round(xi);
int y=(int)Math.round(yi);
return new Point(x, y);
}
//***************************************************************************************
public static void main(String[] args)
{
final collision Collision=new collision();
Collision.run();
}//end main
}//end class
Create a simple 10 second countdown
_x000D_
_x000D_
var seconds_inputs = document.getElementsByClassName('deal_left_seconds');
var total_timers = seconds_inputs.length;
for ( var i = 0; i < total_timers; i++){
var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
var cal_seconds = seconds_inputs[i].getAttribute('value');
eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');
eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');
}
function timer() {
for ( var i = 0; i < total_timers; i++) {
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);
var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);
document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);
document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);
document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);
if (eval('seconds_'+ seconds_prod_id) == 0) {
clearInterval(countdownTimer);
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);
} else {
var value = eval('seconds_'+seconds_prod_id);
value--;
eval('seconds_' + seconds_prod_id + '= ' + value + ';');
}
}
}
var countdownTimer = setInterval('timer()', 1000);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="deal_left_seconds" data-value="1" value="10">
<div class="box-wrapper">
<div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>
</div>
<div class="box-wrapper">
<div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>
</div>
<div class="box-wrapper">
<div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>
</div>
<div class="box-wrapper hidden-md">
<div class="seconds box"> <span class="key" id="deal_sec_1">0p0</span> <span class="value">SEC</span> </div>
</div>
_x000D_
_x000D_
_x000D_
Is there a function to split a string in PL/SQL?
You could use a combination of SUBSTR and INSTR as follows :
Example string : field = 'DE124028#@$1048708#@$000#@$536967136#@$'
The seperator being #@$.
To get the '1048708' for example :
If the field is of fixed length ( 7 here ) :
substr(field,instr(field,'#@$',1,1)+3,7)
If the field is of variable length :
substr(field,instr(field,'#@$',1,1)+3,instr(field,'#@$',1,2) - (instr(field,'#@$',1,1)+3))
You should probably look into SUBSTR and INSTR functions for more flexibility.
Remove an item from a dictionary when its key is unknown
Be aware that you're currently testing for object identity (is
only returns True
if both operands are represented by the same object in memory - this is not always the case with two object that compare equal with ==
). If you are doing this on purpose, then you could rewrite your code as
some_dict = {key: value for key, value in some_dict.items()
if value is not value_to_remove}
But this may not do what you want:
>>> some_dict = {1: "Hello", 2: "Goodbye", 3: "You say yes", 4: "I say no"}
>>> value_to_remove = "You say yes"
>>> some_dict = {key: value for key, value in some_dict.items() if value is not value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 3: 'You say yes', 4: 'I say no'}
>>> some_dict = {key: value for key, value in some_dict.items() if value != value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 4: 'I say no'}
So you probably want !=
instead of is not
.
Postgresql - select something where date = "01/01/11"
With PostgreSQL there are a number of date/time functions available, see here.
In your example, you could use:
SELECT * FROM myTable WHERE date_trunc('day', dt) = 'YYYY-MM-DD';
If you are running this query regularly, it is possible to create an index using the date_trunc
function as well:
CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt) );
One advantage of this is there is some more flexibility with timezones if required, for example:
CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt at time zone 'Australia/Sydney') );
SELECT * FROM myTable WHERE date_trunc('day', dt at time zone 'Australia/Sydney') = 'YYYY-MM-DD';
How to insert DECIMAL into MySQL database
I noticed something else about your coding.... look
INSERT INTO reports_services (id,title,description,cost) VALUES (0, 'test title', 'test decription ', '3.80')
in your "CREATE TABLE" code you have the id set to "AUTO_INCREMENT" which means it's automatically generating a result for that field.... but in your above code you include it as one of the insertions and in the "VALUES" you have a 0 there... idk if that's your way of telling us you left it blank because it's set to AUTO_INC. or if that's the actual code you have... if it's the code you have not only should you not be trying to send data to a field set to generate it automatically, but the RIGHT WAY to do it WRONG would be
'0',
you put
0,
lol....so that might be causing some of the problem... I also just noticed in the code after "test description" you have a space before the '.... that might be throwing something off too.... idk.. I hope this helps n maybe resolves some other problem you might be pulling your hair out about now.... speaking of which.... I need to figure out my problem before I tear all my hair out..... good luck.. :)
UPDATE.....
I almost forgot... if you have the 0 there to show that it's blank... you could be entering "test title" as the id and "test description" as the title then "3.whatever cents" for the description leaving "cost" empty...... which could be why it maxed out because if I'm not mistaking you have it set to NOT NULL.... and you left it null... so it forced something... maybe.... lol
How do I compare two string variables in an 'if' statement in Bash?
For a version with pure Bash and without test
, but really ugly, try:
if ( exit "${s1/*$s2*/0}" )2>/dev/null
then
echo match
fi
Explanation: In ( )
an extra subshell is opened. It exits with 0 if there was a match, and it tries to exit with $s1 if there was no match which raises an error (ugly). This error is directed to /dev/null
.
How to disable postback on an asp Button (System.Web.UI.WebControls.Button)
you can use the code:
_x000D_
_x000D_
<asp:Button ID="Button2" runat="server"_x000D_
Text="Pulsa"_x000D_
OnClientClick="this.disabled=true"_x000D_
UseSubmitBehavior="False"/>
_x000D_
_x000D_
_x000D_
if nee submit
_x000D_
_x000D_
..._x000D_
<form id="form1" runat="server" onsubmit="deshabilita()">_x000D_
..._x000D_
<script type="text/javascript">_x000D_
function deshabilita()_x000D_
{_x000D_
var btn = "<%= Button1.ClientID %>";_x000D_
if (confirm("Confirme postback"))_x000D_
{_x000D_
document.getElementById(btn).disabled = true;_x000D_
return true;_x000D_
}_x000D_
return false;_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_
Can't install APK from browser downloads
It shouldn't be HTTP headers if the file has been downloaded successfully and it's the same file that you can open from OI.
A shot in the dark, but could it be that you are not allowing installation from unknown sources, and that OI is somehow bypassing that?
Settings > Applications > Unknown sources...
Edit
Answer extracted from comments which worked. Ensure the Content-Type is set to application/vnd.android.package-archive
What's the difference between Apache's Mesos and Google's Kubernetes
Kubernetes is an open source project that brings 'Google style' cluster management capabilities to the world of virtual machines, or 'on the metal' scenarios. It works very well with modern operating system environments (like CoreOS or Red Hat Atomic) that offer up lightweight computing 'nodes' that are managed for you. It is written in Golang and is lightweight, modular, portable and extensible. We (the Kubernetes team) are working with a number of different technology companies (including Mesosphere who curate the Mesos open source project) to establish Kubernetes as the standard way to interact with computing clusters. The idea is to reproduce the patterns that we see people needing to build cluster applications based on our experience at Google. Some of these concepts include:
- pods — a way to group containers together
- replication controllers — a way to handle the lifecycle of containers
- labels — a way to find and query containers, and
- services — a set of containers performing a common function.
So with Kubernetes alone you will have something that is simple, easy to get up-and-running, portable and extensible that adds 'cluster' as a noun to the things that you manage in the lightest weight manner possible. Run an application on a cluster, and stop worrying about an individual machine. In this case, cluster is a flexible resource just like a VM. It is a logical computing unit. Turn it up, use it, resize it, turn it down quickly and easily.
With Mesos, there is a fair amount of overlap in terms of the basic vision, but the products are at quite different points in their lifecycle and have different sweet spots. Mesos is a distributed systems kernel that stitches together a lot of different machines into a logical computer. It was born for a world where you own a lot of physical resources to create a big static computing cluster. The great thing about it is that lots of modern scalable data processing application run well on Mesos (Hadoop, Kafka, Spark) and it is nice because you can run them all on the same basic resource pool, along with your new age container packaged apps. It is somewhat more heavy weight than the Kubernetes project, but is getting easier and easier to manage thanks to the work of folks like Mesosphere.
Now what gets really interesting is that Mesos is currently being adapted to add a lot of the Kubernetes concepts and to support the Kubernetes API. So it will be a gateway to getting more capabilities for your Kubernetes app (high availability master, more advanced scheduling semantics, ability to scale to a very large number of nodes) if you need them, and is well suited to run production workloads (Kubernetes is still in an alpha state).
When asked, I tend to say:
Kubernetes is a great place to start if you are new to the clustering world; it is the quickest, easiest and lightest way to kick the tires and start experimenting with cluster oriented development. It offers a very high level of portability since it is being supported by a lot of different providers (Microsoft, IBM, Red Hat, CoreOs, MesoSphere, VMWare, etc).
If you have existing workloads (Hadoop, Spark, Kafka, etc), Mesos gives you a framework that let's you interleave those workloads with each other, and mix in a some of the new stuff including Kubernetes apps.
Mesos gives you an escape valve if you need capabilities that are not yet implemented by the community in the Kubernetes framework.
Deleting a SQL row ignoring all foreign keys and constraints
Yes, simply run
DELETE FROM myTable where myTable.ID = 6850
AND LET ENGINE VERIFY THE CONSTRAINTS.
If you're trying to be 'clever' and disable constraints, you'll pay a huge price: enabling back the constraints has to verify every row instead of the one you just deleted. There are internal flags SQL keeps to know that a constraint is 'trusted' or not. You're 'optimization' would result in either changing these flags to 'false' (meaning SQL no longer trusts the constraints) or it has to re-verify them from scratch.
See Guidelines for Disabling Indexes and Constraints and Non-trusted constraints and performance.
Unless you did some solid measurements that demonstrated that the constraint verification of the DELETE operation are a performance bottleneck, let the engine do its work.
How to add image to canvas
In my case, I was mistaken the function parameters, which are:
context.drawImage(image, left, top);
context.drawImage(image, left, top, width, height);
If you expect them to be
context.drawImage(image, width, height);
you will place the image just outside the canvas with the same effects as described in the question.
Why is null an object and what's the difference between null and undefined?
One way to make sense of null and undefined is to understand where each occurs.
Expect a null return value in the following situations:
Methods that query the DOM
console.log(window.document.getElementById("nonExistentElement"));
//Prints: null
JSON responses received from an Ajax request
{
name: "Bob",
address: null
}
var proto = Object.getPrototypeOf(Object.getPrototypeOf({}));
// But this returns undefined:
Object.getOwnPropertyDescriptor({}, "a");
All other cases of non-existence are denoted by undefined (as noted by @Axel). Each of the following prints "undefined":
var uninitalised;
console.log(uninitalised);
var obj = {};
console.log(obj.nonExistent);
function missingParam(missing){
console.log(missing);
}
missingParam();
var arr = [];
console.log(arr.pop());
Of course if you decide to write var unitialised = null; or return null from a method yourself then you have null occurring in other situations. But that should be pretty obvious.
A third case is when you want to access a variable but you don't even know if it has been declared. For that case use typeof to avoid a reference error:
if(typeof unknown !== "undefined"){
//use unknown
}
In summary check for null when you are manipulating the DOM, dealing with Ajax, or using certain ECMAScript 5 features. For all other cases it is safe to check for undefined with strict equality:
if(value === undefined){
// stuff
}
Iterating Over Dictionary Key Values Corresponding to List in Python
You have several options for iterating over a dictionary.
If you iterate over the dictionary itself (for team in league
), you will be iterating over the keys of the dictionary. When looping with a for loop, the behavior will be the same whether you loop over the dict (league
) itself, or league.keys()
:
for team in league.keys():
runs_scored, runs_allowed = map(float, league[team])
You can also iterate over both the keys and the values at once by iterating over league.items()
:
for team, runs in league.items():
runs_scored, runs_allowed = map(float, runs)
You can even perform your tuple unpacking while iterating:
for team, (runs_scored, runs_allowed) in league.items():
runs_scored = float(runs_scored)
runs_allowed = float(runs_allowed)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)
We struck this error when running manage.py migrate
in Django with localized fixtures.
Our source contained the # -*- coding: utf-8 -*-
declaration, MySQL was correctly configured for utf8 and Ubuntu had the appropriate language pack and values in /etc/default/locale
.
The issue was simply that the Django container (we use docker) was missing the LANG
env var.
Setting LANG
to en_US.UTF-8
and restarting the container before re-running migrations fixed the problem.
How do I create a dynamic key to be added to a JavaScript object variable
Square brackets:
jsObj['key' + i] = 'example' + 1;
In JavaScript, all arrays are objects, but not all objects are arrays. The primary difference (and one that's pretty hard to mimic with straight JavaScript and plain objects) is that array instances maintain the length
property so that it reflects one plus the numeric value of the property whose name is numeric and whose value, when converted to a number, is the largest of all such properties. That sounds really weird, but it just means that given an array instance, the properties with names like "0"
, "5"
, "207"
, and so on, are all treated specially in that their existence determines the value of length
. And, on top of that, the value of length
can be set to remove such properties. Setting the length
of an array to 0
effectively removes all properties whose names look like whole numbers.
OK, so that's what makes an array special. All of that, however, has nothing at all to do with how the JavaScript [ ]
operator works. That operator is an object property access mechanism which works on any object. It's important to note in that regard that numeric array property names are not special as far as simple property access goes. They're just strings that happen to look like numbers, but JavaScript object property names can be any sort of string you like.
Thus, the way the [ ]
operator works in a for
loop iterating through an array:
for (var i = 0; i < myArray.length; ++i) {
var value = myArray[i]; // property access
// ...
}
is really no different from the way [ ]
works when accessing a property whose name is some computed string:
var value = jsObj["key" + i];
The [ ]
operator there is doing precisely the same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.
When setting property values using [ ]
, the story is the same except for the special behavior around maintaining the length
property. If you set a property with a numeric key on an array instance:
myArray[200] = 5;
then (assuming that "200" is the biggest numeric property name) the length
property will be updated to 201
as a side-effect of the property assignment. If the same thing is done to a plain object, however:
myObj[200] = 5;
there's no such side-effect. The property called "200" of both the array and the object will be set to the value 5
in otherwise the exact same way.
One might think that because that length
behavior is kind-of handy, you might as well make all objects instances of the Array constructor instead of plain objects. There's nothing directly wrong about that (though it can be confusing, especially for people familiar with some other languages, for some properties to be included in the length
but not others). However, if you're working with JSON serialization (a fairly common thing), understand that array instances are serialized to JSON in a way that only involves the numerically-named properties. Other properties added to the array will never appear in the serialized JSON form. So for example:
var obj = [];
obj[0] = "hello world";
obj["something"] = 5000;
var objJSON = JSON.stringify(obj);
the value of "objJSON" will be a string containing just ["hello world"]
; the "something" property will be lost.
ES2015:
If you're able to use ES6 JavaScript features, you can use Computed Property Names to handle this very easily:
var key = 'DYNAMIC_KEY',
obj = {
[key]: 'ES6!'
};
console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' }
HTTP get with headers using RestTemplate
The RestTemplate getForObject()
method does not support setting headers. The solution is to use the exchange()
method.
So instead of restTemplate.getForObject(url, String.class, param)
(which has no headers), use
HttpHeaders headers = new HttpHeaders();
headers.set("Header", "value");
headers.set("Other-Header", "othervalue");
...
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<String> response = restTemplate.exchange(
url, HttpMethod.GET, entity, String.class, param);
Finally, use response.getBody()
to get your result.
This question is similar to this question.
How to run Unix shell script from Java code?
It is possible, just exec it as any other program. Just make sure your script has the proper #! (she-bang) line as the first line of the script, and make sure there are execute permissions on the file.
For example, if it is a bash script put #!/bin/bash at the top of the script, also chmod +x .
Also as for if it's good practice, no it's not, especially for Java, but if it saves you a lot of time porting a large script over, and you're not getting paid extra to do it ;) save your time, exec the script, and put the porting to Java on your long-term todo list.
JSON.stringify output to div in pretty print way
Consider your REST API returns:
{"Intent":{"Command":"search","SubIntent":null}}
Then you can do the following to print it in a nice format:
<pre id="ciResponseText">Output will de displayed here.</pre>
var ciResponseText = document.getElementById('ciResponseText');
var obj = JSON.parse(http.response);
ciResponseText.innerHTML = JSON.stringify(obj, undefined, 2);
What is String pool in Java?
Let's start with a quote from the virtual machine spec:
Loading of a class or interface that contains a String literal may create a new String object (§2.4.8) to represent that literal. This may not occur if the a String object has already been created to represent a previous occurrence of that literal, or if the String.intern method has been invoked on a String object representing the same string as the literal.
This may not occur - This is a hint, that there's something special about String
objects. Usually, invoking a constructor will always create a new instance of the class. This is not the case with Strings, especially when String objects are 'created' with literals. Those Strings are stored in a global store (pool) - or at least the references are kept in a pool, and whenever a new instance of an already known Strings is needed, the vm returns a reference to the object from the pool. In pseudo code, it may go like that:
1: a := "one"
--> if(pool[hash("one")] == null) // true
pool[hash("one") --> "one"]
return pool[hash("one")]
2: b := "one"
--> if(pool[hash("one")] == null) // false, "one" already in pool
pool[hash("one") --> "one"]
return pool[hash("one")]
So in this case, variables a
and b
hold references to the same object. IN this case, we have (a == b) && (a.equals(b)) == true
.
This is not the case if we use the constructor:
1: a := "one"
2: b := new String("one")
Again, "one"
is created on the pool but then we create a new instance from the same literal, and in this case, it leads to (a == b) && (a.equals(b)) == false
So why do we have a String pool? Strings and especially String literals are widely used in typical Java code. And they are immutable. And being immutable allowed to cache String to save memory and increase performance (less effort for creation, less garbage to be collected).
As programmers we don't have to care much about the String pool, as long as we keep in mind:
(a == b) && (a.equals(b))
may be true
or false
(always use equals
to compare Strings)
- Don't use reflection to change the backing
char[]
of a String (as you don't know who is actualling using that String)
How to move screen without moving cursor in Vim?
I wrote a plugin which enables me to navigate the file without moving the cursor position. It's based on folding the lines between your position and your target position and then jumping over the fold, or abort it and don't move at all.
It's also easy to fast-switch between the cursor on the first line, the last line and cursor in the middle by just clicking j, k or l when you are in the mode of the plugin.
I guess it would be a good fit here.
.htaccess not working on localhost with XAMPP
for xampp vm on MacOS capitan, high sierra, MacOS Mojave (10.12+), you can follow these
1. mount /opt/lampp
2. explore the folder
3. open terminal from the folder
4. cd to `htdocs`>yourapp (ex: techaz.co)
5. vim .htaccess
6. paste your .htaccess content (that is suggested on options-permalink.php)
Oracle Error ORA-06512
ORA-06512 is part of the error stack. It gives us the line number where the exception occurred, but not the cause of the exception. That is usually indicated in the rest of the stack (which you have still not posted).
In a comment you said
"still, the error comes when pNum is not between 12 and 14; when pNum
is between 12 and 14 it does not fail"
Well, your code does this:
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
That is, it raises an exception when pNum is not between 12 and 14. So does the rest of the error stack include this line?
ORA-06510: PL/SQL: unhandled user-defined exception
If so, all you need to do is add an exception block to handle the error. Perhaps:
PROCEDURE PX(pNum INT,pIdM INT,pCv VARCHAR2,pSup FLOAT)
AS
vSOME_EX EXCEPTION;
BEGIN
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
ELSE
EXECUTE IMMEDIATE 'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('||pCv||', '||pSup||', '||pIdM||')';
END IF;
exception
when vsome_ex then
raise_application_error(-20000
, 'This is not a valid table: M'||pNum||'GR');
END PX;
The documentation covers handling PL/SQL exceptions in depth.
Making RGB color in Xcode
Objective-C
You have to give the values between 0 and 1.0. So divide the RGB values by 255.
myLabel.textColor= [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1] ;
Update:
You can also use this macro
#define Rgb2UIColor(r, g, b) [UIColor colorWithRed:((r) / 255.0) green:((g) / 255.0) blue:((b) / 255.0) alpha:1.0]
and you can call in any of your class like this
myLabel.textColor = Rgb2UIColor(160, 97, 5);
Swift
This is the normal color synax
myLabel.textColor = UIColor(red: (160/255.0), green: (97/255.0), blue: (5/255.0), alpha: 1.0)
//The values should be between 0 to 1
Swift is not much friendly with macros
Complex macros are used in C and Objective-C but have no counterpart
in Swift. Complex macros are macros that do not define constants,
including parenthesized, function-like macros. You use complex macros
in C and Objective-C to avoid type-checking constraints or to avoid
retyping large amounts of boilerplate code. However, macros can make
debugging and refactoring difficult. In Swift, you can use functions
and generics to achieve the same results without any compromises.
Therefore, the complex macros that are in C and Objective-C source
files are not made available to your Swift code.
So we use extension for this
extension UIColor {
convenience init(_ r: Double,_ g: Double,_ b: Double,_ a: Double) {
self.init(red: r/255, green: g/255, blue: b/255, alpha: a)
}
}
You can use it like
myLabel.textColor = UIColor(160.0, 97.0, 5.0, 1.0)
Rails: Check output of path helper from console
Remember if your route is name-spaced, Like:
product GET /products/:id(.:format) spree/products#show
Then try :
helper.link_to("test", app.spree.product_path(Spree::Product.first), method: :get)
output
Spree::Product Load (0.4ms) SELECT "spree_products".* FROM "spree_products" WHERE "spree_products"."deleted_at" IS NULL ORDER BY "spree_products"."id" ASC LIMIT 1
=> "<a data-method=\"get\" href=\"/products/this-is-the-title\">test</a>"
How to calculate age in T-SQL with years, months, and days
CREATE FUNCTION DBO.GET_AGE
(
@DATE AS DATETIME
)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @YEAR AS VARCHAR(50) = ''
DECLARE @MONTH AS VARCHAR(50) = ''
DECLARE @DAYS AS VARCHAR(50) = ''
DECLARE @RESULT AS VARCHAR(MAX) = ''
SET @YEAR = CONVERT(VARCHAR,(SELECT DATEDIFF(MONTH,CASE WHEN DAY(@DATE) > DAY(GETDATE()) THEN DATEADD(MONTH,1,@DATE) ELSE @DATE END,GETDATE()) / 12 ))
SET @MONTH = CONVERT(VARCHAR,(SELECT DATEDIFF(MONTH,CASE WHEN DAY(@DATE) > DAY(GETDATE()) THEN DATEADD(MONTH,1,@DATE) ELSE @DATE END,GETDATE()) % 12 ))
SET @DAYS = DATEDIFF(DD,DATEADD(MM,CONVERT(INT,CONVERT(INT,@YEAR)*12 + CONVERT(INT,@MONTH)),@DATE),GETDATE())
SET @RESULT = (RIGHT('00' + @YEAR, 2) + ' YEARS ' + RIGHT('00' + @MONTH, 2) + ' MONTHS ' + RIGHT('00' + @DAYS, 2) + ' DAYS')
RETURN @RESULT
END
SELECT DBO.GET_AGE('04/12/1986')
Why do I keep getting 'SVN: Working Copy XXXX locked; try performing 'cleanup'?
Make sure you exactly cleanup what the console says. For example if a subfolder (a package) is locked:
svn: E155004: Commit failed (details follow):
svn: E155004: Working copy 'C:\Users\laura\workspace\tparser\src\de\test\order' locked
svn: E155004: 'C:\Users\laura\workspace\tparser\src\de\test\order' is already locked.
cleanup C:/Users/liparulol/workspace/tparser/src/de/mc/etn/parsers/order
Then you need to cleanup the specified folder and not the whole project. If you are in eclipse right click on the package, not on the project folder and execute the clean up.
Data structure for maintaining tabular data in memory?
I personally wrote a lib for pretty much that quite recently, it is called BD_XML
as its most fundamental reason of existence is to serve as a way to send data back and forth between XML files and SQL databases.
It is written in Spanish (if that matters in a programming language) but it is very simple.
from BD_XML import Tabla
It defines an object called Tabla (Table), it can be created with a name for identification an a pre-created connection object of a pep-246 compatible database interface.
Table = Tabla('Animals')
Then you need to add columns with the agregar_columna
(add_column) method, with can take various key word arguments:
campo
(field): the name of the field
tipo
(type): the type of data stored, can be a things like 'varchar' and 'double' or name of python objects if you aren't interested in exporting to a data base latter.
defecto
(default): set a default value for the column if there is none when you add a row
there are other 3 but are only there for database tings and not actually functional
like:
Table.agregar_columna(campo='Name', tipo='str')
Table.agregar_columna(campo='Year', tipo='date')
#declaring it date, time, datetime or timestamp is important for being able to store it as a time object and not only as a number, But you can always put it as a int if you don't care for dates
Table.agregar_columna(campo='Priority', tipo='int')
Then you add the rows with the += operator (or + if you want to create a copy with an extra row)
Table += ('Cat', date(1998,1,1), 1)
Table += {'Year':date(1998,1,1), 'Priority':2, Name:'Fish'}
#…
#The condition for adding is that is a container accessible with either the column name or the position of the column in the table
Then you can generate XML and write it to a file with exportar_XML
(export_XML) and escribir_XML
(write_XML):
file = os.path.abspath(os.path.join(os.path.dirname(__file__), 'Animals.xml'))
Table.exportar_xml()
Table.escribir_xml(file)
And then import it back with importar_XML
(import_XML) with the file name and indication that you are using a file and not an string literal:
Table.importar_xml(file, tipo='archivo')
#archivo means file
Advanced
This are ways you can use a Tabla object in a SQL manner.
#UPDATE <Table> SET Name = CONCAT(Name,' ',Priority), Priority = NULL WHERE id = 2
for row in Table:
if row['id'] == 2:
row['Name'] += ' ' + row['Priority']
row['Priority'] = None
print(Table)
#DELETE FROM <Table> WHERE MOD(id,2) = 0 LIMIT 1
n = 0
nmax = 1
for row in Table:
if row['id'] % 2 == 0:
del Table[row]
n += 1
if n >= nmax: break
print(Table)
this examples assume a column named 'id'
but can be replaced width row.pos for your example.
if row.pos == 2:
The file can be download from:
https://bitbucket.org/WolfangT/librerias
Declare and Initialize String Array in VBA
In the specific case of a String array you could initialize the array using the Split Function as it returns a String array rather than a Variant array:
Dim arrWsNames() As String
arrWsNames = Split("Value1,Value2,Value3", ",")
This allows you to avoid using the Variant data type and preserve the desired type for arrWsNames.
Change image source in code behind - Wpf
You are all wrong!
Why? Because all you need is this code to work:
(image View) / C# Img is : your Image box
Keep this as is, without change ("ms-appx:///) this is code not your app name
Images is your folder in your project you can change it.
dog.png is your file in your folder, as well as i do my folder 'Images' and file 'dog.png'
So the uri is :"ms-appx:///Images/dog.png"
and my code :
private void Button_Click(object sender, RoutedEventArgs e)
{
img.Source = new BitmapImage(new Uri("ms-appx:///Images/dog.png"));
}
Why use Select Top 100 Percent?
The error says it all...
Msg 1033, Level 15, State 1, Procedure TestView, Line 5 The ORDER BY
clause is invalid in views, inline functions, derived tables,
subqueries, and common table expressions, unless TOP, OFFSET or FOR
XML is also specified.
Don't use TOP 100 PERCENT
, use TOP n
, where N is a number
The TOP 100 PERCENT (for reasons I don't know) is ignored by SQL Server VIEW (post 2012 versions), but I think MS kept it for syntax reasons. TOP n is better and will work inside a view and sort it the way you want when a view is used initially, but be careful.
Change the bullet color of list
You have to use image
.listStyle {
list-style: none;
background: url(bullet.jpg) no-repeat left center;
padding-left: 40px;
}
How to compare data between two table in different databases using Sql Server 2008?
In order to compare two databases, I've written the procedures bellow.
If you want to compare two tables you can use procedure 'CompareTables'. Example :
EXEC master.dbo.CompareTables 'DB1', 'dbo', 'table1', 'DB2', 'dbo', 'table2'
If you want to compare two databases, use the procedure 'CompareDatabases'. Example :
EXEC master.dbo.CompareDatabases 'DB1', 'DB2'
Note : - I tried to make the procedures secure, but anyway, those procedures are only for testing and debugging.
- If you want a complete solution for comparison use third party like (Visual Studio, ...)
USE [master]
GO
create proc [dbo].[CompareDatabases]
@FirstDatabaseName nvarchar(50),
@SecondDatabaseName nvarchar(50)
as
begin
-- Check that databases exist
if not exists(SELECT name FROM sys.databases WHERE name=@FirstDatabaseName)
return 0
if not exists(SELECT name FROM sys.databases WHERE name=@SecondDatabaseName)
return 0
declare @result table (TABLE_NAME nvarchar(256))
SET NOCOUNT ON
insert into @result EXEC('(Select distinct TABLE_NAME from ' + @FirstDatabaseName + '.INFORMATION_SCHEMA.COLUMNS '
+'Where TABLE_SCHEMA=''dbo'')'
+ 'intersect'
+ '(Select distinct TABLE_NAME from ' + @SecondDatabaseName + '.INFORMATION_SCHEMA.COLUMNS '
+'Where TABLE_SCHEMA=''dbo'')')
DECLARE @TABLE_NAME nvarchar(256)
DECLARE curseur CURSOR FOR
SELECT TABLE_NAME FROM @result
OPEN curseur
FETCH curseur INTO @TABLE_NAME
WHILE @@FETCH_STATUS = 0
BEGIN
print 'TABLE : ' + @TABLE_NAME
EXEC master.dbo.CompareTables @FirstDatabaseName, 'dbo', @TABLE_NAME, @SecondDatabaseName, 'dbo', @TABLE_NAME
FETCH curseur INTO @TABLE_NAME
END
CLOSE curseur
DEALLOCATE curseur
SET NOCOUNT OFF
end
GO
.
USE [master]
GO
CREATE PROC [dbo].[CompareTables]
@FirstTABLE_CATALOG nvarchar(256),
@FirstTABLE_SCHEMA nvarchar(256),
@FirstTABLE_NAME nvarchar(256),
@SecondTABLE_CATALOG nvarchar(256),
@SecondTABLE_SCHEMA nvarchar(256),
@SecondTABLE_NAME nvarchar(256)
AS
BEGIN
-- Verify if first table exist
DECLARE @table1 nvarchar(256) = @FirstTABLE_CATALOG + '.' + @FirstTABLE_SCHEMA + '.' + @FirstTABLE_NAME
DECLARE @return_status int
EXEC @return_status = master.dbo.TableExist @FirstTABLE_CATALOG, @FirstTABLE_SCHEMA, @FirstTABLE_NAME
IF @return_status = 0
BEGIN
PRINT @table1 + ' : Table Not FOUND'
RETURN 0
END
-- Verify if second table exist
DECLARE @table2 nvarchar(256) = @SecondTABLE_CATALOG + '.' + @SecondTABLE_SCHEMA + '.' + @SecondTABLE_NAME
EXEC @return_status = master.dbo.TableExist @SecondTABLE_CATALOG, @SecondTABLE_SCHEMA, @SecondTABLE_NAME
IF @return_status = 0
BEGIN
PRINT @table2 + ' : Table Not FOUND'
RETURN 0
END
-- Compare the two tables
DECLARE @sql AS NVARCHAR(MAX)
SELECT @sql = '('
+ '(SELECT ''' + @table1 + ''' as _Table, * FROM ' + @FirstTABLE_CATALOG + '.' + @FirstTABLE_SCHEMA + '.' + @FirstTABLE_NAME + ')'
+ 'EXCEPT'
+ '(SELECT ''' + @table1 + ''' as _Table, * FROM ' + @SecondTABLE_CATALOG + '.' + @SecondTABLE_SCHEMA + '.' + @SecondTABLE_NAME + ')'
+ ')'
+ 'UNION'
+ '('
+ '(SELECT ''' + @table2 + ''' as _Table, * FROM ' + @SecondTABLE_CATALOG + '.' + @SecondTABLE_SCHEMA + '.' + @SecondTABLE_NAME + ')'
+ 'EXCEPT'
+ '(SELECT ''' + @table2 + ''' as _Table, * FROM ' + @FirstTABLE_CATALOG + '.' + @FirstTABLE_SCHEMA + '.' + @FirstTABLE_NAME + ')'
+ ')'
DECLARE @wrapper AS NVARCHAR(MAX) = 'if exists (' + @sql + ')' + char(10) + ' (' + @sql + ')ORDER BY 2'
Exec(@wrapper)
END
GO
.
USE [master]
GO
CREATE PROC [dbo].[TableExist]
@TABLE_CATALOG nvarchar(256),
@TABLE_SCHEMA nvarchar(256),
@TABLE_NAME nvarchar(256)
AS
BEGIN
IF NOT EXISTS(SELECT name FROM sys.databases WHERE name=@TABLE_CATALOG)
RETURN 0
declare @result table (TABLE_SCHEMA nvarchar(256), TABLE_NAME nvarchar(256))
SET NOCOUNT ON
insert into @result EXEC('Select TABLE_SCHEMA, TABLE_NAME from ' + @TABLE_CATALOG + '.INFORMATION_SCHEMA.COLUMNS')
SET NOCOUNT OFF
IF EXISTS(SELECT TABLE_SCHEMA, TABLE_NAME FROM @result
WHERE TABLE_SCHEMA=@TABLE_SCHEMA AND TABLE_NAME=@TABLE_NAME)
RETURN 1
RETURN 0
END
GO
How to print number with commas as thousands separators?
I'm surprised that no one has mentioned that you can do this with f-strings in Python 3.6+ as easy as this:
>>> num = 10000000
>>> print(f"{num:,}")
10,000,000
... where the part after the colon is the format specifier. The comma is the separator character you want, so f"{num:_}"
uses underscores instead of a comma.
This is equivalent of using format(num, ",")
for older versions of python 3.
Link vs compile vs controller
Also, a good reason to use a controller vs. link function (since they both have access to the scope, element, and attrs) is because you can pass in any available service or dependency into a controller (and in any order), whereas you cannot do that with the link function. Notice the different signatures:
controller: function($scope, $exceptionHandler, $attr, $element, $parse, $myOtherService, someCrazyDependency) {...
vs.
link: function(scope, element, attrs) {... //no services allowed
How to Validate Google reCaptcha on Form Submit
You can verify the response in 3 ways as per the Google reCAPTCHA documentation:
g-recaptcha-response
: Once user checks the checkbox (I am not a robot), a field with id g-recaptcha-response
gets populated in your HTML.
You can now use the value of this field to know if the user is a bot or not, using the below mentioed lines:-
var captchResponse = $('#g-recaptcha-response').val();
if(captchResponse.length == 0 )
//user has not yet checked the 'I am not a robot' checkbox
else
//user is a verified human and you are good to submit your form now
Before you are about to submit your form, you can make a call as follows:-
var isCaptchaValidated = false;
var response = grecaptcha.getResponse();
if(response.length == 0) {
isCaptchaValidated = false;
toast('Please verify that you are a Human.');
} else {
isCaptchaValidated = true;
}
if (isCaptchaValidated ) {
//you can now submit your form
}
You can display your reCAPTCHA as follows:-
<div class="col s12 g-recaptcha" data-sitekey="YOUR_PRIVATE_KEY" data-callback='doSomething'></div>
And then define the function in your JavaScript, which can also be used to submit your form.
function doSomething() { alert(1); }
Now, once the checkbox (I am not a robot) is checked, you will get a callback to the defined callback, which is doSomething
in your case.
How to Cast Objects in PHP
a better aproach:
class Animal
{
private $_name = null;
public function __construct($name = null)
{
$this->_name = $name;
}
/**
* casts object
* @param Animal $to
* @return Animal
*/
public function cast($to)
{
if ($to instanceof Animal) {
$to->_name = $this->_name;
} else {
throw(new Exception('cant cast ' . get_class($this) . ' to ' . get_class($to)));
return $to;
}
public function getName()
{
return $this->_name;
}
}
class Cat extends Animal
{
private $_preferedKindOfFish = null;
public function __construct($name = null, $preferedKindOfFish = null)
{
parent::__construct($name);
$this->_preferedKindOfFish = $preferedKindOfFish;
}
/**
* casts object
* @param Animal $to
* @return Animal
*/
public function cast($to)
{
parent::cast($to);
if ($to instanceof Cat) {
$to->_preferedKindOfFish = $this->_preferedKindOfFish;
}
return $to;
}
public function getPreferedKindOfFish()
{
return $this->_preferedKindOfFish;
}
}
class Dog extends Animal
{
private $_preferedKindOfCat = null;
public function __construct($name = null, $preferedKindOfCat = null)
{
parent::__construct($name);
$this->_preferedKindOfCat = $preferedKindOfCat;
}
/**
* casts object
* @param Animal $to
* @return Animal
*/
public function cast($to)
{
parent::cast($to);
if ($to instanceof Dog) {
$to->_preferedKindOfCat = $this->_preferedKindOfCat;
}
return $to;
}
public function getPreferedKindOfCat()
{
return $this->_preferedKindOfCat;
}
}
$dogs = array(
new Dog('snoopy', 'vegetarian'),
new Dog('coyote', 'any'),
);
foreach ($dogs as $dog) {
$cat = $dog->cast(new Cat());
echo get_class($cat) . ' - ' . $cat->getName() . "\n";
}
Reducing the gap between a bullet and text in a list item
Reduce text-indent
to a negative number to decrease the space between the list item's bullet and its text.
li {
text-indent: -4px;
}
You can also use margin-left
to adjust any space between the list-item's bullet and the edge of its surrounding element.
li {
margin-left: 24px;
}
Both text-indent
and padding-left
can add space between the bullet and text, but only text-indent
can reduce space to negative.
li { padding-left: -4px; } /* Doesn't work. */
Java OCR implementation
There are a variety of OCR libraries out there. However, my experience is that the major commercial implementations, ABBYY, Omnipage, and ReadIris, far outdo the open-source or other minor implementations. These commercial libraries are not primarily designed to work with Java, though of course it is possible.
Of course, if your interest is to learn the code, the open-source implementations will do the trick.
how to set JAVA_OPTS for Tomcat in Windows?
It is recommended that you create a file named setenv.bat and place it in the Tomcat bin directory. With this file (which is run by the catalina.bat and catalina.sh scripts), you can change the following Tomcat environment settings with the JAVA_OPTS variable:
You can set the minimum and maximum memory heap size with the
JVM -Xms and -Xmx parameters.
The best limits depend on many conditions, such as transformations that Integrator ETL should execute. For Information Discovery transformations, a maximum of 1 GB is recommended. For example, to set the minimum heap size to 128 MB and the maximum heap size to 1024 MB, use
JAVA_OPTS=-Xms128m -Xmx1024m
You should set the maximum limit of the PermGen (Permanent Generation) memory space to a size larger than the default. The default of 64 MB is not enough for enterprise applications. A suitable memory limit depends on various criteria, but 256 MB would make a good choice in most cases. If the PermGen space maximum is too low, OutOfMemoryError: PermGen space errors may occur. You can set the PermGen maximum limit with the following JVM parameter
-XX:MaxPermSize=256m
For performance reasons, it is recommended that the application is run in Server mode. Apache Tomcat does not run in Server mode by default. You can set the Server mode by using the JVM -server parameter. You can set the JVM parameter in the JAVA_OPTS variable in the environment variable in the setenv file.
The following is an example of a setenv.bat file:
set "JAVA_OPTS=%JAVA_OPTS% -Xms128m -Xmx1024m -XX:MaxPermSize=256m -server"
Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?
In my case I am using:
SQLite,
prepared statements with placeholders to handle unknown number of fields,
AJAX request sent by user where everything is a string and there is no such thing like NULL
value and
I desperately need to insert NULL
s as that does not violates foreign key constrains (acceptable value).
Suppose, now user sends with post: $_POST[field1]
with value value1
which can be the empty string ""
or "null"
or "NULL"
.
First I make the statement:
$stmt = $this->dbh->prepare("INSERT INTO $table ({$sColumns}) VALUES ({$sValues})");
where {$sColumns}
is sth like field1, field2, ...
and {$sValues}
are my placeholders ?, ?, ...
.
Then, I collect my $_POST
data related with the column names in an array $values
and replace with NULL
s:
for($i = 0; $i < \count($values); $i++)
if((\strtolower($values[$i]) == 'null') || ($values[$i] == ''))
$values[$i] = null;
Now, I can execute:
$stmt->execute($values);
and among other bypass foreign key constrains.
If on the other hand, an empty string does makes more sense then you have to check if that field is part of a foreign key or not (more complicated).
how to check confirm password field in form without reloading page
We will be looking at two approaches to achieve this. With and without using jQuery.
1. Using jQuery
You need to add a keyup function to both of your password and confirm password fields. The reason being that the text equality should be checked even if the password
field changes. Thanks @kdjernigan for pointing that out
In this way, when you type in the field you will know if the password is same or not:
_x000D_
_x000D_
$('#password, #confirm_password').on('keyup', function () {
if ($('#password').val() == $('#confirm_password').val()) {
$('#message').html('Matching').css('color', 'green');
} else
$('#message').html('Not Matching').css('color', 'red');
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>password :
<input name="password" id="password" type="password" />
</label>
<br>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" />
<span id='message'></span>
</label>
_x000D_
_x000D_
_x000D_
and here is the fiddle: http://jsfiddle.net/aelor/F6sEv/325/
2. Without using jQuery
We will use the onkeyup event of javascript on both the fields to achieve the same effect.
_x000D_
_x000D_
var check = function() {
if (document.getElementById('password').value ==
document.getElementById('confirm_password').value) {
document.getElementById('message').style.color = 'green';
document.getElementById('message').innerHTML = 'matching';
} else {
document.getElementById('message').style.color = 'red';
document.getElementById('message').innerHTML = 'not matching';
}
}
_x000D_
<label>password :
<input name="password" id="password" type="password" onkeyup='check();' />
</label>
<br>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" onkeyup='check();' />
<span id='message'></span>
</label>
_x000D_
_x000D_
_x000D_
and here is the fiddle: http://jsfiddle.net/aelor/F6sEv/324/
Downloading Java JDK on Linux via wget is shown license page instead
@eric answer did the trick for me, you need to accept terms in the command you are setting
i.e
"Cookie: oraclelicense=accept-securebackup-cookie"
so your final command looks thus
wget -c --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jdk-8u131-linux-x64.tar.gz
You can decide to update the version by changing 8u131
to 8uXXX
. so long it is available in the repo.
Positioning background image, adding padding
this is actually pretty easily done. You're almost there, doing what you've done with background-position: right center;
. What is actually needed in this case is something very much like that. Let's convert these to percentages. We know that center
=50%
, so that's easy enough. Now, in order to get the padding you wanted, you need to position the background like so: background-position: 99% 50%
.
The second, and more effective way of going about this, is to use the same background-position
idea, and just use background-position: 400px (width of parent) 50%;
. Of course, this method requires a static width, but will give you the same thing every time.
Method 1 (99% 50%)
Method 2 (400px 50%)
How to process SIGTERM signal gracefully?
I think you are near to a possible solution.
Execute mainloop
in a separate thread and extend it with the property shutdown_flag
. The signal can be caught with signal.signal(signal.SIGTERM, handler)
in the main thread (not in a separate thread). The signal handler should set shutdown_flag
to True and wait for the thread to end with thread.join()
c++ Read from .csv file
Your csv is malformed. The output is not three loopings but just one output.
To ensure that this is a single loop, add a counter and increment it with every loop. It should only count to one.
This is what your code sees
0,Filipe,19,M\n1,Maria,20,F\n2,Walter,60,M
Try this
0,Filipe,19,M
1,Maria,20,F
2,Walter,60,M
while(file.good())
{
getline(file, ID, ',');
cout << "ID: " << ID << " " ;
getline(file, nome, ',') ;
cout << "User: " << nome << " " ;
getline(file, idade, ',') ;
cout << "Idade: " << idade << " " ;
getline(file, genero) ; \\ diff
cout << "Sexo: " << genero;\\diff
}
How do I truly reset every setting in Visual Studio 2012?
How to hard reset Visual Studio instance
When developing extensions sometimes you just mess up, others someone else does. If you start getting errors loading even the most mundane extensions, these are the instructions to hard reset your instance.
Close Visual Studio (if you haven’t already).
Open the registry editor (regedit.exe)
Delete the HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\{version}
Delete the HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\{version}_Config
Delete the %LOCALAPPDATA%\Microsoft\VisualStudio\{version} directory.
Enjoy your brand new Visual Studio instance.
- Use {version}=10.0 for Visual Studio 2010
- Use {version}=11.0 for Visual Studio 2012
- Use {version}=12.0 for Visual Studio 2013
If on the other side you want to reset the experimental hive you can do the same to with the ‘{version}Exp’ ones.
Happy coding!
Source: http://www.corvalius.com/site/hacks/how-to-hard-reset-visual-studio-instance/
jQuery call function after load
In regards to the question in your comment:
Assuming that you've previously bound your function to the click event of the radio button, add this to your $(document).ready
function:
$('#[radioButtonOptionID]').click()
Without a parameter, that simulates the click event.
How to define Typescript Map of key value pair. where key is a number and value is an array of objects
First thing, define a type or interface for your object, it will make things much more readable:
type Product = { productId: number; price: number; discount: number };
You used a tuple of size one instead of array, it should look like this:
let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();
So now this works fine:
myarray.push({productId : 1 , price : 100 , discount : 10});
myarray.push({productId : 2 , price : 200 , discount : 20});
myarray.push({productId : 3 , price : 300 , discount : 30});
priceListMap.set(1 , this.myarray);
myarray = null;
(code in playground)
How to write to Console.Out during execution of an MSTest test
The Console output is not appearing is because the backend code is not running in the context of the test.
You're probably better off using Trace.WriteLine
(In System.Diagnostics) and then adding a trace listener which writes to a file.
This topic from MSDN shows a way of doing this.
According to Marty Neal's and Dave Anderson's comments:
using System;
using System.Diagnostics;
...
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
// or Trace.Listeners.Add(new ConsoleTraceListener());
Trace.WriteLine("Hello World");
How can I specify a [DllImport] path at runtime?
As long as you know the directory where your C++ libraries could be found at run time, this should be simple. I can clearly see that this is the case in your code. Your myDll.dll
would be present inside myLibFolder
directory inside temporary folder of the current user.
string str = Path.GetTempPath() + "..\\myLibFolder\\myDLL.dll";
Now you can continue using the DllImport statement using a const string as shown below:
[DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int DLLFunction(int Number1, int Number2);
Just at run time before you call the DLLFunction
function (present in C++ library) add this line of code in C# code:
string assemblyProbeDirectory = Path.GetTempPath() + "..\\myLibFolder\\myDLL.dll";
Directory.SetCurrentDirectory(assemblyProbeDirectory);
This simply instructs the CLR to look for the unmanaged C++ libraries at the directory path which you obtained at run time of your program. Directory.SetCurrentDirectory
call sets the application's current working directory to the specified directory. If your myDLL.dll
is present at path represented by assemblyProbeDirectory
path then it will get loaded and the desired function will get called through p/invoke.
Purpose of __repr__ method?
An example to see the differences between them (I copied from this source),
>>> x=4
>>> repr(x)
'4'
>>> str(x)
'4'
>>> y='stringy'
>>> repr(y)
"'stringy'"
>>> str(y)
'stringy'
The returns of repr()
and str()
are identical for int x
, but there's a difference between the return values for str
y
-- one is formal and the other is informal. One of the most important differences between the formal and informal representations is that the default implementation of __repr__
for a str value can be called as an argument to eval, and the return value would be a valid string object, like this:
>>> repr(y)
"'a string'"
>>> y2=eval(repr(y))
>>> y==y2
True
If you try to call the return value of __str__
as an argument to eval, the result won't be valid.
Who sets response content-type in Spring MVC (@ResponseBody)
The simple way to solve this problem in Spring 3.1.1 is that: add following configuration codes in servlet-context.xml
<annotation-driven>
<message-converters register-defaults="true">
<beans:bean class="org.springframework.http.converter.StringHttpMessageConverter">
<beans:property name="supportedMediaTypes">
<beans:value>text/plain;charset=UTF-8</beans:value>
</beans:property>
</beans:bean>
</message-converters>
</annotation-driven>
Don't need to override or implement anything.
Change color of Button when Mouse is over
<Button Content="Click" Width="200" Height="50">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="LightBlue" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="Border" Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="LightGreen" TargetName="Border" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
Git - Won't add files?
I had the same problem and it was because there was a program using some file and git throws an error in this case Visual Studio had locked that file.
Is there a date format to display the day of the week in java?
I know the question is about getting the day of week as string (e.g. the short name), but for anybody who is looking for the numeric day of week (as I was), you can use the new "u" format string, supported since Java 7. For example:
new SimpleDateFormat("u").format(new Date());
returns today's day-of-week index, namely: 1 = Monday, 2 = Tuesday, ..., 7 = Sunday.
Pandas: Convert Timestamp to datetime.date
Use the .date
method:
In [11]: t = pd.Timestamp('2013-12-25 00:00:00')
In [12]: t.date()
Out[12]: datetime.date(2013, 12, 25)
In [13]: t.date() == datetime.date(2013, 12, 25)
Out[13]: True
To compare against a DatetimeIndex (i.e. an array of Timestamps), you'll want to do it the other way around:
In [21]: pd.Timestamp(datetime.date(2013, 12, 25))
Out[21]: Timestamp('2013-12-25 00:00:00')
In [22]: ts = pd.DatetimeIndex([t])
In [23]: ts == pd.Timestamp(datetime.date(2013, 12, 25))
Out[23]: array([ True], dtype=bool)
No space left on device
Maybe you are out of inodes. Try df -i
2591792 136322 2455470 6% /home
/dev/sdb1 1887488 1887488 0 100% /data
Disk used 6% but inode table full.
Path to Powershell.exe (v 2.0)
It is always C:\Windows\System32\WindowsPowershell\v1.0. It was left like that for backward compability is what I heard or read somewhere.
Does C# have extension properties?
For the moment it is still not supported out of the box by Roslyn compiler ...
Until now, the extension properties were not seen as valuable enough to be included in the previous versions of C# standard. C# 7 and C# 8.0 have seen this as proposal champion but it wasn't released yet, most of all because even if there is already an implementation, they want to make it right from the start.
But it will ...
There is an extension members item in the C# 7 work list so it may be supported in the near future. The current status of extension property can be found on Github under the related item.
However, there is an even more promising topic which is the "extend everything" with a focus on especially properties and static classes or even fields.
Moreover you can use a workaround
As specified in this article, you can use the TypeDescriptor
capability to attach an attribute to an object instance at runtime. However, it is not using the syntax of the standard properties.
It's a little bit different from just syntactic sugar adding a possibility to define an extended property like
string Data(this MyClass instance)
as an alias for extension method
string GetData(this MyClass instance)
as it stores data into the class.
I hope that C#7 will provide a full featured extension everything (properties and fields), however on that point, only time will tell.
And feel free to contribute as the software of tomorrow will come from the community.
Update: August 2016
As dotnet team published what's new in C# 7.0 and from a comment of Mads Torgensen:
Extension properties: we had a (brilliant!) intern implement them over
the summer as an experiment, along with other kinds of extension
members. We remain interested in this, but it’s a big change and we
need to feel confident that it’s worth it.
It seems that extension properties and other members, are still good candidates to be included in a future release of Roslyn, but maybe not the 7.0 one.
Update: May 2017
The extension members has been closed as duplicate of extension everything issue which is closed too.
The main discussion was in fact about Type extensibility in a broad sense.
The feature is now tracked here as a proposal and has been removed from 7.0 milestone.
Update: August, 2017 - C# 8.0 proposed feature
While it still remains only a proposed feature, we have now a clearer view of what would be its syntax. Keep in mind that this will be the new syntax for extension methods as well:
public interface IEmployee
{
public decimal Salary { get; set; }
}
public class Employee
{
public decimal Salary { get; set; }
}
public extension MyPersonExtension extends Person : IEmployee
{
private static readonly ConditionalWeakTable<Person, Employee> _employees =
new ConditionalWeakTable<Person, Employee>();
public decimal Salary
{
get
{
// `this` is the instance of Person
return _employees.GetOrCreate(this).Salary;
}
set
{
Employee employee = null;
if (!_employees.TryGetValue(this, out employee)
{
employee = _employees.GetOrCreate(this);
}
employee.Salary = value;
}
}
}
IEmployee person = new Person();
var salary = person.Salary;
Similar to partial classes, but compiled as a separate class/type in a different assembly. Note you will also be able to add static members and operators this way. As mentioned in Mads Torgensen podcast, the extension won't have any state (so it cannot add private instance members to the class) which means you won't be able to add private instance data linked to the instance. The reason invoked for that is it would imply to manage internally dictionaries and it could be difficult (memory management, etc...).
For this, you can still use the TypeDescriptor
/ConditionalWeakTable
technique described earlier and with the property extension, hides it under a nice property.
Syntax is still subject to change as implies this issue. For example, extends
could be replaced by for
which some may feel more natural and less java related.
Update December 2018 - Roles, Extensions and static interface members
Extension everything didn't make it to C# 8.0, because of some of drawbacks explained as the end of this GitHub ticket. So, there was an exploration to improve the design. Here, Mads Torgensen explains what are roles and extensions and how they differs:
Roles allow interfaces to be implemented on specific values of a given
type. Extensions allow interfaces to be implemented on all values of a
given type, within a specific region of code.
It can be seen at a split of previous proposal in two use cases. The new syntax for extension would be like this:
public extension ULongEnumerable of ulong
{
public IEnumerator<byte> GetEnumerator()
{
for (int i = sizeof(ulong); i > 0; i--)
{
yield return unchecked((byte)(this >> (i-1)*8));
}
}
}
then you would be able to do this:
foreach (byte b in 0x_3A_9E_F1_C5_DA_F7_30_16ul)
{
WriteLine($"{e.Current:X}");
}
And for a static interface:
public interface IMonoid<T> where T : IMonoid<T>
{
static T operator +(T t1, T t2);
static T Zero { get; }
}
Add an extension property on int
and treat the int
as IMonoid<int>
:
public extension IntMonoid of int : IMonoid<int>
{
public static int Zero => 0;
}
SQL select join: is it possible to prefix all columns as 'prefix.*'?
In postgres, I use the json functions to instead return json objects....
then, after querying, I json_decode the fields with a _json suffix.
IE:
select row_to_json(tab1.*),tab1_json, row_to_json(tab2.*) tab2_json
from tab1
join tab2 on tab2.t1id=tab1.id
then in PHP (or any other language), I loop through the returned columns and json_decode() them if they have the "_json" suffix (also removing the suffix. In the end, I get an object called "tab1" that includes all tab1 fields, and another called "tab2" that includes all tab2 fields.
Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax
Using NickW's suggestion, I was able to get this working using things = JSON.stringify({ 'things': things });
Here is the complete code.
$(document).ready(function () {
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
things = JSON.stringify({ 'things': things });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Home/PassThings',
data: things,
success: function () {
$('#result').html('"PassThings()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
public void PassThings(List<Thing> things)
{
var t = things;
}
public class Thing
{
public int Id { get; set; }
public string Color { get; set; }
}
There are two things I learned from this:
The contentType and dataType settings are absolutely necessary in the ajax() function. It won't work if they are missing. I found this out after much trial and error.
To pass in an array of objects to an MVC controller method, simply use the JSON.stringify({ 'things': things }) format.
I hope this helps someone else!
Fixing broken UTF-8 encoding
As Dan pointed out: you need to convert them to binary and then convert/correct the encoding.
E.g., for utf8 stored as latin1 the following SQL will fix it:
UPDATE table
SET field = CONVERT( CAST(field AS BINARY) USING utf8)
WHERE $broken_field_condition
estimating of testing effort as a percentage of development time
Are you talking about automated unit/integration tests or manual tests?
For the former, my rule of thumb (based on measurements) is 40-50% added to development time i.e. if developing a use case takes 10 days (before an QA and serious bugfixing happens), writing good tests takes another 4 to 5 days - though this should best happen before and during development, not afterwards.
Iterate over a Javascript associative array in sorted order
You cannot iterate over them directly, but you can find all the keys and then just sort them.
var a = new Array();
a['b'] = 1;
a['z'] = 1;
a['a'] = 1;
function keys(obj)
{
var keys = [];
for(var key in obj)
{
if(obj.hasOwnProperty(key))
{
keys.push(key);
}
}
return keys;
}
keys(a).sort(); // ["a", "b", "z"]
However there is no need to make the variable 'a' an array. You are really just using it as an object and should create it like this:
var a = {};
a["key"] = "value";
Setting Windows PATH for Postgres tools
Set path For PostgreSQL in Windows:
- Searching for env will show Edit environment variables for your account
- Select Environment Variables
- From the System Variables box select PATH
- Click New (to add new path)
Change the PATH variable to include the bin directory of your PostgreSQL installation.
then add new path their....[for example]
C:\Program Files\PostgreSQL\12\bin
After that click OK
Open CMD/Command Prompt. Type this to open psql
psql -U username database_name
For Example psql -U postgres test
Now, you will be prompted to give Password for the User. (It will be hidden as a security measure).
Then you are good to go.
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
Traditionally PHP has been tolerant to bad practice and failures in code,
which makes debugging quite hard.
The problem in this specific case is that both mysqli and PDO
by default don't tell you, when a query failed and just return FALSE
.
(I will not talk about the depricated mysql extention.
The support for prepared statements is reason anough to switch either to PDO or mysqli.)
But you can change the default behavior of PHP to always throw exceptions when a query fails.
For PDO: Use $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
error_reporting(E_ALL);
$pdo = new PDO("mysql:host=localhost;dbname=test", "test","");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $pdo->query('select emal from users');
$data = $result->fetchAll();
This will show you the following:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emal' in 'field list'' in E:\htdocs\test\mysql_errors\pdo.php on line 8
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emal' in 'field list' in E:\htdocs\test\mysql_errors\pdo.php on line 8
As you see, it tells you exactly, what is wrong with the query, and where to fix it in your code.
Without $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
you will get
Fatal error: Call to a member function fetchAll() on boolean in E:\htdocs\test\mysql_errors\pdo.php on line 9
For mysqli: Use mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'test', '', 'test');
$result = $mysqli->query('select emal from users');
$data = $result->fetch_all();
You will get
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Unknown column 'emal' in 'field list'' in E:\htdocs\test\mysql_errors\mysqli.php on line 8
mysqli_sql_exception: Unknown column 'emal' in 'field list' in E:\htdocs\test\mysql_errors\mysqli.php on line 8
Without mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
you only get
Fatal error: Call to a member function fetch_all() on boolean in E:\htdocs\test\mysql_errors\mysqli.php on line 10
Of course, you could manually check the MySQL errors.
But I would go crazy if I had to do that every time I made a typo -
or worse - every time I want to query the database.
Google Maps API v3 adding an InfoWindow to each marker
I had a similar problem.
If all you want is for some info to be displayed when you hover over a marker, instead of clicking it, then I found that a good alternative to using an info Window was to set a title on the marker. That way whenever you hover the mouse over the marker the title displays like an ALT tag.
'marker.setTitle('Marker '+id);'
It removes the need to create a listener for the marker too
OPTION (RECOMPILE) is Always Faster; Why?
Often when there is a drastic difference from run to run of a query I find that it is often one of 5 issues.
STATISTICS - Statistics are out of date. A database stores statistics on the range and distribution of the types of values in various column on tables and indexes. This helps the query engine to develop a "Plan" of attack for how it will do the query, for example the type of method it will use to match keys between tables using a hash or looking through the entire set. You can call Update Statistics on the entire database or just certain tables or indexes. This slows down the query from one run to another because when statistics are out of date, its likely the query plan is not optimal for the newly inserted or changed data for the same query (explained more later below). It may not be proper to Update Statistics immediately on a Production database as there will be some overhead, slow down and lag depending on the amount of data to sample. You can also choose to use a Full Scan or Sampling to update Statistics. If you look at the Query Plan, you can then also view the statistics on the Indexes in use such using the command DBCC SHOW_STATISTICS (tablename, indexname). This will show you the distribution and ranges of the keys that the query plan is using to base its approach on.
PARAMETER SNIFFING - The query plan that is cached is not optimal for the particular parameters you are passing in, even though the query itself has not changed. For example, if you pass in a parameter which only retrieves 10 out of 1,000,000 rows, then the query plan created may use a Hash Join, however if the parameter you pass in will use 750,000 of the 1,000,000 rows, the plan created may be an index scan or table scan. In such a situation you can tell the SQL statement to use the option OPTION (RECOMPILE) or an SP to use WITH RECOMPILE. To tell the Engine this is a "Single Use Plan" and not to use a Cached Plan which likely does not apply. There is no rule on how to make this decision, it depends on knowing the way the query will be used by users.
INDEXES - Its possible that the query haven't changed, but a change elsewhere such as the removal of a very useful index has slowed down the query.
ROWS CHANGED - The rows you are querying drastically changes from call to call. Usually statistics are automatically updated in these cases. However if you are building dynamic SQL or calling SQL within a tight loop, there is a possibility you are using an outdated Query Plan based on the wrong drastic number of rows or statistics. Again in this case OPTION (RECOMPILE) is useful.
THE LOGIC Its the Logic, your query is no longer efficient, it was fine for a small number of rows, but no longer scales. This usually involves more indepth analysis of the Query Plan. For example, you can no longer do things in bulk, but have to Chunk things and do smaller Commits, or your Cross Product was fine for a smaller set but now takes up CPU and Memory as it scales larger, this may also be true for using DISTINCT, you are calling a function for every row, your key matches don't use an index because of CASTING type conversion or NULLS or functions... Too many possibilities here.
In general when you write a query, you should have some mental picture of roughly how certain data is distributed within your table. A column for example, can have an evenly distributed number of different values, or it can be skewed, 80% of the time have a specific set of values, whether the distribution will varying frequently over time or be fairly static. This will give you a better idea of how to build an efficient query. But also when debugging query performance have a basis for building a hypothesis as to why it is slow or inefficient.
SQL use CASE statement in WHERE IN clause
I realize this has been answered, but there is a slight issue with the accepted solution. It will return false positives. Easy to fix:
SELECT * FROM Products P
WHERE (@Status='published' and P.Status IN (1,3))
or (@Status='standby' and P.Status IN (2,5,9,6))
or (@Status='deleted' and P.Status IN (4,5,8,10))
or (@Status not in ('published','standby','deleted') and P.Status IN (1,2))
Parentheses aren't needed (although perhaps easier to read hence why I included them).
React navigation goBack() and update parent state
is there a way to pass param from navigate.goback()
and parent can listen to the params and update its state?
You can pass a callback function as parameter (as mentioned in other answers).
Here is a more clear example, when you navigate from A to B and you want B to communicate information back to A you can pass a callback (here onSelect
):
ViewA.js
import React from "react";
import { Button, Text, View } from "react-native";
class ViewA extends React.Component {
state = { selected: false };
onSelect = data => {
this.setState(data);
};
onPress = () => {
this.props.navigate("ViewB", { onSelect: this.onSelect });
};
render() {
return (
<View>
<Text>{this.state.selected ? "Selected" : "Not Selected"}</Text>
<Button title="Next" onPress={this.onPress} />
</View>
);
}
}
ViewB.js
import React from "react";
import { Button } from "react-native";
class ViewB extends React.Component {
goBack() {
const { navigation } = this.props;
navigation.goBack();
navigation.state.params.onSelect({ selected: true });
}
render() {
return <Button title="back" onPress={this.goBack} />;
}
}
Hats off for debrice - Refer to https://github.com/react-navigation/react-navigation/issues/288#issuecomment-315684617
Edit
For React Navigation v5
ViewB.js
import React from "react";
import { Button } from "react-native";
class ViewB extends React.Component {
goBack() {
const { navigation, route } = this.props;
navigation.goBack();
route.params.onSelect({ selected: true });
}
render() {
return <Button title="back" onPress={this.goBack} />;
}
}
Spring expected at least 1 bean which qualifies as autowire candidate for this dependency
If there is an interface anywhere in the ThreadProvider hierarchy try putting the name of the Interface as the type of your service provider, eg. if you have say this structure:
public class ThreadProvider implements CustomInterface{
...
}
Then in your controller try this:
@Controller
public class ChiusuraController {
@Autowired
private CustomInterface chiusuraProvider;
}
The reason why this is happening is, in your first case when you DID NOT have ChiusuraProvider
extend ThreadProvider
Spring probably was underlying creating a CGLIB based proxy for you(to handle the @Transaction).
When you DID extend from ThreadProvider
assuming that ThreadProvider extends some interface, Spring in that case creates a Java Dynamic Proxy based Proxy, which would appear to be an implementation of that interface instead of being of ChisuraProvider
type.
If you absolutely need to use ChisuraProvider
you can try AspectJ as an alternative or force CGLIB based proxy in the case with ThreadProvider also this way:
<aop:aspectj-autoproxy proxy-target-class="true"/>
Here is some more reference on this from the Spring Reference site: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/classic-aop-spring.html#classic-aop-pfb
Current Subversion revision command
First of all svn status has the revision number, you can read it from there.
Also, each file that you store in SVN can store the revision number in itself -- add the $Rev$
keyword to your file and run propset: svn propset svn:keywords "Revision" file
Finally, the revision number is also in .svn/entries
file, fourth line
Now each time you checkout that file, it will have the revision in itself.
get current url in twig template?
{{ path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) }}
If you want to read it into a view variable:
{% set currentPath = path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) %}
The app
global view variable contains all sorts of useful shortcuts, such as app.session
and app.security.token.user
, that reference the services you might use in a controller.
Plotting a python dict in order of key values
Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict
In your case, sort the dict by key before plotting,
import matplotlib.pylab as plt
lists = sorted(d.items()) # sorted by key, return a list of tuples
x, y = zip(*lists) # unpack a list of pairs into two tuples
plt.plot(x, y)
plt.show()
Here is the result.
How do I do word Stemming or Lemmatization?
In Java, i use tartargus-snowball to stemming words
Maven:
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-snowball</artifactId>
<version>3.0.3</version>
<scope>test</scope>
</dependency>
Sample code:
SnowballProgram stemmer = new EnglishStemmer();
String[] words = new String[]{
"testing",
"skincare",
"eyecare",
"eye",
"worked",
"read"
};
for (String word : words) {
stemmer.setCurrent(word);
stemmer.stem();
//debug
logger.info("Origin: " + word + " > " + stemmer.getCurrent());// result: test, skincar, eyecar, eye, work, read
}
python filter list of dictionaries based on key value
Use filter
, or if the number of dictionaries in exampleSet
is too high, use ifilter
of the itertools
module. It would return an iterator, instead of filling up your system's memory with the entire list at once:
from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
print elem
How to disable keypad popup when on edittext?
try it.......i solve this problem using code:-
EditText inputArea;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputArea = (EditText) findViewById(R.id.inputArea);
//This line is you answer.Its unable your click ability in this Edit Text
//just write
inputArea.setInputType(0);
}
nothing u can input by default calculator on anything but u can set any string.
try it
Docker container not starting (docker start)
You are trying to run bash
, an interactive shell that requires a tty in order to operate. It doesn't really make sense to run this in "detached" mode with -d
, but you can do this by adding -it
to the command line, which ensures that the container has a valid tty associated with it and that stdin
remains connected:
docker run -it -d -p 52022:22 basickarl/docker-git-test
You would more commonly run some sort of long-lived non-interactive process (like sshd
, or a web server, or a database server, or a process manager like systemd
or supervisor
) when starting detached containers.
If you are trying to run a service like sshd
, you cannot simply run service ssh start
. This will -- depending on the distribution you're running inside your container -- do one of two things:
It will try to contact a process manager like systemd
or upstart
to start the service. Because there is no service manager running, this will fail.
It will actually start sshd
, but it will be started in the background. This means that (a) the service sshd start
command exits, which means that (b) Docker considers your container to have failed, so it cleans everything up.
If you want to run just ssh in a container, consider an example like this.
If you want to run sshd
and other processes inside the container, you will need to investigate some sort of process supervisor.
Boolean vs boolean in Java
You can use Boolean / boolean. Simplicity is the way to go.
If you do not need specific api (Collections, Streams, etc.) and you are not foreseeing that you will need them - use primitive version of it (boolean).
With primitives you guarantee that you will not pass null values.
You will not fall in traps like this. The code below throws NullPointerException (from: Booleans, conditional operators and autoboxing):
public static void main(String[] args) throws Exception {
Boolean b = true ? returnsNull() : false; // NPE on this line.
System.out.println(b);
}
public static Boolean returnsNull() {
return null;
}
Use Boolean when you need an object, eg:
- Stream of Booleans,
- Optional
- Collections of Booleans
Error in spring application context schema
Referenced file contains errors
(http://www.springframework.org/schema/context/spring-context-3.0.xsd)
i faced this problem, when i was configuring dispatcher-servlet.xml ,you can remove this:
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"
from your xml and you can also follow the steps
go to window -> preferences -> validation -> and unchecked XML validator and XML schema validator.
Use own username/password with git and bitbucket
I had to merge some of those good answers here! This works for me:
git remote set-url origin 'https://bitbucket.org/teamName/repo.git'
In the end, it will always prompt anyone who wants to pull from it
How can I increase a scrollbar's width using CSS?
Yes.
If the scrollbar is not the browser scrollbar, then it will be built of regular HTML elements (probably div
s and span
s) and can thus be styled (or will be Flash, Java, etc and can be customized as per those environments).
The specifics depend on the DOM structure used.