text:
Q: Asynchronously wait for Task to complete with timeout I want to wait for a Task<T> to complete with some special rules:
If it hasn't completed after X milliseconds, I want to display a message to the user.
And if it hasn't completed after Y milliseconds, I want to automatically request cancellation.
I can use Task.ContinueWith to asynchronously wait for the task to complete (i.e. schedule an action to be executed when the task is complete), but that doesn't allow to specify a timeout.
I can use Task.Wait to synchronously wait for the task to complete with a timeout, but that blocks my thread.
How can I asynchronously wait for the task to complete with a timeout?

A: Use a Timer to handle the message and automatic cancellation.  When the Task completes, call Dispose on the timers so that they will never fire.  Here is an example; change taskDelay to 500, 1500, or 2500 to see the different cases:
using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        private static Task CreateTaskWithTimeout(
            int xDelay, int yDelay, int taskDelay)
        {
            var cts = new CancellationTokenSource();
            var token = cts.Token;
            var task = Task.Factory.StartNew(() =>
            {
                // Do some work, but fail if cancellation was requested
                token.WaitHandle.WaitOne(taskDelay);
                token.ThrowIfCancellationRequested();
                Console.WriteLine("Task complete");
            });
            var messageTimer = new Timer(state =>
            {
                // Display message at first timeout
                Console.WriteLine("X milliseconds elapsed");
            }, null, xDelay, -1);
            var cancelTimer = new Timer(state =>
            {
                // Display message and cancel task at second timeout
                Console.WriteLine("Y milliseconds elapsed");
                cts.Cancel();
            }
                , null, yDelay, -1);
            task.ContinueWith(t =>
            {
                // Dispose the timers when the task completes
                // This will prevent the message from being displayed
                // if the task completes before the timeout
                messageTimer.Dispose();
                cancelTimer.Dispose();
            });
            return task;
        }

        static void Main(string[] args)
        {
            var task = CreateTaskWithTimeout(1000, 2000, 2500);
            // The task has been started and will display a message after
            // one timeout and then cancel itself after the second
            // You can add continuations to the task
            // or wait for the result as needed
            try
            {
                task.Wait();
                Console.WriteLine("Done waiting for task");
            }
            catch (AggregateException ex)
            {
                Console.WriteLine("Error waiting for task:");
                foreach (var e in ex.InnerExceptions)
                {
                    Console.WriteLine(e);
                }
            }
        }
    }
}

Also, the Async CTP provides a TaskEx.Delay method that will wrap the timers in tasks for you.  This can give you more control to do things like set the TaskScheduler for the continuation when the Timer fires.
private static Task CreateTaskWithTimeout(
    int xDelay, int yDelay, int taskDelay)
{
    var cts = new CancellationTokenSource();
    var token = cts.Token;
    var task = Task.Factory.StartNew(() =>
    {
        // Do some work, but fail if cancellation was requested
        token.WaitHandle.WaitOne(taskDelay);
        token.ThrowIfCancellationRequested();
        Console.WriteLine("Task complete");
    });

    var timerCts = new CancellationTokenSource();

    var messageTask = TaskEx.Delay(xDelay, timerCts.Token);
    messageTask.ContinueWith(t =>
    {
        // Display message at first timeout
        Console.WriteLine("X milliseconds elapsed");
    }, TaskContinuationOptions.OnlyOnRanToCompletion);

    var cancelTask = TaskEx.Delay(yDelay, timerCts.Token);
    cancelTask.ContinueWith(t =>
    {
        // Display message and cancel task at second timeout
        Console.WriteLine("Y milliseconds elapsed");
        cts.Cancel();
    }, TaskContinuationOptions.OnlyOnRanToCompletion);

    task.ContinueWith(t =>
    {
        timerCts.Cancel();
    });

    return task;
}

A: How about this:
int timeout = 1000;
var task = SomeOperationAsync();
if (await Task.WhenAny(task, Task.Delay(timeout)) == task) {
    // task completed within timeout
} else {
    // timeout logic
}

And here's a great blog post "Crafting a Task.TimeoutAfter Method"  (from MS Parallel Library team) with more info on this sort of thing.
Addition: at the request of a comment on my answer, here is an expanded solution that includes cancellation handling. Note that passing cancellation to the task and the timer means that there are multiple ways cancellation can be experienced in your code, and you should be sure to test for and be confident you properly handle all of them. Don't leave to chance various combinations and hope your computer does the right thing at runtime.
int timeout = 1000;
var task = SomeOperationAsync(cancellationToken);
if (await Task.WhenAny(task, Task.Delay(timeout, cancellationToken)) == task)
{
    // Task completed within timeout.
    // Consider that the task may have faulted or been canceled.
    // We re-await the task so that any exceptions/cancellation is rethrown.
    await task;

}
else
{
    // timeout/cancellation logic
}

A: With .Net 6 (preview 7 as the date of this answer), it is possible to use the new WaitAsync(TimeSpan, CancellationToken) which answers to this particular need.
If you can use .Net6, this version is moreover described to be optimized if we compare to the majority of good solutions proposed in this posts.
(Thanks for all participants because I used your solution for years)

A: Another way of solving this problem is using Reactive Extensions:
public static Task TimeoutAfter(this Task task, TimeSpan timeout, IScheduler scheduler)
{
        return task.ToObservable().Timeout(timeout, scheduler).ToTask();
}

Test up above using below code in your unit test, it works for me
TestScheduler scheduler = new TestScheduler();
Task task = Task.Run(() =>
                {
                    int i = 0;
                    while (i < 5)
                    {
                        Console.WriteLine(i);
                        i++;
                        Thread.Sleep(1000);
                    }
                })
                .TimeoutAfter(TimeSpan.FromSeconds(5), scheduler)
                .ContinueWith(t => { }, TaskContinuationOptions.OnlyOnFaulted);

scheduler.AdvanceBy(TimeSpan.FromSeconds(6).Ticks);

You may need the following namespace:
using System.Threading.Tasks;
using System.Reactive.Subjects;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using Microsoft.Reactive.Testing;
using System.Threading;
using System.Reactive.Concurrency;

A: From .Net 6 (Preview 7) or later, there is a new build-in method Task.WaitAsync to achieve this.
// Using TimeSpan
await myTask.WaitAsync(TimeSpan.FromSeconds(10));

// Using CancellationToken
await myTask.WaitAsync(cancellationToken);

// Using both TimeSpan and CancellationToken
await myTask.WaitAsync(TimeSpan.FromSeconds(10), cancellationToken);

If the task isn't finished before the TimeSpan or CancellationToken then it throws TimeoutException or TaskCanceledException respectively
try
{
    await myTask.WaitAsync(TimeSpan.FromSeconds(10), cancellationToken);

}
catch (TaskCanceledException)
{
    Console.WriteLine("Task didn't get finished before the `CancellationToken`");
}
catch (TimeoutException)
{
    Console.WriteLine("Task didn't get finished before the `TimeSpan`");
}

A: You can use Task.WaitAny to wait the first of multiple tasks.
You could create two additional tasks (that complete after the specified timeouts) and then use WaitAny to wait for whichever completes first. If the task that completed first is your "work" task, then you're done. If the task that completed first is a timeout task, then you can react to the timeout (e.g. request cancellation).

A: A generic version of @Kevan's answer above, using Reactive Extensions.
public static Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout, IScheduler scheduler)
{
    return task.ToObservable().Timeout(timeout, scheduler).ToTask();
}

With optional Scheduler:
public static Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout, Scheduler scheduler = null)
{
    return scheduler is null
       ? task.ToObservable().Timeout(timeout).ToTask()
       : task.ToObservable().Timeout(timeout, scheduler).ToTask();
}

BTW: When a Timeout happens, a timeout exception will be thrown

A: For the fun of it I made a 'OnTimeout' extension to Task. On timeout Task executes the desired inline lambda Action() and returns true, otherwise false.
public static async Task<bool> OnTimeout<T>(this T t, Action<T> action, int waitms) where T : Task
{
    if (!(await Task.WhenAny(t, Task.Delay(waitms)) == t))
    {
        action(t);
        return true;
    } else {
        return false;
    }
}

The OnTimeout extension returns a bool result that can be assigned to a variable like in this example calling an UDP socket Async:
var t = UdpSocket.ReceiveAsync();

var timeout = await t.OnTimeout(task => {
    Console.WriteLine("No Response");
}, 5000);

The 'task' variable is accessible in the timeout lambda for more processing.
The use of Action receiving an object may inspire to various other extension designs.

A: Here's a extension method version that incorporates cancellation of the timeout when the original task completes as suggested by Andrew Arnott in a comment to his answer.
public static async Task<TResult> TimeoutAfter<TResult>(this Task<TResult> task, TimeSpan timeout) {

    using (var timeoutCancellationTokenSource = new CancellationTokenSource()) {

        var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
        if (completedTask == task) {
            timeoutCancellationTokenSource.Cancel();
            return await task;  // Very important in order to propagate exceptions
        } else {
            throw new TimeoutException("The operation has timed out.");
        }
    }
}

A: This is a slightly enhanced version of previous answers.

*

*In addition to Lawrence's answer, it cancels the original task when timeout occurs.

*In addtion to sjb's answer variants 2 and 3, you can provide CancellationToken for the original task, and when timeout occurs, you get TimeoutException instead of OperationCanceledException.

async Task<TResult> CancelAfterAsync<TResult>(
    Func<CancellationToken, Task<TResult>> startTask,
    TimeSpan timeout, CancellationToken cancellationToken)
{
    using (var timeoutCancellation = new CancellationTokenSource())
    using (var combinedCancellation = CancellationTokenSource
        .CreateLinkedTokenSource(cancellationToken, timeoutCancellation.Token))
    {
        var originalTask = startTask(combinedCancellation.Token);
        var delayTask = Task.Delay(timeout, timeoutCancellation.Token);
        var completedTask = await Task.WhenAny(originalTask, delayTask);
        // Cancel timeout to stop either task:
        // - Either the original task completed, so we need to cancel the delay task.
        // - Or the timeout expired, so we need to cancel the original task.
        // Canceling will not affect a task, that is already completed.
        timeoutCancellation.Cancel();
        if (completedTask == originalTask)
        {
            // original task completed
            return await originalTask;
        }
        else
        {
            // timeout
            throw new TimeoutException();
        }
    }
}

Usage
InnerCallAsync may take a long time to complete. CallAsync wraps it with a timeout.
async Task<int> CallAsync(CancellationToken cancellationToken)
{
    var timeout = TimeSpan.FromMinutes(1);
    int result = await CancelAfterAsync(ct => InnerCallAsync(ct), timeout,
        cancellationToken);
    return result;
}

async Task<int> InnerCallAsync(CancellationToken cancellationToken)
{
    return 42;
}

