问:
JQuery datepicker- 2 inputs From and To
I am using the Jquery datepicker plugin  with this timepicker addon in two input boxes, one for the "From" date and the second with the "To" date.

When I set the first one, I want the second one to be one day after the date selected in the first,disabling all the dates earlier than the date selected in the "From" date

If the "To" date is selected first, then the "From" date is set to the day before the "To" date.

I have found some examples, but I don't know how to get the date with time.So,If I  ,for example, select 13/12/2010 15:50 in the "From" date, the date in the "To" date is set to 14/12/2010 15:50 or at least to 14/12/2010 00:00.

 EDITED***

I've just found this piece of code that works as I want , but without the timepicker addon.

```<code> $(function(){

  $('#dateFrom').datepicker({
    dateFormat: 'dd/mm/yy',
    onSelect: function(dateText, inst) {
         $('#dateTo').datepicker('option','minDate', new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay));
          }
  });
  $('#dateTo').datepicker({
    dateFormat: 'dd/mm/yy',
    onSelect: function(dateText, inst) {
         $('#dateFrom').datepicker('option','maxDate', new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay));
    }
  });

});
</code>```

Based on the above code, would it be possible to adapt it ,so that I can use it with the timepicker addon?

Thanks beforehand

答:
I've got most of it, but could not figure out how to set the hourMin and minuteMin after the widget had already been initialized.  Given the following HTML:

```<code><label for="from">From</label><input id="from" name="from" />
<label for="to">To</label><input id="to" name="to" />
</code>```

And this JS:

```<code>$("#from").datetimepicker();
$("#to").datetimepicker({
    beforeShow: function(input, inst) {
        var $toDateInput = $("#to");
        var fromDate = $("#from").datetimepicker("getDate");
        var toDate = $toDateInput.datetimepicker("getDate");
        var afterFromDate;

        if (fromDate) {
            if (!toDate || (toDate <= fromDate)) {
                afterFromDate = new Date(fromDate.toUTCString());
                afterFromDate.setDate(afterFromDate.getDate() + 1);
                $toDateInput.datetimepicker("setDate", afterFromDate);
            }
            $toDateInput.datetimepicker("option", "minDate", fromDate);
        }
    }
});
</code>```

See it here: http://jsfiddle.net/RWjtL/3/

Most of your criteria are met, but there are a few things that are off:

When you set the 'To' field blank, the 'From' datepicker's min date is not removed.  I tried setting the minDate option to null and "" and got weird behavior.  Here's a documented issue that could be related.

The beforeShow method is called multiple times.  I think this is because of the call to setDate inside the handler, but can't be sure.

As stated above, I could not manage to set hourMin and minuteMin after the fact, and setting the minDate doesn't seem to respect the time part of the date.

The author's GitHub page has a list of issues, some of which seem related to the issues I ran into.  Hope that gets you started at least.

Title: JQuery datepicker- 2 inputs From and To

Body:
I am using the Jquery datepicker plugin  with this timepicker addon in two input boxes, one for the "From" date and the second with the "To" date.

When I set the first one, I want the second one to be one day after the date selected in the first,disabling all the dates earlier than the date selected in the "From" date

If the "To" date is selected first, then the "From" date is set to the day before the "To" date.

I have found some examples, but I don't know how to get the date with time.So,If I  ,for example, select 13/12/2010 15:50 in the "From" date, the date in the "To" date is set to 14/12/2010 15:50 or at least to 14/12/2010 00:00.

 EDITED***

I've just found this piece of code that works as I want , but without the timepicker addon.

 $(function(){

  $('#dateFrom').datepicker({
    dateFormat: 'dd/mm/yy',
    onSelect: function(dateText, inst) {
         $('#dateTo').datepicker('option','minDate', new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay));
          }
  });
  $('#dateTo').datepicker({
    dateFormat: 'dd/mm/yy',
    onSelect: function(dateText, inst) {
         $('#dateFrom').datepicker('option','maxDate', new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay));
    }
  });

});

Based on the above code, would it be possible to adapt it ,so that I can use it with the timepicker addon?

Thanks beforehand

Body:
I've got most of it, but could not figure out how to set the hourMin and minuteMin after the widget had already been initialized.  Given the following HTML:

<label for="from">From</label><input id="from" name="from" />
<label for="to">To</label><input id="to" name="to" />

And this JS:

$("#from").datetimepicker();
$("#to").datetimepicker({
    beforeShow: function(input, inst) {
        var $toDateInput = $("#to");
        var fromDate = $("#from").datetimepicker("getDate");
        var toDate = $toDateInput.datetimepicker("getDate");
        var afterFromDate;

        if (fromDate) {
            if (!toDate || (toDate <= fromDate)) {
                afterFromDate = new Date(fromDate.toUTCString());
                afterFromDate.setDate(afterFromDate.getDate() + 1);
                $toDateInput.datetimepicker("setDate", afterFromDate);
            }
            $toDateInput.datetimepicker("option", "minDate", fromDate);
        }
    }
});

See it here: http://jsfiddle.net/RWjtL/3/

Most of your criteria are met, but there are a few things that are off:

When you set the 'To' field blank, the 'From' datepicker's min date is not removed.  I tried setting the minDate option to null and "" and got weird behavior.  Here's a documented issue that could be related.

The beforeShow method is called multiple times.  I think this is because of the call to setDate inside the handler, but can't be sure.

As stated above, I could not manage to set hourMin and minuteMin after the fact, and setting the minDate doesn't seem to respect the time part of the date.

The author's GitHub page has a list of issues, some of which seem related to the issues I ran into.  Hope that gets you started at least.


来源: stackexchange

问:
How to make long press gesture in Xamarin Forms?
Could you please let me know how can I recognize long press gesture in Xamarin Forms application?

A few days before I used TapGestureRecognizer

TapGestureRecognizer imageTap = new TapGestureRecognizer();
imageTap.Tapped += (sender, args) => this.OnClickImage;
image.GestureRecognizers.Add(imageTap);
```

<p>But I don't know how to make long press gesture according to this thread from xamarin forum</p>

<p>It should looks something like this, but it does not work.</p>

<pre class="lang-cs prettyprint-override"><code>var dumpParam = new RelayGesture((g, x) => DisplayAlert("Title", "Hello message", "Cancel"));

book.Cover.SetValue(Gestures.InterestsProperty, new GestureCollection() {
    new GestureInterest
        {
            GestureType = GestureType.LongPress
            GestureCommand = // what should I set?
            GestureParameter = dumpParam
        }
 });
</code>```

How to set my custom handler method?

答:
Make use of XLabs.Forms nuget package, which make long press and other gesture in PCL code only.
Use of XLabs.Forms package will reduce the need of custom rendering in individual platforms...
Add XAML code in .xaml file and attached event handler in .xaml.cs file..
It is working fine in Android..

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="MultiImage.Page1"
         xmlns:lc="clr-namespace:XLabs.Forms.Controls;assembly=XLabs.Forms"
         xmlns:lb="clr-namespace:XLabs.Forms.Behaviors;assembly=XLabs.Forms">
<ContentPage.Content>
    <lc:GesturesContentView ExcludeChildren="False" GestureRecognized="GesturesContentView_GestureRecognized">
         <lb:Gestures.Interests>
                <lb:GestureCollection>
                    <lb:GestureInterest GestureType="SingleTap"/>
                    <lb:GestureInterest GestureType="LongPress"/>
                    <lb:GestureInterest GestureType="DoubleTap"/>
                </lb:GestureCollection>
          </lb:Gestures.Interests>
          <Image Source="Myimage.png" Aspect="AspectFit" HeightRequest="100"/>
        </lc:GesturesContentView>
</ContentPage.Content>
```

<p>C# backend code: </p>

<pre class="lang-cs prettyprint-override"><code>private void GesturesContentView_GestureRecognized(object sender, GestureResult e)
{
    switch (e.GestureType)
    {
        case GestureType.LongPress:
            //Add code here
            break;
        case GestureType.SingleTap:
            // Add code here
            break;
        case GestureType.DoubleTap:
            // Add code here
            break;
        default:
            break;
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Could you please let me know how can I recognize long press gesture in Xamarin Forms application?

A few days before I used TapGestureRecognizer

TapGestureRecognizer imageTap = new TapGestureRecognizer();
imageTap.Tapped += (sender, args) => this.OnClickImage;
image.GestureRecognizers.Add(imageTap);

But I don't know how to make long press gesture according to this thread from xamarin forum

It should looks something like this, but it does not work.

var dumpParam = new RelayGesture((g, x) => DisplayAlert("Title", "Hello message", "Cancel"));

book.Cover.SetValue(Gestures.InterestsProperty, new GestureCollection() {
    new GestureInterest
        {
            GestureType = GestureType.LongPress
            GestureCommand = // what should I set?
            GestureParameter = dumpParam
        }
 });

How to set my custom handler method?

Body:
Make use of XLabs.Forms nuget package, which make long press and other gesture in PCL code only.
Use of XLabs.Forms package will reduce the need of custom rendering in individual platforms...
Add XAML code in .xaml file and attached event handler in .xaml.cs file..
It is working fine in Android..

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="MultiImage.Page1"
         xmlns:lc="clr-namespace:XLabs.Forms.Controls;assembly=XLabs.Forms"
         xmlns:lb="clr-namespace:XLabs.Forms.Behaviors;assembly=XLabs.Forms">
<ContentPage.Content>
    <lc:GesturesContentView ExcludeChildren="False" GestureRecognized="GesturesContentView_GestureRecognized">
         <lb:Gestures.Interests>
                <lb:GestureCollection>
                    <lb:GestureInterest GestureType="SingleTap"/>
                    <lb:GestureInterest GestureType="LongPress"/>
                    <lb:GestureInterest GestureType="DoubleTap"/>
                </lb:GestureCollection>
          </lb:Gestures.Interests>
          <Image Source="Myimage.png" Aspect="AspectFit" HeightRequest="100"/>
        </lc:GesturesContentView>
</ContentPage.Content>

C# backend code:

private void GesturesContentView_GestureRecognized(object sender, GestureResult e)
{
    switch (e.GestureType)
    {
        case GestureType.LongPress:
            //Add code here
            break;
        case GestureType.SingleTap:
            // Add code here
            break;
        case GestureType.DoubleTap:
            // Add code here
            break;
        default:
            break;
    }


问:
Class instances passed to ConcurrentStack.Push vanish?
EDIT: TL;DR ConcurrentStack.Push is not playing nice in a multithreaded environment and I am clueless as to why.

Summary

After trying to write a "custom ThreadPool", dubbed the "ThreadFactory", I started to stumble into some peculiar issues.

Namely, ConcurrentStack.Push seems to not always push the passed parameter to the stack.

Source

ThreadFactory.cs

using System.Collections.Concurrent;

namespace CustomThreadFactory
{
    public class ThreadFactory
    {
        public uint Working
        {
            get
            {
                return (uint)( _numWorkers - _available.Count );    // Returns how many workers are currently busy
            }

            set { }
        }

        private uint _numWorkers;                                   // Stores the amount of workers

        private ConcurrentStack<ThreadWorker> _available;           // Stores the available workers
        private ConcurrentQueue<ThreadTask> _backlog;               // ThreadTask backlog, ThreadTasks queue up here if there're no workers available

        public ThreadFactory( uint numWorkers = 8 )
        {
            _numWorkers = numWorkers;

            _available = new ConcurrentStack<ThreadWorker>();
            _backlog = new ConcurrentQueue<ThreadTask>();

            for ( uint i = 0; i < numWorkers; i++ )
                _available.Push( new ThreadWorker( this ) );        // Populate worker stack
        }

        public bool Continue( ThreadWorker sender, ref ThreadTask task )
        {                                                           // This function is called by ThreadWorker to decide whether it should lock next call
            if( _backlog.Count > 0 )                                // More work available = Do not lock, a new ThreadTask has been set
            {
                while ( !_backlog.TryDequeue( out task ) ) ;        // Busy-wait TryDequeue on the backlog queue, this should only take a couple cycles (if not one)
                return false;                                       // ThreadWorker._lockThread boolean is set to false here, it won't lock next cycle
            }
            else
            {
                task = null;                                        // No more tasks available, last task is marked for GC
                _available.Push( sender );                          // Push the worker back onto the available stack

                return true;                                        // ThreadWorker._lockThread boolean is set to true here, the worker thread will now lock and wait
            }
        }

        public void Enqueue( ThreadTask task )
        {
            if( _available.Count > 0 )                              // If there's a worker available (and sleeping/locked), wake them and pass the new task
            {
                ThreadWorker worker;
                while ( !_available.TryPop( out worker ) ) ;        // Busy-wait TryPop on worker stack, this should only take a couple cycles (if not one)

                worker.Wake( task );
            }
            else                                                    // Otherwise this task will be added to the backlog queue
            {
                _backlog.Enqueue( task );
            }
        }
    }
}
```

