Python: Maximum recursion depth exceeded
You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:
import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values
... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.
Colorizing text in the console with C++
Do not use "system("Color …")" if you don't want the entire screen to be filled up with color. This is the script needed to make colored text:
#include <iostream>
#include <windows.h>
int main()
{
const WORD colors[] =
{
0x1A, 0x2B, 0x3C, 0x4D, 0x5E, 0x6F,
0xA1, 0xB2, 0xC3, 0xD4, 0xE5, 0xF6
};
HANDLE hstdin = GetStdHandle(STD_INPUT_HANDLE);
HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
WORD index = 0;
SetConsoleTextAttribute(hstdout, colors[index]);
std::cout << "Hello world" << std::endl;
FlushConsoleInputBuffer(hstdin);
return 0;
}
How to make inactive content inside a div?
div[disabled]
{
pointer-events: none;
opacity: 0.7;
}
The above code makes the contents of the div disabled.
You can make div disabled by adding disabled attribute.
<div disabled>
/* Contents */
</div>
Specifying number of decimal places in Python
To calculate tax, you could use round
(after all, that's what the restaurant does):
def calc_tax(mealPrice):
tax = round(mealPrice*.06,2)
return tax
To display the data, you could use a multi-line string, and the string format method:
def display_data(mealPrice, tax):
total=round(mealPrice+tax,2)
print('''\
Your Meal Price is {m:=5.2f}
Tax {x:=5.2f}
Total {t:=5.2f}
'''.format(m=mealPrice,x=tax,t=total))
Note the format method was introduced in Python 2.6, for earlier versions you'll need to use old-style string interpolation %
:
print('''\
Your Meal Price is %5.2f
Tax %5.2f
Total %5.2f
'''%(mealPrice,tax,total))
Then
mealPrice=input_meal()
tax=calc_tax(mealPrice)
display_data(mealPrice,tax)
yields:
# Enter the meal subtotal: $43.45
# Your Meal Price is 43.45
# Tax 2.61
# Total 46.06
How to make a new List in Java
Additionally, if you want to create a list that has things in it (though it will be fixed size):
List<String> messages = Arrays.asList("Hello", "World!", "How", "Are", "You");
mysql data directory location
Well, if yo don't know where is my.cnf (such Mac OS X installed with homebrew), or You are looking found others choices:
ps aux|grep mysql
abkrim 1160 0.0 0.2 2913068 26224 ?? R Tue04PM 0:14.63 /usr/local/opt/mariadb/bin/mysqld --basedir=/usr/local/opt/mariadb --datadir=/usr/local/var/mysql --plugin-dir=/usr/local/opt/mariadb/lib/plugin --bind-address=127.0.0.1 --log-error=/usr/local/var/mysql/iMac-2.local.err --pid-file=iMac-2.local.pid
You get datadir=/usr/local/var/mysql
how to draw smooth curve through N points using javascript HTML5 canvas?
I found this to work nicely
function drawCurve(points, tension) {
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
var t = (tension != null) ? tension : 1;
for (var i = 0; i < points.length - 1; i++) {
var p0 = (i > 0) ? points[i - 1] : points[0];
var p1 = points[i];
var p2 = points[i + 1];
var p3 = (i != points.length - 2) ? points[i + 2] : p2;
var cp1x = p1.x + (p2.x - p0.x) / 6 * t;
var cp1y = p1.y + (p2.y - p0.y) / 6 * t;
var cp2x = p2.x - (p3.x - p1.x) / 6 * t;
var cp2y = p2.y - (p3.y - p1.y) / 6 * t;
ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, p2.x, p2.y);
}
ctx.stroke();
}
getElementsByClassName not working
There are several issues:
- Class names (and IDs) are not allowed to start with a digit.
- You have to pass a class to
getElementsByClassName()
.
- You have to iterate of the result set.
Example (untested):
<script type="text/javascript">
function hideTd(className){
var elements = document.getElementsByClassName(className);
for(var i = 0, length = elements.length; i < length; i++) {
if( elements[i].textContent == ''){
elements[i].style.display = 'none';
}
}
}
</script>
</head>
<body onload="hideTd('td');">
<table border="1">
<tr>
<td class="td">not empty</td>
</tr>
<tr>
<td class="td"></td>
</tr>
<tr>
<td class="td"></td>
</tr>
</table>
</body>
Note that getElementsByClassName()
is not available up to and including IE8.
Update:
Alternatively you can give the table an ID and use:
var elements = document.getElementById('tableID').getElementsByTagName('td');
to get all td
elements.
To hide the parent row, use the parentNode
property of the element:
elements[i].parentNode.style.display = "none";
Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?
def merge_with(f, xs, ys):
xs = a_copy_of(xs) # dict(xs), maybe generalizable?
for (y, v) in ys.iteritems():
xs[y] = v if y not in xs else f(xs[x], v)
merge_with((lambda x, y: x + y), A, B)
You could easily generalize this:
def merge_dicts(f, *dicts):
result = {}
for d in dicts:
for (k, v) in d.iteritems():
result[k] = v if k not in result else f(result[k], v)
Then it can take any number of dicts.
Wait until boolean value changes it state
You need a mechanism which avoids busy-waiting. The old wait/notify
mechanism is fraught with pitfalls so prefer something from the java.util.concurrent
library, for example the CountDownLatch
:
public final CountDownLatch latch = new CountDownLatch(1);
public void run () {
latch.await();
...
}
And at the other side call
yourRunnableObj.latch.countDown();
However, starting a thread to do nothing but wait until it is needed is still not the best way to go. You could also employ an ExecutorService
to which you submit as a task the work which must be done when the condition is met.
proper hibernate annotation for byte[]
Here goes what O'reilly Enterprise JavaBeans, 3.0 says
JDBC has special types for these very large objects. The java.sql.Blob type represents binary data, and java.sql.Clob represents character data.
Here goes PostgreSQLDialect source code
public PostgreSQLDialect() {
super();
...
registerColumnType(Types.VARBINARY, "bytea");
/**
* Notice it maps java.sql.Types.BLOB as oid
*/
registerColumnType(Types.BLOB, "oid");
}
So what you can do
Override PostgreSQLDialect as follows
public class CustomPostgreSQLDialect extends PostgreSQLDialect {
public CustomPostgreSQLDialect() {
super();
registerColumnType(Types.BLOB, "bytea");
}
}
Now just define your custom dialect
<property name="hibernate.dialect" value="br.com.ar.dialect.CustomPostgreSQLDialect"/>
And use your portable JPA @Lob annotation
@Lob
public byte[] getValueBuffer() {
UPDATE
Here has been extracted here
I have an application running in hibernate 3.3.2 and the applications works fine, with all blob fields using oid (byte[] in java)
...
Migrating to hibernate 3.5 all blob fields not work anymore, and the server log shows: ERROR org.hibernate.util.JDBCExceptionReporter - ERROR: column is of type oid but expression is of type bytea
which can be explained here
This generaly is not bug in PG JDBC, but change of default implementation of Hibernate in 3.5 version. In my situation setting compatible property on connection
did not helped.
...
Much more this what I saw in 3.5 - beta 2, and i do not know if this was fixed is Hibernate - without @Type annotation - will auto-create column of type oid, but will try to read this as bytea
Interesting is because when he maps Types.BOLB as bytea (See CustomPostgreSQLDialect) He get
Could not execute JDBC batch update
when inserting or updating
List<Object> and List<?>
Why cant I do this:
List<Object> object = new List<Object>();
You can't do this because List
is an interface, and interfaces cannot be instantiated. Only (concrete) classes can be. Examples of concrete classes implementing List
include ArrayList
, LinkedList
etc.
Here is how one would create an instance of ArrayList
:
List<Object> object = new ArrayList<Object>();
I have a method that returns a List<?>
, how would I turn that into a List<Object>
Show us the relevant code and I'll update the answer.
Node.js Web Application examples/tutorials
Update
Dav Glass from Yahoo has given a talk at YuiConf2010 in November which is now available in Video from.
He shows to great extend how one can use YUI3 to render out widgets on the server side an make them work with GET requests when JS is disabled, or just make them work normally when it's active.
He also shows examples of how to use server side DOM to apply style sheets before rendering and other cool stuff.
The demos can be found on his GitHub Account.
The part that's missing IMO to make this really awesome, is some kind of underlying storage of the widget state. So that one can visit the page without JavaScript and everything works as expected, then they turn JS on and now the widget have the same state as before but work without page reloading, then throw in some saving to the server + WebSockets to sync between multiple open browser.... and the next generation of unobtrusive and gracefully degrading ARIA's is born.
Original Answer
Well go ahead and built it yourself then.
Seriously, 90% of all WebApps out there work fine with a REST approach, of course you could do magical things like superior user tracking, tracking of downloads in real time, checking which parts of videos are being watched etc.
One problem is scalability, as soon as you have more then 1 Node process, many (but not all) of the benefits of having the data stored between requests go away, so you have to make sure that clients always hit the same process. And even then, bigger things will yet again need a database layer.
Node.js isn't the solution to everything, I'm sure people will build really great stuff in the future, but that needs some time, right now many are just porting stuff over to Node to get things going.
What (IMHO) makes Node.js so great, is the fact that it streamlines the Development process, you have to write less code, it works perfectly with JSON, you loose all that context switching.
I mainly did gaming experiments so far, but I can for sure say that there will be many cool multi player (or even MMO) things in the future, that use both HTML5 and Node.js.
Node.js is still gaining traction, it's not even near to the RoR Hype some years ago (just take a look at the Node.js tag here on SO, hardly 4-5 questions a day).
Rome (or RoR) wasn't built over night, and neither will Node.js be.
Node.js has all the potential it needs, but people are still trying things out, so I'd suggest you to join them :)
How to put comments in Django templates
As answer by Miles, {% comment %}...{% endcomment %}
is used for multi-line comments, but you can also comment out text on the same line like this:
{# some text #}
brew install mysql on macOS
If brew installed MySQL 5.7, the process is a bit different than for previous versions.
In order to reset the root password, proceed as follows:
sudo rm -rf /usr/local/var/mysql
mysqld --initialize
A temporary password will be printed to the console and it can only be used for updating the root password:
mysql.server start
echo "ALTER USER 'root'@'localhost' IDENTIFIED BY 'my-new-password';" | mysql -uroot --password=TEMPORARY_PASSWORD
How to tell if a JavaScript function is defined
All of the current answers use a literal string, which I prefer to not have in my code if possible - this does not (and provides valuable semantic meaning, to boot):
function isFunction(possibleFunction) {
return typeof(possibleFunction) === typeof(Function);
}
Personally, I try to reduce the number of strings hanging around in my code...
Also, while I am aware that typeof
is an operator and not a function, there is little harm in using syntax that makes it appear as the latter.
Resize image with javascript canvas (smoothly)
Based on K3N answer, I rewrite code generally for anyone wants
var oc = document.createElement('canvas'), octx = oc.getContext('2d');
oc.width = img.width;
oc.height = img.height;
octx.drawImage(img, 0, 0);
while (oc.width * 0.5 > width) {
oc.width *= 0.5;
oc.height *= 0.5;
octx.drawImage(oc, 0, 0, oc.width, oc.height);
}
oc.width = width;
oc.height = oc.width * img.height / img.width;
octx.drawImage(img, 0, 0, oc.width, oc.height);
UPDATE JSFIDDLE DEMO
Here is my ONLINE DEMO
How do I set a textbox's text to bold at run time?
Here is an example for toggling bold, underline, and italics.
protected override bool ProcessCmdKey( ref Message msg, Keys keyData )
{
if ( ActiveControl is RichTextBox r )
{
if ( keyData == ( Keys.Control | Keys.B ) )
{
r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Bold ); // XOR will toggle
return true;
}
if ( keyData == ( Keys.Control | Keys.U ) )
{
r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Underline ); // XOR will toggle
return true;
}
if ( keyData == ( Keys.Control | Keys.I ) )
{
r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Italic ); // XOR will toggle
return true;
}
}
return base.ProcessCmdKey( ref msg, keyData );
}
Regex allow a string to only contain numbers 0 - 9 and limit length to 45
You are almost there, all you need is start anchor (^
) and end anchor ($
):
^[0-9]{1,45}$
\d
is short for the character class [0-9]
. You can use that as:
^\d{1,45}$
The anchors force the pattern to match entire input, not just a part of it.
Your regex [0-9]{1,45}
looks for 1 to 45 digits, so string like foo1
also get matched as it contains 1
.
^[0-9]{1,45}
looks for 1 to 45 digits but these digits must be at the beginning of the input. It matches 123
but also 123foo
[0-9]{1,45}$
looks for 1 to 45 digits but these digits must be at the end of the input. It matches 123
but also foo123
^[0-9]{1,45}$
looks for 1 to 45 digits but these digits must be both at the start and at the end of the input, effectively it should be entire input.
Hashing a dictionary?
To preserve key order, instead of hash(str(dictionary))
or hash(json.dumps(dictionary))
I would prefer quick-and-dirty solution:
from pprint import pformat
h = hash(pformat(dictionary))
It will work even for types like DateTime
and more that are not JSON serializable.
Determine if two rectangles overlap each other?
I have a very easy solution
let x1,y1 x2,y2 ,l1,b1,l2,be cordinates and lengths and breadths of them respectively
consider the condition ((x2
now the only way these rectangle will overlap is if the point diagonal to x1,y1 will lie inside the other rectangle or similarly the point diagonal to x2,y2 will lie inside the other rectangle. which is exactly the above condition implies.
Exit single-user mode
We just experienced this in SQL 2012.
A replication process jumped in when we killed the original session that set it to single user. But sp_who2 did not show that new process attached to the DB.
Closing SSMS and re-opening then allowed us to see this process on the database and then we could kill it and switch to multi_user mode immediately and that worked.
I can't work out the logic behind this, but it does appear to be a bug in SSMS and is still manifesting itself in SQL 2012.
Return the most recent record from ElasticSearch index
the _timestamp didn't work out for me,
this query does work for me:
(as in mconlin's answer)
{
"query": {
"match_all": {}
},
"size": "1",
"sort": [
{
"@timestamp": {
"order": "desc"
}
}
]
}
Could be trivial but the _timestamp answer didn't gave an error but not a good result either...
Hope to help someone...
(kibana/elastic 5.0.4)
S.
How to select first and last TD in a row?
You could use the :first-child
and :last-child
pseudo-selectors:
tr td:first-child,
tr td:last-child {
/* styles */
}
This should work in all major browsers, but IE7 has some problems when elements are added dynamically (and it won't work in IE6).
Cause of a process being a deadlock victim
Q1:Could the time it takes for a transaction to execute make the associated process more likely to be flagged as a deadlock victim.
No. The SELECT is the victim because it had only read data, therefore the transaction has a lower cost associated with it so is chosen as the victim:
By default, the Database Engine chooses as the deadlock victim the
session running the transaction that is least expensive to roll back.
Alternatively, a user can specify the priority of sessions in a
deadlock situation using the SET DEADLOCK_PRIORITY
statement.
DEADLOCK_PRIORITY can be set to LOW, NORMAL, or HIGH, or alternatively
can be set to any integer value in the range (-10 to 10).
Q2. If I execute the select with a NOLOCK hint, will this remove the problem?
No. For several reasons:
Q3. I suspect that a datetime field that is checked as part of the WHERE clause in the select statement is causing the slow lookup time. Can I create an index based on this field? Is it advisable?
Probably. The cause of the deadlock is almost very likely to be a poorly indexed database.10 minutes queries are acceptable in such narrow conditions, that I'm 100% certain in your case is not acceptable.
With 99% confidence I declare that your deadlock is cased by a large table scan conflicting with updates. Start by capturing the deadlock graph to analyze the cause. You will very likely have to optimize the schema of your database. Before you do any modification, read this topic Designing Indexes and the sub-articles.
How to add a changed file to an older (not last) commit in Git
Use git rebase
. Specifically:
- Use
git stash
to store the changes you want to add.
- Use
git rebase -i HEAD~10
(or however many commits back you want to see).
- Mark the commit in question (
a0865...
) for edit by changing the word pick
at the start of the line into edit
. Don't delete the other lines as that would delete the commits.[^vimnote]
- Save the rebase file, and git will drop back to the shell and wait for you to fix that commit.
- Pop the stash by using
git stash pop
- Add your file with
git add <file>
.
- Amend the commit with
git commit --amend --no-edit
.
- Do a
git rebase --continue
which will rewrite the rest of your commits against the new one.
- Repeat from step 2 onwards if you have marked more than one commit for edit.
[^vimnote]: If you are using vim
then you will have to hit the Insert key to edit, then Esc and type in :wq
to save the file, quit the editor, and apply the changes. Alternatively, you can configure a user-friendly git commit editor with git config --global core.editor "nano"
.
Decompile an APK, modify it and then recompile it
This is a way:
Using apktool
to decode:
$ apktool d -f {apkfile} -o {output folder}
Next, using JADX (at github.com/skylot/jadx)
$ jadx -d {output folder} {apkfile}
2 tools extract and decompiler to same output folder.
Easy way: Using Online APK Decompiler
String length in bytes in JavaScript
I compared some of the methods suggested here in Firefox for speed.
The string I used contained the following characters:
œ´®†¥¨ˆøp¬°??©ƒ?ßåO˜çv?˜µ=
All results are averages of 3 runs each. Times are in milliseconds. Note that all URIEncoding methods behaved similarly and had extreme results, so I only included one.
While there are some fluctuations based on the size of the string, the charCode methods (lovasoa and fuweichin) both perform similarly and the fastest overall, with fuweichin's charCode method the fastest. The Blob and TextEncoder methods performed similarly to each other. Generally the charCode methods were about 75% faster than the Blob and TextEncoder methods. The URIEncoding method was basically unacceptable.
Here are the results I got:
Size 6.4 * 10^6 bytes:
Lauri Oherd – URIEncoding: 6400000 et: 796
lovasoa – charCode: 6400000 et: 15
fuweichin – charCode2: 6400000 et: 16
simap – Blob: 6400000 et: 26
Riccardo Galli – TextEncoder: 6400000 et: 23
Size 19.2 * 10^6 bytes:
Blob does kind of a weird thing here.
Lauri Oherd – URIEncoding: 19200000 et: 2322
lovasoa – charCode: 19200000 et: 42
fuweichin – charCode2: 19200000 et: 45
simap – Blob: 19200000 et: 169
Riccardo Galli – TextEncoder: 19200000 et: 70
Size 64 * 10^6 bytes:
Lauri Oherd – URIEncoding: 64000000 et: 12565
lovasoa – charCode: 64000000 et: 138
fuweichin – charCode2: 64000000 et: 133
simap – Blob: 64000000 et: 231
Riccardo Galli – TextEncoder: 64000000 et: 211
Size 192 * 10^6 bytes:
URIEncoding methods freezes browser at this point.
lovasoa – charCode: 192000000 et: 754
fuweichin – charCode2: 192000000 et: 480
simap – Blob: 192000000 et: 701
Riccardo Galli – TextEncoder: 192000000 et: 654
Size 640 * 10^6 bytes:
lovasoa – charCode: 640000000 et: 2417
fuweichin – charCode2: 640000000 et: 1602
simap – Blob: 640000000 et: 2492
Riccardo Galli – TextEncoder: 640000000 et: 2338
Size 1280 * 10^6 bytes:
Blob & TextEncoder methods are starting to hit the wall here.
lovasoa – charCode: 1280000000 et: 4780
fuweichin – charCode2: 1280000000 et: 3177
simap – Blob: 1280000000 et: 6588
Riccardo Galli – TextEncoder: 1280000000 et: 5074
Size 1920 * 10^6 bytes:
lovasoa – charCode: 1920000000 et: 7465
fuweichin – charCode2: 1920000000 et: 4968
JavaScript error: file:///Users/xxx/Desktop/test.html, line 74: NS_ERROR_OUT_OF_MEMORY:
Here is the code:
function byteLengthURIEncoding(str) {
return encodeURI(str).split(/%..|./).length - 1;
}
function byteLengthCharCode(str) {
// returns the byte length of an utf8 string
var s = str.length;
for (var i=str.length-1; i>=0; i--) {
var code = str.charCodeAt(i);
if (code > 0x7f && code <= 0x7ff) s++;
else if (code > 0x7ff && code <= 0xffff) s+=2;
if (code >= 0xDC00 && code <= 0xDFFF) i--; //trail surrogate
}
return s;
}
function byteLengthCharCode2(s){
//assuming the String is UCS-2(aka UTF-16) encoded
var n=0;
for(var i=0,l=s.length; i<l; i++){
var hi=s.charCodeAt(i);
if(hi<0x0080){ //[0x0000, 0x007F]
n+=1;
}else if(hi<0x0800){ //[0x0080, 0x07FF]
n+=2;
}else if(hi<0xD800){ //[0x0800, 0xD7FF]
n+=3;
}else if(hi<0xDC00){ //[0xD800, 0xDBFF]
var lo=s.charCodeAt(++i);
if(i<l&&lo>=0xDC00&&lo<=0xDFFF){ //followed by [0xDC00, 0xDFFF]
n+=4;
}else{
throw new Error("UCS-2 String malformed");
}
}else if(hi<0xE000){ //[0xDC00, 0xDFFF]
throw new Error("UCS-2 String malformed");
}else{ //[0xE000, 0xFFFF]
n+=3;
}
}
return n;
}
function byteLengthBlob(str) {
return new Blob([str]).size;
}
function byteLengthTE(str) {
return (new TextEncoder().encode(str)).length;
}
var sample = "œ´®†¥¨ˆøp¬°??©ƒ?ßåO˜çv?˜µ=i";
var string = "";
// Adjust multiplier to change length of string.
let mult = 1000000;
for (var i = 0; i < mult; i++) {
string += sample;
}
let t0;
try {
t0 = Date.now();
console.log("Lauri Oherd – URIEncoding: " + byteLengthURIEncoding(string) + " et: " + (Date.now() - t0));
} catch(e) {}
t0 = Date.now();
console.log("lovasoa – charCode: " + byteLengthCharCode(string) + " et: " + (Date.now() - t0));
t0 = Date.now();
console.log("fuweichin – charCode2: " + byteLengthCharCode2(string) + " et: " + (Date.now() - t0));
t0 = Date.now();
console.log("simap – Blob: " + byteLengthBlob(string) + " et: " + (Date.now() - t0));
t0 = Date.now();
console.log("Riccardo Galli – TextEncoder: " + byteLengthTE(string) + " et: " + (Date.now() - t0));
How to download all files (but not HTML) from a website using wget?
You may try:
wget --user-agent=Mozilla --content-disposition --mirror --convert-links -E -K -p http://example.com/
Also you can add:
-A pdf,ps,djvu,tex,doc,docx,xls,xlsx,gz,ppt,mp4,avi,zip,rar
to accept the specific extensions, or to reject only specific extensions:
-R html,htm,asp,php
or to exclude the specific areas:
-X "search*,forum*"
If the files are ignored for robots (e.g. search engines), you've to add also: -e robots=off
change directory in batch file using variable
simple way to do this... here are the example
cd program files
cd poweriso
piso mount D:\<Filename.iso> <Virtual Drive>
Pause
this will mount the ISO image to the specific drive...use
Get Android API level of phone currently running my application
Integer.valueOf(android.os.Build.VERSION.SDK);
Values are:
Platform Version API Level
Android 9.0 28
Android 8.1 27
Android 8.0 26
Android 7.1 25
Android 7.0 24
Android 6.0 23
Android 5.1 22
Android 5.0 21
Android 4.4W 20
Android 4.4 19
Android 4.3 18
Android 4.2 17
Android 4.1 16
Android 4.0.3 15
Android 4.0 14
Android 3.2 13
Android 3.1 12
Android 3.0 11
Android 2.3.3 10
Android 2.3 9
Android 2.2 8
Android 2.1 7
Android 2.0.1 6
Android 2.0 5
Android 1.6 4
Android 1.5 3
Android 1.1 2
Android 1.0 1
CAUTION: don't use android.os.Build.VERSION.SDK_INT
if <uses-sdk android:minSdkVersion="3" />
.
You will get exception on all devices with Android 1.5 and lower because Build.VERSION.SDK_INT
is since SDK 4 (Donut 1.6).
How to get a value from a Pandas DataFrame and not the index and object type
import pandas as pd
dataset = pd.read_csv("data.csv")
values = list(x for x in dataset["column name"])
>>> values[0]
'item_0'
edit:
actually, you can just index the dataset like any old array.
import pandas as pd
dataset = pd.read_csv("data.csv")
first_value = dataset["column name"][0]
>>> print(first_value)
'item_0'
How to build an android library with Android Studio and gradle?
Note: This answer is a pure Gradle answer, I use this in IntelliJ on a regular basis but I don't know how the integration is with Android Studio. I am a believer in knowing what is going on for me, so this is how I use Gradle and Android.
TL;DR Full Example - https://github.com/ethankhall/driving-time-tracker/
Disclaimer: This is a project I am/was working on.
Gradle has a defined structure ( that you can change, link at the bottom tells you how ) that is very similar to Maven if you have ever used it.
Project Root
+-- src
| +-- main (your project)
| | +-- java (where your java code goes)
| | +-- res (where your res go)
| | +-- assets (where your assets go)
| | \-- AndroidManifest.xml
| \-- instrumentTest (test project)
| \-- java (where your java code goes)
+-- build.gradle
\-- settings.gradle
If you only have the one project, the settings.gradle file isn't needed. However you want to add more projects, so we need it.
Now let's take a peek at that build.gradle file. You are going to need this in it (to add the android tools)
build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.3'
}
}
Now we need to tell Gradle about some of the Android parts. It's pretty simple. A basic one (that works in most of my cases) looks like the following. I have a comment in this block, it will allow me to specify the version name and code when generating the APK.
build.gradle
apply plugin: "android"
android {
compileSdkVersion 17
/*
defaultConfig {
versionCode = 1
versionName = "0.0.0"
}
*/
}
Something we are going to want to add, to help out anyone that hasn't seen the light of Gradle yet, a way for them to use the project without installing it.
build.gradle
task wrapper(type: org.gradle.api.tasks.wrapper.Wrapper) {
gradleVersion = '1.4'
}
So now we have one project to build. Now we are going to add the others. I put them in a directory, maybe call it deps, or subProjects. It doesn't really matter, but you will need to know where you put it. To tell Gradle where the projects are you are going to need to add them to the settings.gradle.
Directory Structure:
Project Root
+-- src (see above)
+-- subProjects (where projects are held)
| +-- reallyCoolProject1 (your first included project)
| \-- See project structure for a normal app
| \-- reallyCoolProject2 (your second included project)
| \-- See project structure for a normal app
+-- build.gradle
\-- settings.gradle
settings.gradle:
include ':subProjects:reallyCoolProject1'
include ':subProjects:reallyCoolProject2'
The last thing you should make sure of is the subProjects/reallyCoolProject1/build.gradle has apply plugin: "android-library"
instead of apply plugin: "android"
.
Like every Gradle project (and Maven) we now need to tell the root project about it's dependency. This can also include any normal Java dependencies that you want.
build.gradle
dependencies{
compile 'com.fasterxml.jackson.core:jackson-core:2.1.4'
compile 'com.fasterxml.jackson.core:jackson-databind:2.1.4'
compile project(":subProjects:reallyCoolProject1")
compile project(':subProjects:reallyCoolProject2')
}
I know this seems like a lot of steps, but they are pretty easy once you do it once or twice. This way will also allow you to build on a CI server assuming you have the Android SDK installed there.
NDK Side Note: If you are going to use the NDK you are going to need something like below. Example build.gradle file can be found here: https://gist.github.com/khernyo/4226923
build.gradle
task copyNativeLibs(type: Copy) {
from fileTree(dir: 'libs', include: '**/*.so' ) into 'build/native-libs'
}
tasks.withType(Compile) { compileTask -> compileTask.dependsOn copyNativeLibs }
clean.dependsOn 'cleanCopyNativeLibs'
tasks.withType(com.android.build.gradle.tasks.PackageApplication) { pkgTask ->
pkgTask.jniDir new File('build/native-libs')
}
Sources:
- http://tools.android.com/tech-docs/new-build-system/user-guide
- https://gist.github.com/khernyo/4226923
- https://github.com/ethankhall/driving-time-tracker/
Groovy executing shell commands
command = "ls *"
def execute_state=sh(returnStdout: true, script: command)
but if the command failure the process will terminate
How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?
Copy the diff file to the root of your repository, and then do:
git apply yourcoworkers.diff
More information about the apply
command is available on its man page.
By the way: A better way to exchange whole commits by file is the combination of the commands git format-patch
on the sender and then git am
on the receiver, because it also transfers the authorship info and the commit message.
If the patch application fails and if the commits the diff was generated from are actually in your repo, you can use the -3
option of apply
that tries to merge in the changes.
It also works with Unix pipe as follows:
git diff d892531 815a3b5 | git apply
Using ZXing to create an Android barcode scanning app
Using Zxing this way requires a user to also install the barcode scanner app, which isn't ideal. What you probably want is to bundle Zxing into your app directly.
I highly recommend using this library: https://github.com/dm77/barcodescanner
It takes all the crazy build issues you're going to run into trying to integrate Xzing or Zbar directly. It uses those libraries under the covers, but wraps them in a very simple to use API.
How to remove unused C/C++ symbols with GCC and ld?
From the GCC 4.2.1 manual, section -fwhole-program
:
Assume that the current compilation unit represents whole program being compiled. All public functions and variables with the exception of main
and those merged by attribute externally_visible
become static functions and in a affect gets more aggressively optimized by interprocedural optimizers. While this option is equivalent to proper use of static
keyword for programs consisting of single file, in combination with option --combine
this flag can be used to compile most of smaller scale C programs since the functions and variables become local for the whole combined compilation unit, not for the single source file itself.
CXF: No message body writer found for class - automatically mapping non-simple resources
It isn't quite out of the box but CXF does support JSON bindings to rest services. See cxf jax-rs json docs here. You'll still need to do some minimal configuration to have the provider available and you need to be familiar with jettison if you want to have more control over how the JSON is formed.
EDIT: Per comment request, here is some code. I don't have a lot of experience with this but the following code worked as an example in a quick test system.
//TestApi parts
@GET
@Path ( "test" )
@Produces ( "application/json" )
public Demo getDemo () {
Demo d = new Demo ();
d.id = 1;
d.name = "test";
return d;
}
//client config for a TestApi interface
List providers = new ArrayList ();
JSONProvider jsonProvider = new JSONProvider ();
Map<String, String> map = new HashMap<String, String> ();
map.put ( "http://www.myserviceapi.com", "myapi" );
jsonProvider.setNamespaceMap ( map );
providers.add ( jsonProvider );
TestApi proxy = JAXRSClientFactory.create ( url, TestApi.class,
providers, true );
Demo d = proxy.getDemo ();
if ( d != null ) {
System.out.println ( d.id + ":" + d.name );
}
//the Demo class
@XmlRootElement ( name = "demo", namespace = "http://www.myserviceapi.com" )
@XmlType ( name = "demo", namespace = "http://www.myserviceapi.com",
propOrder = { "name", "id" } )
@XmlAccessorType ( XmlAccessType.FIELD )
public class Demo {
public String name;
public int id;
}
Notes:
- The providers list is where you code configure the JSON provider on the client. In particular, you see the namespace mapping. This needs to match what is on your server side configuration. I don't know much about Jettison options so I'm not much help on manipulating all of the various knobs for controlling the marshalling process.
- Jettison in CXF works by marshalling XML from a JAXB provider into JSON. So you have to ensure that the payload objects are all marked up (or otherwise configured) to marshall as application/xml before you can have them marshall as JSON. If you know of a way around this (other than writing your own message body writer), I'd love to hear about it.
- I use spring on the server so my configuration there is all xml stuff. Essentially, you need to go through the same process to add the JSONProvider to the service with the same namespace configuration. Don't have code for that handy but I imagine it will mirror the client side fairly well.
This is a bit dirty as an example but will hopefully get you going.
Edit2: An example of a message body writer that is based on xstream to avoid jaxb.
@Produces ( "application/json" )
@Consumes ( "application/json" )
@Provider
public class XstreamJsonProvider implements MessageBodyReader<Object>,
MessageBodyWriter<Object> {
@Override
public boolean isWriteable ( Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType ) {
return MediaType.APPLICATION_JSON_TYPE.equals ( mediaType )
&& type.equals ( Demo.class );
}
@Override
public long getSize ( Object t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType ) {
// I'm being lazy - should compute the actual size
return -1;
}
@Override
public void writeTo ( Object t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream )
throws IOException, WebApplicationException {
// deal with thread safe use of xstream, etc.
XStream xstream = new XStream ( new JettisonMappedXmlDriver () );
xstream.setMode ( XStream.NO_REFERENCES );
// add safer encoding, error handling, etc.
xstream.toXML ( t, entityStream );
}
@Override
public boolean isReadable ( Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType ) {
return MediaType.APPLICATION_JSON_TYPE.equals ( mediaType )
&& type.equals ( Demo.class );
}
@Override
public Object readFrom ( Class<Object> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream )
throws IOException, WebApplicationException {
// add error handling, etc.
XStream xstream = new XStream ( new JettisonMappedXmlDriver () );
return xstream.fromXML ( entityStream );
}
}
//now your client just needs this
List providers = new ArrayList ();
XstreamJsonProvider jsonProvider = new XstreamJsonProvider ();
providers.add ( jsonProvider );
TestApi proxy = JAXRSClientFactory.create ( url, TestApi.class,
providers, true );
Demo d = proxy.getDemo ();
if ( d != null ) {
System.out.println ( d.id + ":" + d.name );
}
The sample code is missing the parts for robust media type support, error handling, thread safety, etc. But, it ought to get you around the jaxb issue with minimal code.
EDIT 3 - sample server side configuration
As I said before, my server side is spring configured. Here is a sample configuration that works to wire in the provider:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:cxf="http://cxf.apache.org/core"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<jaxrs:server id="TestApi">
<jaxrs:serviceBeans>
<ref bean="testApi" />
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean id="xstreamJsonProvider" class="webtests.rest.XstreamJsonProvider" />
</jaxrs:providers>
</jaxrs:server>
<bean id="testApi" class="webtests.rest.TestApi">
</bean>
</beans>
I have also noted that in the latest rev of cxf that I'm using there is a difference in the media types, so the example above on the xstream message body reader/writer needs a quick modification where isWritable/isReadable change to:
return MediaType.APPLICATION_JSON_TYPE.getType ().equals ( mediaType.getType () )
&& MediaType.APPLICATION_JSON_TYPE.getSubtype ().equals ( mediaType.getSubtype () )
&& type.equals ( Demo.class );
EDIT 4 - non-spring configuration
Using your servlet container of choice, configure
org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet
with at least 2 init params of:
jaxrs.serviceClasses
jaxrs.providers
where the serviceClasses is a space separated list of the service implementations you want bound, such as the TestApi mentioned above and the providers is a space separated list of message body providers, such as the XstreamJsonProvider mentioned above. In tomcat you might add the following to web.xml:
<servlet>
<servlet-name>cxfservlet</servlet-name>
<servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class>
<init-param>
<param-name>jaxrs.serviceClasses</param-name>
<param-value>webtests.rest.TestApi</param-value>
</init-param>
<init-param>
<param-name>jaxrs.providers</param-name>
<param-value>webtests.rest.XstreamJsonProvider</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
That is pretty much the quickest way to run it without spring. If you are not using a servlet container, you would need to configure the JAXRSServerFactoryBean.setProviders with an instance of XstreamJsonProvider and set the service implementation via the JAXRSServerFactoryBean.setResourceProvider method. Check the CXFNonSpringJaxrsServlet.init method to see how they do it when setup in a servlet container.
That ought to get you going no matter your scenario.
window.location.reload with clear cache
In my case reload() doesn't work because the asp.net controls behavior. So, to solve this issue I've used this approach, despite seems a work around.
self.clear = function () {
//location.reload(true); Doesn't work to IE neither Firefox;
//also, hash tags must be removed or no postback will occur.
window.location.href = window.location.href.replace(/#.*$/, '');
};
Indexes of all occurrences of character in a string
This is a java 8 solution.
public int[] solution (String s, String subString){
int initialIndex = s.indexOf(subString);
List<Integer> indexList = new ArrayList<>();
while (initialIndex >=0){
indexList.add(initialIndex);
initialIndex = s.indexOf(subString, initialIndex+1);
}
int [] intA = indexList.stream().mapToInt(i->i).toArray();
return intA;
}
Wildcards in a Windows hosts file
We have this working using wildcard DNS in our local DNS server: add an A
record something like *.local -> 127.0.0.1
I think that your network settings will need to have the chosen domain suffix in the domain suffix search list for machines on the network, so you might want to replace .local
with your company's internal domain (e.g. .int
) and then add a subdomain like .localhost.int
to make it clear what it's for.
So *.localhost.int
would resolve to 127.0.0.1
for everybody on the network, and config file settings for all developers would "just work" if endpoints hang off that subdomain e.g. site1.localhost.int
, site2.localhost.int
This is pretty much the scheme we have introduced.
dnsmasq also looks nice, but I have not tried it yet:
http://ihaveabackup.net/2012/06/28/using-wildcards-in-the-hosts-file/
How to listen for changes to a MongoDB collection?
After 3.6 one is allowed to use database the following database triggers types:
- event-driven triggers - useful to update related documents automatically, notify downstream services, propagate data to support mixed workloads, data integrity & auditing
- scheduled triggers - useful for scheduled data retrieval, propagation, archival and analytics workloads
Log into your Atlas account and select Triggers
interface and add new trigger:
Expand each section for more settings or details.
What is exactly the base pointer and stack pointer? To what do they point?
Long time since I've done Assembly programming, but this link might be useful...
The processor has a collection of registers which are used to store data. Some of these are direct values while others are pointing to an area within RAM. Registers do tend to be used for certain specific actions and every operand in assembly will require a certain amount of data in specific registers.
The stack pointer is mostly used when you're calling other procedures. With modern compilers, a bunch of data will be dumped first on the stack, followed by the return address so the system will know where to return once it's told to return. The stack pointer will point at the next location where new data can be pushed to the stack, where it will stay until it's popped back again.
Base registers or segment registers just point to the address space of a large amount of data. Combined with a second regiser, the Base pointer will divide the memory in huge blocks while the second register will point at an item within this block. Base pointers therefor point to the base of blocks of data.
Do keep in mind that Assembly is very CPU specific. The page I've linked to provides information about different types of CPU's.
Find unused code
Resharper is good for this like others have stated. Be careful though, these tools don't find you code that is used by reflection, e.g. cannot know if some code is NOT used by reflection.
Difference between git checkout --track origin/branch and git checkout -b branch origin/branch
The two commands have the same effect (thanks to Robert Siemer’s answer for pointing it out).
The practical difference comes when using a local branch named differently:
git checkout -b mybranch origin/abranch
will create mybranch
and track origin/abranch
git checkout --track origin/abranch
will only create 'abranch
', not a branch with a different name.
(That is, as commented by Sebastian Graf, if the local branch did not exist already.
If it did, you would need git checkout -B abranch origin/abranch
)
Note: with Git 2.23 (Q3 2019), that would use the new command git switch
:
git switch -c <branch> --track <remote>/<branch>
If the branch exists in multiple remotes and one of them is named by the checkout.defaultRemote
configuration variable, we'll use that one for the purposes of disambiguation, even if the <branch>
isn't unique across all remotes.
Set it to e.g. checkout.defaultRemote=origin
to always checkout remote branches from there if <branch>
is ambiguous but exists on the 'origin' remote.
Here, '-c
' is the new '-b
'.
First, some background: Tracking means that a local branch has its upstream set to a remote branch:
# git config branch.<branch-name>.remote origin
# git config branch.<branch-name>.merge refs/heads/branch
git checkout -b branch origin/branch
will:
- create/reset
branch
to the point referenced by origin/branch
.
- create the branch
branch
(with git branch
) and track the remote tracking branch origin/branch
.
When a local branch is started off a remote-tracking branch, Git sets up the branch (specifically the branch.<name>.remote
and branch.<name>.merge
configuration entries) so that git pull
will appropriately merge from the remote-tracking branch.
This behavior may be changed via the global branch.autosetupmerge
configuration flag. That setting can be overridden by using the --track
and --no-track
options, and changed later using git branch --set-upstream-to
.
And git checkout --track origin/branch
will do the same as git branch --set-upstream-to
):
# or, since 1.7.0
git branch --set-upstream upstream/branch branch
# or, since 1.8.0 (October 2012)
git branch --set-upstream-to upstream/branch branch
# the short version remains the same:
git branch -u upstream/branch branch
It would also set the upstream for 'branch
'.
(Note: git1.8.0 will deprecate git branch --set-upstream
and replace it with git branch -u|--set-upstream-to
: see git1.8.0-rc1 announce)
Having an upstream branch registered for a local branch will:
- tell git to show the relationship between the two branches in
git status
and git branch -v
.
- directs
git pull
without arguments to pull from the upstream when the new branch is checked out.
See "How do you make an existing git branch track a remote branch?" for more.
Class is not abstract and does not override abstract method
Both classes Rectangle and Ellipse need to override both of the abstract methods.
To work around this, you have 3 options:
- Add the two methods
- Make each class that extends Shape abstract
Have a single method that does the function of the classes that will extend Shape, and override that method in Rectangle and Ellipse, for example:
abstract class Shape {
// ...
void draw(Graphics g);
}
And
class Rectangle extends Shape {
void draw(Graphics g) {
// ...
}
}
Finally
class Ellipse extends Shape {
void draw(Graphics g) {
// ...
}
}
And you can switch in between them, like so:
Shape shape = new Ellipse();
shape.draw(/* ... */);
shape = new Rectangle();
shape.draw(/* ... */);
Again, just an example.
How to unmount a busy device
Multiple mounts inside a folder
An additional reason could be a secondary mount inside your primary mount folder, e.g. after you worked on an SD card for an embedded device:
# mount /dev/sdb2 /mnt # root partition which contains /boot
# mount /dev/sdb1 /mnt/boot # boot partition
Unmounting /mnt will fail:
# umount /mnt
umount: /mnt: target is busy.
First we have to unmount the boot folder and then the root:
# umount /mnt/boot
# umount /mnt
x86 Assembly on a Mac
Don't forget that unlike Windows, all Unix based system need to have the source before destination unlike Windows
On Windows its:
mov $source , %destination
but on the Mac its the other way around.
How do I turn off Oracle password expiration?
To alter the password expiry policy for a certain user profile in Oracle first check which profile the user is using:
select profile from DBA_USERS where username = '<username>';
Then you can change the limit to never expire using:
alter profile <profile_name> limit password_life_time UNLIMITED;
If you want to previously check the limit you may use:
select resource_name,limit from dba_profiles where profile='<profile_name>';
How to plot time series in python
Convert your x-axis data from text to datetime.datetime
, use datetime.strptime
:
>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
datetime.datetime(2012, 5, 31, 19, 0)
This is an example of how to plot data once you have an array of datetimes:
import matplotlib.pyplot as plt
import datetime
import numpy as np
x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)
plt.plot(x,y)
plt.show()
Setting the correct PATH for Eclipse
Go to System Properties > Advanced > Enviroment Variables
and look under System variables
First, create/set your JAVA_HOME
variable
Even though Eclipse doesn't consult the JAVA_HOME
variable, it's still a good idea to set it. See How do I run Eclipse? for more information.
If you have not created and/or do not see JAVA_HOME
under the list of System variables
, do the following:
- Click
New...
at the very bottom
- For
Variable name
, type JAVA_HOME
exactly
- For
Variable value
, this could be different depending on what bits your computer and java are.
- If both your computer and java are 64-bit, type
C:\Program Files\Java\jdk1.8.0_60
- If both your computer and java are 32-bit, type
C:\Program Files\Java\jdk1.8.0_60
- If your computer is 64-bit, but your java is 32-bit, type
C:\Program Files (x86)\Java\jdk1.8.0_60
If you have created and/or do see JAVA_HOME
, do the following:
- Click on the row under
System variables
that you see JAVA_HOME
in
- Click
Edit...
at the very bottom
- For
Variable value
, change it to what was stated in #3 above based on java's and your computer's bits. To repeat:
- If both your computer and java are 64-bit, change it to
C:\Program Files\Java\jdk1.8.0_60
- If both your computer and java are 32-bit, change it to
C:\Program Files\Java\jdk1.8.0_60
- If your computer is 64-bit, but your java is 32-bit, change it to
C:\Program Files (x86)\Java\jdk1.8.0_60
Next, add to your PATH
variable
- Click on the row under
System variables
with PATH
in it
- Click
Edit...
at the very bottom
- If you have a newer version of windows:
- Click
New
- Type in
C:\Program Files (x86)\Java\jdk1.8.0_60
OR C:\Program Files\Java\jdk1.8.0_60
depending on the bits of your computer and java (see above ^).
- Press
Enter
and Click New
again.
- Type in
C:\Program Files (x86)\Java\jdk1.8.0_60\jre
OR C:\Program Files\Java\jdk1.8.0_60\jre
depending on the bits of your computer and java (see above again ^).
- Press
Enter
and press OK
on all of the related windows
- If you have an older version of windows
- In the
Variable value
textbox (or something similar) drag the cursor all the way to the very end
- Add a semicolon (
;
) if there isn't one already
C:\Program Files (x86)\Java\jdk1.8.0_60
OR C:\Program Files\Java\jdk1.8.0_60
- Add another semicolon (
;
)
C:\Program Files (x86)\Java\jdk1.8.0_60\jre
OR C:\Program Files\Java\jdk1.8.0_60\jre
Changing eclipse.ini
- Find your
eclipse.ini
file and copy-paste it in the same directory (should be named eclipse(1).ini
)
- Rename
eclipse.ini
to eclipse.ini.old
just in case something goes wrong
- Rename
eclipse(1).ini
to eclipse.ini
Open your newly-renamed eclipse.ini
and replace all of it with this:
-startup
plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.100.v20110502
-product
org.eclipse.epp.package.java.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vm
C:\Program Files\Java\jdk1.8.0_60\bin\javaw.exe
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx1024m
XXMaxPermSize
may be deprecated, so it might not work. If eclipse still does not launch, do the following:
- Delete the newer
eclipse.ini
- Rename
eclipse.ini.old
to eclipse.ini
- Open command prompt
- type in
eclipse -vm C:\Program Files (x86)\Java\jdk1.8.0_60\bin\javaw.exe
If the problem remains
Try updating your eclipse and java to the latest version. 8u60 (1.8.0_60
) is not the latest version of java. Sometimes, the latest version of java doesn't work with older versions of eclipse and vice versa. Otherwise, leave a comment if you're still having problems. You could also try a fresh reinstallation of Java.
Multiple Indexes vs Multi-Column Indexes
I agree with Cade Roux.
This article should get you on the right track:
One thing to note, clustered indexes should have a unique key (an identity column I would recommend) as the first column.
Basically it helps your data insert at the end of the index and not cause lots of disk IO and Page splits.
Secondly, if you are creating other indexes on your data and they are constructed cleverly they will be reused.
e.g. imagine you search a table on three columns
state, county, zip.
- you sometimes search by state only.
- you sometimes search by state and county.
- you frequently search by state, county, zip.
Then an index with state, county, zip. will be used in all three of these searches.
If you search by zip alone quite a lot then the above index will not be used (by SQL Server anyway) as zip is the third part of that index and the query optimiser will not see that index as helpful.
You could then create an index on Zip alone that would be used in this instance.
By the way We can take advantage of the fact that with Multi-Column indexing the first index column is always usable for searching and when you search only by 'state' it is efficient but yet not as efficient as Single-Column index on 'state'
I guess the answer you are looking for is that it depends on your where clauses of your frequently used queries and also your group by's.
The article will help a lot. :-)
How can change width of dropdown list?
The dropdown width itself cannot be set. It's width depend on the option-values. See also here ( jsfiddle.net/LgS3C/ )
How the select box looks like is also depending on your browser.
You can build your own control or use Select2
https://select2.org
Finding last occurrence of substring in string, replacing that
Naïve approach:
a = "A long string with a . in the middle ending with ."
fchar = '.'
rchar = '. -'
a[::-1].replace(fchar, rchar[::-1], 1)[::-1]
Out[2]: 'A long string with a . in the middle ending with . -'
Aditya Sihag's answer with a single rfind
:
pos = a.rfind('.')
a[:pos] + '. -' + a[pos+1:]
Force LF eol in git repo and working copy
Without a bit of information about what files are in your repository (pure source code, images, executables, ...), it's a bit hard to answer the question :)
Beside this, I'll consider that you're willing to default to LF as line endings in your working directory because you're willing to make sure that text files have LF line endings in your .git repository wether you work on Windows or Linux. Indeed better safe than sorry....
However, there's a better alternative: Benefit from LF line endings in your Linux workdir, CRLF line endings in your Windows workdir AND LF line endings in your repository.
As you're partially working on Linux and Windows, make sure core.eol
is set to native
and core.autocrlf
is set to true
.
Then, replace the content of your .gitattributes
file with the following
* text=auto
This will let Git handle the automagic line endings conversion for you, on commits and checkouts. Binary files won't be altered, files detected as being text files will see the line endings converted on the fly.
However, as you know the content of your repository, you may give Git a hand and help him detect text files from binary files.
Provided you work on a C based image processing project, replace the content of your .gitattributes
file with the following
* text=auto
*.txt text
*.c text
*.h text
*.jpg binary
This will make sure files which extension is c, h, or txt will be stored with LF line endings in your repo and will have native line endings in the working directory. Jpeg files won't be touched. All of the others will be benefit from the same automagic filtering as seen above.
In order to get a get a deeper understanding of the inner details of all this, I'd suggest you to dive into this very good post "Mind the end of your line" from Tim Clem, a Githubber.
As a real world example, you can also peek at this commit where those changes to a .gitattributes
file are demonstrated.
UPDATE to the answer considering the following comment
I actually don't want CRLF in my Windows directories, because my Linux environment is actually a VirtualBox sharing the Windows directory
Makes sense. Thanks for the clarification. In this specific context, the .gitattributes
file by itself won't be enough.
Run the following commands against your repository
$ git config core.eol lf
$ git config core.autocrlf input
As your repository is shared between your Linux and Windows environment, this will update the local config file for both environment. core.eol
will make sure text files bear LF line endings on checkouts. core.autocrlf
will ensure potential CRLF in text files (resulting from a copy/paste operation for instance) will be converted to LF in your repository.
Optionally, you can help Git distinguish what is a text file by creating a .gitattributes
file containing something similar to the following:
# Autodetect text files
* text=auto
# ...Unless the name matches the following
# overriding patterns
# Definitively text files
*.txt text
*.c text
*.h text
# Ensure those won't be messed up with
*.jpg binary
*.data binary
If you decided to create a .gitattributes
file, commit it.
Lastly, ensure git status
mentions "nothing to commit (working directory clean)", then perform the following operation
$ git checkout-index --force --all
This will recreate your files in your working directory, taking into account your config changes and the .gitattributes
file and replacing any potential overlooked CRLF in your text files.
Once this is done, every text file in your working directory WILL bear LF line endings and git status
should still consider the workdir as clean.
phonegap open link in browser
<a onclick="navigator.app.loadUrl('https://google.com/', { openExternal:true });">Link</a>
Works for me with android & PG 3.0
Angular 2 Scroll to bottom (Chat style)
In angular using material design sidenav I had to use the following:
let ele = document.getElementsByClassName('md-sidenav-content');
let eleArray = <Element[]>Array.prototype.slice.call(ele);
eleArray.map( val => {
val.scrollTop = val.scrollHeight;
});
How to get < span > value?
Try this
var div = document.getElementById("test");
var spans = div.getElementsByTagName("span");
for(i=0;i<spans.length;i++)
{
alert(spans[i].innerHTML);
}
Asynchronous Process inside a javascript for loop
JavaScript code runs on a single thread, so you cannot principally block to wait for the first loop iteration to complete before beginning the next without seriously impacting page usability.
The solution depends on what you really need. If the example is close to exactly what you need, @Simon's suggestion to pass i
to your async process is a good one.
getResourceAsStream returns null
Don't use absolute paths, make them relative to the 'resources' directory in your project. Quick and dirty code that displays the contents of MyTest.txt from the directory 'resources'.
@Test
public void testDefaultResource() {
// can we see default resources
BufferedInputStream result = (BufferedInputStream)
Config.class.getClassLoader().getResourceAsStream("MyTest.txt");
byte [] b = new byte[256];
int val = 0;
String txt = null;
do {
try {
val = result.read(b);
if (val > 0) {
txt += new String(b, 0, val);
}
} catch (IOException e) {
e.printStackTrace();
}
} while (val > -1);
System.out.println(txt);
}
ES6 export default with multiple functions referring to each other
tl;dr: baz() { this.foo(); this.bar() }
In ES2015 this construct:
var obj = {
foo() { console.log('foo') }
}
is equal to this ES5 code:
var obj = {
foo : function foo() { console.log('foo') }
}
exports.default = {}
is like creating an object, your default export translates to ES5 code like this:
exports['default'] = {
foo: function foo() {
console.log('foo');
},
bar: function bar() {
console.log('bar');
},
baz: function baz() {
foo();bar();
}
};
now it's kind of obvious (I hope) that baz
tries to call foo
and bar
defined somewhere in the outer scope, which are undefined. But this.foo
and this.bar
will resolve to the keys defined in exports['default']
object. So the default export referencing its own methods shold look like this:
export default {
foo() { console.log('foo') },
bar() { console.log('bar') },
baz() { this.foo(); this.bar() }
}
See babel repl transpiled code.
How to remove and clear all localStorage data
If you want to remove/clean all the values from local storage than use
localStorage.clear();
And if you want to remove the specific item from local storage than use the following code
localStorage.removeItem(key);
How do I show/hide a UIBarButtonItem?
Subclass UIBarButtonItem
.
Make sure the button in Interface Builder is set to HidableBarButtonItem
.
Make an outlet from the button to the view controller. From the view controller you can then hide/show the button by calling setHidden:
HidableBarButtonItem.h
#import <UIKit/UIKit.h>
@interface HidableBarButtonItem : UIBarButtonItem
@property (nonatomic) BOOL hidden;
@end
HidableBarButtonItem.m
#import "HidableBarButtonItem.h"
@implementation HidableBarButtonItem
- (void)setHidden:(BOOL const)hidden {
_hidden = hidden;
self.enabled = hidden ? YES : NO;
self.tintColor = hidden ? [UIApplication sharedApplication].keyWindow.tintColor : [UIColor clearColor];
}
@end
CSS filter: make color image with transparency white
You can use
filter: brightness(0) invert(1);
_x000D_
_x000D_
html {_x000D_
background: red;_x000D_
}_x000D_
p {_x000D_
float: left;_x000D_
max-width: 50%;_x000D_
text-align: center;_x000D_
}_x000D_
img {_x000D_
display: block;_x000D_
max-width: 100%;_x000D_
}_x000D_
.filter {_x000D_
-webkit-filter: brightness(0) invert(1);_x000D_
filter: brightness(0) invert(1);_x000D_
}
_x000D_
<p>_x000D_
Original:_x000D_
<img src="http://i.stack.imgur.com/jO8jP.gif" />_x000D_
</p>_x000D_
<p>_x000D_
Filter:_x000D_
<img src="http://i.stack.imgur.com/jO8jP.gif" class="filter" />_x000D_
</p>
_x000D_
_x000D_
_x000D_
First, brightness(0)
makes all image black, except transparent parts, which remain transparent.
Then, invert(1)
makes the black parts white.
React Native Responsive Font Size
I managed to overcome this by doing the following.
Pick the font size you like for the current view you have (Make sure
it looks good for the current device you are using in the
simulator).
import { Dimensions } from 'react-native'
and define the width
outside of the component like so: let width = Dimensions.get('window').width;
Now console.log(width) and write it down. If your good looking font
size is 15 and your width is 360 for example, then take 360 and
divide by 15 ( = 24). This is going to be the important value that
is going to adjust to different sizes.
Use this number in your styles object like so: textFontSize: { fontSize = width / 24 },...
Now you have a responsive fontSize.
conversion from string to json object android
Remove the slashes:
String json = {"phonetype":"N95","cat":"WP"};
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
How to reset Android Studio
From Linux this is what I did:
Remove the .AndroidStudioBeta folder:
rm -r ~/.AndroidStudioBeta
Remove the project folder. For example:
rm -r ~/AndroidStudioProjects
I needed to do both or stuff kept hanging around.
Hope this helps.
Elevating process privilege programmatically?
[PrincipalPermission(SecurityAction.Demand, Role = @"BUILTIN\Administrators")]
This will do it without UAC - no need to start a new process. If the running user is member of Admin group as for my case.
Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
If it is still not working after giving permissions try running these commands:
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
export PATH=~/.npm-global/bin:$PATH
source ~/.profile
and finally test with this command
npm install -g jshint
This does not work for Windows.
How do you fix a bad merge, and replay your good commits onto a fixed merge?
Please don't use this recipe if your situation is not the one described in the question. This recipe is for fixing a bad merge, and replaying your good commits onto a fixed merge.
Although filter-branch
will do what you want, it is quite a complex command and I would probably choose to do this with git rebase
. It's probably a personal preference. filter-branch
can do it in a single, slightly more complex command, whereas the rebase
solution is performing the equivalent logical operations one step at a time.
Try the following recipe:
# create and check out a temporary branch at the location of the bad merge
git checkout -b tmpfix <sha1-of-merge>
# remove the incorrectly added file
git rm somefile.orig
# commit the amended merge
git commit --amend
# go back to the master branch
git checkout master
# replant the master branch onto the corrected merge
git rebase tmpfix
# delete the temporary branch
git branch -d tmpfix
(Note that you don't actually need a temporary branch, you can do this with a 'detached HEAD', but you need to take a note of the commit id generated by the git commit --amend
step to supply to the git rebase
command rather than using the temporary branch name.)
Error Installing Homebrew - Brew Command Not Found
The warning is telling you what is wrong. The problem is that brew
is kept in /usr/local/bin
So, you can try /usr/local/bin/brew doctor
To fix it permanently alter your bash profile (.bashrc or .profile in your home directory) and add the following line:
export PATH=/usr/local/bin:$PATH
How to bind a List to a ComboBox?
public class Country
{
public string Name { get; set; }
public IList<City> Cities { get; set; }
public Country()
{
Cities = new List<City>();
}
}
public class City
{
public string Name { get; set; }
}
List<Country> Countries = new List<Country>
{
new Country
{
Name = "Germany",
Cities =
{
new City {Name = "Berlin"},
new City {Name = "Hamburg"}
}
},
new Country
{
Name = "England",
Cities =
{
new City {Name = "London"},
new City {Name = "Birmingham"}
}
}
};
bindingSource1.DataSource = Countries;
member_CountryComboBox.DataSource = bindingSource1.DataSource;
member_CountryComboBox.DisplayMember = "Name";
member_CountryCombo
Box.ValueMember = "Name";
This is the code I am using now.
sql server Get the FULL month name from a date
SELECT DATENAME(MONTH, GETDATE())
+ RIGHT(CONVERT(VARCHAR(12), GETDATE(), 107), 9) AS [Month DD, YYYY]
OR Date without Comma Between date and year, you can use the following
SELECT DATENAME(MONTH, GETDATE()) + ' ' + CAST(DAY(GETDATE()) AS VARCHAR(2))
+ ' ' + CAST(YEAR(GETDATE()) AS VARCHAR(4)) AS [Month DD YYYY]
JavaScript listener, "keypress" doesn't detect backspace?
The keypress
event might be different across browsers.
I created a Jsfiddle to compare keyboard events (using the JQuery shortcuts) on Chrome and Firefox. Depending on the browser you're using a keypress
event will be triggered or not -- backspace will trigger keydown/keypress/keyup
on Firefox but only keydown/keyup
on Chrome.
Single keyclick events triggered
on Chrome
keydown/keypress/keyup
when browser registers a keyboard input (keypress
is fired)
keydown/keyup
if no keyboard input (tested with alt, shift, backspace, arrow keys)
keydown
only for tab?
on Firefox
keydown/keypress/keyup
when browser registers a keyboard input but also for backspace, arrow keys, tab (so here keypress
is fired even with no input)
keydown/keyup
for alt, shift
This shouldn't be surprising because according to https://api.jquery.com/keypress/:
Note: as the keypress event isn't covered by any official
specification, the actual behavior encountered when using it may
differ across browsers, browser versions, and platforms.
The use of the keypress event type is deprecated by W3C (http://www.w3.org/TR/DOM-Level-3-Events/#event-type-keypress)
The keypress event type is defined in this specification for reference
and completeness, but this specification deprecates the use of this
event type. When in editing contexts, authors can subscribe to the
beforeinput event instead.
Finally, to answer your question, you should use keyup
or keydown
to detect a backspace across Firefox and Chrome.
Try it out on here:
_x000D_
_x000D_
$(".inputTxt").bind("keypress keyup keydown", function (event) {_x000D_
var evtType = event.type;_x000D_
var eWhich = event.which;_x000D_
var echarCode = event.charCode;_x000D_
var ekeyCode = event.keyCode;_x000D_
_x000D_
switch (evtType) {_x000D_
case 'keypress':_x000D_
$("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<br>");_x000D_
break;_x000D_
case 'keyup':_x000D_
$("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<p>");_x000D_
break;_x000D_
case 'keydown':_x000D_
$("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<br>");_x000D_
break;_x000D_
default:_x000D_
break;_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input class="inputTxt" type="text" />_x000D_
<div id="log"></div>
_x000D_
_x000D_
_x000D_
What are the best PHP input sanitizing functions?
It depends on the kind of data you are using. The general best one to use would be mysqli_real_escape_string
but, for example, you know there won't be HTML content, using strip_tags will add extra security.
You can also remove characters you know shouldn't be allowed.
List comprehension vs. lambda + filter
Curiously on Python 3, I see filter performing faster than list comprehensions.
I always thought that the list comprehensions would be more performant.
Something like:
[name for name in brand_names_db if name is not None]
The bytecode generated is a bit better.
>>> def f1(seq):
... return list(filter(None, seq))
>>> def f2(seq):
... return [i for i in seq if i is not None]
>>> disassemble(f1.__code__)
2 0 LOAD_GLOBAL 0 (list)
2 LOAD_GLOBAL 1 (filter)
4 LOAD_CONST 0 (None)
6 LOAD_FAST 0 (seq)
8 CALL_FUNCTION 2
10 CALL_FUNCTION 1
12 RETURN_VALUE
>>> disassemble(f2.__code__)
2 0 LOAD_CONST 1 (<code object <listcomp> at 0x10cfcaa50, file "<stdin>", line 2>)
2 LOAD_CONST 2 ('f2.<locals>.<listcomp>')
4 MAKE_FUNCTION 0
6 LOAD_FAST 0 (seq)
8 GET_ITER
10 CALL_FUNCTION 1
12 RETURN_VALUE
But they are actually slower:
>>> timeit(stmt="f1(range(1000))", setup="from __main__ import f1,f2")
21.177661532000116
>>> timeit(stmt="f2(range(1000))", setup="from __main__ import f1,f2")
42.233950221000214
Python - Module Not Found
After trying to add the path using:
pip show
on command prompt and using
sys.path.insert(0, "/home/myname/pythonfiles")
and didn't work. Also got SSL error when trying to install the module again using conda this time instead of pip.
I simply copied the module that wasn't found from the path "Mine was in
C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages
so I copied it to 'C:\Users\user\Anaconda3\Lib\site-packages'
How to remove unique key from mysql table
For those who don't know how to get index_name
which mentioned in Devart's answer, or key_name
which mentioned in Uday Sawant's answer, you can get it like this:
SHOW INDEX FROM table_name;
This will show all indexes for the given table, then you can pick name of the index or unique key that you want to remove.
How do I redirect in expressjs while passing some context?
I had to find another solution because none of the provided solutions actually met my requirements, for the following reasons:
Query strings: You may not want to use query strings because the URLs could be shared by your users, and sometimes the query parameters do not make sense for a different user. For example, an error such as ?error=sessionExpired
should never be displayed to another user by accident.
req.session: You may not want to use req.session
because you need the express-session dependency for this, which includes setting up a session store (such as MongoDB), which you may not need at all, or maybe you are already using a custom session store solution.
next(): You may not want to use next()
or next("router")
because this essentially just renders your new page under the original URL, it's not really a redirect to the new URL, more like a forward/rewrite, which may not be acceptable.
So this is my fourth solution that doesn't suffer from any of the previous issues. Basically it involves using a temporary cookie, for which you will have to first install cookie-parser. Obviously this means it will only work where cookies are enabled, and with a limited amount of data.
Implementation example:
var cookieParser = require("cookie-parser");
app.use(cookieParser());
app.get("/", function(req, res) {
var context = req.cookies["context"];
res.clearCookie("context", { httpOnly: true });
res.render("home.jade", context); // Here context is just a string, you will have to provide a valid context for your template engine
});
app.post("/category", function(req, res) {
res.cookie("context", "myContext", { httpOnly: true });
res.redirect("/");
}
How to convert a string or integer to binary in Ruby?
I asked a similar question. Based on @sawa's answer, the most succinct way to represent an integer in a string in binary format is to use the string formatter:
"%b" % 245
=> "11110101"
You can also choose how long the string representation to be, which might be useful if you want to compare fixed-width binary numbers:
1.upto(10).each { |n| puts "%04b" % n }
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
Accessing the index in 'for' loops?
Here's what you get when you're accessing index in for
loops:
for i in enumerate(items): print(i)
items = [8, 23, 45, 12, 78]
for i in enumerate(items):
print("index/value", i)
Result:
# index/value (0, 8)
# index/value (1, 23)
# index/value (2, 45)
# index/value (3, 12)
# index/value (4, 78)
for i, val in enumerate(items): print(i, val)
items = [8, 23, 45, 12, 78]
for i, val in enumerate(items):
print("index", i, "for value", val)
Result:
# index 0 for value 8
# index 1 for value 23
# index 2 for value 45
# index 3 for value 12
# index 4 for value 78
for i, val in enumerate(items): print(i)
items = [8, 23, 45, 12, 78]
for i, val in enumerate(items):
print("index", i)
Result:
# index 0
# index 1
# index 2
# index 3
# index 4
Filename too long in Git for Windows
You should be able to run the command
git config --system core.longpaths true
or add it to one of your Git configuration files manually to turn this functionality on, once you are on a supported version of Git. It looks like maybe 1.9.0 and after.
In Bootstrap 3,How to change the distance between rows in vertical?
There's a simply way of doing it.
You define for all the rows, except the first one, the following class with properties:
.not-first-row
{
position: relative;
top: -20px;
}
Then you apply the class to all non-first rows and adjust the negative top value to fit your desired row space. It's easy and works way better. :)
Hope it helped.
Freeze screen in chrome debugger / DevTools panel for popover inspection?
I tried the other solutions here, they work but I'm lazy so this is my solution
- hover over the element to trigger expanded state
- ctrl+shift+c
- hover over element again
- right click
- navigate to the debugger
by right clicking it no longer registers mouse event since a context menu pops up, so you can move the mouse away safely
What does the "at" (@) symbol do in Python?
@ symbol is also used to access variables inside a plydata / pandas dataframe query, pandas.DataFrame.query
.
Example:
df = pandas.DataFrame({'foo': [1,2,15,17]})
y = 10
df >> query('foo > @y') # plydata
df.query('foo > @y') # pandas
Select the first row by group
What about
DT <- data.table(test)
setkey(DT, id)
DT[J(unique(id)), mult = "first"]
Edit
There is also a unique method for data.tables
which will return the the first row by key
jdtu <- function() unique(DT)
I think, if you are ordering test
outside the benchmark, then you can removing the setkey
and data.table
conversion from the benchmark as well (as the setkey basically sorts by id, the same as order
).
set.seed(21)
test <- data.frame(id=sample(1e3, 1e5, TRUE), string=sample(LETTERS, 1e5, TRUE))
test <- test[order(test$id), ]
DT <- data.table(DT, key = 'id')
ju <- function() test[!duplicated(test$id),]
jdt <- function() DT[J(unique(id)),mult = 'first']
library(rbenchmark)
benchmark(ju(), jdt(), replications = 5)
## test replications elapsed relative user.self sys.self
## 2 jdt() 5 0.01 1 0.02 0
## 1 ju() 5 0.05 5 0.05 0
and with more data
** Edit with unique method**
set.seed(21)
test <- data.frame(id=sample(1e4, 1e6, TRUE), string=sample(LETTERS, 1e6, TRUE))
test <- test[order(test$id), ]
DT <- data.table(test, key = 'id')
test replications elapsed relative user.self sys.self
2 jdt() 5 0.09 2.25 0.09 0.00
3 jdtu() 5 0.04 1.00 0.05 0.00
1 ju() 5 0.22 5.50 0.19 0.03
The unique method is fastest here.
Binding a Button's visibility to a bool value in ViewModel
Generally there are two ways to do it, a converter class or a property in the Viewmodel that essentially converts the value for you.
I tend to use the property approach if it is a one off conversion. If you want to reuse it, use the converter. Below, find an example of the converter:
<ValueConversion(GetType(Boolean), GetType(Visibility))> _
Public Class BoolToVisibilityConverter
Implements IValueConverter
Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
If value IsNot Nothing Then
If value = True Then
Return Visibility.Visible
Else
Return Visibility.Collapsed
End If
Else
Return Visibility.Collapsed
End If
End Function
Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
Throw New NotImplementedException
End Function
End Class
A ViewModel property method would just check the boolean property value, and return a visibility based on that. Be sure to implement INotifyPropertyChanged and call it on both the Boolean and Visibility properties to updated properly.
Count the cells with same color in google spreadsheet
function countbackgrounds() {
var book = SpreadsheetApp.getActiveSpreadsheet();
var sheet = book.getActiveSheet();
var range_input = sheet.getRange("B3:B4");
var range_output = sheet.getRange("B6");
var cell_colors = range_input.getBackgroundColors();
var color = "#58FA58";
var count = 0;
for(var r = 0; r < cell_colors.length; r++) {
for(var c = 0; c < cell_colors[0].length; c++) {
if(cell_colors[r][c] == color) {
count = count + 1;
}
}
}
range_output.setValue(count);
}
Font scaling based on width of container
Use CSS Variables
No one has mentioned CSS variables yet, and this approach worked best for me, so:
Let's say you've got a column on your page that is 100% of the width of a mobile user's screen, but has a max-width
of 800px, so on desktop there's some space on either side of the column. Put this at the top of your page:
<script> document.documentElement.style.setProperty('--column-width', Math.min(window.innerWidth, 800)+'px'); </script>
And now you can use that variable (instead of the built-in vw
unit) to set the size of your font. E.g.
p {
font-size: calc( var(--column-width) / 100 );
}
It's not a pure CSS approach, but it's pretty close.
Get current category ID of the active page
I used this for breadcrums in the category template page:
$cat_obj = $wp_query->get_queried_object();
$thiscat_id = $cat_obj->term_id;
$thiscat = get_category($thiscat_id);
$parentcat = get_category($thiscat->parent);
How do I read all classes from a Java package in the classpath?
If you have Spring in you classpath then the following will do it.
Find all classes in a package that are annotated with XmlRootElement:
private List<Class> findMyTypes(String basePackage) throws IOException, ClassNotFoundException
{
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
List<Class> candidates = new ArrayList<Class>();
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
resolveBasePackage(basePackage) + "/" + "**/*.class";
Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
for (Resource resource : resources) {
if (resource.isReadable()) {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
if (isCandidate(metadataReader)) {
candidates.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
}
}
}
return candidates;
}
private String resolveBasePackage(String basePackage) {
return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage));
}
private boolean isCandidate(MetadataReader metadataReader) throws ClassNotFoundException
{
try {
Class c = Class.forName(metadataReader.getClassMetadata().getClassName());
if (c.getAnnotation(XmlRootElement.class) != null) {
return true;
}
}
catch(Throwable e){
}
return false;
}
Bootstrap 3 Flush footer to bottom. not fixed
For a pure CSS solution, scroll after the 2nd <hr>
. The first one is the initial answer (given back in 2016)
The major flaw of the solutions above is they have a fixed height for the footer.
And that just doesn't cut it in the real world, where people use a zillion number of devices and have this bad habit of rotating them when you least expect it and **Poof!** there goes your page content behind the footer!
In the real world, you need a function that calculates the height of the footer and dynamically adjusts the page content's padding-bottom
to accommodate that height.
And you need to run this tiny function on page load
and resize
events as well as on footer's DOMSubtreeModified
(just in case your footer gets dynamically updated asynchronously or it contains animated elements that change size when interacted with).
Here's a proof of concept, using jQuery v3.0.0
and Bootstrap v4-alpha
, but there is no reason why it shouldn't work on lower versions of each.
_x000D_
_x000D_
jQuery(document).ready(function($) {_x000D_
$.fn.accomodateFooter = function() {_x000D_
var footerHeight = $('footer').outerHeight();_x000D_
$(this).css({_x000D_
'padding-bottom': footerHeight + 'px'_x000D_
});_x000D_
}_x000D_
$('footer').on('DOMSubtreeModified', function() {_x000D_
$('body').accomodateFooter();_x000D_
})_x000D_
$(window).on('resize', function() {_x000D_
$('body').accomodateFooter();_x000D_
})_x000D_
$('body').accomodateFooter();_x000D_
window.addMoreContentToFooter = function() {_x000D_
var f = $('footer');_x000D_
f.append($('<p />', {_x000D_
text: "Human give me attention meow flop over sun bathe licks your face wake up wander around the house making large amounts of noise jump on top of your human's bed and fall asleep again. Throwup on your pillow sun bathe. The dog smells bad jump around on couch, meow constantly until given food, so nap all day, yet hiss at vacuum cleaner."_x000D_
}))_x000D_
.append($('<hr />'));_x000D_
}_x000D_
});
_x000D_
body {_x000D_
min-height: 100vh;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
footer {_x000D_
background-color: rgba(0, 0, 0, .65);_x000D_
color: white;_x000D_
position: absolute;_x000D_
bottom: 0;_x000D_
width: 100%;_x000D_
padding: 1.5rem;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
footer hr {_x000D_
border-top: 1px solid rgba(0, 0, 0, .42);_x000D_
border-bottom: 1px solid rgba(255, 255, 255, .21);_x000D_
}
_x000D_
<link href="http://v4-alpha.getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">_x000D_
<link href="http://v4-alpha.getbootstrap.com/examples/starter-template/starter-template.css" rel="stylesheet">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.2.0/js/tether.min.js"></script>_x000D_
<script src="http://v4-alpha.getbootstrap.com/dist/js/bootstrap.min.js"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse fixed-top">_x000D_
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">Navbar</a>_x000D_
_x000D_
<div class="collapse navbar-collapse" id="navbarsExampleDefault">_x000D_
<ul class="navbar-nav mr-auto">_x000D_
<li class="nav-item active">_x000D_
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link disabled" href="#">Disabled</a>_x000D_
</li>_x000D_
<li class="nav-item dropdown">_x000D_
<a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a>_x000D_
<div class="dropdown-menu" aria-labelledby="dropdown01">_x000D_
<a class="dropdown-item" href="#">Action</a>_x000D_
<a class="dropdown-item" href="#">Another action</a>_x000D_
<a class="dropdown-item" href="#">Something else here</a>_x000D_
</div>_x000D_
</li>_x000D_
</ul>_x000D_
<form class="form-inline my-2 my-lg-0">_x000D_
<input class="form-control mr-sm-2" type="text" placeholder="Search">_x000D_
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>_x000D_
</form>_x000D_
</div>_x000D_
</nav>_x000D_
_x000D_
<div class="container">_x000D_
<div class="starter-template">_x000D_
<h1>Feed that footer - not a game (yet!)</h1>_x000D_
<p class="lead">You will notice the body bottom padding is growing to accomodate the height of the footer as you feed it (so the page contents do not get covered by it).</p><button class="btn btn-warning" onclick="window.addMoreContentToFooter()">Feed that footer</button>_x000D_
<hr />_x000D_
<blockquote class="lead"><strong>Note:</strong> I used jQuery <code>v3.0.0</code> and Bootstrap <code>v4-alpha</code> but there is no reason why it shouldn't work with lower versions of each.</blockquote>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<footer>I am a footer with dynamic content._x000D_
<hr />_x000D_
</footer>
_x000D_
_x000D_
_x000D_
Initially, I have posted this solution here but I realized it might help more people if posted under this question.
Note: I have purposefully wrapped the $([selector]).accomodateFooter()
as a jQuery plugin, so it could be run on any DOM element, as in most layouts it is not the $('body')
's bottom-padding
that needs adjusting, but some page wrapper element with position:relative
(usually the immediate parent of the footer
).
Later edit (3+ years after initial answer):
At this point I no longer consider acceptable using JavaScript for positioning a dynamic content footer at the bottom of the page. It can be achieved with CSS alone, using flexbox, lightning fast, cross-browser.
Here it is:
_x000D_
_x000D_
// Left this in so you could inject content into the footer and test it:_x000D_
// (but it's no longer sizing the footer)_x000D_
_x000D_
function addMoreContentToFooter() {_x000D_
var f = $('footer');_x000D_
f.append($('<p />', {_x000D_
text: "Human give me attention meow flop over sun bathe licks your face wake up wander around the house making large amounts of noise jump on top of your human's bed and fall asleep again. Throwup on your pillow sun bathe. The dog smells bad jump around on couch, meow constantly until given food, so nap all day, yet hiss at vacuum cleaner."_x000D_
}))_x000D_
.append($('<hr />'));_x000D_
}
_x000D_
.wrapper {_x000D_
min-height: 100vh;_x000D_
padding-top: 54px;_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
}_x000D_
_x000D_
.wrapper>* {_x000D_
flex-grow: 0;_x000D_
}_x000D_
_x000D_
.wrapper>main {_x000D_
flex-grow: 1;_x000D_
}_x000D_
_x000D_
footer {_x000D_
background-color: rgba(0, 0, 0, .65);_x000D_
color: white;_x000D_
width: 100%;_x000D_
padding: 1.5rem;_x000D_
}_x000D_
_x000D_
footer hr {_x000D_
border-top: 1px solid rgba(0, 0, 0, .42);_x000D_
border-bottom: 1px solid rgba(255, 255, 255, .21);_x000D_
}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="wrapper">_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top">_x000D_
<a class="navbar-brand" href="#">Navbar</a>_x000D_
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
_x000D_
<div class="collapse navbar-collapse" id="navbarSupportedContent">_x000D_
<ul class="navbar-nav mr-auto">_x000D_
<li class="nav-item active">_x000D_
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li>_x000D_
<li class="nav-item dropdown">_x000D_
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
Dropdown_x000D_
</a>_x000D_
<div class="dropdown-menu" aria-labelledby="navbarDropdown">_x000D_
<a class="dropdown-item" href="#">Action</a>_x000D_
<a class="dropdown-item" href="#">Another action</a>_x000D_
<div class="dropdown-divider"></div>_x000D_
<a class="dropdown-item" href="#">Something else here</a>_x000D_
</div>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>_x000D_
</li>_x000D_
</ul>_x000D_
<form class="form-inline my-2 my-lg-0">_x000D_
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">_x000D_
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>_x000D_
</form>_x000D_
</div>_x000D_
</nav>_x000D_
<main>_x000D_
<div class="container">_x000D_
<div class="starter-template">_x000D_
<h1>Feed that footer - not a game (yet!)</h1>_x000D_
<p class="lead">Footer won't ever cover the body contents, as its not fixed. It's simply placed at the bottom when the page should be shorter using `min-height:100vh` on container and using flexbox to push it down.</p><button class="btn btn-warning" onclick="addMoreContentToFooter()">Feed that footer</button>_x000D_
<hr />_x000D_
<blockquote class="lead">_x000D_
<strong>Note:</strong> This example uses current latest versions of jQuery (<code>3.4.1.slim</code>) and Bootstrap (<code>4.4.1</code>) (unlike the one above)._x000D_
</blockquote>_x000D_
</div>_x000D_
</div>_x000D_
</main>_x000D_
<footer>I am a footer with dynamic content._x000D_
<hr />_x000D_
</footer>_x000D_
</div>
_x000D_
_x000D_
_x000D_
PHP Fatal error: Using $this when not in object context
If you are invoking foobarfunc
with resolution scope operator (::
), then you are calling it statically, e.g. on the class level instead of the instance level, thus you are using $this
when not in object context. $this
does not exist in class context.
If you enable E_STRICT
, PHP will raise a Notice about this:
Strict Standards:
Non-static method foobar::foobarfunc() should not be called statically
Do this instead
$fb = new foobar;
echo $fb->foobarfunc();
On a sidenote, I suggest not to use global
inside your classes. If you need something from outside inside your class, pass it through the constructor. This is called Dependency Injection and it will make your code much more maintainable and less dependant on outside things.
Why doesn't git recognize that my file has been changed, therefore git add not working
TL;DR; Are you even on the correct repository?
My story is bit funny but I thought it can happen with someone who might be having a similar scenario so sharing it here.
Actually on my machine, I had two separate git repositories repo1
and repo2
configured in the same root directory named source
. These two repositories are essentially the repositories of two products I work off and on in my company. Now the thing is that as a standard guideline, the directory structure of source code of all the products is exactly the same in my company.
So without realizing I modified an exactly same named file in repo2
which I was supposed to change in repo1
. So, I just kept running command git status
on repo1
and it kept giving the same message
On branch master
nothing to commit, working directory clean
for half an hour. Then colleague of mine observed it as independent pair of eyes and brought this thing to my notice that I was in wrong but very similar looking repository. The moment I switched to repo1
Git started noticing the changed files.
Not so common case. But you never know!
How to convert AAR to JAR
The 'aar' bundle is the binary distribution of an Android Library Project. .aar file
consists a JAR file and some resource files. You can convert it
as .jar file using this steps
1) Copy the .aar file in a separate folder and Rename the .aar file to .zip file using
any winrar or zip Extractor software.
2) Now you will get a .zip file. Right click on the .zip file and select "Extract files".
Will get a folder which contains "classes.jar, resource, manifest, R.java,
proguard(optional), libs(optional), assets(optional)".
3) Rename the classes.jar file as yourjarfilename.jar and use this in your project.
Note: If you want to get only .jar file from your .aar file use the
above way.
Suppose If you want to include the manifest.xml and resources with your .jar file means
you can just right click on your .aar file and save it as .jar file directly instead of
saving it as a .zip. To view the .jar file which you have extracted, download JD-GUI(Java Decompiler). Then drag and drop your .jar file into this JD_GUI, you can see the .class file in readable formats like a .java file.
java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?
From the documentation of SimpleDateFormat:
Letter Date or Time Component Presentation Examples
S Millisecond Number 978
So it is milliseconds, or 1/1000th of a second. You just format it with on 6 digits, so you add 3 extra leading zeroes...
You can check it this way:
Date d =new Date();
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(d));
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS").format(d));
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(d));
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS").format(d));
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSS").format(d));
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").format(d));
Output:
2013-10-07 12:13:27.132
2013-10-07 12:13:27.132
2013-10-07 12:13:27.132
2013-10-07 12:13:27.0132
2013-10-07 12:13:27.00132
2013-10-07 12:13:27.000132
(Ideone fiddle)
Combine Date and Time columns using python pandas
I don't have enough reputation to comment on jka.ne so:
I had to amend jka.ne's line for it to work:
df.apply(lambda r : pd.datetime.combine(r['date_column_name'],r['time_column_name']).time(),1)
This might help others.
Also, I have tested a different approach, using replace
instead of combine
:
def combine_date_time(df, datecol, timecol):
return df.apply(lambda row: row[datecol].replace(
hour=row[timecol].hour,
minute=row[timecol].minute),
axis=1)
which in the OP's case would be:
combine_date_time(df, 'Date', 'Time')
I have timed both approaches for a relatively large dataset (>500.000 rows), and they both have similar runtimes, but using combine
is faster (59s for replace
vs 50s for combine
).
How to resolve 'unrecognized selector sent to instance'?
How are you importing ClassA into your AppDelegate Class? Did you include the .h file in the main project? I had this problem for a while because I didn't copy the header file into the main project as well as the normal #include "ClassA.h."
Copying, or creating the .h solved it for me.
Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"
I think you can get this error if your database model is not correct and the underlying data contains a null which the model is attempting to map to a non-null object.
For example, some auto-generated models can attempt to map nvarchar(1) columns to char rather than string and hence if this column contains nulls it will throw an error when you attempt to access the data.
Note, LinqPad has a compatibility option if you want it to generate a model like that, but probably doesn't do this by default, which might explain it doesn't give you the error.
Is the MIME type 'image/jpg' the same as 'image/jpeg'?
tl;dr the "standards" are a hodge-podge mess; it depends who you ask!
Overall, there appears to be no MIME type image/jpg
. Yet, in practice, nearly all software handles image files named "*.jpg
" just fine.
This particular topic is confusing because the varying association of file name extension associated to a MIME type depends which organization created the table of file name extensions to MIME types. In other words, file name extension .jpg
could be many different things.
For example, here are three "complete lists" and one RFC that with varying JPEG Image format file name extensions and the associated MIME types.
- sitepoint.com mime-types-complete-list (archived)
.jfif
, .jfif-tbnl
, .jpe
, .jpeg
, .jpg
? image/jpeg
.jfif
, .jpe
, .jpeg
, .jpg
? image/pjpeg
- freeformatter.com mime-types (archived)
.jpeg
, .jpg
? image/jpeg
.jpeg
, .jpg
? image/x-citrix-jpeg
.pjpeg
? image/pjpeg
- IANA "Media Types" (formerly known as MIME types) lists (archived)
(this document lists "names", not "file name extensions")
jpg
not mentioned
jpeg
? see RFC 2045 (no mention), see RFC 2046 ? image/jpeg
13
JPEG
? video/JPEG
jpeg2000
? video/jpeg2000
jpm
? image/jpm
(JPEG 2000)
jpx
? image/jpx
(JPEG 2000)
vnd.sealedmedia.softseal.jpg
? image/vnd.sealedmedia.softseal.jpg
- RFC 3745 MIME Type Registrations for JPEG 2000 (ISO/IEC 15444)
.jpg
file extension not mentioned
.jpeg
file extension not mentioned
.jp2
, .jpg2
? image/jp2
(JPEG 2000)9
.jpf
, .jpx
? image/jpx
(JPEG 2000 ISO-JPEG2000-2 encoded image data)10
.mj2
, .mjp2
? video/mj2
(Motion JPEG 2000)11
.jpm
, .jpgm
? image/jpm
(JPEG 2000 profiles and
extensions)12
These "complete lists" and RFC do not have MIME type image/jpg
! But for MIME type image/jpeg
some lists do have varying file name extensions (.jpeg
, .jpg
, …). Other lists do not mention image/jpeg
.
Also, there are different types of JPEG Image formats (e.g. Progressive JPEG Image format, JPEG 2000, etcetera) and "JPEG Extensions" that may or may not overlap in file name extension and declared MIME type.
Another confusing thing is RFC 3745 does not appear to match IANA Media Types yet the same RFC is supposed to inform the IANA Media Types document. For example, in RFC 3745 .jpf
is preferred file extension for image/jpx
but in IANA Media Types the name jpf
is not present (and that IANA document references RFC 3745!).
Another confusing thing is IANA Media Types lists "names" but does not list "file name extensions". This is on purpose, but confuses the endeavor of mapping file name extensions to MIME types.
Another confusing thing: is it "mime", or "MIME", or "MIME type", or "mime type", or "mime/type", or "media type"?
The most official seeming document by IANA is surprisingly inadequate. No MIME type is registered for file extension .jpg
yet there exists the odd vnd.sealedmedia.softseal.jpg
. File extension.JPEG
is only known as a video
type while file extension .jpeg
is an image type (when did lowercase and uppercase letters start mattering!?). At the same time, jpeg2000
is type video
yet RFC 3745 considers JPEG 2000 an image
type! The IANA list seems to cater to company-specific jpeg formats (e.g. vnd.sealedmedia.softseal.jpg
).
In summary...
Because of the prior confusions, it is difficult to find an industry-accepted canonical document that maps file name extensions to MIME types, particularly for the JPEG Image File Format.
Related question "List of ALL MimeTypes on the Planet, mapped to File Extensions?".
onMeasure custom view explanation
onMeasure()
is your opportunity to tell Android how big you want your custom view to be dependent the layout constraints provided by the parent; it is also your custom view's opportunity to learn what those layout constraints are (in case you want to behave differently in a match_parent
situation than a wrap_content
situation). These constraints are packaged up into the MeasureSpec
values that are passed into the method. Here is a rough correlation of the mode values:
- EXACTLY means the
layout_width
or layout_height
value was set to a specific value. You should probably make your view this size. This can also get triggered when match_parent
is used, to set the size exactly to the parent view (this is layout dependent in the framework).
- AT_MOST typically means the
layout_width
or layout_height
value was set to match_parent
or wrap_content
where a maximum size is needed (this is layout dependent in the framework), and the size of the parent dimension is the value. You should not be any larger than this size.
- UNSPECIFIED typically means the
layout_width
or layout_height
value was set to wrap_content
with no restrictions. You can be whatever size you would like. Some layouts also use this callback to figure out your desired size before determine what specs to actually pass you again in a second measure request.
The contract that exists with onMeasure()
is that setMeasuredDimension()
MUST be called at the end with the size you would like the view to be. This method is called by all the framework implementations, including the default implementation found in View
, which is why it is safe to call super
instead if that fits your use case.
Granted, because the framework does apply a default implementation, it may not be necessary for you to override this method, but you may see clipping in cases where the view space is smaller than your content if you do not, and if you lay out your custom view with wrap_content
in both directions, your view may not show up at all because the framework doesn't know how large it is!
Generally, if you are overriding View
and not another existing widget, it is probably a good idea to provide an implementation, even if it is as simple as something like this:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desiredWidth = 100;
int desiredHeight = 100;
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
//Measure Width
if (widthMode == MeasureSpec.EXACTLY) {
//Must be this size
width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
width = Math.min(desiredWidth, widthSize);
} else {
//Be whatever you want
width = desiredWidth;
}
//Measure Height
if (heightMode == MeasureSpec.EXACTLY) {
//Must be this size
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
height = Math.min(desiredHeight, heightSize);
} else {
//Be whatever you want
height = desiredHeight;
}
//MUST CALL THIS
setMeasuredDimension(width, height);
}
Hope that Helps.
Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>
The IEnumerable<T>
interface does not include an indexer, you're probably confusing it with IList<T>
If the object really is an IList<T>
(e.g. List<T>
or an array T[]
), try making the reference to it of type IList<T>
too.
Otherwise, you can use myEnumerable.ElementAt(index)
which uses the Enumerable.ElementAt extension method. This should work for all IEnumerable<T>
s .
Note that unless the (run-time) object implements IList<T>
, this will cause all of the first index + 1
items to be enumerated, with all but the last being discarded.
EDIT:
As an explanation, IEnumerable<T>
is simply an interface that represents "that which exposes an enumerator." A concrete implementation may well be some sort of in-memory list that does allow fast-access by index, or it may not. For instance, it could be a collection that cannot efficiently satisfy such a query, such as a linked-list (as mentioned by James Curran). It may even be no sort of in-memory data-structure at all, such as an iterator, where items are generated ('yielded') on demand, or by an enumerator that fetches the items from some remote data-source. Because IEnumerable<T>
must support all these cases, indexers are excluded from its definition.
How to convert seconds to time format?
1 day = 86400000 milliseconds.
DecodeTime(milliseconds/86400000,hr,min,sec,msec)
Ups! I was thinking in delphi, there must be something similar in all languages.
How to get file name from file path in android
Final working solution:
public static String getFileName(Uri uri) {
try {
String path = uri.getLastPathSegment();
return path != null ? path.substring(path.lastIndexOf("/") + 1) : "unknown";
} catch (Exception e) {
e.printStackTrace();
}
return "unknown";
}
Escape double quotes for JSON in Python
i know this question is old, but hopefully it will help someone.
i found a great plugin for those who are using PyCharm IDE:
string-manipulation
that can easily escape double quotes (and many more...), this plugin is great for cases where you know what the string going to be.
for other cases, using json.dumps(string)
will be the recommended solution
str_to_escape = 'my string with "double quotes" blablabla'
after_escape = 'my string with \"double quotes\" blablabla'
Keyboard shortcuts with jQuery
There is a new version of hotKeys.js that works with 1.10+ version of jQuery. It is small, 100 line javascript file. 4kb or just 2kb minified. Here are some Simple usage examples are :
$('#myBody').hotKey({ key: 'c', modifier: 'alt' }, doSomething);
$('#myBody').hotKey({ key: 'f4' }, doSomethingElse);
$('#myBody').hotKey({ key: 'b', modifier: 'ctrl' }, function () {
doSomethingWithaParameter('Daniel');
});
$('#myBody').hotKey({ key: 'd', modifier :'shift' }, doSomethingCool);
Clone the repo from github : https://github.com/realdanielbyrne/HoyKeys.git
or go to the github repo page https://github.com/realdanielbyrne/HoyKeys or fork and contribute.
Message Queue vs. Web Services?
Message queues are ideal for requests which may take a long time to process. Requests are queued and can be processed offline without blocking the client. If the client needs to be notified of completion, you can provide a way for the client to periodically check the status of the request.
Message queues also allow you to scale better across time. It improves your ability to handle bursts of heavy activity, because the actual processing can be distributed across time.
Note that message queues and web services are orthogonal concepts, i.e. they are not mutually exclusive. E.g. you can have a XML based web service which acts as an interface to a message queue. I think the distinction your looking for is Message Queues versus Request/Response, the latter is when the request is processed synchronously.
How to send a model in jQuery $.ajax() post request to MVC controller method
If you need to send the FULL model to the controller, you first need the model to be available to your javascript code.
In our app, we do this with an extension method:
public static class JsonExtensions
{
public static string ToJson(this Object obj)
{
return new JavaScriptSerializer().Serialize(obj);
}
}
On the view, we use it to render the model:
<script type="javascript">
var model = <%= Model.ToJson() %>
</script>
You can then pass the model variable into your $.ajax call.
Github: error cloning my private repository
On Windows using msysgit I had this error and the cause was my additions of our corporate proxy certificates.
If you edit your curl-ca-bundle.crt you have to get sure about your lineendings. In case of the curl-ca-bundle you have to use Linux-Style lineendings.
> git ls-remote --tags --heads https://github.com/oblador/angular-scroll.git
fatal: unable to access 'https://github.com/oblador/angular-scroll.git/': error setting certificate verify locations:
CAfile: C:\Program Files (x86)\Git\bin\curl-ca-bundle.crt
CApath: none
You can use notepad++ to convert the lineendings to Linux (linefeed).
Getting the array length of a 2D array in Java
Consider
public static void main(String[] args) {
int[][] foo = new int[][] {
new int[] { 1, 2, 3 },
new int[] { 1, 2, 3, 4},
};
System.out.println(foo.length); //2
System.out.println(foo[0].length); //3
System.out.println(foo[1].length); //4
}
Column lengths differ per row. If you're backing some data by a fixed size 2D array, then provide getters to the fixed values in a wrapper class.
How can I fix MySQL error #1064?
TL;DR
Error #1064 means that MySQL can't understand your command. To fix it:
Read the error message. It tells you exactly where in your command MySQL got confused.
Examine your command. If you use a programming language to create your command, use echo
, console.log()
, or its equivalent to show the entire command so you can see it.
Check the manual. By comparing against what MySQL expected at that point, the problem is often obvious.
Check for reserved words. If the error occurred on an object identifier, check that it isn't a reserved word (and, if it is, ensure that it's properly quoted).
Aaaagh!! What does #1064 mean?
Error messages may look like gobbledygook, but they're (often) incredibly informative and provide sufficient detail to pinpoint what went wrong. By understanding exactly what MySQL is telling you, you can arm yourself to fix any problem of this sort in the future.
As in many programs, MySQL errors are coded according to the type of problem that occurred. Error #1064 is a syntax error.
What is this "syntax" of which you speak? Is it witchcraft?
Whilst "syntax" is a word that many programmers only encounter in the context of computers, it is in fact borrowed from wider linguistics. It refers to sentence structure: i.e. the rules of grammar; or, in other words, the rules that define what constitutes a valid sentence within the language.
For example, the following English sentence contains a syntax error (because the indefinite article "a" must always precede a noun):
This sentence contains syntax error a.
What does that have to do with MySQL?
Whenever one issues a command to a computer, one of the very first things that it must do is "parse" that command in order to make sense of it. A "syntax error" means that the parser is unable to understand what is being asked because it does not constitute a valid command within the language: in other words, the command violates the grammar of the programming language.
It's important to note that the computer must understand the command before it can do anything with it. Because there is a syntax error, MySQL has no idea what one is after and therefore gives up before it even looks at the database and therefore the schema or table contents are not relevant.
How do I fix it?
Obviously, one needs to determine how it is that the command violates MySQL's grammar. This may sound pretty impenetrable, but MySQL is trying really hard to help us here. All we need to do is…
Read the message!
MySQL not only tells us exactly where the parser encountered the syntax error, but also makes a suggestion for fixing it. For example, consider the following SQL command:
UPDATE my_table WHERE id=101 SET name='foo'
That command yields the following error message:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id=101 SET name='foo'' at line 1
MySQL is telling us that everything seemed fine up to the word WHERE
, but then a problem was encountered. In other words, it wasn't expecting to encounter WHERE
at that point.
Messages that say ...near '' at line...
simply mean that the end of command was encountered unexpectedly: that is, something else should appear before the command ends.
Examine the actual text of your command!
Programmers often create SQL commands using a programming language. For example a php program might have a (wrong) line like this:
$result = $mysqli->query("UPDATE " . $tablename ."SET name='foo' WHERE id=101");
If you write this this in two lines
$query = "UPDATE " . $tablename ."SET name='foo' WHERE id=101"
$result = $mysqli->query($query);
then you can add echo $query;
or var_dump($query)
to see that the query actually says
UPDATE userSET name='foo' WHERE id=101
Often you'll see your error immediately and be able to fix it.
Obey orders!
MySQL is also recommending that we "check the manual that corresponds to our MySQL version for the right syntax to use". Let's do that.
I'm using MySQL v5.6, so I'll turn to that version's manual entry for an UPDATE
command. The very first thing on the page is the command's grammar (this is true for every command):
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
The manual explains how to interpret this syntax under Typographical and Syntax Conventions, but for our purposes it's enough to recognise that: clauses contained within square brackets [
and ]
are optional; vertical bars |
indicate alternatives; and ellipses ...
denote either an omission for brevity, or that the preceding clause may be repeated.
We already know that the parser believed everything in our command was okay prior to the WHERE
keyword, or in other words up to and including the table reference. Looking at the grammar, we see that table_reference
must be followed by the SET
keyword: whereas in our command it was actually followed by the WHERE
keyword. This explains why the parser reports that a problem was encountered at that point.
A note of reservation
Of course, this was a simple example. However, by following the two steps outlined above (i.e. observing exactly where in the command the parser found the grammar to be violated and comparing against the manual's description of what was expected at that point), virtually every syntax error can be readily identified.
I say "virtually all", because there's a small class of problems that aren't quite so easy to spot—and that is where the parser believes that the language element encountered means one thing whereas you intend it to mean another. Take the following example:
UPDATE my_table SET where='foo'
Again, the parser does not expect to encounter WHERE
at this point and so will raise a similar syntax error—but you hadn't intended for that where
to be an SQL keyword: you had intended for it to identify a column for updating! However, as documented under Schema Object Names:
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it. (Exception: A reserved word that follows a period in a qualified name must be an identifier, so it need not be quoted.) Reserved words are listed at Section 9.3, “Keywords and Reserved Words”.
[ deletia ]
The identifier quote character is the backtick (“`
”):
mysql> SELECT * FROM `select` WHERE `select`.id > 100;
If the ANSI_QUOTES
SQL mode is enabled, it is also permissible to quote identifiers within double quotation marks:
mysql> CREATE TABLE "test" (col INT);
ERROR 1064: You have an error in your SQL syntax...
mysql> SET sql_mode='ANSI_QUOTES';
mysql> CREATE TABLE "test" (col INT);
Query OK, 0 rows affected (0.00 sec)
How to dynamically build a JSON object with Python?
myjson={}
myjson["Country"]= {"KR": { "id": "220", "name": "South Korea"}}
myjson["Creative"]= {
"1067405": {
"id": "1067405",
"url": "https://cdn.gowadogo.com/559d1ba1-8d50-4c7f-b3f5-d80f918006e0.jpg"
},
"1067406": {
"id": "1067406",
"url": "https://cdn.gowadogo.com/3799a70d-339c-4ecb-bc1f-a959dde675b8.jpg"
},
"1067407": {
"id": "1067407",
"url": "https://cdn.gowadogo.com/180af6a5-251d-4aa9-9cd9-51b2fc77d0c6.jpg"
}
}
myjson["Offer"]= {
"advanced_targeting_enabled": "f",
"category_name": "E-commerce/ Shopping",
"click_lifespan": "168",
"conversion_cap": "50",
"currency": "USD",
"default_payout": "1.5"
}
json_data = json.dumps(myjson)
#reverse back into a json
paths=[]
def walk_the_tree(inputDict,suffix=None):
for key, value in inputDict.items():
if isinstance(value, dict):
if suffix==None:
suffix=key
else:
suffix+=":"+key
walk_the_tree(value,suffix)
else:
paths.append(suffix+":"+key+":"+value)
walk_the_tree(myjson)
print(paths)
#split and build your nested dictionary
json_specs = {}
for path in paths:
parts=path.split(':')
value=(parts[-1])
d=json_specs
for p in parts[:-1]:
if p==parts[-2]:
d = d.setdefault(p,value)
else:
d = d.setdefault(p,{})
print(json_specs)
Paths:
['Country:KR:id:220', 'Country:KR:name:South Korea', 'Country:Creative:1067405:id:1067405', 'Country:Creative:1067405:url:https://cdn.gowadogo.com/559d1ba1-8d50-4c7f-b3f5-d80f918006e0.jpg', 'Country:Creative:1067405:1067406:id:1067406', 'Country:Creative:1067405:1067406:url:https://cdn.gowadogo.com/3799a70d-339c-4ecb-bc1f-a959dde675b8.jpg', 'Country:Creative:1067405:1067406:1067407:id:1067407', 'Country:Creative:1067405:1067406:1067407:url:https://cdn.gowadogo.com/180af6a5-251d-4aa9-9cd9-51b2fc77d0c6.jpg', 'Country:Creative:Offer:advanced_targeting_enabled:f', 'Country:Creative:Offer:category_name:E-commerce/ Shopping', 'Country:Creative:Offer:click_lifespan:168', 'Country:Creative:Offer:conversion_cap:50', 'Country:Creative:Offer:currency:USD', 'Country:Creative:Offer:default_payout:1.5']
How to join two sets in one line without using "|"
You could use or_
alias:
>>> from operator import or_
>>> from functools import reduce # python3 required
>>> reduce(or_, [{1, 2, 3, 4}, {3, 4, 5, 6}])
set([1, 2, 3, 4, 5, 6])
Cleanest way to write retry logic?
You might also consider adding the exception type you want to retry for. For instance is this a timeout exception you want to retry? A database exception?
RetryForExcpetionType(DoSomething, typeof(TimeoutException), 5, 1000);
public static void RetryForExcpetionType(Action action, Type retryOnExceptionType, int numRetries, int retryTimeout)
{
if (action == null)
throw new ArgumentNullException("action");
if (retryOnExceptionType == null)
throw new ArgumentNullException("retryOnExceptionType");
while (true)
{
try
{
action();
return;
}
catch(Exception e)
{
if (--numRetries <= 0 || !retryOnExceptionType.IsAssignableFrom(e.GetType()))
throw;
if (retryTimeout > 0)
System.Threading.Thread.Sleep(retryTimeout);
}
}
}
You might also note that all of the other examples have a similar issue with testing for retries == 0 and either retry infinity or fail to raise exceptions when given a negative value. Also Sleep(-1000) will fail in the catch blocks above. Depends on how 'silly' you expect people to be but defensive programming never hurts.
Convert String to Uri
If you are using Kotlin and Kotlin android extensions, then there is a beautiful way of doing this.
val uri = myUriString.toUri()
To add Kotlin extensions (KTX) to your project add the following to your app module's build.gradle
repositories {
google()
}
dependencies {
implementation 'androidx.core:core-ktx:1.0.0-rc01'
}
How to use global variable in node.js?
Global variables can be used in Node when used wisely.
Declaration of global variables in Node:
a = 10;
GLOBAL.a = 10;
global.a = 10;
All of the above commands the same actions with different syntaxes.
Use global variables when they are not about to be changed
Here an example of something that can happen when using global variables:
// app.js
a = 10; // no var or let or const means global
// users.js
app.get("/users", (req, res, next) => {
res.send(a); // 10;
});
// permissions.js
app.get("/permissions", (req, res, next) => {
a = 11; // notice that there is no previous declaration of a in the permissions.js, means we looking for the global instance of a.
res.send(a); // 11;
});
Explained:
Run users route first and receive 10;
Then run permissions route and receive 11;
Then run again the users route and receive 11 as well instead of 10;
Global variables can be overtaken!
Now think about using express and assignin res object as global.. And you end up with async error become corrupt and server is shuts down.
When to use global vars?
As I said - when var is not about to be changed.
Anyways it's more recommended that you will be using the process.env
object from the config file.
javac: invalid target release: 1.8
I got the same issue with netbeans, but mvn build is OK in cmd window. For me the issue resolved after changing netbeans' JDK (in netbeans.conf as below),
netbeans_jdkhome="C:\Program Files\Java\jdk1.8.0_91"
Edit: Seems it's mentioned here: netbeans bug 236364
popup form using html/javascript/css
But the problem with this code is that, I cannot change the content popup content from "Please enter your name" to my html form.
Umm. Just change the string passed to the prompt()
function.
While searching, I found that there we CANNOT change the content of popup Prompt Box
You can't change the title. You can change the content, it is the first argument passed to the prompt()
function.
How to get a responsive button in bootstrap 3
<a href="#"><button type="button" class="btn btn-info btn-block regular-link"> <span class="text">Create New Board</span></button></a>
We can use btn-block for automatic responsive.
What does "xmlns" in XML mean?
xmlns - xml namespace. It's just a method to avoid element name conflicts. For example:
<config xmlns:rnc="URI1" xmlns:bsc="URI2">
<rnc:node>
<rnc:rncId>5</rnc:rncId>
</rnc:node>
<bsc:node>
<bsc:cId>5</bsc:cId>
</bsc:node>
</config>
Two different node
elements in one xml file. Without namespaces this file would not be valid.
Asyncio.gather vs asyncio.wait
asyncio.wait
is more low level than asyncio.gather
.
As the name suggests, asyncio.gather
mainly focuses on gathering the results. It waits on a bunch of futures and returns their results in a given order.
asyncio.wait
just waits on the futures. And instead of giving you the results directly, it gives done and pending tasks. You have to manually collect the values.
Moreover, you could specify to wait for all futures to finish or just the first one with wait
.
Force GUI update from UI Thread
If you only need to update a couple controls, .update() is sufficient.
btnMyButton.BackColor=Color.Green; // it eventually turned green, after a delay
btnMyButton.Update(); // after I added this, it turned green quickly
NPM global install "cannot find module"
In my case both node
and npm
were in same path (/usr/bin
). The NODE_PATH
was empty, so the npm
placed the global modules into /usr/lib/node_modules
where require(...)
successfully find them.
The only exception was the npm
module, which came with the nodejs package. Since I'm using 64 bit system, it was placed into /usr/lib64/node_modules
. This is not where require(...) searches in case of empty NODE_PATH
and node started from /usr/bin
. So I had two options:
- link
/usr/lib64/node_modules/npm
to /usr/lib/node_modules/npm
- move modules from
/usr/lib/node_modules/*
to /usr/lib64/node_modules/
and set NODE_PATH=/usr/lib64/node_modules
Both worked. I'm using OpenSUSE 42.1 and the nodejs package from updates repository. Version is 4.4.5.
How can I insert binary file data into a binary SQL field using a simple insert statement?
If you mean using a literal, you simply have to create a binary string:
insert into Files (FileId, FileData) values (1, 0x010203040506)
And you will have a record with a six byte value for the FileData field.
You indicate in the comments that you want to just specify the file name, which you can't do with SQL Server 2000 (or any other version that I am aware of).
You would need a CLR stored procedure to do this in SQL Server 2005/2008 or an extended stored procedure (but I'd avoid that at all costs unless you have to) which takes the filename and then inserts the data (or returns the byte string, but that can possibly be quite long).
In regards to the question of only being able to get data from a SP/query, I would say the answer is yes, because if you give SQL Server the ability to read files from the file system, what do you do when you aren't connected through Windows Authentication, what user is used to determine the rights? If you are running the service as an admin (God forbid) then you can have an elevation of rights which shouldn't be allowed.
Adding a dictionary to another
foreach(var newAnimal in NewAnimals)
Animals.Add(newAnimal.Key,newAnimal.Value)
Note: this throws an exception on a duplicate key.
Or if you really want to go the extension method route(I wouldn't), then you could define a general AddRange
extension method that works on any ICollection<T>
, and not just on Dictionary<TKey,TValue>
.
public static void AddRange<T>(this ICollection<T> target, IEnumerable<T> source)
{
if(target==null)
throw new ArgumentNullException(nameof(target));
if(source==null)
throw new ArgumentNullException(nameof(source));
foreach(var element in source)
target.Add(element);
}
(throws on duplicate keys for dictionaries)
Not an enclosing class error Android Studio
you are calling the context of not existing activity...so just replace your code in onClick(View v) as
Intent intent=new Intent(this,Katra_home.class);
startActivity(intent);
it will definitely works....
xml.LoadData - Data at the root level is invalid. Line 1, position 1
The hidden character is probably BOM.
The explanation to the problem and the solution can be found here, credits to James Schubert, based on an answer by James Brankin found here.
Though the previous answer does remove the hidden character, it also removes the whole first line. The more precise version would be:
string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (xml.StartsWith(_byteOrderMarkUtf8))
{
xml = xml.Remove(0, _byteOrderMarkUtf8.Length);
}
I encountered this problem when fetching an XSLT file from Azure blob and loading it into an XslCompiledTransform object.
On my machine the file looked just fine, but after uploading it as a blob and fetching it back, the BOM character was added.
Append text to input field
_x000D_
_x000D_
// Define appendVal by extending JQuery_x000D_
$.fn.appendVal = function( TextToAppend ) {_x000D_
return $(this).val(_x000D_
$(this).val() + TextToAppend_x000D_
);_x000D_
};_x000D_
//______________________________________________x000D_
_x000D_
// And that's how to use it:_x000D_
$('#SomeID')_x000D_
.appendVal( 'This text was just added' )
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form>_x000D_
<textarea _x000D_
id = "SomeID"_x000D_
value = "ValueText"_x000D_
type = "text"_x000D_
>Current NodeText_x000D_
</textarea>_x000D_
</form>
_x000D_
_x000D_
_x000D_
Well when creating this example I somehow got a little confused. "ValueText" vs >Current NodeText< Isn't .val()
supposed to run on the data of the value attribute? Anyway I and you me may clear up this sooner or later.
However the point for now is:
When working with form data use .val().
When dealing with the mostly read only data in between the tag use .text() or .append() to append text.
How do I animate constraint changes?
Storyboard, Code, Tips and a few Gotchas
The other answers are just fine but this one highlights a few fairly important gotchas of animating constraints using a recent example. I went through a lot of variations before I realized the following:
Make the constraints you want to target into Class variables to hold a strong reference. In Swift I used lazy variables:
lazy var centerYInflection:NSLayoutConstraint = {
let temp = self.view.constraints.filter({ $0.firstItem is MNGStarRating }).filter ( { $0.secondItem is UIWebView }).filter({ $0.firstAttribute == .CenterY }).first
return temp!
}()
After some experimentation I noted that one MUST obtain the constraint from the view ABOVE (aka the superview) the two views where the constraint is defined. In the example below (both MNGStarRating and UIWebView are the two types of items I am creating a constraint between, and they are subviews within self.view).
Filter Chaining
I take advantage of Swift's filter method to separate the desired constraint that will serve as the inflection point. One could also get much more complicated but filter does a nice job here.
Animating Constraints Using Swift
Nota Bene - This example is the storyboard/code solution and assumes
one has made default constraints in the storyboard. One can then
animate the changes using code.
Assuming you create a property to filter with accurate criteria and get to a specific inflection point for your animation (of course you could also filter for an array and loop through if you need multiple constraints):
lazy var centerYInflection:NSLayoutConstraint = {
let temp = self.view.constraints.filter({ $0.firstItem is MNGStarRating }).filter ( { $0.secondItem is UIWebView }).filter({ $0.firstAttribute == .CenterY }).first
return temp!
}()
....
Sometime later...
@IBAction func toggleRatingView (sender:AnyObject){
let aPointAboveScene = -(max(UIScreen.mainScreen().bounds.width,UIScreen.mainScreen().bounds.height) * 2.0)
self.view.layoutIfNeeded()
//Use any animation you want, I like the bounce in springVelocity...
UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0.75, options: [.CurveEaseOut], animations: { () -> Void in
//I use the frames to determine if the view is on-screen
if CGRectContainsRect(self.view.frame, self.ratingView.frame) {
//in frame ~ animate away
//I play a sound to give the animation some life
self.centerYInflection.constant = aPointAboveScene
self.centerYInflection.priority = UILayoutPriority(950)
} else {
//I play a different sound just to keep the user engaged
//out of frame ~ animate into scene
self.centerYInflection.constant = 0
self.centerYInflection.priority = UILayoutPriority(950)
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
}) { (success) -> Void in
//do something else
}
}
}
The many wrong turns
These notes are really a set of tips that I wrote for myself. I did all the don'ts personally and painfully. Hopefully this guide can spare others.
Watch out for zPositioning. Sometimes when nothing is apparently
happening, you should hide some of the other views or use the view
debugger to locate your animated view. I've even found cases where a User Defined Runtime
Attribute was lost in a storyboard's xml and led to the animated
view being covered (while working).
Always take a minute to read the documentation (new and old), Quick
Help, and headers. Apple keeps making a lot of changes to better
manage AutoLayout constraints (see stack views). Or at least the AutoLayout Cookbook. Keep in mind that sometimes the best solutions are in the older documentation/videos.
Play around with the values in the animation and consider using
other animateWithDuration variants.
Don't hardcode specific layout values as criteria for determining
changes to other constants, instead use values that allow you to
determine the location of the view. CGRectContainsRect
is one
example
- If needed, don't hesitate to use the layout margins associated with
a view participating in the constraint definition
let viewMargins = self.webview.layoutMarginsGuide
: is on example
- Don't do work you don't have to do, all views with constraints on the
storyboard have constraints attached to the property
self.viewName.constraints
- Change your priorities for any constraints to less than 1000. I set
mine to 250 (low) or 750 (high) on the storyboard; (if you try to change a 1000 priority to anything in code then the app will crash because 1000 is required)
- Consider not immediately trying to use activateConstraints and
deactivateConstraints (they have their place but when just learning or if you are using a storyboard using these probably means your doing too much ~ they do have a place though as seen below)
- Consider not using addConstraints / removeConstraints unless you are
really adding a new constraint in code. I found that most times I
layout the views in the storyboard with desired constraints (placing
the view offscreen), then in code, I animate the constraints previously created in the storyboard to move the view around.
- I spent a lot of wasted time building up constraints with the new
NSAnchorLayout class and subclasses. These work just fine but it
took me a while to realize that all the constraints that I needed
already existed in the storyboard. If you build constraints in code
then most certainly use this method to aggregate your constraints:
Quick Sample Of Solutions to AVOID when using Storyboards
private var _nc:[NSLayoutConstraint] = []
lazy var newConstraints:[NSLayoutConstraint] = {
if !(self._nc.isEmpty) {
return self._nc
}
let viewMargins = self.webview.layoutMarginsGuide
let minimumScreenWidth = min(UIScreen.mainScreen().bounds.width,UIScreen.mainScreen().bounds.height)
let centerY = self.ratingView.centerYAnchor.constraintEqualToAnchor(self.webview.centerYAnchor)
centerY.constant = -1000.0
centerY.priority = (950)
let centerX = self.ratingView.centerXAnchor.constraintEqualToAnchor(self.webview.centerXAnchor)
centerX.priority = (950)
if let buttonConstraints = self.originalRatingViewConstraints?.filter({
($0.firstItem is UIButton || $0.secondItem is UIButton )
}) {
self._nc.appendContentsOf(buttonConstraints)
}
self._nc.append( centerY)
self._nc.append( centerX)
self._nc.append (self.ratingView.leadingAnchor.constraintEqualToAnchor(viewMargins.leadingAnchor, constant: 10.0))
self._nc.append (self.ratingView.trailingAnchor.constraintEqualToAnchor(viewMargins.trailingAnchor, constant: 10.0))
self._nc.append (self.ratingView.widthAnchor.constraintEqualToConstant((minimumScreenWidth - 20.0)))
self._nc.append (self.ratingView.heightAnchor.constraintEqualToConstant(200.0))
return self._nc
}()
If you forget one of these tips or the more simple ones such as where to add the layoutIfNeeded, most likely nothing will happen: In which case you may have a half baked solution like this:
NB - Take a moment to read the AutoLayout Section Below and the
original guide. There is a way to use these techniques to supplement
your Dynamic Animators.
UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.3, initialSpringVelocity: 1.0, options: [.CurveEaseOut], animations: { () -> Void in
//
if self.starTopInflectionPoint.constant < 0 {
//-3000
//offscreen
self.starTopInflectionPoint.constant = self.navigationController?.navigationBar.bounds.height ?? 0
self.changeConstraintPriority([self.starTopInflectionPoint], value: UILayoutPriority(950), forView: self.ratingView)
} else {
self.starTopInflectionPoint.constant = -3000
self.changeConstraintPriority([self.starTopInflectionPoint], value: UILayoutPriority(950), forView: self.ratingView)
}
}) { (success) -> Void in
//do something else
}
}
Snippet from the AutoLayout Guide (note the second snippet is for using OS X). BTW - This is no longer in the current guide as far as I can see. The preferred techniques continue to evolve.
Animating Changes Made by Auto Layout
If you need full control over animating changes made by Auto Layout, you must make your constraint changes programmatically. The basic concept is the same for both iOS and OS X, but there are a few minor differences.
In an iOS app, your code would look something like the following:
[containerView layoutIfNeeded]; // Ensures that all pending layout operations have been completed
[UIView animateWithDuration:1.0 animations:^{
// Make all constraint changes here
[containerView layoutIfNeeded]; // Forces the layout of the subtree animation block and then captures all of the frame changes
}];
In OS X, use the following code when using layer-backed animations:
[containterView layoutSubtreeIfNeeded];
[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
[context setAllowsImplicitAnimation: YES];
// Make all constraint changes here
[containerView layoutSubtreeIfNeeded];
}];
When you aren’t using layer-backed animations, you must animate the constant using the constraint’s animator:
[[constraint animator] setConstant:42];
For those who learn better visually check out this early video from Apple.
Pay Close Attention
Often in documentation there are small notes or pieces of code that lead to bigger ideas. For example attaching auto layout constraints to dynamic animators is a big idea.
Good Luck and May the Force be with you.
Does JavaScript pass by reference?
Think of it like this:
Whenever you create an object in ECMAscript, this object is formed in a mystique ECMAscript universal place where no man will ever be able to get. All you get back is a reference to that object in this mystique place.
var obj = { };
Even obj
is only a reference to the object (which is located in that special wonderful place) and hence, you can only pass this reference around. Effectively, any piece of code which accesses obj will modify the object which is far, far away.
Best way to restrict a text field to numbers only?
It's worth pointing out that no matter how tightly you manage to control this via the front end (Javascript, HTML, etc), you still need to validate it at the server, because there's nothing to stop a user from turning off javascript, or even deliberately posting junk to your form to try to hack you.
My advice: Use the HTML5 markup so that browsers which support it will use it. Also use the JQuery option previously suggested (the inital solution may have flaws, but it seems like the comments have been working through that). And then do server-side validation as well.
Integer to hex string in C++
Just have a look on my solution,[1] that I verbatim copied from my project, so there a German is API doc included. My goal was to combine flexibility and safety within my actual needs:[2]
- no
0x
prefix added: caller may decide
- automatic width deduction: less typing
- explicit width control: widening for formatting, (lossless) shrinking to save space
- capable for dealing with
long long
- restricted to integral types: avoid surprises by silent conversions
- ease of understanding
- no hard-coded limit
#include <string>
#include <sstream>
#include <iomanip>
/// Vertextet einen Ganzzahlwert val im Hexadezimalformat.
/// Auf die Minimal-Breite width wird mit führenden Nullen aufgefüllt;
/// falls nicht angegeben, wird diese Breite aus dem Typ des Arguments
/// abgeleitet. Funktion geeignet von char bis long long.
/// Zeiger, Fließkommazahlen u.ä. werden nicht unterstützt, ihre
/// Übergabe führt zu einem (beabsichtigten!) Compilerfehler.
/// Grundlagen aus: http://stackoverflow.com/a/5100745/2932052
template <typename T>
inline std::string int_to_hex(T val, size_t width=sizeof(T)*2)
{
std::stringstream ss;
ss << std::setfill('0') << std::setw(width) << std::hex << (val|0);
return ss.str();
}
[1] based on the answer by Kornel Kisielewicz
[2] Translated into the language of CppTest, this is how it reads:
TEST_ASSERT(int_to_hex(char(0x12)) == "12");
TEST_ASSERT(int_to_hex(short(0x1234)) == "1234");
TEST_ASSERT(int_to_hex(long(0x12345678)) == "12345678");
TEST_ASSERT(int_to_hex((long long)(0x123456789abcdef0)) == "123456789abcdef0");
TEST_ASSERT(int_to_hex(0x123, 1) == "123");
TEST_ASSERT(int_to_hex(0x123, 8) == "00000123");
// with deduction test as suggested by Lightness Races in Orbit:
TEST_ASSERT(int_to_hex(short(0x12)) == "0012");
Error ITMS-90717: "Invalid App Store Icon"
Remove the alpha channel using this command in the folder 'Images.xcassets', this command will remove all alpha channels from your .png files and it will put the background color to white
for i in `ls *.png`; do convert $i -background white -alpha remove -alpha off $i; done
How to serialize Joda DateTime with Jackson JSON processor?
https://stackoverflow.com/a/10835114/1113510
Although you can put an annotation for each date field, is better to do a global configuration for your object mapper. If you use jackson you can configure your spring as follow:
<bean id="jacksonObjectMapper" class="com.company.CustomObjectMapper" />
<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" >
</bean>
For CustomObjectMapper:
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
super();
configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false);
setDateFormat(new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'ZZZ (z)"));
}
}
Of course, SimpleDateFormat can use any format you need.
height: 100% for <div> inside <div> with display: table-cell
When you use %
for setting heights or widths, always set the widths/heights of parent elements as well:
_x000D_
_x000D_
.table {_x000D_
display: table;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
border: 2px solid black;_x000D_
vertical-align: top;_x000D_
display: table-cell;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.container {_x000D_
height: 100%;_x000D_
border: 2px solid green;_x000D_
-moz-box-sizing: border-box;_x000D_
}
_x000D_
<div class="table">_x000D_
<div class="cell">_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
</div>_x000D_
<div class="cell">_x000D_
<div class="container">Text</div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
How to convert a JSON string to a dictionary?
With Swift 3, JSONSerialization
has a method called json?Object(with:?options:?)
. json?Object(with:?options:?)
has the following declaration:
class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
Returns a Foundation object from given JSON data.
When you use json?Object(with:?options:?)
, you have to deal with error handling (try
, try?
or try!
) and type casting (from Any
). Therefore, you can solve your problem with one of the following patterns.
#1. Using a method that throws and returns a non-optional type
import Foundation
func convertToDictionary(from text: String) throws -> [String: String] {
guard let data = text.data(using: .utf8) else { return [:] }
let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
return anyResult as? [String: String] ?? [:]
}
Usage:
let string1 = "{\"City\":\"Paris\"}"
do {
let dictionary = try convertToDictionary(from: string1)
print(dictionary) // prints: ["City": "Paris"]
} catch {
print(error)
}
let string2 = "{\"Quantity\":100}"
do {
let dictionary = try convertToDictionary(from: string2)
print(dictionary) // prints [:]
} catch {
print(error)
}
let string3 = "{\"Object\"}"
do {
let dictionary = try convertToDictionary(from: string3)
print(dictionary)
} catch {
print(error) // prints: Error Domain=NSCocoaErrorDomain Code=3840 "No value for key in object around character 9." UserInfo={NSDebugDescription=No value for key in object around character 9.}
}
#2. Using a method that throws and returns an optional type
import Foundation
func convertToDictionary(from text: String) throws -> [String: String]? {
guard let data = text.data(using: .utf8) else { return [:] }
let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
return anyResult as? [String: String]
}
Usage:
let string1 = "{\"City\":\"Paris\"}"
do {
let dictionary = try convertToDictionary(from: string1)
print(String(describing: dictionary)) // prints: Optional(["City": "Paris"])
} catch {
print(error)
}
let string2 = "{\"Quantity\":100}"
do {
let dictionary = try convertToDictionary(from: string2)
print(String(describing: dictionary)) // prints nil
} catch {
print(error)
}
let string3 = "{\"Object\"}"
do {
let dictionary = try convertToDictionary(from: string3)
print(String(describing: dictionary))
} catch {
print(error) // prints: Error Domain=NSCocoaErrorDomain Code=3840 "No value for key in object around character 9." UserInfo={NSDebugDescription=No value for key in object around character 9.}
}
#3. Using a method that does not throw and returns a non-optional type
import Foundation
func convertToDictionary(from text: String) -> [String: String] {
guard let data = text.data(using: .utf8) else { return [:] }
let anyResult: Any? = try? JSONSerialization.jsonObject(with: data, options: [])
return anyResult as? [String: String] ?? [:]
}
Usage:
let string1 = "{\"City\":\"Paris\"}"
let dictionary1 = convertToDictionary(from: string1)
print(dictionary1) // prints: ["City": "Paris"]
let string2 = "{\"Quantity\":100}"
let dictionary2 = convertToDictionary(from: string2)
print(dictionary2) // prints: [:]
let string3 = "{\"Object\"}"
let dictionary3 = convertToDictionary(from: string3)
print(dictionary3) // prints: [:]
#4. Using a method that does not throw and returns an optional type
import Foundation
func convertToDictionary(from text: String) -> [String: String]? {
guard let data = text.data(using: .utf8) else { return nil }
let anyResult = try? JSONSerialization.jsonObject(with: data, options: [])
return anyResult as? [String: String]
}
Usage:
let string1 = "{\"City\":\"Paris\"}"
let dictionary1 = convertToDictionary(from: string1)
print(String(describing: dictionary1)) // prints: Optional(["City": "Paris"])
let string2 = "{\"Quantity\":100}"
let dictionary2 = convertToDictionary(from: string2)
print(String(describing: dictionary2)) // prints: nil
let string3 = "{\"Object\"}"
let dictionary3 = convertToDictionary(from: string3)
print(String(describing: dictionary3)) // prints: nil
Pytorch reshape tensor dimension
or you can use this, the '-1' means you don't have to specify the number of the elements.
In [3]: a.view(1,-1)
Out[3]:
1 2 3 4 5
[torch.FloatTensor of size 1x5]
How to break out from foreach loop in javascript
Use a for
loop instead of .forEach()
var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false
for(var call of myObj) {
console.log(call)
var a = call['a'], b = call['b']
if(a == null || b == null) {
result = false
break
}
}
The term 'Get-ADUser' is not recognized as the name of a cmdlet
For the particular case of Windows 10 October 2018 Update or later activedirectory
module is not available unless the optional feature RSAT: Active Directory Domain Services and Lightweight Directory Services Tools
is installed (instructions here + uncollapse install instructions).
Reopen Windows Powershell and import-module activedirectory
will work as expected.
Chrome Extension - Get DOM content
You don't have to use the message passing to obtain or modify DOM. I used chrome.tabs.executeScript
instead. In my example I am using only activeTab permission, therefore the script is executed only on the active tab.
part of manifest.json
"browser_action": {
"default_title": "Test",
"default_popup": "index.html"
},
"permissions": [
"activeTab",
"<all_urls>"
]
index.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<button id="test">TEST!</button>
<script src="test.js"></script>
</body>
</html>
test.js
document.getElementById("test").addEventListener('click', () => {
console.log("Popup DOM fully loaded and parsed");
function modifyDOM() {
//You can play with your DOM here or check URL against your regex
console.log('Tab script:');
console.log(document.body);
return document.body.innerHTML;
}
//We have permission to access the activeTab, so we can call chrome.tabs.executeScript:
chrome.tabs.executeScript({
code: '(' + modifyDOM + ')();' //argument here is a string but function.toString() returns function's code
}, (results) => {
//Here we have just the innerHTML and not DOM structure
console.log('Popup script:')
console.log(results[0]);
});
});
How to pad zeroes to a string?
str(n).zfill(width)
will work with string
s, int
s, float
s... and is Python 2.x and 3.x compatible:
>>> n = 3
>>> str(n).zfill(5)
'00003'
>>> n = '3'
>>> str(n).zfill(5)
'00003'
>>> n = '3.0'
>>> str(n).zfill(5)
'003.0'