A: Using Stephen Cleary's excellent AsyncEx library, you can do:
TimeSpan timeout = TimeSpan.FromSeconds(10);

using (var cts = new CancellationTokenSource(timeout))
{
    await myTask.WaitAsync(cts.Token);
}

TaskCanceledException will be thrown in the event of a timeout.

A: Create a extension to wait for the task or a delay to complete, whichever comes first. Throw an exception if the delay wins.
public static async Task<TResult> WithTimeout<TResult>(this Task<TResult> task, TimeSpan timeout)
{
    if (await Task.WhenAny(task, Task.Delay(timeout)) != task)
        throw new TimeoutException();
    return await task;
}

A: Here is a fully worked example based on the top voted answer, which is:
int timeout = 1000;
var task = SomeOperationAsync();
if (await Task.WhenAny(task, Task.Delay(timeout)) == task) {
    // task completed within timeout
} else {
    // timeout logic
}

The main advantage of the implementation in this answer is that generics have been added, so the function (or task) can return a value. This means that any existing function can be wrapped in a timeout function, e.g.:
Before:
int x = MyFunc();

After:
// Throws a TimeoutException if MyFunc takes more than 1 second
int x = TimeoutAfter(MyFunc, TimeSpan.FromSeconds(1));

This code requires .NET 4.5.
using System;
using System.Threading;
using System.Threading.Tasks;

namespace TaskTimeout
{
    public static class Program
    {
        /// <summary>
        ///     Demo of how to wrap any function in a timeout.
        /// </summary>
        private static void Main(string[] args)
        {

            // Version without timeout.
            int a = MyFunc();
            Console.Write("Result: {0}\n", a);
            // Version with timeout.
            int b = TimeoutAfter(() => { return MyFunc(); },TimeSpan.FromSeconds(1));
            Console.Write("Result: {0}\n", b);
            // Version with timeout (short version that uses method groups).
            int c = TimeoutAfter(MyFunc, TimeSpan.FromSeconds(1));
            Console.Write("Result: {0}\n", c);

            // Version that lets you see what happens when a timeout occurs.
            try
            {
                int d = TimeoutAfter(
                    () =>
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(123));
                        return 42;
                    },
                    TimeSpan.FromSeconds(1));
                Console.Write("Result: {0}\n", d);
            }
            catch (TimeoutException e)
            {
                Console.Write("Exception: {0}\n", e.Message);
            }

            // Version that works on tasks.
            var task = Task.Run(() =>
            {
                Thread.Sleep(TimeSpan.FromSeconds(1));
                return 42;
            });

            // To use async/await, add "await" and remove "GetAwaiter().GetResult()".
            var result = task.TimeoutAfterAsync(TimeSpan.FromSeconds(2)).
                           GetAwaiter().GetResult();

            Console.Write("Result: {0}\n", result);

            Console.Write("[any key to exit]");
            Console.ReadKey();
        }

        public static int MyFunc()
        {
            return 42;
        }

        public static TResult TimeoutAfter<TResult>(
            this Func<TResult> func, TimeSpan timeout)
        {
            var task = Task.Run(func);
            return TimeoutAfterAsync(task, timeout).GetAwaiter().GetResult();
        }

        private static async Task<TResult> TimeoutAfterAsync<TResult>(
            this Task<TResult> task, TimeSpan timeout)
        {
            var result = await Task.WhenAny(task, Task.Delay(timeout));
            if (result == task)
            {
                // Task completed within timeout.
                return task.GetAwaiter().GetResult();
            }
            else
            {
                // Task timed out.
                throw new TimeoutException();
            }
        }
    }
}

Caveats
Having given this answer, its generally not a good practice to have exceptions thrown in your code during normal operation, unless you absolutely have to:

*

*Each time an exception is thrown, its an extremely heavyweight operation,

*Exceptions can slow your code down by a factor of 100 or more if the exceptions are in a tight loop.

Only use this code if you absolutely cannot alter the function you are calling so it times out after a specific TimeSpan.
This answer is really only applicable when dealing with 3rd party library libraries that you simply cannot refactor to include a timeout parameter.
How to write robust code
If you want to write robust code, the general rule is this:

Every single operation that could potentially block indefinitely, must have a timeout.

If you do not observe this rule, your code will eventually hit an operation that fails for some reason, then it will block indefinitely, and your app has just permanently hung.
If there was a reasonable timeout after some time, then your app would hang for some extreme amount of time (e.g. 30 seconds) then it would either display an error and continue on its merry way, or retry.

A: What about something like this?
    const int x = 3000;
    const int y = 1000;

    static void Main(string[] args)
    {
        // Your scheduler
        TaskScheduler scheduler = TaskScheduler.Default;

        Task nonblockingTask = new Task(() =>
            {
                CancellationTokenSource source = new CancellationTokenSource();

                Task t1 = new Task(() =>
                    {
                        while (true)
                        {
                            // Do something
                            if (source.IsCancellationRequested)
                                break;
                        }
                    }, source.Token);

                t1.Start(scheduler);

                // Wait for task 1
                bool firstTimeout = t1.Wait(x);

                if (!firstTimeout)
                {
                    // If it hasn't finished at first timeout display message
                    Console.WriteLine("Message to user: the operation hasn't completed yet.");

                    bool secondTimeout = t1.Wait(y);

                    if (!secondTimeout)
                    {
                        source.Cancel();
                        Console.WriteLine("Operation stopped!");
                    }
                }
            });

        nonblockingTask.Start();
        Console.WriteLine("Do whatever you want...");
        Console.ReadLine();
    }

You can use the Task.Wait option without blocking main thread using another Task.

A: I felt the Task.Delay() task and CancellationTokenSource in the other answers a bit much for my use case in a tight-ish networking loop.
And although Joe Hoag's Crafting a Task.TimeoutAfter Method on MSDN blogs was inspiring, I was a little weary of using TimeoutException for flow control for the same reason as above, because timeouts are expected more frequently than not.
So I went with this, which also handles the optimizations mentioned in the blog:
public static async Task<bool> BeforeTimeout(this Task task, int millisecondsTimeout)
{
    if (task.IsCompleted) return true;
    if (millisecondsTimeout == 0) return false;

    if (millisecondsTimeout == Timeout.Infinite)
    {
        await Task.WhenAll(task);
        return true;
    }

    var tcs = new TaskCompletionSource<object>();

    using (var timer = new Timer(state => ((TaskCompletionSource<object>)state).TrySetCanceled(), tcs,
        millisecondsTimeout, Timeout.Infinite))
    {
        return await Task.WhenAny(task, tcs.Task) == task;
    }
}

An example use case is as such:
var receivingTask = conn.ReceiveAsync(ct);

while (!await receivingTask.BeforeTimeout(keepAliveMilliseconds))
{
    // Send keep-alive
}

// Read and do something with data
var data = await receivingTask;

A: A few variants of Andrew Arnott's answer:

*

*If you want to wait for an existing task and find out whether it completed or timed out, but don't want to cancel it if the timeout occurs:
public static async Task<bool> TimedOutAsync(this Task task, int timeoutMilliseconds)
{
    if (timeoutMilliseconds < 0 || (timeoutMilliseconds > 0 && timeoutMilliseconds < 100)) { throw new ArgumentOutOfRangeException(); }

    if (timeoutMilliseconds == 0) {
        return !task.IsCompleted; // timed out if not completed
    }
    var cts = new CancellationTokenSource();
    if (await Task.WhenAny( task, Task.Delay(timeoutMilliseconds, cts.Token)) == task) {
        cts.Cancel(); // task completed, get rid of timer
        await task; // test for exceptions or task cancellation
        return false; // did not timeout
    } else {
        return true; // did timeout
    }
}

*If you want to start a work task and cancel the work if the timeout occurs:
public static async Task<T> CancelAfterAsync<T>( this Func<CancellationToken,Task<T>> actionAsync, int timeoutMilliseconds)
{
    if (timeoutMilliseconds < 0 || (timeoutMilliseconds > 0 && timeoutMilliseconds < 100)) { throw new ArgumentOutOfRangeException(); }

    var taskCts = new CancellationTokenSource();
    var timerCts = new CancellationTokenSource();
    Task<T> task = actionAsync(taskCts.Token);
    if (await Task.WhenAny(task, Task.Delay(timeoutMilliseconds, timerCts.Token)) == task) {
        timerCts.Cancel(); // task completed, get rid of timer
    } else {
        taskCts.Cancel(); // timer completed, get rid of task
    }
    return await task; // test for exceptions or task cancellation
}

*If you have a task already created that you want to cancel if a timeout occurs:
public static async Task<T> CancelAfterAsync<T>(this Task<T> task, int timeoutMilliseconds, CancellationTokenSource taskCts)
{
    if (timeoutMilliseconds < 0 || (timeoutMilliseconds > 0 && timeoutMilliseconds < 100)) { throw new ArgumentOutOfRangeException(); }

    var timerCts = new CancellationTokenSource();
    if (await Task.WhenAny(task, Task.Delay(timeoutMilliseconds, timerCts.Token)) == task) {
        timerCts.Cancel(); // task completed, get rid of timer
    } else {
        taskCts.Cancel(); // timer completed, get rid of task
    }
    return await task; // test for exceptions or task cancellation
}

Another comment, these versions will cancel the timer if the timeout does not occur, so multiple calls will not cause timers to pile up.
sjb

A: So this is ancient, but there's a much better modern solution. Not sure what version of c#/.NET is required, but this is how I do it:

... Other method code not relevant to the question.

// a token source that will timeout at the specified interval, or if cancelled outside of this scope
using var timeoutTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5));
using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, timeoutTokenSource.Token);

async Task<MessageResource> FetchAsync()
{
    try
    {
        return await MessageResource.FetchAsync(m.Sid);
    } catch (TaskCanceledException e)
    {
        if (timeoutTokenSource.IsCancellationRequested)
            throw new TimeoutException("Timeout", e);
        throw;
    }
}

return await Task.Run(FetchAsync, linkedTokenSource.Token);

the CancellationTokenSource constructor takes a TimeSpan parameter which will cause that token to cancel after that interval has elapsed. You can then wrap your async (or syncronous, for that matter) code in another call to Task.Run, passing the timeout token.
This assumes you're passing in a cancellation token (the token variable). If you don't have a need to cancel the task separately from the timeout, you can just use timeoutTokenSource directly. Otherwise, you create linkedTokenSource, which will cancel if the timeout ocurrs, or if it's otherwise cancelled.
We then just catch OperationCancelledException and check which token threw the exception, and throw a TimeoutException if a timeout caused this to raise. Otherwise, we rethrow.
Also, I'm using local functions here, which were introduced in C# 7, but you could easily use lambda or actual functions to the same affect. Similarly, c# 8 introduced a simpler syntax for using statements, but those are easy enough to rewrite.