<p><strong>ThreadWorker.cs</strong>  </p>

<pre class="lang-cs prettyprint-override"><code>using System.Threading;

namespace CustomThreadFactory
{
    public class ThreadWorker
    {
        private ThreadFactory _factory;         // Parent ThreadFactory

        private volatile bool _lockThread;      // Should lock on next cycle?
        private object _threadLock;             // Locking object
        private Thread _thread;                 // Worker thread

        private ThreadTask _task;               // Current task

        public ThreadWorker( ThreadFactory parent )
        {
            _factory = parent;

            _lockThread = true;
            _threadLock = new object();

            _thread = new Thread( _Work );
            _thread.Start();
        }

        ~ThreadWorker()
        {
            _thread?.Abort();                   // If _thread is "valid", _thread.Abort
            _threadLock = null;                 // Mark for GC (not sure if required)
        }

        private void _Work()
        {
            while( true )
            {
                if ( _lockThread )
                    lock ( _threadLock )
                        Monitor.Wait( _threadLock );
                // ---

                _task?.Run();                   // If _task is "valid", _task.Run

                                                // If _factory has more tasks, _task will be set and _lockThread will be false
                                                // Otherwise the worker thread will lock on the next cycle
                _lockThread = _factory.Continue( this, ref _task );
            }
        }

        public void Wake( ThreadTask task )
        {
            _task = task;                       // Set _task
            _lockThread = false;                // Don't lock the thread unless the ThreadFactory specifically "says so"

            lock ( _threadLock )
                Monitor.Pulse( _threadLock );   // Unlock if currently locked
        }
    }
}
</code>```

ThreadTask.cs

namespace CustomThreadFactory
{
    public delegate void ThreadAction( object parameters );

    public class ThreadTask
    {
        private ThreadAction _action;               // Delegate action
        private object _parameters;                 // Object parameter(s)

        public ThreadTask( ThreadAction action )    // Parameterless constructor
        {
            _action = action;
            _parameters = null;
        }

        public ThreadTask( ThreadAction action, object parameters )
        {
            _action = action;
            _parameters = parameters;
        }

        public void Run()                          // Executes the delegate, passing the stored parameters (or null)
        {
            _action( _parameters );
        }
    }
}
```

<p><strong>Program.cs</strong>  </p>

