If you don't want to SELECT SLEEP(1);
, you can also DO SLEEP(1);
It's useful for those situations in procedures where you don't want to see output.
e.g.
SELECT ...
DO SLEEP(5);
SELECT ...
Lua doesn't provide a standard sleep
function, but there are several ways to implement one, see Sleep Function for detail.
For Linux, this may be the easiest one:
function sleep(n)
os.execute("sleep " .. tonumber(n))
end
In Windows, you can use ping
:
function sleep(n)
if n > 0 then os.execute("ping -n " .. tonumber(n+1) .. " localhost > NUL") end
end
The one using select
deserves some attention because it is the only portable way to get sub-second resolution:
require "socket"
function sleep(sec)
socket.select(nil, nil, sec)
end
sleep(0.2)
tail
does not blockAs always: For everything there is an answer which is short, easy to understand, easy to follow and completely wrong. Here tail -f /dev/null
falls into this category ;)
If you look at it with strace tail -f /dev/null
you will notice, that this solution is far from blocking! It's probably even worse than the sleep
solution in the question, as it uses (under Linux) precious resources like the inotify
system. Also other processes which write to /dev/null
make tail
loop. (On my Ubuntu64 16.10 this adds several 10 syscalls per second on an already busy system.)
Read: I do not know any way to archive this with the shell directly.
Everything (even sleep infinity
) can be interrupted by some signal. So if you want to be really sure it does not exceptionally return, it must run in a loop, like you already did for your sleep
. Please note, that (on Linux) /bin/sleep
apparently is capped at 24 days (have a look at strace sleep infinity
), hence the best you can do probably is:
while :; do sleep 2073600; done
(Note that I believe sleep
loops internally for higher values than 24 days, but this means: It is not blocking, it is very slowly looping. So why not move this loop to the outside?)
fifo
You can create something which really blocks as long as there are no signals send to the process. Following uses bash 4
, 2 PIDs and 1 fifo
:
bash -c 'coproc { exec >&-; read; }; eval exec "${COPROC[0]}<&-"; wait'
You can check that this really blocks with strace
if you like:
strace -ff bash -c '..see above..'
read
blocks if there is no input data (see some other answers). However, the tty
(aka. stdin
) usually is not a good source, as it is closed when the user logs out. Also it might steal some input from the tty
. Not nice.
To make read
block, we need to wait for something like a fifo
which will never return anything. In bash 4
there is a command which can exactly provide us with such a fifo
: coproc
. If we also wait the blocking read
(which is our coproc
), we are done. Sadly this needs to keep open two PIDs and a fifo
.
fifo
If you do not bother using a named fifo
, you can do this as follows:
mkfifo "$HOME/.pause.fifo" 2>/dev/null; read <"$HOME/.pause.fifo"
Not using a loop on the read is a bit sloppy, but you can reuse this fifo
as often as you like and make the read
s terminat using touch "$HOME/.pause.fifo"
(if there are more than a single read waiting, all are terminated at once).
pause()
syscallFor the infinite blocking there is a Linux kernel call, called pause()
, which does what we want: Wait forever (until a signal arrives). However there is no userspace program for this (yet).
Create such a program is easy. Here is a snippet to create a very small Linux program called pause
which pauses indefinitely (needs diet
, gcc
etc.):
printf '#include <unistd.h>\nint main(){for(;;)pause();}' > pause.c;
diet -Os cc pause.c -o pause;
strip -s pause;
ls -al pause
python
If you do not want to compile something yourself, but you have python
installed, you can use this under Linux:
python -c 'while 1: import ctypes; ctypes.CDLL(None).pause()'
(Note: Use exec python -c ...
to replace the current shell, this frees one PID. The solution can be improved with some IO redirection as well, freeing unused FDs. This is up to you.)
How this works (I think): ctypes.CDLL(None)
loads the standard C library and runs the pause()
function in it within some additional loop. Less efficient than the C version, but works.
Stay at the looping sleep. It's easy to understand, very portable, and blocks most of the time.
Like this:
sleep(num_secs)
The num_secs
value can be an integer or float.
Also, if you're writing this within a Rails app, or have included the ActiveSupport library in your project, you can construct longer intervals using the following convenience syntax:
sleep(4.minutes)
# or, even longer...
sleep(2.hours); sleep(3.days) # etc., etc.
# or shorter
sleep(0.5) # half a second
In addition to the accepted answer from 10 years ago, with more modern Javascript one can use async
/await
/Promise()
or generator function to achieve the correct behavior. (The incorrect behavior suggested in other answers would be setting series of 3 seconds alerts regardless of "accepting" the alert()
- or finishing the task at hand)
Using async
/await
/Promise()
:
alert('hi');
(async () => {
for(let start = 1; start < 10; start++) {
await new Promise(resolve => setTimeout(() => {
alert('hello');
resolve();
}, 3000));
}
})();
_x000D_
Using a generator function:
alert('hi');
let func;
(func = (function*() {
for(let start = 1; start < 10; start++) {
yield setTimeout(() => {
alert('hello');
func.next();
}, 3000);
}
})()).next();
_x000D_
When using Android (the only time when I use Java) I would recommend using a handler instead putting the thread to sleep.
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.i(TAG, "I've waited for two hole seconds to show this!");
}
}, 2000);
Reference: http://developer.android.com/reference/android/os/Handler.html
#! /bin/sh
# Run all programs in a directory in parallel
# Usage: run-parallel directory delay
# Copyright 2013 by Marc Perkel
# docs at http://wiki.junkemailfilter.com/index.php/How_to_run_a_Linux_script_every_few_seconds_under_cron"
# Free to use with attribution
if [ $# -eq 0 ]
then
echo
echo "run-parallel by Marc Perkel"
echo
echo "This program is used to run all programs in a directory in parallel"
echo "or to rerun them every X seconds for one minute."
echo "Think of this program as cron with seconds resolution."
echo
echo "Usage: run-parallel [directory] [delay]"
echo
echo "Examples:"
echo " run-parallel /etc/cron.20sec 20"
echo " run-parallel 20"
echo " # Runs all executable files in /etc/cron.20sec every 20 seconds or 3 times a minute."
echo
echo "If delay parameter is missing it runs everything once and exits."
echo "If only delay is passed then the directory /etc/cron.[delay]sec is assumed."
echo
echo 'if "cronsec" is passed then it runs all of these delays 2 3 4 5 6 10 12 15 20 30'
echo "resulting in 30 20 15 12 10 6 5 4 3 2 executions per minute."
echo
exit
fi
# If "cronsec" is passed as a parameter then run all the delays in parallel
if [ $1 = cronsec ]
then
$0 2 &
$0 3 &
$0 4 &
$0 5 &
$0 6 &
$0 10 &
$0 12 &
$0 15 &
$0 20 &
$0 30 &
exit
fi
# Set the directory to first prameter and delay to second parameter
dir=$1
delay=$2
# If only parameter is 2,3,4,5,6,10,12,15,20,30 then automatically calculate
# the standard directory name /etc/cron.[delay]sec
if [[ "$1" =~ ^(2|3|4|5|6|10|12|15|20|30)$ ]]
then
dir="/etc/cron.$1sec"
delay=$1
fi
# Exit if directory doesn't exist or has no files
if [ ! "$(ls -A $dir/)" ]
then
exit
fi
# Sleep if both $delay and $counter are set
if [ ! -z $delay ] && [ ! -z $counter ]
then
sleep $delay
fi
# Set counter to 0 if not set
if [ -z $counter ]
then
counter=0
fi
# Run all the programs in the directory in parallel
# Use of timeout ensures that the processes are killed if they run too long
for program in $dir/* ; do
if [ -x $program ]
then
if [ "0$delay" -gt 1 ]
then
timeout $delay $program &> /dev/null &
else
$program &> /dev/null &
fi
fi
done
# If delay not set then we're done
if [ -z $delay ]
then
exit
fi
# Add delay to counter
counter=$(( $counter + $delay ))
# If minute is not up - call self recursively
if [ $counter -lt 60 ]
then
. $0 $dir $delay &
fi
# Otherwise we're done
Beyond usleep, the humble select with NULL file descriptor sets will let you pause with microsecond precision, and without the risk of SIGALRM
complications.
sigtimedwait and sigwaitinfo offer similar behavior.
Use time.sleep()
from time import sleep
sleep(0.05)
You can create a delay using the following example
setInterval(function(){alert("Hello")},3000);
Replace 3000 with # of milliseconds
You can place the content of what you want executed inside the function.
timeout 5
to delay
timeout 5 >nul
to delay without asking you to press any key to cancel
JS does not have a sleep function, it has setTimeout() or setInterval() functions.
If you can move the code that you need to run after the pause into the setTimeout()
callback, you can do something like this:
//code before the pause
setTimeout(function(){
//do what you need here
}, 2000);
see example here : http://jsfiddle.net/9LZQp/
This won't halt the execution of your script, but due to the fact that setTimeout()
is an asynchronous function, this code
console.log("HELLO");
setTimeout(function(){
console.log("THIS IS");
}, 2000);
console.log("DOG");
will print this in the console:
HELLO
DOG
THIS IS
(note that DOG is printed before THIS IS)
You can use the following code to simulate a sleep for short periods of time:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
now, if you want to sleep for 1 second, just use:
sleep(1000);
example: http://jsfiddle.net/HrJku/1/
please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.
for C use /// in gcc.
#include <windows.h>
then use Sleep(); /// Sleep() with capital S. not sleep() with s .
//Sleep(1000) is 1 sec /// maybe.
clang supports sleep(), sleep(1) is for 1 sec time delay/wait.
blocking the main thread is not a good style for node because in most cases more then one person is using it. You should use settimeout/setinterval in combination with callbacks.
With .Net 4.x you can use Task-based Asynchronous Pattern (TAP) to achieve this:
// .NET 4.x async-await
using UnityEngine;
using System.Threading.Tasks;
public class AsyncAwaitExample : MonoBehaviour
{
private async void Start()
{
Debug.Log("Wait.");
await WaitOneSecondAsync();
DoMoreStuff(); // Will not execute until WaitOneSecond has completed
}
private async Task WaitOneSecondAsync()
{
await Task.Delay(TimeSpan.FromSeconds(1));
Debug.Log("Finished waiting.");
}
}
this is a feature to use .Net 4.x with Unity please see this link for description about it
and this link for sample project and compare it with coroutine
But becareful as documentation says that This is not fully replacement with coroutine
POSIX 7
First find the function: http://pubs.opengroup.org/onlinepubs/9699919799/functions/nanosleep.html
That contains a link to a time.h
, which as a header should be where structs are defined:
The header shall declare the timespec structure, which shall > include at least the following members:
time_t tv_sec Seconds. long tv_nsec Nanoseconds.
man 2 nanosleep
Pseudo-official glibc docs which you should always check for syscalls:
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
Use:
#include <windows.h>
Sleep(sometime_in_millisecs); // Note uppercase S
And here's a small example that compiles with MinGW and does what it says on the tin:
#include <windows.h>
#include <stdio.h>
int main() {
printf( "starting to sleep...\n" );
Sleep(3000); // Sleep three seconds
printf("sleep ended\n");
}
You should generally NOT ignore the exception. Take a look at the following paper:
Don't swallow interrupts
Sometimes throwing InterruptedException is not an option, such as when a task defined by Runnable calls an interruptible method. In this case, you can't rethrow InterruptedException, but you also do not want to do nothing. When a blocking method detects interruption and throws InterruptedException, it clears the interrupted status. If you catch InterruptedException but cannot rethrow it, you should preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the interruption and respond to it if it wants to. This task is accomplished by calling interrupt() to "reinterrupt" the current thread, as shown in Listing 3. At the very least, whenever you catch InterruptedException and don't rethrow it, reinterrupt the current thread before returning.
public class TaskRunner implements Runnable { private BlockingQueue<Task> queue; public TaskRunner(BlockingQueue<Task> queue) { this.queue = queue; } public void run() { try { while (true) { Task task = queue.take(10, TimeUnit.SECONDS); task.execute(); } } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); } } }
See the entire paper here:
http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-
From perlfaq8:
How can I sleep() or alarm() for under a second?
If you want finer granularity than the 1 second that the sleep() function provides, the easiest way is to use the select() function as documented in select in perlfunc. Try the Time::HiRes and the BSD::Itimer modules (available from CPAN, and starting from Perl 5.8 Time::HiRes is part of the standard distribution).
For cross Python 2/3 compatibility, you can use input
via the six
library:
import six
six.moves.input( 'Press the <ENTER> key to continue...' )
for C use in gcc. #include <windows.h>
then use Sleep(); /// Sleep() with capital S. not sleep() with s .
//Sleep(1000) is 1 sec /// maybe.
clang supports sleep(), sleep(1) is for 1 sec time delay/wait.
this is what I use for a cross-platform code:
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
int main()
{
pollingDelay = 100
//do stuff
//sleep:
#ifdef _WIN32
Sleep(pollingDelay);
#else
usleep(pollingDelay*1000); /* sleep for 100 milliSeconds */
#endif
//do stuff again
return 0;
}
If you're using .NET 4.5 you can use the new async/await framework to sleep without locking the thread.
How it works is that you mark the function in need of asynchronous operations, with the async
keyword. This is just a hint to the compiler. Then you use the await
keyword on the line where you want your code to run asynchronously and your program will wait without locking the thread or the UI. The method you call (on the await line) has to be marked with an async
keyword as well and is usually named ending with Async, as in ImportFilesAsync.
What you need to do in your example is:
async
keyword (see example below)using System.Threading.Tasks;
to your code.Your code is now ready to use the Task.Delay
method instead of the System.Threading.Thread.Sleep
method (it is possible to use await
on Task.Delay
because Task.Delay
is marked with async
in its definition).
private async void button1_Click(object sender, EventArgs e)
{
textBox1.Text += "\r\nThread Sleeps!";
await Task.Delay(3000);
textBox1.Text += "\r\nThread awakens!";
}
Here you can read more about Task.Delay and Await.
I've added a notification that you can easily enable / disable just setting its variable to $true or $false. Also the mouse cursor moves 1 px right and then 1 px left so it basically stays in the same place even after several iterations.
# Lines needed for the notification
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
Add-Type -AssemblyName System.Windows.Forms
$isNotificationOn = $true
$secondsBetweenMouseMoves = 6
$Pos = [System.Windows.Forms.Cursor]::Position
$PosDelta = 1
$logFilename = "previousMouseMoverAction.txt"
$errorLogFilename = "mouseMoverLog.txt"
if (!(Test-Path "$PSScriptRoot\$logFilename")) {
New-Item -path $PSScriptRoot -name $logFilename -type "file" -value "right"
Write-Host "Warning: previousMouseMoverAction.txt missing, created a new one."
}
$previousPositionChangeAction = Get-Content -Path $PSScriptRoot\$logFilename
if ($previousPositionChangeAction -eq "left") {
$PosDelta = 1
Set-Content -Path $PSScriptRoot\$logFilename -Value 'right'
} else {
$PosDelta = -1
Set-Content -Path $PSScriptRoot\$logFilename -Value 'left'
}
for ($i = 0; $i -lt $secondsBetweenMouseMoves; $i++) {
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) + $PosDelta) , $Pos.Y)
if ($isNotificationOn) {
# Sending a notification to the user
$global:balloon = New-Object System.Windows.Forms.NotifyIcon
$path = (Get-Process -id $pid).Path
$balloon.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($path)
$balloon.BalloonTipIcon = [System.Windows.Forms.ToolTipIcon]::Warning
$balloon.BalloonTipText = 'I have just moved your cheese...'
$balloon.BalloonTipTitle = "Attention, $Env:USERNAME"
$balloon.Visible = $true
$balloon.ShowBalloonTip(3000)
}
}
Use this:
public static void wait(int ms)
{
try
{
Thread.sleep(ms);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
and, then you can call this method anywhere like:
wait(1000);
You cannot just put in a function to pause Javascript unfortunately.
You have to use setTimeout()
Example:
function startTimer () {
timer.start();
setTimeout(stopTimer,5000);
}
function stopTimer () {
timer.stop();
}
EDIT:
For your user generated countdown, it is just as simple.
HTML:
<input type="number" id="delay" min="1" max="5">
JS:
var delayInSeconds = parseInt(delay.value);
var delayInMilliseconds = delayInSeconds*1000;
function startTimer () {
timer.start();
setTimeout(stopTimer,delayInMilliseconds);
}
function stopTimer () {
timer.stop;
}
Now you simply need to add a trigger for startTimer()
, such as onchange
.
It blocks the thread. If you look in Modules/timemodule.c in the Python source, you'll see that in the call to floatsleep()
, the substantive part of the sleep operation is wrapped in a Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS block, allowing other threads to continue to execute while the current one sleeps. You can also test this with a simple python program:
import time
from threading import Thread
class worker(Thread):
def run(self):
for x in xrange(0,11):
print x
time.sleep(1)
class waiter(Thread):
def run(self):
for x in xrange(100,103):
print x
time.sleep(5)
def run():
worker().start()
waiter().start()
Which will print:
>>> thread_test.run()
0
100
>>> 1
2
3
4
5
101
6
7
8
9
10
102
The problems with calling Thread.Sleep
are explained quite succinctly here:
Thread.Sleep
has its use: simulating lengthy operations while testing/debugging on an MTA thread. In .NET there's no other reason to use it.
Thread.Sleep(n)
means block the current thread for at least the number of timeslices (or thread quantums) that can occur withinn
milliseconds. The length of a timeslice is different on different versions/types of Windows and different processors and generally ranges from 15 to 30 milliseconds. This means the thread is almost guaranteed to block for more thann
milliseconds. The likelihood that your thread will re-awaken exactly aftern
milliseconds is about as impossible as impossible can be. So,Thread.Sleep
is pointless for timing.Threads are a limited resource, they take approximately 200,000 cycles to create and about 100,000 cycles to destroy. By default they reserve 1 megabyte of virtual memory for its stack and use 2,000-8,000 cycles for each context switch. This makes any waiting thread a huge waste.
The preferred solution: WaitHandles
The most-made-mistake is using Thread.Sleep
with a while-construct (demo and answer, nice blog-entry)
EDIT:
I would like to enhance my answer:
We have 2 different use-cases:
We are waiting because we know a specific timespan when we should continue (use
Thread.Sleep
,System.Threading.Timer
or alikes)We are waiting because some condition changes some time ... keyword(s) is/are some time! if the condition-check is in our code-domain, we should use WaitHandles - otherwise the external component should provide some kind of hooks ... if it doesn't its design is bad!
My answer mainly covers use-case 2
Should be called from synchronized block : wait()
method is always called from synchronized block i.e. wait()
method needs to lock object monitor before object on which it is called. But sleep()
method can be called from outside synchronized block i.e. sleep()
method doesn’t need any object monitor.
IllegalMonitorStateException : if wait()
method is called without acquiring object lock than IllegalMonitorStateException
is thrown at runtime, but sleep()
method never throws such exception.
Belongs to which class : wait()
method belongs to java.lang.Object
class but sleep()
method belongs to java.lang.Thread
class.
Called on object or thread : wait()
method is called on objects but sleep()
method is called on Threads not objects.
Thread state : when wait()
method is called on object, thread that holded object’s monitor goes from running to waiting state and can return to runnable state only when notify()
or notifyAll()
method is called on that object. And later thread scheduler schedules that thread to go from from runnable to running state.
when sleep()
is called on thread it goes from running to waiting state and can return to runnable state when sleep time is up.
When called from synchronized block : when wait()
method is called thread leaves the object lock. But sleep()
method when called from synchronized block or method thread doesn’t leaves object lock.
For More Reference
Here is a very simple piece of C# code to test the CommandTimeout with. It creates a new command which will wait for 2 seconds. Set the CommandTimeout to 1 second and you will see an exception when running it. Setting the CommandTimeout to either 0 or something higher than 2 will run fine. By the way, the default CommandTimeout is 30 seconds.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var builder = new SqlConnectionStringBuilder();
builder.DataSource = "localhost";
builder.IntegratedSecurity = true;
builder.InitialCatalog = "master";
var connectionString = builder.ConnectionString;
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "WAITFOR DELAY '00:00:02'";
command.CommandTimeout = 1;
command.ExecuteNonQuery();
}
}
}
}
}
You can't (and shouldn't) block processing with a sleep function. However, you can use setTimeout
to kick off a function after a delay:
setTimeout(function(){alert("hi")}, 1000);
Depending on your needs, setInterval
might be useful, too.
To use the standard sleep function add the following in your .cpp file:
#include <unistd.h>
As of Qt version 4.8, the following sleep functions are available:
void QThread::msleep(unsigned long msecs)
void QThread::sleep(unsigned long secs)
void QThread::usleep(unsigned long usecs)
To use them, simply add the following in your .cpp file:
#include <QThread>
Reference: QThread (via Qt documentation): http://doc.qt.io/qt-4.8/qthread.html
Otherwise, perform these steps...
Modify the project file as follows:
CONFIG += qtestlib
Note that in newer versions of Qt you will get the following error:
Project WARNING: CONFIG+=qtestlib is deprecated. Use QT+=testlib instead.
... so, instead modify the project file as follows:
QT += testlib
Then, in your .cpp file, be sure to add the following:
#include <QtTest>
And then use one of the sleep functions like so:
usleep(100);
This might work. It worked for me in c and javascript.
function sleep(time) {
var x = 0;
for(x = 0;x < time;x++) {/* Do nothing*/}
}
import time
time.sleep(5) # Delays for 5 seconds. You can also use a float value.
Here is another example where something is run approximately once a minute:
import time
while True:
print("This prints once a minute.")
time.sleep(60) # Delay for 1 minute (60 seconds).
These are class stereotypes used in analysis.
boundary classes are ones at the boundary of the system - the classes that you or other systems interact with
entity classes classes are your typical business entities like "person" and "bank account"
control classes implement some business logic or other
You can use
for spaces, <
for <
(less than, entity number <
) and >
for >
(greater than, entity number >
).
A complete list can be found at HTML Entities.
Here are 2 ways(both are OS independent.)
Using Paths
: Since 1.7
Path p = Paths.get(<Absolute Path of Linux/Windows system>);
String fileName = p.getFileName().toString();
String directory = p.getParent().toString();
Using FilenameUtils
in Apache Commons IO :
String name1 = FilenameUtils.getName("/ab/cd/xyz.txt");
String name2 = FilenameUtils.getName("c:\\ab\\cd\\xyz.txt");
As stated in 1.7.12 Release Notes, you may use
$ git rebase -i --root
Simply:
DECLARE @MIN INT=3; --We define minimum value, it can be generated.
DECLARE @MAX INT=6; --We define maximum value, it can be generated.
SELECT @MIN+FLOOR((@MAX-@MIN+1)*RAND(CONVERT(VARBINARY,NEWID()))); --And then this T-SQL snippet generates an integer between minimum and maximum integer values.
You can change and edit this code for your needs.
Should be noted that strip()
method would trim any leading and trailing whitespace characters from the string (if there is no passed-in argument). If you want to trim space character(s), while keeping the others (like newline), this answer might be helpful:
sample = ' some string\n'
sample_modified = sample.strip(' ')
print(sample_modified) # will print 'some string\n'
strip([chars])
: You can pass in optional characters to strip([chars])
method. Python will look for occurrences of these characters and trim the given string accordingly.
You can also perform case insensitive searches using search/match without the IGNORECASE flag (tested in Python 2.7.3):
re.search(r'(?i)test', 'TeSt').group() ## returns 'TeSt'
re.match(r'(?i)test', 'TeSt').group() ## returns 'TeSt'
Add cellpadding and cellspacing to solve it. Edit: Also removed double pixel border.
<style>
td
{border-left:1px solid black;
border-top:1px solid black;}
table
{border-right:1px solid black;
border-bottom:1px solid black;}
</style>
<html>
<body>
<table cellpadding="0" cellspacing="0">
<tr>
<td width="350" >
Foo
</td>
<td width="80" >
Foo1
</td>
<td width="65" >
Foo2
</td>
</tr>
<tr>
<td>
Bar1
</td>
<td>
Bar2
</td>
<td>
Bar3
</td>
</tr>
<tr >
<td>
Bar1
</td>
<td>
Bar2
</td>
<td>
Bar3
</td>
</tr>
</table>
</body>
</html>
You use the Headers
property with a string index:
request.Headers["X-My-Custom-Header"] = "the-value";
According to MSDN, this has been available since:
https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers(v=vs.110).aspx
The big difference is, substr()
is a deprecated method that can still be used, but should be used with caution because they are expected to be removed entirely sometime in the future. You should work to remove their use from your code. And the substring()
method succeeded and specified the former one.
In addition to what have been suggested, setdefault
might be useful in situations where you don't want to modify a value that has been already set. For example, when you have duplicate numbers and you want to treat them as one group. In this case, if you encounter a repeated duplicate
key which has been already set, you won't update the value of that key. You will keep the first encountered value. As if you are iterating/updating the repeated keys once only.
Here's a code example of recording the index for the keys/elements of a sorted list:
nums = [2,2,2,2,2]
d = {}
for idx, num in enumerate(sorted(nums)):
# This will be updated with the value/index of the of the last repeated key
# d[num] = idx # Result (sorted_indices): [4, 4, 4, 4, 4]
# In the case of setdefault, all encountered repeated keys won't update the key.
# However, only the first encountered key's index will be set
d.setdefault(num,idx) # Result (sorted_indices): [0, 0, 0, 0, 0]
sorted_indices = [d[i] for i in nums]
The Transact-SQL control-of-flow language keywords are:
BEGIN
...END
BREAK
CONTINUE
GOTO
label
IF
...ELSE
RETURN
THROW
TRY
...CATCH
WAITFOR
WHILE
The web.config transforms that are part of Visual Studio 2010 use XSLT in order to "transform" the current web.config file into its .Debug or .Release version.
In your .Debug/.Release files, you need to add the following parameter in your connection string fields:
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"
This will cause each connection string line to find the matching name and update the attributes accordingly.
Note: You won't have to worry about updating your providerName parameter in the transform files, since they don't change.
Here's an example from one of my apps. Here's the web.config file section:
<connectionStrings>
<add name="EAF" connectionString="[Test Connection String]" />
</connectionString>
And here's the web.config.release section doing the proper transform:
<connectionStrings>
<add name="EAF" connectionString="[Prod Connection String]"
xdt:Transform="SetAttributes"
xdt:Locator="Match(name)" />
</connectionStrings>
One added note: Transforms only occur when you publish the site, not when you simply run it with F5 or CTRL+F5. If you need to run an update against a given config locally, you will have to manually change your Web.config file for this.
For more details you can see the MSDN documentation
https://msdn.microsoft.com/en-us/library/dd465326(VS.100).aspx
Like this:
import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);
Or adding from an Array/ or multiple literals; wrap to a list, first.
Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b)); // from an array variable
b.addAll( Arrays.asList( 8, 9, 10)); // from literals
To get the intersection:
// copies all from A; then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print; r.toString() implied.
System.out.println("A intersect B="+r);
Hope this answer helps. Vote for it!
Try disabling iptables: service iptables stop
If this works, enable TCP port 80 to your firewall rules: run system-config-selinux from root, and enable TCP port 80 (HTTP) on your firewall.
After reading this post, from Baeldung. I found that the solution is pretty simple.
What I have done, is to add the role and permissions into the GrantedAuthority. I was able to access both methods hasRole() and hasAuthority().
If you want the margin-left
to work on a span
element you'll need to make it display: inline-block
or display:block
as well.
You should also set this parameter to log every statement:
log_min_duration_statement = 0
This will alert the index of the clicked selector (starting with 0 for the first):
$('selector').click(function(){
alert( $('selector').index(this) );
});
When you're analyzing code, you have to analyse it line by line, counting every operation/recognizing time complexity, in the end, you have to sum it to get whole picture.
For example, you can have one simple loop with linear complexity, but later in that same program you can have a triple loop that has cubic complexity, so your program will have cubic complexity. Function order of growth comes into play right here.
Let's look at what are possibilities for time complexity of an algorithm, you can see order of growth I mentioned above:
Constant time has an order of growth 1
, for example: a = b + c
.
Logarithmic time has an order of growth LogN
, it usually occurs
when you're dividing something in half (binary search, trees, even loops), or multiplying something in same way.
Linear, order of growth is N
, for example
int p = 0;
for (int i = 1; i < N; i++)
p = p + 2;
Linearithmic, order of growth is n*logN
, usually occurs in divide and conquer algorithms.
Cubic, order of growth N^3
, classic example is a triple loop where you check all triplets:
int x = 0;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
for (int k = 0; k < N; k++)
x = x + 2
Exponential, order of growth 2^N
, usually occurs when you do exhaustive search, for example check subsets of some set.
I tried this query and it works for me.
SELECT username FROM dba_users
ORDER BY username;
If you want to get the list of all that users which are created by end-user, then you can try this:
SELECT username FROM dba_users where Default_TableSpace not in ('SYSAUX', 'SYSTEM', 'USERS')
ORDER BY username;
The default shortcut key is Ctrl-Alt-C.
In Intellij 13 the layout has changed, the Settings button can only be found in File -> Settings and not in the toolbars, and from there you follow the same steps: Editor -> Appearance -> Show line numbers, or search for Line numbers in the Settings search input.
Use the substring method of the String class :
String removeCurrency=amount.getText().toString().substring(3);
EDIT: As mentioned by Stephen Niedzielski in his comment, the issue seems to come from the 32-bit being of the JRE, which is de facto, looking for the 32-bit version of libXtst6
. To install the required version of the library:
$ sudo apt-get install libxtst6:i386
Type:
$ sudo apt-get update
$ sudo apt-get install libxtst6
If this isn’t OK, type:
$ sudo updatedb
$ locate libXtst
it should return something like:
/usr/lib/x86_64-linux-gnu/libXtst.so.6 # Mine is OK
/usr/lib/x86_64-linux-gnu/libXtst.so.6.1.0
If you do not have libXtst.so.6
but do have libXtst.so.6.X.X
create a symbolic link:
$ cd /usr/lib/x86_64-linux-gnu/
$ ln -s libXtst.so.6 libXtst.so.6.X.X
Hope this helps.
I am not very good in grep. But your problem can be solved using AWK command. Just see
awk '/select/,/from/' *.sql
The above code will result from first occurence of select
till first sequence of from
. Now you need to verify whether returned statements are having customername
or not. For this you can pipe the result. And can use awk or grep again.
There are many ways mentioned above. But I use rather simple way (well not simple as SELECT @@SERVERNAME). When you start SQL server management studio you will prompt below GUI
In there Server name is your server name (There may have multiple servers according to you dev environment choose correct one). Hope this helps :)
Well, first of all, in Python there is no !
operator, that'd be not
. But open
would not fail silently either - it would throw an exception. And the blocks need to be indented properly - Python uses whitespace to indicate block containment.
Thus we get:
fn = input('Enter file name: ')
try:
file = open(fn, 'r')
except IOError:
file = open(fn, 'w')
Just updating with Nuget 2.8.3. To change the location of installed packages , I enabled package restore from right clicking solution. Edited NuGet.Config and added these lines :
<config>
<add key="repositorypath" value="..\Core\Packages" />
</config>
Then rebuilt the solution, it downloaded all packages to my desired folder and updated references automatically.
In pure JS it will be much simpler
foo.onsubmit = e=> {
e.preventDefault();
fetch(foo.action,{method:'post', body: new FormData(foo)});
}
foo.onsubmit = e=> {
e.preventDefault();
fetch(foo.action,{method:'post', body: new FormData(foo)});
}
_x000D_
<form name="foo" action="form.php" method="POST" id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
_x000D_
Let's say we have an external table called employee
hive> SHOW CREATE TABLE employee;
OK
CREATE EXTERNAL TABLE employee(
id string,
fname string,
lname string,
salary double)
ROW FORMAT SERDE
'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'
WITH SERDEPROPERTIES (
'colelction.delim'=':',
'field.delim'=',',
'line.delim'='\n',
'serialization.format'=',')
STORED AS INPUTFORMAT
'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
'maprfs:/user/hadoop/data/employee'
TBLPROPERTIES (
'COLUMN_STATS_ACCURATE'='false',
'numFiles'='0',
'numRows'='-1',
'rawDataSize'='-1',
'totalSize'='0',
'transient_lastDdlTime'='1487884795')
To create a person
table like employee
CREATE TABLE person LIKE employee;
To create a person
external table like employee
CREATE TABLE person LIKE employee LOCATION 'maprfs:/user/hadoop/data/person';
then use
DESC person;
to see the newly created table schema.
In case anyone is running into this issue testing, No it is not universally supported.
I am currently testing with Sahi Pro and it is very apparent a http DELETE call strips any provided body data (a large list of id's to delete in bulk as per endpoint design).
I have been in contact with them several times as well as sent in three separate packages of scrips, images, logs for them to review and they still have not confirmed this. A failed patch, and a missed conference calls by their support later and I still haven't gotten a solid answer.
I am certain Sahi does not support this, and I would imagine many other tools follow suite.
If it's the same number of characters at the beginning of the cell each time, you can use the text to columns command and select the fixed width option to chop the cell data into two columns. Then just delete the unwanted stuff in the first column.
Found a workaround solution. Say that you want to scroll to an div, Element here for example, and you want to have a spacing of 20px above it. Set the ref to a created div above it:
<div ref={yourRef} style={{position: 'relative', bottom: 20}}/>
<Element />
Doing so will create this spacing that you want.
If you have a header, create an empty div as well behind the header and assign to it a height equal to the height of the header and reference it.
If I'm not mistaking you can use, whatever-query-set.group_by=['field']
When your form is maximized, set its minimum size = max size, so user cannot resize it.
this.WindowState = FormWindowState.Maximized;
this.MinimumSize = this.Size;
this.MaximumSize = this.Size;
I've developed my own MySQL escape method in Java (if useful for anyone).
See class code below.
Warning: wrong if NO_BACKSLASH_ESCAPES SQL mode is enabled.
private static final HashMap<String,String> sqlTokens;
private static Pattern sqlTokenPattern;
static
{
//MySQL escape sequences: http://dev.mysql.com/doc/refman/5.1/en/string-syntax.html
String[][] search_regex_replacement = new String[][]
{
//search string search regex sql replacement regex
{ "\u0000" , "\\x00" , "\\\\0" },
{ "'" , "'" , "\\\\'" },
{ "\"" , "\"" , "\\\\\"" },
{ "\b" , "\\x08" , "\\\\b" },
{ "\n" , "\\n" , "\\\\n" },
{ "\r" , "\\r" , "\\\\r" },
{ "\t" , "\\t" , "\\\\t" },
{ "\u001A" , "\\x1A" , "\\\\Z" },
{ "\\" , "\\\\" , "\\\\\\\\" }
};
sqlTokens = new HashMap<String,String>();
String patternStr = "";
for (String[] srr : search_regex_replacement)
{
sqlTokens.put(srr[0], srr[2]);
patternStr += (patternStr.isEmpty() ? "" : "|") + srr[1];
}
sqlTokenPattern = Pattern.compile('(' + patternStr + ')');
}
public static String escape(String s)
{
Matcher matcher = sqlTokenPattern.matcher(s);
StringBuffer sb = new StringBuffer();
while(matcher.find())
{
matcher.appendReplacement(sb, sqlTokens.get(matcher.group(1)));
}
matcher.appendTail(sb);
return sb.toString();
}
The MOST CORRECT answer to your question is...
#content > div:first-of-type { /* css */ }
This will apply the CSS to the first div that is a direct child of #content (which may or may not be the first child element of #content)
Another option:
#content > div:nth-of-type(1) { /* css */ }
To remove all default error messages use
$.validator.messages.required = "";
Try this function. I just wrote it and haven't had much of a chance to test it, but my preliminary tests are promising.
public static XmlDocument JsonToXml(string json)
{
XmlNode newNode = null;
XmlNode appendToNode = null;
XmlDocument returnXmlDoc = new XmlDocument();
returnXmlDoc.LoadXml("<Document />");
XmlNode rootNode = returnXmlDoc.SelectSingleNode("Document");
appendToNode = rootNode;
string[] arrElementData;
string[] arrElements = json.Split('\r');
foreach (string element in arrElements)
{
string processElement = element.Replace("\r", "").Replace("\n", "").Replace("\t", "").Trim();
if ((processElement.IndexOf("}") > -1 || processElement.IndexOf("]") > -1) && appendToNode != rootNode)
{
appendToNode = appendToNode.ParentNode;
}
else if (processElement.IndexOf("[") > -1)
{
processElement = processElement.Replace(":", "").Replace("[", "").Replace("\"", "").Trim();
newNode = returnXmlDoc.CreateElement(processElement);
appendToNode.AppendChild(newNode);
appendToNode = newNode;
}
else if (processElement.IndexOf("{") > -1 && processElement.IndexOf(":") > -1)
{
processElement = processElement.Replace(":", "").Replace("{", "").Replace("\"", "").Trim();
newNode = returnXmlDoc.CreateElement(processElement);
appendToNode.AppendChild(newNode);
appendToNode = newNode;
}
else
{
if (processElement.IndexOf(":") > -1)
{
arrElementData = processElement.Replace(": \"", ":").Replace("\",", "").Replace("\"", "").Split(':');
newNode = returnXmlDoc.CreateElement(arrElementData[0]);
for (int i = 1; i < arrElementData.Length; i++)
{
newNode.InnerText += arrElementData[i];
}
appendToNode.AppendChild(newNode);
}
}
}
return returnXmlDoc;
}
The code was most likely compiled with a later JDK (without using cross-compilation options) and is being run on an earlier JRE. While upgrading the JRE is one solution, it would be better to use the cross-compilation options to ensure the code will run on whatever JRE is intended as the minimum version for the app.
Using React.createRef()
class MessageBox extends Component {
constructor(props) {
super(props)
this.boxRef = React.createRef()
}
scrollToBottom = () => {
this.boxRef.current.scrollTop = this.boxRef.current.scrollHeight
}
componentDidUpdate = () => {
this.scrollToBottom()
}
render() {
return (
<div ref={this.boxRef}></div>
)
}
}
It doesn't work on Ubuntu 16.04, it seems that some libraries have been forgotten in the python installation package on this one. You should use package manager instead.
Uninstall matplotlib from pip then install it again with apt-get
python 2:
sudo pip uninstall matplotlib
sudo apt-get install python-matplotlib
python 3:
sudo pip3 uninstall matplotlib
sudo apt-get install python3-matplotlib
import pprint pprint.pprint(list(chunks(range(10, 75), 10))) [range(10, 20), range(20, 30), range(30, 40), range(40, 50), range(50, 60), range(60, 70), range(70, 75)]
Confer this implementation's result with the example usage result of the accepted answer.
Many of the above functions assume that the length of the whole iterable are known up front, or at least are cheap to calculate.
For some streamed objects that would mean loading the full data into memory first (e.g. to download the whole file) to get the length information.
If you however don't know the the full size yet, you can use this code instead:
def chunks(iterable, size):
"""
Yield successive chunks from iterable, being `size` long.
https://stackoverflow.com/a/55776536/3423324
:param iterable: The object you want to split into pieces.
:param size: The size each of the resulting pieces should have.
"""
i = 0
while True:
sliced = iterable[i:i + size]
if len(sliced) == 0:
# to suppress stuff like `range(max, max)`.
break
# end if
yield sliced
if len(sliced) < size:
# our slice is not the full length, so we must have passed the end of the iterator
break
# end if
i += size # so we start the next chunk at the right place.
# end while
# end def
This works because the slice command will return less/no elements if you passed the end of an iterable:
"abc"[0:2] == 'ab'
"abc"[2:4] == 'c'
"abc"[4:6] == ''
We now use that result of the slice, and calculate the length of that generated chunk. If it is less than what we expect, we know we can end the iteration.
That way the iterator will not be executed unless access.
Checked this on many complex and obfuscated scripts:
var js = "alert('Hello, World!');" // put your JS code here
var oScript = document.createElement("script");
var oScriptText = document.createTextNode(js);
oScript.appendChild(oScriptText);
document.body.appendChild(oScript);
Here is a no fancy one:
def reverse(text):
r_text = ''
index = len(text) - 1
while index >= 0:
r_text += text[index] #string canbe concatenated
index -= 1
return r_text
print reverse("hello, world!")
A Node is a part of the DOM tree, an Element is a particular type of Node
e.g.
<foo> This is Text </foo>
You have a foo Element, (which is also a Node, as Element inherits from Node) and a Text Node 'This is Text', that is a child of the foo Element/Node
swift 4 way:
extension UIColor {
static let system = UIView().tintColor!
}
Try
.zshrc
or .bashrc
:LANG="en_US.UTF-8" LC_COLLATE="en_US.UTF-8" LC_CTYPE="en_US.UTF-8" LC_MESSAGES="en_US.UTF-8" LC_MONETARY="en_US.UTF-8" LC_NUMERIC="en_US.UTF-8" LC_TIME="en_US.UTF-8" LC_ALL="en_US.UTF-8"
TL;DR No, it can't be done automatically. Yes, it is possible.
import matplotlib.pyplot as plt
my_colors = plt.rcParams['axes.prop_cycle']() # <<< note that we CALL the prop_cycle
fig, axes = plt.subplots(2,3)
for ax in axes.flatten(): ax.plot((0,1), (0,1), **next(my_colors))
Each plot (axes
) in a figure (figure
) has its own cycle of colors — if you don't force a different color for each plot, all the plots share the same order of colors but, if we stretch a bit what "automatically" means, it can be done.
The OP wrote
[...] I have to identify each plot with a different color which should be automatically generated by [Matplotlib].
But... Matplotlib automatically generates different colors for each different curve
In [10]: import numpy as np
...: import matplotlib.pyplot as plt
In [11]: plt.plot((0,1), (0,1), (1,2), (1,0));
Out[11]:
So why the OP request? If we continue to read, we have
Can you please give me a method to put different colors for different plots in the same figure?
and it make sense, because each plot (each axes
in Matplotlib's parlance) has its own color_cycle
(or rather, in 2018, its prop_cycle
) and each plot (axes
) reuses the same colors in the same order.
In [12]: fig, axes = plt.subplots(2,3)
In [13]: for ax in axes.flatten():
...: ax.plot((0,1), (0,1))
If this is the meaning of the original question, one possibility is to explicitly name a different color for each plot.
If the plots (as it often happens) are generated in a loop we must have an additional loop variable to override the color automatically chosen by Matplotlib.
In [14]: fig, axes = plt.subplots(2,3)
In [15]: for ax, short_color_name in zip(axes.flatten(), 'brgkyc'):
...: ax.plot((0,1), (0,1), short_color_name)
Another possibility is to instantiate a cycler object
from cycler import cycler
my_cycler = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])
actual_cycler = my_cycler()
fig, axes = plt.subplots(2,3)
for ax in axes.flat:
ax.plot((0,1), (0,1), **next(actual_cycler))
Note that type(my_cycler)
is cycler.Cycler
but type(actual_cycler)
is itertools.cycle
.
Using :
Set the head of the list to it bottom lv.setStackFromBottom(true);
Worked for me and the list is scrolled to the bottom automatically when it is first brought into visibility. The list then scrolls as it should with TRANSCRIPT_MODE_ALWAYS_SCROLL
.
One possibility is to use the itemgetter function from the operator
module:
import operator
f = operator.itemgetter(0)
print map(f, tuple_list).index("cherry") # yields 1
The call to itemgetter
returns a function that will do the equivalent of foo[0]
for anything passed to it. Using map
, you then apply that function to each tuple, extracting the info into a new list, on which you then call index
as normal.
map(f, tuple_list)
is equivalent to:
[f(tuple_list[0]), f(tuple_list[1]), ...etc]
which in turn is equivalent to:
[tuple_list[0][0], tuple_list[1][0], tuple_list[2][0]]
which gives:
["pineapple", "cherry", ...etc]
Simple code for dynamic array. In below code then array will become full of size we copy all element to new double size array(variable size array).sample code is below
public class DynamicArray {
static int []increaseSizeOfArray(int []arr){
int []brr=new int[(arr.length*2)];
for (int i = 0; i < arr.length; i++) {
brr[i]=arr[i];
}
return brr;
}
public static void main(String[] args) {
int []arr=new int[5];
for (int i = 0; i < 11; i++) {
if (i<arr.length) {
arr[i]=i+100;
}
else {
arr=increaseSizeOfArray(arr);
arr[i]=i+100;
}
}
for (int i = 0; i < arr.length; i++) {
System.out.println("arr="+arr[i]);
}
}
}
Source : How to make dynamic array
Using these libraries:
Using this code:
List<Object[]> testNovedads = crudService.createNativeQuery(
"SELECT cantidad, id FROM NOVEDADES GROUP BY id ");
Gson gson = new Gson();
String json = gson.toJson(new TestNovedad());
JSONObject jsonObject = new JSONObject(json);
Collection<TestNovedad> novedads = new ArrayList<>();
for (Object[] object : testNovedads) {
Iterator<String> iterator = jsonObject.keys();
int pos = 0;
for (Iterator i = iterator; i.hasNext();) {
jsonObject.put((String) i.next(), object[pos++]);
}
novedads.add(gson.fromJson(jsonObject.toString(), TestNovedad.class));
}
for (TestNovedad testNovedad : novedads) {
System.out.println(testNovedad.toString());
}
/**
* Autores: Chalo Mejia
* Fecha: 01/10/2020
*/
package org.main;
import java.io.Serializable;
public class TestNovedad implements Serializable {
private static final long serialVersionUID = -6362794385792247263L;
private int id;
private int cantidad;
public TestNovedad() {
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
@Override
public String toString() {
return "TestNovedad [id=" + id + ", cantidad=" + cantidad + "]";
}
}
[request setValue:@"application/zip" forHTTPHeaderField:@"Content-Type"];
pandas DataFrame/Series
or numpy array
:The top answers are optimized methods for single point calculation, but when you want to apply these methods to a pandas series or numpy array, it requires apply
, which is basically for loop in the background and will iterate over every row and apply the method. This is quite inefficient.
To speed up our code, we can make use of vectorization and numpy broadcasting:
x = np.arange(-5,5)
np.divide(1, 1+np.exp(-x))
0 0.006693
1 0.017986
2 0.047426
3 0.119203
4 0.268941
5 0.500000
6 0.731059
7 0.880797
8 0.952574
9 0.982014
dtype: float64
Or with a pandas Series
:
x = pd.Series(np.arange(-5,5))
np.divide(1, 1+np.exp(-x))
Where are you configuring your authenticated URL pattern(s)? I only see one uri in your code.
Do you have multiple configure(HttpSecurity) methods or just one? It looks like you need all your URIs in the one method.
I have a site which requires authentication to access everything so I want to protect /*. However in order to authenticate I obviously want to not protect /login. I also have static assets I'd like to allow access to (so I can make the login page pretty) and a healthcheck page that shouldn't require auth.
In addition I have a resource, /admin, which requires higher privledges than the rest of the site.
The following is working for me.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login**").permitAll()
.antMatchers("/healthcheck**").permitAll()
.antMatchers("/static/**").permitAll()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.antMatchers("/**").access("hasRole('ROLE_USER')")
.and()
.formLogin().loginPage("/login").failureUrl("/login?error")
.usernameParameter("username").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling().accessDeniedPage("/403")
.and()
.csrf();
}
NOTE: This is a first match wins so you may need to play with the order. For example, I originally had /** first:
.antMatchers("/**").access("hasRole('ROLE_USER')")
.antMatchers("/login**").permitAll()
.antMatchers("/healthcheck**").permitAll()
Which caused the site to continually redirect all requests for /login back to /login. Likewise I had /admin/** last:
.antMatchers("/**").access("hasRole('ROLE_USER')")
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
Which resulted in my unprivledged test user "guest" having access to the admin interface (yikes!)
Get URL param as an object.
import { Router } from '@angular/router';
constructor(private router: Router) {
console.log(router.parseUrl(router.url));
}
Most answers suggest appending '%' at the end. I would rather prefer Intl.NumberFormat()
with { style: 'percent'}
var num = 25;_x000D_
_x000D_
var option = {_x000D_
style: 'percent'_x000D_
_x000D_
};_x000D_
var formatter = new Intl.NumberFormat("en-US", option);_x000D_
var percentFormat = formatter.format(num / 100);_x000D_
console.log(percentFormat);
_x000D_
The simplest way to insert a new line between echo
statements is to insert an echo
without arguments, for example:
echo Create the snapshots
echo
echo Snapshot created
That is, echo
without any arguments will print a blank line.
Another alternative to use a single echo
statement with the -e
flag and embedded newline characters \n
:
echo -e "Create the snapshots\n\nSnapshot created"
However, this is not portable, as the -e
flag doesn't work consistently in all systems. A better way if you really want to do this is using printf
:
printf "Create the snapshots\n\nSnapshot created\n"
This works more reliably in many systems, though it's not POSIX compliant. Notice that you must manually add a \n
at the end, as printf
doesn't append a newline automatically as echo
does.
I recommended an experimental new attribute CSS I tested on latest browser and it's good:
image-rendering: optimizeSpeed; /* */
image-rendering: -moz-crisp-edges; /* Firefox */
image-rendering: -o-crisp-edges; /* Opera */
image-rendering: -webkit-optimize-contrast; /* Chrome (and Safari) */
image-rendering: optimize-contrast; /* CSS3 Proposed */
-ms-interpolation-mode: nearest-neighbor; /* IE8+ */
With this the browser will know the algorithm for rendering
I set the max width for my video to be 100%. On phones the video automatically fits the width of the screen. Since the embedded video is only 560px wide, I just added a 10% left-margin to the iframe, and put a "0" back in for the margin for the mobile CSS (to allow the full width view). I did't want to bother putting a div around every video...
Desktop CSS:
iframe {_x000D_
margin-left: 10%;_x000D_
}
_x000D_
Mobile CSS:
iframe {_x000D_
margin-left: 0;_x000D_
}
_x000D_
Worked perfect for my blog (Botanical Amy).
If you don't know which checkboxes your page has (ex: if you are creating them dynamically) you can simply put a hidden field with the same name and 0 value right above the checkbox.
<input type="hidden" name="foo" value="0" />
<input type="checkbox" name="foo" value="1">
This way you will get 1 or 0 based on whether the checkbox is selected or not.
The problem comes from the fact that np.isnan()
does not handle string values correctly. For example, if you do:
np.isnan("A")
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
However the pandas version pd.isnull()
works for numeric and string values:
pd.isnull("A")
> False
pd.isnull(3)
> False
pd.isnull(np.nan)
> True
pd.isnull(None)
> True
With the module pygame.draw shapes like rectangles, circles, polygons, liens, ellipses or arcs can be drawn. Some examples:
pygame.draw.rect
draws filled rectangular shapes or outlines. The arguments are the target Surface (i.s. the display), the color, the rectangle and the optional outline width. The rectangle argument is a tuple with the 4 components (x, y, width, height), where (x, y) is the upper left point of the rectangle. Alternatively, the argument can be a pygame.Rect
object:
pygame.draw.rect(window, color, (x, y, width, height))
rectangle = pygame.Rect(x, y, width, height)
pygame.draw.rect(window, color, rectangle)
pygame.draw.circle
draws filled circles or outlines. The arguments are the target Surface (i.s. the display), the color, the center, the radius and the optional outline width. The center argument is a tuple with the 2 components (x, y):
pygame.draw.circle(window, color, (x, y), radius)
pygame.draw.polygon
draws filled polygons or contours. The arguments are the target Surface (i.s. the display), the color, a list of points and the optional contour width. Each point is a tuple with the 2 components (x, y):
pygame.draw.polygon(window, color, [(x1, y1), (x2, y2), (x3, y3)])
Minimal example:
import pygame
pygame.init()
window = pygame.display.set_mode((200, 200))
clock = pygame.time.Clock()
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill((255, 255, 255))
pygame.draw.rect(window, (0, 0, 255), (20, 20, 160, 160))
pygame.draw.circle(window, (255, 0, 0), (100, 100), 80)
pygame.draw.polygon(window, (255, 255, 0),
[(100, 20), (100 + 0.8660 * 80, 140), (100 - 0.8660 * 80, 140)])
pygame.display.flip()
pygame.quit()
exit()
The exact conversion of the java static method to kotlin equivalent would be like this. e.g. Here the util class has one static method which would be equivalent in both java and kotlin. The use of @JvmStatic is important.
Java code:
class Util{
public static String capitalize(String text){
return text.toUpperCase();}
}
Kotlin code:
class Util {
companion object {
@JvmStatic
fun capitalize(text:String): String {
return text.toUpperCase()
}
}
}
Gwerder's solution wont work because hash = hmac.read();
happens before the stream is done being finalized. Thus AngraX's issues. Also the hmac.write
statement is un-necessary in this example.
Instead do this:
var crypto = require('crypto');
var hmac;
var algorithm = 'sha1';
var key = 'abcdeg';
var text = 'I love cupcakes';
var hash;
hmac = crypto.createHmac(algorithm, key);
// readout format:
hmac.setEncoding('hex');
//or also commonly: hmac.setEncoding('base64');
// callback is attached as listener to stream's finish event:
hmac.end(text, function () {
hash = hmac.read();
//...do something with the hash...
});
More formally, if you wish, the line
hmac.end(text, function () {
could be written
hmac.end(text, 'utf8', function () {
because in this example text is a utf string
updated:
startdate = "20.03.2014";
var new_date = moment(startdate, "DD-MM-YYYY").add(5,'days');
alert(new_date)
If you want to stop your server with npm stop
or something like this. You can write the code that kill your server process as:
require('child_process').exec(`kill -9 ${pid}`)
Check this link for the detail: https://gist.github.com/dominhhai/aa7f3314ad27e2c50fd5
Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.
As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:
var clone = _.clone(data, true);
data[1].values.d = 'x';
_.isEqual(data, clone) === false
_.isEqual(data, clone) === true
I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.
Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).
This code will list out all the form variables that are being sent in a POST. This way you can see if you have the proper names of the post values.
string[] keys = Request.Form.AllKeys;
for (int i= 0; i < keys.Length; i++)
{
Response.Write(keys[i] + ": " + Request.Form[keys[i]] + "<br>");
}
rem This is the command line version
cscript "C:\Users\guest\Desktop\123\MyScript.vbs"
OR
rem This is the windowed version
wscript "C:\Users\guest\Desktop\123\MyScript.vbs"
You can also add the option //e:vbscript
to make sure the scripting engine will recognize your script as a vbscript.
Windows/DOS batch files doesn't require escaping \
like *nix.
You can still use "C:\Users\guest\Desktop\123\MyScript.vbs"
, but this requires the user has *.vbs
associated to wscript
.
if use JPA I recommend change to lowercase schema, table and column names, you can use next intructions for help you:
select
psat.schemaname,
psat.relname,
pa.attname,
psat.relid
from
pg_catalog.pg_stat_all_tables psat,
pg_catalog.pg_attribute pa
where
psat.relid = pa.attrelid
change schema name:
ALTER SCHEMA "XXXXX" RENAME TO xxxxx;
change table names:
ALTER TABLE xxxxx."AAAAA" RENAME TO aaaaa;
change column names:
ALTER TABLE xxxxx.aaaaa RENAME COLUMN "CCCCC" TO ccccc;
You will need to parse the input to a DateTime object and then convert it to any text format you want.
If you are not sure what format you will get, you can restrict the user to a fixed format by using validation or datetimePicker, or some other component.
Here's an answer for those deploying a Node.js application to Amazon AWS Elastic Beanstalk. I haven't seen this documented anywhere else:
Under Configuration -> Software -> Environment Properties
, simply set the key value pair TZ
and your time zone e.g. America/Los Angeles
, and Apply the change.
You can verify the effect by outputting new Date().toString()
in your Node app and paying attention to the time zone suffix.
Another way around this would be to insert a DEFAULT element in the other table. For example, any reference to uuid=00000000-0000-0000-0000-000000000000 on the other table would indicate no action. You also need to set all the values for that id to be "neutral", e.g. 0, empty string, null in order to not affect your code logic.
@Autowired
private RestOperations restTemplate;
You can only autowire interfaces with implementations.
download jre1.7.0_45 and then extract it into the Eclipse folder and rename folder of jre1.7.0_45 to jre and Eclipse will run
The easiest solution to animate the DOM elements is using CSS transitions/animations but I think you already know that and you try to use canvas to do stuff CSS doesn't let you to do. What about CSS custom filters? you can transform your elements in any imaginable way if you know how to write shaders. Some other link and don't forget to check the CSS filter lab.
Note: As you can probably imagine browser support is bad.
Just store the index generated in a variable, and then access the array using this varaible:
int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);
P.S. I usually don't like generating new Random
object per randoization - I prefer using a single Random
in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.
According to this approach, I will have some variable Random r
somewhere, and I will just use:
int idx = r.nextInt(fruits.length)
However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.
Give the container class
.container{
height: 100vh;
width: 100vw;
display: flex;
}
Give the div that's inside the container:
align-content: center;
All the content inside this div will show up in the middle of the page.
var date = new Date();
var targetDate = moment(date).subtract(1, 'day').toDate(); // date object
Now, you can format how you wanna see this date or you can compare this date with another etc.
toDate()
function is the point.
Let's say I have an array arr. When would the following not give the number of elements of the array: sizeof(arr) / sizeof(arr[0])?
One thing I've often seen new programmers doing this:
void f(Sample *arr)
{
int count = sizeof(arr)/sizeof(arr[0]); //what would be count? 10?
}
Sample arr[10];
f(arr);
So new programmers think the value of count
will be 10. But that's wrong.
Even this is wrong:
void g(Sample arr[]) //even more deceptive form!
{
int count = sizeof(arr)/sizeof(arr[0]); //count would not be 10
}
It's all because once you pass an array to any of these functions, it becomes pointer type, and so sizeof(arr)
would give the size of pointer, not array!
EDIT:
The following is an elegant way you can pass an array to a function, without letting it to decay into pointer type:
template<size_t N>
void h(Sample (&arr)[N])
{
size_t count = N; //N is 10, so would be count!
//you can even do this now:
//size_t count = sizeof(arr)/sizeof(arr[0]); it'll return 10!
}
Sample arr[10];
h(arr); //pass : same as before!
zip()
in conjunction with the *
operator can be used to unzip
a list
unzip_lst = zip(*mylist)
for i in unzip_lst:
for j in i:
print j
Definitely in Modules.
Since the tooling is so poor in primitive systems such as Excel VBA, best practices, obsessive code hygiene and religious following of conventions are important, especially if you're trying to do anything remotely complex with it.
This article explains the intended usages of different types of code containers. It doesn't qualify why these distinctions should be made, but I believe most developers trying to develop serious applications on the Excel platform follow them.
There's also a list of VBA coding conventions I've found helpful, although they're not directly related to Excel VBA. Please ignore the crazy naming conventions they have on that site, it's all crazy hungarian.
If you don't mind using 3rd party libraries, AOL's cyclops-react lib (disclosure I am a contributor) has extensions for all JDK Collection types, including List. The ListX interface extends java.util.List and adds a large number of useful operators, including filter.
You can simply write-
ListX<Long> sourceLongList = ListX.of(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
ListX<Long> targetLongList = sourceLongList.filter(l -> l > 100);
ListX also can be created from an existing List (via ListX.fromIterable)
Javascript will throw an exception if you attempt to use a break;
statement inside an if else. It is used mainly for loops. You can "break" out of an if else statement with a condition, which does not make sense to include a "break" statement.
I am making a blog website on github pages. I got an idea to embbed comments in the end of every blog page. I understand how firebase get and gives you data.
I have tested many times with project and even using console. I am totally disagree the saying vlit is vulnerable. Believe me there is no issue of showing your api key publically if you have followed privacy steps recommend by firebase. Go to https://console.developers.google.com/apis and perfrom a security steup.
The following are my requirements for a 404 solution and below i show how i implement it:
I think you should save Application_Error
in the Global.asax for higher things, like unhandled exceptions and logging (like Shay Jacoby's answer shows) but not 404 handling. This is why my suggestion keeps the 404 stuff out of the Global.asax file.
This is a good idea for maintainability. Use an ErrorController so that future improvements to your well designed 404 page can adapt easily. Also, make sure your response has the 404 code!
public class ErrorController : MyController
{
#region Http404
public ActionResult Http404(string url)
{
Response.StatusCode = (int)HttpStatusCode.NotFound;
var model = new NotFoundViewModel();
// If the url is relative ('NotFound' route) then replace with Requested path
model.RequestedUrl = Request.Url.OriginalString.Contains(url) & Request.Url.OriginalString != url ?
Request.Url.OriginalString : url;
// Dont get the user stuck in a 'retry loop' by
// allowing the Referrer to be the same as the Request
model.ReferrerUrl = Request.UrlReferrer != null &&
Request.UrlReferrer.OriginalString != model.RequestedUrl ?
Request.UrlReferrer.OriginalString : null;
// TODO: insert ILogger here
return View("NotFound", model);
}
public class NotFoundViewModel
{
public string RequestedUrl { get; set; }
public string ReferrerUrl { get; set; }
}
#endregion
}
HandleUnknownAction
404s in ASP.NET MVC need to be caught at a number of places. The first is HandleUnknownAction
.
The InvokeHttp404
method creates a common place for re-routing to the ErrorController
and our new Http404
action. Think DRY!
public abstract class MyController : Controller
{
#region Http404 handling
protected override void HandleUnknownAction(string actionName)
{
// If controller is ErrorController dont 'nest' exceptions
if (this.GetType() != typeof(ErrorController))
this.InvokeHttp404(HttpContext);
}
public ActionResult InvokeHttp404(HttpContextBase httpContext)
{
IController errorController = ObjectFactory.GetInstance<ErrorController>();
var errorRoute = new RouteData();
errorRoute.Values.Add("controller", "Error");
errorRoute.Values.Add("action", "Http404");
errorRoute.Values.Add("url", httpContext.Request.Url.OriginalString);
errorController.Execute(new RequestContext(
httpContext, errorRoute));
return new EmptyResult();
}
#endregion
}
Like so (it doesn't have to be StructureMap):
MVC1.0 example:
public class StructureMapControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(Type controllerType)
{
try
{
if (controllerType == null)
return base.GetControllerInstance(controllerType);
}
catch (HttpException ex)
{
if (ex.GetHttpCode() == (int)HttpStatusCode.NotFound)
{
IController errorController = ObjectFactory.GetInstance<ErrorController>();
((ErrorController)errorController).InvokeHttp404(RequestContext.HttpContext);
return errorController;
}
else
throw ex;
}
return ObjectFactory.GetInstance(controllerType) as Controller;
}
}
MVC2.0 example:
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
try
{
if (controllerType == null)
return base.GetControllerInstance(requestContext, controllerType);
}
catch (HttpException ex)
{
if (ex.GetHttpCode() == 404)
{
IController errorController = ObjectFactory.GetInstance<ErrorController>();
((ErrorController)errorController).InvokeHttp404(requestContext.HttpContext);
return errorController;
}
else
throw ex;
}
return ObjectFactory.GetInstance(controllerType) as Controller;
}
I think its better to catch errors closer to where they originate. This is why i prefer the above to the Application_Error
handler.
This is the second place to catch 404s.
This route should point to our Http404
action. Notice the url
param will be a relative url because the routing engine is stripping the domain part here? That is why we have all that conditional url logic in Step 1.
routes.MapRoute("NotFound", "{*url}",
new { controller = "Error", action = "Http404" });
This is the third and final place to catch 404s in an MVC app that you don't invoke yourself. If you don't catch unmatched routes here then MVC will pass the problem up to ASP.NET (Global.asax) and you don't really want that in this situation.
Like when a bad ID is submitted to my Loans controller (derives from MyController
):
//
// GET: /Detail/ID
public ActionResult Detail(int ID)
{
Loan loan = this._svc.GetLoans().WithID(ID);
if (loan == null)
return this.InvokeHttp404(HttpContext);
else
return View(loan);
}
It would be nice if all this could be hooked up in fewer places with less code but i think this solution is more maintainable, more testable and fairly pragmatic.
Thanks for the feedback so far. I'd love to get more.
NOTE: This has been edited significantly from my original answer but the purpose/requirements are the same - this is why i have not added a new answer
ResponseEntity
is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.
@ResponseBody
is a marker for the HTTP response body and @ResponseStatus
declares the status code of the HTTP response.
@ResponseStatus
isn't very flexible. It marks the entire method so you have to be sure that your handler method will always behave the same way. And you still can't set the headers. You'd need the HttpServletResponse
or a HttpHeaders
parameter.
Basically, ResponseEntity
lets you do more.
@Component({
selector: 'my-app',
template: `
<div>
<input name="file" type="file" (change)="onChange($event)"/>
</div>
`,
providers: [ UploadService ]
})
export class AppComponent {
file: File;
onChange(event: EventTarget) {
let eventObj: MSInputMethodContext = <MSInputMethodContext> event;
let target: HTMLInputElement = <HTMLInputElement> eventObj.target;
let files: FileList = target.files;
this.file = files[0];
console.log(this.file);
}
doAnythingWithFile() {
}
}
You can get errors working correctly without hacking global.cs, messing with HandleErrorAttribute, doing Response.TrySkipIisCustomErrors, hooking up Application_Error, or whatever:
In system.web (just the usual, on/off)
<customErrors mode="On">
<error redirect="/error/401" statusCode="401" />
<error redirect="/error/500" statusCode="500" />
</customErrors>
and in system.webServer
<httpErrors existingResponse="PassThrough" />
Now things should behave as expected, and you can use your ErrorController to display whatever you need.
ActiveRecord#where will return an ActiveRecord::Relation object (which will never be nil). Try using .empty? on the relation to test if it will return any records.
In my case, I have several tasks I want to execute in parallel, but I need to do something different with the result of those tasks.
function wait(ms, data) {
console.log('Starting task:', data, ms);
return new Promise(resolve => setTimeout(resolve, ms, data));
}
var tasks = [
async () => {
var result = await wait(1000, 'moose');
// do something with result
console.log(result);
},
async () => {
var result = await wait(500, 'taco');
// do something with result
console.log(result);
},
async () => {
var result = await wait(5000, 'burp');
// do something with result
console.log(result);
}
]
await Promise.all(tasks.map(p => p()));
console.log('done');
And the output:
Starting task: moose 1000
Starting task: taco 500
Starting task: burp 5000
taco
moose
burp
done
Tools-> Options-> Select no proxy is worked for me
entropy is availability of information or knowledge, Lack of information will leads to difficulties in prediction of future which is high entropy (next word prediction in text mining) and availability of information/knowledge will help us more realistic prediction of future (low entropy).
Relevant information of any type will reduce entropy and helps us predict more realistic future, that information can be word "meat" is present in sentence or word "meat" is not present. This is called Information Gain
entropy is lack of order of predicability
They are both examples of floating point input/output.
%g and %G are simplifiers of the scientific notation floats %e and %E.
%g will take a number that could be represented as %f (a simple float or double) or %e (scientific notation) and return it as the shorter of the two.
The output of your print statement will depend on the value of sum.
It is very simple using Sass, just use @extend
:
.pull-right-xs {
@extend .pull-right;
}
The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.
Try using %lx
or %llx
. For more portability, include inttypes.h
and use the PRIx64
macro.
For example: printf("val = 0x%" PRIx64 "\n", val);
(note that it's string concatenation)
You can run the MySQL command SHOW FULL PROCESSLIST;
to see what queries are being processed at any given time, but that probably won't achieve what you're hoping for.
The best method to get a history without having to modify every application using the server is probably through triggers. You could set up triggers so that every query run results in the query being inserted into some sort of history table, and then create a separate page to access this information.
Do be aware that this will probably considerably slow down everything on the server though, with adding an extra INSERT
on top of every single query.
Edit: another alternative is the General Query Log, but having it written to a flat file would remove a lot of possibilities for flexibility of displaying, especially in real-time. If you just want a simple, easy-to-implement way to see what's going on though, enabling the GQL and then using running tail -f
on the logfile would do the trick.
I like KHexEdit, which is part of KDE
Its "Windows style" UI is probably quite quick to learn for most people (compared to Vim or Emacs anyway :)
You can use a subquery. The subquery will get the Max(CompletedDate)
. You then take this value and join on your table again to retrieve the note associate with that date:
select ET1.TrainingID,
ET1.CompletedDate,
ET1.Notes
from HR_EmployeeTrainings ET1
inner join
(
select Max(CompletedDate) CompletedDate, TrainingID
from HR_EmployeeTrainings
--where AvantiRecID IS NULL OR AvantiRecID = @avantiRecID
group by TrainingID
) ET2
on ET1.TrainingID = ET2.TrainingID
and ET1.CompletedDate = ET2.CompletedDate
where ET1.AvantiRecID IS NULL OR ET1.AvantiRecID = @avantiRecID
Rebooting the phone was the solution for me.
The easiest option is to make use of the Excel copy/paste.
Public Sub insertRowBelow()
ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrAbove
ActiveCell.EntireRow.Copy
ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End Sub
Postgres has few types of timestamps:
timestamp without timezone - (Preferable to store UTC timestamps) You find it in multinational database storage. The client in this case will take care of the timezone offset for each country.
timestamp with timezone - The timezone offset is already included in the timestamp.
In some cases, your database does not use the timezone but you still need to group records in respect with local timezone and Daylight Saving Time (e.g. https://www.timeanddate.com/time/zone/romania/bucharest)
To add timezone you can use this example and replace the timezone offset with yours.
"your_date_column" at time zone '+03'
To add the +1 Summer Time offset specific to DST you need to check if your timestamp falls into a Summer DST. As those intervals varies with 1 or 2 days, I will use an aproximation that does not affect the end of month records, so in this case i can ignore each year exact interval.
If more precise query has to be build, then you have to add conditions to create more cases. But roughly, this will work fine in splitting data per month in respect with timezone and SummerTime when you find timestamp without timezone in your database:
SELECT
"id", "Product", "Sale",
date_trunc('month',
CASE WHEN
Extract(month from t."date") > 03 AND
Extract(day from t."date") > 26 AND
Extract(hour from t."date") > 3 AND
Extract(month from t."date") < 10 AND
Extract(day from t."date") < 29 AND
Extract(hour from t."date") < 4
THEN
t."date" at time zone '+03' -- Romania TimeZone offset + DST
ELSE
t."date" at time zone '+02' -- Romania TimeZone offset
END) as "date"
FROM
public."Table" AS t
WHERE 1=1
AND t."date" >= '01/07/2015 00:00:00'::TIMESTAMP WITHOUT TIME ZONE
AND t."date" < '01/07/2017 00:00:00'::TIMESTAMP WITHOUT TIME ZONE
GROUP BY date_trunc('month',
CASE WHEN
Extract(month from t."date") > 03 AND
Extract(day from t."date") > 26 AND
Extract(hour from t."date") > 3 AND
Extract(month from t."date") < 10 AND
Extract(day from t."date") < 29 AND
Extract(hour from t."date") < 4
THEN
t."date" at time zone '+03' -- Romania TimeZone offset + DST
ELSE
t."date" at time zone '+02' -- Romania TimeZone offset
END)
EDIT: see bobince's solution which uses contains rather than start-with, along with a trick to ensure the comparison is done at the level of a complete token (lest the 'atag' pattern be found as part of another 'tag').
"atag btag" is an odd value for the class attribute, but never the less, try:
//*[starts-with(@class,"atag")]
next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
Read article :Difference between next() and nextLine()
Replace your while loop with :
while(r.hasNext()) {
scan = r.next();
System.out.println(scan);
if(scan.length()==0) {continue;}
//treatment
}
Using hasNext()
and next()
methods will resolve the issue.
finalName is created as:
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
</build>
One of the solutions is to add own property:
<properties>
<finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
<finalName>${finalName}</finalName>
</build>
And now try:
mvn -DfinalName=build clean package
If you prefer splitting a CSV list in SQL, there's a different way to do it using Common Table Expressions (CTEs). See Efficient way to string split using CTE.
The (+) operator indicates an outer join. This means that Oracle will still return records from the other side of the join even when there is no match. For example if a and b are emp and dept and you can have employees unassigned to a department then the following statement will return details of all employees whether or not they've been assigned to a department.
select * from emp, dept where emp.dept_id=dept.dept_id(+)
So in short, removing the (+) may make a significance difference but you might not notice for a while depending on your data!
What happens with bittorrent and a DHT is that at the beginning bittorrent uses information embedded in the torrent file to go to either a tracker or one of a set of nodes from the DHT. Then once it finds one node, it can continue to find others and persist using the DHT without needing a centralized tracker to maintain it.
The original information bootstraps the later use of the DHT.
The illegal character is not in $matches[1]
, but in $xml
Try
iconv($matches[1], 'utf-8//TRANSLIT', $xml);
And showing us the input string would be nice for a better answer.
None of the solutions provided seemed at all easiest to me, so I'd like to add my own way.
Basically, you get the list of the elements instead of just the element and then count the results; if it's zero, then it doesn't exist. Example:
if driver.find_elements_by_css_selector('#element'):
print "Element exists"
Notice the "s" in find_elements_by_css_selector
to make sure it can be countable.
EDIT: I was checking the len(
of the list, but I recently learned that an empty list is falsey, so you don't need to get the length of the list at all, leaving for even simpler code.
Also, another answer says that using xpath is more reliable, which is just not true. See What is the difference between css-selector & Xpath? which is better(according to performance & for cross browser testing)?
I found a work around but with this I'll need to annotate each date's setter throughout the project. Is there a way in which I can specify the format while creating the ObjectMapper?
Here's what I did:
public class CustomJsonDateDeserializer extends JsonDeserializer<Date>
{
@Override
public Date deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String date = jsonParser.getText();
try {
return format.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
And annotated each Date field's setter method with this:
@JsonDeserialize(using = CustomJsonDateDeserializer.class)
One way to control the locale settings is to set the java system properties user.language and user.region.
You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t
below) and alias the columns as well.
The DISTINCT
can also be safely removed as the internal GROUP BY
makes it redundant:
SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
SELECT MIN(`date`) AS `date`, `player_name`
FROM `player_playtime`
GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;
Since the COUNT
is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*)
and further simplify the query:
SELECT t.date , COUNT(*) AS player_count
FROM (
SELECT DATE(MIN(`date`)) AS date
FROM player_playtime
GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;
In Scala, building up on YourBestBet's solution but simplified:
def prettyDuration(seconds: Long): List[String] = seconds match {
case t if t < 60 => List(s"${t} seconds")
case t if t < 3600 => s"${t / 60} minutes" :: prettyDuration(t % 60)
case t if t < 3600*24 => s"${t / 3600} hours" :: prettyDuration(t % 3600)
case t => s"${t / (3600*24)} days" :: prettyDuration(t % (3600*24))
}
val dur = prettyDuration(12345).mkString(", ") // => 3 hours, 25 minutes, 45 seconds
Use jQuery each()
. There are other ways but each is designed for this purpose.
$.each(substr, function(index, value) {
alert(value);
});
And do not put the comma after the last number.
Normally you want to show this message, when the user has made changes in a form, but they are not saved.
Take this approach to show a message, only when the user has changed something
var form = $('#your-form'),
original = form.serialize()
form.submit(function(){
window.onbeforeunload = null
})
window.onbeforeunload = function(){
if (form.serialize() != original)
return 'Are you sure you want to leave?'
}
You can do it with FormBuilder. Add this to the array in your FormBuilder:
'attr'=> array('class'=>'span2')
I figured out this problem by:
./gradlew
cleanWhile moopasta's answer works, it doesn't appear to allow wildcards and there is another (potentially better) option. The Chromium project has some HTTP authentication documentation that is useful but incomplete.
Specifically the option that I found best is to whitelist sites that you would like to allow Chrome to pass authentication information to, you can do this by:
auth-server-whitelist
command line switch. e.g. --auth-server-whitelist="*example.com,*foobar.com,*baz"
. Downfall to this approach is that opening links from other programs will launch Chrome without the command line switch.AuthServerWhitelist
/"Authentication server whitelist" Group Policy or Local Group Policy. This seems like the most stable option but takes more work to setup. You can set this up locally, no need to have this remotely deployed.Those looking to set this up for an enterprise can likely follow the directions for using Group Policy or the Admin console to configure the AuthServerWhitelist
policy. Those looking to set this up for one machine only can also follow the Group Policy instructions:
Start > Run > gpedit.msc
Local Computer Policy > Computer Configuration > Administrative Templates
Administrative Templates
, and select Add/Remove Templates
windows\adm\en-US\chrome.adm
template via the dialogComputer Configuration > Administrative Templates > Classic Administrative Templates > Google > Google Chrome > Policies for HTTP Authentication
enable and configure Authentication server whitelist
chrome://policy
to view active policiesThis worked for me:
curl -v --cookie "USER_TOKEN=Yes" http://127.0.0.1:5000/
I could see the value in backend using
print request.cookies
Head First Javascript is a good intro to JS for beginning programmers - it creatively explains basic programming concepts using JS syntax. The Head First series is based on researched techniques for helping you learn and remember new information. They have you do a lot of exercises and puzzles which might seem juvenile, but really help cement the knowledge in your brain.
One exercise I really liked was after they explained data types, they show a picture of a city street and say "label all the data types you can find in this picture." So the blinker on a car is a boolean, the sign on the store is a string, and the address is a number. That helped me get the idea of how to translate real information into a program.
Based only on this book, I'd say the Head First series is a great way to learn something the first time, but the story-like format they have would make them difficult to use as references.
To convert DateTime.UtcNow to a string representation of yyyy-MM-ddTHH:mm:ssZ, you can use the ToString() method of the DateTime structure with a custom formatting string. When using custom format strings with a DateTime, it is important to remember that you need to escape your seperators using single quotes.
The following will return the string represention you wanted:
DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", DateTimeFormatInfo.InvariantInfo)
It depends on whether you process IDNs before or after the IDN toASCII
algorithm (that is, do you see the domain name pa??de??µa.d???µ?
in Greek or as xn--hxajbheg2az3al.xn--jxalpdlp
?).
In the latter case—where you are handling IDNs through the punycode—the old RFC 1123 rules apply:
U+0041 through U+005A (A-Z), U+0061 through U+007A (a-z) case folded as each other, U+0030 through U+0039 (0-9) and U+002D (-).
and U+002E (.) of course; the rules for labels allow the others, with dots between labels.
If you are seeing it in IDN form, the allowed characters are much varied, see http://unicode.org/reports/tr36/idn-chars.html for a handy chart of all valid characters.
Chances are your network code will deal with the punycode, but your display code (or even just passing strings to and from other layers) with the more human-readable form as nobody running a server on the ????????. domain wants to see their server listed as being on .xn--mgberp4a5d4ar
.
I just want to propose another alternative that will concern some of you, indeed, as explained above:
android:configChanges="orientation|keyboardHidden"
implies that we explicitly declare the layout to be injected.
In case we want to keep the automatic injection thanks to the layout-land and layout folders. All you have to do is add it to the onCreate:
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
getSupportActionBar().hide();
} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
getSupportActionBar().show();
}
Here, we display or not the actionbar depending on the orientation of the phone
Make a bat file with the following in it:
copy /y C:\temp\log1k.txt C:\temp\log1k_copied.txt
However, I think there are issues if there are spaces in your directory names. Notice this was copied to the same directory, but that doesn't matter. If you want to see how it runs, make another bat file that calls the first and outputs to a log:
C:\temp\test.bat > C:\temp\test.log
(assuming the first bat file was called test.bat and was located in that directory)
if anyone cares there is a much better way to capture focus now, $(foo).focus(...)
You just need to specify a minimum date - setting it to 0 means that the minimum date is 0 days from today i.e. today. You could pass the string '0d'
instead (the default unit is days).
$(function () {
$('#date').datepicker({ minDate: 0 });
});
Happy coding!
If you get an error on Internet Explorer, Change the security settings to allow ActiveX
var CallBackFunction = function(content) {
alert(content);
}
ReadFileAllBrowsers(document.getElementById("file_upload"), CallBackFunction);
//Tested in Mozilla Firefox browser, Chrome
function ReadFileAllBrowsers(FileElement, CallBackFunction) {
try {
var file = FileElement.files[0];
var contents_ = "";
if (file) {
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function(evt) {
CallBackFunction(evt.target.result);
}
reader.onerror = function(evt) {
alert("Error reading file");
}
}
} catch (Exception) {
var fall_back = ieReadFile(FileElement.value);
if (fall_back != false) {
CallBackFunction(fall_back);
}
}
}
///Reading files with Internet Explorer
function ieReadFile(filename) {
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile(filename, 1);
var contents = fh.ReadAll();
fh.Close();
return contents;
} catch (Exception) {
alert(Exception);
return false;
}
}
If your goal is to have
str = "Hello\nWorld";
and output what it contains in string literal form, you can use JSON.stringify
:
console.log(JSON.stringify(str)); // ""Hello\nWorld""
const str = "Hello\nWorld";_x000D_
const json = JSON.stringify(str);_x000D_
console.log(json); // ""Hello\nWorld""_x000D_
for (let i = 0; i < json.length; ++i) {_x000D_
console.log(`${i}: ${json.charAt(i)}`);_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
max-height: 100% !important;_x000D_
}
_x000D_
console.log
adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).
JSON.stringify
takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("
), the word Hello
, a backslash (\
), the letter n
, the word World
, and the closing quote ("
). The linefeed in the string is escaped in the output as a \
and an n
because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.
Although I didn't use this exact function I got this same error.
In my case I just had to remove the protocol.
Instead of $uri = "http://api.hostip.info/?ip=$ip&position=true";
Use $uri = "api.hostip.info/?ip=$ip&position=true";
And it worked fine afterwards
The first is not working of course. The controls on a form are private, visible only for that form by design.
To make it all public is also not the best way.
If I would like to expose something to the outer world (which also can mean an another form), I make a public property for it.
public Boolean nameOfControlVisible
{
get { return this.nameOfControl.Visible; }
set { this.nameOfControl.Visible = value; }
}
You can use this public property to hide or show the control or to ask the control current visibility property:
otherForm.nameOfControlVisible = true;
You can also expose full controls, but I think it is too much, you should make visible only the properties you really want to use from outside the current form.
public ControlType nameOfControlP
{
get { return this.nameOfControl; }
set { this.nameOfControl = value; }
}
You can add a watchpoint for each variable you're interested in.
A watchpoint is a special breakpoint that stops the execution of an application whenever the value of a given expression changes, without specifying where it might occur. Unlike breakpoints (which are line-specific), watchpoints are associated with files. They take effect whenever a specified condition is true, regardless of when or where it occurred. You can set a watchpoint on a global variable by highlighting the variable in the editor, or by selecting it in the Outline view.
A typescript version of broofa's update from 2017-06-28, based on crypto
API:
function genUUID() {
// Reference: https://stackoverflow.com/a/2117523/709884
return ("10000000-1000-4000-8000-100000000000").replace(/[018]/g, s => {
const c = Number.parseInt(s, 10)
return (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
})
}
Reasons:
+
between number[]
and number
isn't validstring
to number
has to be explicitYou can use display: flow-root
on the parent element to prevent margin collapsing through the containing element as it creates new Block Formatting Context.
Changing the value of the overflow property to auto or using flexbox will have the same effect.
Lets Think this is your HTML Form in step2.php
step2.php
<form name="new user" method="post" action="step2_check.php">
<input type="text" name="mail"/> <br />
<input type="password" name="password"/><br />
<input type="submit" value="continue"/>
</form>
I think you need it for your database, so you can assign your HTML Form Value to php Variable, now you can use Real Escape String and below must be your
step2_check.php
if(isset($_POST['mail']) && !empty($_POST['mail']))
{
$mail = mysqli_real_escape_string($db, $_POST['mail']);
}
Where $db is your Database Connection.
This site Android Create AVD shows you how to install the latest version of the Android SDK and AVD version 4 in Eclipse with video and screenshots if you're still stuck?
Assembly.GetEntryAssembly()
The sample mvcmusicstore.codeplex.com opened in vs2015 missed some references, one of them System.web.mvc.
The fix for this was to remove it from the references and to add a reference: choose Extentions under Assemblies, there you can find and add System.Web.Mvc.
(The other assemblies I added with the nuget packages.)
This is working for me.
jQuery("#form_name").validate().settings.ignore = "";
Use this CSS for Modal and modal-dialog
.modal{
pointer-events: none;
}
.modal-dialog{
pointer-events: all;
}
This can resolve your problem in Modal
I had a slightly augmented issue. I needed to rename a machine and then RE-JOIN a domain it was already a member of and could not find where to do that but its seems very close to what is here. The individual solutions above don't do it but with some togetherness... If you try to rename, you get denied. If you rename and then rejoin, you get an account already exists error. You need to bail from the domain by joining a workgroup and then you can run the rename and join in one command.
$Chops = Get-Credential
# Or bring in a stored credential
$NewComputerName = "WhoImGonnaBe"
# or value from CSV
$MyDomainName = "MyDomain"
Add-Computer -WorkgroupName NotADomain -force -DomainCredential $Chops
Add-Computer -DomainName $MyDomainName -Computername $ENV:Computername -NewName $NewComputerName -DomainCredential $Chops -Force -Restart
# If running locally you really only need the -NewName and can omit the -Computername
You can display an image in your own window using Tkinter, w/o depending on image viewers installed in your system:
import Tkinter as tk
from PIL import Image, ImageTk # Place this at the end (to avoid any conflicts/errors)
window = tk.Tk()
#window.geometry("500x500") # (optional)
imagefile = {path_to_your_image_file}
img = ImageTk.PhotoImage(Image.open(imagefile))
lbl = tk.Label(window, image = img).pack()
window.mainloop()
For Python 3, replace import Tkinter as tk
with import tkinter as tk
.
Instances of classes are stored on the managed heap. All variables 'containing' an instance are simply a reference to the instance on the heap. Passing an object to a method results in a copy of the reference being passed, not the object itself.
Structures (technically, value types) are stored wherever they are used, much like a primitive type. The contents may be copied by the runtime at any time and without invoking a customised copy-constructor. Passing a value type to a method involves copying the entire value, again without invoking any customisable code.
The distinction is made better by the C++/CLI names: "ref class" is a class as described first, "value class" is a class as described second. The keywords "class" and "struct" as used by C# are simply something that must be learned.
The accepted answer is good and fast:
i.ToString("00")
or
i.ToString("000")
If you need more complexity, String.Format is worth a try:
var str1 = "";
var str2 = "";
for (int i = 1; i < 100; i++)
{
str1 = String.Format("{0:00}", i);
str2 = String.Format("{0:000}", i);
}
For the i = 10
case:
str1: "10"
str2: "010"
I use this, for example, to clear the text on particular Label Controls on my form by name:
private void EmptyLabelArray()
{
var fmt = "Label_Row{0:00}_Col{0:00}";
for (var rowIndex = 0; rowIndex < 100; rowIndex++)
{
for (var colIndex = 0; colIndex < 100; colIndex++)
{
var lblName = String.Format(fmt, rowIndex, colIndex);
foreach (var ctrl in this.Controls)
{
var lbl = ctrl as Label;
if ((lbl != null) && (lbl.Name == lblName))
{
lbl.Text = null;
}
}
}
}
}
No, anonymous types cannot implement an interface. From the C# programming guide:
Anonymous types are class types that consist of one or more public read-only properties. No other kinds of class members such as methods or events are allowed. An anonymous type cannot be cast to any interface or type except for object.
<?php
ob_start();
var_dump($_POST['C']);
$result = ob_get_clean();
?>
if you want to capture the result in a variable
I have created main.css file and included all css files in it.
We can include only one main.css file
@import url('style.css');
@import url('platforms.css');
Beware of timestamp changing when you do a UPDATE statement on a table. If you have a table with columns 'Name' (varchar), 'Age' (int), and 'Date_Added' (timestamp) and you run the following DML statement
UPDATE table
SET age = 30
then every single value in your 'Date_Added' column would be changed to the current timestamp.
There are several issues:
elif option == 2:
and the subsequent elif
-else
should be aligned with the second if option == 1
, not with the for
.
The for x in range(x, 1, 1):
is missing a body.
Since "option 1 (count)" requires a second input, you need to call input()
for the second time. However, for sanity's sake I urge you to store the result in a second variable rather than repurposing option
.
The comparison in the first line of your code is probably meant to be an assignment.
You'll discover more issues once you're able to run your code (you'll need a couple more input()
calls, one of the range()
calls will need attention etc).
Lastly, please don't use the same variable as the loop variable and as part of the initial/terminal condition, as in:
for x in range(1, x, 1):
print x
It may work, but it is very confusing to read. Give the loop variable a different name:
for i in range(1, x, 1):
print i
Would that work for you?
public class Main {
public static void main(String[] args) {
Random r = new Random(System.currentTimeMillis());
System.out.println(r.nextInt(100000) * 0.000001);
}
}
result e.g. 0.019007
import keyboard
while True:
print('please say yes')
if keyboard.is_pressed('y'):
break
print('i got u :) ')
print('i was trying to write you are a idiot ')
print(' :( ')
for enter use 'ENTER'
I have found it!
You can catch the close event using the following code:
$('div#popup_content').on('dialogclose', function(event) {
alert('closed');
});
Obviously I can replace the alert with whatever I need to do.
Edit: As of Jquery 1.7, the bind() has become on()
If your need to redirect to an action outside the controller this will work.
return RedirectToAction("ACTION", "CONTROLLER", new { id = 99 });
Insert an XML comment. ;-)
/// <summary>
/// Describe your member here.
/// </summary>
public string Something
{
get;
set;
}
This may appear like a joke at the first glance, but it may actually be useful. For me it turned out to be helpful to think about what methods do even for private methods (unless really trivial, of course).
Probably the easiest way to explore your ElasticSearch cluster is to use elasticsearch-head.
You can install it by doing:
cd elasticsearch/
./bin/plugin -install mobz/elasticsearch-head
Then (assuming ElasticSearch is already running on your local machine), open a browser window to:
http://localhost:9200/_plugin/head/
Alternatively, you can just use curl
from the command line, eg:
Check the mapping for an index:
curl -XGET 'http://127.0.0.1:9200/my_index/_mapping?pretty=1'
Get some sample docs:
curl -XGET 'http://127.0.0.1:9200/my_index/_search?pretty=1'
See the actual terms stored in a particular field (ie how that field has been analyzed):
curl -XGET 'http://127.0.0.1:9200/my_index/_search?pretty=1' -d '
{
"facets" : {
"my_terms" : {
"terms" : {
"size" : 50,
"field" : "foo"
}
}
}
}
More available here: http://www.elasticsearch.org/guide
By far the easiest way of writing curl
-style commands for Elasticsearch is the Sense plugin in Marvel.
It comes with source highlighting, pretty indenting and autocomplete.
Note: Sense was originally a standalone chrome plugin but is now part of the Marvel project.
Since bit wise operations work on bits that are either 0 or 1, each bit represents a power of 2, so if I have the bits
1010
that value is 10.
Each bit is a power of two, so if we shift the bits to the right, we divide by 2
1010 --> 0101
0101 is 5
so, in general if you want to divide by some power of 2, you need to shift right by the exponent you raise two to, to get that value
so for instance, to divide by 16, you would shift by 4, as 2^^4 = 16.
I frequently use this pattern when building private inner classes to simplify my code, but I would not recommend exposing such objects in a public API. In general, the more frequently you can make objects in your public API immutable the better, and it is not possible to construct your 'struct-like' object in an immutable fashion.
As an aside, even if I were writing this object as a private inner class I would still provide a constructor to simplify the code to initialize the object. Having to have 3 lines of code to get a usable object when one will do is just messy.
if string.startswith('"'):
string = string[1:]
if string.endswith('"'):
string = string[:-1]
First confusion on my side was about where exactly to set SSH Keys in BitBucket.
I am new to BitBucket and I was setting a Deployment Key which gives read-access only.
So make sure you are setting your rsa pub key
in your BitBucket Account Settings.
Click your BitBucket avatar and select Bitbucket Settings(Manage account). There you'll be able to set SSH Keys.
I simply deleted the Deployment Key, I don't need any for now. And it worked
Even more meaningful :
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
// ...
verify(dependency, never()).someMethod();
The documentation of this feature is there §4 "Verifying exact number of invocations / at least x / never", and the never
javadoc is here.
A little late for the party, here's how I do it
./shutdown.sh
/work/Catalina/...
./startup.sh
/webapps
and start it.#Server Connection to MySQL:
import MySQLdb
conn = MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="engy1")
x = conn.cursor()
try:
x.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
conn.commit()
except:
conn.rollback()
conn.close()
edit working for me:
>>> import MySQLdb
>>> #connect to db
... db = MySQLdb.connect("localhost","root","password","testdb" )
>>>
>>> #setup cursor
... cursor = db.cursor()
>>>
>>> #create anooog1 table
... cursor.execute("DROP TABLE IF EXISTS anooog1")
__main__:2: Warning: Unknown table 'anooog1'
0L
>>>
>>> sql = """CREATE TABLE anooog1 (
... COL1 INT,
... COL2 INT )"""
>>> cursor.execute(sql)
0L
>>>
>>> #insert to table
... try:
... cursor.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
... db.commit()
... except:
... db.rollback()
...
1L
>>> #show table
... cursor.execute("""SELECT * FROM anooog1;""")
1L
>>> print cursor.fetchall()
((188L, 90L),)
>>>
>>> db.close()
table in mysql;
mysql> use testdb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> SELECT * FROM anooog1;
+------+------+
| COL1 | COL2 |
+------+------+
| 188 | 90 |
+------+------+
1 row in set (0.00 sec)
mysql>
Use the library EventBus to pass event that could contain your variable back and forth. It's a good solution because it keeps your activities and fragments loosely coupled
All the answers provide sufficient details to the question. However, let me add something more.
Why are we using these Interfaces:
Which interface does what:
When to use which interface:
According to http://jtuts.com/2014/08/26/difference-between-crudrepository-and-jparepository-in-spring-data-jpa/
Generally the best idea is to use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.
The JpaRepository should be avoided if possible, because it ties you repositories to the JPA persistence technology, and in most cases you probably wouldn’t even use the extra methods provided by it.
Assuming you're on at least 3.2, there's a built in for this:
int.from_bytes( bytes, byteorder, *, signed=False )
...
The argument bytes must either be a bytes-like object or an iterable producing bytes.
The byteorder argument determines the byte order used to represent the integer. If byteorder is "big", the most significant byte is at the beginning of the byte array. If byteorder is "little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value.
The signed argument indicates whether two’s complement is used to represent the integer.
## Examples:
int.from_bytes(b'\x00\x01', "big") # 1
int.from_bytes(b'\x00\x01', "little") # 256
int.from_bytes(b'\x00\x10', byteorder='little') # 4096
int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) #-1024
For thoses running Linux with apache2 you need to install php-mysql
apt-get install php-mysql
or if you are running ubuntu 16.04 or higher just running the following command will be enought, no need to edit your php.ini file
apt-get install php7.2-mysql
If you are running ubuntu 15.10 or below:
Edit your php.ini file, it's located at /etc/php/[version]/apache2/php.ini
and search for pdo_mysql
you might found something like this
;extension=pdo_mysql.so
Change it to this
extension=pdo_mysql.so
Save the file and restart apache
service apache2 restart
Check that it's available in your phpinfo()
In rails 6, simply add this to your controller:
class UsersController < ApplicationController
include UsersHelper
# Your actions
end
Now the user_helpers.rb will be available in the controller.
Just for giggles, give this XAML a whirl. It isn't perfect as it is not an 'alignment' but it allows you to adjust text alignment within a paragraph.
<TextBlock>
<TextBlock BaselineOffset="30">One</TextBlock>
<TextBlock BaselineOffset="20">Two</TextBlock>
<Run>Three</Run>
<Run BaselineAlignment="Subscript">Four</Run>
</TextBlock>
Color.parseColor("#rrggbb")
instead of #rrggbb
you should be using hex values 0 to F for rr, gg and bb:
e.g. Color.parseColor("#000000")
or Color.parseColor("#FFFFFF")
From documentation:
public static int parseColor (String colorString):
Parse the color string, and return the corresponding color-int. If the string cannot be parsed, throws an IllegalArgumentException exception. Supported formats are: #RRGGBB #AARRGGBB 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey', 'aqua', 'fuschia', 'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal'
So I believe that if you are using #rrggbb
you are getting IllegalArgumentException in your logcat
Alternative:
Color mColor = new Color();
mColor.red(redvalue);
mColor.green(greenvalue);
mColor.blue(bluevalue);
li.setBackgroundColor(mColor);
Use a span and a javascript onclick instead. Some browsers "jump" if you have a link and "#" href.
Git is warning that you might lose history by deleting this branch. Even though it would not actually delete any commits right away, some or all of the commits on the branch would become unreachable if they are not part of some other branch as well.
For the branch experiment
to be “fully merged” into another branch, its tip commit must be an ancestor of the other branch’s tip, making the commits in experiment
a subset of the other branch. This makes it safe to delete experiment
, since all its commits will remain part of the repository history via the other branch. It must be “fully” merged, because it may have been merged several times already, but now have commits added since the last merge that are not contained in the other branch.
Git doesn’t check every other branch in the repository, though; just two:
The “upstream branch” for experiment
, as in your case, is probably origin/experiment
. If experiment
is fully merged in the current branch, then Git deletes it with no complaint. If it is not, but it is fully merged in its upstream branch, then Git proceeds with a warning seeming like:
warning: deleting branch 'experiment' that has been merged
to 'refs/remotes/origin/experiment', but not yet merged to
HEAD.
Deleted branch experiment (was xxxxxxxx).
Where xxxxxxxx
indicates a commit id. Being fully merged in its upstream indicates that the commits in experiment
have been pushed to the origin repository, so that even if you lose them here, they may at least be saved elsewhere.
Since Git doesn’t check other branches, it may be safe to delete a branch because you know it is fully merged into another one; you can do this with the -D
option as indicated, or switch to that branch first and let Git confirm the fully merged status for you.
A vertical tab was the opposite of a line feed i.e. it went upwards by one line. It had nothing to do with tab positions. If you want to prove this, try it on an RS232 terminal.
None of these was quite what i wanted:
public static T GetFieldValueOrDefault<T>(this SqlDataReader reader, string name)
{
int index = reader.GetOrdinal(name);
T value = reader.IsDBNull(index) ? default(T) : reader.GetFieldValue<T>(index);
return value;
}
This query will use index if you have it for signup_date
field
SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d')
FROM users
WHERE signup_date >= CURDATE() && signup_date < (CURDATE() + INTERVAL 1 DAY)
The target container should have the white-space:pre
style.
Try it below.
<script>_x000D_
function copycontent(){_x000D_
var content = document.getElementById('ta').value;_x000D_
document.getElementById('target').innerText = content;_x000D_
}_x000D_
</script>_x000D_
<textarea id='ta' rows='3'>_x000D_
line 1_x000D_
line 2_x000D_
line 3_x000D_
</textarea>_x000D_
<button id='btn' onclick='copycontent();'>_x000D_
Copy_x000D_
</button>_x000D_
<p id='target' style='white-space:pre'>_x000D_
_x000D_
</p>
_x000D_
The answer given by deepak goel does not work for me because I always get null from entry.getName()
;
What I do is to set a Tag to the fragment this way:
ft.add(R.id.fragment_container, fragmentIn, FRAGMENT_TAG);
Where ft is my fragment transaction and FRAGMENT_TAG
is the tag. Then I use this code to get the fragment:
Fragment prev_fragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG);
@Mark Hurd, thanks for pointing out the error.
this will work (if you are using Postgresql, Sql Server 2008):
create table products
(
product_id int not null
);
insert into products values(1),(2),(10),(100);
SELECT
CASE
WHEN EXISTS(
SELECT 1
FROM (values(1),(10),(100)) as x(id)
WHERE x.id NOT IN (select product_id from products))
THEN 0 --'NOT ALL'
ELSE 1 -- 'ALL'
END
If you are using MySQL, make a temporary memory table(then populate 1,10,100 there):
create table product_memory(product_id int) engine=MEMORY;
insert into product_memory values(1),(10),(100);
SELECT
CASE
WHEN EXISTS(
SELECT 1
FROM product_memory
WHERE product_memory.id NOT IN (select product_id from products))
THEN 0 -- 'NOT ALL'
ELSE 1 -- 'ALL'
END
On your C# code:
bool isAllExist = (int)(new SqlCommand(queryHere).ExecuteScalar()) == 1;
[EDIT]
How can I write a query that will return a row if all the product id's exist and no row if one or more product id's does not exist?
Regarding, returning a row(singular) if all rows exists, and no row to be returned if one or more product id does not exists:
MySql:
SELECT 1
WHERE
NOT EXISTS(
SELECT 1
FROM product_memory
WHERE product_memory.id NOT IN (select product_id from products) )
Posgresql, Sql Server 2008:
SELECT 1
WHERE
NOT EXISTS(
SELECT 1
FROM (values(1),(10),(100)) as x(id)
WHERE x.id NOT IN (select product_id from products) )
Then on your C# code:
var da = new SqlDataAdapter(queryhere, connectionhere);
var dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
return true;
else
return false;
Or just make the condition shorter:
return dt.Rows.Count > 0;
Store your results in variables, and use them in your HTML and add the necessary styling.
$usercity = $ip['cityName'];
$usercountry = $ip['countryName'];
And in the HTML, you could do:
<div id="userdetails">
<p> User's IP: <?php echo $usercity; ?> </p>
<p> Country: <?php echo $usercountry; ?> </p>
</div>
Now, you can simply add the styles for country
class in your CSS, like so:
#userdetails {
/* styles go here */
}
Alternatively, you could also use this in your HTML:
<p style="font-size:15px; font-color: green;"><?php echo $userip; ?> </p>
<p style="font-size:15px; font-color: green;"><?php echo $usercountry; ?> </p>
Hope this helps!
If your YAML file looks like this:
# tree format
treeroot:
branch1:
name: Node 1
branch1-1:
name: Node 1-1
branch2:
name: Node 2
branch2-1:
name: Node 2-1
And you've installed PyYAML
like this:
pip install PyYAML
And the Python code looks like this:
import yaml
with open('tree.yaml') as f:
# use safe_load instead load
dataMap = yaml.safe_load(f)
The variable dataMap
now contains a dictionary with the tree data. If you print dataMap
using PrettyPrint, you will get something like:
{
'treeroot': {
'branch1': {
'branch1-1': {
'name': 'Node 1-1'
},
'name': 'Node 1'
},
'branch2': {
'branch2-1': {
'name': 'Node 2-1'
},
'name': 'Node 2'
}
}
}
So, now we have seen how to get data into our Python program. Saving data is just as easy:
with open('newtree.yaml', "w") as f:
yaml.dump(dataMap, f)
You have a dictionary, and now you have to convert it to a Python object:
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
Then you can use:
>>> args = your YAML dictionary
>>> s = Struct(**args)
>>> s
<__main__.Struct instance at 0x01D6A738>
>>> s...
and follow "Convert Python dict to object".
For more information you can look at pyyaml.org and this.
You could use JNA. Unfortunately there is no common JNA API to get the current process ID yet, but each platform is pretty simple:
Make sure you have jna-platform.jar
then:
int pid = Kernel32.INSTANCE.GetCurrentProcessId();
Declare:
private interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary("c", CLibrary.class);
int getpid ();
}
Then:
int pid = CLibrary.INSTANCE.getpid();
Under Java 9 the new process API can be used to get the current process ID. First you grab a handle to the current process, then query the PID:
long pid = ProcessHandle.current().pid();
Dim FindRow as Range
Set FindRow = Range("A:A").Find(What:="ProjTemp", _' This is what you are searching for
After:=.Cells(.Cells.Count), _ ' This is saying after the last cell in the_
' column i.e. the first
LookIn:=xlValues, _ ' this says look in the values of the cell not the formula
LookAt:=xlWhole, _ ' This look s for EXACT ENTIRE MATCH
SearchOrder:=xlByRows, _ 'This look down the column row by row
'Larger Ranges with multiple columns can be set to
' look column by column then down
MatchCase:=False) ' this says that the search is not case sensitive
If Not FindRow Is Nothing Then ' if findrow is something (Prevents Errors)
FirstRow = FindRow.Row ' set FirstRow to the first time a match is found
End If
If you would like to get addition ones you can use:
Do Until FindRow Is Nothing
Set FindRow = Range("A:A").FindNext(after:=FindRow)
If FindRow.row = FirstRow Then
Exit Do
Else ' Do what you'd like with the additional rows here.
End If
Loop
It is not possible to force a capslock only via the XML. Also 3rd party libraries do not help. You could do a toUpper()
on the text on the receiving side, but there's no way to prevent it on the keyboard side
You can use XML to set the keyboard to caps lock.
Java
You can set the input_type
to TYPE_CLASS_TEXT| TYPE_TEXT_FLAG_CAP_CHARACTERS
. The keyboard
should honor that.
Kotlin
android:inputType="textCapCharacters"
It's my reload. Because of some browser very weird. location.reload
can't reload.
methods:{
reload: function(){
this.isRouterAlive = false
setTimeout(()=>{
this.isRouterAlive = true
},0)
}
}
<router-view v-if="isRouterAlive"/>
Setting project's SDK in IntelliJ (File > Project Structure > Project:Project SDK) worked for me
As a commenter below pointed correctly, this is not a general solution for services, only for threads launched from your activity (a service can be such a thread, but not all of those are). On the complicated topic of service-activity communication please read the whole Services section of the official doc - it is complex, so it would pay to understand the basics: http://developer.android.com/guide/components/services.html#Notifications
The method below may work in the simplest cases:
If I understand you correctly you need some code to be executed in the GUI thread of the application (cannot think about anything else called "main" thread).
For this there is a method on Activity
:
someActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
//Your code to run in GUI thread here
}//public void run() {
});
Hope this is what you are looking for.
Have a wrapper around your program that does the following.
import sys
req_version = (2,5)
cur_version = sys.version_info
if cur_version >= req_version:
import myApp
myApp.run()
else:
print "Your Python interpreter is too old. Please consider upgrading."
You can also consider using sys.version()
, if you plan to encounter people who are using pre-2.0 Python interpreters, but then you have some regular expressions to do.
And there might be more elegant ways to do this.
The problem is that your PATH does not include the location of the node executable.
You can likely run node as "/usr/local/bin/node
".
You can add that location to your path by running the following command to add a single line to your bashrc file:
echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc
nginx is useful for forwarding HTTP on many platforms including Windows. It's easy to setup and extend with more advanced configuration. A basic configuration could look something like this:
events {}
http {
server {
listen 192.168.1.111:4422;
location / {
proxy_pass http://192.168.2.33:80/;
}
}
}
TLDR; technically space sorts before exclamation mar, and can be used by preceding it with ' or - (which will be ignored in sorting), but exclamation mark follows right after space, and is easier to use.
On windows 7 at least, a minus sign (-) and (') seem to be ignored in a name except for one quirk: in a name that is otherwise identical, the ' will be sorted before -, for example: (a'a) will sort above (a-a)
Empty string will sort above everything else, which means for example aa will sort above aaa because the 'empty string' after two a letters will sort before the third 'a'.
This also means that aa will be sorted above a'a because the 'empty string' between two a letters will sort above the ' mark.
What follows then is, ' alone will sort first, because technically it's an empty string. However adding for example letters behind it will sort the name as if the ' didn't exist.
Since the first 'unignored' character (as far as I know) is space, in case you want to sort 'real names' above others, the best way to go would be ' followed by space, and then the name you want to actually use. For example: (' first)
You can of course top that by using more than one space in the strong, such as (' firster) and (' firstest) with two and three blanks before the f.
While minus sign sorts below ' in otherwise similar name, there's no other difference in sorting (that I know of), and I find minus sign visually clearer, so if I want to put something on top of list, I'd use minus followed by space, then the 'actual name', for example: (- first file -)
If you are worried about using space on the filename, then exclamation mark (!) is the next best thing - and since it can appear as first character on a string, it's easier to use.
Should anybody land with the same silly problem I had, make sure your component has the 'data' property spelled correctly. (eg. data, and not date)
<template>
<span>{{name}}</span>
</template>
<script>
export default {
name: "MyComponent",
data() {
return {
name: ""
};
}
</script>
<session-config>
<session-timeout>-1</session-timeout>
</session-config>
In the above code "60" stands for the minutes.
The session will expired after 60 minutes.
So if you want to more time. For Example -1
that is described your session never expires.
For ubuntu users, run this command in your terminal [Tested in UBUNTU 16.04]
sudo apt-get -y install libcurl4-openssl-dev
post this install libraries the way you usually do in R using
install.packages("package name")