A: If you use a BlockingCollection to schedule the task, the producer can run the potentially long running task and the consumer can use the TryTake method which has timeout and cancellation token built in.

A: I'm recombinging the ideas of some other answers here and this answer on another thread into a Try-style extension method. This has a benefit if you want an extension method, yet avoiding an exception upon timeout.
public static async Task<bool> TryWithTimeoutAfter<TResult>(this Task<TResult> task,
    TimeSpan timeout, Action<TResult> successor)
{

    using var timeoutCancellationTokenSource = new CancellationTokenSource();
    var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token))
                                  .ConfigureAwait(continueOnCapturedContext: false);

    if (completedTask == task)
    {
        timeoutCancellationTokenSource.Cancel();

        // propagate exception rather than AggregateException, if calling task.Result.
        var result = await task.ConfigureAwait(continueOnCapturedContext: false);
        successor(result);
        return true;
    }
    else return false;
}

async Task Example(Task<string> task)
{
    string result = null;
    if (await task.TryWithTimeoutAfter(TimeSpan.FromSeconds(1), r => result = r))
    {
        Console.WriteLine(result);
    }
}


text:
Q: Interface Builder is missing in xCode 4.0 I have installed xCode 4.0.2 on my mac mini, every thing is working fine, I have compiled some sample applications too, but the interface builder is missing in the directory Developer/Application while xCode.app is there.

A: Interface Builder is no longer a sperate app, it is fully integrated in Xcode 4.

A: Interface Builder is inbuilt with Xcode 4 now. So you can just select your .xib file and it will show at right side. You may need to select last icon on right side top navigator to display Interface builder.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Failed dbunit test leaves transaction open I have set up dbunit (2.4.9) to work with my hibernate (4.2.19) code. All is working well until an exception is thrown during an insert. The test case fails (correctly) but the db transaction is left open and I have no way to close it.
Here is my base test case that extends from dbUnits DbTestCase. I am guessing that my tearDown method isn't getting called.
public class DbTestCase extends DBTestCase
{
 private static boolean doOnce = false;
 private Session session;

 public DbTestCase() throws Exception
 {
    super();
    //This connection info is duplicated in dbu.hib.cfg.xml
    System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, "oracle.jdbc.driver.OracleDriver" );
    System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, "jdbc:oracle:thin:@host:1521:SID" );
    System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, "schema" );
    System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, "psswd" );

}

@Override
protected void setUp() throws Exception
{
    super.setUp();
    if(!doOnce)
    {
        doOnce = true;

        BasicConfigurator.configure();

        EbigHibernateFactory.setImplementation(new DbUnitHibUtils());
        EbigHibernateFactory.initilize();
    }

    session = EbigHibernateFactory.getSession();
    session.beginTransaction();
}

public void tearDown() throws Exception
{
    session.getTransaction().commit();
    if(session.isOpen())
    {
        session.close();
    }
    super.tearDown();
}

@Override
protected IDataSet getDataSet() throws Exception
{
    return new FlatXmlDataSetBuilder().build(new FileInputStream("src/dbtest/dataset.xml"));
}

}


text:
Q: Kubernetes kill process inside pod I was using the following code to randomly kill processes inside the pods
   : ${DELAY:=30}

if [ "$#" -ne 1 ]; then
    echo "One argument expected specifying the time in seconds to run"
else
 end=$((SECONDS+$1))
 while [ $SECONDS -lt $end ]; do
  kubectl \
    -o 'jsonpath={.items[*].metadata.name}' \
    get pods | \
      tr " " "\n" | \
      shuf | \
      head -n 1 |
      #xargs -t --no-run-if-empty \

      kubectl exec $(head -n 1) -- kill -9 9
  #if [ $((SECONDS+${DELAY})) -lt $end ];then            #break loop if (seconds completed + delay) is greater than time specified in argument
  # sleep "${DELAY}"                                     #sleep so that pod gets completely deleted and a terminating pod not selecte
  #else
  # break
  #fi
 done
fi

The script runs but no output is shown as in it goes into some infinite loop. Can someone help where I am going wrong?

A: Two things:
-o 'jsonpath={.items[*].metadata.name}' should go after kubectl get pods, otherwise kubectl will return help message.
Also, add -t to kubectl exec in order to see output from the container in your terminal.


text:
Q: Different families and releases of Windows OSes I was wondering

*

*What distinguishes different families of Windows: Windows 9x, Windows CE and Windows NT? For example, why does Windows 7 belong to the NT family, instead of to a
new family?
Is kernel the criterion, i.e. are kernels the same within a family, and different in some sense between different families?

*Does a release of Windows OS have multiple (versions of) kernels so that one can choose any kernel of them to boot the Windows OS, just as Ubuntu 10.10 has several kernels: 2.6.32 and 2.6.35 to boot from?

A: It is the underlying architecture.
95/98/ME used FAT32 file structure as the default and a less stable kernel, which shared memory for all the processes. Windows 95 allowed you to hit CTRL+ALT+DEL to end a process, but because they shared memory, it often destabilized the computer, and required you to reboot nevertheless. One other great difference is that 95/98/ME allowed virtually any program to interact directly with hardware and other devices. This meant that if a programmer made a bad call to something, it could bring the system crashing down.
NT3.51/NT4/XP/Vista/Windows7 all default to NTFS, which was better at keeping file corruption down, and use a kernel, which keeps processes separate, so when you kill one, you do not destabilize the whole computer. In contrast to 95/98/ME, NT3.51/NT4/XP/Vista/Windows7 all require any calls to hardware and devices to be made by the kernel. A program makes the request to the kernel, and if the kernel deems it safe to execute, it does it on behalf of the program. This makes all the calls to hardware very clean and consistent, and not haphazard based on how some programmer programs.
The answer to question 2 is simply no. Each kernel was a different OS, requiring a different paid license, so they did not put in the functionality to boot different kernels. You could install different versions on different partitions, and boot them, but that is different from what you are describing with Linux.


text:
Q: Adobe Reader unable to locate PDFs sent to iPhone I can open my PDFs from iBooks, but Adobe Reader cannot find them on the iPhone.
How can I open them in Adobe Reader, which I prefer?

A: If you're transferring your pdf files through itunes, you need to open your device in iTunes, then select Adobe reader from the apps file sharing section and drag/drop the files you want to open with adobe.


text:
Q: Focus tabindex on table element in ng-repeat I have a table with list elements that I want to be able to skip through using arrow keys. Right now I have to click on the table element border before I can use the arrow keys. If I set tabindex on one of the elements in the loop, it doesn't work. So, how can I focus tabindex on a table element when it is clicked?

              <button  type="button" ng-click="toSubmit()"  class="btn btn-default">Add resource
              </button>

                {{resource.name}}

A: document.getElementById('table_id').focus();


text:
Q: accessing django form variable in javascript which is inside html page I have django form with name and email address as a form field in forms.py file.
I am implementing that form in HTML Page with the help of {form.as_p}.
Now I have JavaScript inside that same HTML page with...
{% block javascript %}
<script>
</script>
{% endblock %}
Now How can I access both form variable inside this script tag. I want to validate data at client-side and than wants to send at server.
Will getElementById() method works? and If so what I need to write for access my form variables or any other good alternative.
Thanks

A: Yes, its possible. Django gives an id in format id_fieldname to each field you define in your Django form.
E.g. For name field, id in HTML will be id_name and For email_address field ,id in HTML will be id_email_address
Now you can simply use getElementById() in your JS with these ID for validation.


text:
Q: Spring Reactor: switchIfEmpty with onErrorContinue - Bug or Feature? I have made a interesting observation using switchIfEmpty in conjunction with onErrorContinue.
Given the following pipeline (in Kotlin):
Flux.fromIterable(keys).concatMap { key ->
     someRepository.findByKey(key)
        .map { domain -> someFunction(domain) }
        .flatMap { domain -> someRepository.save(domain) }
        .switchIfEmpty(Mono.defer { onEmptyFunction().toMono() })
    }

The outer pipeline maps a Flux of keys to a Mono of a domain object and pipes it through the someFunction and saves it through the someRepository function.
If the findByKey function completes without data (cannot find the domain object in the repo) it should straight go to the switchIfEmpty in the pipline. Okay so far so good.
The above description works perfectly until the inner pipeline throws an Exception. Then the pipeline does not continue any further and the subscriber will get notified by its onError consumer function.
What if we want to continue the inner pipeline even if an Exception is thrown and just try the next key from the outer Flux?
Thats possible and we introduce a new operator onErrorContinue:
Flux.fromIterable(keys).concatMap { key ->
     someRepository.findByKey(key)
        .map { domain -> someFunction(domain) }
        .flatMap { domain -> someRepository.save(domain) }
        .switchIfEmpty(Mono.defer { onEmptyFunction().toMono() })
    }.onErrorContinue(::someLog)

Now the pipeline should continue working even if the inner pipeline throws an exception (and it does so, I tested it).
However, here comes the interesting observation:
The switchIfEmpty function is ALSO getting called if the inner pipeline throws an Exception.
This means switchIfEmpty gets executed in TWO events:
- findByKey completes with an empty Mono
- inner pipeline throws an Exception (e.g. someFunction)
This is fundamentally different from above pipeline without onErrorContinue where the switchIfEmpty is NOT executed if the inner pipeline throws an Exception.
Questions:
Is this intended behaviour?
Is this a bug?
Can i somehow control that switchIfEmtpy is ONLY executed on empty data not on errors?
This is is really a dangerous situation which bugged me for a while!


text:
Q: What is the relationship between vector and its associated skew symmetric matrix? This is my first post in this forum, so hello everyone!
I am working with geometries (i.e. areas, volumes and inertias of polygons and polyhedrons in 3D space). For doing that, I to use both the Cross Product
 and the Parallel Axis Theorem, among others.
According to wikipedia, these can be defined, by using the

[...] skew symmetric matrix associated with the position vector [...]

and then operating on them (see links)
So, my question is:
What is the connection between $ \vec{r} = (x,y,z)$ and $ [r]=\left( \begin{array}{ccc} 0 & -z & y \\ z & 0 & -x \\ -y & x & 0 \end{array} \right)$ ?
After googling and looking for an answer for this for a while, I have not been able to find an answer. I guess it may have something to do with the eigenvectors, but I am just not sure.
Any help will be appreciated!
Thanks!