<pre class="lang-cs prettyprint-override"><code>namespace CustomThreadFactory
{
    class Program
    {
        static void Main( string[] args )
        {
            ThreadFactory f = new ThreadFactory();

            Stopwatch s = new Stopwatch();
            s.Start();

            for ( uint i = 0; i < 512; i++ )
            {
                f.Enqueue( new ThreadTask( ( object parameters ) =>
                {
                    for ( uint x = 0; x < 2048; x++ )
                    {
                        long y = (long)Math.Pow( x, 2 );
                    }
                } ) );
            }

            while ( f.Working > 0 )
                Thread.Sleep( 1 );

            s.Stop();
            Console.WriteLine( string.Format( "Took {0}ms", s.Elapsed.TotalMilliseconds - 1 ) );

            Console.ReadLine();
        }
    }
}
</code>```

Issue

The problem seems to lie within ThreadFactory.Continue, if _backlog.Count > 0 is not met, the ThreadWorker sender is supposed to be readded to the available workers stack.

Though this doesn't always happen. (Implying that sometimes it does readd all the ThreadWorkers successfully)

I have tried:

Debug vs. Release (no difference)

Console.WriteLine( "Thread now available" ) in ThreadWorker.Continue, always prints the correct amount of lines (default 8), though not all ThreadWorkers are pushed to the available workers stack

EDIT: lock( _stackLock ) around _available.Push( sender ) (no difference)

From here on I can't really see what's causing the ConcurrentStack to not push the ThreadWorkers back on to the available workers stack.

A helping hand would be very much appreciated.

答:
You have some race conditions and there is a problem with the Monitor.Lock / Monitor.Pulse. I changed some of your code to get it basicly working;

Changes in ThreadFactory

```<code>public class ThreadFactory
{
    ...

    public ThreadTask Continue( ThreadWorker sender )
    {
        if ( _backlog.Count > 0 )
        {
            ThreadTask task;
            do
            {
                if ( _backlog.TryDequeue( out task ) )
                {
                    return task;
                }
            }
            while ( _backlog.Count > 0 );
        }

        _available.Push( sender );
        return null;

    }

    public void Enqueue( ThreadTask task )
    {
        if ( _available.Count > 0 )                              // If there's a worker available (and sleeping/locked), wake them and pass the new task
        {
            ThreadWorker worker;
            do
            {
                if ( _available.TryPop( out worker ) )
                {
                    worker.Wake( task );
                }
            }
            while ( _available.Count > 0 );        // Busy-wait TryPop on worker stack, this should only take a couple cycles (if not one)
        }
        else                                                    // Otherwise this task will be added to the backlog queue
        {
            _backlog.Enqueue( task );
        }
    }
}
</code>```

and the whole ThreadWorker

```<code>public class ThreadWorker
{
    private ThreadFactory _factory;         // Parent ThreadFactory

    private AutoResetEvent _event = new AutoResetEvent( false );
    private Thread _thread;                 // Worker thread
    private volatile ThreadTask _task;               // Current task

    public ThreadWorker( ThreadFactory parent, string name = null )
    {
        Name = name;

        _factory = parent;

        _thread = new Thread( _Work );
        _thread.Start();
    }

    public string Name { get; }

    ~ThreadWorker()
    {
        _thread?.Abort();                   // If _thread is "valid", _thread.Abort
    }

    private void _Work()
    {
        while ( true )
        {
            _event.WaitOne();
            _task?.Run();                   // If _task is "valid", _task.Run

            // If _factory has more tasks, _task will be set and _lockThread will be false
            // Otherwise the worker thread will lock on the next cycle
            Wake( _factory.Continue( this ) );
        }
    }

    public void Wake( ThreadTask task )
    {
        _task = task;
        if ( _task != null )
        {
            _event.Set();
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
EDIT: TL;DR ConcurrentStack.Push is not playing nice in a multithreaded environment and I am clueless as to why.

Summary

After trying to write a "custom ThreadPool", dubbed the "ThreadFactory", I started to stumble into some peculiar issues.

Namely, ConcurrentStack.Push seems to not always push the passed parameter to the stack.

Source

ThreadFactory.cs

using System.Collections.Concurrent;

namespace CustomThreadFactory
{
    public class ThreadFactory
    {
        public uint Working
        {
            get
            {
                return (uint)( _numWorkers - _available.Count );    // Returns how many workers are currently busy
            }

            set { }
        }

        private uint _numWorkers;                                   // Stores the amount of workers

        private ConcurrentStack<ThreadWorker> _available;           // Stores the available workers
        private ConcurrentQueue<ThreadTask> _backlog;               // ThreadTask backlog, ThreadTasks queue up here if there're no workers available

        public ThreadFactory( uint numWorkers = 8 )
        {
            _numWorkers = numWorkers;

            _available = new ConcurrentStack<ThreadWorker>();
            _backlog = new ConcurrentQueue<ThreadTask>();

            for ( uint i = 0; i < numWorkers; i++ )
                _available.Push( new ThreadWorker( this ) );        // Populate worker stack
        }

        public bool Continue( ThreadWorker sender, ref ThreadTask task )
        {                                                           // This function is called by ThreadWorker to decide whether it should lock next call
            if( _backlog.Count > 0 )                                // More work available = Do not lock, a new ThreadTask has been set
            {
                while ( !_backlog.TryDequeue( out task ) ) ;        // Busy-wait TryDequeue on the backlog queue, this should only take a couple cycles (if not one)
                return false;                                       // ThreadWorker._lockThread boolean is set to false here, it won't lock next cycle
            }
            else
            {
                task = null;                                        // No more tasks available, last task is marked for GC
                _available.Push( sender );                          // Push the worker back onto the available stack

                return true;                                        // ThreadWorker._lockThread boolean is set to true here, the worker thread will now lock and wait
            }
        }

        public void Enqueue( ThreadTask task )
        {
            if( _available.Count > 0 )                              // If there's a worker available (and sleeping/locked), wake them and pass the new task
            {
                ThreadWorker worker;
                while ( !_available.TryPop( out worker ) ) ;        // Busy-wait TryPop on worker stack, this should only take a couple cycles (if not one)

                worker.Wake( task );
            }
            else                                                    // Otherwise this task will be added to the backlog queue
            {
                _backlog.Enqueue( task );
            }
        }
    }
}

ThreadWorker.cs

using System.Threading;

namespace CustomThreadFactory
{
    public class ThreadWorker
    {
        private ThreadFactory _factory;         // Parent ThreadFactory

        private volatile bool _lockThread;      // Should lock on next cycle?
        private object _threadLock;             // Locking object
        private Thread _thread;                 // Worker thread

        private ThreadTask _task;               // Current task

        public ThreadWorker( ThreadFactory parent )
        {
            _factory = parent;

            _lockThread = true;
            _threadLock = new object();

            _thread = new Thread( _Work );
            _thread.Start();
        }

        ~ThreadWorker()
        {
            _thread?.Abort();                   // If _thread is "valid", _thread.Abort
            _threadLock = null;                 // Mark for GC (not sure if required)
        }

        private void _Work()
        {
            while( true )
            {
                if ( _lockThread )
                    lock ( _threadLock )
                        Monitor.Wait( _threadLock );
                // ---

                _task?.Run();                   // If _task is "valid", _task.Run

                                                // If _factory has more tasks, _task will be set and _lockThread will be false
                                                // Otherwise the worker thread will lock on the next cycle
                _lockThread = _factory.Continue( this, ref _task );
            }
        }

        public void Wake( ThreadTask task )
        {
            _task = task;                       // Set _task
            _lockThread = false;                // Don't lock the thread unless the ThreadFactory specifically "says so"

            lock ( _threadLock )
                Monitor.Pulse( _threadLock );   // Unlock if currently locked
        }
    }
}

ThreadTask.cs

namespace CustomThreadFactory
{
    public delegate void ThreadAction( object parameters );

    public class ThreadTask
    {
        private ThreadAction _action;               // Delegate action
        private object _parameters;                 // Object parameter(s)

        public ThreadTask( ThreadAction action )    // Parameterless constructor
        {
            _action = action;
            _parameters = null;
        }

        public ThreadTask( ThreadAction action, object parameters )
        {
            _action = action;
            _parameters = parameters;
        }

        public void Run()                          // Executes the delegate, passing the stored parameters (or null)
        {
            _action( _parameters );
        }
    }
}

Program.cs

namespace CustomThreadFactory
{
    class Program
    {
        static void Main( string[] args )
        {
            ThreadFactory f = new ThreadFactory();

            Stopwatch s = new Stopwatch();
            s.Start();

            for ( uint i = 0; i < 512; i++ )
            {
                f.Enqueue( new ThreadTask( ( object parameters ) =>
                {
                    for ( uint x = 0; x < 2048; x++ )
                    {
                        long y = (long)Math.Pow( x, 2 );
                    }
                } ) );
            }

            while ( f.Working > 0 )
                Thread.Sleep( 1 );

            s.Stop();
            Console.WriteLine( string.Format( "Took {0}ms", s.Elapsed.TotalMilliseconds - 1 ) );

            Console.ReadLine();
        }
    }
}

Issue

The problem seems to lie within ThreadFactory.Continue, if _backlog.Count > 0 is not met, the ThreadWorker sender is supposed to be readded to the available workers stack.

Though this doesn't always happen. (Implying that sometimes it does readd all the ThreadWorkers successfully)

I have tried:

Debug vs. Release (no difference)

Console.WriteLine( "Thread now available" ) in ThreadWorker.Continue, always prints the correct amount of lines (default 8), though not all ThreadWorkers are pushed to the available workers stack

EDIT: lock( _stackLock ) around _available.Push( sender ) (no difference)

From here on I can't really see what's causing the ConcurrentStack to not push the ThreadWorkers back on to the available workers stack.

A helping hand would be very much appreciated.

Body:
You have some race conditions and there is a problem with the Monitor.Lock / Monitor.Pulse. I changed some of your code to get it basicly working;

Changes in ThreadFactory

public class ThreadFactory
{
    ...

    public ThreadTask Continue( ThreadWorker sender )
    {
        if ( _backlog.Count > 0 )
        {
            ThreadTask task;
            do
            {
                if ( _backlog.TryDequeue( out task ) )
                {
                    return task;
                }
            }
            while ( _backlog.Count > 0 );
        }

        _available.Push( sender );
        return null;

    }

    public void Enqueue( ThreadTask task )
    {
        if ( _available.Count > 0 )                              // If there's a worker available (and sleeping/locked), wake them and pass the new task
        {
            ThreadWorker worker;
            do
            {
                if ( _available.TryPop( out worker ) )
                {
                    worker.Wake( task );
                }
            }
            while ( _available.Count > 0 );        // Busy-wait TryPop on worker stack, this should only take a couple cycles (if not one)
        }
        else                                                    // Otherwise this task will be added to the backlog queue
        {
            _backlog.Enqueue( task );
        }
    }
}

and the whole ThreadWorker

public class ThreadWorker
{
    private ThreadFactory _factory;         // Parent ThreadFactory

    private AutoResetEvent _event = new AutoResetEvent( false );
    private Thread _thread;                 // Worker thread
    private volatile ThreadTask _task;               // Current task

    public ThreadWorker( ThreadFactory parent, string name = null )
    {
        Name = name;

        _factory = parent;

        _thread = new Thread( _Work );
        _thread.Start();
    }

    public string Name { get; }

    ~ThreadWorker()
    {
        _thread?.Abort();                   // If _thread is "valid", _thread.Abort
    }

    private void _Work()
    {
        while ( true )
        {
            _event.WaitOne();
            _task?.Run();                   // If _task is "valid", _task.Run

            // If _factory has more tasks, _task will be set and _lockThread will be false
            // Otherwise the worker thread will lock on the next cycle
            Wake( _factory.Continue( this ) );
        }
    }

    public void Wake( ThreadTask task )
    {
        _task = task;
        if ( _task != null )
        {
            _event.Set();
        }
    }
}


问:
how to extract data from namedtuple in file handling in python
Having trouble extracting data from namedtuple in file handling in python.
It shows property object at --- location

```<code>from collections import namedtuple

filename=input("Enter name of file ")
Data=namedtuple('Data',['name','id','balance'])

def write():
    file=open(filename,'a')
    name=input("Enter name ")
    idee=input("Enter ID ")
    bal=input("Enter balance ")
    data=Data(name,idee,bal)
    file.write(str(data))
    file.close()

def read():
    file=open(filename,'r')
    for line in file:
        print(Data.name,"\t",Data.id,"\t",Data.balance,"\n")

write()
write()
read()
</code>```

What should I do to extract data in data.name?

答:
When you write the data to the file it is just only a string and you can get only string when you read it.</p>

```<code>from collections import namedtuple
import pickle
filename=input("Enter name of file ")
Data=namedtuple('Data',['name','id','balance'])

def write():

    name=input("Enter name ")
    idee=input("Enter ID ")
    bal=input("Enter balance ")
    data=Data(name,idee,bal)
    with open(filename,'ab') as f:
       pickle.dump(data,f)

def read():
    with open(filename,'rb') as f:
       while True:
        try:
         data=pickle.load(f)
         print(data.name,"\t",data.id,"\t",data.balance,"\n")
        except:
            break

write()
write()
read()
</code>```

Body:
Having trouble extracting data from namedtuple in file handling in python.
It shows property object at --- location

from collections import namedtuple

filename=input("Enter name of file ")
Data=namedtuple('Data',['name','id','balance'])

def write():
    file=open(filename,'a')
    name=input("Enter name ")
    idee=input("Enter ID ")
    bal=input("Enter balance ")
    data=Data(name,idee,bal)
    file.write(str(data))
    file.close()

def read():
    file=open(filename,'r')
    for line in file:
        print(Data.name,"\t",Data.id,"\t",Data.balance,"\n")

write()
write()
read()

What should I do to extract data in data.name?

Body:
When you write the data to the file it is just only a string and you can get only string when you read it.

from collections import namedtuple
import pickle
filename=input("Enter name of file ")
Data=namedtuple('Data',['name','id','balance'])

def write():

    name=input("Enter name ")
    idee=input("Enter ID ")
    bal=input("Enter balance ")
    data=Data(name,idee,bal)
    with open(filename,'ab') as f:
       pickle.dump(data,f)

def read():
    with open(filename,'rb') as f:
       while True:
        try:
         data=pickle.load(f)
         print(data.name,"\t",data.id,"\t",data.balance,"\n")
        except:
            break

write()
write()
read()


问:
Sending instructions to a thread which is waiting for TCP?
I'm trying to understand multi-threading in TCP so I'm coding a basic telnet text "router".

using ReadLine() each thread using a TCP listener will wait for input from the telnet client and then respond based on the text which is sent. I have this working with multiple threads and multiple telnet clients.

I want to conditionally send messages to all threads.
For example, if the text sent from any one thread is "Alert!" then I want every thread for connected clients to execute WriteLine("Alert!")

Does this make sense?
My problem is that I don't know how to make one thread raise an event in another thread.

答:
Don't think of threads as data.  Think of them as constructs.

Obviously to have class A raise an event in class B, B must reference A and subscribe to its event.

But honestly, I think you are going about it the wrong way.  Have a single TCP listener.  When a message comes in, you'll get a web request object and you can process in its own thread.  When processing the thread, if you find word "Alert", generate an event to a higher level class.  Then handle the event and do whatever needs to be done.  Example architecture:

Manager instantiates TcpHandler and subscribes to its AlertReceived event.
TcpHandler instantiates MessageProcessor and subscribes to its MessageReceived event.

When TcpHandler reads something off its TcpListener object, fire off the MessageProcessor class and have it read the actual data on another thread.

Fire the MessageReceived event.  Then in the TcpHandler class, handle the event.  If the data received is "Alert", fire the AlertReceived event.

The Manager class will catch the event and do whatever else you then desire.

ContentLicense: CC BY-SA 2.5


问:
program that determines if array is ascending, descending, or random(C language)
i have to build a program that scans "size", then array in the size of "size".
returns 1 if ascending, -1 if descending, and 0 if neither.

so for I've came up with this, and its not working.

```<code>int UpOrDown(int *arr,int size)
{
int i,j,flag;
if(arr[0]<arr[1])// ascending or random
{
    flag=1;
    {
        for(i=1;i<size;i++)
            if(arr[i]>arr[i+1])
                flag=0;
    }
    if (flag=0) return 0;
    else return 1;
}
else //descending or random
{
    flag=-1;
        if(arr[0]>arr[1])
        {
            for(i=1;i<size;i++)
                if(arr[i]<arr[i+1])
                    flag=0;
        }
        if (flag=0) return 0;
        else return -1;
}
</code>```

i'd appreciate some guidance.

答:
For starters in the presented function implementation there is absent the closing brace.

In general the value of the parameter size can be equal to 0 or 1. In this case the function has undefined behavior due to the first statement

```<code>if(arr[0]<arr[1])
</code>```

Moreover as the parameter has the type int then the user can supply a negative value. So it is better to declare the parameter as having type size_t.

Also in the loops like this

```<code>    for(i=1;i<size;i++)
        if(arr[i]>arr[i+1])
            flag=0;
</code>```

there is an attempt to access beyond the array when the variable i is equal to size - 1.

In this code snippet that corresponds to the else statement

```<code>else //descending or random
{
    flag=-1;
        if(arr[0]>arr[1])
        {
            for(i=1;i<size;i++)
                if(arr[i]<arr[i+1])
                    flag=0;
        }
        if (flag=0) return 0;
        else return -1;
}
</code>```

the function can return -1 even if the array has only two elements that are equal each other.

I can suggest the following function implementation. At least it works.:)

```<code>#include <stdio.h>

int UpOrDown(const int a[], size_t n)
{
    int ordered = !(n < 2 || a[0] == a[1]);

    if (ordered)
    {
        ordered = a[0] < a[1];
        size_t i = 2;

        while (i < n && ordered == a[i - 1] < a[i]) i++;

        if (i != n)
        {
            ordered = 0;
        }
        else
        {
            ordered = ordered == 0 ? -1 : 1;
        }
    }

    return ordered;
}

int main( void )
{
    int a[] = { 1 };
    int b[] = { 1, 1 };
    int c[] = { 1, 2 };
    int d[] = { 2, 1 };
    int e[] = { 1, 2, 2 };

    printf("a: %d\n", UpOrDown(a, sizeof(a) / sizeof(*a)));
    printf("b: %d\n", UpOrDown(b, sizeof(b) / sizeof(*b)));
    printf("c: %d\n", UpOrDown(c, sizeof(c) / sizeof(*c)));
    printf("d: %d\n", UpOrDown(d, sizeof(d) / sizeof(*d)));
    printf("e: %d\n", UpOrDown(e, sizeof(e) / sizeof(*e)));
}
</code>```

The program output is

```<code>a: 0
b: 0
c: 1
d: -1
e: 0
</code>```

Body:
i have to build a program that scans "size", then array in the size of "size".
returns 1 if ascending, -1 if descending, and 0 if neither.

so for I've came up with this, and its not working.

int UpOrDown(int *arr,int size)
{
int i,j,flag;
if(arr[0]<arr[1])// ascending or random
{
    flag=1;
    {
        for(i=1;i<size;i++)
            if(arr[i]>arr[i+1])
                flag=0;
    }
    if (flag=0) return 0;
    else return 1;
}
else //descending or random
{
    flag=-1;
        if(arr[0]>arr[1])
        {
            for(i=1;i<size;i++)
                if(arr[i]<arr[i+1])
                    flag=0;
        }
        if (flag=0) return 0;
        else return -1;
}

i'd appreciate some guidance.

Body:
For starters in the presented function implementation there is absent the closing brace.

In general the value of the parameter size can be equal to 0 or 1. In this case the function has undefined behavior due to the first statement

if(arr[0]<arr[1])

Moreover as the parameter has the type int then the user can supply a negative value. So it is better to declare the parameter as having type size_t.

Also in the loops like this

    for(i=1;i<size;i++)
        if(arr[i]>arr[i+1])
            flag=0;

there is an attempt to access beyond the array when the variable i is equal to size - 1.

In this code snippet that corresponds to the else statement

else //descending or random
{
    flag=-1;
        if(arr[0]>arr[1])
        {
            for(i=1;i<size;i++)
                if(arr[i]<arr[i+1])
                    flag=0;
        }
        if (flag=0) return 0;
        else return -1;
}

the function can return -1 even if the array has only two elements that are equal each other.

I can suggest the following function implementation. At least it works.:)

#include <stdio.h>

int UpOrDown(const int a[], size_t n)
{
    int ordered = !(n < 2 || a[0] == a[1]);

    if (ordered)
    {
        ordered = a[0] < a[1];
        size_t i = 2;

        while (i < n && ordered == a[i - 1] < a[i]) i++;

        if (i != n)
        {
            ordered = 0;
        }
        else
        {
            ordered = ordered == 0 ? -1 : 1;
        }
    }

    return ordered;
}

int main( void )
{
    int a[] = { 1 };
    int b[] = { 1, 1 };
    int c[] = { 1, 2 };
    int d[] = { 2, 1 };
    int e[] = { 1, 2, 2 };

    printf("a: %d\n", UpOrDown(a, sizeof(a) / sizeof(*a)));
    printf("b: %d\n", UpOrDown(b, sizeof(b) / sizeof(*b)));
    printf("c: %d\n", UpOrDown(c, sizeof(c) / sizeof(*c)));
    printf("d: %d\n", UpOrDown(d, sizeof(d) / sizeof(*d)));
    printf("e: %d\n", UpOrDown(e, sizeof(e) / sizeof(*e)));
}

The program output is

a: 0
b: 0
c: 1
d: -1
e: 0


问:
If- satement and loops in an object arraylist
I'm doing a school project where I simulate a simple banking system where the user creates the account and can put a deposit, transfer money and delete accounts.

The method transaction should go through the arraylist, find the first account and the second account and transfer money but it jumps the code and says the account cannot be found. How is it possible to fix this problem

The code down below shows what happens in the method

```<code>public boolean transaction(String accountNumber, String newAccountNumber, double amount){
    for(int i = 0; i < bList.size(); i++){
        if(bList.get(i).getAccountNumber().equals(accountNumber)&& bList.get(i).getAccountNumber().equals(newAccountNumber)){
            bList.get(i).deposit(-amount);
            deposit(newAccountNumber, amount);
            return true;
        }
        else if(bList.get(i).getBalance()< amount){
            JOptionPane.showMessageDialog(null, "Du har inte tillräckligt med pengar");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(newAccountNumber) && bList.get(i).getAccountNumber().equals(accountNumber)){
            JOptionPane.showMessageDialog(null, "Kontot finns inte ");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(newAccountNumber)){
            JOptionPane.showMessageDialog(null, "kontot finns inte");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(accountNumber)){
            JOptionPane.showMessageDialog(null, "Kontot finns inte");
            return false;
        }

    }
    return false;
}
</code>```

The first if-statement should check if both accounts exsist and transfer money from the account that has money to the account that the user has selected but it skips the if-statement and says there is no account.

答:
Your search logic isn't right you are checking the same account object if it has two account numbers.

You can search arraylist of account objects for specific account number using nested for each:

```<code>for(Account account : bList) {
    for(Account newaccount : bList) {
        if(account.getAccountNumber().equals(accountNumber) && newaccount.getAccountNumber().equals(newAccountNumber)){
            //account matches
        }
    }
}
</code>```

Body:
I'm doing a school project where I simulate a simple banking system where the user creates the account and can put a deposit, transfer money and delete accounts.

The method transaction should go through the arraylist, find the first account and the second account and transfer money but it jumps the code and says the account cannot be found. How is it possible to fix this problem

The code down below shows what happens in the method

public boolean transaction(String accountNumber, String newAccountNumber, double amount){
    for(int i = 0; i < bList.size(); i++){
        if(bList.get(i).getAccountNumber().equals(accountNumber)&& bList.get(i).getAccountNumber().equals(newAccountNumber)){
            bList.get(i).deposit(-amount);
            deposit(newAccountNumber, amount);
            return true;
        }
        else if(bList.get(i).getBalance()< amount){
            JOptionPane.showMessageDialog(null, "Du har inte tillräckligt med pengar");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(newAccountNumber) && bList.get(i).getAccountNumber().equals(accountNumber)){
            JOptionPane.showMessageDialog(null, "Kontot finns inte ");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(newAccountNumber)){
            JOptionPane.showMessageDialog(null, "kontot finns inte");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(accountNumber)){
            JOptionPane.showMessageDialog(null, "Kontot finns inte");
            return false;
        }

    }
    return false;
}

The first if-statement should check if both accounts exsist and transfer money from the account that has money to the account that the user has selected but it skips the if-statement and says there is no account.

Body:
Your search logic isn't right you are checking the same account object if it has two account numbers.

You can search arraylist of account objects for specific account number using nested for each:

for(Account account : bList) {
    for(Account newaccount : bList) {
        if(account.getAccountNumber().equals(accountNumber) && newaccount.getAccountNumber().equals(newAccountNumber)){
            //account matches
        }
    }
}


问:
Gradle DSL method not found: 'exclude()'
I am working in Android Studio and when I added the line in build.gradle file

```<code>dependencies {
    compile files('libs/poi-ooxml-schemas-3.12-20150511-a.jar'){
        exclude group: 'stax', module: 'stax-api'
    }
}
</code>```

I caught the error:

Gradle DSL method not found: 'exclude()'

What is the reason of the error?

答:
The way you defined the dependency, you applied the closure to files instead of compile.

```<code>files('libs/poi-ooxml-schemas-3.12-20150511-a.jar'){
    exclude group: 'stax', module: 'stax-api'
}
</code>```

Instead you have to make sure to apply the closure to compile directly.

```<code>compile(files('libs/poi-ooxml-schemas-3.12-20150511-a.jar')){
    exclude group: 'stax', module: 'stax-api'
}
</code>```

But I doubt it's necessary at all. Groups and modules are part of the Maven system and the JAR file itself doesn't have this information to exclude.

Body:
I am working in Android Studio and when I added the line in build.gradle file

dependencies {
    compile files('libs/poi-ooxml-schemas-3.12-20150511-a.jar'){
        exclude group: 'stax', module: 'stax-api'
    }
}

I caught the error:

Gradle DSL method not found: 'exclude()'

What is the reason of the error?

Body:
The way you defined the dependency, you applied the closure to files instead of compile.

files('libs/poi-ooxml-schemas-3.12-20150511-a.jar'){
    exclude group: 'stax', module: 'stax-api'
}

Instead you have to make sure to apply the closure to compile directly.

compile(files('libs/poi-ooxml-schemas-3.12-20150511-a.jar')){
    exclude group: 'stax', module: 'stax-api'
}

But I doubt it's necessary at all. Groups and modules are part of the Maven system and the JAR file itself doesn't have this information to exclude.


问:
MySQL - Retrieving the record with the maximum value
I've a table like below on my MySQL database:

```<code>employee
-------------------------
id    name    num
1     Jack    1
2     John    1
3     Jack    2
4     Steve   1
5     Jack    3
6     Steve   2
7     Carol   1
</code>```

The thing I want to do is to retrieve names with the highest "num" value.

For example:

```<code>5     Jack    3
</code>```

There more than one records named Jack but I want to get the one with the maximum "num" value.

I've tried to use the query below:

```<code>SELECT MAX(num),id,name FROM `employee`
</code>```

But it returns the id and name of first record (first "Jack") but the num of the latest.

```<code>MAX(num)    id     num
-----------------------
3           1      Jack
</code>```

Of course I can try to use "Order by" but I also want to retrieve the only record with the highest value.

```<code>SELECT num,id,name FROM `employee` order by num desc
</code>```

This query will also return all the records including the smaller ones.

```<code>id    name    num
-------------------------
3     5       Jack
2     3       Jack
2     6       Steve
1     1       Jack
1     2       John
1     4       Steve
1     7       Carol
</code>```

When I try to group by name, it returns the records grouped by name but again only the small records.

The both of the queries below give the same result:

```<code>SELECT num,id,name FROM `employee` group by name order by num desc

SELECT * FROM
(
select * from `employee` order by num desc
) as employee_tmp
group by name
order by num desc
</code>```

Again, it groups with only the first and smallest records.

```<code>id  name    num
1   Jack    1
2   John    1
4   Steve   1
7   Carol   1
</code>```

答:
You need to use inner query with MAX, e.g.:

```<code>SELECT *
FROM employee
WHERE num = (
    SELECT MAX(num) FROM employee
);
</code>```

This would give you the required result.

Body:
I've a table like below on my MySQL database:

employee
-------------------------
id    name    num
1     Jack    1
2     John    1
3     Jack    2
4     Steve   1
5     Jack    3
6     Steve   2
7     Carol   1

The thing I want to do is to retrieve names with the highest "num" value.

For example:

5     Jack    3

There more than one records named Jack but I want to get the one with the maximum "num" value.

I've tried to use the query below:

SELECT MAX(num),id,name FROM `employee`

But it returns the id and name of first record (first "Jack") but the num of the latest.

MAX(num)    id     num
-----------------------
3           1      Jack

Of course I can try to use "Order by" but I also want to retrieve the only record with the highest value.

SELECT num,id,name FROM `employee` order by num desc

This query will also return all the records including the smaller ones.

id    name    num
-------------------------
3     5       Jack
2     3       Jack
2     6       Steve
1     1       Jack
1     2       John
1     4       Steve
1     7       Carol

When I try to group by name, it returns the records grouped by name but again only the small records.

The both of the queries below give the same result:

SELECT num,id,name FROM `employee` group by name order by num desc

SELECT * FROM
(
select * from `employee` order by num desc
) as employee_tmp
group by name
order by num desc

Again, it groups with only the first and smallest records.

id  name    num
1   Jack    1
2   John    1
4   Steve   1
7   Carol   1

Body:
You need to use inner query with MAX, e.g.:

SELECT *
FROM employee
WHERE num = (
    SELECT MAX(num) FROM employee
);

This would give you the required result.


问:
DirectX 10 Draw Text to texture
I am atempting to draw text to a textured mesh object. The mesh is basically a cube which has been pasted up to the front of the screen. (overall I'm aiming for a menu system). After a bit of googling I've found surprisingly little information on how to draw a text to a texture. I've read that it should be as simple as making a texture, setting it as a render source and then drawing to it, yet I cannot figure this one out.

Any ideas, suggestions or skeleton code with the necessary function calls to give me a jump start?

答:
When you need to render text into texture, you should setup rendering to texture as Adam suggested, to actually render some text you can do this

Create font and sprite

```<code>D3DX10CreateFont(device, 16, 0, FW_BOLD, 0, FALSE, DEFAULT_CHARSET, OUT_TT_ONLY_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Verdana", &font);
D3DX10CreateSprite(device, 256, &sprite);
</code>```

and render

```<code>hr = sprite->Begin(0);
left = L"Some text to render";
RECT r;
r.top = 0;
r.bottom = window->height;
r.left = 0;
r.right = window->width;
hr = font->DrawTextW(sprite, left.c_str(), -1, &r, DT_LEFT | DT_TOP | DT_CALCRECT, D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f));
hr = font->DrawTextW(sprite, left.c_str(), -1, &r, DT_LEFT | DT_TOP, D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f));
//hr = sprite->Flush();
hr = sprite->End();
device->OMSetBlendState(NULL, 0, 0xffffffff);
</code>```

Beware, sprite rendering changes blend state, so be sure to set it to default. If you need only "text on plain surface" (no texture mapping on mesh) you could render sprite into main scene instead of texture.

Title: DirectX 10 Draw Text to texture

Body:
When you need to render text into texture, you should setup rendering to texture as Adam suggested, to actually render some text you can do this

Create font and sprite

D3DX10CreateFont(device, 16, 0, FW_BOLD, 0, FALSE, DEFAULT_CHARSET, OUT_TT_ONLY_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Verdana", &font);
D3DX10CreateSprite(device, 256, &sprite);

and render

hr = sprite->Begin(0);
left = L"Some text to render";
RECT r;
r.top = 0;
r.bottom = window->height;
r.left = 0;
r.right = window->width;
hr = font->DrawTextW(sprite, left.c_str(), -1, &r, DT_LEFT | DT_TOP | DT_CALCRECT, D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f));
hr = font->DrawTextW(sprite, left.c_str(), -1, &r, DT_LEFT | DT_TOP, D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f));
//hr = sprite->Flush();
hr = sprite->End();
device->OMSetBlendState(NULL, 0, 0xffffffff);

Beware, sprite rendering changes blend state, so be sure to set it to default. If you need only "text on plain surface" (no texture mapping on mesh) you could render sprite into main scene instead of texture.


问:
Inputs on left depends on div
I have two inputs in div

Here is code

                <form>
                  <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;"/>
                  <input class="form-control" type="text" id="lname" name="lname" placeholder="From" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;"/>
                </form>

```
</div>
</div>
</p>

<p>But they floating to left because of div</p>

<p>I need them to be like this</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="width:100%;height:500px;border-style:solid;border-color:#1d69b4;margin-top:25px;">

        <div style="width:100%;height:30%;">
                <form>
                  <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;"/>
                  <input class="form-control" type="text" id="lname" name="lname" placeholder="From" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;"/>
                </form>
        </div>
    </div></code>```

But div need to be floating to left, how I can do this?

答:
The elements are aligned left, but the containing div is not wide enough to hold them side by side.

Lets say you have 2 50% divs inside a 100% div, it will overflow due to a whitespace that's added.

Try addeding 'white-space: nowrap;' to the parent div:

                <form>
                  <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;"/>
                  <input class="form-control" type="text" id="lname" name="lname" placeholder="From" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;"/>
                </form>

```

Title: Inputs on left depends on div

Body:
I have two inputs in div

Here is code

                <form>
                  <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;"/>
                  <input class="form-control" type="text" id="lname" name="lname" placeholder="From" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;"/>
                </form>

But they floating to left because of div

I need them to be like this

                <form>
                  <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;"/>
                  <input class="form-control" type="text" id="lname" name="lname" placeholder="From" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;"/>
                </form>

But div need to be floating to left, how I can do this?

Body:
The elements are aligned left, but the containing div is not wide enough to hold them side by side.

Lets say you have 2 50% divs inside a 100% div, it will overflow due to a whitespace that's added.

Try addeding 'white-space: nowrap;' to the parent div:

<div style="width:100%;height:500px;border-style:solid;border-color:#1d69b4;margin-top:25px; white-space: nowrap;">
    <div style="float:left; width:70%;height:100%;">
        <div style="width:100%;height:30%;">
                <form>
                  <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;"/>
                  <input class="form-control" type="text" id="lname" name="lname" placeholder="From" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;"/>
                </form>
        </div>
    </div>
</div>


问:
loop using python in html
so i want to loop a html element like this(i loop it in a .html file not .py file):

```<code>{% for i in range(0, row['star']) %}
    <span class="glyphicon glyphicon-star star"></span>
{% endfor %}
</code>```

but it gives me this error :

TypeError: an integer is required

i know i need an integer for looping but i dont know how to convert it

答:
Converting string to int use int template tag

```<code>{% for i in range(0, row['star']|int) %}
    <span class="glyphicon glyphicon-star star"></span>
{% endfor %}
</code>```

Title: loop using python in html

Body:
so i want to loop a html element like this(i loop it in a .html file not .py file):

{% for i in range(0, row['star']) %}

{% endfor %}

but it gives me this error :

TypeError: an integer is required

i know i need an integer for looping but i dont know how to convert it

Body:
Converting string to int use int template tag

{% for i in range(0, row['star']|int) %}
    <span class="glyphicon glyphicon-star star"></span>
{% endfor %}


问:
MVC6, If user submit decimal / int value empty from view, server side model validation show wrong message
MVC6,
There is issue found on model validation server side.

```<code>public string Genre { get; set; }
public decimal Price { get; set; }
</code>```

If user submits decimal / int value empty from view, server side model validation shows wrong message i.e. the value "" is not valid.

I have checked in the controller, the incoming model is showing price value 0 as the default but ModelState getting rawValue="". So conflicting with datatype and throw msg.

model is carring 0 as default (even user submit with empty) so should validate with 0 not with "" (string.empty).

front javascript validation working fine but server side model validation shows wrong error message
as "the value "" is not valid"

decimal / int is always getting 0 as default value.

Any solution to resolve this?

答:
I had similar problem in my ASP Core project. Model validation was set for integers by using Range attribute and Required with errors message. But when user put into input control empty i get error message like

"The value '' is invalid."

In model value was 0 but raw value was empty. I have to edit my model for nullable properties and use attributes. And i get result as i want.

```<code>[Range(1, int.MaxValue,ErrorMessage = "My message1")]
[Required (ErrorMessage = "My message2")]
public int? PreparationTimeMinutes { get; set; }
</code>```

I hope someone will help.

Body:
MVC6,
There is issue found on model validation server side.

public string Genre { get; set; }
public decimal Price { get; set; }

If user submits decimal / int value empty from view, server side model validation shows wrong message i.e. the value "" is not valid.

I have checked in the controller, the incoming model is showing price value 0 as the default but ModelState getting rawValue="". So conflicting with datatype and throw msg.

model is carring 0 as default (even user submit with empty) so should validate with 0 not with "" (string.empty).

front javascript validation working fine but server side model validation shows wrong error message
as "the value "" is not valid"

decimal / int is always getting 0 as default value.

Any solution to resolve this?

Body:
I had similar problem in my ASP Core project. Model validation was set for integers by using Range attribute and Required with errors message. But when user put into input control empty i get error message like

"The value '' is invalid."

In model value was 0 but raw value was empty. I have to edit my model for nullable properties and use attributes. And i get result as i want.

[Range(1, int.MaxValue,ErrorMessage = "My message1")]
[Required (ErrorMessage = "My message2")]
public int? PreparationTimeMinutes { get; set; }

I hope someone will help.


问:
TypeError when writing a list on a csv file
I am trying to create a code to reformat csv files and write it a list of lists on a csv file. The code is not very clean but has worked in the past. But now that I added a new first part to it, where I delete the rows and create betweenfile, it gives me a Type Error. I am unable to realize what I am doing wrong, thanks for your help. </p>

```<code>import os
import csv
outputfile = input("")
nodefile = input("")
inputfile =input("")
betweenfile= input("")
os.mknod(outputfile)
os.mknod(nodefile)
os.mknod(betweenfile)

with open(inputfile, newline='') as data:
    reader = csv.reader(data, delimiter=',')
    stack=[]
    try:
        for row in reader:
            del row[0]
            del row[3]
            del row[3]
            del row[3]
            del row[3]
            del row[3]
            del row[4]
            row[1],row[2]=row[2],row[1]
            row[2],row[3]=row[3],row[2]
            stack.append(row)
    except:
        IndexError
    with open(betweenfile, 'w') as outputfile:
        writer= csv.writer(outputfile, delimiter=',')
        for row in stack:
            writer.writerow(row)

with open(betweenfile, newline='') as data:
    reader = csv.reader(data, delimiter=',')
    listee=[]
    for row in reader:
        if row[3]=='1':
            row[0],row[1]=row[1],row[0]
        if row[3]=='3':
            row[0],row[1]=row[1],row[0]
        row.pop(3)
        listee.append(row)
    listee.pop(0)
    for row in listee:
        for i in range(len(row)):
            if row[i]== '0':
                listee.remove(row)
    for row in listee:
        for i in range(len(row)):
            if row[i]== '0':
                listee.remove(row)
    print(type(listee))
    with open(outputfile, 'w') as outputfile:
        writer= csv.writer(outputfile, delimiter=',')
        writer.writerow(['from', 'to' , 'weight'])
        for row in listee:
            writer.writerow(row)
</code>```

<p>The error message is: </p>

```<code> Traceback (most recent call last):
  File "dataformater3.py", line 54, in <module>
    with open(outputfile, 'w') as outputfile:
TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper
</code>```

答:
This is why you should never reuse variables. They have unintended side effects. First you define outputfile as

```<code> outputfile = input("")
</code>```

Then

```<code>with open(betweenfile, 'w') as outputfile:
</code>```

outputfile is a filehandle now, it's no longer the string that the user type in. And further down in your code.

```<code>print(type(listee))
with open(outputfile, 'w') as outputfile:
</code>```

You are passing a file handle as the first parameter to open, which obviously doesn't know how to deal with it.

The remedy then is to avoid reusing variables. Why not borrow from .NET devs and make the following change

```<code> outputfile_s = input("")
 ....
 with open(outputfile_s, 'w') as outputfile_f:
</code>```

Body:
I am trying to create a code to reformat csv files and write it a list of lists on a csv file. The code is not very clean but has worked in the past. But now that I added a new first part to it, where I delete the rows and create betweenfile, it gives me a Type Error. I am unable to realize what I am doing wrong, thanks for your help.

import os
import csv
outputfile = input("")
nodefile = input("")
inputfile =input("")
betweenfile= input("")
os.mknod(outputfile)
os.mknod(nodefile)
os.mknod(betweenfile)

with open(inputfile, newline='') as data:
    reader = csv.reader(data, delimiter=',')
    stack=[]
    try:
        for row in reader:
            del row[0]
            del row[3]
            del row[3]
            del row[3]
            del row[3]
            del row[3]
            del row[4]
            row[1],row[2]=row[2],row[1]
            row[2],row[3]=row[3],row[2]
            stack.append(row)
    except:
        IndexError
    with open(betweenfile, 'w') as outputfile:
        writer= csv.writer(outputfile, delimiter=',')
        for row in stack:
            writer.writerow(row)

with open(betweenfile, newline='') as data:
    reader = csv.reader(data, delimiter=',')
    listee=[]
    for row in reader:
        if row[3]=='1':
            row[0],row[1]=row[1],row[0]
        if row[3]=='3':
            row[0],row[1]=row[1],row[0]
        row.pop(3)
        listee.append(row)
    listee.pop(0)
    for row in listee:
        for i in range(len(row)):
            if row[i]== '0':
                listee.remove(row)
    for row in listee:
        for i in range(len(row)):
            if row[i]== '0':
                listee.remove(row)
    print(type(listee))
    with open(outputfile, 'w') as outputfile:
        writer= csv.writer(outputfile, delimiter=',')
        writer.writerow(['from', 'to' , 'weight'])
        for row in listee:
            writer.writerow(row)

The error message is:

 Traceback (most recent call last):
  File "dataformater3.py", line 54, in <module>
    with open(outputfile, 'w') as outputfile:
TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper

Body:
This is why you should never reuse variables. They have unintended side effects. First you define outputfile as

 outputfile = input("")

Then

with open(betweenfile, 'w') as outputfile:

outputfile is a filehandle now, it's no longer the string that the user type in. And further down in your code.

print(type(listee))
with open(outputfile, 'w') as outputfile:

You are passing a file handle as the first parameter to open, which obviously doesn't know how to deal with it.

The remedy then is to avoid reusing variables. Why not borrow from .NET devs and make the following change

 outputfile_s = input("")
 ....
 with open(outputfile_s, 'w') as outputfile_f:


问:
Setting a connection to an access database in VBA crashes excel
This is the code I use to open a connection to an access database from excel.  It used to work for more than a year.

```<code>Set dbname = New ADODB.Connection
theconnection = "//xxx.sharepoint.com/sites" & Application.PathSeparator & TARGET_DB
With dbname
    .Provider = "Microsoft.ACE.OLEDB.12.0"
    .Open theconnection
End With
</code>```

By trial an error I've come to the conclusion that this line is causing the problem.

```<code>Set dbname= New ADODB.Connection
</code>```

The problem began after an automatic update of my PC
My Excel version 2016 MSO (16.0.7726.1036) 32-bit

Please let me know if you have run also into this problem, and if you know any fix or workaround.

答:
Maybe

```<code>Dim dbname As Object
Set dbname = CreateObject("ADODB.Connection")

theconnection = "//xxx.sharepoint.com/sites" & Application.PathSeparator & TARGET_DB
With dbname
    .Provider = "Microsoft.ACE.OLEDB.12.0"
    .Open theconnection
End With
</code>```

I used like this , all code

```<code>Dim Rs As Object
Dim strConn As String
Dim i As Integer
Dim strSQL As String

strSQL = "select * from [table] "
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
    "Data Source=" & ThisWorkbook.FullName & ";" & _
        "Extended Properties=Excel 12.0;"

Set Rs = CreateObject("ADODB.Recordset")
Rs.Open strSQL, strConn

If Not Rs.EOF Then
     With Ws
        .Range("a1").CurrentRegion.ClearContents
        For i = 0 To Rs.Fields.Count - 1
           .Cells(1, i + 1).Value = Rs.Fields(i).Name
        Next
        .Range("a" & 2).CopyFromRecordset Rs
    End With
End If
Rs.Close
Set Rs = Nothing
</code>```

Body:
This is the code I use to open a connection to an access database from excel.  It used to work for more than a year.

Set dbname = New ADODB.Connection
theconnection = "//xxx.sharepoint.com/sites" & Application.PathSeparator & TARGET_DB
With dbname
    .Provider = "Microsoft.ACE.OLEDB.12.0"
    .Open theconnection
End With

By trial an error I've come to the conclusion that this line is causing the problem.

Set dbname= New ADODB.Connection

The problem began after an automatic update of my PC
My Excel version 2016 MSO (16.0.7726.1036) 32-bit

Please let me know if you have run also into this problem, and if you know any fix or workaround.

Body:
Maybe

Dim dbname As Object
Set dbname = CreateObject("ADODB.Connection")

theconnection = "//xxx.sharepoint.com/sites" & Application.PathSeparator & TARGET_DB
With dbname
    .Provider = "Microsoft.ACE.OLEDB.12.0"
    .Open theconnection
End With

I used like this , all code

Dim Rs As Object
Dim strConn As String
Dim i As Integer
Dim strSQL As String

strSQL = "select * from [table] "
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
    "Data Source=" & ThisWorkbook.FullName & ";" & _
        "Extended Properties=Excel 12.0;"

Set Rs = CreateObject("ADODB.Recordset")
Rs.Open strSQL, strConn

If Not Rs.EOF Then
     With Ws
        .Range("a1").CurrentRegion.ClearContents
        For i = 0 To Rs.Fields.Count - 1
           .Cells(1, i + 1).Value = Rs.Fields(i).Name
        Next
        .Range("a" & 2).CopyFromRecordset Rs
    End With
End If
Rs.Close
Set Rs = Nothing


问:
j-query and javascript form using multiple submits not submitting all data from form
I'm not hugely good with javascript or jQuery, mainly dealing with databases, but I've been having a little trouble getting a rather complex form to submit all its data.

Basically it amounts to three different submit buttons which are meant to post the data in the form with a different privacy setting sent to the table. The table in the database is being updated with the correct privacy setting for each button, but it isn't sending a value for the thought part of the form to the php file it is meant to.

The form is implemented in the HTML as follows:

```<code><FORM action="thought_post.php" method="post" name="thought">

<INPUT onfocus="this.select(); this.value=''"
       type="text" value="Thought..."
       size="72" />
<div class="megamenu" style="position: absolute; ;left: 478px; top: 11px;">
    <ul>
        <li class="downservices"><a href="#">Publish...</a></li>
        <div class="servicesdropped">
            <ul class="right">
                <input type="hidden" name="privacy">
                <li><a href="javascript:poststyle('private')">Private</a></li>
                <li><a href="javascript:poststyle('friends')">Friends only</a></li>
                <li><a href="javascript:poststyle('public')">Public</a></li>
            </ul>
        </div>
    </ul>
</div>

</FORM>
</code>```

and the javascript in the header of the same page is as follows:

```<code><link rel="stylesheet" href="dropdown.css" type="text/css" media="screen" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>

<script type="text/javascript">
    $(document).ready(function(){
        $(".downservices").click(function(){
            $(".servicesdropped").toggle("fast");
        });
    });
</script>

<script language="JavaScript" type="text/javascript">
<!--
   function poststyle(selectedtype)
    {
       document.thought.privacy.value = selectedtype ;
       document.thought.submit() ;
    }
-->
</script>
</code>```

If anyone could explain why the thought value entered by the user isn't being passed to thought_post.php that would be wonderful!

答:
Try setting an id for the privacy field (like, say, id="privacy") and selecting it with this:

```<code>getElementById("privacy").value = selectedtype;
</code>```

By the way, you can put all the javascript in one
```

You could also very easily handle the focus event on your input with jQuery so the scripting isn't down in your HTML.

Body:
I'm not hugely good with javascript or jQuery, mainly dealing with databases, but I've been having a little trouble getting a rather complex form to submit all its data.

Basically it amounts to three different submit buttons which are meant to post the data in the form with a different privacy setting sent to the table. The table in the database is being updated with the correct privacy setting for each button, but it isn't sending a value for the thought part of the form to the php file it is meant to.

The form is implemented in the HTML as follows:

<FORM action="thought_post.php" method="post" name="thought">

<INPUT onfocus="this.select(); this.value=''"
       type="text" value="Thought..."
       size="72" />

Publish...

                <input type="hidden" name="privacy">

Private

Friends only

Public

</FORM>

and the javascript in the header of the same page is as follows:

<link rel="stylesheet" href="dropdown.css" type="text/css" media="screen" />

If anyone could explain why the thought value entered by the user isn't being passed to thought_post.php that would be wonderful!

Body:
Try setting an id for the privacy field (like, say, id="privacy") and selecting it with this:

getElementById("privacy").value = selectedtype;

By the way, you can put all the javascript in one <script> block:

<script type="text/javascript">
    $(document).ready(function(){
        $(".downservices").click(function(){
            $(".servicesdropped").toggle("fast");
        });
    });

    function poststyle(selectedtype)
    {
        document.thought.privacy.value = selectedtype ;
        document.thought.submit() ;
    }
</script>

You could also very easily handle the focus event on your input with jQuery so the scripting isn't down in your HTML.


问:
Decode Marshalled JSON unicode
I think the quickest way to explain my problem is with an example:

```<code>package main

import (
    "fmt"
    "encoding/json"
)

type JSON struct {
    Body string
}

func main() {
    body := "<html><body>Hello World</body></html>"

    obj := JSON{body}

    result, _ := json.Marshal(obj)
    fmt.Println(string(result))
}
</code>```

Output:

{"Body":"\u003chtml\u003e\u003cbody\u003eHello World\u003c/body\u003e\u003c/html\u003e"}

I'd like the result to be a utf8-encoded string that reads the same as it went in. How can I achieve this? I tried to use utf8.DecodeRune, in a loop:

```<code>str := ""

for _, res := range result {
    decoded, _ := utf8.DecodeRune(res)
    str += string(decoded)
}
</code>```

but that causes a compilation error

main.go:21: cannot use res (type byte) as type []byte in argument to utf8.DecodeRune

And calling DecodeRune on the marshalled object returns the first character, as you'd expect

{

Edit: I'm  using Go 1.6.2, which apparently doesn't have SetEscapeHTML for whatever reason.

答:
This is intended behavior. From the docs:

String values encode as JSON strings coerced to valid UTF-8, replacing
  invalid bytes with the Unicode replacement rune. The angle brackets
  "<" and ">" are escaped to "\u003c" and "\u003e" to keep some browsers
  from misinterpreting JSON output as HTML. Ampersand "&" is also
  escaped to "\u0026" for the same reason. This escaping can be disabled
  using an Encoder that had SetEscapeHTML(false) called on it.

You can get the required result by using an Encoder and calling SetEscapeHTML(false) on it:

```<code>func main() {
    body := "<html><body>Hello World</body></html>"

    obj := JSON{body}

    enc := json.NewEncoder(os.Stdout)
    enc.SetEscapeHTML(false)
    enc.Encode(obj)
}
</code>```

Working example: https://play.golang.org/p/lMNCJ16dIo

Title: Decode Marshalled JSON unicode

Body:
I think the quickest way to explain my problem is with an example:

package main

import (
    "fmt"
    "encoding/json"
)

type JSON struct {
    Body string
}

func main() {
    body := "Hello World"

    obj := JSON{body}

    result, _ := json.Marshal(obj)
    fmt.Println(string(result))
}

Output:

{"Body":"\u003chtml\u003e\u003cbody\u003eHello World\u003c/body\u003e\u003c/html\u003e"}

I'd like the result to be a utf8-encoded string that reads the same as it went in. How can I achieve this? I tried to use utf8.DecodeRune, in a loop:

str := ""

for _, res := range result {
    decoded, _ := utf8.DecodeRune(res)
    str += string(decoded)
}

but that causes a compilation error

main.go:21: cannot use res (type byte) as type []byte in argument to utf8.DecodeRune

And calling DecodeRune on the marshalled object returns the first character, as you'd expect

{

Edit: I'm  using Go 1.6.2, which apparently doesn't have SetEscapeHTML for whatever reason.

Body:
This is intended behavior. From the docs:

String values encode as JSON strings coerced to valid UTF-8, replacing
  invalid bytes with the Unicode replacement rune. The angle brackets
  "<" and ">" are escaped to "\u003c" and "\u003e" to keep some browsers
  from misinterpreting JSON output as HTML. Ampersand "&" is also
  escaped to "\u0026" for the same reason. This escaping can be disabled
  using an Encoder that had SetEscapeHTML(false) called on it.

You can get the required result by using an Encoder and calling SetEscapeHTML(false) on it:

func main() {
    body := "<html><body>Hello World</body></html>"

    obj := JSON{body}

    enc := json.NewEncoder(os.Stdout)
    enc.SetEscapeHTML(false)
    enc.Encode(obj)
}

Working example: https://play.golang.org/p/lMNCJ16dIo


问:
SQL Null: Preferred way of distinguishing between unknown and no value
Suppose I have a simple table such as:

```<code>CREATE TABLE authors (
    id INT PRIMARY KEY,
    name VARCHAR(40),
    born DATE,
    died DATE
);
</code>```

Both the born and died dates are optional, so they can contain NULL.

Presumably authors who haven’t been born yet, won’t make it into the table, so the obvious way to interpret NULL would be that the date is unknown.

However, there is some ambiguity with the died date. A null could imply that the date is unknown, or that the author has yet to die.

What is the preferred way allow for both an unknown date and an event which has not yet occurred?

For what it’s worth, I routinely use PostgreSQL, MySQL/MariaDB and SQL Server, so this question isn’t specific to a particular DBMS.

答:
A possible solution would be to remove the died column and add the following table:

```<code>CREATE TABLE deaths (
    id INT PRIMARY KEY REFERENCES authors(id),
    died DATE
);
</code>```

In this case, no record could imply that the author has not died, while a NULL in died would imply that the author has died, but the date is unknown.

The data data could then be extracted as follows:

```<code>SELECT
    a.id, a.name, a.born,
    CASE WHEN d.id IS NULL THEN 'living' ELSE coalesce(d.died,'unknown') END
FROM authors a LEFT JOIN deaths d ON a.id=d.id;
</code>```

The d.id column is used to determine whether there is a matching row, otherwise the author is considered living. If there is a matching row, the result is either the died date or a coalesced alternative.

Body:
Suppose I have a simple table such as:

CREATE TABLE authors (
    id INT PRIMARY KEY,
    name VARCHAR(40),
    born DATE,
    died DATE
);

Both the born and died dates are optional, so they can contain NULL.

Presumably authors who haven’t been born yet, won’t make it into the table, so the obvious way to interpret NULL would be that the date is unknown.

However, there is some ambiguity with the died date. A null could imply that the date is unknown, or that the author has yet to die.

What is the preferred way allow for both an unknown date and an event which has not yet occurred?

For what it’s worth, I routinely use PostgreSQL, MySQL/MariaDB and SQL Server, so this question isn’t specific to a particular DBMS.

Body:
A possible solution would be to remove the died column and add the following table:

CREATE TABLE deaths (
    id INT PRIMARY KEY REFERENCES authors(id),
    died DATE
);

In this case, no record could imply that the author has not died, while a NULL in died would imply that the author has died, but the date is unknown.

The data data could then be extracted as follows:

SELECT
    a.id, a.name, a.born,
    CASE WHEN d.id IS NULL THEN 'living' ELSE coalesce(d.died,'unknown') END
FROM authors a LEFT JOIN deaths d ON a.id=d.id;

The d.id column is used to determine whether there is a matching row, otherwise the author is considered living. If there is a matching row, the result is either the died date or a coalesced alternative.


问:
How to show current object inside template used with class based FormView
Having this urls.py snippet:

```<code>url(r'^storageitem/(?P<pk>[\w]+)/addtransaction/$', login_required(
    StorageItemTransactionAddView.as_view()),
    name='storage_item_transaction'),
</code>```

I'm wondering what is the correct way to make the object beihind pk available inside a template to show it e.g. with

```<code><h1>{{ object.name }}</h1>
</code>```

I tried to configure a query set

```<code>...
queryset = StorageItem.objects.get
    pk=get_from_kwargs()['object'])

def get_form_kwargs(self):
    kwargs = super(ItemCreate, self).get_form_kwargs()
    kwargs.update({
        'object' : self.kwargs['pk']
    })
    return kwargs
</code>```

but the method is not access able at this point. So I'm wondering how could one do it the correct way? All I need would be something like

```<code>self.object = StorageItem.objects.get(pk='my pk')
</code>```

答:
You can override get_context_data to pass extra context:</p>

```<code>...

def get_context_data(self, **kwargs):
    context = super(ItemCreate, self).get_context_data(**kwargs)
    context['storage_item'] = StorageItem.objects.get(pk=self.kwargs['pk'])
    return context
</code>```

Body:
Having this urls.py snippet:

url(r'^storageitem/(?P<pk>[\w]+)/addtransaction/$', login_required(
    StorageItemTransactionAddView.as_view()),
    name='storage_item_transaction'),

I'm wondering what is the correct way to make the object beihind pk available inside a template to show it e.g. with

{{ object.name }}

I tried to configure a query set

...
queryset = StorageItem.objects.get
    pk=get_from_kwargs()['object'])

def get_form_kwargs(self):
    kwargs = super(ItemCreate, self).get_form_kwargs()
    kwargs.update({
        'object' : self.kwargs['pk']
    })
    return kwargs

but the method is not access able at this point. So I'm wondering how could one do it the correct way? All I need would be something like

self.object = StorageItem.objects.get(pk='my pk')

Body:
You can override get_context_data to pass extra context:

...

def get_context_data(self, **kwargs):
    context = super(ItemCreate, self).get_context_data(**kwargs)
    context['storage_item'] = StorageItem.objects.get(pk=self.kwargs['pk'])
    return context


问:
"no such table: users" when testing and using Bookshelf / Knex
I'm trying to run a simple test using Mocha and my Bookshelf / Knex model, however I'm getting the error "Unhandled rejection Error: SQLITE_ERROR: no such table: users". Note that I'm trying to use in memory SQLite.

Here's my Knexfile:

```<code>module.exports = {

  development: {
    client: 'sqlite3',
    connection: {
      filename: ':memory:'
    }
  },

  test: {
    client: 'mysql',
    connection: {
      host: '172.18.0.2',
      user: 'root',
      password: '',
      database: 'staging_db',
      charset  : 'utf8'
    },
    pool: {
      min: 2,
      max: 10
    },
    migrations: {
      tableName: 'knex_migrations'
    }
  },

  production: {
    client: 'mysql',
    connection: {
      host: process.env.DB_HOST || 'localhost',
      user: process.env.DB_USER || 'usr',
      password: process.env.DB_PWD || '',
      database: process.env.DB_NAME || 'db',
      charset  : 'utf8'
    },
    pool: {
      min: 2,
      max: 10
    },
    migrations: {
      tableName: 'knex_migrations'
    }
  }

};
</code>```

Database.js:

```<code>var config      = require('../knexfile.js');
var env         = process.env.NODE_ENV || 'development';
var knex        = require('knex')(config[env]);

knex.migrate.latest([config]);

let bookshelf = require('bookshelf')(knex);

bookshelf.plugin('registry'); // Resolve circular dependencies with relations

// Export bookshelf for use elsewhere
module.exports = bookshelf;
</code>```

And my User model:

```<code>let bookshelf = require('../config/database');

require('./role');

var User = bookshelf.Model.extend({
    tableName: 'users',
    role: function() {
        return this.hasOne(Role);
    }
});

module.exports = bookshelf.model('user', User);
</code>```

And my test:

```<code>var User = require('../../models/user'),
    chai = require('chai'),
    expect = chai.expect;

describe('User model', function () {

    it('should return empty set before adding anything', () => {
        expect(User.collection().count()).to.equal(0);
    });

});
</code>```

Am I missing something?

UPDATE

Adding the migration file:

```<code>exports.up = function(knex, Promise) {
  return knex.schema.createTable('roles', function (table) {
        //this creates an id column as auto incremented primary key
        table.increments();
        table.string('description', 45).notNullable();
    })
    .createTable('users', function (table) {
        table.increments();
        table.string('name', 60);
        table.string('password', 45);
        table.integer('role_id').unsigned();
        table.foreign('role_id').references('roles.id');
    });
};

exports.down = function(knex, Promise) {
  return knex.schema.dropTable('users').dropTable('roles');
};
</code>```

答:
First: your test is wrong: count() returns a count promise not the count itself. So change your test to:

```<code>it('should return empty set before adding anything', function(done) {
    User
    .collection()
    .count()
    .then(count => {
        expect(count).to.equal(0);
        done()
    })
    .catch(err => done(err));
});
</code>```

Second: You have a race condition between the test and the migration.

If you enable Knex debug mode on your knexfile.js

```<code>//...
development: {
  client: 'sqlite3',
  connection: {
    filename: ':memory:'
  },
  debug: true
},
//...
</code>```

You will get

```<code>$ ./node_modules/mocha/bin/_mocha ./test/user.js
Knex:warning - sqlite does not support inserting default values. Set the `useNullAsDefault` flag to hide this warning. (see docs http://knexjs.org/#Builder-insert).

  User model
[ { sql: 'select * from sqlite_master where type = \'table\' and name = ?',
    output: [Function: output],
    bindings: [ 'knex_migrations' ] } ]
[ { sql: 'create table if not exists "knex_migrations" ("id" integer not null primary key autoincrement, "name" varchar(255), "batch" integer, "migration_time" datetime)',
    bindings: [] } ]
{ method: 'select',
  options: {},
  timeout: false,
  cancelOnTimeout: false,
  bindings: [],
  __knexQueryUid: '7186321c-92b5-416c-8a5f-304118e47a0d',
  sql: 'select count(*) as "count" from "users"' }
[ { sql: 'select * from sqlite_master where type = \'table\' and name = ?',
    output: [Function: output],
    bindings: [ 'knex_migrations_lock' ] } ]
    1) should return empty set before adding anything
[ { sql: 'create table if not exists "knex_migrations_lock" ("is_locked" integer)',
    bindings: [] } ]

{ method: 'select',
  options: {},
  timeout: false,
  cancelOnTimeout: false,
  bindings: [],
  __knexQueryUid: '7ebd63cc-1070-4422-b664-47e28b58de15',
  sql: 'select * from "knex_migrations_lock"' }

  0 passing (62ms)
  1 failing

  1) User model should return empty set before adding anything:
     select count(*) as "count" from "users" - SQLITE_ERROR: no such table: users
  Error: SQLITE_ERROR: no such table: users
</code>```

Note the count() query happened while the migration was still checking if migration tables existed.

An easy (and overly ugly) fix is to add some delays to the test:

```<code>describe('User model', function () {

    this.timeout(20000);

    before(function (done) {
        setTimeout(() => done(), 200);  // 200ms was enough on my env
    })

    it('should return empty set before adding anything', function (done) {
        User.collection().count()
        .then(count => {
            expect(count).to.equal(0);
            done()
        })
        .catch(err => done(err));
    });

});
</code>```

And you will happily get

```<code>$ ./node_modules/mocha/bin/_mocha ./test/user.js
Knex:warning - sqlite does not support inserting default values. Set the `useNullAsDefault` flag to hide this warning. (see docs http://knexjs.org/#Builder-insert).

  User model
    ✓ should return empty set before adding anything

  1 passing (225ms)
</code>```

Note the test took slightly over 200ms to run.

Another possible approach could be to add the migrations to the before() clause. That would enable you to use await on them.

Body:
I'm trying to run a simple test using Mocha and my Bookshelf / Knex model, however I'm getting the error "Unhandled rejection Error: SQLITE_ERROR: no such table: users". Note that I'm trying to use in memory SQLite.

Here's my Knexfile:

module.exports = {

  development: {
    client: 'sqlite3',
    connection: {
      filename: ':memory:'
    }
  },

  test: {
    client: 'mysql',
    connection: {
      host: '172.18.0.2',
      user: 'root',
      password: '',
      database: 'staging_db',
      charset  : 'utf8'
    },
    pool: {
      min: 2,
      max: 10
    },
    migrations: {
      tableName: 'knex_migrations'
    }
  },

  production: {
    client: 'mysql',
    connection: {
      host: process.env.DB_HOST || 'localhost',
      user: process.env.DB_USER || 'usr',
      password: process.env.DB_PWD || '',
      database: process.env.DB_NAME || 'db',
      charset  : 'utf8'
    },
    pool: {
      min: 2,
      max: 10
    },
    migrations: {
      tableName: 'knex_migrations'
    }
  }

};

Database.js:

var config      = require('../knexfile.js');
var env         = process.env.NODE_ENV || 'development';
var knex        = require('knex')(config[env]);

knex.migrate.latest([config]);

let bookshelf = require('bookshelf')(knex);

bookshelf.plugin('registry'); // Resolve circular dependencies with relations

// Export bookshelf for use elsewhere
module.exports = bookshelf;

And my User model:

let bookshelf = require('../config/database');

require('./role');

var User = bookshelf.Model.extend({
    tableName: 'users',
    role: function() {
        return this.hasOne(Role);
    }
});

module.exports = bookshelf.model('user', User);

And my test:

var User = require('../../models/user'),
    chai = require('chai'),
    expect = chai.expect;

describe('User model', function () {

    it('should return empty set before adding anything', () => {
        expect(User.collection().count()).to.equal(0);
    });

});

Am I missing something?

UPDATE

Adding the migration file:

exports.up = function(knex, Promise) {
  return knex.schema.createTable('roles', function (table) {
        //this creates an id column as auto incremented primary key
        table.increments();
        table.string('description', 45).notNullable();
    })
    .createTable('users', function (table) {
        table.increments();
        table.string('name', 60);
        table.string('password', 45);
        table.integer('role_id').unsigned();
        table.foreign('role_id').references('roles.id');
    });
};

exports.down = function(knex, Promise) {
  return knex.schema.dropTable('users').dropTable('roles');
};

Body:
First: your test is wrong: count() returns a count promise not the count itself. So change your test to:

it('should return empty set before adding anything', function(done) {
    User
    .collection()
    .count()
    .then(count => {
        expect(count).to.equal(0);
        done()
    })
    .catch(err => done(err));
});

Second: You have a race condition between the test and the migration.

If you enable Knex debug mode on your knexfile.js

//...
development: {
  client: 'sqlite3',
  connection: {
    filename: ':memory:'
  },
  debug: true
},
//...

You will get

$ ./node_modules/mocha/bin/_mocha ./test/user.js
Knex:warning - sqlite does not support inserting default values. Set the `useNullAsDefault` flag to hide this warning. (see docs http://knexjs.org/#Builder-insert).

  User model
[ { sql: 'select * from sqlite_master where type = \'table\' and name = ?',
    output: [Function: output],
    bindings: [ 'knex_migrations' ] } ]
[ { sql: 'create table if not exists "knex_migrations" ("id" integer not null primary key autoincrement, "name" varchar(255), "batch" integer, "migration_time" datetime)',
    bindings: [] } ]
{ method: 'select',
  options: {},
  timeout: false,
  cancelOnTimeout: false,
  bindings: [],
  __knexQueryUid: '7186321c-92b5-416c-8a5f-304118e47a0d',
  sql: 'select count(*) as "count" from "users"' }
[ { sql: 'select * from sqlite_master where type = \'table\' and name = ?',
    output: [Function: output],
    bindings: [ 'knex_migrations_lock' ] } ]
    1) should return empty set before adding anything
[ { sql: 'create table if not exists "knex_migrations_lock" ("is_locked" integer)',
    bindings: [] } ]

{ method: 'select',
  options: {},
  timeout: false,
  cancelOnTimeout: false,
  bindings: [],
  __knexQueryUid: '7ebd63cc-1070-4422-b664-47e28b58de15',
  sql: 'select * from "knex_migrations_lock"' }

  0 passing (62ms)
  1 failing

  1) User model should return empty set before adding anything:
     select count(*) as "count" from "users" - SQLITE_ERROR: no such table: users
  Error: SQLITE_ERROR: no such table: users

Note the count() query happened while the migration was still checking if migration tables existed.

An easy (and overly ugly) fix is to add some delays to the test:

describe('User model', function () {

    this.timeout(20000);

    before(function (done) {
        setTimeout(() => done(), 200);  // 200ms was enough on my env
    })

    it('should return empty set before adding anything', function (done) {
        User.collection().count()
        .then(count => {
            expect(count).to.equal(0);
            done()
        })
        .catch(err => done(err));
    });

});

And you will happily get

$ ./node_modules/mocha/bin/_mocha ./test/user.js
Knex:warning - sqlite does not support inserting default values. Set the `useNullAsDefault` flag to hide this warning. (see docs http://knexjs.org/#Builder-insert).

  User model
    ✓ should return empty set before adding anything

  1 passing (225ms)

Note the test took slightly over 200ms to run.

Another possible approach could be to add the migrations to the before() clause. That would enable you to use await on them.


问:
In binary search what is the case we roundup the mid
When low=mid then we change m=l+(h-l+1)/2 .My doubt is why we take low=mid.</p>

答:
if you mean the case when l+h is odd number it will be rounded automatically, you don't need any explicit code to round the mid.and here is binary search alorithm.

Given an array A of n elements with values or records A0 ... An−1, sorted such that A0 ≤ ... ≤ An−1, and target value T, the following subroutine uses binary search to find the index of T in A.[7]

```<code>Set L to 0 and R to n − 1.
If L > R, the search terminates as unsuccessful.
Set m (the position of the middle element) to the floor (the largest previous integer) of (L + R) / 2.
If Am < T, set L to m + 1 and go to step 2.
If Am > T, set R to m – 1 and go to step 2.
Now Am = T, the search is done; return m.
</code>```

you will never find something  like m=l+(h-l+1)/2

Body:
if you mean the case when l+h is odd number it will be rounded automatically, you don't need any explicit code to round the mid.and here is binary search alorithm.

Given an array A of n elements with values or records A0 ... An−1, sorted such that A0 ≤ ... ≤ An−1, and target value T, the following subroutine uses binary search to find the index of T in A.[7]

Set L to 0 and R to n − 1.
If L > R, the search terminates as unsuccessful.
Set m (the position of the middle element) to the floor (the largest previous integer) of (L + R) / 2.
If Am < T, set L to m + 1 and go to step 2.
If Am > T, set R to m – 1 and go to step 2.
Now Am = T, the search is done; return m.

you will never find something  like m=l+(h-l+1)/2