You can use this:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// Actions to do after 10 seconds
}
}, 10000);
For Stop the Handler, You can try this:
handler.removeCallbacksAndMessages(null);
It looks to me as though the basic problem is that you have one wait()
call rather than a loop that waits until there are no more children. You also only wait if the last fork()
is successful rather than if at least one fork()
is successful.
You should only use _exit()
if you don't want normal cleanup operations - such as flushing open file streams including stdout
. There are occasions to use _exit()
; this is not one of them. (In this example, you could also, of course, simply have the children return instead of calling exit()
directly because returning from main()
is equivalent to exiting with the returned status. However, most often you would be doing the forking and so on in a function other than main()
, and then exit()
is often appropriate.)
Hacked, simplified version of your code that gives the diagnostics I'd want. Note that your for
loop skipped the first element of the array (mine doesn't).
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(void)
{
pid_t child_pid, wpid;
int status = 0;
int i;
int a[3] = {1, 2, 1};
printf("parent_pid = %d\n", getpid());
for (i = 0; i < 3; i++)
{
printf("i = %d\n", i);
if ((child_pid = fork()) == 0)
{
printf("In child process (pid = %d)\n", getpid());
if (a[i] < 2)
{
printf("Should be accept\n");
exit(1);
}
else
{
printf("Should be reject\n");
exit(0);
}
/*NOTREACHED*/
}
}
while ((wpid = wait(&status)) > 0)
{
printf("Exit status of %d was %d (%s)\n", (int)wpid, status,
(status > 0) ? "accept" : "reject");
}
return 0;
}
Example output (MacOS X 10.6.3):
parent_pid = 15820
i = 0
i = 1
In child process (pid = 15821)
Should be accept
i = 2
In child process (pid = 15822)
Should be reject
In child process (pid = 15823)
Should be accept
Exit status of 15823 was 256 (accept)
Exit status of 15822 was 0 (reject)
Exit status of 15821 was 256 (accept)
if you're using a MacBook or UNIX based system, use this:
function wait(time)
if tonumber(time) ~= nil then
os.execute("Sleep "..tonumber(time))
else
os.execute("Sleep "..tonumber("0.1"))
end
wait()
Here's a solution using the new async/await syntax.
async function testWait() {
alert('going to wait for 5 second');
await wait(5000);
alert('finally wait is over');
}
function wait(time) {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, time);
});
}
Note: You can call function wait only in async functions
I've had a go at this and combined all the best parts from the other examples here. This script will execute the checkpids
function when any background process exits, and output the exit status without resorting to polling.
#!/bin/bash
set -o monitor
sleep 2 &
sleep 4 && exit 1 &
sleep 6 &
pids=`jobs -p`
checkpids() {
for pid in $pids; do
if kill -0 $pid 2>/dev/null; then
echo $pid is still alive.
elif wait $pid; then
echo $pid exited with zero exit status.
else
echo $pid exited with non-zero exit status.
fi
done
echo
}
trap checkpids CHLD
wait
There is no builtin feature to wait for any process to finish.
You could send kill -0
to any PID found, so you don't get puzzled by zombies and stuff that will still be visible in ps
(while still retrieving the PID list using ps
).
Not a queue example, but extremely simple :)
class MyHouse {
private boolean pizzaArrived = false;
public void eatPizza(){
synchronized(this){
while(!pizzaArrived){
wait();
}
}
System.out.println("yumyum..");
}
public void pizzaGuy(){
synchronized(this){
this.pizzaArrived = true;
notifyAll();
}
}
}
Some important points:
1) NEVER do
if(!pizzaArrived){
wait();
}
Always use while(condition), because
while(!pizzaExists){ wait(); }
.2) You must hold the lock (synchronized) before invoking wait/nofity. Threads also have to acquire lock before waking.
3) Try to avoid acquiring any lock within your synchronized block and strive to not invoke alien methods (methods you don't know for sure what they are doing). If you have to, make sure to take measures to avoid deadlocks.
4) Be careful with notify(). Stick with notifyAll() until you know what you are doing.
5)Last, but not least, read Java Concurrency in Practice!
Ok, yup you use the timeout
command to sleep. But to do the whole process silently, it's not possible with cmd/batch. One of the ways is to create a VBScript that will run the Batch File without opening/showing any window.
And here is the script:
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "PATH OF BATCH FILE WITH QUOTATION MARKS" & Chr(34), 0
Set WshShell = Nothing
Copy and paste the above code on notepad and save it as Anyname.**vbs ** An example of the *"PATH OF BATCH FILE WITH QUOTATION MARKS" * might be: "C:\ExampleFolder\MyBatchFile.bat"
I just had a look at the source - Protractor is waiting for Angular only in a few cases (like when element.all
is invoked, or setting / getting location).
So Protractor won't wait for Angular to stabilise after every command.
Also, it looks like sometimes in my tests I had a race between Angular digest cycle and click event, so sometimes I have to do:
elm.click();
browser.driver.sleep(1000);
browser.waitForAngular();
using sleep to wait for execution to enter AngularJS context (triggered by click
event).
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);
These methods works on the locks and locks are associated with Object and not Threads. Hence, it is in Object class.
The methods wait(), notify() and notifyAll() are not only just methods, these are synchronization utility and used in communication mechanism among threads in Java.
For more detailed explanation, please visit : http://parameshk.blogspot.in/2013/11/why-wait-notify-and-notifyall-methods.html
Your code only creates a time without a date. If your assumption is correct that when it runs the application.wait the time actually already reached that time it will wait for 24 hours exactly. I also worry a bit about calling now() multiple times (could be different?) I would change the code to
application.wait DateAdd("s", 1, Now)
Thread wait on the monitoring object (object used by synchronization block), There can be n number of monitoring object in whole journey of a single thread. If Thread wait outside the synchronization block then there is no monitoring object and also other thread notify to access for the monitoring object, so how would the thread outside the synchronization block would know that it has been notified. This is also one of the reason that wait(), notify() and notifyAll() are in object class rather than thread class.
Basically the monitoring object is common resource here for all the threads, and monitoring objects can only be available in synchronization block.
class A {
int a = 0;
//something......
public void add() {
synchronization(this) {
//this is your monitoring object and thread has to wait to gain lock on **this**
}
}
You shouldn't edit it, you should completely scrap it.
Any attempt to make execution stop for a certain amount of time will lock up the browser and switch it to a Not Responding state. The only thing you can do is use setTimeout
correctly.
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.
we can use following method QT_Delay
:
QTimer::singleShot(2000,this,SLOT(print_lcd()));
This will wait for 2 seconds before calling print_lcd()
.
Selenium does it for you. Or at least it tries its best. Sometimes it falls short, and you must help it a little bit. The usual solution is Implicit Wait
which solves most of the problems.
If you really know what you're doing, and why you're doing it, you could try to write a generic method which would check whether the page is completely loaded. However, it can't be done for every web and for every situation.
Related question: Selenium WebDriver : Wait for complex page with JavaScript(JS) to load, see my answer there.
Shorter version: You'll never be sure.
The "normal" load is easy - document.readyState
. This one is implemented by Selenium, of course. The problematic thing are asynchronous requests, AJAX, because you can never tell whether it's done for good or not. Most of today's webpages have scripts that run forever and poll the server all the time.
The various things you could do are under the link above. Or, like 95% of other people, use Implicit Wait
implicity and Explicit Wait
+ ExpectedConditions
where needed.
E.g. after a click, some element on the page should become visible and you need to wait for it:
WebDriverWait wait = new WebDriverWait(driver, 10); // you can reuse this one
WebElement elem = driver.findElement(By.id("myInvisibleElement"));
elem.click();
wait.until(ExpectedConditions.visibilityOf(elem));
wait() works fine for me. The subprocesses p1, p2 and p3 are executed at the same. Therefore, all processes are done after 3 seconds.
import subprocess
processes = []
p1 = subprocess.Popen("sleep 3", stdout=subprocess.PIPE, shell=True)
p2 = subprocess.Popen("sleep 3", stdout=subprocess.PIPE, shell=True)
p3 = subprocess.Popen("sleep 3", stdout=subprocess.PIPE, shell=True)
processes.append(p1)
processes.append(p2)
processes.append(p3)
for p in processes:
if p.wait() != 0:
print("There was an error")
print("all processed finished")
I imagine that you're calling your download in a background thread such as provided by a SwingWorker. If so, then simply call your next code sequentially in the same SwingWorker's doInBackground method.
A clean example that answers the Title
string output = "Error";
Task task = Task.Factory.StartNew(() =>
{
System.Threading.Thread.Sleep(2000);
output = "Complete";
});
task.Wait();
Console.WriteLine(output);
You can do it with the Object "ThreadGroup" and its parameter activeCount:
Only javascript It will work without jQuery
<!DOCTYPE html>
<html>
<head>
<script>
function sleep(miliseconds) {
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()) {
}
}
function hello() {
sleep(5000);
alert('Hello');
}
function hi() {
sleep(10000);
alert('Hi');
}
</script>
</head>
<body>
<a href="#" onclick="hello();">Say me hello after 5 seconds </a>
<br>
<a href="#" onclick="hi();">Say me hi after 10 seconds </a>
</body>
</html>
Use this in your main thread: while(!executor.isTerminated()); Put this line of code after starting all the threads from executor service. This will only start the main thread after all the threads started by executors are finished. Make sure to call executor.shutdown(); before the above loop.
Imports VB = Microsoft.VisualBasic
Public Sub wait(ByVal seconds As Single)
Static start As Single
start = VB.Timer()
Do While VB.Timer() < start + seconds
System.Windows.Forms.Application.DoEvents()
Loop
End Sub
%20+ high cpu usage + no lag
Private Sub wait(ByVal seconds As Integer)
For i As Integer = 0 To seconds * 100
System.Threading.Thread.Sleep(10)
Application.DoEvents()
Next
End Sub
%0.1 cpu usage + high lag
for people new to this you can also use a callback for example:
In your service:
.factory('DataHandler',function ($http){
var GetRandomArtists = function(data, callback){
$http.post(URL, data).success(function (response) {
callback(response);
});
}
})
In your controller:
DataHandler.GetRandomArtists(3, function(response){
$scope.data.random_artists = response;
});
I prefer to this approach because you can return the promise and use .then(successFunction, failFunction); anywhere you need to.
var promise = $.ajax({
type: 'GET',
dataType: 'json',
url: url,
timeout: 5000
}).then(function( data, textStatus, jqXHR ) {
alert('request successful');
}, function( jqXHR, textStatus, errorThrown ) {
alert('request failed');
});
//also access the success and fail using variable
promise.then(successFunction, failFunction);
There are many ways to wait in Unity. It is really simple but I think it's worth covering most ways to do these:
1.With a coroutine and WaitForSeconds
.
The is by far the simplest way. Put all the code that you need to wait for some time in a coroutine function then you can wait with WaitForSeconds
. Note that in coroutine function, you call the function with StartCoroutine(yourFunction)
.
Example below will rotate 90 deg, wait for 4 seconds, rotate 40 deg and wait for 2 seconds, and then finally rotate rotate 20 deg.
void Start()
{
StartCoroutine(waiter());
}
IEnumerator waiter()
{
//Rotate 90 deg
transform.Rotate(new Vector3(90, 0, 0), Space.World);
//Wait for 4 seconds
yield return new WaitForSeconds(4);
//Rotate 40 deg
transform.Rotate(new Vector3(40, 0, 0), Space.World);
//Wait for 2 seconds
yield return new WaitForSeconds(2);
//Rotate 20 deg
transform.Rotate(new Vector3(20, 0, 0), Space.World);
}
2.With a coroutine and WaitForSecondsRealtime
.
The only difference between WaitForSeconds
and WaitForSecondsRealtime
is that WaitForSecondsRealtime
is using unscaled time to wait which means that when pausing a game with Time.timeScale
, the WaitForSecondsRealtime
function would not be affected but WaitForSeconds
would.
void Start()
{
StartCoroutine(waiter());
}
IEnumerator waiter()
{
//Rotate 90 deg
transform.Rotate(new Vector3(90, 0, 0), Space.World);
//Wait for 4 seconds
yield return new WaitForSecondsRealtime(4);
//Rotate 40 deg
transform.Rotate(new Vector3(40, 0, 0), Space.World);
//Wait for 2 seconds
yield return new WaitForSecondsRealtime(2);
//Rotate 20 deg
transform.Rotate(new Vector3(20, 0, 0), Space.World);
}
Wait and still be able to see how long you have waited:
3.With a coroutine and incrementing a variable every frame with Time.deltaTime
.
A good example of this is when you need the timer to display on the screen how much time it has waited. Basically like a timer.
It's also good when you want to interrupt the wait/sleep with a boolean
variable when it is true. This is where yield break;
can be used.
bool quit = false;
void Start()
{
StartCoroutine(waiter());
}
IEnumerator waiter()
{
float counter = 0;
//Rotate 90 deg
transform.Rotate(new Vector3(90, 0, 0), Space.World);
//Wait for 4 seconds
float waitTime = 4;
while (counter < waitTime)
{
//Increment Timer until counter >= waitTime
counter += Time.deltaTime;
Debug.Log("We have waited for: " + counter + " seconds");
//Wait for a frame so that Unity doesn't freeze
//Check if we want to quit this function
if (quit)
{
//Quit function
yield break;
}
yield return null;
}
//Rotate 40 deg
transform.Rotate(new Vector3(40, 0, 0), Space.World);
//Wait for 2 seconds
waitTime = 2;
//Reset counter
counter = 0;
while (counter < waitTime)
{
//Increment Timer until counter >= waitTime
counter += Time.deltaTime;
Debug.Log("We have waited for: " + counter + " seconds");
//Check if we want to quit this function
if (quit)
{
//Quit function
yield break;
}
//Wait for a frame so that Unity doesn't freeze
yield return null;
}
//Rotate 20 deg
transform.Rotate(new Vector3(20, 0, 0), Space.World);
}
You can still simplify this by moving the while
loop into another coroutine function and yielding it and also still be able to see it counting and even interrupt the counter.
bool quit = false;
void Start()
{
StartCoroutine(waiter());
}
IEnumerator waiter()
{
//Rotate 90 deg
transform.Rotate(new Vector3(90, 0, 0), Space.World);
//Wait for 4 seconds
float waitTime = 4;
yield return wait(waitTime);
//Rotate 40 deg
transform.Rotate(new Vector3(40, 0, 0), Space.World);
//Wait for 2 seconds
waitTime = 2;
yield return wait(waitTime);
//Rotate 20 deg
transform.Rotate(new Vector3(20, 0, 0), Space.World);
}
IEnumerator wait(float waitTime)
{
float counter = 0;
while (counter < waitTime)
{
//Increment Timer until counter >= waitTime
counter += Time.deltaTime;
Debug.Log("We have waited for: " + counter + " seconds");
if (quit)
{
//Quit function
yield break;
}
//Wait for a frame so that Unity doesn't freeze
yield return null;
}
}
Wait/Sleep until variable changes or equals to another value:
4.With a coroutine and the WaitUntil
function:
Wait until a condition becomes true
. An example is a function that waits for player's score to be 100
then loads the next level.
float playerScore = 0;
int nextScene = 0;
void Start()
{
StartCoroutine(sceneLoader());
}
IEnumerator sceneLoader()
{
Debug.Log("Waiting for Player score to be >=100 ");
yield return new WaitUntil(() => playerScore >= 10);
Debug.Log("Player score is >=100. Loading next Leve");
//Increment and Load next scene
nextScene++;
SceneManager.LoadScene(nextScene);
}
5.With a coroutine and the WaitWhile
function.
Wait while a condition is true
. An example is when you want to exit app when the escape key is pressed.
void Start()
{
StartCoroutine(inputWaiter());
}
IEnumerator inputWaiter()
{
Debug.Log("Waiting for the Exit button to be pressed");
yield return new WaitWhile(() => !Input.GetKeyDown(KeyCode.Escape));
Debug.Log("Exit button has been pressed. Leaving Application");
//Exit program
Quit();
}
void Quit()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
6.With the Invoke
function:
You can call tell Unity to call function in the future. When you call the Invoke
function, you can pass in the time to wait before calling that function to its second parameter. The example below will call the feedDog()
function after 5
seconds the Invoke
is called.
void Start()
{
Invoke("feedDog", 5);
Debug.Log("Will feed dog after 5 seconds");
}
void feedDog()
{
Debug.Log("Now feeding Dog");
}
7.With the Update()
function and Time.deltaTime
.
It's just like #3 except that it does not use coroutine. It uses the Update
function.
The problem with this is that it requires so many variables so that it won't run every time but just once when the timer is over after the wait.
float timer = 0;
bool timerReached = false;
void Update()
{
if (!timerReached)
timer += Time.deltaTime;
if (!timerReached && timer > 5)
{
Debug.Log("Done waiting");
feedDog();
//Set to false so that We don't run this again
timerReached = true;
}
}
void feedDog()
{
Debug.Log("Now feeding Dog");
}
There are still other ways to wait in Unity but you should definitely know the ones mentioned above as that makes it easier to make games in Unity. When to use each one depends on the circumstances.
For your particular issue, this is the solution:
IEnumerator showTextFuntion()
{
TextUI.text = "Welcome to Number Wizard!";
yield return new WaitForSeconds(3f);
TextUI.text = ("The highest number you can pick is " + max);
yield return new WaitForSeconds(3f);
TextUI.text = ("The lowest number you can pick is " + min);
}
And to call/start the coroutine function from your start or Update function, you call it with
StartCoroutine (showTextFuntion());
Try this function
public void Wait(int time)
{
Thread thread = new Thread(delegate()
{
System.Threading.Thread.Sleep(time);
});
thread.Start();
while (thread.IsAlive)
Application.DoEvents();
}
Call function
Wait(1000); // Wait for 1000ms = 1s
Have a look at tapestry web-framework. You can download source code there.
The idea is to signalize that page is ready by html attribute of body. You can use this idea ignore complicated sue cases.
<html>
<head>
</head>
<body data-page-initialized="false">
<p>Write you page here</p>
<script>
$(document).ready(function () {
$(document.body).attr('data-page-initialized', 'true');
});
</script>
</body>
</html>
And then create extension of Selenium webdriver (according to tapestry framework)
public static void WaitForPageToLoad(this IWebDriver driver, int timeout = 15000)
{
//wait a bit for the page to start loading
Thread.Sleep(100);
//// In a limited number of cases, a "page" is an container error page or raw HTML content
// that does not include the body element and data-page-initialized element. In those cases,
// there will never be page initialization in the Tapestry sense and we return immediately.
if (!driver.ElementIsDisplayed("/html/body[@data-page-initialized]"))
{
return;
}
Stopwatch stopwatch = Stopwatch.StartNew();
int sleepTime = 20;
while(true)
{
if (driver.ElementIsDisplayed("/html/body[@data-page-initialized='true']"))
{
return;
}
if (stopwatch.ElapsedMilliseconds > 30000)
{
throw new Exception("Page did not finish initializing after 30 seconds.");
}
Thread.Sleep(sleepTime);
sleepTime *= 2; // geometric row of sleep time
}
}
Use extension ElementIsDisplayed written by Alister Scott.
public static bool ElementIsDisplayed(this IWebDriver driver, string xpath)
{
try
{
return driver.FindElement(By.XPath(xpath)).Displayed;
}
catch(NoSuchElementException)
{
return false;
}
}
And finally create test:
driver.Url = this.GetAbsoluteUrl("/Account/Login");
driver.WaitForPageToLoad();
Wait() and sleep() Differences?
Thread.sleep() Once its work completed then only its release the lock to everyone. until its never release the lock to anyone.
Sleep() take the key, its never release the key to anyone, when its work completed then only its release then only take the key waiting stage threads.
Object.wait() When its going to waiting stage, its will be release the key and its waiting for some of the seconds based on the parameter.
For Example:
you are take the coffee in yours right hand, you can take another anyone of the same hand, when will your put down then only take another object same type here. also. this is sleep() you sleep time you didn't any work, you are doing only sleeping.. same here also.
wait(). when you are put down and take another one mean while you are waiting , that's wait
you are play movie or anything in yours system same as player you can't play more than one at a time right, thats its here, when you close and choose another anyone movie or song mean while is called wait
You can use properties:
Object.defineProperty MDN documentation
Example:
function def(varName, onChange) {
var _value;
Object.defineProperty(this, varName, {
get: function() {
return _value;
},
set: function(value) {
if (onChange)
onChange(_value, value);
_value = value;
}
});
return this[varName];
}
def('myVar', function (oldValue, newValue) {
alert('Old value: ' + oldValue + '\nNew value: ' + newValue);
});
myVar = 1; // alert: Old value: undefined | New value: 1
myVar = 2; // alert: Old value: 1 | New value: 2
You can KILL the processid.
mysql> show full processlist;
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| Id | User | Host | db | Command | Time | State | Info |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| 1193777 | TestUser12 | 192.168.1.11:3775 | www | Sleep | 25946 | | NULL |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
mysql> kill 1193777;
But:
Or you configure your mysql-server by setting a shorter timeout on wait_timeout
and interactive_timeout
mysql> show variables like "%timeout%";
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| connect_timeout | 5 |
| delayed_insert_timeout | 300 |
| innodb_lock_wait_timeout | 50 |
| interactive_timeout | 28800 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| slave_net_timeout | 3600 |
| table_lock_wait_timeout | 50 |
| wait_timeout | 28800 |
+--------------------------+-------+
9 rows in set (0.00 sec)
Set with:
set global wait_timeout=3;
set global interactive_timeout=3;
(and also set in your configuration file, for when your server restarts)
But you're treating the symptoms instead of the underlying cause - why are the connections open? If the PHP script finished, shouldn't they close? Make sure your webserver is not using connection pooling...
One way to do this in Python 2, is to use raw_input()
:
raw_input("Press Enter to continue...")
In python3 it's just input()
You need to call ignoring
with exception to ignore while the WebDriver
will wait.
FluentWait<WebDriver> fluentWait = new FluentWait<>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(200, TimeUnit.MILLISECONDS)
.ignoring(NoSuchElementException.class);
See the documentation of FluentWait for more info. But beware that this condition is already implemented in ExpectedConditions so you should use
WebElement element = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
*Update for newer versions of Selenium:
withTimeout(long, TimeUnit) has become withTimeout(Duration)
pollingEvery(long, TimeUnit) has become pollingEvery(Duration)
So the code will look as such:
FluentWait<WebDriver> fluentWait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(30)
.pollingEvery(Duration.ofMillis(200)
.ignoring(NoSuchElementException.class);
Basic tutorial for waiting can be found here.
I received a IllegalMonitorStateException
while trying to wake up a thread in / from a different class
/ thread. In java 8
you can use the lock
features of the new Concurrency API instead of synchronized
functions.
I was already storing objects for asynchronous
websocket transactions in a WeakHashMap
. The solution in my case was to also store a lock
object in a ConcurrentHashMap
for synchronous
replies. Note the condition.await
(not .wait
).
To handle the multi threading I used a Executors.newCachedThreadPool()
to create a thread pool.
The second thing to learn (one would argue that this should be the first) is the command line interface of your OS and compiler/linker flags and switches.
Omar's solution is decent* if you cannot upgrade your environment to .NET 4.5 in order to gain access to the async and await APIs. That said, there here is one important change that should be made in order to avoid poor performance. A slight delay should be added between calls to Application.DoEvents() in order to prevent excessive CPU usage. By adding
Thread.Sleep(1);
before the call to Application.DoEvents(), you can add such a delay (1 millisecond) and prevent the application from using all of the cpu cycles available to it.
private void WaitNSeconds(int seconds)
{
if (seconds < 1) return;
DateTime _desired = DateTime.Now.AddSeconds(seconds);
while (DateTime.Now < _desired) {
Thread.Sleep(1);
System.Windows.Forms.Application.DoEvents();
}
}
*See https://blog.codinghorror.com/is-doevents-evil/ for a more detailed discussion on the potential pitfalls of using Application.DoEvents().
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.
There's always cmd. It may be less annoying if you have trouble quoting arguments to start-process:
cmd /c start /wait notepad
Or
notepad | out-host
Using jquery you can do it this way
$("#order").click(function(e){
e.preventDefault();
window.location="login.php";
});
Also in HMTL you can do it this way
<form name="frm" action="login.php" method="POST">
...
</form>
Hope this helps
You could use rebase interactive to modify the last two commits before they've been pushed to a remote
git rebase HEAD^^ -i
Simple way is to get the process id of mongodb and kill it. Please note DO NOT USE kill -9 pid for this as it may cause damage to the database.
so, 1. get the pid of mongodb
$ pgrep mongo
you will get pid of mongo, Now
$ kill
You may use kill -15 as well
You can loop through variable with list of directories:
- name: Copy files from several directories
copy:
src: "{{ item }}"
dest: "/etc/fooapp/"
owner: root
mode: "0600"
loop: "{{ files }}"
vars:
files:
- "dir1/"
- "dir2/"
Did you try passwd -d root
? Most likely, this will do what you want.
You can also manually edit /etc/shadow
: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to
root:$X$SK5xfLB1ZW:0:0...
There, delete the second field (everything between the first and second colon):
root::0:0...
Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)
root:*:0:0...
Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d
, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd
, and use mkpasswd
to create the second field for the /etc/shadow.)
From Object-Oriented Programming Concept:
If you have a function that is accessing/muttating the fields of your class, it becomes method. Otherwise, it is a function.
It will not be a crime if you keep calling all the functions in Java/C++ classes as methods. The reason is that you are directly/indirectly accessing/mutating class properties. So why not all the functions in Java/C++ classes are methods?
Actually the C++ standard (i.e. C++ 0x draft) says (tnx to @Xeo & @Ben Voigt for pointing that out to me):
23.2.4 Associative containers
5 For set and multiset the value type is the same as the key type. For map and multimap it is equal to pair. Keys in an associative container are immutable.
6 iterator of an associative container is of the bidirectional iterator category. For associative containers where the value type is the same as the key type, both iterator and const_iterator are constant iterators. It is unspecified whether or not iterator and const_iterator are the same type.
So VC++ 2008 Dinkumware implementation is faulty.
Old answer:
You got that error because in certain implementations of the std lib the set::iterator
is the same as set::const_iterator
.
For example libstdc++ (shipped with g++) has it (see here for the entire source code):
typedef typename _Rep_type::const_iterator iterator;
typedef typename _Rep_type::const_iterator const_iterator;
And in SGI's docs it states:
iterator Container Iterator used to iterate through a set.
const_iterator Container Const iterator used to iterate through a set. (Iterator and const_iterator are the same type.)
On the other hand VC++ 2008 Express compiles your code without complaining that you're calling non const methods on set::iterator
s.
The easier way (same as @Matt M's answer but corrected and added fallback to default map)
// override TypeMapProvider to return custom map for every requested type
Dapper.SqlMapper.TypeMapProvider = type =>
{
// create fallback default type map
var fallback = new DefaultTypeMap(type);
return new CustomPropertyTypeMap(type, (t, column) =>
{
var property = t.GetProperties().FirstOrDefault(prop =>
prop.GetCustomAttributes(typeof(ColumnAttribute))
.Cast<ColumnAttribute>()
.Any(attr => attr.Name == column));
// if no property matched - fall back to default type map
if (property == null)
{
property = fallback.GetMember(column)?.Property;
}
return property;
});
};
fscanf
will treat 2 arguments, and thus return 2. Your while statement will be false, hence never displaying what has been read, plus as it has read only 1 line, if is not at EOF, resulting in what you see.
What worked for me is to create a .launchd.conf
with the variables I needed:
setenv FOO barbaz
This file is read by launchd at login. You can add a variable 'on the fly' to the running launchd using:
launchctl setenv FOO barbaz`
In fact, .launchd.cond
simply contains launchctl commands.
Variables set this way seem to be present in GUI applications properly.
If you happen to be trying to set your LANG or LC_ variables in this way, and you happen to be using iTerm2, make sure you disable the 'Set locale variables automatically' setting under the Terminal tab of the Profile you're using. That seems to override launchd's environment variables, and in my case was setting a broken LC_CTYPE causing issues on remote servers (which got passed the variable).
(The environment.plist still seems to work on my Lion though. You can use the RCenvironment preference pane to maintain the file instead of manually editing it or required Xcode. Still seems to work on Lion, though it's last update is from the Snow Leopard era. Makes it my personally preferred method.)
$('.cw2').change(function () {
if ($('input.cw2').filter(':checked').length >= 1) {
$('input.cw2').not(this).prop('checked', false);
}
});
$('td, input').prop(function (){
$(this).css({ 'background-color': '#DFD8D1' });
$(this).addClass('changed');
});
I've used this with great success:
http://system.data.sqlite.org/
Free with no restrictions.
(Note from review: Original site no longer exists. The above link has a link pointing the the 404 site and has all the info of the original)
--Bruce
According to the documentation:
$validator = Validator::make($request->all(), [
'file' => 'max:500000',
]);
The value is in kilobytes. I.e. max:10240
= max 10 MB.
You should use the csv
module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows([row[2:4] for _ in range(count)])
or, using the itertools
module to do the repeating with itertools.repeat()
:
from itertools import repeat
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows(repeat(row[2:4], count))
try this one
public void writeFile(String arg1,String arg2) {_x000D_
try {_x000D_
if (!dir.exists()) {_x000D_
_x000D_
if (dir.mkdirs()) {_x000D_
_x000D_
Toast.makeText(getBaseContext(), "Directory created",_x000D_
Toast.LENGTH_SHORT).show();_x000D_
} else {_x000D_
Toast.makeText(getBaseContext(),_x000D_
"Error writng file " + filename, Toast.LENGTH_LONG)_x000D_
.show();_x000D_
}_x000D_
}_x000D_
_x000D_
else {_x000D_
_x000D_
File file = new File(dir, filename);_x000D_
if (!file.exists()) {_x000D_
file.createNewFile();_x000D_
}_x000D_
_x000D_
FileWriter fileWritter = new FileWriter(file, true);_x000D_
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);_x000D_
bufferWritter.write(arg1 + "\n");_x000D_
bufferWritter.close();_x000D_
_x000D_
} catch (Exception e) {_x000D_
e.printStackTrace();_x000D_
Toast.makeText(getBaseContext(),_x000D_
"Error writng file " + e.toString(), Toast.LENGTH_LONG)_x000D_
.show();_x000D_
}_x000D_
_x000D_
}
_x000D_
how about loading that background image somewhere hidden. That way it will be loaded when the page is opened and wont take any time once the form is created using ajax:
body {
background: #ffffff url('img_tree.png') no-repeat -100px -100px;
}
If you could use Ant then you would just use the JUnitReport task as detailed here: http://ant.apache.org/manual/Tasks/junitreport.html, but you mentioned in your question that you're not supposed to use Ant. I believe that task merely transforms the XML report into HTML so it would be feasible to use any XSLT processor to generate a similar report.
Alternatively, you could switch to using TestNG ( http://testng.org/doc/index.html ) which is very similar to JUnit but has a default HTML report as well as several other cool features.
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.
This is an edit of the answer from @kgiannakakis:
The original code is wrong because it does not correctly close the InputStream after Properties.load(InputStream)
is called. From the Javadocs: The specified stream remains open after this method returns.
================================
I believe that the configure method expects an absolute path. Anyhow, you may also try to load a Properties object first:
Properties props = new Properties();
InputStream is = new FileInputStream("log4j.properties");
try {
props.load(is);
}
finally {
try {
is.close();
}
catch (Exception e) {
// ignore this exception
}
}
PropertyConfigurator.configure(props);
If the properties file is in the jar, then you could do something like this:
Properties props = new Properties();
InputStream is = getClass().getResourceAsStream("/log4j.properties");
try {
props.load(is);
}
finally {
try {
is.close();
}
catch (Exception e) {
// ignore this exception
}
}
PropertyConfigurator.configure(props);
The above assumes that the log4j.properties is in the root folder of the jar file.
First you need to install tensorflow-gpu, because this package is responsible for gpu computations. Also remember to run your code with environment variable CUDA_VISIBLE_DEVICES = 0 (or if you have multiple gpus, put their indices with comma). There might be some issues related to using gpu. if your tensorflow does not use gpu anyway, try this
Try This:
SELECT systimestamp INTO time_db FROM dual ;
DBMS_OUTPUT.PUT_LINE('time before procedure ' || time_db);
Maybe you are using:
$(document).ready(function(){
// Your code here
});
Try this instead:
window.onload = function(){ }
If you come to this thread because you're using the node postgres / pg module, there is a better solution than setting NODE_TLS_REJECT_UNAUTHORIZED
or rejectUnauthorized
, which will lead to insecure connections.
Instead, configure the "ssl" option to match the parameters for tls.connect:
{
ca: fs.readFileSync('/path/to/server-ca.pem').toString(),
cert: fs.readFileSync('/path/to/client-cert.pem').toString(),
key: fs.readFileSync('/path/to/client-key.pem').toString(),
servername: 'my-server-name' // e.g. my-project-id/my-sql-instance-id for Google SQL
}
I've written a module to help with parsing these options from environment variables like PGSSLROOTCERT
, PGSSLCERT
, and PGSSLKEY
:
Just for fun, here is a GOTO implementation in Java.
Example:
1 public class GotoDemo { 2 public static void main(String[] args) { 3 int i = 3; 4 System.out.println(i); 5 i = i - 1; 6 if (i >= 0) { 7 GotoFactory.getSharedInstance().getGoto().go(4); 8 } 9 10 try { 11 System.out.print("Hell"); 12 if (Math.random() > 0) throw new Exception(); 13 System.out.println("World!"); 14 } catch (Exception e) { 15 System.out.print("o "); 16 GotoFactory.getSharedInstance().getGoto().go(13); 17 } 18 } 19 }
Running it:
$ java -cp bin:asm-3.1.jar GotoClassLoader GotoDemo 3 2 1 0 Hello World!
Do I need to add "don't use it!"?
You are missing the pythoncom
package. It comes with ActivePython but you can get it separately on GitHub (previously on SourceForge) as part of pywin32.
You can also simply use:
pip install pywin32
There's no difference in the size of the memory block allocated. calloc
just fills the memory block with physical all-zero-bits pattern. In practice it is often assumed that the objects located in the memory block allocated with calloc
have initilial value as if they were initialized with literal 0
, i.e. integers should have value of 0
, floating-point variables - value of 0.0
, pointers - the appropriate null-pointer value, and so on.
From the pedantic point of view though, calloc
(as well as memset(..., 0, ...)
) is only guaranteed to properly initialize (with zeroes) objects of type unsigned char
. Everything else is not guaranteed to be properly initialized and may contain so called trap representation, which causes undefined behavior. In other words, for any type other than unsigned char
the aforementioned all-zero-bits patterm might represent an illegal value, trap representation.
Later, in one of the Technical Corrigenda to C99 standard, the behavior was defined for all integer types (which makes sense). I.e. formally, in the current C language you can initialize only integer types with calloc
(and memset(..., 0, ...)
). Using it to initialize anything else in general case leads to undefined behavior, from the point of view of C language.
In practice, calloc
works, as we all know :), but whether you'd want to use it (considering the above) is up to you. I personally prefer to avoid it completely, use malloc
instead and perform my own initialization.
Finally, another important detail is that calloc
is required to calculate the final block size internally, by multiplying element size by number of elements. While doing that, calloc
must watch for possible arithmetic overflow. It will result in unsuccessful allocation (null pointer) if the requested block size cannot be correctly calculated. Meanwhile, your malloc
version makes no attempt to watch for overflow. It will allocate some "unpredictable" amount of memory in case overflow happens.
There is an excellent jquery plugin, LiveQuery, that does just this.
Live Query utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated.
For example you could use the following code to bind a click event to all A tags, even any A tags you might add via AJAX.
$('a').livequery('click', function(event) {
alert('clicked');
return false;
});
Once you add new A tags to your document, Live Query will bind the click event and there is nothing else that needs to be called or done.
Here is a working example of its magic...
The defaultdict solution is better. But for completeness you could also check and create empty list before the append. Add the + lines:
+ if not u in self.adj.keys():
+ self.adj[u] = []
self.adj[u].append(edge)
.
.
Only such dialog is FileDialog. Its part of WinForms, but its actually only wrapper around WinAPI standard OS file dialog. And I don't think it is ugly, its actually part of OS, so it looks like OS it is run on.
Other way, there is nothing to help you with. You either need to look for 3rd party implementation, either free (and I don't think there are any good) or paid.
Generates a strong password of length 8 containing at least one lower case letter, one uppercase letter, one digit, and one special character. You can change the length in the code too.
function checkForCharacterCondition($string) {
return (bool) preg_match('/(?=.*([A-Z]))(?=.*([a-z]))(?=.*([0-9]))(?=.*([~`\!@#\$%\^&\*\(\)_\{\}\[\]]))/', $string);
}
$j = 1;
function generate_pass() {
global $j;
$allowedCharacters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_{}[]';
$pass = '';
$length = 8;
$max = mb_strlen($allowedCharacters, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$pass .= $allowedCharacters[random_int(0, $max)];
}
if (checkForCharacterCondition($pass)){
return '<br><strong>Selected password: </strong>'.$pass;
}else{
echo 'Iteration '.$j.': <strong>'.$pass.'</strong> Rejected<br>';
$j++;
return generate_pass();
}
}
echo generate_pass();
You're saying that you need GPS location first if its available, but what you did is first you're getting location from network provider and then from GPS. This will get location from Network and GPS as well if both are available. What you can do is, write these cases in if..else if
block. Similar to-
if( !isGPSEnabled && !isNetworkEnabled) {
// Can't get location by any way
} else {
if(isGPSEnabled) {
// get location from GPS
} else if(isNetworkEnabled) {
// get location from Network Provider
}
}
So this will fetch location from GPS first (if available), else it will try to fetch location from Network Provider.
EDIT:
To make it better, I'll post a snippet. Consider it is in try-catch
:
boolean gps_enabled = false;
boolean network_enabled = false;
LocationManager lm = (LocationManager) mCtx
.getSystemService(Context.LOCATION_SERVICE);
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location net_loc = null, gps_loc = null, finalLoc = null;
if (gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (gps_loc != null && net_loc != null) {
//smaller the number more accurate result will
if (gps_loc.getAccuracy() > net_loc.getAccuracy())
finalLoc = net_loc;
else
finalLoc = gps_loc;
// I used this just to get an idea (if both avail, its upto you which you want to take as I've taken location with more accuracy)
} else {
if (gps_loc != null) {
finalLoc = gps_loc;
} else if (net_loc != null) {
finalLoc = net_loc;
}
}
Now you check finalLoc
for null
, if not then return
it.
You can write above code in a function which returns the desired (finalLoc
) location. I think this might help.
I think you both are right. The later answer works fine but its like setting a global option so you have to do the following:
$.ajaxSetup({
async: false
});
//ajax call here
$.ajaxSetup({
async: true
});
I agree with Corey, urllib2 is more complete than urllib and should likely be the module used if you want to do more complex things, but to make the answers more complete, urllib is a simpler module if you want just the basics:
import urllib
response = urllib.urlopen('http://www.example.com/sound.mp3')
mp3 = response.read()
Will work fine. Or, if you don't want to deal with the "response" object you can call read() directly:
import urllib
mp3 = urllib.urlopen('http://www.example.com/sound.mp3').read()
Type hints are for maintainability and don't get interpreted by Python. In the code below, the line def add(self, ic:int)
doesn't result in an error until the next return...
line:
class C1:
def __init__(self):
self.idn = 1
def add(self, ic: int):
return self.idn + ic
c1 = C1()
c1.add(2)
c1.add(c1)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 5, in add
TypeError: unsupported operand type(s) for +: 'int' and 'C1'
EDIT: This code was used to show notes on top of a HTML5 video. It changes the font-size on the fly when the video is resized (when the browser window is resized.) The notes was connected to the video (just like notes on YouTube), which is why the code uses instances instead of a DOM handle directly.
As per request I'll throw in some code that I used to achieve this. (Text boxes over an HTML5 video.) The code was written a long time ago, and I quite frankly think it's pretty messy. Since the question is already answered and an answer is already accepted a long time ago I don't bother rewriting this. But if anyone wants to simplify this a bit, you're more than welcome!
// Figure out the text size:
var text = val['text'];
var letters = text.length;
var findMultiplier = function(x) { // g(x)
/* By analysing some functions with regression, the resulting function that
gives the best font size with respect to the number of letters and the size
of the note is:
g(x) = 8.3 - 2.75x^0.15 [1 < x < 255]
f(x) = g(letters) * (x / 1000)^0.5
Font size = f(size)
*/
return 8.3 - 2.75 * Math.pow(x, 0.15);
};
var findFontSize = function(x) { // f(x)
return findMultiplier(letters) * Math.pow(x / 1000, 0.5);
};
val.setFontSizeListener = function() {
p.style.fontSize = '1px'; // So the text should not overflow the box when measuring.
var noteStyle = window.getComputedStyle(table);
var width = noteStyle.getPropertyValue('width');
var height = noteStyle.getPropertyValue('height');
var size = width.substring(0, width.length - 2) * height.substring(0, height.length - 2);
p.style.fontSize = findFontSize(size) + 'px';
};
window.addEventListener('resize', val.setFontSizeListener);
You'll probably need to tweak these numbers from font-family to font-family. A good way to do this is download a free graph visualizer called GeoGebra. Change the length of the text and the size of the box. Then you manually set the size. Plot the manual results into the coordinate system. Then you enter the two equations I've posted here and you tweak the numbers until "my" graph fits your own manually plotted points.
this is the only case in which ==
and !=
should be used:
if (val == null) console.log('val is null or undefined')
if (val != null) console.log('val is neither null nor undefined')
For any other comparisons, the strict comparators (===
and !==
) should be used.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
The current answer wasn't working. I wanted to remove the title entirely, yet the text "back" wasn't going away.
Go back to the previous view controller and set its title property:
self.title = @" ";
ONLY works when the previous View Controller does not have a title
Try using this:
If you specify
ON DUPLICATE KEY UPDATE
, and a row is inserted that would cause a duplicate value in aUNIQUE index or
PRIMARY KEY, MySQL performs an [
UPDATE`](http://dev.mysql.com/doc/refman/5.7/en/update.html) of the old row...The
ON DUPLICATE KEY UPDATE
clause can contain multiple column assignments, separated by commas.With
ON DUPLICATE KEY UPDATE
, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify theCLIENT_FOUND_ROWS
flag tomysql_real_connect()
when connecting to mysqld, the affected-rows value is 1 (not 0) if an existing row is set to its current values...
Visual Studio 2013: Yes to both adding to the watch windows during debugging and dragging variables or typing them in without "user::". But before any of that would work I also needed to go to Tools > Options, then Debugging > General and had to scroll right down to the bottom of the right hand pane to be able to tick "Use Managed Compatibility Mode". Then I had to stop and restart debugging. Finally the above advice worked. Many thanks to the above and to this article: Visual Studio 2015 Debugging: Can't expand local variables?
If you change your property to use a backing field (instead of an automatic property), you can do the following:
public event EventHandler ImageFullPath1Changed;
private string _imageFullPath1 = string.Empty;
public string ImageFullPath1
{
get
{
return imageFullPath1 ;
}
set
{
if (_imageFullPath1 != value)
{
_imageFullPath1 = value;
EventHandler handler = ImageFullPathChanged;
if (handler != null)
handler(this, e);
}
}
}
Taken from http://forum.jquery.com/topic/multiple-versions-of-jquery-on-the-same-page:
$
and jQuery
belong to versionX.$
and jQuery
belong to versionY, plus _$
and _jQuery
belong to versionX.my_jQuery = jQuery.noConflict(true);
-- now $
and jQuery
belong to versionX, _$
and _jQuery
are probably null, and my_jQuery
is versionY.create a logfile in php, to do it you need to pass data on function and it will create log file for you.
function wh_log($log_msg)
{
$log_filename = "log";
if (!file_exists($log_filename))
{
// create directory/folder uploads.
mkdir($log_filename, 0777, true);
}
$log_file_data = $log_filename.'/log_' . date('d-M-Y') . '.log';
// if you don't add `FILE_APPEND`, the file will be erased each time you add a log
file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND);
}
// call to function
wh_log("this is my log message");
Using the chronic gem:
class MyModel < ActiveRecord::Base
validate :valid_date?
def valid_date?
unless Chronic.parse(from_date)
errors.add(:from_date, "is missing or invalid")
end
end
end
All that's needed is that the format specifiers and the types agree, and you can always cast to make that true. long
is at least 32 bits, so %lu
together with (unsigned long)k
is always correct:
uint32_t k;
printf("%lu\n", (unsigned long)k);
size_t
is trickier, which is why %zu
was added in C99. If you can't use that, then treat it just like k
(long
is the biggest type in C89, size_t
is very unlikely to be larger).
size_t sz;
printf("%zu\n", sz); /* C99 version */
printf("%lu\n", (unsigned long)sz); /* common C89 version */
If you don't get the format specifiers correct for the type you are passing, then printf
will do the equivalent of reading too much or too little memory out of the array. As long as you use explicit casts to match up types, it's portable.
It's entirely possible in browser-side javascript.
The easy way:
The readAsDataURL() method might already encode it as base64 for you. You'll probably need to strip out the beginning stuff (up to the first ,
), but that's no biggie. This would take all the fun out though.
The hard way:
If you want to try it the hard way (or it doesn't work), look at readAsArrayBuffer()
. This will give you a Uint8Array and you can use the method specified. This is probably only useful if you want to mess with the data itself, such as manipulating image data or doing other voodoo magic before you upload.
There are two methods:
btoa
or similar
I recently implemented tar in the browser. As part of that process, I made my own direct Uint8Array->base64 implementation. I don't think you'll need that, but it's here if you want to take a look; it's pretty neat.
What I do now:
The code for converting to string from a Uint8Array is pretty simple (where buf is a Uint8Array):
function uint8ToString(buf) {
var i, length, out = '';
for (i = 0, length = buf.length; i < length; i += 1) {
out += String.fromCharCode(buf[i]);
}
return out;
}
From there, just do:
var base64 = btoa(uint8ToString(yourUint8Array));
Base64 will now be a base64-encoded string, and it should upload just peachy. Try this if you want to double check before pushing:
window.open("data:application/octet-stream;base64," + base64);
This will download it as a file.
Other info:
To get the data as a Uint8Array, look at the MDN docs:
Today I was looking for this very solution and I tried PDFtoPrinter which I had an issue with (the PDFs I tried printing suggested they used incorrect paper size which hung the print job and nothing else printed until resolved). In my effort to find an alternative, I remembered GhostScript and utilities associated with it. I found GSView and it's associated program GSPrint (reference https://www.ghostscript.com/). Both these require GhostScript (https://www.ghostscript.com/) but when all the components are installed, GSPrint worked flawlessly and I was able to create a scheduled task that printed PDFs automatically overnight.
\r
is the ASCII Carriage Return (CR) character.
There are different newline conventions used by different operating systems. The most common ones are:
\r\n
);\n
);\r
).The \n\r
(LF+CR) looks unconventional.
edit: My reading of the Telnet RFC suggests that:
The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").
canvas.toDataURL
is not working if the original image URL (either relative or absolute) does not belong to the same domain as the web page. Tested from a bookmarklet and a simple javascript in the web page containing the images.
Have a look to David Walsh working example. Put the html and images on your own web server, switch original image to relative or absolute URL, change to an external image URL. Only the first two cases are working.
TryParse is usually the most elegant way to handle this type of thing:
long temp = 0;
if (Int64.TryParse(dataAccCom.GetParameterValue(IDbCmd, "op_Id").ToString(), out temp))
{
DataTO.Id = temp;
}
Say you have multiple jar files a.jar,b.jar and c.jar. To add them to classpath while compiling you need to do
$javac -cp .:a.jar:b.jar:c.jar HelloWorld.java
To run do
$java -cp .:a.jar:b.jar:c.jar HelloWorld
The simple way I found to export / Backup Redis data (create dump file ) is to start up a server via command line with slaveof flag and create live replica as follow (assuming the source Redis is 1.2.3.4 on port 6379):
/usr/bin/redis-server --port 6399 --dbfilename backup_of_master.rdb --slaveof 1.2.3.4 6379
How about this?
<div class="relative">
<div class="yellow-div"></div>
<div class="yellow-div"></div>
<div class="absolute"></div>
</div>
.relative{
position:relative;
}
.absolute {
position:absolute;
width: 40px;
height: 100px;
background: #000;
z-index: 1;
top:30px;
left:0px;
}
.yellow-div {
position:relative;
width: 200px;
height: 50px;
background: yellow;
margin-bottom:4px;
z-index:0;
}
use the relative div as wrapper and let the yellow div's have normal positioning.
Only the black block need to have an absolute position then.
var dict = File.ReadLines("test.txt")
.Where(line => !string.IsNullOrWhitespace(line))
.Select(line => line.Split(new char[] { '=' }, 2, 0))
.ToDictionary(parts => parts[0], parts => parts[1]);
or
enter code here
line="[email protected][email protected]";
string[] tokens = line.Split(new char[] { '=' }, 2, 0);
ans:
tokens[0]=to
token[1][email protected][email protected]"
For me, adding the foreground
to CardView
didn't work (reason unknown :/)
Adding the same to it's child layout did the trick.
CODE:
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:focusable="true"
android:clickable="true"
card_view:cardCornerRadius="@dimen/card_corner_radius"
card_view:cardUseCompatPadding="true">
<LinearLayout
android:id="@+id/card_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:foreground="?android:attr/selectableItemBackground"
android:padding="@dimen/card_padding">
</LinearLayout>
</android.support.v7.widget.CardView>
An alternative to the answer Max Fahl gave.
You can define callback function as an arrow function in the parent component so that you won't need to bind that.
@Component({_x000D_
..._x000D_
// unlike this, template: '<child [myCallback]="theCallback.bind(this)"></child>',_x000D_
template: '<child [myCallback]="theCallback"></child>',_x000D_
directives: [ChildComponent]_x000D_
})_x000D_
export class ParentComponent {_x000D_
_x000D_
// unlike this, public theCallback(){_x000D_
public theCallback = () => {_x000D_
..._x000D_
}_x000D_
}_x000D_
_x000D_
@Component({...})_x000D_
export class ChildComponent{_x000D_
//This will be bound to the ParentComponent.theCallback_x000D_
@Input()_x000D_
public myCallback: Function; _x000D_
..._x000D_
}
_x000D_
If you are using IntelliJ IDEA, there is an option in the flutter inspector to disable it.
run the project
When you are in the Flutter Inspector, click or choose "More Actions."
Picture of the Flutter Inspector
When the menu appears, choose "Hide Debug Mode Banner"
Just a note, FishEye (and a lot of other Atlassian products) have a $10 Starter Editions, which in the case of FishEye gives you 5 repositories and access for up to 10 committers. The money goes to charity in this case.
You can use the following code to check if a textbox object is null/empty
'Checks if the box is null
If Me.TextBox & "" <> "" Then
'Enter Code here...
End if
This could help, by the way:
The box-sizing CSS property is used to alter the default CSS box model used to calculate widths and heights of elements.
http://www.w3.org/TR/css3-ui/#box-sizing
https://developer.mozilla.org/En/CSS/Box-sizing
Try: Console.WriteLine
(type out
for a Visual Studio snippet)
Console.WriteLine(stuff);
Another way is to use System.Diagnostics.Debug.WriteLine
:
System.Diagnostics.Debug.WriteLine(stuff);
Debug.WriteLine
may suit better for Output window in IDE because it will be rendered for both Console and Windows applications. Whereas Console.WriteLine
won't be rendered in Output window but only in the Console itself in case of Console Application type.
Another difference is that Debug.WriteLine
will not print anything in Release configuration.
After changing target name
My problem was xcconfig with old target names.
It would update to new ones.
Also if you had missing .h files that's the reason (pods header search path is in these xcconfig)
A small usage of np.nan ! = np.nan
s[s==s]
Out[953]:
0 1.0
1 2.0
2 3.0
3 4.0
5 5.0
dtype: float64
More Info
np.nan == np.nan
Out[954]: False
You could have a redirect servlet. In you web.xml you'd have:
<servlet>
<servlet-name>images</servlet-name>
<servlet-class>com.example.images.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>images</servlet-name>
<url-pattern>/images/*</url-pattern>
</servlet-mapping>
All your images would be in "/images", which would be intercepted by the servlet. It would then read in the relevant file in whatever folder and serve it right back out. For example, say you have a gif in your images folder, c:\Server_Images\smilie.gif. In the web page would be <img src="http:/example.com/app/images/smilie.gif"...
. In the servlet, HttpServletRequest.getPathInfo()
would yield "/smilie.gif". Which the servlet would find in the folder.
You could use the <pre>
tag
<div class="text">_x000D_
<pre>_x000D_
abc_x000D_
def_x000D_
ghi_x000D_
</pre>_x000D_
abc_x000D_
def_x000D_
ghi_x000D_
</div>
_x000D_
Please Search Google given to the world by Larry Page and Sergey Brin.
BufferedWriter out = null;
try {
FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
out = new BufferedWriter(fstream);
out.write("\nsue");
}
catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
finally {
if(out != null) {
out.close();
}
}
I do think that realizing Haskell's feature by examples is the best way to start above all.
http://en.wikipedia.org/wiki/Haskell_98_features
Here is tricky typeclasses including monads and arrows
http://www.haskell.org/haskellwiki/Typeclassopedia
for real world problems and bigger project, remember these tags: GHC(most used compiler), Hackage(libraryDB), Cabal(building system), darcs(another building system).
A integrated system can save your time: http://hackage.haskell.org/platform/
the package database for this system: http://hackage.haskell.org/
GHC compiler's wiki: http://www.haskell.org/haskellwiki/GHC
After Haskell_98_features and Typeclassopedia, I think you already can find and read the documention about them yourself
By the way, you may want to test some GHC's languages extension which may be a part of haskell standard in the future.
this is my best way for learning haskell. i hope it can help you.
This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....
To cover the identities listed:
IIS_IUSRS:
This is analogous to the old IIS6 IIS_WPG
group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.
IUSR:
This account is analogous to the old IUSR_<MACHINE_NAME>
local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).
For more information about IIS_IUSRS
and IUSR
see:
DefaultAppPool:
If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name>
will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool
created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>
. You also won't see these pool accounts in your computers User Manager. See the following for more information:
ASP.NET v4.0:
-
This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool
above.
NETWORK SERVICE:
-
The NETWORK SERVICE
account is a built-in identity introduced on Windows 2003. NETWORK SERVICE
is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).
In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE
). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" />
setting in web.config
file locally (if that setting is locked then it would need to be done by an admin in the machine.config
file).
Setting <identity impersonate="true">
is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).
In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR
or a specific custom anonymous account.
LOCAL SERVICE:
The LOCAL SERVICE
account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:
LOCAL SYSTEM:
You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.
In Practice:
In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity
. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity
:
In the website you should then configure the Authentication feature:
Right click and edit the Anonymous Authentication entry:
Ensure that "Application pool identity" is selected:
When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0
pool permissions then you can either do this via Explorer:
Click the "Check Names" button:
Or you can do this using the ICACLS.EXE
utility:
icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)
...or...if you site's application pool is called BobsCatPicBlog
then:
icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)
I hope this helps clear things up.
Update:
I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:
The difference between the 'Local System' account and the 'Network Service' account?
<style type="text/css">
body {background:none transparent;
}
</style>
that might work (if you put in the iframe) along with
<iframe src="stuff.htm" allowtransparency="true">
I use window.onresize = function(){ checkOrientation(); }
And in checkOrientation you can employ window.orientation or body width checking
but the idea is, the "window.onresize" is the most cross browser method, at least with the majority of the mobile and desktop browsers that I've had an opportunity to test with.
NAs also appear if there are attributes with zero variance (with all elements equal); see for instance:
cor(cbind(a=runif(10),b=rep(1,10)))
which returns:
a b
a 1 NA
b NA 1
Warning message:
In cor(cbind(a = runif(10), b = rep(1, 10))) :
the standard deviation is zero
Here is a quick and dirty way to extract the code from V3 or V4 ipynb without using ipython. It does not check cell types, etc.
import sys,json
f = open(sys.argv[1], 'r') #input.ipynb
j = json.load(f)
of = open(sys.argv[2], 'w') #output.py
if j["nbformat"] >=4:
for i,cell in enumerate(j["cells"]):
of.write("#cell "+str(i)+"\n")
for line in cell["source"]:
of.write(line)
of.write('\n\n')
else:
for i,cell in enumerate(j["worksheets"][0]["cells"]):
of.write("#cell "+str(i)+"\n")
for line in cell["input"]:
of.write(line)
of.write('\n\n')
of.close()
I remember the part from this exception : "Cannot modify header information - headers already sent by" occurring in PHP. It occurred when the headers were already sent in the redirection phase and any other output was generated e.g.:
echo "hello"; header("Location:http://stackoverflow.com");
Pardon me and do correct me if I am wrong but I am still learning MS Technologies and I was trying to help.
Here's an alternative to the HeberLZ's answer, using npm scripts.
My package.json
:
"scripts": {
"watch": "nodemon -e ts -w ./src -x npm run watch:serve",
"watch:serve": "ts-node --inspect src/index.ts"
},
-e
flag sets the extenstions to look for,-w
sets the watched directory,-x
executes the script.--inspect
in the watch:serve
script is actually a node.js flag, it just enables debugging protocol.
As documented in ?legend
you do this like so:
plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")
points(1:10,1:10)
Line breaks are achieved with the new line character \n
. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.
Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).
You can do something like this
import React from 'react';
class Header extends React.Component {
constructor() {
super();
}
checkClick(e, notyId) {
alert(notyId);
}
render() {
return (
<PopupOver func ={this.checkClick } />
)
}
};
class PopupOver extends React.Component {
constructor(props) {
super(props);
this.props.func(this, 1234);
}
render() {
return (
<div className="displayinline col-md-12 ">
Hello
</div>
);
}
}
export default Header;
Using statics
var MyComponent = React.createClass({
statics: {
customMethod: function(foo) {
return foo === 'bar';
}
},
render: function() {
}
});
MyComponent.customMethod('bar'); // true
Run all Collection in a folder in parallel:
'use strict';
global.Promise = require('bluebird');
const path = require('path');
const newman = Promise.promisifyAll(require('newman'));
const fs = Promise.promisifyAll(require('fs'));
const environment = 'postman_environment.json';
const FOLDER = path.join(__dirname, 'Collections_Folder');
let files = fs.readdirSync(FOLDER);
files = files.map(file=> path.join(FOLDER, file))
console.log(files);
Promise.map(files, file => {
return newman.runAsync({
collection: file, // your collection
environment: path.join(__dirname, environment), //your env
reporters: ['cli']
});
}, {
concurrency: 2
});
How to edit one specific row/tuple in Server Management Studio 2008/2012/2014/2016
Step 1: Right button mouse > Select "Edit Top 200 Rows"
Step 2: Navigate to Query Designer > Pane > SQL (Shortcut: Ctrl+3)
Step 3: Modify the query
Step 4: Right button mouse > Select "Execute SQL" (Shortcut: Ctrl+R)
The code marked as the solution did not work for me. This was my solution.
/*
* http://www.java2s.com/Code/Java/Security/EncryptingaStringwithDES.htm
* https://stackoverflow.com/questions/23561104/how-to-encrypt-and-decrypt-string-with-my-passphrase-in-java-pc-not-mobile-plat
*/
package encryptiondemo;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
*
* @author zchumager
*/
public class EncryptionDemo {
Cipher ecipher;
Cipher dcipher;
EncryptionDemo(SecretKey key) throws Exception {
ecipher = Cipher.getInstance("AES");
dcipher = Cipher.getInstance("AES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
}
public String encrypt(String str) throws Exception {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
}
public String decrypt(String str) throws Exception {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
}
public static void main(String args []) throws Exception
{
String data = "Don't tell anybody!";
String k = "Bar12345Bar12345";
//SecretKey key = KeyGenerator.getInstance("AES").generateKey();
SecretKey key = new SecretKeySpec(k.getBytes(), "AES");
EncryptionDemo encrypter = new EncryptionDemo(key);
System.out.println("Original String: " + data);
String encrypted = encrypter.encrypt(data);
System.out.println("Encrypted String: " + encrypted);
String decrypted = encrypter.decrypt(encrypted);
System.out.println("Decrypted String: " + decrypted);
}
}
Cleaning up : Since the post section of a Pipeline is guaranteed to run at the end of a Pipeline’s execution, we can add some notification or other steps to perform finalization, notification, or other end-of-Pipeline tasks.
pipeline {
agent any
stages {
stage('No-op') {
steps {
sh 'ls'
}
}
}
post {
cleanup {
echo 'One way or another, I have finished'
deleteDir() /* clean up our workspace */
}
}
}
Try request.setAttribute("param",value);
. It worked fine for me.
Please find this code sample:
private void sanitizePrice(ServletRequest request){
if(request.getParameterValues ("price") != null){
String price[] = request.getParameterValues ("price");
for(int i=0;i<price.length;i++){
price[i] = price[i].replaceAll("[^\\dA-Za-z0-9- ]", "").trim();
System.out.println(price[i]);
}
request.setAttribute("price", price);
//request.getParameter("numOfBooks").re
}
}
As the answers here demonstrates nicely, yes, there are several ways. However, in PHP you rarely actually need to do that. The "dogmatic way" to write PHP is to rely on the language's loose typing system, which will transparently coerce the type as needed. For integer values, this is usually without trouble. You should be very careful with floating point values, though.
<div>
looks nice, but a bit complicated in setting all these display: block, float: left
... Maybe because the general idea behind <div>
is a block of a paragraph size or more.
I have found the following nice way for spacing:
<button>Button 1></button>
<button style="margin-left: 4em">Button 2</button>
For multiple selection dropdown list,cannot accomplish it directly using dropdown..Can be done in similar ways..
Either you have to use checkbox list or listbox (ajax inclusive)
http://www.codeproject.com/Articles/55184/MultiSelect-Dropdown-in-ASP-NET
Be careful when using the MAC address as an identifier. I've experienced several gotchas:
Even with the above issues, I still think it's the best pure Java approach to hardware locking a license.
As now to day CKEditor 4+ launched we have to use it.ekeditor 4 setData documentation
CKEDITOR.instances['editor1'].setData(value);
Where editor1
is textarea Id.
Old methods such as insertHtml('html data')
and insertText('text data')
also works fine.
and to get data use
var ckdata = CKEDITOR.instances['editor1'].getData();
var data = CKEDITOR.instances.editor1.getData();
First You have to inject HttpClient
and Not HttpClientModule
,
second thing you have to remove .map((res:any) => res.json())
you won't need it any more because the new HttpClient
will give you the body of the response by default , finally make sure that you import HttpClientModule
in your AppModule
:
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AppSettingsService {
constructor(private http: HttpClient) {
this.getJSON().subscribe(data => {
console.log(data);
});
}
public getJSON(): Observable<any> {
return this.http.get("./assets/mydata.json");
}
}
to add this to your Component:
@Component({
selector: 'mycmp',
templateUrl: 'my.component.html',
styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
constructor(
private appSettingsService : AppSettingsService
) { }
ngOnInit(){
this.appSettingsService.getJSON().subscribe(data => {
console.log(data);
});
}
}
No, but the 32-bit version runs just fine on 64-bit Windows.
Try this character set:
[ \t]
This does only match a space or a tabulator.
There is a much easier way:
someButton.lineBreakMode = UILineBreakModeWordWrap;
(Edit for iOS 3 and later:)
someButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
Yes you can do that by just creating a BroadcastReceiver
that calls your Service
when your Application boots. Here is a complete answer given by me.
Android - Start service on boot
If you don't want any icon/launcher for you Application you can do that also, just don't create any Activity with
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
Just declare your Service
as declared normally.
If you want more Thread to be created, in above case you have to repeat the code inside run method or at least repeat calling some method inside.
Try this, which will help you to call as many times you needed. It will be helpful when you need to execute your run more then once and from many place.
class A extends Thread {
public void run() {
//Code you want to get executed seperately then main thread.
}
}
Main class
A obj1 = new A();
obj1.start();
A obj2 = new A();
obj2.start();
In the root folder where package.json
is located, run npm outdated
. You'll get outdated packages returned with some details. In those details, you'll see the current version number of the outdated package.
After then, open the package.json
file and manually change the version number of the corresponding package.
Then delete the node_modules
folder and run npm install
. It should solve this issue.
From ?factor
:
To transform a factor f to approximately its original numeric values,
as.numeric(levels(f))[f]
is recommended and slightly more efficient thanas.numeric(as.character(f))
.
I use [NSException raise:format:]
as follows:
[NSException raise:@"Invalid foo value" format:@"foo of %d is invalid", foo];
Serialize both objects and compare the resulting strings by @JoelFan
So to do this, create a static class like so and use Extensions to extend ALL objects (so you can pass anytype of object, collection, etc into the method)
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
public static class MySerializer
{
public static string Serialize(this object obj)
{
var serializer = new DataContractJsonSerializer(obj.GetType());
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.Default.GetString(ms.ToArray());
}
}
}
Once you reference this static class in any other file, you can do this:
Person p = new Person { Firstname = "Jason", LastName = "Argonauts" };
Person p2 = new Person { Firstname = "Jason", LastName = "Argonaut" };
//assuming you have already created a class person!
string personString = p.Serialize();
string person2String = p2.Serialize();
Now you can simply use .Equals to compare them. I use this for checking if objects are in collections too. It works really well.
The path location must not contain á,à,â, and similars. Chinese characters or any other diferent than the usual alphabetical characters. For example, my path was C:\Users\Vinícius\AndroidStudioProjects\MyApplication .But my user name had the letter í. So I create a folder 'custom2222' and change the path to C:\custom2222\MyApplication
Browse to its page in the package index, eg. http://www.nuget.org/packages/Newtonsoft.Json/4.0.5
Then follow the install instructions given:
Install-Package Newtonsoft.Json -Version 4.0.5
Alternatively to download the .nupkg
file, follow the 'Download' link eg. https://www.nuget.org/api/v2/package/Newtonsoft.Json/4.0.5
Obsolete: install my Chrome extension Nutake which inserts a download link.
For CodeIgniter 4
, you can use the built-in API Response Trait
Here's sample code for reference:
<?php namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
class Home extends BaseController
{
use ResponseTrait;
public function index()
{
$data = [
'data' => 'value1',
'data2' => 'value2',
];
return $this->respond($data);
}
}
To complement Alex's response, I would add that starting from Python 2.2.0a2, from __future__ import division
is a convenient alternative to using lots of float(…)/…
. All divisions perform float divisions, except those with //
. This works with all versions from 2.2.0a2 on.
The most simple way is to use Record type Record<number, productDetails >
interface productDetails {
productId : number ,
price : number ,
discount : number
};
const myVar : Record<number, productDetails> = {
1: {
productId : number ,
price : number ,
discount : number
}
}
Frnds... I had the same issue while restroring database and tried every solution but could nt get resolved. Then i tried to re install SQL 2005 and the problem solved. Actully last time i forgot to check on customize option while instlling SQL.. It comes two times while installing and i checkd it for ones only..
This question can also be extended if necessary jar file can be found in global library, how can you configure it into your current project.
Process like these: "project structure"-->"modules"-->"click your current project pane at right"-->"dependencies"-->"click little add(+) button"-->"library"-->"select the library you want".
if you are using maven and you can also configure dependency in your pom.xml, but it your chosen version is not like the global library, you will waste memory on storing another version of the same jar file. so i suggest use the first step.
UrlConnection is an awkward API to work with. HttpClient is by far the better API and it'll spare you from loosing time searching how to achieve certain things like this stackoverflow question illustrates perfectly. I write this after having used the jdk HttpUrlConnection in several REST clients. Furthermore when it comes to scalability features (like threadpools, connection pools etc.) HttpClient is superior
To get country code
<uses-permission android:name="android.permission.INTERNET" />
public String makeServiceCall() {
String response = null;
String reqUrl = "https://ipinfo.io/country";
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
This question being tagged Bash, here's the Bash (=4) way of doing: use mapfile
with the -s
(skip) and -n
(count) option.
If you need to get the 42nd line of a file file
:
mapfile -s 41 -n 1 ary < file
At this point, you'll have an array ary
the fields of which containing the lines of file
(including the trailing newline), where we have skipped the first 41 lines (-s 41
), and stopped after reading one line (-n 1
). So that's really the 42nd line. To print it out:
printf '%s' "${ary[0]}"
If you need a range of lines, say the range 42–666 (inclusive), and say you don't want to do the math yourself, and print them on stdout:
mapfile -s $((42-1)) -n $((666-42+1)) ary < file
printf '%s' "${ary[@]}"
If you need to process these lines too, it's not really convenient to store the trailing newline. In this case use the -t
option (trim):
mapfile -t -s $((42-1)) -n $((666-42+1)) ary < file
# do stuff
printf '%s\n' "${ary[@]}"
You can have a function do that for you:
print_file_range() {
# $1-$2 is the range of file $3 to be printed to stdout
local ary
mapfile -s $(($1-1)) -n $(($2-$1+1)) ary < "$3"
printf '%s' "${ary[@]}"
}
No external commands, only Bash builtins!
Probably you want something like:
firstline = True
for row in kidfile:
if firstline: #skip first line
firstline = False
continue
# parse the line
An other way to achive the same result is calling readline
before the loop:
kidfile.readline() # skip the first line
for row in kidfile:
#parse the line
Open WSDL file and find:
<soap:operation soapAction="[actionNameIsHere]" style="document"/>
Add to the requests header [request send to service]:
'soapAction' : '[actionNameIsHere]'
This work for me.
For devs. using node-soap [ https://github.com/vpulim/node-soap ] - example:
var soap = require('soap');
var options = {
...your options...
forceSoap12Headers: true
}
soap.createClient(
wsdl, options,
function(err, client) {
if(err) {
return callBack(err, result);
}
client.addHttpHeader('soapAction', '[actionNameIsHere]');
...your code - request send...
});
Like Sunil said, this is not memory address.This is just the hashcode
To get the same @ content, you can:
If hashCode is not overridden in that class:
"@" + Integer.toHexString(obj.hashCode())
If hashCode is overridden, you get the original value with:
"@" + Integer.toHexString(System.identityHashCode(obj))
This is often confused with memory address because if you don't override hashCode(), the memory address is used to calculate the hash.
that syntax is now deprecated, you will get this error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 14: Expected a stage @ line 14, column 9.
parallel firstTask: {
^
WorkflowScript: 14: Stage does not have a name @ line 14, column 9.
parallel secondTask: {
^
2 errors
You should do something like:
stage("Parallel") {
steps {
parallel (
"firstTask" : {
//do some stuff
},
"secondTask" : {
// Do some other stuff in parallel
}
)
}
}
Just to add the use of node here, to distribute jobs across multiple build servers/ VMs:
pipeline {
stages {
stage("Work 1"){
steps{
parallel ( "Build common Library":
{
node('<Label>'){
/// your stuff
}
},
"Build Utilities" : {
node('<Label>'){
/// your stuff
}
}
)
}
}
All VMs should be labelled as to use as a pool.
I have been trying to attach an audio which should autoplay and will be hidden. It's very simple. Just a few lines of HTML and CSS. Check this out!! Here is the piece of code I used within the body.
<div id="player">
<audio controls autoplay hidden>
<source src="file.mp3" type="audio/mpeg">
unsupported !!
</audio>
</div>
You need to disable Script Debugging In Visual Studio
Generally, the answer to your question is no, you cannot define more than one externally visible function per file. You can return function handles to local functions, though, and a convenient way to do so is to make them fields of a struct. Here is an example:
function funs = makefuns
funs.fun1=@fun1;
funs.fun2=@fun2;
end
function y=fun1(x)
y=x;
end
function z=fun2
z=1;
end
And here is how it could be used:
>> myfuns = makefuns;
>> myfuns.fun1(5)
ans =
5
>> myfuns.fun2()
ans =
1
In addition to @pawelzieba's answer, which definitely is correct, to join two tables, while you can use an INNER JOIN
like this
SELECT * FROM expense INNER JOIN refuel
ON exp_id = expense_id
WHERE refuel_id = 1
via raw query like this -
String rawQuery = "SELECT * FROM " + RefuelTable.TABLE_NAME + " INNER JOIN " + ExpenseTable.TABLE_NAME
+ " ON " + RefuelTable.EXP_ID + " = " + ExpenseTable.ID
+ " WHERE " + RefuelTable.ID + " = " + id;
Cursor c = db.rawQuery(
rawQuery,
null
);
because of SQLite's backward compatible support of the primitive way of querying, we turn that command into this -
SELECT *
FROM expense, refuel
WHERE exp_id = expense_id AND refuel_id = 1
and hence be able to take advanatage of the SQLiteDatabase.query() helper method
Cursor c = db.query(
RefuelTable.TABLE_NAME + " , " + ExpenseTable.TABLE_NAME,
Utils.concat(RefuelTable.PROJECTION, ExpenseTable.PROJECTION),
RefuelTable.EXP_ID + " = " + ExpenseTable.ID + " AND " + RefuelTable.ID + " = " + id,
null,
null,
null,
null
);
For a detailed blog post check this http://blog.championswimmer.in/2015/12/doing-a-table-join-in-android-without-using-rawquery
You can use the inbuilt readline
package, see docs here. I use stream to create a new output stream.
var fs = require('fs'),
readline = require('readline'),
stream = require('stream');
var instream = fs.createReadStream('/path/to/file');
var outstream = new stream;
outstream.readable = true;
outstream.writable = true;
var rl = readline.createInterface({
input: instream,
output: outstream,
terminal: false
});
rl.on('line', function(line) {
console.log(line);
//Do your stuff ...
//Then write to outstream
rl.write(cubestuff);
});
Large files will take some time to process. Do tell if it works.
Another option is to use a regex and gsub, which takes a block:
'one TWO three foUR'.gsub(/\w+/, &:capitalize)
If the relation must not be bidirectional then an @ElementCollection might be easier than using a lazy One2Many collection.
I also found another way of doing this that gives proper 'x10(superscript)5' notation on the axes. I'm posting it here in the hope it might be useful to some. I got the code from here so I claim no credit for it, that rightly goes to Brian Diggs.
fancy_scientific <- function(l) {
# turn in to character string in scientific notation
l <- format(l, scientific = TRUE)
# quote the part before the exponent to keep all the digits
l <- gsub("^(.*)e", "'\\1'e", l)
# turn the 'e+' into plotmath format
l <- gsub("e", "%*%10^", l)
# return this as an expression
parse(text=l)
}
Which you can then use as
ggplot(data=df, aes(x=x, y=y)) +
geom_point() +
scale_y_continuous(labels=fancy_scientific)
for i in range (1,10):
string="string"+str(i)
To get string0, string1 ..... string10
, you could do like
>>> ["string"+str(i) for i in range(11)]
['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9', 'string10']
For people like me want the long date format (LLLL
) but without the time of day, there's a GitHub issue for that: https://github.com/moment/moment/issues/2505. For now, there's a workaround:
var localeData = moment.localeData( moment.locale() ),
llll = localeData.longDateFormat( 'llll' ),
lll = localeData.longDateFormat( 'lll' ),
ll = localeData.longDateFormat( 'll' ),
longDateFormat = llll.replace( lll.replace( ll, '' ), '' );
var formattedDate = myMoment.format(longDateFormat);
This is in response to the above post by Efx:
If the URL already contains the var you want to change, then it is added yet again as a hidden field.
Here is a modification of that code as to prevent duplicating vars in the URL:
foreach ($_GET as $key => $value) {
if ($key != "my_key") {
echo("<input type='hidden' name='$key' value='$value'/>");
}
}
While
constructs are terminated not with an End While
but with a Wend
.
While counter < 20
counter = counter + 1
Wend
Note that this information is readily available in the documentation; just press F1. The page you link to deals with Visual Basic .NET, not VBA. While (no pun intended) there is some degree of overlap in syntax between VBA and VB.NET, one can't just assume that the documentation for the one can be applied directly to the other.
Also in the VBA help file:
Tip The
Do...Loop
statement provides a more structured and flexible way to perform looping.
You might want colored output with this.
I use this one-liner for listing the tracked files and directories in the current directory of the current branch:
ls --group-directories-first --color=auto -d $(git ls-tree $(git branch | grep \* | cut -d " " -f2) --name-only)
You might want to add it as an alias:
alias gl='ls --group-directories-first --color=auto -d $(git ls-tree $(git branch | grep \* | cut -d " " -f2) --name-only)'
If you want to recursively list files:
'ls' --color=auto -d $(git ls-tree -rt $(git branch | grep \* | cut -d " " -f2) --name-only)
And an alias:
alias glr="'ls' --color=auto -d \$(git ls-tree -rt \$(git branch | grep \\* | cut -d \" \" -f2) --name-only)"
If you use UTF-8 encoding then one character can takes a various number of bytes (2 - 4). For PL/SQL the varchar2 limit is 32767 bytes, not characters. See how I increase a PL/SQL varchar2 variable of the 4000 character size:
SQL> set serveroutput on
SQL> l
1 declare
2 l_var varchar2(30000);
3 begin
4 l_var := rpad('A', 4000);
5 dbms_output.put_line(length(l_var));
6 l_var := l_var || rpad('B', 10000);
7 dbms_output.put_line(length(l_var));
8* end;
SQL> /
4000
14000
PL/SQL procedure successfully completed.
But you can't insert into your table the value of such variable:
SQL> ed
Wrote file afiedt.buf
1 create table ttt (
2 col1 varchar2(2000 char)
3* )
SQL> /
Table created.
SQL> ed
Wrote file afiedt.buf
1 declare
2 l_var varchar2(30000);
3 begin
4 l_var := rpad('A', 4000);
5 dbms_output.put_line(length(l_var));
6 l_var := l_var || rpad('B', 10000);
7 dbms_output.put_line(length(l_var));
8 insert into ttt values (l_var);
9* end;
SQL> /
4000
14000
declare
*
ERROR at line 1:
ORA-01461: can bind a LONG value only for insert into a LONG column
ORA-06512: at line 8
As a solution, you can try to split this variable's value into several parts (SUBSTR) and store them separately.
If the array is a global, static, or automatic variable (int array[10];
), then sizeof(array)/sizeof(array[0])
works.
If it is a dynamically allocated array (int* array = malloc(sizeof(int)*10);
) or passed as a function argument (void f(int array[])
), then you cannot find its size at run-time. You will have to store the size somewhere.
Note that sizeof(array)/sizeof(array[0])
compiles just fine even for the second case, but it will silently produce the wrong result.
For Windows, from Nodejs cannot find installed module on Windows? what worked for me is running npm link as in
npm link wisp
Edit: as of RC2 and RTM releases, this advice is out of date. The best way I have found to accomplish this in release is to edit the following web.config sections in IIS for each environment:
system.webServer/aspNetCore
:
Edit the environmentVariable entry and add an environment variable setting:
ASPNETCORE_ENVIRONMENT
: < Your environment name >
As an alternative to drpdrp's approach, you can do the following:
In your project.json, add commands that pass the ASPNET_ENV variable directly to Kestrel:
"commands": {
"Development": "Microsoft.AspNet.Server.Kestrel --ASPNET_ENV Development",
"Staging": "Microsoft.AspNet.Server.Kestrel --ASPNET_ENV Staging",
"Production": "Microsoft.AspNet.Server.Kestrel --ASPNET_ENV Production"
}
When publishing, use the --iis-command
option to specify an environment:
dnu publish --configuration Debug --iis-command Staging --out "outputdir" --runtime dnx-clr-win-x86-1.0.0-rc1-update1
I found this approach to be less intrusive than creating extra IIS users.
Use @Named
to differentiate between different objects of the same type bound in the same scope.
@Named("maxWaitTime")
public long maxWaitTimeMs;
@Named("minWaitTime")
public long minWaitTimeMs;
Without the @Named
qualifier, the injector would not know which long to bind to which variable.
If you want to create annotations that act like @Named
, use the @Qualifier
annotation when creating them.
If you look at @Named
, it is itself annotated with @Qualifier
.
If you only need to find a free port for later use, here is a snippet similar to a previous answer, but shorter, using socketserver:
import socketserver
with socketserver.TCPServer(("localhost", 0), None) as s:
free_port = s.server_address[1]
Note that the port is not guaranteed to remain free, so you may need to put this snippet and the code using it in a loop.
Simple solution: The sequence is really matter while including the auto complete libraries:
<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<script src='https://cdn.rawgit.com/pguso/jquery-plugin-circliful/master/js/jquery.circliful.min.js'></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>
You should open File/Settings/Version Control/Subversion and uncheck 3 options: Use command line client, Use system default Subversion configuration directory and Use system default Subversion configuration directory like http://screencast.com/t/rlh9H2WVpgo
And then go to network tab. Choose SSLv3 instead of All in the field SSL protocols like http://screencast.com/t/l5yw1jqOxV
Lastly, check in or out your source via svn. It works well
The R packages dplyr and sf import the operator %>% from the R package magrittr.
Help is available by using the following command:
?'%>%'
Of course the package must be loaded before by using e.g.
library(sf)
The documentation of the magrittr forward-pipe operator gives a good example: When functions require only one argument, x %>% f is equivalent to f(x)
For PHP's PHPSESSID variable, this function works:
function getPHPSessId() {
var phpSessionId = document.cookie.match(/PHPSESSID=[A-Za-z0-9]+\;/i);
if(phpSessionId == null)
return '';
if(typeof(phpSessionId) == 'undefined')
return '';
if(phpSessionId.length <= 0)
return '';
phpSessionId = phpSessionId[0];
var end = phpSessionId.lastIndexOf(';');
if(end == -1) end = phpSessionId.length;
return phpSessionId.substring(10, end);
}
I imagine this like that:
<html>
<head>
<script>
var frame_loaded = 0;
function setFrameLoaded()
{
frame_loaded = 1;
alert("Iframe is loaded");
}
$('#click').click(function(){
if(frame_loaded == 1)
console.log('iframe loaded')
} else {
console.log('iframe not loaded')
}
})
</script>
</head>
<button id='click'>click me</button>
<iframe id='MainPopupIframe' onload='setFrameLoaded();' src='http://...' />...</iframe>
This is a fairly standard communication question. One approach would be to use a ResultReceiver in Activity A:
Intent GotoB=new Intent(A.this,B.class);
GotoB.putExtra("finisher", new ResultReceiver(null) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
A.this.finish();
}
});
startActivityForResult(GotoB,1);
and then in Activity B you can just finish it on demand like so:
((ResultReceiver)getIntent().getExtra("finisher")).send(1, new Bundle());
Try something like that.
A div
is a block level element, meaning that will behave as a block, and blocks can't stay side by side without being floated. You can however set them to inline elements with:
display:inline-block;
Give it a try...
Another way is to place them using:
position:absolute;
left:0;
and/or
position:absolute;
right:0;
Note: For this to work as expected, the wrapper element must have a position:relative;
so that the elements with absolute positioning stay relative to their wrapper element.
Really, really, really check if the TCP/IP protocol is enabled in your local SQLEXPRESS instance.
Follow these steps to make sure:
If you have any problem, check this blog post for details, as it contains screenshots and much more info.
Also check if the "SQL Server Browser" windows service is activated and running:
That's it.
After I installed a fresh local SQLExpress, all I had to do was to enable TCP/IP and start the SQL Server Browser service.
Below a code I use to test the SQLEXPRESS local connection. Of course, you should change the IP, DatabaseName and user/password as needed.:
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JtdsSqlExpressInstanceConnect {
public static void main(String[] args) throws SQLException {
Connection conn = null;
ResultSet rs = null;
String url = "jdbc:jtds:sqlserver://127.0.0.1;instance=SQLEXPRESS;DatabaseName=master";
String driver = "net.sourceforge.jtds.jdbc.Driver";
String userName = "user";
String password = "password";
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, userName, password);
System.out.println("Connected to the database!!! Getting table list...");
DatabaseMetaData dbm = conn.getMetaData();
rs = dbm.getTables(null, null, "%", new String[] { "TABLE" });
while (rs.next()) { System.out.println(rs.getString("TABLE_NAME")); }
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.close();
rs.close();
}
}
}
And if you use Maven, add this to your pom.xml:
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.2.4</version>
</dependency>
You didn't select post_id
in the subquery. You have to select it in the subquery like this:
SELECT wp_woocommerce_order_items.order_id As No_Commande
FROM wp_woocommerce_order_items
LEFT JOIN
(
SELECT meta_value As Prenom, post_id -- <----- this
FROM wp_postmeta
WHERE meta_key = '_shipping_first_name'
) AS a
ON wp_woocommerce_order_items.order_id = a.post_id
WHERE wp_woocommerce_order_items.order_id =2198
Use a virtual environment:
$ virtualenv myenv
.. some output ..
$ source myenv/bin/activate
(myenv) $ pip install what-i-want
You only use sudo
or elevated permissions when you want to install stuff for the global, system-wide Python installation.
It is best to use a virtual environment which isolates packages for you. That way you can play around without polluting the global python install.
As a bonus, virtualenv does not need elevated permissions.
DECLARE @String NVARCHAR(MAX);
USE Databse Name;
SELECT @String
=
(
SELECT 'ALTER INDEX [' + dbindexes.[name] + '] ON [' + db.name + '].[' + dbschemas.[name] + '].[' + dbtables.[name]
+ '] REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = PAGE);' + CHAR(10) AS [text()]
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
INNER JOIN sys.tables dbtables
ON dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas
ON dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes
ON dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
INNER JOIN sys.databases AS db
ON db.database_id = indexstats.database_id
WHERE dbindexes.name IS NOT NULL
AND indexstats.database_id = DB_ID()
AND indexstats.avg_fragmentation_in_percent >= 10
ORDER BY indexstats.page_count DESC
FOR XML PATH('')
);
EXEC (@String);
Short answer: use for...break
for this or change your code to avoid breaking of forEach
. Do not use .some()
or .every()
to emulate for...break
. Rewrite your code to avoid for...break
loop, or use for...break
. Every time you use these methods as for...break
alternative God kills kitten.
Long answer:
.some()
and .every()
both return boolean
value, .some()
returns true
if there any element for which passed function returns true
, every returns false
if there any element for which passed function returns false
. This is what that functions mean. Using functions for what they doesn't mean is much worse then using tables for layout instead of CSS, because it frustrates everybody who reads your code.
Also, the only possible way to use these methods as for...break
alternative is to make side-effects (change some vars outside of .some()
callback function), and this is not much different from for...break
.
So, using .some()
or .every()
as for...break
loop alternative isn't free of side effects, this isn't much cleaner then for...break
, this is frustrating, so this isn't better.
You can always rewrite your code so that there will be no need in for...break
. You can filter array using .filter()
, you can split array using .slice()
and so on, then use .forEach()
or .map()
for that part of array.
Are you 100% sure your browser is even loading the script? Go to your page in Firefox and use the console in Firebug to check if the script has been loaded or not.
<asp:Button ID="btnGet" runat="server" Text="Get" OnClick="btnGet_Click" OnClientClick="retun callMethod();" />
<script type="text/javascript">
function callMethod() {
//your logic should be here and make sure your logic code note returing function
return false;
}
</script>
What worked for me is to add include tag in order to specify exactly what I want to filter.
It seems the resource plugin has problems going through the whole src/main/resource folder, probably due to some specific files inside.
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>application.yml</include>
</includes>
</resource>
</resources>
Sounds like mssql jdbc is buffering the entire resultset for you. You can add a connect string parameter saying selectMode=cursor or responseBuffering=adaptive. If you are on version 2.0+ of the 2005 mssql jdbc driver then response buffering should default to adaptive.
You don't have to cram multiple operations into one stream/lambda. Consider separating them into 2 statements (using static import of toList()
):
entryList.forEach(e->e.setTempId(tempId));
List<Entry> updatedEntries = entryList.stream()
.map(e->entityManager.update(entry, entry.getId()))
.collect(toList());
One of the best options is to go for MongoDB(NOSql dB) that supports scalability.Stores large amounts of data nothing but bigdata in the form of documents unlike rows and tables in sql.This is fasters that follows sharding of the data.Uses replicasets to ensure data guarantee that maintains multiple servers having primary db server as the base. Language independent. Flexible to use
setTimeout( function ( ) { alert( "moo" ); }, 10000 ); //displays msg in 10 seconds
There's a couple ways of doing this. As long as the WAR file is expanded (a set of files instead of one .war file), you can use this API:
ServletContext context = getContext();
String fullPath = context.getRealPath("/WEB-INF/test/foo.txt");
That will get you the full system path to the resource you are looking for. However, that won't work if the Servlet Container never expands the WAR file (like Tomcat). What will work is using the ServletContext's getResource
methods.
ServletContext context = getContext();
URL resourceUrl = context.getResource("/WEB-INF/test/foo.txt");
or alternatively if you just want the input stream:
InputStream resourceContent = context.getResourceAsStream("/WEB-INF/test/foo.txt");
The latter approach will work no matter what Servlet Container you use and where the application is installed. The former approach will only work if the WAR file is unzipped before deployment.
EDIT:
The getContext() method is obviously something you would have to implement. JSP pages make it available as the context
field. In a servlet you get it from your ServletConfig
which is passed into the servlet's init()
method. If you store it at that time, you can get your ServletContext any time you want after that.
you will need the package and its dependencies.
since you mentioned synaptic, you must be using a Debian based system. one way to get what you need:
sudo apt-get install python-tk
You should check out Losswise (https://losswise.com), it has a plugin for Keras that's easier to use than Tensorboard and has some nice extra features. With Losswise you'd just use from losswise.libs import LosswiseKerasCallback
and then callback = LosswiseKerasCallback(tag='my fancy convnet 1')
and you're good to go (see https://docs.losswise.com/#keras-plugin).
You can set the location of your log4j.properties from inside your java app by using:
org.apache.log4j.PropertyConfigurator.configure(file/location/log4j.properties)
More information is available here: https://logging.apache.org/log4j/1.2/manual.html
Convert your x-axis data from text to datetime.datetime
, use datetime.strptime
:
>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
datetime.datetime(2012, 5, 31, 19, 0)
This is an example of how to plot data once you have an array of datetimes:
import matplotlib.pyplot as plt
import datetime
import numpy as np
x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)
plt.plot(x,y)
plt.show()
One other place worth checking: Look in the pom.xml for your project, if you are using Maven compiler plugin, at the source/target config and make sure it is the desired version of Java. I found that I had 1.7 in the following; I changed it to 1.8 and then everything compiled correctly in IntelliJ.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
Which version of .NET are you using? If it's .NET 3.5, I'd just call ToArray()
and be done with it.
If you only have a non-generic IEnumerable, do something like this:
IEnumerable query = ...;
MyEntityType[] array = query.Cast<MyEntityType>().ToArray();
If you don't know the type within that method but the method's callers do know it, make the method generic and try this:
public static void T[] PerformQuery<T>()
{
IEnumerable query = ...;
T[] array = query.Cast<T>().ToArray();
return array;
}
I always use this code below for more readable
$('table').append([
'<tr>',
'<td>My Item 1</td>',
'<td>My Item 2</td>',
'<td>My Item 3</td>',
'<td>My Item 4</td>',
'</tr>'
].join(''));
or if it have tbody
$('table').find('tbody').append([
'<tr>',
'<td>My Item 1</td>',
'<td>My Item 2</td>',
'<td>My Item 3</td>',
'<td>My Item 4</td>',
'</tr>'
].join(''));
Regardless of whether its a script, a html file (for a frame, for example), css file, image, whatever, if you dont specify a server/domain the path of the html doc will be the default, so you could do, for example,
<script type=text/javascript src='/dir/jsfile.js'></script>
or
<script type=text/javascript src='../../scripts/jsfile.js'></script>
If you don't provide the server/domain, the path will be relative to either the path of the page or script of the main document's path
I have executed the code in my machine its working for IE and FF also.
function closeSelf(){
// do something
if(condition satisfied){
alert("conditions satisfied, submiting the form.");
document.forms['certform'].submit();
window.close();
}else{
alert("conditions not satisfied, returning to form");
}
}
<form action="/system/wpacert" method="post" enctype="multipart/form-data" name="certform">
<div>Certificate 1: <input type="file" name="cert1"/></div>
<div>Certificate 2: <input type="file" name="cert2"/></div>
<div>Certificate 3: <input type="file" name="cert3"/></div>
// change the submit button to normal button
<div><input type="button" value="Upload" onclick="closeSelf();"/></div>
</form>
You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams>
and you are passing var model = tm.Name.ToList();
name list. You have to pass list of Teams.
You have to pass following model
var model = new List<Teams>();
model.Add(new Teams { Name = new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name = new List<string>(){"John","XYZ"} });
return View(model);
Updated version of answer by Daniel Krom above:
extension UIView {
func bindToKeyboard() {
NotificationCenter.default.addObserver(
self,
selector: #selector(UIView.keyboardWillChange(notification:)),
name: UIResponder.keyboardWillChangeFrameNotification,
object: nil
)
}
func unbindToKeyboard() {
NotificationCenter.default.removeObserver(
self,
name: UIResponder.keyboardWillChangeFrameNotification,
object: nil
)
}
@objc func keyboardWillChange(notification: Notification) {
let duration = notification.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
let curve = notification.userInfo![UIResponder.keyboardAnimationCurveUserInfoKey] as! UInt
let curFrame = (notification.userInfo![UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let targetFrame = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let deltaY = targetFrame.origin.y - curFrame.origin.y
UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIView.KeyframeAnimationOptions(rawValue: curve), animations: {
self.frame.origin.y += deltaY
})
}
}
I understand using a global variable is sometimes the most convenient thing to do, especially in cases where usage of class makes the easiest thing so much harder (e.g., multiprocessing
). I ran into the same problem with declaring global variables and figured it out with some experiments.
The reason that g_c
was not changed by the run
function within your class is that the referencing to the global name within g_c
was not established precisely within the function. The way Python handles global declaration is in fact quite tricky. The command global g_c
has two effects:
Preconditions the entrance of the key "g_c"
into the dictionary accessible by the built-in function, globals()
. However, the key will not appear in the dictionary until after a value is assigned to it.
(Potentially) alters the way Python looks for the variable g_c
within the current method.
The full understanding of (2) is particularly complex. First of all, it only potentially alters, because if no assignment to the name g_c
occurs within the method, then Python defaults to searching for it among the globals()
. This is actually a fairly common thing, as is the case of referencing within a method modules that are imported all the way at the beginning of the code.
However, if an assignment command occurs anywhere within the method, Python defaults to finding the name g_c
within local variables. This is true even when a referencing occurs before an actual assignment, which will lead to the classic error:
UnboundLocalError: local variable 'g_c' referenced before assignment
Now, if the declaration global g_c
occurs anywhere within the method, even after any referencing or assignment, then Python defaults to finding the name g_c
within global variables. However, if you are feeling experimentative and place the declaration after a reference, you will be rewarded with a warning:
SyntaxWarning: name 'g_c' is used prior to global declaration
If you think about it, the way the global declaration works in Python is clearly woven into and consistent with how Python normally works. It's just when you actually want a global variable to work, the norm becomes annoying.
Here is a code that summarizes what I just said (with a few more observations):
g_c = 0
print ("Initial value of g_c: " + str(g_c))
print("Variable defined outside of method automatically global? "
+ str("g_c" in globals()))
class TestClass():
def direct_print(self):
print("Directly printing g_c without declaration or modification: "
+ str(g_c))
#Without any local reference to the name
#Python defaults to search for the variable in globals()
#This of course happens for all the module names you import
def mod_without_dec(self):
g_c = 1
#A local assignment without declaring reference to global variable
#makes Python default to access local name
print ("After mod_without_dec, local g_c=" + str(g_c))
print ("After mod_without_dec, global g_c=" + str(globals()["g_c"]))
def mod_with_late_dec(self):
g_c = 2
#Even with a late declaration, the global variable is accessed
#However, a syntax warning will be issued
global g_c
print ("After mod_with_late_dec, local g_c=" + str(g_c))
print ("After mod_with_late_dec, global g_c=" + str(globals()["g_c"]))
def mod_without_dec_error(self):
try:
print("This is g_c" + str(g_c))
except:
print("Error occured while accessing g_c")
#If you try to access g_c without declaring it global
#but within the method you also alter it at some point
#then Python will not search for the name in globals()
#!!!!!Even if the assignment command occurs later!!!!!
g_c = 3
def sound_practice(self):
global g_c
#With correct declaration within the method
#The local name g_c becomes an alias for globals()["g_c"]
g_c = 4
print("In sound_practice, the name g_c points to: " + str(g_c))
t = TestClass()
t.direct_print()
t.mod_without_dec()
t.mod_with_late_dec()
t.mod_without_dec_error()
t.sound_practice()
The angular.forEach()
will iterate through your json
object.
First iteration,
key = 0, value = { "name" : "Thomas", "password" : "thomasTheKing"}
Second iteration,
key = 1, value = { "name" : "Linda", "password" : "lindatheQueen" }
To get the value of your name
, you can use value.name
or value["name"]
. Same with your password
, you use value.password
or value["password"]
.
The code below will give you what you want:
angular.forEach(json, function (value, key)
{
//console.log(key);
//console.log(value);
if (value.password == "thomasTheKing") {
console.log("username is thomas");
}
});
After making no changes to a production server we began receiving this error. After trying several different things and thinking that perhaps there were DNS issues, restarting IIS fixed the issue (restarting only the site did not fix the issue). It likely won't work for everyone but if we tried that first it would have saved a lot of time.
If your grep supports -R
, do:
grep -R 'string' dir/
If not, then use find
:
find dir/ -type f -exec grep -H 'string' {} +
overrides:
- files: *-tests.js
rules:
no-param-reassign: 0
You can also set a specific env for a folder, like this :
overrides:
- files: test/*-tests.js
env:
mocha: true
This configuration will fix error message about describe
and it
not defined, only for your test folder:
/myproject/test/init-tests.js
6:1 error 'describe' is not defined no-undef
9:3 error 'it' is not defined no-undef
Step 1:
select object_name, s.sid, s.serial#, p.spid
from v$locked_object l, dba_objects o, v$session s, v$process p
where l.object_id = o.object_id and l.session_id = s.sid and s.paddr = p.addr;
Step 2:
alter system kill session 'sid,serial#'; --`sid` and `serial#` get from step 1
More info: http://www.oracle-base.com/articles/misc/killing-oracle-sessions.php
The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:
XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
where xml2.Element("ID").Value == variable
select xml2).FirstOrDefault();
This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.
Marc
One important point that people forget to mention is the life time of the Broadcast Receiver
. The difference of programmatically registering it from registering in AndroidManifest.xml is that. In the manifest file, it doesn't depend on application life time. While when programmatically registering it it does depend on the application life time. This means that if you register in AndroidManifest.xml, you can catch the broadcasted intents even when your application is not running.
Edit: The mentioned note is no longer true as of Android 3.1, the Android system excludes all receiver from receiving intents by default if the corresponding application has never been started by the user or if the user explicitly stopped the application via the Android menu (in Manage ? Application). https://developer.android.com/about/versions/android-3.1.html
This is an additional security feature as the user can be sure that only the applications he started will receive broadcast intents.
So it can be understood as receivers programmatically registered in Application's onCreate()
would have same effect with ones declared in AndroidManifest.xml from Android 3.1 above.
There are a couple things going on with your example. You have a list containing a string of numbers and newline characters:
list = ['350882 348521 350166\r\n']
And you are trying to find a number ID within this list:
id = 348521
if id not in list:
...
Your first conditional is always going to pass, because it will be looking for integer 348521
in list
which has one element at index list[0]
with the string value of '350882 348521 350166\r\n'
, so integer 348521 will be added to that list, making it a list of two elements: a string and an integer, as your output shows.
To reiterate: list is searched for id, not the string in list's first element.
If you were trying to find if the string representation of '348521'
was contained within the larger string contained within your list, you could do the following, noting that you would need to do this for each element in list
:
if str(id) not in list[0]: # list[0]: '350882 348521 350166\r\n'
... # ^^^^^^
However be aware that you would need to wrap str(id)
with whitespace for the search, otherwise it would also match:
2348521999
^^^^^^
It is unclear whether you want your "list" to be a "string of integers separated by whitespace" or if you really want a list of integers.
If all you are trying to accomplish is to have a list of IDs, and to add IDs to that list only if they are not already contained, (and if the order of the elements in the list is not important,) then a set would be the best data structure to use.
ids = set(
[int(id) for id in '350882 348521 350166\r\n'.strip().split(' ')]
)
# Adding an ID already in the set has no effect
ids.add(348521)
If the ordering of the IDs in the string is important then I would keep your IDs in a standard list and use your conditional check:
ids = [int(id) for id in '350882 348521 350166\r\n'.strip().split(' ')]
if 348521 not in ids:
...
var employee = (from res in _db.EMPLOYEEs
where (res.EMAIL == givenInfo || res.USER_NAME == givenInfo)
select new {res.EMAIL, res.USERNAME} );
OR you can use
var employee = (from res in _db.EMPLOYEEs
where (res.EMAIL == givenInfo || res.USER_NAME == givenInfo)
select new {email=res.EMAIL, username=res.USERNAME} );
Explanation :
Select employee from the db as res.
Filter the employee details as per the where condition.
Select required fields from the employee object by creating an Anonymous object using new { }
It's quite simple actually if you're using PostgreSQL, just use distinct(columns)
(documentation).
Productorder.objects.all().distinct('category')
Note that this feature has been included in Django since 1.4
ArrayList
inherits its toString()
-method from AbstractCollection
, ie:
public String toString() {
Iterator<E> i = iterator();
if (! i.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = i.next();
sb.append(e == this ? "(this Collection)" : e);
if (! i.hasNext())
return sb.append(']').toString();
sb.append(", ");
}
}
Building the string yourself will be far more efficient.
If you really want to aggregate the strings beforehand in some sort of List, you should provide your own method to efficiently join them, e.g. like this:
static String join(Collection<?> items, String sep) {
if(items.size() == 0)
return "";
String[] strings = new String[items.size()];
int length = sep.length() * (items.size() - 1);
int idx = 0;
for(Object item : items) {
String str = item.toString();
strings[idx++] = str;
length += str.length();
}
char[] chars = new char[length];
int pos = 0;
for(String str : strings) {
str.getChars(0, str.length(), chars, pos);
pos += str.length();
if(pos < length) {
sep.getChars(0, sep.length(), chars, pos);
pos += sep.length();
}
}
return new String(chars);
}
these methods can help setTitle("your new title"); or super("your new title");
I had the same problem. At least I could solve it with this:
sudo yum install gcc gcc-c++
Hope it solves your problem too.
The main issue with 301 is browser will cache the redirection even if you disabled the redirection from the server level.
Its always better to use 302 if you are enabling the redirection for a short maintenance window.
SELECT CONVERT(nvarchar(6), GETDATE(), 112)
Late one but hopefully useful since it adds more details…
There is no way to see queries executed in SSMS by default. There are several options though.
Reading transaction log – this is not an easy thing to do because its in proprietary format. However if you need to see queries that were executed historically (except SELECT) this is the only way.
You can use third party tools for this such as ApexSQL Log and SQL Log Rescue (free but SQL 2000 only). Check out this thread for more details here SQL Server Transaction Log Explorer/Analyzer
SQL Server profiler – best suited if you just want to start auditing and you are not interested in what happened earlier. Make sure you use filters to select only transactions you need. Otherwise you’ll end up with ton of data very quickly.
SQL Server trace - best suited if you want to capture all or most commands and keep them in trace file that can be parsed later.
Triggers – best suited if you want to capture DML (except select) and store these somewhere in the database
Embed this code in your css.
::-webkit-scrollbar {
width: 0px;
}
/* Track */
::-webkit-scrollbar-track {
-webkit-box-shadow: none;
}
/* Handle */
::-webkit-scrollbar-thumb {
background: white;
-webkit-box-shadow: none;
}
::-webkit-scrollbar-thumb:window-inactive {
background: none;
}
Starting from Oracle 12.2, you don't need the TABLE
function, you can directly select from the built-in collection.
SQL> select * FROM sys.odcinumberlist(5,2,6,3,78);
COLUMN_VALUE
------------
5
2
6
3
78
SQL> select * FROM sys.odcivarchar2list('A','B','C','D');
COLUMN_VALUE
------------
A
B
C
D
Underlying cause:
Content scripts are executed in an "isolated world" environment.
Solution::
To access functions/variables of the page context ("main world") you have to inject the code into the page itself using DOM. Same thing if you want to expose your functions/variables to the page context (in your case it's the state()
method).
Note in case communication with the page script is needed:
Use DOM CustomEvent
handler. Examples: one, two, and three.
Note in case chrome
API is needed in the page script:
Since chrome.*
APIs can't be used in the page script, you have to use them in the content script and send the results to the page script via DOM messaging (see the note above).
Safety warning:
A page may redefine or augment/hook a built-in prototype so your exposed code may fail if the page did it in an incompatible fashion. If you want to make sure your exposed code runs in a safe environment then you should either a) declare your content script with "run_at": "document_start" and use Methods 2-3 not 1, or b) extract the original native built-ins via an empty iframe, example. Note that with document_start
you may need to use DOMContentLoaded
event inside the exposed code to wait for DOM.
This is the easiest/best method when you have lots of code. Include your actual JS code in a file within your extension, say script.js
. Then let your content script be as follows (explained here: Google Chome “Application Shortcut” Custom Javascript):
var s = document.createElement('script');
// TODO: add "script.js" to web_accessible_resources in manifest.json
s.src = chrome.runtime.getURL('script.js');
s.onload = function() {
this.remove();
};
(document.head || document.documentElement).appendChild(s);
Note: For security reasons, Chrome prevents loading of js files. Your file must be added as a "web_accessible_resources"
item (example) :
// manifest.json must include:
"web_accessible_resources": ["script.js"],
If not, the following error will appear in the console:
Denying load of chrome-extension://[EXTENSIONID]/script.js. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.
This method is useful when you want to quickly run a small piece of code. (See also: How to disable facebook hotkeys with Chrome extension?).
var actualCode = `// Code here.
// If you want to use a variable, use $ and curly braces.
// For example, to use a fixed random number:
var someFixedRandomValue = ${ Math.random() };
// NOTE: Do not insert unsafe variables in this way, see below
// at "Dynamic values in the injected code"
`;
var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.remove();
Note: template literals are only supported in Chrome 41 and above. If you want the extension to work in Chrome 40-, use:
var actualCode = ['/* Code here. Example: */' + 'alert(0);',
'// Beware! This array have to be joined',
'// using a newline. Otherwise, missing semicolons',
'// or single-line comments (//) will mess up your',
'// code ----->'].join('\n');
For a big chunk of code, quoting the string is not feasible. Instead of using an array, a function can be used, and stringified:
var actualCode = '(' + function() {
// All code is executed in a local scope.
// For example, the following does NOT overwrite the global `alert` method
var alert = null;
// To overwrite a global variable, prefix `window`:
window.alert = null;
} + ')();';
var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.remove();
This method works, because the +
operator on strings and a function converts all objects to a string. If you intend on using the code more than once, it's wise to create a function to avoid code repetition. An implementation might look like:
function injectScript(func) {
var actualCode = '(' + func + ')();'
...
}
injectScript(function() {
alert("Injected script");
});
Note: Since the function is serialized, the original scope, and all bound properties are lost!
var scriptToInject = function() {
console.log(typeof scriptToInject);
};
injectScript(scriptToInject);
// Console output: "undefined"
Sometimes, you want to run some code immediately, e.g. to run some code before the <head>
element is created. This can be done by inserting a <script>
tag with textContent
(see method 2/2b).
An alternative, but not recommended is to use inline events. It is not recommended because if the page defines a Content Security policy that forbids inline scripts, then inline event listeners are blocked. Inline scripts injected by the extension, on the other hand, still run. If you still want to use inline events, this is how:
var actualCode = '// Some code example \n' +
'console.log(document.documentElement.outerHTML);';
document.documentElement.setAttribute('onreset', actualCode);
document.documentElement.dispatchEvent(new CustomEvent('reset'));
document.documentElement.removeAttribute('onreset');
Note: This method assumes that there are no other global event listeners that handle the reset
event. If there is, you can also pick one of the other global events. Just open the JavaScript console (F12), type document.documentElement.on
, and pick on of the available events.
Occasionally, you need to pass an arbitrary variable to the injected function. For example:
var GREETING = "Hi, I'm ";
var NAME = "Rob";
var scriptToInject = function() {
alert(GREETING + NAME);
};
To inject this code, you need to pass the variables as arguments to the anonymous function. Be sure to implement it correctly! The following will not work:
var scriptToInject = function (GREETING, NAME) { ... };
var actualCode = '(' + scriptToInject + ')(' + GREETING + ',' + NAME + ')';
// The previous will work for numbers and booleans, but not strings.
// To see why, have a look at the resulting string:
var actualCode = "(function(GREETING, NAME) {...})(Hi, I'm ,Rob)";
// ^^^^^^^^ ^^^ No string literals!
The solution is to use JSON.stringify
before passing the argument. Example:
var actualCode = '(' + function(greeting, name) { ...
} + ')(' + JSON.stringify(GREETING) + ',' + JSON.stringify(NAME) + ')';
If you have many variables, it's worthwhile to use JSON.stringify
once, to improve readability, as follows:
...
} + ')(' + JSON.stringify([arg1, arg2, arg3, arg4]) + ')';
For macOS Mojave , additional configuration was required, for compilers to find openssl you may need to set:
export LDFLAGS="-L/usr/local/opt/openssl/lib"
export CPPFLAGS="-I/usr/local/opt/openssl/include"
The reason I think is that ProgressDialog
is attached to the activity that props up the ProgressDialog
as the dialog cannot remain after the activity gets destroyed so it needs to be passed this
(ActivityContext) that also gets destroyed with the activity whereas the ApplicationContext remains even after the activity gets destroyed.
where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS')
should work.
in Angular 2.x.x , 4, 5 ...
<form #loginForm="ngForm">
<input type="text" required>
<button type="submit" [disabled]="loginForm.form.invalid">Submit</button>
</form>
SELECT rowInt, Value,
COALESCE(
(
SELECT TOP 1 Value
FROM myTable mi
WHERE mi.rowInt > m.rowInt
ORDER BY
rowInt
), 0) - Value AS diff
FROM myTable m
ORDER BY
rowInt
To do a cross server query, check out the system stored procedure: sp_addlinkedserver in the help files.
Once the server is linked you can run a query against it.
just add this code in .vscode/settings.json file
,"python.linting.pylintPath": "venv/bin/pylint"
This will notify the location of pylint(which is an error checker for python)
I tested JonVD's code, but found it was very slow, 6s.
This code took 0s.
SELECT TOP(5) ORDERID, CUSTOMERID, OrderDate
FROM Orders where EmployeeID=5
Order By OrderDate DESC
Check this
double[] myarray = ...;
System.out.println(myarray[myarray.length-1]); //last
System.out.println(myarray[0]); //first
select * from table where
(dtColumn between #3/1/2009# and #3/31/2009#) and
(hour(dtColumn) between 6 and 22) and
(weekday(dtColumn, 1) between 2 and 4)
To get selected item, you have to use SELECTEDITEM property of comboBox. And since this is an Object, if you wanna assign it to a string, you have to convert it to string, by using ToString() method:
string myItem = comboBox1.SelectedItem.ToString(); //this does the trick
Without Plugin, we can do this; bootstrap multi-level responsive menu for mobile phone with slide toggle for mobile:
$('[data-toggle="slide-collapse"]').on('click', function() {_x000D_
$navMenuCont = $($(this).data('target'));_x000D_
$navMenuCont.animate({_x000D_
'width': 'toggle'_x000D_
}, 350);_x000D_
$(".menu-overlay").fadeIn(500);_x000D_
});_x000D_
_x000D_
$(".menu-overlay").click(function(event) {_x000D_
$(".navbar-toggle").trigger("click");_x000D_
$(".menu-overlay").fadeOut(500);_x000D_
});_x000D_
_x000D_
// if ($(window).width() >= 767) {_x000D_
// $('ul.nav li.dropdown').hover(function() {_x000D_
// $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
// }, function() {_x000D_
// $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
// });_x000D_
_x000D_
// $('ul.nav li.dropdown-submenu').hover(function() {_x000D_
// $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
// }, function() {_x000D_
// $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
// });_x000D_
_x000D_
_x000D_
// $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
// event.preventDefault();_x000D_
// event.stopPropagation();_x000D_
// $(this).parent().siblings().removeClass('open');_x000D_
// $(this).parent().toggleClass('open');_x000D_
// $('b', this).toggleClass("caret caret-up");_x000D_
// });_x000D_
// }_x000D_
_x000D_
// $(window).resize(function() {_x000D_
// if( $(this).width() >= 767) {_x000D_
// $('ul.nav li.dropdown').hover(function() {_x000D_
// $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
// }, function() {_x000D_
// $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
// });_x000D_
// }_x000D_
// });_x000D_
_x000D_
var windowWidth = $(window).width();_x000D_
if (windowWidth > 767) {_x000D_
// $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
// event.preventDefault();_x000D_
// event.stopPropagation();_x000D_
// $(this).parent().siblings().removeClass('open');_x000D_
// $(this).parent().toggleClass('open');_x000D_
// $('b', this).toggleClass("caret caret-up");_x000D_
// });_x000D_
_x000D_
$('ul.nav li.dropdown').hover(function() {_x000D_
$(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
}, function() {_x000D_
$(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
});_x000D_
_x000D_
$('ul.nav li.dropdown-submenu').hover(function() {_x000D_
$(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
}, function() {_x000D_
$(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
});_x000D_
_x000D_
_x000D_
$('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
event.preventDefault();_x000D_
event.stopPropagation();_x000D_
$(this).parent().siblings().removeClass('open');_x000D_
$(this).parent().toggleClass('open');_x000D_
// $('b', this).toggleClass("caret caret-up");_x000D_
});_x000D_
}_x000D_
if (windowWidth < 767) {_x000D_
$('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
event.preventDefault();_x000D_
event.stopPropagation();_x000D_
$(this).parent().siblings().removeClass('open');_x000D_
$(this).parent().toggleClass('open');_x000D_
// $('b', this).toggleClass("caret caret-up");_x000D_
});_x000D_
}_x000D_
_x000D_
// $('.dropdown a').append('Some text');
_x000D_
@media only screen and (max-width: 767px) {_x000D_
#slide-navbar-collapse {_x000D_
position: fixed;_x000D_
top: 0;_x000D_
left: 15px;_x000D_
z-index: 999999;_x000D_
width: 280px;_x000D_
height: 100%;_x000D_
background-color: #f9f9f9;_x000D_
overflow: auto;_x000D_
bottom: 0;_x000D_
max-height: inherit;_x000D_
}_x000D_
.menu-overlay {_x000D_
display: none;_x000D_
background-color: #000;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
opacity: 0.5;_x000D_
filter: alpha(opacity=50);_x000D_
/* IE7 & 8 */_x000D_
position: fixed;_x000D_
right: 0;_x000D_
top: 0;_x000D_
z-index: 49;_x000D_
}_x000D_
.navbar-fixed-top {_x000D_
position: initial !important;_x000D_
}_x000D_
.navbar-nav .open .dropdown-menu {_x000D_
background-color: #ffffff;_x000D_
}_x000D_
ul.nav.navbar-nav li {_x000D_
border-bottom: 1px solid #eee;_x000D_
}_x000D_
.navbar-nav .open .dropdown-menu .dropdown-header,_x000D_
.navbar-nav .open .dropdown-menu>li>a {_x000D_
padding: 10px 20px 10px 15px;_x000D_
}_x000D_
}_x000D_
_x000D_
.dropdown-submenu {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.dropdown-submenu .dropdown-menu {_x000D_
top: 0;_x000D_
left: 100%;_x000D_
margin-top: -1px;_x000D_
}_x000D_
_x000D_
li.dropdown a {_x000D_
display: block;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
li.dropdown>a:before {_x000D_
content: "\f107";_x000D_
font-family: FontAwesome;_x000D_
position: absolute;_x000D_
right: 6px;_x000D_
top: 5px;_x000D_
font-size: 15px;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu>a:before {_x000D_
content: "\f107";_x000D_
font-family: FontAwesome;_x000D_
position: absolute;_x000D_
right: 6px;_x000D_
top: 10px;_x000D_
font-size: 15px;_x000D_
}_x000D_
_x000D_
ul.dropdown-menu li {_x000D_
border-bottom: 1px solid #eee;_x000D_
}_x000D_
_x000D_
.dropdown-menu {_x000D_
padding: 0px;_x000D_
margin: 0px;_x000D_
border: none !important;_x000D_
}_x000D_
_x000D_
li.dropdown.open {_x000D_
border-bottom: 0px !important;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu.open {_x000D_
border-bottom: 0px !important;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu>a {_x000D_
font-weight: bold !important;_x000D_
}_x000D_
_x000D_
li.dropdown>a {_x000D_
font-weight: bold !important;_x000D_
}_x000D_
_x000D_
.navbar-default .navbar-nav>li>a {_x000D_
font-weight: bold !important;_x000D_
padding: 10px 20px 10px 15px;_x000D_
}_x000D_
_x000D_
li.dropdown>a:before {_x000D_
content: "\f107";_x000D_
font-family: FontAwesome;_x000D_
position: absolute;_x000D_
right: 6px;_x000D_
top: 9px;_x000D_
font-size: 15px;_x000D_
}_x000D_
_x000D_
@media (min-width: 767px) {_x000D_
li.dropdown-submenu>a {_x000D_
padding: 10px 20px 10px 15px;_x000D_
}_x000D_
li.dropdown>a:before {_x000D_
content: "\f107";_x000D_
font-family: FontAwesome;_x000D_
position: absolute;_x000D_
right: 3px;_x000D_
top: 12px;_x000D_
font-size: 15px;_x000D_
}_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
<title>Bootstrap Example</title>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<nav class="navbar navbar-default navbar-fixed-top">_x000D_
<div class="container-fluid">_x000D_
<!-- Brand and toggle get grouped for better mobile display -->_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle collapsed" data-toggle="slide-collapse" data-target="#slide-navbar-collapse" aria-expanded="false">_x000D_
<span class="sr-only">Toggle navigation</span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">Brand</a>_x000D_
</div>_x000D_
<!-- Collect the nav links, forms, and other content for toggling -->_x000D_
<div class="collapse navbar-collapse" id="slide-navbar-collapse">_x000D_
<ul class="nav navbar-nav">_x000D_
<li><a href="#">Link <span class="sr-only">(current)</span></a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
<li class="dropdown">_x000D_
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</span></a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#">Action</a></li>_x000D_
<li><a href="#">Another action</a></li>_x000D_
<li><a href="#">Something else here</a></li>_x000D_
<li><a href="#">Separated link</a></li>_x000D_
<li><a href="#">One more separated link</a></li>_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" data-toggle="dropdown">SubMenu 1</span></a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#">3rd level dropdown</a></li>_x000D_
<li><a href="#">3rd level dropdown</a></li>_x000D_
<li><a href="#">3rd level dropdown</a></li>_x000D_
<li><a href="#">3rd level dropdown</a></li>_x000D_
<li><a href="#">3rd level dropdown</a></li>_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" data-toggle="dropdown">SubMenu 2</span></a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#">3rd level dropdown</a></li>_x000D_
<li><a href="#">3rd level dropdown</a></li>_x000D_
<li><a href="#">3rd level dropdown</a></li>_x000D_
<li><a href="#">3rd level dropdown</a></li>_x000D_
<li><a href="#">3rd level dropdown</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">Link</a></li>_x000D_
</ul>_x000D_
<ul class="nav navbar-nav navbar-right">_x000D_
<li><a href="#">Link</a></li>_x000D_
<li class="dropdown">_x000D_
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</span></a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#">Action</a></li>_x000D_
<li><a href="#">Another action</a></li>_x000D_
<li><a href="#">Something else here</a></li>_x000D_
<li><a href="#">Separated link</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<!-- /.navbar-collapse -->_x000D_
</div>_x000D_
<!-- /.container-fluid -->_x000D_
</nav>_x000D_
<div class="menu-overlay"></div>_x000D_
<div class="col-md-12">_x000D_
<h1>Resize the window to see the result</h1>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
</p>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
</p>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
</p>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
</p>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
</p>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
As suggested on the Chrome Mobile Emulation page, you can use Clumsy on Windows, Network Link Conditioner on Mac OS X and dummynet on Linux.
Just a poke, but here's another way to write FizzBuzz :) 100 rows is enough to show the WITH statement, I reckon.
;WITH t100 AS (
SELECT n=number
FROM master..spt_values
WHERE type='P' and number between 1 and 100
)
SELECT
ISNULL(NULLIF(
CASE WHEN n % 3 = 0 THEN 'Fizz' Else '' END +
CASE WHEN n % 5 = 0 THEN 'Buzz' Else '' END, ''), RIGHT(n,3))
FROM t100
But the real power behind WITH (known as Common Table Expression http://msdn.microsoft.com/en-us/library/ms190766.aspx "CTE") in SQL Server 2005 and above is the Recursion, as below where the table is built up through iterations adding to the virtual-table each time.
;WITH t100 AS (
SELECT n=1
union all
SELECT n+1
FROM t100
WHERE n < 100
)
SELECT
ISNULL(NULLIF(
CASE WHEN n % 3 = 0 THEN 'Fizz' Else '' END +
CASE WHEN n % 5 = 0 THEN 'Buzz' Else '' END, ''), RIGHT(n,3))
FROM t100
To run a similar query in all database, you can use the undocumented sp_msforeachdb. It has been mentioned in another answer, but it is sp_msforeachdb, not sp_foreachdb.
Be careful when using it though, as some things are not what you expect. Consider this example
exec sp_msforeachdb 'select count(*) from sys.objects'
Instead of the counts of objects within each DB, you will get the SAME count reported, begin that of the current DB. To get around this, always "use" the database first. Note the square brackets to qualify multi-word database names.
exec sp_msforeachdb 'use [?]; select count(*) from sys.objects'
For your specific query about populating a tally table, you can use something like the below. Not sure about the DATE column, so this tally table has only the DBNAME and IMG_COUNT columns, but hope it helps you.
create table #tbl (dbname sysname, img_count int);
exec sp_msforeachdb '
use [?];
if object_id(''tbldoc'') is not null
insert #tbl
select ''?'', count(*) from tbldoc'
select * from #tbl
$('[data-poload]').popover({
content: function(){
var div_id = "tmp-id-" + $.now();
return details_in_popup($(this).data('poload'), div_id, $(this));
},
delay: 500,
trigger: 'hover',
html:true
});
function details_in_popup(link, div_id, el){
$.ajax({
url: link,
cache:true,
success: function(response){
$('#'+div_id).html(response);
el.data('bs.popover').options.content = response;
}
});
return '<div id="'+ div_id +'"><i class="fa fa-spinner fa-spin"></i></div>';
}
Ajax content is loaded once! see el.data('bs.popover').options.content = response;
If you would use asp:dropdownlist
you could select it easier by testSelect.Text
.
Now you'd have to do a Request.Form["testSelect"]
to get the value after pressed btnTes
.
Hope it helps.
EDIT: You need to specify a name
of the select (not only ID) to be able to Request.Form["testSelect"]
Antonio's answer
CONCAT(REPLACE(FORMAT(number,0),',','.'),',',SUBSTRING_INDEX(FORMAT(number,2),'.',-1))
is wrong; it may produce incorrect results!
For example, if "number" is 12345.67, the resulting string would be:
'12.346,67'
instead of
'12.345,67'
because FORMAT(number,0) rounds "number" up if fractional part is greater or equal than 0.5 (as it is in my example)!
What you COULD use is
CONCAT(REPLACE(FORMAT(FLOOR(number),0),',','.'),',',SUBSTRING_INDEX(FORMAT(number,2),'.',-1))
if your MySQL/MariaDB's FORMAT doesn't support "locale_name" (see MindStalker's post - Thx 4 that, pal). Note the FLOOR function I've added.
Check this page out: http://matplotlib.org/examples/pylab_examples/subplots_demo.html
plt.subplots
is similar. I think it's better since it's easier to set parameters of the figure. The first two arguments define the layout (in your case 1 row, 2 columns), and other parameters change features such as figure size:
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(5, 3))
axes[0].plot(x1, y1)
axes[1].plot(x2, y2)
fig.tight_layout()