A: You seem to have exchanged $y$ and $z$ in your formula, but $A=\begin{pmatrix}0&-z&y\\z&0&-x\\-y&x&0\end{pmatrix}$ is the matrix such that $A\vec v=\vec r\times\vec v$ for all $\vec v$.
The fact that this matrix is skew symmetric corresponds to the fact that $\vec r\times \vec v$ is always perpendicular to $\vec v$ -- the skew-symmetric matrices are exactly those where $\vec v\cdot A\vec v=0$ for all column vectors $\vec v$.
It is somewhat interesting that every $3\times 3$ skew-symmetric matrix arises in this way -- so whenever you have a linear transformation $\mathbb R^3\to\mathbb R^3$ where the output is always perpendicular to the input, that transformation is necessarily the same as crossing with an appropriately chosen $\vec r$. In dimensions other than $3$ this don't work because the vector space of skew-symmetric matrices has a different dimension than the space itself -- this is in fact one of the reasons why there is no straightforward generalization of the cross product to dimensions other than $3$. (Various such generalizations do exist but can't be claimed to be straightforward).

A: If you want only vector definition for skew symmetric matrix assume $r$ is a vector $= [r_x  r_y  r_z]^T$ in the frame described by versors $i, j, k$ Then skew-symetric matrix $S(r)$ assigned to the vector $r$ is constructed this way
$$S(r) = \begin{pmatrix} r \times i \ \ r \times j \ \ r \times k \end{pmatrix}$$
As you see in the form of matrix you have written down in the first column $r_x$ is missing, in the second $r_y$ , in the third $r_z$ so columns are perpendicular to $i, j, k$ as to $r$ as well. This is the only matrix (up to the scale of columns) that has such property.


text:
Q: Meteor - Get plain username & password on server when user tries to login I am trying to authenticate user login from some 3rd Party Api with same login credentials in case the login on Meteor fails.
I have tried to check for the username & password in Accounts.validateLoginAttempt, but it is not providing me the credentials which user just input from web app or mobile app.
Is there any work around to get plain username and password in that case?


text:
Q: How do you add a new directory in Linux? I am currently taking a Computing GCSE, and I have got a Linux Controlled Assessment, and this is one of the tasks:

Create a directory within your home directory. Name it A452. Navigate to your new A452 directory. Type touch mynametextfile, where myname is your
  first name.

I tried adding a new folder called A452, and then opening the terminal and typing touch matthewtextfile, but that didn't work. I am very new to Linux, and I tried Wikipedia, so what should I do?
Edit: It turns out that it was in my Home folder, not my newly created one!

A: try this in your terminal:
$ cd ~               # move to your home directory
$ mkdir A452         # create directory named A452
$ cd A452            # mv to that directory
$ touch mynametextfile  # create file "mynametextfile"


text:
Q: A word to describe an incident or event that may or may not have taken place Is there any word that can be used to describe an incident or event that may have taken place but people are not sure if that event actually took place because there is a lack of comprehensive evidence.
For example many people believe that the Roswell Incident is actually true, however others believe that such an incident did not take place.
Another example is an event from an Eastern religion called Mahabharat that is considered to be true by many people, however others differ suggesting that there is no conclusive evidence to suggest that this event actually took place.

A: Consider alleged

Represented as existing or as being as described but not so proved; supposed: an alleged conspiracy; an alleged traitor; an alleged victim of a crime.

American Heritage Dictionary
Similarly claimed

to say that something is true or is a fact, although you cannot prove it and other people might not believe it

Cambridge Dictionaries Online
Also

*

*supposed

*declared

*assumed

*so-called

*apparent

*rumoured

*stated

*described

*asserted

*presumed

*affirmed

*professed

*reputed

*hypothetical

*averred

A:
purported - said to be true or real but not definitely true or real

If things are more certain, you can bump the status of a purported event up to putative:

putative -  generally believed to be something

A: Apocryphal would be a good way to describe the alien landing at Roswell.


text:
Q: C# WPF close new user control I am new to c#. I have created main windows that I am adding usercontrols to switch between screens with command:
Switcher.Switch(new NewPage());

The class Switcher is:
public static class Switcher
    {
        public static MainWindow pageSwitcher;

        public static void Switch(UserControl newPage)
        {
            pageSwitcher.Navigate(newPage);
        }

        public static void Switch(UserControl newPage, object state)
        {
            pageSwitcher.Navigate(newPage, state);
        }

    }

But how to I exit the user control? I wish to finish it (like back button). I can use:
Switcher.Switch(new PreviousPage());

but it will keep the new page in memory and will not release it.
Example of NewPage class:
namespace MyProject.Screens
{

    public partial class NewPage : UserControl
    {
        public NewPage()
        {
            InitializeComponent();
        }

        private void back_button_Click_(object sender, RoutedEventArgs e)
        {
           //what to put here?
        }
    }
}

A: You should really try and use the standard Navigation services available with WPF. This will give you configurable oage caching and journalling.
http://msdn.microsoft.com/en-GB/library/ms750478(v=vs.100).aspx

A: The framework does a lot of the heavy lifting for navigation for you, including the "back" operation that you're interested in.
Take a look at http://msdn.microsoft.com/en-us/library/ms750478.aspx
NavigationService.GoBack is what you'll use.
In the off-chance that you're working on a Windows Store App, let me know, since my answer will be different.

A: Try this:
    private void back_button_Click_(object sender, RoutedEventArgs e)
    {
       Window parentWindow = (Window)this.Parent;
       parentWindow.Close();
    }


text:
Q: read and write to same socket (TCP) using select We're writing a client and a server to do (what I thought was) pretty simple network communications.  Mulitple clients connect to the server which then is supposed to send the data back to all other clients.
The server just sits in a blocking select loop waiting for traffic, and when it comes, sends the data to the other clients.  This seems to work just fine.
The problem is the client.  In response to a read, it will sometimes want to do a write.
However, I've found that if I use:
 rv = select(fdmax + 1, &master_list, NULL, NULL, NULL);

My code will block until there is new data to read.  But sometimes (asynchronously, from another thread) I'll have new data to write on the network communication thread. So, I want my select to wake up periodically and let me check if there are data to write, like:
if (select(....) != -1)
{
  if (FD_SET(sockfd, &master_list))
     // handle data or disconnect
  else
     // look for data to write and write() / send() those.
}

I tried setting the select to poll mode (or ridiculously short timeouts) with:
// master list contains the sockfd from the getaddrinfo/socket/connect seq
struct timeval t;
memset(&t, 0, sizeof t);
rv = select(fdmax + 1, &master_list, NULL, NULL, &t);

but have found that then then client never gets any incoming data.
I also tried setting the socket fd to be non-blocking, like:
fcntl(sockfd, F_SETFL, O_NONBLOCK);

but that doesn't solve the problem:

*

*if my client select() has no struct timeval, reading data works, but it never unblocks to let me look for writable data.

*if my client select() has a timeval to get it to poll, then it never signals that there are incoming data to read, and my app freezes thinking there is no network connection made (despite the fact that all other function calls have succeeded)

Any pointers at all as to what I could be doing wrong? Is it not possible to do read-write on the same socket (I can't believe that to be true).
(EDIT: The correct answer, and thing that I remembered on the server but not on the client, is to have a second fd_set, and copy master_list before each call to select():
// declare and FD_ZERO read_fds:
// put sockfd in master_list

while (1)
{
   read_fds = master_list;
   select(...);

   if (FD_ISSET(read_fds))
     ....
   else
     // sleep or otherwise don't hog cpu resources
}

)

A: I seem to recall a trick about creating and sharing a read/write filedescriptor between the network thread and the main thread that is added to the descriptors in the select call.
This fd has one byte written to it by the main thread when it has something to send. The write wakes up network thread from the select call and the network thread is then grabs the data from a shared buffer and writes it to the network then go back to sleep in the select.
Sorry if that's a bit vague and lacking of code ... and my memory may be incorrect.. so others may have to guide you further.

A: Everything looks fine, except the line where you do if (FD_SET(sockfd, &master_list)). I have a very similar code structure and I used FD_ISSET. You're supposed to test if the list is set, not to set it again. Other than that, I see nothing else.
Edit. Also, I have the following for the timeout:
timeval listening_timeout;
listening_timeout.tv_sec = timeout_in_seconds;
listening_timeout.tv_usec = 0;

perhaps there's an issue if you set it to 0 (as you seem to be doing?)
Edit2. I remembered I ran into a strange problem when I wasn't clearing the read set after the select exited and before I entered it again. I had to do something like:
FD_ZERO(&sockfd);
FD_SET(sockfd, &rd);

before I was entering select. I can't remember why though.

A: I don't see anything wrong with your code, so it should work. If you can't get it working, one way to work around it would be to create a pipe to be used by your reading thread and the thread that prepares things for writing, and add the pipe's reading end to your select set. Then, when the other thread has prepared data to write, it just sends something on the pipe, your reading thread gets woken up from the select, and it can then do the writing. Depending on how often there is data to read or write, this could also be more efficient.

A: 2 threads should be able to work with the same socket at a time, so your main thread should be able to write to a client while the other one sleeps in select waiting for incoming data. This of course assumes that both threads have access to the client list.


text:
Q: Hide My site menu from Sharepoint 2010 welcome control Using jQuery I am able to hide the 'sign in as a different user', 'My Settings' and 'Personalize this page' option in the SharePoint Welcome menu using the following jQuery code:
jQuery(document).ready(function($){
  $("[text='Sign in as Different User']").remove();
  $("[text='My Settings']").remove();
  $("[text='Personalize this Page']").remove();
});

However, I am not able to hide the 'My site' and 'My Profile' option using the same script i.e
jQuery(document).ready(function($){
  $("[text='My Site']").remove();
  $("[text='My Profile']").remove();
});

Please, how do I get around this using jQuery?

A: Instead of using JQuery, you can also use CSS:
#mp1_0_0_Anchor, #mp1_0_1_Anchor {
    display: none;
}


text:
Q: Append comma after each value and then show in single line I have around 15000 rows in my excel like
ATM-12345678976-0001
ATM-12345675555-0002
ATM-12345675555-0003

and so on......
I wanted to append comma after each value and then want in a single like like below :
ATM-12345678976-0001,ATM-12345675555-0002, ATM-12345675555-0003,.......

How i can achieve this ?

A: *

*Ctrl+H

*Find what: \R

*Replace with: ,  # a comma and a space

*CHECK Wrap around

*CHECK Regular expression

*Replace all
Explanation:
\R          # any kind of linebreak (i.e. \r, \n, \r\n)

Screenshot (before):

Screenshot (after):


text:
Q: Will this architecture be effective for a dashboard that is cross platform/browser compatible? I am researching architecture for a dashboard for my company to eliminate the clunky reporting UI we have now that has a treeview menu and uses the SQL Reporting Services Report Viewer control.
I am considering using ASP.NET MVC 4 server side and Telerik Kendo UI on the client side for the data tables, charts, and graphs. For data access, I would use ADOMD.NET to retrieve data from the SSAS cube.
Reasons for this is I am interested in something that is lightweight, fast, and that runs equally well on Android tablets, iPad's, in Firefox, Safari, and IE 9, iPhone's, Android phones, etc.
Will this be an effective architecture for a lightweight, cross platform compatible corporate dashboard? For a MSFT environment, are there better alternatives that meet my requirements?

