Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)
The difference between a recursive and non-recursive mutex has to do with ownership. In the case of a recursive mutex, the kernel has to keep track of the thread who actually obtained the mutex the first time around so that it can detect the difference between recursion vs. a different thread that should block instead. As another answer pointed out, there is a question of the additional overhead of this both in terms of memory to store this context and also the cycles required for maintaining it.
However, there are other considerations at play here too.
Because the recursive mutex has a sense of ownership, the thread that grabs the mutex must be the same thread that releases the mutex. In the case of non-recursive mutexes, there is no sense of ownership and any thread can usually release the mutex no matter which thread originally took the mutex. In many cases, this type of "mutex" is really more of a semaphore action, where you are not necessarily using the mutex as an exclusion device but use it as synchronization or signaling device between two or more threads.
Another property that comes with a sense of ownership in a mutex is the ability to support priority inheritance. Because the kernel can track the thread owning the mutex and also the identity of all the blocker(s), in a priority threaded system it becomes possible to escalate the priority of the thread that currently owns the mutex to the priority of the highest priority thread that is currently blocking on the mutex. This inheritance prevents the problem of priority inversion that can occur in such cases. (Note that not all systems support priority inheritance on such mutexes, but it is another feature that becomes possible via the notion of ownership).
If you refer to classic VxWorks RTOS kernel, they define three mechanisms:
- mutex - supports recursion, and optionally priority inheritance. This mechanism is commonly used to protect critical sections of data in a coherent manner.
- binary semaphore - no recursion, no inheritance, simple exclusion, taker and giver does not have to be same thread, broadcast release available. This mechanism can be used to protect critical sections, but is also particularly useful for coherent signalling or synchronization between threads.
- counting semaphore - no recursion or inheritance, acts as a coherent resource counter from any desired initial count, threads only block where net count against the resource is zero.
Again, this varies somewhat by platform - especially what they call these things, but this should be representative of the concepts and various mechanisms at play.
What is a deadlock?
Deadlocks will only occur when you have two or more locks that can be aquired at the same time and they are grabbed in different order.
Ways to avoid having deadlocks are:
- avoid having locks (if possible),
- avoid having more than one lock
- always take the locks in the same order.
await vs Task.Wait - Deadlock?
Some important facts were not given in other answers:
"async await" is more complex at CIL level and thus costs memory and CPU time.
Any task can be canceled if the waiting time is unacceptable.
In the case "async await" we do not have a handler for such a task to cancel it or monitoring it.
Using Task is more flexible then "async await".
Any sync functionality can by wrapped by async.
public async Task<ActionResult> DoAsync(long id)
{
return await Task.Run(() => { return DoSync(id); } );
}
"async await" generate many problems. We do not now is await statement will be reached without runtime and context debugging. If first await not reached everything is blocked. Some times even await seems to be reached still everything is blocked:
https://github.com/dotnet/runtime/issues/36063
I do not see why I'm must live with the code duplication for sync and async method or using hacks.
Conclusion: Create Task manually and control them is much better. Handler to Task give more control. We can monitor Tasks and manage them:
https://github.com/lsmolinski/MonitoredQueueBackgroundWorkItem
Sorry for my english.
How to solve SQL Server Error 1222 i.e Unlock a SQL Server table
In the SQL Server Management Studio,
to find out details of the active transaction, execute following command
DBCC opentran()
You will get the detail of the active transaction, then from the SPID of the active transaction, get the detail about the SPID using following commands
exec sp_who2 <SPID>
exec sp_lock <SPID>
For example, if SPID is 69 then execute the command as
exec sp_who2 69
exec sp_lock 69
Now , you can kill that process using the following command
KILL 69
I hope this helps :)
Working around MySQL error "Deadlock found when trying to get lock; try restarting transaction"
The idea of retrying the query in case of Deadlock exception is good, but it can be terribly slow, since mysql query will keep waiting for locks to be released. And incase of deadlock mysql is trying to find if there is any deadlock, and even after finding out that there is a deadlock, it waits a while before kicking out a thread in order to get out from deadlock situation.
What I did when I faced this situation is to implement locking in your own code, since it is the locking mechanism of mysql is failing due to a bug. So I implemented my own row level locking in my java code:
private HashMap<String, Object> rowIdToRowLockMap = new HashMap<String, Object>();
private final Object hashmapLock = new Object();
public void handleShortCode(Integer rowId)
{
Object lock = null;
synchronized(hashmapLock)
{
lock = rowIdToRowLockMap.get(rowId);
if (lock == null)
{
rowIdToRowLockMap.put(rowId, lock = new Object());
}
}
synchronized (lock)
{
// Execute your queries on row by row id
}
}
How to implement a lock in JavaScript
JavaScript is, with a very few exceptions (XMLHttpRequest
onreadystatechange
handlers in some versions of Firefox) event-loop concurrent. So you needn't worry about locking in this case.
JavaScript has a concurrency model based on an "event loop". This model is quite different than the model in other languages like C or Java.
...
A JavaScript runtime contains a message queue, which is a list of messages to be processed. To each message is associated a function. When the stack is empty, a message is taken out of the queue and processed. The processing consists of calling the associated function (and thus creating an initial stack frame) The message processing ends when the stack becomes empty again.
...
Each message is processed completely before any other message is processed. This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates). This differs from C, for instance, where if a function runs in a thread, it can be stopped at any point to run some other code in another thread.
A downside of this model is that if a message takes too long to complete, the web application is unable to process user interactions like click or scroll. The browser mitigates this with the "a script is taking too long to run" dialog. A good practice to follow is to make message processing short and if possible cut down one message into several messages.
For more links on event-loop concurrency, see E
C++ terminate called without an active exception
When a thread object goes out of scope and it is in joinable state, the program is terminated. The Standard Committee had two other options for the destructor of a joinable thread. It could quietly join -- but join might never return if the thread is stuck. Or it could detach the thread (a detached thread is not joinable). However, detached threads are very tricky, since they might survive till the end of the program and mess up the release of resources. So if you don't want to terminate your program, make sure you join (or detach) every thread.
What's the difference between deadlock and livelock?
Imagine you've thread A and thread B. They are both synchronised
on the same object and inside this block there's a global variable they are both updating;
static boolean commonVar = false;
Object lock = new Object;
...
void threadAMethod(){
...
while(commonVar == false){
synchornized(lock){
...
commonVar = true
}
}
}
void threadBMethod(){
...
while(commonVar == true){
synchornized(lock){
...
commonVar = false
}
}
}
So, when thread A enters in the while
loop and holds the lock, it does what it has to do and set the commonVar
to true
. Then thread B comes in, enters in the while
loop and since commonVar
is true
now, it is be able to hold the lock. It does so, executes the synchronised
block, and sets commonVar
back to false
. Now, thread A again gets it's new CPU window, it was about to quit the while
loop but thread B has just set it back to false
, so the cycle repeats over again. Threads do something (so they're not blocked in the traditional sense) but for pretty much nothing.
It maybe also nice to mention that livelock does not necessarily have to appear here. I'm assuming that the scheduler favours the other thread once the synchronised
block finish executing. Most of the time, I think it's a hard-to-hit expectation and depends on many things happening under the hood.
How to avoid mysql 'Deadlock found when trying to get lock; try restarting transaction'
I have a method, the internals of which are wrapped in a MySqlTransaction.
The deadlock issue showed up for me when I ran the same method in parallel with itself.
There was not an issue running a single instance of the method.
When I removed MySqlTransaction, I was able to run the method in parallel with itself with no issues.
Just sharing my experience, I'm not advocating anything.
Simple Deadlock Examples
public class DeadLock {
public static void main(String[] args) throws InterruptedException {
Thread mainThread = Thread.currentThread();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
mainThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread1.join();
}
}
SQL query to get the deadlocks in SQL SERVER 2008
In order to capture deadlock graphs without using a trace (you don't need profiler necessarily), you can enable trace flag 1222. This will write deadlock information to the error log. However, the error log is textual, so you won't get nice deadlock graph pictures - you'll have to read the text of the deadlocks to figure it out.
I would set this as a startup trace flag (in which case you'll need to restart the service). However, you can run it only for the current running instance of the service (which won't require a restart, but which won't resume upon the next restart) using the following global trace flag command:
DBCC TRACEON(1222, -1);
A quick search yielded this tutorial:
http://www.mssqltips.com/sqlservertip/2130/finding-sql-server-deadlocks-using-trace-flag-1222/
Also note that if your system experiences a lot of deadlocks, this can really hammer your error log, and can become quite a lot of noise, drowning out other, important errors.
Have you considered third party monitoring tools? SQL Sentry Performance Advisor, for example, has a much nicer deadlock graph, showing you object / index names as well as the order in which the locks were taken. As a bonus, these are captured for you automatically on monitored servers without having to configure trace flags, run your own traces, etc.:
Disclaimer: I work for SQL Sentry.
MySQL: Curdate() vs Now()
CURDATE()
will give current date while NOW()
will give full date time.
Run the queries, and you will find out whats the difference between them.
SELECT NOW(); -- You will get 2010-12-09 17:10:18
SELECT CURDATE(); -- You will get 2010-12-09
Directly assigning values to C Pointers
The problem is that you're not initializing the pointer. You've created a pointer to "anywhere you want"—which could be the address of some other variable, or the middle of your code, or some memory that isn't mapped at all.
You need to create an int
variable somewhere in memory for the int *
variable to point at.
Your second example does this, but it does other things that aren't relevant here. Here's the simplest thing you need to do:
int main(){
int variable;
int *ptr = &variable;
*ptr = 20;
printf("%d", *ptr);
return 0;
}
Here, the int
variable isn't initialized—but that's fine, because you're just going to replace whatever value was there with 20
. The key is that the pointer is initialized to point to the variable
. In fact, you could just allocate some raw memory to point to, if you want:
int main(){
void *memory = malloc(sizeof(int));
int *ptr = (int *)memory;
*ptr = 20;
printf("%d", *ptr);
free(memory);
return 0;
}
How to run mysql command on bash?
I have written a shell script which will read data from properties file and then run mysql script on shell script. sharing this may help to others.
#!/bin/bash
PROPERTY_FILE=filename.properties
function getProperty {
PROP_KEY=$1
PROP_VALUE=`cat $PROPERTY_FILE | grep "$PROP_KEY" | cut -d'=' -f2`
echo $PROP_VALUE
}
echo "# Reading property from $PROPERTY_FILE"
DB_USER=$(getProperty "db.username")
DB_PASS=$(getProperty "db.password")
ROOT_LOC=$(getProperty "root.location")
echo $DB_USER
echo $DB_PASS
echo $ROOT_LOC
echo "Writing on DB ... "
mysql -u$DB_USER -p$DB_PASS dbname<<EOFMYSQL
update tablename set tablename.value_ = "$ROOT_LOC" where tablename.name_="Root directory location";
EOFMYSQL
echo "Writing root location($ROOT_LOC) is done ... "
counter=`mysql -u${DB_USER} -p${DB_PASS} dbname -e "select count(*) from tablename where tablename.name_='Root directory location' and tablename.value_ = '$ROOT_LOC';" | grep -v "count"`;
if [ "$counter" = "1" ]
then
echo "ROOT location updated"
fi
Convert Map to JSON using Jackson
You can convert Map
to JSON
using Jackson as follows:
Map<String,String> payload = new HashMap<>();
payload.put("key1","value1");
payload.put("key2","value2");
String json = new ObjectMapper().writeValueAsString(payload);
System.out.println(json);
Replace Default Null Values Returned From Left Outer Join
MySQL
COALESCE(field, 'default')
For example:
SELECT
t.id,
COALESCE(d.field, 'default')
FROM
test t
LEFT JOIN
detail d ON t.id = d.item
Also, you can use multiple columns to check their NULL
by COALESCE function.
For example:
mysql> SELECT COALESCE(NULL, 1, NULL);
-> 1
mysql> SELECT COALESCE(0, 1, NULL);
-> 0
mysql> SELECT COALESCE(NULL, NULL, NULL);
-> NULL
HTML: can I display button text in multiple lines?
Yes, you can have it on multiple lines using the white-space css property :)
_x000D_
_x000D_
input[type="submit"] {_x000D_
white-space: normal;_x000D_
width: 100px;_x000D_
}
_x000D_
<input type="submit" value="Some long text that won't fit." />
_x000D_
_x000D_
_x000D_
add this to your element
white-space: normal;
width: 100px;
Reading all files in a directory, store them in objects, and send the object
async/await
const { promisify } = require("util")
const directory = path.join(__dirname, "/tmpl")
const pathnames = promisify(fs.readdir)(directory)
try {
async function emitData(directory) {
let filenames = await pathnames
var ob = {}
const data = filenames.map(async function(filename, i) {
if (filename.includes(".")) {
var storedFile = promisify(fs.readFile)(directory + `\\${filename}`, {
encoding: "utf8",
})
ob[filename.replace(".js", "")] = await storedFile
socket.emit("init", { data: ob })
}
return ob
})
}
emitData(directory)
} catch (err) {
console.log(err)
}
Who wants to try with generators?
Why is Visual Studio 2013 very slow?
I had similar problems when moving from Visual Studio 2012 → Visual Studio 2013. The IDE would lock up after almost every click or save, and building would take several times longer. None of the solutions listed here helped.
What finally did help was moving my projects to a local drive. Visual Studio 2012 had no problems storing my projects on a network share, but Visual Studio 2013 for some reason couldn't handle it.
here-document gives 'unexpected end of file' error
The line that starts or ends the here-doc probably has some non-printable or whitespace characters (for example, carriage return) which means that the second "EOF" does not match the first, and doesn't end the here-doc like it should. This is a very common error, and difficult to detect with just a text editor. You can make non-printable characters visible for example with cat
:
cat -A myfile.sh
Once you see the output from cat -A
the solution will be obvious: remove the offending characters.
How do pointer-to-pointer's work in C? (and when might you use them?)
There so many of the useful explanations, but I didnt found just a short description, so..
Basically pointer is address of the variable.
Short summary code:
int a, *p_a;//declaration of normal variable and int pointer variable
a = 56; //simply assign value
p_a = &a; //save address of "a" to pointer variable
*p_a = 15; //override the value of the variable
//print 0xfoo and 15
//- first is address, 2nd is value stored at this address (that is called dereference)
printf("pointer p_a is having value %d and targeting at variable value %d", p_a, *p_a);
Also useful info can be found in topic What means reference and dereference
And I am not so sure, when can be pointers useful, but in common it is necessary to use them when you are doing some manual/dynamic memory allocation- malloc, calloc, etc.
So I hope it will also helps for clarify the problematic :)
Calculating Time Difference
from time import time
start_time = time()
...
end_time = time()
seconds_elapsed = end_time - start_time
hours, rest = divmod(seconds_elapsed, 3600)
minutes, seconds = divmod(rest, 60)
How should you diagnose the error SEHException - External component has thrown an exception
Just another information...
Had that problem today on a Windows 2012 R2 x64 TS system where the application was started from a unc/network path. The issue occured for one application for all terminal server users.
Executing the application locally worked without problems. After a reboot it started working again - the SEHException's thrown had been Constructor init and TargetInvocationException
Occurrences of substring in a string
As @Mr_and_Mrs_D suggested:
String haystack = "hellolovelyworld";
String needle = "lo";
return haystack.split(Pattern.quote(needle), -1).length - 1;
Find and replace entire mysql database
Short answer: You can't.
Long answer: You can use the INFORMATION_SCHEMA to get the table definitions and use this to generate the necessary UPDATE statements dynamically. For example you could start with this:
SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'your_schema'
I'd try to avoid doing this though if at all possible.
Sleep function in C++
Just use it...
Firstly include the unistd.h
header file, #include<unistd.h>
, and use this function for pausing your program execution for desired number of seconds:
sleep(x);
x
can take any value in seconds.
If you want to pause the program for 5 seconds it is like this:
sleep(5);
It is correct and I use it frequently.
It is valid for C and C++.
Get parent directory of running script
I Hope this will help you.
echo getcwd().'<br>'; // getcwd() will return current working directory
echo dirname(getcwd(),1).'<br>';
echo dirname(getcwd(),2).'<br>';
echo dirname(getcwd(),3).'<br>';
Output :
C:\wamp64\www\public_html\step
C:\wamp64\www\public_html
C:\wamp64\www
C:\wamp64
Print "hello world" every X seconds
What he said. You can handle the exceptions however you like, but
Thread.sleep(miliseconds);
is the best route to take.
public static void main(String[] args) throws InterruptedException {
Twitter Bootstrap Button Text Word Wrap
Try this: add white-space: normal; to the style definition of the Bootstrap Button or you can replace the code you displayed with the one below
<div class="col-lg-3"> <!-- FIRST COL -->
<div class="panel panel-default">
<div class="panel-body">
<h4>Posted on</h4>
<p>22nd September 2013</p>
<h4>Tags</h4>
<a href="#" class="btn btn-primary btn-xs col-lg-12" style="margin-bottom:4px;white-space: normal;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>
<a href="#" class="btn btn-primary btn-xs col-lg-12" style="margin-bottom:4px;white-space: normal;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>
<a href="#" class="btn btn-primary btn-xs col-lg-12" style="margin-bottom:4px;white-space: normal;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>
</div>
</div>
</div>
I have updated your fiddle here to show how it comes out.
How to order by with union in SQL?
Both other answers are correct, but I thought it worth noting that the place where I got stuck was not realizing that you'll need order by the alias and make sure that the alias is the same for both the selects... so
select 'foo'
union
select item as `foo`
from myTable
order by `foo`
notice that I'm using single quotes in the first select but backticks for the others.
That will get you the sorting you need.
bootstrap 4 responsive utilities visible / hidden xs sm lg not working
With Bootstrap 4 .hidden-*
classes were completely removed (yes, they were replaced by hidden-*-*
but those classes are also gone from v4 alphas).
Starting with v4-beta, you can combine .d-*-none
and .d-*-block
classes to achieve the same result.
visible-* was removed as well; instead of using explicit .visible-*
classes, make the element visible by not hiding it (again, use combinations of .d-none .d-md-block). Here is the working example:
<div class="col d-none d-sm-block">
<span class="vcard">
…
</span>
</div>
<div class="col d-none d-xl-block">
<div class="d-none d-md-block">
…
</div>
<div class="d-none d-sm-block">
…
</div>
</div>
class="hidden-xs"
becomes class="d-none d-sm-block"
(or d-none d-sm-inline-block) ...
<span class="d-none d-sm-inline">hidden-xs</span>
<span class="d-none d-sm-inline-block">hidden-xs</span>
An example of Bootstrap 4 responsive utilities:
<div class="d-none d-sm-block"> hidden-xs
<div class="d-none d-md-block"> visible-md and up (hidden-sm and down)
<div class="d-none d-lg-block"> visible-lg and up (hidden-md and down)
<div class="d-none d-xl-block"> visible-xl </div>
</div>
</div>
</div>
<div class="d-sm-none"> eXtra Small <576px </div>
<div class="d-none d-sm-block d-md-none d-lg-none d-xl-none"> SMall =576px </div>
<div class="d-none d-md-block d-lg-none d-xl-none"> MeDium =768px </div>
<div class="d-none d-lg-block d-xl-none"> LarGe =992px </div>
<div class="d-none d-xl-block"> eXtra Large =1200px </div>
<div class="d-xl-none"> hidden-xl (visible-lg and down)
<div class="d-lg-none d-xl-none"> visible-md and down (hidden-lg and up)
<div class="d-md-none d-lg-none d-xl-none"> visible-sm and down (or hidden-md and up)
<div class="d-sm-none"> visible-xs </div>
</div>
</div>
</div>
Documentation
What is the preferred syntax for defining enums in JavaScript?
The com.recoyxgroup.javascript.enum package allows you to properly define enum and flags enum classes, where:
- Every constant is represented as an immutable
{ _value: someNumber }
- Every constant has a property attached to the enum class (E.CONSTANT_NAME)
- Every constant has a friendly String (
constantName
)
- Every constant has a Number (
someNumber
)
- You can declare custom properties/methods using
E.prototype
.
Wherever a specific enum is expected, the convention is to do E(v)
, like this:
const { FlagsEnum } from 'com.recoyxgroup.javascript.enum';
const Rights = FlagsEnum('Rights', [
'ADMINISTRATION',
'REVIEW',
]);
function fn(rights) {
rights = Rights(rights);
console.log('administration' in rights, 'review' in rights);
}
fn( ['administration', 'review'] ); // true true
fn( 'administration' ); // true false
fn( undefined ); // false false
var r = Rights.ADMINISTRATION;
console.log( r == 'administration' );
As you can see, you can still compare the value to a String.
Definitions can be more specific:
const E = FlagsEnum('E', [
['Q', 0x10],
['K', 'someB'],
['L', [0x40, 'someL']],
]);
FlagsEnum products > Instance properties/methods
- number (was going to be valueOf(), but because of JS ==, had to be 'number')
- set()
- exclude()
- toggle()
- filter()
- valueOf()
- toString()
How to check if dropdown is disabled?
The legacy solution, before 1.6, was to use .attr
and handle the returned value as a bool
. The main problem is that the returned type of .attr
has changed to string
, and therefore the comparison with == true
is broken (see http://jsfiddle.net/2vene/1/ (and switch the jquery-version)).
With 1.6 .prop
was introduced, which returns a bool
.
Nevertheless, I suggest to use .is()
, as the returned type is intrinsically bool
, like:
$('#dropUnit').is(':disabled');
$('#dropUnit').is(':enabled');
Furthermore .is()
is much more natural (in terms of "natural language") and adds more conditions than a simple attribute-comparison (eg: .is(':last')
, .is(':visible')
, ... please see documentation on selectors).
Superscript in Python plots
If you want to write unit per meter (m^-1)
, use $m^{-1}$)
, which means -1
inbetween {}
Example:
plt.ylabel("Specific Storage Values ($m^{-1}$)", fontsize = 12 )
Extracting extension from filename in Python
try this:
files = ['file.jpeg','file.tar.gz','file.png','file.foo.bar','file.etc']
pen_ext = ['foo', 'tar', 'bar', 'etc']
for file in files: #1
if (file.split(".")[-2] in pen_ext): #2
ext = file.split(".")[-2]+"."+file.split(".")[-1]#3
else:
ext = file.split(".")[-1] #4
print (ext) #5
- get all file name inside the list
- splitting file name and check the penultimate extension, is it in the pen_ext list or not?
- if yes then join it with the last extension and set it as the file's extension
- if not then just put the last extension as the file's extension
- and then check it out
Which data structures and algorithms book should I buy?
If you want the algorithms to be implemented specifically in Java then there is Mitchell Waite's Series book "Data Structures & Algorithms in Java". It starts from basic data structures like linked lists, stacks and queues, and the basic algorithms for sorting and searching. Working your way through it you will eventually get to Tree data structures, Red-Black trees, 2-3 trees and Graphs.
All-in-all its not an extremely theoretical book, but if you just want an introduction in a language you are familiar with then its a good book. At the end of the day, if you want a deeper understanding of algorithms you're going to have to learn some of the more theoretical concepts, and read one of the classics, like Cormen/Leiserson/Rivest/Stein's Introduction to Algorithms.
Typescript sleep
You have to wait for TypeScript 2.0 with async
/await
for ES5 support as it now supported only for TS to ES6 compilation.
You would be able to create delay function with async
:
function delay(ms: number) {
return new Promise( resolve => setTimeout(resolve, ms) );
}
And call it
await delay(300);
Please note, that you can use await
only inside async
function.
If you can't (let's say you are building nodejs application), just place your code in the anonymous async
function. Here is an example:
(async () => {
// Do something before delay
console.log('before delay')
await delay(1000);
// Do something after
console.log('after delay')
})();
Example TS Application: https://github.com/v-andrew/ts-template
In OLD JS you have to use
setTimeout(YourFunctionName, Milliseconds);
or
setTimeout( () => { /*Your Code*/ }, Milliseconds );
However with every major browser supporting async
/await
it less useful.
Update:
TypeScript 2.1 is here with async/await
.
Just do not forget that you need Promise
implementation when you compile to ES5, where Promise is not natively available.
PS
You have to export the function if you want to use it outside of the original file.
How can I expand and collapse a <div> using javascript?
Since you have jQuery on the page, you can remove that onclick
attribute and the majorpointsexpand
function. Add the following script to the bottom of you page or, preferably, to an external .js file:
$(function(){
$('.majorpointslegend').click(function(){
$(this).next().toggle().text( $(this).is(':visible')?'Collapse':'Expand' );
});
});
This solutionshould work with your HTML as is but it isn't really a very robust answer. If you change your fieldset
layout, it could break it. I'd suggest that you put a class
attribute in that hidden div, like class="majorpointsdetail"
and use this code instead:
$(function(){
$('.majorpoints').on('click', '.majorpointslegend', function(event){
$(event.currentTarget).find('.majorpointsdetail').toggle();
$(this).text( $(this).is(':visible')?'Collapse':'Expand' );
});
});
Obs: there's no closing </fieldset>
tag in your question so I'm assuming the hidden div is inside the fieldset.
Placing a textview on top of imageview in android
you can try this too. I use just framelayout.
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/cover"
android:gravity="bottom">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Hello !"
android:id="@+id/welcomeTV"
android:textColor="@color/textColor"
android:layout_gravity="left|bottom" />
</FrameLayout>
The connection to adb is down, and a severe error has occurred
The problem might be with your firewall or antivirus.
- Disable all network connection
- Disable firewall
- Disable Antivirus
Make sure they all disabled.
Run your script in Eclipse. If it works, then 2 and 3 might be the culprit. For me, it was comodo firewall. I created a filter for Adb.exe
How to delete the top 1000 rows from a table using Sql Server 2008?
The code you tried is in fact two statements. A DELETE
followed by a SELECT
.
You don't define TOP
as ordered by what.
For a specific ordering criteria deleting from a CTE or similar table expression is the most efficient way.
;WITH CTE AS
(
SELECT TOP 1000 *
FROM [mytab]
ORDER BY a1
)
DELETE FROM CTE
How to Validate a DateTime in C#?
DateTime temp;
try
{
temp = Convert.ToDateTime(grd.Rows[e.RowIndex].Cells["dateg"].Value);
grd.Rows[e.RowIndex].Cells["dateg"].Value = temp.ToString("yyyy/MM/dd");
}
catch
{
MessageBox.Show("Sorry The date not valid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop,MessageBoxDefaultButton.Button1,MessageBoxOptions .RightAlign);
grd.Rows[e.RowIndex].Cells["dateg"].Value = null;
}
how to detect search engine bots with php?
I'm using this to detect bots:
if (preg_match('/bot|crawl|curl|dataprovider|search|get|spider|find|java|majesticsEO|google|yahoo|teoma|contaxe|yandex|libwww-perl|facebookexternalhit/i', $_SERVER['HTTP_USER_AGENT'])) {
// is bot
}
In addition I use a whitelist to block unwanted bots:
if (preg_match('/apple|baidu|bingbot|facebookexternalhit|googlebot|-google|ia_archiver|msnbot|naverbot|pingdom|seznambot|slurp|teoma|twitter|yandex|yeti/i', $_SERVER['HTTP_USER_AGENT'])) {
// allowed bot
}
An unwanted bot (= false-positive user) is then able to solve a captcha to unblock himself for 24 hours. And as no one solves this captcha, I know it does not produce false-positives. So the bot detection seem to work perfectly.
Note: My whitelist is based on Facebooks robots.txt.
How to make a <div> or <a href="#"> to align center
You can use the code below:
a {
display: block;
width: 113px;
margin: auto;
}
By setting, in my case, the link to display:block
, it is easier
to position the link.
This works the same when you use a <div>
tag/class.
You can pick any width
you want.
JSON order mixed up
Underscore-java uses linkedhashmap to store key/value for json. I am the maintainer of the project.
Map<String, Object> myObject = new LinkedHashMap<>();
myObject.put("userid", "User 1");
myObject.put("amount", "24.23");
myObject.put("success", "NO");
System.out.println(U.toJson(myObject));
What does yield mean in PHP?
An interesting aspect, which worth to be discussed here, is yielding by reference. Every time we need to change a parameter such that it is reflected outside of the function, we have to pass this parameter by reference. To apply this to generators, we simply prepend an ampersand &
to the name of the generator and to the variable used in the iteration:
<?php
/**
* Yields by reference.
* @param int $from
*/
function &counter($from) {
while ($from > 0) {
yield $from;
}
}
foreach (counter(100) as &$value) {
$value--;
echo $value . '...';
}
// Output: 99...98...97...96...95...
The above example shows how changing the iterated values within the foreach
loop changes the $from
variable within the generator. This is because $from
is yielded by reference due to the ampersand before the generator name. Because of that, the $value
variable within the foreach
loop is a reference to the $from
variable within the generator function.
Bootstrap 4 - Glyphicons migration?
Bootstrap 4 files do not come with the glyphicon support. But you can simply open up your bootstrap.css or bootstrap.min.css and paste this code which I came across here.
@font-face{font-family:'Glyphicons Halflings';src:url('https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot');src:url('https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),url('https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.woff') format('woff'),url('https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.ttf') format('truetype'),url('https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing:antialiased;}
.glyphicon-asterisk:before{content:"\2a";}
.glyphicon-plus:before{content:"\2b";}
.glyphicon-euro:before{content:"\20ac";}
.glyphicon-minus:before{content:"\2212";}
.glyphicon-cloud:before{content:"\2601";}
.glyphicon-envelope:before{content:"\2709";}
.glyphicon-pencil:before{content:"\270f";}
.glyphicon-glass:before{content:"\e001";}
.glyphicon-music:before{content:"\e002";}
.glyphicon-search:before{content:"\e003";}
.glyphicon-heart:before{content:"\e005";}
.glyphicon-star:before{content:"\e006";}
.glyphicon-star-empty:before{content:"\e007";}
.glyphicon-user:before{content:"\e008";}
.glyphicon-film:before{content:"\e009";}
.glyphicon-th-large:before{content:"\e010";}
.glyphicon-th:before{content:"\e011";}
.glyphicon-th-list:before{content:"\e012";}
.glyphicon-ok:before{content:"\e013";}
.glyphicon-remove:before{content:"\e014";}
.glyphicon-zoom-in:before{content:"\e015";}
.glyphicon-zoom-out:before{content:"\e016";}
.glyphicon-off:before{content:"\e017";}
.glyphicon-signal:before{content:"\e018";}
.glyphicon-cog:before{content:"\e019";}
.glyphicon-trash:before{content:"\e020";}
.glyphicon-home:before{content:"\e021";}
.glyphicon-file:before{content:"\e022";}
.glyphicon-time:before{content:"\e023";}
.glyphicon-road:before{content:"\e024";}
.glyphicon-download-alt:before{content:"\e025";}
.glyphicon-download:before{content:"\e026";}
.glyphicon-upload:before{content:"\e027";}
.glyphicon-inbox:before{content:"\e028";}
.glyphicon-play-circle:before{content:"\e029";}
.glyphicon-repeat:before{content:"\e030";}
.glyphicon-refresh:before{content:"\e031";}
.glyphicon-list-alt:before{content:"\e032";}
.glyphicon-flag:before{content:"\e034";}
.glyphicon-headphones:before{content:"\e035";}
.glyphicon-volume-off:before{content:"\e036";}
.glyphicon-volume-down:before{content:"\e037";}
.glyphicon-volume-up:before{content:"\e038";}
.glyphicon-qrcode:before{content:"\e039";}
.glyphicon-barcode:before{content:"\e040";}
.glyphicon-tag:before{content:"\e041";}
.glyphicon-tags:before{content:"\e042";}
.glyphicon-book:before{content:"\e043";}
.glyphicon-print:before{content:"\e045";}
.glyphicon-font:before{content:"\e047";}
.glyphicon-bold:before{content:"\e048";}
.glyphicon-italic:before{content:"\e049";}
.glyphicon-text-height:before{content:"\e050";}
.glyphicon-text-width:before{content:"\e051";}
.glyphicon-align-left:before{content:"\e052";}
.glyphicon-align-center:before{content:"\e053";}
.glyphicon-align-right:before{content:"\e054";}
.glyphicon-align-justify:before{content:"\e055";}
.glyphicon-list:before{content:"\e056";}
.glyphicon-indent-left:before{content:"\e057";}
.glyphicon-indent-right:before{content:"\e058";}
.glyphicon-facetime-video:before{content:"\e059";}
.glyphicon-picture:before{content:"\e060";}
.glyphicon-map-marker:before{content:"\e062";}
.glyphicon-adjust:before{content:"\e063";}
.glyphicon-tint:before{content:"\e064";}
.glyphicon-edit:before{content:"\e065";}
.glyphicon-share:before{content:"\e066";}
.glyphicon-check:before{content:"\e067";}
.glyphicon-move:before{content:"\e068";}
.glyphicon-step-backward:before{content:"\e069";}
.glyphicon-fast-backward:before{content:"\e070";}
.glyphicon-backward:before{content:"\e071";}
.glyphicon-play:before{content:"\e072";}
.glyphicon-pause:before{content:"\e073";}
.glyphicon-stop:before{content:"\e074";}
.glyphicon-forward:before{content:"\e075";}
.glyphicon-fast-forward:before{content:"\e076";}
.glyphicon-step-forward:before{content:"\e077";}
.glyphicon-eject:before{content:"\e078";}
.glyphicon-chevron-left:before{content:"\e079";}
.glyphicon-chevron-right:before{content:"\e080";}
.glyphicon-plus-sign:before{content:"\e081";}
.glyphicon-minus-sign:before{content:"\e082";}
.glyphicon-remove-sign:before{content:"\e083";}
.glyphicon-ok-sign:before{content:"\e084";}
.glyphicon-question-sign:before{content:"\e085";}
.glyphicon-info-sign:before{content:"\e086";}
.glyphicon-screenshot:before{content:"\e087";}
.glyphicon-remove-circle:before{content:"\e088";}
.glyphicon-ok-circle:before{content:"\e089";}
.glyphicon-ban-circle:before{content:"\e090";}
.glyphicon-arrow-left:before{content:"\e091";}
.glyphicon-arrow-right:before{content:"\e092";}
.glyphicon-arrow-up:before{content:"\e093";}
.glyphicon-arrow-down:before{content:"\e094";}
.glyphicon-share-alt:before{content:"\e095";}
.glyphicon-resize-full:before{content:"\e096";}
.glyphicon-resize-small:before{content:"\e097";}
.glyphicon-exclamation-sign:before{content:"\e101";}
.glyphicon-gift:before{content:"\e102";}
.glyphicon-leaf:before{content:"\e103";}
.glyphicon-eye-open:before{content:"\e105";}
.glyphicon-eye-close:before{content:"\e106";}
.glyphicon-warning-sign:before{content:"\e107";}
.glyphicon-plane:before{content:"\e108";}
.glyphicon-random:before{content:"\e110";}
.glyphicon-comment:before{content:"\e111";}
.glyphicon-magnet:before{content:"\e112";}
.glyphicon-chevron-up:before{content:"\e113";}
.glyphicon-chevron-down:before{content:"\e114";}
.glyphicon-retweet:before{content:"\e115";}
.glyphicon-shopping-cart:before{content:"\e116";}
.glyphicon-folder-close:before{content:"\e117";}
.glyphicon-folder-open:before{content:"\e118";}
.glyphicon-resize-vertical:before{content:"\e119";}
.glyphicon-resize-horizontal:before{content:"\e120";}
.glyphicon-hdd:before{content:"\e121";}
.glyphicon-bullhorn:before{content:"\e122";}
.glyphicon-certificate:before{content:"\e124";}
.glyphicon-thumbs-up:before{content:"\e125";}
.glyphicon-thumbs-down:before{content:"\e126";}
.glyphicon-hand-right:before{content:"\e127";}
.glyphicon-hand-left:before{content:"\e128";}
.glyphicon-hand-up:before{content:"\e129";}
.glyphicon-hand-down:before{content:"\e130";}
.glyphicon-circle-arrow-right:before{content:"\e131";}
.glyphicon-circle-arrow-left:before{content:"\e132";}
.glyphicon-circle-arrow-up:before{content:"\e133";}
.glyphicon-circle-arrow-down:before{content:"\e134";}
.glyphicon-globe:before{content:"\e135";}
.glyphicon-tasks:before{content:"\e137";}
.glyphicon-filter:before{content:"\e138";}
.glyphicon-fullscreen:before{content:"\e140";}
.glyphicon-dashboard:before{content:"\e141";}
.glyphicon-heart-empty:before{content:"\e143";}
.glyphicon-link:before{content:"\e144";}
.glyphicon-phone:before{content:"\e145";}
.glyphicon-usd:before{content:"\e148";}
.glyphicon-gbp:before{content:"\e149";}
.glyphicon-sort:before{content:"\e150";}
.glyphicon-sort-by-alphabet:before{content:"\e151";}
.glyphicon-sort-by-alphabet-alt:before{content:"\e152";}
.glyphicon-sort-by-order:before{content:"\e153";}
.glyphicon-sort-by-order-alt:before{content:"\e154";}
.glyphicon-sort-by-attributes:before{content:"\e155";}
.glyphicon-sort-by-attributes-alt:before{content:"\e156";}
.glyphicon-unchecked:before{content:"\e157";}
.glyphicon-expand:before{content:"\e158";}
.glyphicon-collapse-down:before{content:"\e159";}
.glyphicon-collapse-up:before{content:"\e160";}
.glyphicon-log-in:before{content:"\e161";}
.glyphicon-flash:before{content:"\e162";}
.glyphicon-log-out:before{content:"\e163";}
.glyphicon-new-window:before{content:"\e164";}
.glyphicon-record:before{content:"\e165";}
.glyphicon-save:before{content:"\e166";}
.glyphicon-open:before{content:"\e167";}
.glyphicon-saved:before{content:"\e168";}
.glyphicon-import:before{content:"\e169";}
.glyphicon-export:before{content:"\e170";}
.glyphicon-send:before{content:"\e171";}
.glyphicon-floppy-disk:before{content:"\e172";}
.glyphicon-floppy-saved:before{content:"\e173";}
.glyphicon-floppy-remove:before{content:"\e174";}
.glyphicon-floppy-save:before{content:"\e175";}
.glyphicon-floppy-open:before{content:"\e176";}
.glyphicon-credit-card:before{content:"\e177";}
.glyphicon-transfer:before{content:"\e178";}
.glyphicon-cutlery:before{content:"\e179";}
.glyphicon-header:before{content:"\e180";}
.glyphicon-compressed:before{content:"\e181";}
.glyphicon-earphone:before{content:"\e182";}
.glyphicon-phone-alt:before{content:"\e183";}
.glyphicon-tower:before{content:"\e184";}
.glyphicon-stats:before{content:"\e185";}
.glyphicon-sd-video:before{content:"\e186";}
.glyphicon-hd-video:before{content:"\e187";}
.glyphicon-subtitles:before{content:"\e188";}
.glyphicon-sound-stereo:before{content:"\e189";}
.glyphicon-sound-dolby:before{content:"\e190";}
.glyphicon-sound-5-1:before{content:"\e191";}
.glyphicon-sound-6-1:before{content:"\e192";}
.glyphicon-sound-7-1:before{content:"\e193";}
.glyphicon-copyright-mark:before{content:"\e194";}
.glyphicon-registration-mark:before{content:"\e195";}
.glyphicon-cloud-download:before{content:"\e197";}
.glyphicon-cloud-upload:before{content:"\e198";}
.glyphicon-tree-conifer:before{content:"\e199";}
.glyphicon-tree-deciduous:before{content:"\e200";}
.glyphicon-briefcase:before{content:"\1f4bc";}
.glyphicon-calendar:before{content:"\1f4c5";}
.glyphicon-pushpin:before{content:"\1f4cc";}
.glyphicon-paperclip:before{content:"\1f4ce";}
.glyphicon-camera:before{content:"\1f4f7";}
.glyphicon-lock:before{content:"\1f512";}
.glyphicon-bell:before{content:"\1f514";}
.glyphicon-bookmark:before{content:"\1f516";}
.glyphicon-fire:before{content:"\1f525";}
.glyphicon-wrench:before{content:"\1f527";}
Adding blank spaces to layout
Agree with all the answers......also,
<TextView android:text=""
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_weight="2" />
should work :) I am just messing with others as TextView is my favourite (waste of memory though!)
Difference between shared objects (.so), static libraries (.a), and DLL's (.so)?
I've always thought that DLLs and shared objects are just different terms for the same thing - Windows calls them DLLs, while on UNIX systems they're shared objects, with the general term - dynamically linked library - covering both (even the function to open a .so on UNIX is called dlopen()
after 'dynamic library').
They are indeed only linked at application startup, however your notion of verification against the header file is incorrect. The header file defines prototypes which are required in order to compile the code which uses the library, but at link time the linker looks inside the library itself to make sure the functions it needs are actually there. The linker has to find the function bodies somewhere at link time or it'll raise an error. It ALSO does that at runtime, because as you rightly point out the library itself might have changed since the program was compiled. This is why ABI stability is so important in platform libraries, as the ABI changing is what breaks existing programs compiled against older versions.
Static libraries are just bundles of object files straight out of the compiler, just like the ones that you are building yourself as part of your project's compilation, so they get pulled in and fed to the linker in exactly the same way, and unused bits are dropped in exactly the same way.
HTML&CSS + Twitter Bootstrap: full page layout or height 100% - Npx
I've found a post here on Stackoverflow and implemented your design:
http://jsfiddle.net/bKsad/25/
Here's the original post: https://stackoverflow.com/a/5768262/1368423
Is that what you're looking for?
HTML:
<div class="container-fluid wrapper">
<div class="row-fluid columns content">
<div class="span2 article-tree">
navigation column
</div>
<div class="span10 content-area">
content column
</div>
</div>
<div class="footer">
footer content
</div>
</div>
CSS:
html, body {
height: 100%;
}
.container-fluid {
margin: 0 auto;
height: 100%;
padding: 20px 0;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
.columns {
background-color: #C9E6FF;
height: 100%;
}
.content-area, .article-tree{
background: #bada55;
overflow:auto;
height: 100%;
}
.footer {
background: red;
height: 20px;
}
include external .js file in node.js app
To place an emphasis on what everyone else has been saying var foo
in top level does not create a global variable. If you want a global variable then write global.foo
. but we all know globals are evil.
If you are someone who uses globals like that in a node.js project I was on I would refactor them away for as there are just so few use cases for this (There are a few exceptions but this isn't one).
// Declare application
var app = require('express').createServer();
// Declare usefull stuff for DB purposes
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
require('./models/car.js').make(Schema, mongoose);
in car.js
function make(Schema, mongoose) {
// Define Car model
CarSchema = new Schema({
brand : String,
type : String
});
mongoose.model('Car', CarSchema);
}
module.exports.make = make;
WCF error: The caller was not authenticated by the service
If you use basicHttpBinding, configure the endpoint security to "None" and transport clientCredintialType to "None."
<bindings>
<basicHttpBinding>
<binding name="MyBasicHttpBinding">
<security mode="None">
<transport clientCredentialType="None" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="MyServiceBehavior" name="MyService">
<endpoint
binding="basicHttpBinding"
bindingConfiguration="MyBasicHttpBinding"
name="basicEndPoint"
contract="IMyService"
/>
</service>
Also, make sure the directory Authentication Methods in IIS to Enable Anonymous access
Get root password for Google Cloud Engine VM
I tried "ManiIOT"'s solution and it worked surprisingly.
I've added another role (Compute Admin Role) for my google user account from IAM admin. Then stopped and restarted the VM.
Afterwards 'sudo passwd' let me to generate a new password for the user.
So here are steps.
- Go to IAM & Admin
- Select IAM
- Find your user name service account (basically your google account) and click Edit-member
- Add another role --> select 'Compute Engine' - 'Compute Admin'
- Restart your Compute VM
- open SSH shell and run the command 'sudo passwd'
- enter a brand new password. Voilà!
LEFT JOIN only first row
I want to give a more generalized answer. One that will handle any case when you want to select only the first item in a LEFT JOIN.
You can use a subquery that GROUP_CONCATS what you want (sorted, too!), then just split the GROUP_CONCAT'd result and take only its first item, like so...
LEFT JOIN Person ON Person.id = (
SELECT SUBSTRING_INDEX(
GROUP_CONCAT(FirstName ORDER BY FirstName DESC SEPARATOR "_" ), '_', 1)
) FROM Person
);
Since we have DESC as our ORDER BY option, this will return a Person id for someone like "Zack". If we wanted someone with the name like "Andy", we would change ORDER BY FirstName DESC to ORDER BY FirstName ASC.
This is nimble, as this places the power of ordering totally within your hands. But, after much testing, it will not scale well in a situation with lots of users and lots of data.
It is, however, useful in running data-intensive reports for admin.
Getting result of dynamic SQL into a variable for sql-server
dynamic version
ALTER PROCEDURE [dbo].[ReseedTableIdentityCol](@p_table varchar(max))-- RETURNS int
AS
BEGIN
-- Declare the return variable here
DECLARE @sqlCommand nvarchar(1000)
DECLARE @maxVal INT
set @sqlCommand = 'SELECT @maxVal = ISNULL(max(ID),0)+1 from '+@p_table
EXECUTE sp_executesql @sqlCommand, N'@maxVal int OUTPUT',@maxVal=@maxVal OUTPUT
DBCC CHECKIDENT(@p_table, RESEED, @maxVal)
END
exec dbo.ReseedTableIdentityCol @p_table='Junk'
How to use getJSON, sending data with post method?
I had code that was doing getJSON. I simply replaced it with post. To my surprise, it worked
$.post("@Url.Action("Command")", { id: id, xml: xml })
.done(function (response) {
// stuff
})
.fail(function (jqxhr, textStatus, error) {
// stuff
});
[HttpPost]
public JsonResult Command(int id, string xml)
{
// stuff
}
numpy max vs amax vs maximum
np.max
is just an alias for np.amax
. This function only works on a single input array and finds the value of maximum element in that entire array (returning a scalar). Alternatively, it takes an axis
argument and will find the maximum value along an axis of the input array (returning a new array).
>>> a = np.array([[0, 1, 6],
[2, 4, 1]])
>>> np.max(a)
6
>>> np.max(a, axis=0) # max of each column
array([2, 4, 6])
The default behaviour of np.maximum
is to take two arrays and compute their element-wise maximum. Here, 'compatible' means that one array can be broadcast to the other. For example:
>>> b = np.array([3, 6, 1])
>>> c = np.array([4, 2, 9])
>>> np.maximum(b, c)
array([4, 6, 9])
But np.maximum
is also a universal function which means that it has other features and methods which come in useful when working with multidimensional arrays. For example you can compute the cumulative maximum over an array (or a particular axis of the array):
>>> d = np.array([2, 0, 3, -4, -2, 7, 9])
>>> np.maximum.accumulate(d)
array([2, 2, 3, 3, 3, 7, 9])
This is not possible with np.max
.
You can make np.maximum
imitate np.max
to a certain extent when using np.maximum.reduce
:
>>> np.maximum.reduce(d)
9
>>> np.max(d)
9
Basic testing suggests the two approaches are comparable in performance; and they should be, as np.max()
actually calls np.maximum.reduce
to do the computation.
How can I read the contents of an URL with Python?
You can use requests
and beautifulsoup
libraries to read data on a website. Just install these two libraries and type the following code.
import requests
import bs4
help(requests)
help(bs4)
You will get all the information you need about the library.
how to make label visible/invisible?
You are looking for display:
document.getElementById("endTimeLabel").style.display = 'none';
document.getElementById("endTimeLabel").style.display = 'block';
Edit: You could also easily reuse your validation function.
HTML:
<span id="startDateLabel">Start date/time: </span>
<input id="startDateStr" name="startDateStr" size="8" onchange="if (!formatDate(this,'USA')) {this.value = '';}" />
<button id="startDateCalendarTrigger">...</button>
<input id="startDateTime" type="text" size="8" name="startTime" value="12:00 AM" onchange="validateHHMM(this.value, 'startTimeLabel');"/>
<label id="startTimeLabel" class="errorMsg">Time must be entered in the format HH:MM AM/PM</label><br />
<span id="endDateLabel">End date/time: </span>
<input id="endDateStr" name="endDateStr" size="8" onchange="if (!formatDate(this,'USA')) {this.value = '';}" />
<button id="endDateCalendarTrigger">...</button>
<input id="endDateTime" type="text" size="8" name="endTime" value="12:00 AM" onchange="validateHHMM(this.value, 'endTimeLabel');"/>
<label id="endTimeLabel" class="errorMsg">Time must be entered in the format HH:MM AM/PM</label>
Javascript:
function validateHHMM(value, message) {
var isValid = /^(0?[1-9]|1[012])(:[0-5]\d) [APap][mM]$/.test(value);
if (isValid) {
document.getElementById(message).style.display = "none";
}else {
document.getElementById(message).style.display= "inline";
}
return isValid;
}
Live DEMO
putting datepicker() on dynamically created elements - JQuery/JQueryUI
This is what worked for me on JQuery 1.3 and is showing on the first click/focus
function vincularDatePickers() {
$('.mostrar_calendario').live('click', function () {
$(this).datepicker({ showButtonPanel: true, changeMonth: true, changeYear: true, showOn: 'focus' }).focus();
});
}
this needs that your input have the class 'mostrar_calendario'
Live is for JQuery 1.3+ for newer versions you need to adapt this to "on"
See more about the difference here http://api.jquery.com/live/
IF EXISTS condition not working with PLSQL
Unfortunately PL/SQL doesn't have IF EXISTS
operator like SQL Server. But you can do something like this:
begin
for x in ( select count(*) cnt
from dual
where exists (
select 1 from courseoffering co
join co_enrolment ce on ce.co_id = co.co_id
where ce.s_regno = 403
and ce.coe_completionstatus = 'C'
and co.c_id = 803 ) )
loop
if ( x.cnt = 1 )
then
dbms_output.put_line('exists');
else
dbms_output.put_line('does not exist');
end if;
end loop;
end;
/
Create 3D array using Python
There are many ways to address your problem.
- First one as accepted answer by @robert. Here is the generalised
solution for it:
def multi_dimensional_list(value, *args):
#args dimensions as many you like. EG: [*args = 4,3,2 => x=4, y=3, z=2]
#value can only be of immutable type. So, don't pass a list here. Acceptable value = 0, -1, 'X', etc.
if len(args) > 1:
return [ multi_dimensional_list(value, *args[1:]) for col in range(args[0])]
elif len(args) == 1: #base case of recursion
return [ value for col in range(args[0])]
else: #edge case when no values of dimensions is specified.
return None
Eg:
>>> multi_dimensional_list(-1, 3, 4) #2D list
[[-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1]]
>>> multi_dimensional_list(-1, 4, 3, 2) #3D list
[[[-1, -1], [-1, -1], [-1, -1]], [[-1, -1], [-1, -1], [-1, -1]], [[-1, -1], [-1, -1], [-1, -1]], [[-1, -1], [-1, -1], [-1, -1]]]
>>> multi_dimensional_list(-1, 2, 3, 2, 2 ) #4D list
[[[[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]]], [[[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]]]]
P.S If you are keen to do validation for correct values for args i.e. only natural numbers, then you can write a wrapper function before calling this function.
- Secondly, any multidimensional dimensional array can be written as single dimension array. This means you don't need a multidimensional array. Here are the function for indexes conversion:
def convert_single_to_multi(value, max_dim):
dim_count = len(max_dim)
values = [0]*dim_count
for i in range(dim_count-1, -1, -1): #reverse iteration
values[i] = value%max_dim[i]
value /= max_dim[i]
return values
def convert_multi_to_single(values, max_dim):
dim_count = len(max_dim)
value = 0
length_of_dimension = 1
for i in range(dim_count-1, -1, -1): #reverse iteration
value += values[i]*length_of_dimension
length_of_dimension *= max_dim[i]
return value
Since, these functions are inverse of each other, here is the output:
>>> convert_single_to_multi(convert_multi_to_single([1,4,6,7],[23,45,32,14]),[23,45,32,14])
[1, 4, 6, 7]
>>> convert_multi_to_single(convert_single_to_multi(21343,[23,45,32,14]),[23,45,32,14])
21343
- If you are concerned about performance issues then you can use some libraries like pandas, numpy, etc.
CSS - Expand float child DIV height to parent's height
I used this for a comment section:
_x000D_
_x000D_
.parent {_x000D_
display: flex;_x000D_
float: left;_x000D_
border-top:2px solid black;_x000D_
width:635px;_x000D_
margin:10px 0px 0px 0px;_x000D_
padding:0px 20px 0px 20px;_x000D_
background-color: rgba(255,255,255,0.5);_x000D_
}_x000D_
_x000D_
.child-left {_x000D_
align-items: stretch;_x000D_
float: left;_x000D_
width:135px;_x000D_
padding:10px 10px 10px 0px;_x000D_
height:inherit;_x000D_
border-right:2px solid black;_x000D_
}_x000D_
_x000D_
.child-right {_x000D_
align-items: stretch;_x000D_
float: left;_x000D_
width:468px;_x000D_
padding:10px;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child-left">Short</div>_x000D_
<div class="child-right">Tall<br>Tall</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
You could float the child-right to the right, but in this case I've calculated the widths of each div precisely.
Display label text with line breaks in c#
You may append HTML <br />
in between your lines. Something like:
MyLabel.Text = "SomeText asdfa asd fas df asdf" + "<br />" + "Some more text";
With StringBuilder you can try:
StringBuilder sb = new StringBuilder();
sb.AppendLine("Some text with line one");
sb.AppendLine("Some mpre text with line two");
MyLabel.Text = sb.ToString().Replace(Environment.NewLine, "<br />");
How to redirect output of an already running process
Dupx
Dupx is a simple *nix utility to redirect standard output/input/error of an already running process.
Motivation
I've often found myself in a situation where a process I started on a remote system via SSH takes much longer than I had anticipated. I need to break the SSH connection, but if I do so, the process will die if it tries to write something on stdout/error of a broken pipe. I wish I could suspend the process with ^Z and then do a
bg %1 >/tmp/stdout 2>/tmp/stderr
Unfortunately this will not work (in shells I know).
http://www.isi.edu/~yuri/dupx/
How can I create a table with borders in Android?
I have to agree with Brad. That was an awful answer. The Android documentation states that TableLayout containers do not display border lines, so sending them to the Android site wont help them a bit. I was able to find a "dirty" solution on droidnova, which involves setting a background color for the TableLayout, then setting a different background color for the TableRow and adding layout_margin to the row. I'm not fond of this solution, but it does work for row borders. I guess you could do the same thing with the items composing each "cell" item but I haven't verified.
An example similar to the one on DroidNova:
<TableLayout android:background="#000000"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableRow android:background="#FFFFFF"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="1dp">
...
</TableRow>
</TableLayout>
How do I inject a controller into another controller in AngularJS
I'd suggest the question you should be asking is how to inject services into controllers. Fat services with skinny controllers is a good rule of thumb, aka just use controllers to glue your service/factory (with the business logic) into your views.
Controllers get garbage collected on route changes, so for example, if you use controllers to hold business logic that renders a value, your going to lose state on two pages if the app user clicks the browser back button.
var app = angular.module("testApp", ['']);
app.factory('methodFactory', function () {
return { myMethod: function () {
console.log("methodFactory - myMethod");
};
};
app.controller('TestCtrl1', ['$scope', 'methodFactory', function ($scope,methodFactory) { //Comma was missing here.Now it is corrected.
$scope.mymethod1 = methodFactory.myMethod();
}]);
app.controller('TestCtrl2', ['$scope', 'methodFactory', function ($scope, methodFactory) {
$scope.mymethod2 = methodFactory.myMethod();
}]);
Here is a working demo of factory injected into two controllers
Also, I'd suggest having a read of this tutorial on services/factories.
How do I open a Visual Studio project in design view?
My problem, it showed an error called "The class Form1 can be designed, but is not the first class in the file. Visual Studio requires that designers use the first class in the file. Move the class code so that it is the first class in the file and try loading the designer again. ". So I moved the Form class to the first one and it worked. :)
Change image size with JavaScript
You can change the actual width/height attributes like this:
var theImg = document.getElementById('theImgId');
theImg.height = 150;
theImg.width = 150;
React - Component Full Screen (with height 100%)
While this may not be the ideal answer but try this:
style={{top:'0', bottom:'0', left:'0', right:'0', position: 'absolute'}}
It keeps the size attached to borders which is not what you want but gives you somewhat same effect.
How to convert array to SimpleXML
You can Use the following function in you code directly,
function artoxml($arr, $i=1,$flag=false){
$sp = "";
for($j=0;$j<=$i;$j++){
$sp.=" ";
}
foreach($arr as $key=>$val){
echo "$sp<".$key.">";
if($i==1) echo "\n";
if(is_array($val)){
if(!$flag){echo"\n";}
artoxml($val,$i+5);
echo "$sp</".$key.">\n";
}else{
echo "$val"."</".$key.">\n";
}
}
}
Call the function with first argument as your array and the second argument must be 1, this will be increased for perfect indentation, and third must be true.
for example, if the array variable to be converted is $array1 then,
calling would be, the calling function should be encapsulated with <pre>
tag.
artoxml($array1,1,true);
Please see the page source after executing the file, because the < and > symbols won't be displayed in a html page.
Oracle Insert via Select from multiple tables where one table may not have a row
A slightly simplified version of Oglester's solution (the sequence doesn't require a select from DUAL:
INSERT INTO account_type_standard
(account_type_Standard_id, tax_status_id, recipient_id)
VALUES(
account_type_standard_seq.nextval,
(SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?),
(SELECT recipient_id FROM recipient WHERE recipient_code = ?)
)
ERROR: Sonar server 'http://localhost:9000' can not be reached
For me the issue was that the maven sonar plugin was using proxy servers defined in the maven settings.xml. I was trying to access the sonarque on another (not localhost alias) and so it was trying to use the proxy server to access it. Just added my alias to nonProxyHosts in settings.xml and it is working now. I did not face this issue in maven sonar plugin 3.2, only after i upgraded it.
<proxy>
<id>proxy_id</id>
<active>true</active>
<protocol>http</protocol>
<host>your-proxy-host/host>
<port>your-proxy-host</port>
<nonProxyHosts>localhost|127.0.*|other-non-proxy-hosts</nonProxyHosts>
</proxy>enter code here
What do these operators mean (** , ^ , %, //)?
You are correct that **
is the power function.
^
is bitwise XOR.
%
is indeed the modulus operation, but note that for positive numbers, x % m = x
whenever m > x
. This follows from the definition of modulus. (Additionally, Python specifies x % m
to have the sign of m
.)
//
is a division operation that returns an integer by discarding the remainder. This is the standard form of division using the /
in most programming languages. However, Python 3 changed the behavior of /
to perform floating-point division even if the arguments are integers. The //
operator was introduced in Python 2.6 and Python 3 to provide an integer-division operator that would behave consistently between Python 2 and Python 3. This means:
| context | `/` behavior | `//` behavior |
---------------------------------------------------------------------------
| floating-point arguments, Python 2 & 3 | float division | int divison |
---------------------------------------------------------------------------
| integer arguments, python 2 | int division | int division |
---------------------------------------------------------------------------
| integer arguments, python 3 | float division | int division |
For more details, see this question: Division in Python 2.7. and 3.3
What is a handle in C++?
A handle is a sort of pointer in that it is typically a way of referencing some entity.
It would be more accurate to say that a pointer is one type of handle, but not all handles are pointers.
For example, a handle may also be some index into an in memory table, which corresponds to an entry that itself contains a pointer to some object.
The key thing is that when you have a "handle", you neither know nor care how that handle actually ends up identifying the thing that it identifies, all you need to know is that it does.
It should also be obvious that there is no single answer to "what exactly is a handle", because handles to different things, even in the same system, may be implemented in different ways "under the hood". But you shouldn't need to be concerned with those differences.
How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?
I am also looking for an answer to this question, (to clarify, I want to be able to draw an image with user defined opacity such as how you can draw shapes with opacity) if you draw with primitive shapes you can set fill and stroke color with alpha to define the transparency. As far as I have concluded right now, this does not seem to affect image drawing.
//works with shapes but not with images
ctx.fillStyle = "rgba(255, 255, 255, 0.5)";
I have concluded that setting the globalCompositeOperation
works with images.
//works with images
ctx.globalCompositeOperation = "lighter";
I wonder if there is some kind third way of setting color so that we can tint images and make them transparent easily.
EDIT:
After further digging I have concluded that you can set the transparency of an image by setting the globalAlpha
parameter BEFORE you draw the image:
//works with images
ctx.globalAlpha = 0.5
If you want to achieve a fading effect over time you need some kind of loop that changes the alpha value, this is fairly easy, one way to achieve it is the setTimeout
function, look that up to create a loop from which you alter the alpha over time.
Change grid interval and specify tick labels in Matplotlib
There are several problems in your code.
First the big ones:
You are creating a new figure and a new axes in every iteration of your loop ?
put fig = plt.figure
and ax = fig.add_subplot(1,1,1)
outside of the loop.
Don't use the Locators. Call the functions ax.set_xticks()
and ax.grid()
with the correct keywords.
With plt.axes()
you are creating a new axes again. Use ax.set_aspect('equal')
.
The minor things:
You should not mix the MATLAB-like syntax like plt.axis()
with the objective syntax.
Use ax.set_xlim(a,b)
and ax.set_ylim(a,b)
This should be a working minimal example:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
# Major ticks every 20, minor ticks every 5
major_ticks = np.arange(0, 101, 20)
minor_ticks = np.arange(0, 101, 5)
ax.set_xticks(major_ticks)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)
# And a corresponding grid
ax.grid(which='both')
# Or if you want different settings for the grids:
ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=0.5)
plt.show()
Output is this:
Python speed testing - Time Difference - milliseconds
Since Python 2.7 there's the timedelta.total_seconds() method. So, to get the elapsed milliseconds:
>>> import datetime
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> delta = b - a
>>> print delta
0:00:05.077263
>>> int(delta.total_seconds() * 1000) # milliseconds
5077
Remote debugging a Java application
Edit: I noticed that some people are cutting and pasting the invocation here. The answer I originally gave was relevant for the OP only. Here's a more modern invocation style (including using the more conventional port of 8000):
java -agentlib:jdwp=transport=dt_socket,server=y,address=8000,suspend=n <other arguments>
Original answer follows.
Try this:
java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n myapp
Two points here:
- No spaces in the
runjdwp
option.
- Options come before the class name. Any arguments you have after the class name are arguments to your program!
Installing SetupTools on 64-bit Windows
I tried the above and adding the registry keys to the LOCALMACHINE was not getting the job done. So in case you are still stuck , try this.
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\SOFTWARE\Python]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\Help]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\Help\Main Python Documentation]
@="C:\Python27\Doc\python272.chm"
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\InstallPath]
@="C:\Python27\"
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\InstallPath\InstallGroup]
@="Python 2.7"
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\Modules]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\PythonPath]
@="C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk"
Copy paste the above in notepad and save it as Python27.reg . Now run/merge the file as mentioned in the answers above. (Make sure the paths of Python installation are corrected as per your installation.
It simply does ,what the above answers suggest for a local machine ,to the current user.
Vertical Text Direction
To rotate text 90 degrees:
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-ms-transform: rotate(90deg);
-o-transform: rotate(90deg);
transform: rotate(90deg);
Also, it appears that the span tag can't be rotated without being set to display:block.
How to add an extra column to a NumPy array
A bit late to the party, but nobody posted this answer yet, so for the sake of completeness: you can do this with list comprehensions, on a plain Python array:
source = a.tolist()
result = [row + [0] for row in source]
b = np.array(result)
Print multiple arguments in Python
This was probably a casting issue
. Casting syntax
happens when you try to combine two different types of variables
. Since we cannot convert a string
to an integer
or float
always, we have to convert our integers
into a string
. This is how you do it.: str(x)
. To convert to a integer, it's: int(x)
, and a float is float(x)
. Our code will be:
print('Total score for ' + str(name) + ' is ' + str(score))
Also! Run this snippet
to see a table of how to convert different types of variables
!
_x000D_
_x000D_
<table style="border-collapse: collapse; width: 100%;background-color:maroon; color: #00b2b2;">
<tbody>
<tr>
<td style="width: 50%;font-family: serif; padding: 3px;">Booleans</td>
<td style="width: 50%;font-family: serif; padding: 3px;"><code>bool()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding: 3px">Dictionaries</td>
<td style="width: 50%;font-family: serif;padding: 3px"><code>dict()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding: 3px">Floats</td>
<td style="width: 50%;font-family: serif;padding: 3px"><code>float()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding:3px">Integers</td>
<td style="width: 50%;font-family: serif;padding:3px;"><code>int()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding: 3px">Lists</td>
<td style="width: 50%font-family: serif;padding: 3px;"><code>list()</code></td>
</tr>
</tbody>
</table>
_x000D_
_x000D_
_x000D_
MAC addresses in JavaScript
If this is for an intranet application and all of the clients use DHCP, you can query the DHCP server for the MAC address for a given IP address.
Why does jQuery or a DOM method such as getElementById not find the element?
Reasons why id based selectors don't work
- The element/DOM with id specified doesn't exist yet.
- The element exists, but it is not registered in DOM [in case of HTML nodes appended dynamically from Ajax responses].
- More than one element with the same id is present which is causing a conflict.
Solutions
Try to access the element after its declaration or alternatively use stuff like $(document).ready();
For elements coming from Ajax responses, use the .bind()
method of jQuery. Older versions of jQuery had .live()
for the same.
Use tools [for example, webdeveloper plugin for browsers] to find duplicate ids and remove them.
Skipping Incompatible Libraries at compile
Normally, that is not an error per se; it is a warning that the first file it found that matches the -lPI-Http
argument to the compiler/linker is not valid. The error occurs when no other library can be found with the right content.
So, you need to look to see whether /dvlpmnt/libPI-Http.a
is a library of 32-bit object files or of 64-bit object files - it will likely be 64-bit if you are compiling with the -m32
option. Then you need to establish whether there is an alternative libPI-Http.a
or libPI-Http.so
file somewhere else that is 32-bit. If so, ensure that the directory that contains it is listed in a -L/some/where
argument to the linker. If not, then you will need to obtain or build a 32-bit version of the library from somewhere.
To establish what is in that library, you may need to do:
mkdir junk
cd junk
ar x /dvlpmnt/libPI-Http.a
file *.o
cd ..
rm -fr junk
The 'file
' step tells you what type of object files are in the archive. The rest just makes sure you don't make a mess that can't be easily cleaned up.
Android Studio 3.0 Flavor Dimension Issue
Here you can resolve this issue, you need to add flavorDimension with productFlavors's name and need to define dimension as well, see below example and for more information see here https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html
flavorDimensions 'yourAppName' //here defined dimensions
productFlavors {
production {
dimension 'yourAppName' //you just need to add this line
//here you no need to write applicationIdSuffix because by default it will point to your app package which is also available inside manifest.xml file.
}
staging {
dimension 'yourAppName' //added here also
applicationIdSuffix ".staging"//(.staging) will be added after your default package name.
//or you can also use applicationId="your_package_name.staging" instead of applicationIdSuffix but remember if you are using applicationId then You have to mention full package name.
//versionNameSuffix "-staging"
}
develop {
dimension 'yourAppName' //add here too
applicationIdSuffix ".develop"
//versionNameSuffix "-develop"
}
:: (double colon) operator in Java 8
The previous answers are quite complete regarding what ::
method reference does. To sum up, it provides a way to refer to a method(or constructor) without executing it, and when evaluated, it creates an instance of the functional interface that provides the target type context.
Below are two examples to find an object with the max value in an ArrayList
WITH and WITHOUT the use of ::
method reference. Explanations are in the comments below.
WITHOUT the use of ::
import java.util.*;
class MyClass {
private int val;
MyClass (int v) { val = v; }
int getVal() { return val; }
}
class ByVal implements Comparator<MyClass> {
// no need to create this class when using method reference
public int compare(MyClass source, MyClass ref) {
return source.getVal() - ref.getVal();
}
}
public class FindMaxInCol {
public static void main(String args[]) {
ArrayList<MyClass> myClassList = new ArrayList<MyClass>();
myClassList.add(new MyClass(1));
myClassList.add(new MyClass(0));
myClassList.add(new MyClass(3));
myClassList.add(new MyClass(6));
MyClass maxValObj = Collections.max(myClassList, new ByVal());
}
}
WITH the use of ::
import java.util.*;
class MyClass {
private int val;
MyClass (int v) { val = v; }
int getVal() { return val; }
}
public class FindMaxInCol {
static int compareMyClass(MyClass source, MyClass ref) {
// This static method is compatible with the compare() method defined by Comparator.
// So there's no need to explicitly implement and create an instance of Comparator like the first example.
return source.getVal() - ref.getVal();
}
public static void main(String args[]) {
ArrayList<MyClass> myClassList = new ArrayList<MyClass>();
myClassList.add(new MyClass(1));
myClassList.add(new MyClass(0));
myClassList.add(new MyClass(3));
myClassList.add(new MyClass(6));
MyClass maxValObj = Collections.max(myClassList, FindMaxInCol::compareMyClass);
}
}
Entity Framework Join 3 Tables
I think it will be easier using syntax-based query:
var entryPoint = (from ep in dbContext.tbl_EntryPoint
join e in dbContext.tbl_Entry on ep.EID equals e.EID
join t in dbContext.tbl_Title on e.TID equals t.TID
where e.OwnerID == user.UID
select new {
UID = e.OwnerID,
TID = e.TID,
Title = t.Title,
EID = e.EID
}).Take(10);
And you should probably add orderby
clause, to make sure Top(10)
returns correct top ten items.
Nesting CSS classes
Not possible with vanilla CSS. However you can use something like:
Sass makes CSS fun again. Sass is an
extension of CSS3, adding nested
rules, variables, mixins, selector
inheritance, and more. It’s translated
to well-formatted, standard CSS using
the command line tool or a
web-framework plugin.
Or
Rather than constructing long selector
names to specify inheritance, in Less
you can simply nest selectors inside
other selectors. This makes
inheritance clear and style sheets
shorter.
Example:
#header {
color: red;
a {
font-weight: bold;
text-decoration: none;
}
}
rawQuery(query, selectionArgs)
String mQuery = "SELECT Name,Family From tblName";
Cursor mCur = db.rawQuery(mQuery, new String[]{});
mCur.moveToFirst();
while ( !mCur.isAfterLast()) {
String name= mCur.getString(mCur.getColumnIndex("Name"));
String family= mCur.getString(mCur.getColumnIndex("Family"));
mCur.moveToNext();
}
Name and family are your result
How can I invert color using CSS?
Add the same color of the background to the paragraph and then invert with CSS:
_x000D_
_x000D_
div {_x000D_
background-color: #f00;_x000D_
}_x000D_
_x000D_
p { _x000D_
color: #f00;_x000D_
-webkit-filter: invert(100%);_x000D_
filter: invert(100%);_x000D_
}
_x000D_
<div>_x000D_
<p>inverted color</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_
CSS3 transition events
Just for fun, don't do this!
$.fn.transitiondone = function () {
return this.each(function () {
var $this = $(this);
setTimeout(function () {
$this.trigger('transitiondone');
}, (parseFloat($this.css('transitionDelay')) + parseFloat($this.css('transitionDuration'))) * 1000);
});
};
$('div').on('mousedown', function (e) {
$(this).addClass('bounce').transitiondone();
});
$('div').on('transitiondone', function () {
$(this).removeClass('bounce');
});
How do I install SciPy on 64 bit Windows?
Okey, here I am going to share what I have done to install SciPy on my Windows PC without the command line.
My PC configuration is Windows 7 64-bit and Python 2.7
- First I download the required packages form http://www.lfd.uci.edu/~gohlke/pythonlibs/ (which version match your configuration EX: cp27==>python2.7 & cp35==>3.5)
- Second I extract the file using 7-Zip (also can be used any zipper like WinRAR)
- Third I copy the
scipy
folder which I extracted and paste it into C:\Python27\Lib\site-packages
(or put it where the exact location is in your PC like ..\..\Lib\site-packages
)
NOTE: You have to install NumPy first before installing SciPy in this same way.
Javascript change font color
You can use the HTML tag in order to apply font size, font color in one line on JavaScript, as well as you can use .fontcolor()
method to define color, .fontsize()
method to define the font size, .bold()
method to define bold, etc. These are called JavaScript Built-in Functions.
Here is a list of some JavaScript built-in functions:
.big()
.small()
.italics()
.fixed()
.strike()
.sup()
The below built-in functions require parameters:
.fontsize() //e.g.: the size to be applied in number .fontsize(4)
.fontcolor("") //e.g.: the color to be applied in string .fontcolor("red")
.txt.link("") //e.g.: the url to be linkable as string .link("www.test.com")
.toUpperCase() //e.g.: the converted to uppercase to be applied in string .toUpperCase()
Remember the syntax is: string.functionName()
e.g.:
var txt = "Hello World!";
txt.bold();
This also can be done in one line:
var txt = "Hello World!".bold();
The result will be: Hello World!
You can use multiple built-in functions in one line, adding one next to the other. e.g.:
"10/22/2018".fontcolor("red").fontsize(4).bold()
The following is an example how I used it on my JavaScript code to change font (color, size, bold) using both HTML tags and JavaScript functions:
vForm.message = "<HTML><font size = 4 color = 'red'><b> Application
Deadline was </b></font></HTML> " +
"10/22/2018".fontcolor("red").fontsize(4).bold(); /* setting HTML font
color, size, bold and combined them with JavaScript functions to change font
color, size, bold in JavaScript code */
Best practices for copying files with Maven
To summarize some of the fine answers above: Maven is designed to build modules and copy the results to a Maven repository. Any copying of modules to a deployment/installer-input directory must be done outside the context of Maven's core functionality, e.g. with the Ant/Maven copy command.
Android: ScrollView force to bottom
I actually found that calling fullScroll twice does the trick:
myScrollView.fullScroll(View.FOCUS_DOWN);
myScrollView.post(new Runnable() {
@Override
public void run() {
myScrollView.fullScroll(View.FOCUS_DOWN);
}
});
It may have something to do with the activation of the post() method right after performing the first (unsuccessful) scroll. I think this behavior occurs after any previous method call on myScrollView, so you can try replacing the first fullScroll() method by anything else that may be relevant to you.
How to set an iframe src attribute from a variable in AngularJS
It is the $sce
service that blocks URLs with external domains, it is a service that provides Strict Contextual Escaping services to AngularJS, to prevent security vulnerabilities such as XSS, clickjacking, etc. it's enabled by default in Angular 1.2.
You can disable it completely, but it's not recommended
angular.module('myAppWithSceDisabledmyApp', [])
.config(function($sceProvider) {
$sceProvider.enabled(false);
});
for more info
https://docs.angularjs.org/api/ng/service/$sce
Equivalent of Math.Min & Math.Max for Dates?
Linq.Min()
/ Linq.Max()
approach:
DateTime date1 = new DateTime(2000,1,1);
DateTime date2 = new DateTime(2001,1,1);
DateTime minresult = new[] { date1,date2 }.Min();
DateTime maxresult = new[] { date1,date2 }.Max();
Get timezone from DateTime
No.
A developer is responsible for keeping track of time-zone information associated with a DateTime value via some external mechanism.
A quote from an excellent article here.
A must read for every .Net developer.
So my advice is to write a little wrapper class that suits your needs.
Zookeeper connection error
Unable to read additional data from server sessionid 0x0, likely server has closed socket, closing socket connection and attempting reconnect (org.apache.zookeeper.ClientCnxn)
I changed just the number of brokers in the zoo.cfg file and restart zookeeper and kafka service
How to round the double value to 2 decimal points?
public static double addDoubles(double a, double b) {
BigDecimal A = new BigDecimal(a + "");
BigDecimal B = new BigDecimal(b + "");
return A.add(B).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
How should the ViewModel close the form?
The way I would handle it is to add an event handler in my ViewModel. When the user was successfully logged in I would fire the event. In my View I would attach to this event and when it fired I would close the window.
How to set value to form control in Reactive Forms in Angular
Try this.
editqueForm = this.fb.group({
user: [this.question.user],
questioning: [this.question.questioning, Validators.required],
questionType: [this.question.questionType, Validators.required],
options: new FormArray([])
})
setValue() and patchValue()
if you want to set the value of one control, this will not work, therefor you have to set the value of both controls:
formgroup.setValue({name: ‘abc’, age: ‘25’});
It is necessary to mention all the controls inside the method. If this is not done, it will throw an error.
On the other hand patchvalue()
is a lot easier on that part, let’s say you only want to assign the name as a new value:
formgroup.patchValue({name:’abc’});
How can I handle the warning of file_get_contents() function in PHP?
My favourite way to do this is fairly simple:
if (false !== ($data = file_get_contents("http://www.google.com"))) {
$error = error_get_last();
echo "HTTP request failed. Error was: " . $error['message'];
} else {
echo "Everything went better than expected";
}
I found this after experimenting with the try/catch
from @enobrev above, but this allows for less lengthy (and IMO, more readable) code. We simply use error_get_last
to get the text of the last error, and file_get_contents
returns false on failure, so a simple "if" can catch that.
TypeScript static classes
You can create a class in Typescript as follows:
export class coordinate {
static x: number;
static y: number;
static gradient() {
return y/x;
}
}
and reference it's properties and methods "without" instantiation so:
coordinate.x = 10;
coordinate.y = 10;
console.log(`x of ${coordinate.x} and y of ${coordinate.y} has gradient of ${coordinate.gradient()}`);
Fyi using backticks `` in conjunction with interpolation syntax ${} allows ease in mixing code with text :-)
plotting different colors in matplotlib
@tcaswell already answered, but I was in the middle of typing my answer up, so I'll go ahead and post it...
There are a number of different ways you could do this. To begin with, matplotlib
will automatically cycle through colors. By default, it cycles through blue, green, red, cyan, magenta, yellow, black:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 1, 10)
for i in range(1, 6):
plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()
If you want to control which colors matplotlib cycles through, use ax.set_color_cycle
:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 1, 10)
fig, ax = plt.subplots()
ax.set_color_cycle(['red', 'black', 'yellow'])
for i in range(1, 6):
plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()
If you'd like to explicitly specify the colors that will be used, just pass it to the color
kwarg (html colors names are accepted, as are rgb tuples and hex strings):
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 1, 10)
for i, color in enumerate(['red', 'black', 'blue', 'brown', 'green'], start=1):
plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()
Finally, if you'd like to automatically select a specified number of colors from an existing colormap:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 1, 10)
number = 5
cmap = plt.get_cmap('gnuplot')
colors = [cmap(i) for i in np.linspace(0, 1, number)]
for i, color in enumerate(colors, start=1):
plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()
Looping through all rows in a table column, Excel-VBA
You can search column before assignments:
Dim col_n as long
for i = 1 to NumCols
if Cells(1, i).Value = "column header you are looking for" Then col_n = i
next
for i = 1 to NumRows
Cells(i, col_n).Value = "PHEV"
next i
Is it not possible to define multiple constructors in Python?
If your signatures differ only in the number of arguments, using default arguments is the right way to do it. If you want to be able to pass in different kinds of argument, I would try to avoid the isinstance
-based approach mentioned in another answer, and instead use keyword arguments.
If using just keyword arguments becomes unwieldy, you can combine it with classmethods (the bzrlib code likes this approach). This is just a silly example, but I hope you get the idea:
class C(object):
def __init__(self, fd):
# Assume fd is a file-like object.
self.fd = fd
@classmethod
def fromfilename(cls, name):
return cls(open(name, 'rb'))
# Now you can do:
c = C(fd)
# or:
c = C.fromfilename('a filename')
Notice all those classmethods still go through the same __init__
, but using classmethods can be much more convenient than having to remember what combinations of keyword arguments to __init__
work.
isinstance
is best avoided because Python's duck typing makes it hard to figure out what kind of object was actually passed in. For example: if you want to take either a filename or a file-like object you cannot use isinstance(arg, file)
, because there are many file-like objects that do not subclass file
(like the ones returned from urllib, or StringIO, or...). It's usually a better idea to just have the caller tell you explicitly what kind of object was meant, by using different keyword arguments.
What's a standard way to do a no-op in python?
If you need a function that behaves as a nop, try
nop = lambda *a, **k: None
nop()
Sometimes I do stuff like this when I'm making dependencies optional:
try:
import foo
bar=foo.bar
baz=foo.baz
except:
bar=nop
baz=nop
# Doesn't break when foo is missing:
bar()
baz()
How to get domain root url in Laravel 4?
My hint:
FIND IF EXISTS in .env:
APP_URL=http://yourhost.dev
REPLACE TO (OR ADD)
APP_DOMAIN=yourhost.dev
FIND in config/app.php:
'url' => env('APP_URL'),
REPLACE TO
'domain' => env('APP_DOMAIN'),
'url' => 'http://' . env('APP_DOMAIN'),
USE:
Config::get('app.domain'); // yourhost.dev
Config::get('app.url') // http://yourhost.dev
Do your magic!
UUID max character length
Section 3 of RFC4122 provides the formal definition of UUID string representations. It's 36 characters (32 hex digits + 4 dashes).
Sounds like you need to figure out where the invalid 60-char IDs are coming from and decide 1) if you want to accept them, and 2) what the max length of those IDs might be based on whatever API is used to generate them.
HTML Button Close Window
I know this thread has been answered, but another solution that may be useful for some, particularly to those with multiple pages where they want to have this button, is to give the input an id and place the code in a JavaScript file. You can then place the code for the button on multiple pages, taking up less space in your code.
For the button:
<input type="button" id="cancel_edit" value="Cancel"></input>
in the JavaScript file:
$("#cancel_edit").click(function(){
window.open('','_parent','');
window.close();
});
How to Generate unique file names in C#
If you would like to have the datetime,hours,minutes etc..you can use a static variable. Append the value of this variable to the filename. You can start the counter with 0 and increment when you have created a file. This way the filename will surely be unique since you have seconds also in the file.
Example of waitpid() in use?
The syntax is
pid_t waitpid(pid_t pid, int *statusPtr, int options);
1.where pid is the process of the child it should wait.
2.statusPtr is a pointer to the location where status information for the terminating process is to be stored.
3.specifies optional actions for the waitpid function. Either of the following option flags may be specified, or they can be combined with a bitwise inclusive OR operator:
WNOHANG
WUNTRACED
WCONTINUED
If successful, waitpid returns the process ID of the terminated process whose status was reported. If unsuccessful, a -1 is returned.
benifits over wait
1.Waitpid can used when you have more than one child for the process and you want to wait for particular child to get its execution done before parent resumes
2.waitpid supports job control
3.it supports non blocking of the parent process
Checking on a thread / remove from list
Better way is to use Queue class:
http://docs.python.org/library/queue.html
Look at the good example code in the bottom of documentation page:
def worker():
while True:
item = q.get()
do_work(item)
q.task_done()
q = Queue()
for i in range(num_worker_threads):
t = Thread(target=worker)
t.daemon = True
t.start()
for item in source():
q.put(item)
q.join() # block until all tasks are done
How to load json into my angular.js ng-model?
Here's a simple example of how to load JSON data into an Angular model.
I have a JSON 'GET' web service which returns a list of Customer details, from an online copy of Microsoft's Northwind SQL Server database.
http://www.iNorthwind.com/Service1.svc/getAllCustomers
It returns some JSON data which looks like this:
{
"GetAllCustomersResult" :
[
{
"CompanyName": "Alfreds Futterkiste",
"CustomerID": "ALFKI"
},
{
"CompanyName": "Ana Trujillo Emparedados y helados",
"CustomerID": "ANATR"
},
{
"CompanyName": "Antonio Moreno Taquería",
"CustomerID": "ANTON"
}
]
}
..and I want to populate a drop down list with this data, to look like this...
I want the text of each item to come from the "CompanyName" field, and the ID to come from the "CustomerID" fields.
How would I do it ?
My Angular controller would look like this:
function MikesAngularController($scope, $http) {
$scope.listOfCustomers = null;
$http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
.success(function (data) {
$scope.listOfCustomers = data.GetAllCustomersResult;
})
.error(function (data, status, headers, config) {
// Do some error handling here
});
}
... which fills a "listOfCustomers" variable with this set of JSON data.
Then, in my HTML page, I'd use this:
<div ng-controller='MikesAngularController'>
<span>Please select a customer:</span>
<select ng-model="selectedCustomer" ng-options="customer.CustomerID as customer.CompanyName for customer in listOfCustomers" style="width:350px;"></select>
</div>
And that's it. We can now see a list of our JSON data on a web page, ready to be used.
The key to this is in the "ng-options" tag:
customer.CustomerID as customer.CompanyName for customer in listOfCustomers
It's a strange syntax to get your head around !
When the user selects an item in this list, the "$scope.selectedCustomer" variable will be set to the ID (the CustomerID field) of that Customer record.
The full script for this example can be found here:
JSON data with Angular
Mike
Is there a good JSP editor for Eclipse?
I followed the advice of Simon Gibbs in this answer and found it worked out fine - if you're in a hurry, the "Web Page Editor (optional)" package from the Eclipse update site does the trick.
For the Eclipse-challenged (me) Help > Install New Software > Work with > Expand Web, XML, and Java EE Development > Select "Web Page Editor (optional)" and "next-through" to completion.
Laravel migration default value
Put the default value in single quote and it will work as intended. An example of migration:
$table->increments('id');
$table->string('name');
$table->string('url');
$table->string('country');
$table->tinyInteger('status')->default('1');
$table->timestamps();
EDIT : in your case ->default('100.0');
Mock a constructor with parameter
With mockito you can use withSettings(), for example if the CounterService required 2 dependencies, you can pass them as a mock:
UserService userService = Mockito.mock(UserService.class);
SearchService searchService = Mockito.mock(SearchService.class);
CounterService counterService = Mockito.mock(CounterService.class,
withSettings().useConstructor(userService, searchService));
OAuth: how to test with local URLs?
Set your local domain to mywebsite.example.com
(and redirect it to localhost) -- even though the usual is to use mywebsite.dev
. This will allow robust automatic testing.
Although authorizing .test
and .dev
is not allowed, authorizing example.com
is allowed in google oauth2.
(You can redirect any domain to localhost in your hosts file (unix/linux: /etc/hosts
))
Why mywebsite.example.com
?
Because example.com
is a reserved domain name. So
- there would be no naming conflicts on your machine.
- no data-risk if your test system exposes data
to
not-redirected-by-mistake.example.com
.
How to find the socket connection state in C?
get sock opt may be somewhat useful, however, another way would to have a signal handler installed for SIGPIPE. Basically whenever you the socket connection breaks, the kernel will send a SIGPIPE signal to the process and then you can do the needful. But this still does not provide the solution for knowing the status of the connection. hope this helps.
How to set underline text on textview?
you're almost there: just don't call toString()
on Html.fromHtml()
and you get a Spanned Object which will do the job ;)
tvHide.setText(Html.fromHtml("<p><u>Hide post</u></p>"));
Resize font-size according to div size
Here's a SCSS version of @Patrick's mixin.
$mqIterations: 19;
@mixin fontResize($iterations)
{
$i: 1;
@while $i <= $iterations
{
@media all and (min-width: 100px * $i) {
body { font-size:0.2em * $i; }
}
$i: $i + 1;
}
}
@include fontResize($mqIterations);
Access to file download dialog in Firefox
I have a solution for this issue, check the code:
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference("browser.download.dir","c:\\downloads");
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");
WebDriver driver = new FirefoxDriver(firefoxProfile);//new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
driver.navigate().to("http://www.myfile.com/hey.csv");
How do I post form data with fetch api?
To post form data with fetch api,
try this code it works for me ^_^
function card(fileUri) {
let body = new FormData();
let formData = new FormData();
formData.append('file', fileUri);
fetch("http://X.X.X.X:PORT/upload",
{
body: formData,
method: "post"
});
}
How to use an existing database with an Android application
If you are having pre built data base than copy it in asset folder and create an new class as DataBaseHelper which implements SQLiteOpenHelper
Than use following code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHelperClass extends SQLiteOpenHelper{
//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/package_name/databases/";
// Data Base Name.
private static final String DATABASE_NAME = "DBName.sqlite";
// Data Base Version.
private static final int DATABASE_VERSION = 1;
// Table Names of Data Base.
static final String TABLE_Name = "tableName";
public Context context;
static SQLiteDatabase sqliteDataBase;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* @param context
* Parameters of super() are 1. Context
* 2. Data Base Name.
* 3. Cursor Factory.
* 4. Data Base Version.
*/
public DataBaseHelperClass(Context context) {
super(context, DATABASE_NAME, null ,DATABASE_VERSION);
this.context = context;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* By calling this method and empty database will be created into the default system path
* of your application so we are gonna be able to overwrite that database with our database.
* */
public void createDataBase() throws IOException{
//check if the database exists
boolean databaseExist = checkDataBase();
if(databaseExist){
// Do Nothing.
}else{
this.getWritableDatabase();
copyDataBase();
}// end if else dbExist
} // end createDataBase().
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
public boolean checkDataBase(){
File databaseFile = new File(DB_PATH + DATABASE_NAME);
return databaseFile.exists();
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transferring byte stream.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = context.getAssets().open(DATABASE_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DATABASE_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
/**
* This method opens the data base connection.
* First it create the path up till data base of the device.
* Then create connection with data base.
*/
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DATABASE_NAME;
sqliteDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
/**
* This Method is used to close the data base connection.
*/
@Override
public synchronized void close() {
if(sqliteDataBase != null)
sqliteDataBase.close();
super.close();
}
/**
* Apply your methods and class to fetch data using raw or queries on data base using
* following demo example code as:
*/
public String getUserNameFromDB(){
String query = "select User_First_Name From "+TABLE_USER_DETAILS;
Cursor cursor = sqliteDataBase.rawQuery(query, null);
String userName = null;
if(cursor.getCount()>0){
if(cursor.moveToFirst()){
do{
userName = cursor.getString(0);
}while (cursor.moveToNext());
}
}
return userName;
}
@Override
public void onCreate(SQLiteDatabase db) {
// No need to write the create table query.
// As we are using Pre built data base.
// Which is ReadOnly.
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// No need to write the update table query.
// As we are using Pre built data base.
// Which is ReadOnly.
// We should not update it as requirements of application.
}
}
Hope this will help you...
How to return more than one value from a function in Python?
You separate the values you want to return by commas:
def get_name():
# you code
return first_name, last_name
The commas indicate it's a tuple, so you could wrap your values by parentheses:
return (first_name, last_name)
Then when you call the function you a) save all values to one variable as a tuple, or b) separate your variable names by commas
name = get_name() # this is a tuple
first_name, last_name = get_name()
(first_name, last_name) = get_name() # You can put parentheses, but I find it ugly
How can I pass a file argument to my bash script using a Terminal command in Linux?
Assuming you do as David Zaslavsky suggests, so that the first argument simply is the program to run (no option-parsing required), you're dealing with the question of how to pass arguments 2 and on to your external program. Here's a convenient way:
#!/bin/bash
ext_program="$1"
shift
"$ext_program" "$@"
The shift
will remove the first argument, renaming the rest ($2
becomes $1, and so on).
$@` refers to the arguments, as an array of words (it must be quoted!).
If you must have your --file
syntax (for example, if there's a default program to run, so the user doesn't necessarily have to supply one), just replace ext_program="$1"
with whatever parsing of $1
you need to do, perhaps using getopt or getopts.
If you want to roll your own, for just the one specific case, you could do something like this:
if [ "$#" -gt 0 -a "${1:0:6}" == "--file" ]; then
ext_program="${1:7}"
else
ext_program="default program"
fi
Equivalent of LIMIT for DB2
@elcool's solution is a smart idea, but you need to know total number of rows (which can even change while you are executing the query!). So I propose a modified version, which unfortunately needs 3 subqueries instead of 2:
select * from (
select * from (
select * from MYLIB.MYTABLE
order by MYID asc
fetch first {last} rows only
) I
order by MYID desc
fetch first {length} rows only
) II
order by MYID asc
where {last}
should be replaced with row number of the last record I need and {length}
should be replaced with the number of rows I need, calculated as last row - first row + 1
.
E.g. if I want rows from 10 to 25 (totally 16 rows), {last}
will be 25 and {length}
will be 25-10+1=16.
How to implement a read only property
With the introduction of C# 6 (in VS 2015), you can now have get
-only automatic properties, in which the implicit backing field is readonly
(i.e. values can be assigned in the constructor but not elsewhere):
public string Name { get; }
public Customer(string name) // Constructor
{
Name = name;
}
private void SomeFunction()
{
Name = "Something Else"; // Compile-time error
}
And you can now also initialise properties (with or without a setter) inline:
public string Name { get; } = "Boris";
Referring back to the question, this gives you the advantages of option 2 (public member is a property, not a field) with the brevity of option 1.
Unfortunately, it doesn't provide a guarantee of immutability at the level of the public interface (as in @CodesInChaos's point about self-documentation), because to a consumer of the class, having no setter is indistinguishable from having a private setter.
Encrypt and decrypt a String in java
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
}
Here's an example that uses the class:
try {
// Generate a temporary key. In practice, you would save this key.
// See also Encrypting with DES Using a Pass Phrase.
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter(key);
// Encrypt
String encrypted = encrypter.encrypt("Don't tell anybody!");
// Decrypt
String decrypted = encrypter.decrypt(encrypted);
} catch (Exception e) {
}
Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class
Here is a working example.
Keypoints are:
- Declaration of
Accounts
- Use of
JsonProperty
attribute
.
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("http://coderwall.com/mdeiters.json");
var user = JsonConvert.DeserializeObject<User>(json);
}
-
public class User
{
/// <summary>
/// A User's username. eg: "sergiotapia, mrkibbles, matumbo"
/// </summary>
[JsonProperty("username")]
public string Username { get; set; }
/// <summary>
/// A User's name. eg: "Sergio Tapia, John Cosack, Lucy McMillan"
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// A User's location. eh: "Bolivia, USA, France, Italy"
/// </summary>
[JsonProperty("location")]
public string Location { get; set; }
[JsonProperty("endorsements")]
public int Endorsements { get; set; } //Todo.
[JsonProperty("team")]
public string Team { get; set; } //Todo.
/// <summary>
/// A collection of the User's linked accounts.
/// </summary>
[JsonProperty("accounts")]
public Account Accounts { get; set; }
/// <summary>
/// A collection of the User's awarded badges.
/// </summary>
[JsonProperty("badges")]
public List<Badge> Badges { get; set; }
}
public class Account
{
public string github;
}
public class Badge
{
[JsonProperty("name")]
public string Name;
[JsonProperty("description")]
public string Description;
[JsonProperty("created")]
public string Created;
[JsonProperty("badge")]
public string BadgeUrl;
}
Twitter Bootstrap 3.0 how do I "badge badge-important" now
In short: Replace badge-important
with either alert-danger
or progress-bar-danger
.
It looks like this: Bootply Demo.
You might combine the CSS class badge
with alert-*
or progess-bar-*
to color them:
With class="badges alert-*"
<span class="badge alert-info">badge</span> Info
<span class="badge alert-success">badge</span> Success
<span class="badge alert-danger">badge</span> Danger
<span class="badge alert-warning">badge</span> Warning
Alerts Docu: http://getbootstrap.com/components/#alerts
With class="badges progress-bar-*"
(as suggested by @clami219)
<span class="badge progress-bar-info">badge</span> Info
<span class="badge progress-bar-success">badge</span> Success
<span class="badge progress-bar-danger">badge</span> Danger
<span class="badge progress-bar-warning">badge</span> Warning
Progress-Bar Docu: http://getbootstrap.com/components/#progress-alternatives
CSV in Python adding an extra carriage return, on Windows
You can introduce the lineterminator='\n' parameter in the csv writer command.
import csv
delimiter='\t'
with open('tmp.csv', '+w', encoding='utf-8') as stream:
writer = csv.writer(stream, delimiter=delimiter, quoting=csv.QUOTE_NONE, quotechar='', lineterminator='\n')
writer.writerow(['A1' , 'B1', 'C1'])
writer.writerow(['A2' , 'B2', 'C2'])
writer.writerow(['A3' , 'B3', 'C3'])
Get current time in milliseconds in Python?
Time since unix
from time import time
while True:
print(str(time()*1000)+'ms \r', end='')
Time since start of program
from time import time
init = time()
while True:
print(str((time()-init)*1000)+'ms \r', end='')
Thanks for your time
CSS: Background image and padding
The only option to actuall have this made pixel perfect is to create some transparent padding within the GIF itself. That way you can actually align it to the right of the LI and still have the background padding you are looking for.
How can I get the console logs from the iOS Simulator?
[iOS Logger]
You can use the Console
application(select your device in Devices) on your Mac to see a log message that were sent using NSLog
, os_log
, Logger
(you will not see logs from print
function).
Also please check (Action -> Include <Info/Debug> Messages)
Please note that if you want to see a log from WebView
(UIWebView
or WKWebView
) you should use Safary -> Develop -> device
[Find crash log]
How link to any local file with markdown syntax?
If the file is in the same directory as the one where the .md is, then just putting [Click here](MY-FILE.md)
should work.
Otherwise, can create a path from the root directory of the project. So if the entire project/git-repo root directory is called 'my-app', and one wants to point to my-app/client/read-me.md, then try [My hyperlink](/client/read-me.md)
.
At least works from Chrome.
How to use ScrollView in Android?
How to use ScrollView
Using ScrollView
is not very difficult. You can just add one to your layout and put whatever you want to scroll inside. ScrollView
only takes one child so if you want to put a few things inside then you should make the first thing be something like a LinearLayout
.
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- things to scroll -->
</LinearLayout>
</ScrollView>
If you want to scroll things horizontally, then use a HorizontalScrollView
.
Making the content fill the screen
As is talked about in this post, sometimes you want the ScrollView
content to fill the screen. For example, if you had some buttons at the end of a readme. You want the buttons to always be at the end of the text and at bottom of the screen, even if the text doesn't scroll.
If the content scrolls, everything is fine. However, if the content is smaller than the size of the screen, the buttons are not at the bottom.
This can be solved with a combination of using fillViewPort
on the ScrollView
and using a layout weight on the content. Using fillViewPort
makes the ScrollView
fill the parent area. Setting the layout_weight
on one of the views in the LinearLayout
makes that view expand to fill any extra space.
Here is the XML
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"> <--- fillViewport
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/textview"
android:layout_height="0dp" <---
android:layout_weight="1" <--- set layout_weight
android:layout_width="match_parent"
android:padding="6dp"
android:text="hello"/>
<LinearLayout
android:layout_height="wrap_content" <--- wrap_content
android:layout_width="match_parent"
android:background="@android:drawable/bottom_bar"
android:gravity="center_vertical">
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Accept" />
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Refuse" />
</LinearLayout>
</LinearLayout>
</ScrollView>
The idea for this answer came from a previous answer that is now deleted (link for 10K users). The content of this answer is an update and adaptation of this post.
Creating a new directory in C
I want to write a program that (...) creates the directory and a (...) file inside of it
because this is a very common question, here is the code to create multiple levels of directories and than call fopen. I'm using a gnu extension to print the error message with printf.
void rek_mkdir(char *path) {
char *sep = strrchr(path, '/');
if(sep != NULL) {
*sep = 0;
rek_mkdir(path);
*sep = '/';
}
if(mkdir(path, 0777) && errno != EEXIST)
printf("error while trying to create '%s'\n%m\n", path);
}
FILE *fopen_mkdir(char *path, char *mode) {
char *sep = strrchr(path, '/');
if(sep) {
char *path0 = strdup(path);
path0[ sep - path ] = 0;
rek_mkdir(path0);
free(path0);
}
return fopen(path,mode);
}
Wait 5 seconds before executing next line
Create new Js function
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
Call the function when you want to delay execution. Use milliseconds in int for delay value.
####Some code
sleep(1000);
####Next line
Laravel 5 Class 'form' not found
You can also try running the following commands in Terminal or Command:
composer dump-auto
or composer dump-auto -o
php artisan cache:clear
php artisan config:clear
The above worked for me.
Return value from a VBScript function
To return a value from a VBScript function, assign the value to the name of the function, like this:
Function getNumber
getNumber = "423"
End Function