A: I am working on a very similar project with ASP.NET MVC3/4 and Telerik Kendo UI.
Refer to this post concerning the easiest way of doing this, using a third-party Entity Framework provider. Technically this would mean that all you have to do is serializing the data source obtained from SSAS Entity Framework Provider to JSON then giving it to a Kendo UI control and you're in business.


text:
Q: how can I write a scss use vw unit in mobile and use px in pc I try something like this, but not working.
@media (min-width:750px) {
    @function pxvw($val){
        @return $val * 1px;
    }
}
@media (max-width:750px) {
    @function pxvw($val){
        @return $val * 1vw;
    }
}
.block{
    height: pxvw(30);
    width: pxvw(30);
}

Is there any solution to make this work?


text:
Q: Javascript FOR loop inside of an array I have been avoiding javascript for a while now but need to use it for a google chart I am using. My original code looks like this...
echo "function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Date', 'Machines Total'  ],

      [ '$Day[6]', $Hour_Tot[7].$Min_Tot[7] ],
      [ '$Day[5]', $Hour_Tot[6].$Min_Tot[6] ],
      [ '$Day[4]', $Hour_Tot[5].$Min_Tot[5] ],
      [ '$Day[3]', $Hour_Tot[4].$Min_Tot[4] ],
      [ '$Day[2]', $Hour_Tot[3].$Min_Tot[3] ],
      [ '$Day[1]', $Hour_Tot[2].$Min_Tot[2] ],
      [ '$Day[0]', $Hour_Tot[1].$Min_Tot[1] ]

      ]);";

This code works just fine, and has been tested. What I am trying to do now is have
the chart become more dynamic so a user can enter in a number and the chart can ouput
the data for the number of days. So I need to add in a for loop. This is what I got so
far.
echo "function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Date', 'Machine L1'  ],
      for (count = 1, DayNumber = 0; count == 7; ++count, ++DayNumber )
  document.write([ '$Day[DayNumber]', $Hour_Tot[count].$Min_Tot[count]],);
       ]);";

This code does not work. I do not understand how to use the document.write to output
the 7 lines I need to replicate the above code.

A: This code is not going to work because you're putting a for loop inside an array declaration.
You should do the following...
echo "function drawChart() {
var data = google.visualization.arrayToDataTable([
  ['Date', 'Machine L1'  ],";
for ($count = 1, $DayNumber = 0; $count <= 7; ++$count, ++$DayNumber ) {
  echo "  [ '$Day[$DayNumber]', $Hour_Tot[$count].$Min_Tot[$count]],";
}
echo "]);";

Or you can also handle that using javascript, it should looks like:
echo "var arr = [['Date', 'Machine L1']];
  for(var i=1;i<=7;i++) {
    arr.push([{$Day}[i-1], {$Hour_Tot}[i].toString()+{$Min_Tot}[i].toString()]);
  }
  var data = google.visualization.arrayToDataTable(arr);
";


text:
Q: Input loses focus when I try to change an array element within an object managed by state hooks The following is probably the neatest code that illustrates my problem I could think of. I am essentially trying to draw a table to the page that pulls exercise data from a database, sets that data to a state of an array of objects, and then when a row is clicked, render an 'edit' row below it that allows the user to change any of the array data inside one of those objects.
import React, {useEffect} from "react";

import { useState } from "react";
import { useNavigate } from "react-router";

export default function GetProgram() {
    // holds all n number of exercises from database
    const [exercises, setExercises] = useState([])
    // number that holds which exercises is currently being shown/edited
    const [editingExerciseIndex, setEditingExerciseIndex] = useState(-1)
    // once both effects have fetched the data
    const [loading, setLoading] = useState([true, true])
    // holds info about the program to map for exercise displaying
    const [program, setProgram] = useState({
        days: [],
        name : '',
        _id : null
    })

    useEffect(() => {
        async function getProgramInfo() {
            fetch(`http://localhost:5000/program`).then((res) => {
                res.json().then((body) => {
                    setProgram(body)
                    setLoading([false, loading[1]])
                })
            })
            .catch((err) => {
                console.log(`**ERR: ${err}`)
                return
            })
        }
        getProgramInfo()
    }, [])

    useEffect(() => {
        async function getExercises() {
            fetch(`http://localhost:5000/program/getmap`).then((res) =>{
                res.json().then((body) => {

                    setExercises(body)
                    setLoading([loading[0], false])
                })
            })
        }
        getExercises()
    }, [])

    // onChange handler for edit fields
    function updateField(props) {

        var newExercise;

        if (props.reps) {
            const newReps = exercises[props.j].reps.map((r, i) => {
                if (i === props.set-1) {
                    return parseInt(props.reps,10) // user's input
                }
                return r // old value
            })
            newExercise = {...exercises[props.j], reps:newReps} // []
            console.log(newExercise)
        }
        else {
            const newWeight = exercises[props.j].weight.map((w, i) => {
                if (i === props.set-1) {
                    return parseInt(props.weight,10)
                }
                return w
            })
            newExercise = {...exercises[props.j], weight:newWeight}
        }
        console.log([...exercises, newExercise])

        setExercises(exercises.map((exercise, i) => {
            if (exercise.day === newExercise.day && exercise.position === newExercise.position) {
                return newExercise
            }
            return exercise
        }))
    }

    const EditFieldRow = (props) => {
        console.log("Rendering Edit Field Row")
        return (

                {props.set}
                <input key="reps-input" type="text" value={props.reps} onChange={(e) => updateField({j:props.j, set:props.set, reps:e.target.value})}/>
                <input key="weight-input" type="text" value={props.weight} onChange={(e) => updateField({j:props.j, set:props.set, weight:e.target.value})}/>

        )
    }

    const EditField = (props) => {
        return (

                <form onSubmit={() => console.log("submitted")}>

                            Set
                            Reps
                            Weight

                        {[...Array(props.exercise.sets).keys()].map((i) => {
                            return (
                                <EditFieldRow j={props.j} key={`fieldrow-${i}`} set={i+1} reps={props.exercise.reps[i]} weight={props.exercise.weight[i]}/>
                            )
                        })}

                </form>

        )
    }

    const PageContent = (props) => {
        return (

{program.rname??program.name} Program

                    {program.dayMap.map((day, i) => {
                        return (
                            <div className="col" key={`${day}-${i}`}>

{day}

                                        Name
                                        Sets

                                    {exercises.map((exercise, j) => {
                                        if (exercise.day === i+1) {
                                            return (
                                                <tbody key={`${exercise.name}${i}${j}${day}`}>
                                                    <tr id={`exercise-row-${exercise.name.replaceAll(" ", "-")}`} className={`exercise-row`}
                                                    onClick={() => {
                                                        setEditingExerciseIndex(j)
                                                    }}
                                                        key={`${exercise.name}-${i}-${day}`}
                                                    >
                                                        {exercise.name}
                                                        {exercise.sets}

                                                    {editingExerciseIndex === j &&

                                                         <EditField exercise={exercises[j]} j={j}/>

}

                                            )
                                        }
                                    })}

                        )
                    })}

        )
    }

    if (program.dayMap) {
        return (
            <PageContent />
        )
    }
    return (

    )
}

The exercises array would look something like this
{
        "program" : "Full-body-3d",
        "name" : "Bench Press",
        "position" : 1,
        "day" : 1,
        "sets" : 3,
        "reps" : [
            6, 6, 6
        ],
        "ref" : "Bench",
        "weight" : [
            80, 80, 80
        ]
    },

    {
        "program" : "Full-body-3d",
        "name" : "Lat Pulldown",
        "position" : 2,
        "day" : 1,
        "sets" : 3,
        "reps" : [
            12, 12, 12
        ],
        "ref" : "Accessory",
        "weight" : [
            80, 80, 80
        ]
    },
...

Where
position - order of the exercise to perform
day - day that is mapped to said exercise (ex. 1 might represent "Push day")
sets - will always be the length of reps[] and weight[] (not strictly necessary)

the rest aren't extremely important

This is my App.js that routes all pages:
import React, { useEffect, useState } from "react";

// We use Route in order to define the different routes of our application
import { Route, Routes } from "react-router-dom";
import { useCookies } from 'react-cookie';

// We import all the components we need in our app
import NB from "./components/navbar";
import WorkoutCalendar from "./components/workoutCalendar";
import Edit from "./components/edit";
import Create from "./components/create";
import Settings from "./components/settings";
import Header from "./components/header";
import Progress from "./components/progress";
import DayInfo from "./components/dayInfoPage";
import Delete from "./components/deleteall";
import Todo from "./components/dev/todo";
import GetProgram from "./components/lift/programPage";
import AddLift from "./components/lift/create";
import Populate from "./components/dev/pop_db";
import PopulateColorThemes from "./components/dev/pop_colors";
import UserList from "./components/user/list";
import UserLogin from "./components/user/login";
import Rec from "./components/rec";

const App = () => {
    const [cookies, setCookie] = useCookies(['theme'])
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        setCookie('ColorTheme', cookies.ColorTheme ?? 'Ender', {path:'/'})
        setLoading(false)
    },[])

    const [username, setUsername] = useState('');

    if (loading) {
        return (

        )
    }
    else {
        return (

                {/* navbar */}
                <NB />

                {/* header */}

                {/* content */}

                    <Routes>
                        <Route exact path="/" element={<WorkoutCalendar />} />
                        <Route path="/edit/:id" element={<Edit />} />
                        <Route path="/record/create" element={<Create />} />
                        <Route path="/settings" element={<Settings />} />
                        <Route path="/record/:date" element={<DayInfo />} />
                        <Route path="/deleteall" element={<Delete />} />
                        <Route path="/dev/todo" element={<Todo />} />

                        <Route path="/program" element={<GetProgram />} />

                        <Route path="/lift/add" element={<AddLift />} />
                        <Route path="/program/populate" element={<Populate />} />
                        <Route path="/user" element={<UserList />} />
                        <Route path="/user/login" element={<UserLogin headerUsername={setUsername}/>} />
                        <Route path="/color/populate" element={<PopulateColorThemes />} />
                        <Route path="/record" element={<Rec />} />
                    </Routes>

        );
    }

};

export default App;

And finally index.js which renders the components
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
import {CookiesProvider} from 'react-cookie'

import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap';

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(
  <React.StrictMode>
    <CookiesProvider>
    <BrowserRouter>
      <App />
    </BrowserRouter>
    </CookiesProvider>
  </React.StrictMode>,
);

I cannot seem to find where I am going wrong despite reading tons of other posts with similar situations, but different causal issues. I've looked at In React ES6, why does the input field lose focus after typing a character?
and it seems like its almost always caused by rendering a form in a function inside render(). I don't quite know where that would be happening or how to avoid it.
I tried refactoring all of the components into the smallest pieces possible, keeping them all clumped as one. I tried adding keys to every element that would be effected, using an individual state hook that would track only the selected exercise and edit/display based off that rather than directly editing the single exercises state array. I expected this to be a solved problem, since I cannot imagine I am the first person to want to do something like this with a data structure similar to mine


text:
Q: Failed to run wordpress website on local machine, it gets redirected to live website What I want to do > I need to run a version of my live website on my local machine.
Why I need to run it on local machine I need to edit the website on my local machine and when everything is perfect copy it onto server. So I can easily make changes to the website without scaring of breaking the live website.
Whats the problem > I could run it on my local machine but when I log in to wordpress from localhost it redirects me to the live server.
What steps did I followed > I followed this question, installed mamp and downloaded whole wordpress directory to htdocs directory of mamp, then exported the database on server and imported it to my local server. Ran the server, entered username and password and was redirects to the live server rather than running the website on my local machine.

A: The code is the same, you just have to edit the database configuration of localhost and change domain to localhost.

A: tl;dr:
run this to fix it: https://interconnectit.com/products/search-and-replace-for-wordpress-databases/
long answer:
Most importantly, the "Home URL" and "Site URL" on the Settings -> General need to be changed. Also, many other URLs are saved into the Database including the domain name. Since some of them might be php-serialized, just search/replace in the database might screw up some things.
The Wordpress Codex has lots of info on moving / clonign a site. Still, the easiest way is the tool from tl;dr above.


text:
Q: MYSQL query trim a string based on result of results of another query I am trying to update a table ONLY if a condition of another table is met. These tables don't have really anything I can join on. (the phppos_app_config is just key/value pairs). The query below does NOT work as I am not allowed to do a count on a subquery.
Here is what I am trying to achieve (doesn't work as it is NOT allowed in sql; but just showing logic)
UPDATE phppos_giftcards SET giftcard_number = TRIM(LEADING ';' FROM giftcard_number)
WHERE
COUNT
(
   SELECT value FROM phppos_app_config
   WHERE `key` = 'disable_giftcard_detection' and `value` = '0'
) =1

A: I don't have mysql to test so just let me know if it does not work and I will delete
UPDATE phppos_giftcards SET giftcard_number = TRIM(LEADING ';' FROM giftcard_number)
WHERE ( SELECT count(*) FROM phppos_app_config
        WHERE `key` = 'disable_giftcard_detection' and `value` = '0'
      ) = 1

A: The use of the Exists Clause in the subquery will simplify the sub query and will perform better as unnecessary comparisons will be avoided (assuming that you want to update if there us at least one record in the PHPOS_APP_CONFIG table with the specified key, value)
UPDATE phppos_giftcards SET giftcard_number = TRIM(LEADING ';' FROM giftcard_number)
WHERE exists
     ( SELECT count(*) FROM phppos_app_config
       WHERE `key` = 'disable_giftcard_detection' and `value` = '0'
     )


text:
Q: "I am looking forward" I am curious if it possible to use a short phrase:

I am looking forward.

It is a short version without to + noun/gerund. I would like to use it at the end of the discussion with somebody, when it is obvious what I am looking forward to. So this is the way to type less words and I am curious if it is grammatically correct.

A: Very often in English, prepositions attached to verbs alter the meaning. Looking is one such verb.

*

*I am looking — this has a number of meanings, from searching ("looking for it") to appearing ("looking thoughtful"). The "appearing" meaning requires an object; the "searching" meaning requires an object after for. The phrase "I am looking" can omit "for it" when that's understood ("Come on, find it!" "I'm looking!") and generally means that you're looking at something or for something but not seeing it.

*I am looking in — looking in can mean visiting ("looking in on Clive"; "looking in this afternoon") or have its normal prepositional meaning ("I'm looking in the living room"). Where the meaning is its normal prepositional meaning, it requires a prepositional object ("the living room").

*I am looking into — can mean investigating ("looking into Clive's disappearance") or have its normal prepositional meaning ("looking into the living room through the window"). Looking into always requires an object, and the context determines which meaning the verb has.

*I am looking forward — without the additional preposition to can only have its normal meaning, that you are facing forward. The to changes the meaning to "anticipating", and that meaning actually requires an object: you can't simply be anticipating, you have to be anticipating something.

So, no: you can't just say "I am looking forward" when your intended meaning is "I am eagerly anticipating" — just as you can't say simply "I am eagerly anticipating".


text:
Q: ruby builder: can't generate xml tags like  Hy Folks
I got the Problem that i have to create an xml in ruby with builder, running on a sinatra server.
The Xml is filled with xml tags like this one:
<fu-ba:r test="test1" source="h1">
  somthing
</fu-ba:r>

now i don't know how to get builder to create a tag like this one (the attributes are no Problem).
i Tried:
xml.fu-ba:r(......)
xml."fu-ba:r"(.......)
xml. << "fu-ba:r"(......)

Every idea or solution would help a lot, thanks Folks

A:
Ruby identifiers are consist of alphabets, decimal digits, and the
  underscore character, and begin with a alphabets(including
  underscore). There are no restrictions on the lengths of Ruby
  identifiers.

Since ruby identifiers don't allow the use of special characters builder has a method called tag! for this very purpose.
For example
x.tag!("fu-ba:r") {
  x.text! "something"
}

Outputs
# <fu-ba:r>
#   something
# </fu-ba:r>


text:
Q: Multiple GUID_partition_scheme, cant boot MacOS High Sierra, and gpt command resource busy I have a problem after deleting Kali OS from my dual-boot Macbook (with High-Sierra MacOS). The problem is:

*

*I can only boot into internet-recovery-mode

*I can not use gpt command, as it results: 'resource busy'

A: The partition types got hosed by removing Kali Linux. Disk0s2 and disk0s3 got the wrong types. I would expect some Apple partition type for disk0s2 (HFS+/CoreStorage/APFS) and a Linux partition type for disk0s3. Disk0s4 is probably some dispensable Linux boot/swap partition.
To regain access to macOS you have to modify the partition type of disk0s2.

*

*Boot to Internet Recovery Mode

*In the menubar open Terminal.app and enter:
diskutil list
gpt -r show disk0

to get all partition and volume details of the internal SSD

*Unmount all disk0 related volumes and disks (in your example that's disk2 (based on disk0s3), disk0s4 and finally disk0). Examples: diskutil unmountVolume disk0s4 or diskutil unmountDisk disk0.

*Remove the APFS container disk2: diskutil ap deleteContainer disk2

*Remove disk0s3 and disk0s4 (either with diskutil or gpt).
Example: diskutil eraseVolume "Free Space" Nil disk0s4

*Determine the partition type of disk0s2 (How can I make my Mac partition bootable again?) and remove and re-add disk0s2 using gpt with the same size but the proper type. Considering the macOS version (10.13) and the hardware (SSD) the proper partition type is probably 7C3457EF-0000-11AA-AA11-00306543ECAC (APFS) instead of FFFFFFFF-FFFF….

*Expand disk0s2 with diskutil ap resizeContainer disk0s2 0.

Under certain circumstances you have to disable SIP to edit the partition table with gpt!


text:
Q: How to reload web page in GWT How to reload the web page in GWT? I want to reload the page after a user logged in the system and then it will show the personal status on top of the page. Any idea how?
Thanks a lot.

A: For problems like these, you could use an event bus... seems very well suited to what you want to do. Your authentication widget could raise an authentication event on the bus, and all widgets on the page that ought to be reacting to this can just pick it up and change themselves.
There's a discussion about it here.

A: Window.Location.reload() will reload the page, but I'm pretty sure reloading the page is not what really you want.
You probably just want to refresh certain parts of the page to update once the user logs in.
The reason is, reloading the page will re-download the JavaScript and images on the page, which is a lot of traffic just to refresh the UI.

A: I suggest creating a div specifically for this display area in your HTML page.
For example, in your HTML file:

... the rest of our page

However you are catching when someone logged in (Database, EventBus, whatever), just update that single panel like so:
RootPanel statsPanel = RootPanel.get("userStats");
statsPanel.clear();
statsPanel.add(new StatsPanel());

Perhaps you create your StatsPanel using the UiBinder.


text:
Q: Multiple SELECT in the same query which overwrite each-other's result Sorry for the confusing title, better go straight to the code:
Sample table:
|     key    |    value  |    MainLanguage     |     SubLanguage     |
|    mLangID |      5    |       default       |         en          |
|    mLangID |      3    |         esES        |         en          |
|    mTitle  |  Title    |       default       |         en          |
|    mTitle  |  Título   |         esES        |         es          |

I want to avoid using these queries:
SELECT * FROM translation.strings WHERE MainLanguage = 'esES' AND lang='es'
SELECT * FROM translation.strings WHERE MainLanguage = 'esES' AND lang='en'
SELECT * FROM translation.strings WHERE MainLanguage = 'default' AND lang='en'
...

and combine them into one, but make sure the result of the first query will not get overwritten by the results of the second one, and so on. Or, if it's easier, the reverse (Second query overwrites first query's results, 3rd overwrites 2nd query, etc)

A: Use UNION ALL to combine results this will not remove duplicate rows.

A: If I understand correctly, you want union all with where clause to prioritize the results.  I'm guessing you want one row per key.  If so, this might work
SELECT *
FROM translation.strings s
WHERE MainLanguage = 'esES' AND lang = 'es'
UNION ALL
SELECT *
FROM translation.strings s
WHERE MainLanguage = 'esES' AND lang = 'en' AND
      NOT EXISTS (select 1
                  from translation.strings s2
                  where s2.key = s.key and s2.MainLanguage = 'esES' AND s2.lang = 'es'
                 )
UNION ALL
SELECT *
FROM translation.strings s
WHERE MainLanguage = 'default' AND lang = 'en' AND
      NOT EXISTS (select 1
                  from translation.strings s2
                  where s2.key = s.key and
                        (s2.MainLanguage = 'esES' AND s2.lang = 'es' or
                         s2.MainLanguage = 'esES' AND s2.lang='en'
                        )
                 );

As a note:  there are easier ways of solving this in other databases.


text:
Q: Parse co-ordinates from KML if in 500ft region of a latitude/longitude point I have a KML file (NewYork.kml) which has assets listed in co-ordinates (inside LineStrings) in the New York region.
I am trying to pick a random point in New York (For example: 40.739974,-74.009605) and get any assets listed within a 500ft range.
I am working with Java/Google Earth API. Does anyone have any tips on which direction to go?

A: I'd recommend the geojs library, in particular the geo.Point class.
It has useful methods like distance() that you could use to see if two coordinates are within 500ft of each other.


text:
Q: Get records from one table array which are not present in another table records in postgres I want to get records from array of one table which are not present in another  table column. Following are the tables;
automobile_data
   -----------------------------------------------
    veh_id |             vehicle_types
    --------+---------------------------------------
        1  | {"byd_tang","laferrari"}
        2  | {"sonata","jaguarxf"}
        3  | {"swift","teslax","mirai"}
        4  | {"volt","viper"}
        5  | {"ferrariff","bmwi8"}
    ------------------------------------------------

vehicle
   -----------------------------------------------
     vehicle_name |  id
   ------------------------------------------------
      byd_tang    |   1
      laferrari   |   1
      sonata      |   2
      jaguarxf    |   2
       swift      |   3
      teslax      |   3
   ------------------------------------------------

Require following output;
    -----------------------------------------------
     vehicle_name | veh_id
    ------------------------------------------------
      mirai       |   3
      volt        |   4
      viper       |   4
      ferrariff   |   5
      bmwi8       |   5
    ------------------------------------------------

A: This can be done using first unnest the array from table automobile_data and then find name which is not exists in vehicle table;
SELECT  c.vehicle_name, c.veh_id
  FROM
   (
    SELECT veh_id, unnest("vehicle_types") as vehicle_name
    FROM automobile_data
    ) c  where not exists
( SELECT FROM vehicle
      where vehicle_name = c.vehicle_name);


text:
Q: Dimensionality Reduction ValueError New to this subject. I was trying to use PCA, from sklearn to reduce my data dimensionally. As I dont know another method I am trying to use PCA to guess how much dimensions it should be used.
My data is an ndarray with shape (51, 2928). With the next code I try to fit the data
pca = PCA(n_components='mle', svd_solver='full')
pca.fit(data)

But I deal with the following error when trying to fit the data:

ValueError: n_components='mle' is only supported if n_samples >= n_features

What am I doing wrong?


text:
Q: Implementation restriction: EntitySubscription only allows security evaluation for non-admin users when LIMIT is specified and at most 1000 I incorporated Andrew Fawcett's amazing enterprise patterns (code here on GitHub) into my managed extension package (Namespace MY_PACKAGE_NS). In one of my CustomObjects after insert triggers I need to pass the triggering objects to the base package (Namespace BASE_PACKAGE_NS) to let it also do its magic.
I do this inside a SObjectDomain class:
public with sharing class CustomObjects extends SObjectDomain {

   public CustomObjects(List<CustomObject__c> sObjectList) {
      super(sObjectList);
   }

   public override void onAfterInsert() {
      BASE_PACKAGE_NS.SObject_TriggerHandler.afterInsert(this.records);
   }
}

Whenever I insert a new record of this type I receive this really strange exception.
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, MY_PACKAGE_NS.CustomObjects: execution of AfterInsert

caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, BASE_PACKAGE_NS.Member: execution of AfterInsert

caused by: System.DmlException: Update failed. First exception on row 0 with id a09d000000DrG5GAAV; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, BASE_PACKAGE_NS.Member: execution of BeforeUpdate

caused by: System.QueryException: Implementation restriction: EntitySubscription only allows security evaluation for non-admin users when LIMIT is specified and at most 1000

(BASE_PACKAGE_NS)
: []

(BASE_PACKAGE_NS)
: []

(BASE_PACKAGE_NS)
Class.MY_PACKAGE_NS.CustomObjects.onAfterInsert: line 14, column 1
Class.MY_PACKAGE_NS.SObjectDomain.handleAfterInsert: line 129, column 1
Class.MY_PACKAGE_NS.SObjectDomain.triggerHandler: line 208, column 1
Class.MY_PACKAGE_NS.SObjectDomain.triggerHandler: line 185, column 1
Trigger.MY_PACKAGE_NS.CustomObjects: line 2, column 1: []

This is how my trigger looks
trigger CustomObjects on CustomObject__c (after delete, after insert, after update, before delete, before insert, before update) {
    SObjectDomain.triggerHandler(CustomObjects.class);
}

It works when I switch back to my old trigger code that not uses extra domain classes:
trigger CustomObjects on CustomObject__c (before insert, after insert, after update, after delete) {

    if(Trigger.isInsert) {

        if(Trigger.isAfter) {
            BASE_PACKAGE_NS.SObject_TriggerHandler.beforeInsert(trigger.new);
        }
        ...
    }
}

A: Based on the error message at line 14 of CustomObjects.onAfterInsert() you're doing a query of EntitySubscription without a limit.  You'll need to put a limit of at least 1000 on it.
You're only getting the error message when the method is called via the SObjectDomain class because it has a "with sharing" directive.  As @ca_petersen pointed out in the comments, queries on Entity Subscription can be quite resource intensive when sharing calculations are involved, henced the increase limit requirement for those queries.


text:
Q: Storage setup for large files I need to store over 200TB of data (all types, biggest being video files) and be able to access it over a local network. The files will be accessed for editing or searches. I don't need versioning, but a setup that would keep me safe from harddrive failures would be nice.
Right now the content is on different harddrives, some external drives, some regular. I don't exclude the possibility of buying new/extra drives if necessary. If they will ever be exposed to the web, it wont be to the public, but just a couple of people.
I have no idea what to buy to make this happen. I see some NAS solutions over the internet like this http://www.bestbuy.com/site/a/2266043.p?id=1218317764591&skuId=2266043 but the storage is not enough, plus it doesn't seem to be scalable.
What do you recommend?
Thanks

A: If you want scalability, check out GlusterFS, it's a distributed file-system. If you create a storage cluster, GlusterFS can make it seem like a single file-system. It has support for software-based RAID 0 (striping) and 1 (mirroring).

A: I do large scale FC SAN work and that sort of volume is nothing for most mid-level storage kit. Obviously it's not free and I do understand the instinct to cut costs/corners by just scaling up the free roll-your-own code such as FreeNAS etc. but it's the actual chassis and links that is likely to hold you back going that way.
Presumably you need this available 99.9%+ so you'll need due controllers/heads at least. Do you need file or block level access and if the latter from how many client machines over what protocols? What about speed, both bandwidth and overall IOPS? What about snap capabilities, replication, backup? Do you have a budget in mind? Or any preferred vendors/models.


text:
Q: How to create a redux store with local data storage? I am confused by the docs. I am trying to use Redux-storage middleware and this is how they show the store is created with the middleware:
const middleware = storage.createMiddleware(engine);
const createStoreWithMiddleware = applyMiddleware(middleware)(createStore);
const store = createStoreWithMiddleware(reducer);

But the Redux docs show this:
let store = createStore(
  todos,
  [ 'Use Redux' ], // How do I put here the data from the redux-storage?
  applyMiddleware(middleware) // here goes the redux-storage
)

createStore requires an initial store value to be passed, but I can't load the stored values without having a store. This is a kind of catch 22. What did I miss here?

A: You actually miss nothing and that is intended behavior of redux-storage: there is a gap between creating redux store and the moment it got filled with the stored data. That is because storage engine provided to redux-storage createLoader can have an async nature in general case.
The common pattern to deal with that is following:

*

*Your app starts up with uninitialized store state

*It shows some kind of a preloader to your user

*App creates loader and loads stored state: const load = storage.createLoader(engine); load(store);

*Wait store to be rehydrated and hide preloader.

There is another store peristing lib out there: redux-persist. But initialization process works the same way, except you don't have to call load explicitly.


text:
Q: Binding Raw JSON With The Fields Of Different Classes I am getting following JSON string through http webservice:
Raw JSON String:
[
 {
   field1OfClass1:"someValue",
   field2OfClass1:"someValue",
   field1OfClass2:"someValue",
   field2OfClass3:"someValue"
 }
]

Classes:
class Class1
{
    String field1;
    String field2;
}

class Class2
{
    String field1;
}

class Class3
{
    String field2;
}

In GSON is there any way to parse above said JSON string with the fields of depicted classes?
Thanks

A: As best I know, there is no built-in feature of Gson to automagically map the example JSON structure to the example Java data structure in the original question.  Custom deserialization processing is necessary.


text:
Q: c++ object lifetime extension rules with member initializers In this talk, the author mentions lifetime extension rules extend to member initializers based on the standard. I see the opposite though, i.e. ~Y is called before "Hello" is printed below. Is the author referring to something else?
#include <iostream>
using namespace std;

struct Y {
   ~Y() {
      cout << __PRETTY_FUNCTION__ << "\n";
   }
   Y() {
      cout << __PRETTY_FUNCTION__ << "\n";
   }
};

struct X {
   ~X() {
      cout << __PRETTY_FUNCTION__ << "\n";
   }
   X(const Y& y) : ref(y) {
      cout << __PRETTY_FUNCTION__ << "\n";
   }
   const Y &ref;
};

Y gety() {
   return {};
}

X getx() {
   return gety();
}

int main() {
   const X &ref = X{Y{}};
   cout << "Hello\n";
}

The output is
Y::Y()
X::X(const Y&)
Y::~Y()
Hello
X::~X()

Edit:
I see a difference with the following update that does aggregate initialization
struct X {
   ~X() {
      cout << __PRETTY_FUNCTION__ << "\n";
   }
   /*
   X(const Y& y) : ref(y) {
      cout << __PRETTY_FUNCTION__ << "\n";
   }
   */
   const Y &ref;
};

int main() {
   const X &ref = X{Y{}};
   cout << "Hello\n";
}

in which case the output is
Y::Y()
Hello
X::~X()
Y::~Y()

A: It applies only in the case of aggregate initialization, because otherwise there is a constructor call and the prvalue would be bound to the reference parameter of that constructor, not directly to the reference member.
Also, it does not apply to aggregate initialization with parentheses instead of braces in C++20 and later. (There is a specific exception for this case.)


text:
Q: Managing request in spring microservices with multiple instances of a single service I have a java project and I am trying to scale my project so want to spin up 3 instance of a single microservice.
But I have an issue
to explain
From UI when user logs in, every 10sec a api request(for the specific user) goes to backend which gives the status of spring batch job (either running or not running for a particular user who has logged in). This works fine with only 1 instance.
but when I have 3 instances (instance 1, 2 & 3) of the same application,
say
first request at 10sec goes to instance 1  and job is running for the logged in user - it returns job is running. - correct
second request at 20sec goes to instance 2, since no job is running in instance 2 (job is running in instance 1) it return no job is running - incorrect
third request at 30sec goes to instance 3, since no job is running in instance 3 (job is running in instance 3) it return no job is running - incorrect
How do I make sure to get "job is running" as the status till the job in instance 1 gets over.
I am using spring microservices
please help in on this
Thanks in advance
Need to get job is running till job finishes in instance 1 for the particular user, for every api request

A: I assume that you're using Spring Batch and its in memory job repository.
If you are wanting to scale, you should really use a separate database to keep the metadata of those jobs. As per this example.
Configure and deploy your database, add a dataSource, ensure that your jobRepository uses that dataSource. All servers will then return the same values.
If this cannot be achieved, you should at least ensure that your load balancer has sticky sessions enabled.


text:
Q: Azure Data Explorer Python Sandbox initializing error When using the python sandbox in Azure Data Explorer I get the following error any time I am using the Python Sandbox:
'''Error The sandboxed query was aborted due to a failure in initializing sandboxes'''
This issue started two days ago and I dont have any idea why that is happening.
Any help would be appreciated!

A: Please see: https://learn.microsoft.com/en-us/azure/data-explorer/kusto/concepts/sandboxes#errors
in such cases, it's recommended to open a support ticket for your resource, via the Azure portal.


text:
Q: PHP Warning: preg_match(): Compilation failed: range out of order in character class at offset 44 in wp-includes/class-wp.php on line number 223 I am have tried everything , disable plugins , change the theme , change WordPress, change permalink to default all done still seeing that error,
That's the code for line number 223:
if ( preg_match( "#^$match#", $request_match, $matches ) ||
                    preg_match( "#^$match#", urldecode( $request_match ), $matches ) ) {

                    if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) ) {
                        // This is a verbose page match, let's check to be sure about it.
                        $page = get_page_by_path( $matches[ $varmatch[1] ] );
                        if ( ! $page ) {
                            continue;
                        }

                        $post_status_obj = get_post_status_object( $page->post_status );
                        if ( ! $post_status_obj->public && ! $post_status_obj->protected
                            && ! $post_status_obj->private && $post_status_obj->exclude_from_search ) {
                            continue;
                        }
                    }

                    // Got a match.
                    $this->matched_rule = $match;
                    break;
                }


text:
Q: Find FIRST row that satisfies conditions using either Numpy array or Pandas dataframe. (possibly tricky) I will ask the question in a library agnostic manner as one may be better than the other in this instance. Or maybe another magical library exists?
I have a DB table of about 10,000 records and I know how to create a numpy array or dataframe from it. The data is like so.
   ...
   20,25,1,5
   20,25,2,3
   20,25,4,21
   20,25,5,1
   20,25,9,19
   ...
   45,47,6,20
   45,47,10,2
   45,47,11,56
   45,47,21,41
   ...

In the example search criteria below I am after the value '20' in col4 of this row.
45,47,6,20

*

*Notice the first 2 columns have the same values and define a group.

*Col2 will always be >= to col1 in a row.

*The values in col3 will always be in ascending sequence within a group and not necessarily contiguous.

I am after the value of the cell in col4 using the following search criteria.
I know how to use a mask in numpy to find all the rows whose values are eg 'col1 >= 45 AND col2 <= 47'.
I have a third search value of eg '8' that is to be used to search col3 within the above group (col1, col2, 45 -> 47)
I need to find the FIRST row whose value in col3 <= 8.
Therefore I need to search the rows that have 'col1 >= 45 AND col2 <= 47' in a col3 DESCENDING sequence until row '45,47,6,20' is found. I am after the value '20' in col4.
There will only ever be at most 1 row that will match. It is possible that no row will match the criteria (eg if col3 search value was '3').
I need to do 100s of 1000s of searches at a time so would prefer that no new arrays or dataframes be created unless that has a minimal impact on resources.

A: I suggest using a multiindex for the three first columns and a mask on this multiindex as follows:
# I reproduce a similar dataframe
import pandas as pd
import numpy as np
np.random.seed(123)
v1 = np.random.randint(0, 10, 10)
v2 = v1 + 2
v3 = np.random.randint(0, 10, 10)
v4 = np.random.randint(0, 10, 10)
df = pd.DataFrame({"v1": v1,
                   "v2": v2,
                   "v3": v3,
                   "v4": v4})
# and sort it according to your comments
df = df.sort_values(by=["v1", "v2", "v3"])
df.head()

I get the following dataframe:
  v1  v2  v3  v4
8   0   2   4   0
7   1   3   0   8
9   1   3   1   7
3   1   3   9   4
1   2   4   0   3

# parameters for research
val1 = 1 # the equivalent of your 45
val2 = 3 # the equivalent of your 47
val3 = 2 # the equivalent of your 8

# Set the multiindex
hdf = df.set_index(["v1", "v2", "v3"]).sort_index(ascending=False)
hdf.tail()

Your dataframe now looks as follows:
          v4
v1 v2 v3
2  4  0    3
1  3  9    4
      1    7
      0    8
0  2  4    0

# Define the mask
mask = (hdf.index.get_level_values("v1") >= val1) & \
        (hdf.index.get_level_values("v2") <= val2) &\
        (hdf.index.get_level_values("v3") <= val3)

# Select only the first row returned by the selection using cumsum on mask
print(hdf.loc[mask & (mask.cumsum() == 1), ["v4"]])

And you get:
          v4
v1 v2 v3
1  3  1    7

A: I would:

*

*filter the dataframe to only keep the lines matching the criteria

*groupby on first 2 columns

*apply tail(1) on each group to find the relevant line per group, if any

Code would be:
df[(df['col1']>=45)&(df['col2']<=47)&(df['col3']<=8)].groupby(['col1', 'col2']
                                                              ).tail(1)

With your sample, it gives as expected
   col1  col2  col3  col4
5    45    47     6    20

The good news is that you can search multiple groups in one pass, and it still gives expected results if no rows match the criteria. Demo:
>>> df[(df['col1']>=20)&(df['col2']<=47)&(df['col3']<=8)].groupby(['col1', 'col2']).tail(1)
   col1  col2  col3  col4
3    20    25     5     1
5    45    47     6    20
>>> df[(df['col1']>=20)&(df['col2']<=47)&(df['col3']<=3)].groupby(['col1', 'col2']).tail(1)
   col1  col2  col3  col4
1    20    25     2     3
>>> df[(df['col1']>=45)&(df['col2']<=47)&(df['col3']<=3)].groupby(['col1', 'col2']).tail(1)
Empty DataFrame
Columns: [col1, col2, col3, col4]
Index: []


text:
Q: How can I storage 2 values into one state in react native? I am new to react native and redux.
The scenario is I want to edit some information in profile page .
Let's say the code similar as below:
export default function Profile () {
const [a,setA] = useState(null)
const [b,setB] = useState(null)

Const handle = (a,b) => {storage.dispatch({type:'change':{payload:{ email:a , password: b}})

return (
<>
{Item.map(val =>
<TextArea value = {a || val.email}
onChangeText={t => setA(t)}>
)}
{Item2.map(val2=>
<TextArea value = {b|| val2.password}
onChangeText={t => setB(t)}>
)}
<TouchableHighlight onPress={() => handle(a,b)}>Save <TouchableHighlight/>
</>
)
}

The question is how can I storage 2 value into one state??
Since without filling the new data, the value is null, not the current data, anyone can help me? Thanks a lot !


text: Q: Make font size as large as possible without exceeding screen What I want is change the font size in a text view to fit all of content onto the page while being as large as possible. The text in it is also changing in length so just testing won't work. I also don't want it to have to scroll, but it is a multiline text view. This is in C# and I can't list anything I've tried because I am unsure as to where I should start.


text:
Q: How to reload tmux window in faster way I don't have root in the OS and sometimes t or tt can reload old tmux window. But I wonder how to find how many tmux sessions in OS and reload it in faster way?
xx@bsa0483:~$ t ls
0: 3 windows (created Sat Jun 30 14:23:58 2018) [129x34]

xx@bsa0483:~$ tmux ls
server not found: No such file or directory

But previously, tmux ls worked on the OS:
xx@bsa0248:~$ tmux ls
0: 3 windows (created Sun Jun 10 16:39:33 2018) [123x32]
1: 3 windows (created Sun Jun 10 16:43:10 2018) [123x32]
2: 3 windows (created Sun Jun 10 17:14:23 2018) [98x29]

Related setting for the tmux is in below picture:


text:
Q: GTK app compiles with gcc, but does not compile in codeblocks Looking to implement a drawing canvas in C/C++ and, after failing to make code from the internet work, I came across this sample code which does exactly what I need. The code compiles with the terminal command provided by Martin:
gcc example.c -o example `pkg-config --cflags --libs gtk+-3.0`

In Codeblocks, I've started a new GTK+ Project, added the sample code in it and I get

error: unkown type name 'GtkApplication'

Please advise how to set up CodeBlocks. I've tried tinkering with the Compiler Options in CodeBlocks without any luck.
Follow-up:

*

*I checked which packages I have installed and it seems I have both GTK2 and GTK3.

*I've pasted the output of the "command flags" ...

pkg-config --cflags --libs gtk+-3.0

in CodeBlocks -> Project -> Build Options -> Other compiler options. The previous errors are gone, but new errors are raised:

undefined reference to 'gtk_widget_get_allocated_width'
undefined reference to 'gtk_widget_get_allocated_height'
undefined reference to 'gtk_application_window_new'
undefined reference to 'gtk_application_get_type'
undefined reference to 'gtk_window_set_application'
undefined reference to 'gtk_box_new'
undefined reference to 'gtk_application_new'

The motivation behind all this is to use a debugger (I am not able to work with text-based gdb).
Many thanks,
Dani

A: Found the solution:
In CodeBlocks, Project -> Build Options ->Compiler settings -> Other compiler options, add
`pkg-config --cflags gtk+-3.0`

In Project -> Build Options ->Linker settings -> Other linker options, add
`pkg-config --libs gtk+-3.0`


text:
Q: Undefined mixin susy-grid-background in susy 2 I'm trying to get Susy 2 to work on my computer. I have tried several ways of installing but none of them seem to completely work.
First attempt:
Installed compass, susy and sass manually through a gem install compass etc. I then created a project (compass create) and included the @import 'susy'. All seemed well but then the span mixin would not work.
Second attempt:
Uninstalled compass, sass and susy. Installed the gem compass-susy-plugin. Created a compass project with -r susy -u susy. This time span worked but the susy-grid-background mixin was undefined.
Third attempt:
Uninstalled compass susy plugin, compass and sass. Installed sass, susy and the gem compass --pre. Now the span mixin works but the susy-grid-background mixin is undefined. We are really not getting this. It is supposed to be really easy but something is going terribly wrong here.
I now have this Gem list:
Compass (1.0.0.alpha.19),
Sass (3.3.8, 3.2.19),
Susy (2.1.2)
I have tested this on two different computers (mac and windows). Same results.
My screen.scss has a include of base and in the base there is an include of susy. Config.rb has the require susy in it. There is no package.json file.
I hope someone has some pointers.

A: If it's just the grid that's the problem, I use:
@include container(show);

or
@include container(show overlay);

Have you looked up the documentation on http://susy.readthedocs.org/en/latest/ ?