问:
How do I represent a time only value in .NET?
Is there a way one can represent a time only value in .NET without the date? For example, indicating the opening time of a shop?

TimeSpan indicates a range, whereas I only want to store a time value. Using DateTime to indicate this would result in new DateTime(1,1,1,8,30,0) which is not really desirable.

答:
Here's a full featured TimeOfDay class.

This is overkill for simple cases, but if you need more advanced functionality like I did, this may help.

It can handle the corner cases, some basic math, comparisons, interaction with DateTime, parsing, etc.

Below is the source code for the TimeOfDay class.  You can see usage examples and learn more here:

This class uses DateTime for most of its internal calculations and comparisons so that we can leverage all of the knowledge already embedded in DateTime.

```<code>// Author: Steve Lautenschlager, CambiaResearch.com
// License: MIT

using System;
using System.Text.RegularExpressions;

namespace Cambia
{
    public class TimeOfDay
    {
        private const int MINUTES_PER_DAY = 60 * 24;
        private const int SECONDS_PER_DAY = SECONDS_PER_HOUR * 24;
        private const int SECONDS_PER_HOUR = 3600;
        private static Regex _TodRegex = new Regex(@"\d?\d:\d\d:\d\d|\d?\d:\d\d");

        public TimeOfDay()
        {
            Init(0, 0, 0);
        }
        public TimeOfDay(int hour, int minute, int second = 0)
        {
            Init(hour, minute, second);
        }
        public TimeOfDay(int hhmmss)
        {
            Init(hhmmss);
        }
        public TimeOfDay(DateTime dt)
        {
            Init(dt);
        }
        public TimeOfDay(TimeOfDay td)
        {
            Init(td.Hour, td.Minute, td.Second);
        }

        public int HHMMSS
        {
            get
            {
                return Hour * 10000 + Minute * 100 + Second;
            }
        }
        public int Hour { get; private set; }
        public int Minute { get; private set; }
        public int Second { get; private set; }
        public double TotalDays
        {
            get
            {
                return TotalSeconds / (24d * SECONDS_PER_HOUR);
            }
        }
        public double TotalHours
        {
            get
            {
                return TotalSeconds / (1d * SECONDS_PER_HOUR);
            }
        }
        public double TotalMinutes
        {
            get
            {
                return TotalSeconds / 60d;
            }
        }
        public int TotalSeconds
        {
            get
            {
                return Hour * 3600 + Minute * 60 + Second;
            }
        }
        public bool Equals(TimeOfDay other)
        {
            if (other == null) { return false; }
            return TotalSeconds == other.TotalSeconds;
        }
        public override bool Equals(object obj)
        {
            if (obj == null) { return false; }
            TimeOfDay td = obj as TimeOfDay;
            if (td == null) { return false; }
            else { return Equals(td); }
        }
        public override int GetHashCode()
        {
            return TotalSeconds;
        }
        public DateTime ToDateTime(DateTime dt)
        {
            return new DateTime(dt.Year, dt.Month, dt.Day, Hour, Minute, Second);
        }
        public override string ToString()
        {
            return ToString("HH:mm:ss");
        }
        public string ToString(string format)
        {
            DateTime now = DateTime.Now;
            DateTime dt = new DateTime(now.Year, now.Month, now.Day, Hour, Minute, Second);
            return dt.ToString(format);
        }
        public TimeSpan ToTimeSpan()
        {
            return new TimeSpan(Hour, Minute, Second);
        }
        public DateTime ToToday()
        {
            var now = DateTime.Now;
            return new DateTime(now.Year, now.Month, now.Day, Hour, Minute, Second);
        }

        #region -- Static --
        public static TimeOfDay Midnight { get { return new TimeOfDay(0, 0, 0); } }
        public static TimeOfDay Noon { get { return new TimeOfDay(12, 0, 0); } }
        public static TimeOfDay operator -(TimeOfDay t1, TimeOfDay t2)
        {
            DateTime now = DateTime.Now;
            DateTime dt1 = new DateTime(now.Year, now.Month, now.Day, t1.Hour, t1.Minute, t1.Second);
            TimeSpan ts = new TimeSpan(t2.Hour, t2.Minute, t2.Second);
            DateTime dt2 = dt1 - ts;
            return new TimeOfDay(dt2);
        }
        public static bool operator !=(TimeOfDay t1, TimeOfDay t2)
        {
            if (ReferenceEquals(t1, t2)) { return true; }
            else if (ReferenceEquals(t1, null)) { return true; }
            else
            {
                return t1.TotalSeconds != t2.TotalSeconds;
            }
        }
        public static bool operator !=(TimeOfDay t1, DateTime dt2)
        {
            if (ReferenceEquals(t1, null)) { return false; }
            DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
            return dt1 != dt2;
        }
        public static bool operator !=(DateTime dt1, TimeOfDay t2)
        {
            if (ReferenceEquals(t2, null)) { return false; }
            DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
            return dt1 != dt2;
        }
        public static TimeOfDay operator +(TimeOfDay t1, TimeOfDay t2)
        {
            DateTime now = DateTime.Now;
            DateTime dt1 = new DateTime(now.Year, now.Month, now.Day, t1.Hour, t1.Minute, t1.Second);
            TimeSpan ts = new TimeSpan(t2.Hour, t2.Minute, t2.Second);
            DateTime dt2 = dt1 + ts;
            return new TimeOfDay(dt2);
        }
        public static bool operator <(TimeOfDay t1, TimeOfDay t2)
        {
            if (ReferenceEquals(t1, t2)) { return true; }
            else if (ReferenceEquals(t1, null)) { return true; }
            else
            {
                return t1.TotalSeconds < t2.TotalSeconds;
            }
        }
        public static bool operator <(TimeOfDay t1, DateTime dt2)
        {
            if (ReferenceEquals(t1, null)) { return false; }
            DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
            return dt1 < dt2;
        }
        public static bool operator <(DateTime dt1, TimeOfDay t2)
        {
            if (ReferenceEquals(t2, null)) { return false; }
            DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
            return dt1 < dt2;
        }
        public static bool operator <=(TimeOfDay t1, TimeOfDay t2)
        {
            if (ReferenceEquals(t1, t2)) { return true; }
            else if (ReferenceEquals(t1, null)) { return true; }
            else
            {
                if (t1 == t2) { return true; }
                return t1.TotalSeconds <= t2.TotalSeconds;
            }
        }
        public static bool operator <=(TimeOfDay t1, DateTime dt2)
        {
            if (ReferenceEquals(t1, null)) { return false; }
            DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
            return dt1 <= dt2;
        }
        public static bool operator <=(DateTime dt1, TimeOfDay t2)
        {
            if (ReferenceEquals(t2, null)) { return false; }
            DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
            return dt1 <= dt2;
        }
        public static bool operator ==(TimeOfDay t1, TimeOfDay t2)
        {
            if (ReferenceEquals(t1, t2)) { return true; }
            else if (ReferenceEquals(t1, null)) { return true; }
            else { return t1.Equals(t2); }
        }
        public static bool operator ==(TimeOfDay t1, DateTime dt2)
        {
            if (ReferenceEquals(t1, null)) { return false; }
            DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
            return dt1 == dt2;
        }
        public static bool operator ==(DateTime dt1, TimeOfDay t2)
        {
            if (ReferenceEquals(t2, null)) { return false; }
            DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
            return dt1 == dt2;
        }
        public static bool operator >(TimeOfDay t1, TimeOfDay t2)
        {
            if (ReferenceEquals(t1, t2)) { return true; }
            else if (ReferenceEquals(t1, null)) { return true; }
            else
            {
                return t1.TotalSeconds > t2.TotalSeconds;
            }
        }
        public static bool operator >(TimeOfDay t1, DateTime dt2)
        {
            if (ReferenceEquals(t1, null)) { return false; }
            DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
            return dt1 > dt2;
        }
        public static bool operator >(DateTime dt1, TimeOfDay t2)
        {
            if (ReferenceEquals(t2, null)) { return false; }
            DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
            return dt1 > dt2;
        }
        public static bool operator >=(TimeOfDay t1, TimeOfDay t2)
        {
            if (ReferenceEquals(t1, t2)) { return true; }
            else if (ReferenceEquals(t1, null)) { return true; }
            else
            {
                return t1.TotalSeconds >= t2.TotalSeconds;
            }
        }
        public static bool operator >=(TimeOfDay t1, DateTime dt2)
        {
            if (ReferenceEquals(t1, null)) { return false; }
            DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
            return dt1 >= dt2;
        }
        public static bool operator >=(DateTime dt1, TimeOfDay t2)
        {
            if (ReferenceEquals(t2, null)) { return false; }
            DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
            return dt1 >= dt2;
        }
        /// <summary>
        /// Input examples:
        /// 14:21:17            (2pm 21min 17sec)
        /// 02:15               (2am 15min 0sec)
        /// 2:15                (2am 15min 0sec)
        /// 2/1/2017 14:21      (2pm 21min 0sec)
        /// TimeOfDay=15:13:12  (3pm 13min 12sec)
        /// </summary>
        public static TimeOfDay Parse(string s)
        {
            // We will parse any section of the text that matches this
            // pattern: dd:dd or dd:dd:dd where the first doublet can
            // be one or two digits for the hour.  But minute and second
            // must be two digits.

            Match m = _TodRegex.Match(s);
            string text = m.Value;
            string[] fields = text.Split(':');
            if (fields.Length < 2) { throw new ArgumentException("No valid time of day pattern found in input text"); }
            int hour = Convert.ToInt32(fields[0]);
            int min = Convert.ToInt32(fields[1]);
            int sec = fields.Length > 2 ? Convert.ToInt32(fields[2]) : 0;

            return new TimeOfDay(hour, min, sec);
        }
        #endregion

        private void Init(int hour, int minute, int second)
        {
            if (hour < 0 || hour > 23) { throw new ArgumentException("Invalid hour, must be from 0 to 23."); }
            if (minute < 0 || minute > 59) { throw new ArgumentException("Invalid minute, must be from 0 to 59."); }
            if (second < 0 || second > 59) { throw new ArgumentException("Invalid second, must be from 0 to 59."); }
            Hour = hour;
            Minute = minute;
            Second = second;
        }
        private void Init(int hhmmss)
        {
            int hour = hhmmss / 10000;
            int min = (hhmmss - hour * 10000) / 100;
            int sec = (hhmmss - hour * 10000 - min * 100);
            Init(hour, min, sec);
        }
        private void Init(DateTime dt)
        {
            Init(dt.Hour, dt.Minute, dt.Second);
        }
    }
}
</code>```

Body:
Here's a full featured TimeOfDay class.

This is overkill for simple cases, but if you need more advanced functionality like I did, this may help.

It can handle the corner cases, some basic math, comparisons, interaction with DateTime, parsing, etc.

Below is the source code for the TimeOfDay class.  You can see usage examples and learn more here:

This class uses DateTime for most of its internal calculations and comparisons so that we can leverage all of the knowledge already embedded in DateTime.

// Author: Steve Lautenschlager, CambiaResearch.com
// License: MIT

using System;
using System.Text.RegularExpressions;

namespace Cambia
{
    public class TimeOfDay
    {
        private const int MINUTES_PER_DAY = 60 * 24;
        private const int SECONDS_PER_DAY = SECONDS_PER_HOUR * 24;
        private const int SECONDS_PER_HOUR = 3600;
        private static Regex _TodRegex = new Regex(@"\d?\d:\d\d:\d\d|\d?\d:\d\d");

        public TimeOfDay()
        {
            Init(0, 0, 0);
        }
        public TimeOfDay(int hour, int minute, int second = 0)
        {
            Init(hour, minute, second);
        }
        public TimeOfDay(int hhmmss)
        {
            Init(hhmmss);
        }
        public TimeOfDay(DateTime dt)
        {
            Init(dt);
        }
        public TimeOfDay(TimeOfDay td)
        {
            Init(td.Hour, td.Minute, td.Second);
        }

        public int HHMMSS
        {
            get
            {
                return Hour * 10000 + Minute * 100 + Second;
            }
        }
        public int Hour { get; private set; }
        public int Minute { get; private set; }
        public int Second { get; private set; }
        public double TotalDays
        {
            get
            {
                return TotalSeconds / (24d * SECONDS_PER_HOUR);
            }
        }
        public double TotalHours
        {
            get
            {
                return TotalSeconds / (1d * SECONDS_PER_HOUR);
            }
        }
        public double TotalMinutes
        {
            get
            {
                return TotalSeconds / 60d;
            }
        }
        public int TotalSeconds
        {
            get
            {
                return Hour * 3600 + Minute * 60 + Second;
            }
        }
        public bool Equals(TimeOfDay other)
        {
            if (other == null) { return false; }
            return TotalSeconds == other.TotalSeconds;
        }
        public override bool Equals(object obj)
        {
            if (obj == null) { return false; }
            TimeOfDay td = obj as TimeOfDay;
            if (td == null) { return false; }
            else { return Equals(td); }
        }
        public override int GetHashCode()
        {
            return TotalSeconds;
        }
        public DateTime ToDateTime(DateTime dt)
        {
            return new DateTime(dt.Year, dt.Month, dt.Day, Hour, Minute, Second);
        }
        public override string ToString()
        {
            return ToString("HH:mm:ss");
        }
        public string ToString(string format)
        {
            DateTime now = DateTime.Now;
            DateTime dt = new DateTime(now.Year, now.Month, now.Day, Hour, Minute, Second);
            return dt.ToString(format);
        }
        public TimeSpan ToTimeSpan()
        {
            return new TimeSpan(Hour, Minute, Second);
        }
        public DateTime ToToday()
        {
            var now = DateTime.Now;
            return new DateTime(now.Year, now.Month, now.Day, Hour, Minute, Second);
        }

        #region -- Static --
        public static TimeOfDay Midnight { get { return new TimeOfDay(0, 0, 0); } }
        public static TimeOfDay Noon { get { return new TimeOfDay(12, 0, 0); } }
        public static TimeOfDay operator -(TimeOfDay t1, TimeOfDay t2)
        {
            DateTime now = DateTime.Now;
            DateTime dt1 = new DateTime(now.Year, now.Month, now.Day, t1.Hour, t1.Minute, t1.Second);
            TimeSpan ts = new TimeSpan(t2.Hour, t2.Minute, t2.Second);
            DateTime dt2 = dt1 - ts;
            return new TimeOfDay(dt2);
        }
        public static bool operator !=(TimeOfDay t1, TimeOfDay t2)
        {
            if (ReferenceEquals(t1, t2)) { return true; }
            else if (ReferenceEquals(t1, null)) { return true; }
            else
            {
                return t1.TotalSeconds != t2.TotalSeconds;
            }
        }
        public static bool operator !=(TimeOfDay t1, DateTime dt2)
        {
            if (ReferenceEquals(t1, null)) { return false; }
            DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
            return dt1 != dt2;
        }
        public static bool operator !=(DateTime dt1, TimeOfDay t2)
        {
            if (ReferenceEquals(t2, null)) { return false; }
            DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
            return dt1 != dt2;
        }
        public static TimeOfDay operator +(TimeOfDay t1, TimeOfDay t2)
        {
            DateTime now = DateTime.Now;
            DateTime dt1 = new DateTime(now.Year, now.Month, now.Day, t1.Hour, t1.Minute, t1.Second);
            TimeSpan ts = new TimeSpan(t2.Hour, t2.Minute, t2.Second);
            DateTime dt2 = dt1 + ts;
            return new TimeOfDay(dt2);
        }
        public static bool operator <(TimeOfDay t1, TimeOfDay t2)
        {
            if (ReferenceEquals(t1, t2)) { return true; }
            else if (ReferenceEquals(t1, null)) { return true; }
            else
            {
                return t1.TotalSeconds < t2.TotalSeconds;
            }
        }
        public static bool operator <(TimeOfDay t1, DateTime dt2)
        {
            if (ReferenceEquals(t1, null)) { return false; }
            DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
            return dt1 < dt2;
        }
        public static bool operator <(DateTime dt1, TimeOfDay t2)
        {
            if (ReferenceEquals(t2, null)) { return false; }
            DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
            return dt1 < dt2;
        }
        public static bool operator <=(TimeOfDay t1, TimeOfDay t2)
        {
            if (ReferenceEquals(t1, t2)) { return true; }
            else if (ReferenceEquals(t1, null)) { return true; }
            else
            {
                if (t1 == t2) { return true; }
                return t1.TotalSeconds <= t2.TotalSeconds;
            }
        }
        public static bool operator <=(TimeOfDay t1, DateTime dt2)
        {
            if (ReferenceEquals(t1, null)) { return false; }
            DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
            return dt1 <= dt2;
        }
        public static bool operator <=(DateTime dt1, TimeOfDay t2)
        {
            if (ReferenceEquals(t2, null)) { return false; }
            DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
            return dt1 <= dt2;
        }
        public static bool operator ==(TimeOfDay t1, TimeOfDay t2)
        {
            if (ReferenceEquals(t1, t2)) { return true; }
            else if (ReferenceEquals(t1, null)) { return true; }
            else { return t1.Equals(t2); }
        }
        public static bool operator ==(TimeOfDay t1, DateTime dt2)
        {
            if (ReferenceEquals(t1, null)) { return false; }
            DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
            return dt1 == dt2;
        }
        public static bool operator ==(DateTime dt1, TimeOfDay t2)
        {
            if (ReferenceEquals(t2, null)) { return false; }
            DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
            return dt1 == dt2;
        }
        public static bool operator >(TimeOfDay t1, TimeOfDay t2)
        {
            if (ReferenceEquals(t1, t2)) { return true; }
            else if (ReferenceEquals(t1, null)) { return true; }
            else
            {
                return t1.TotalSeconds > t2.TotalSeconds;
            }
        }
        public static bool operator >(TimeOfDay t1, DateTime dt2)
        {
            if (ReferenceEquals(t1, null)) { return false; }
            DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
            return dt1 > dt2;
        }
        public static bool operator >(DateTime dt1, TimeOfDay t2)
        {
            if (ReferenceEquals(t2, null)) { return false; }
            DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
            return dt1 > dt2;
        }
        public static bool operator >=(TimeOfDay t1, TimeOfDay t2)
        {
            if (ReferenceEquals(t1, t2)) { return true; }
            else if (ReferenceEquals(t1, null)) { return true; }
            else
            {
                return t1.TotalSeconds >= t2.TotalSeconds;
            }
        }
        public static bool operator >=(TimeOfDay t1, DateTime dt2)
        {
            if (ReferenceEquals(t1, null)) { return false; }
            DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
            return dt1 >= dt2;
        }
        public static bool operator >=(DateTime dt1, TimeOfDay t2)
        {
            if (ReferenceEquals(t2, null)) { return false; }
            DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
            return dt1 >= dt2;
        }
        /// <summary>
        /// Input examples:
        /// 14:21:17            (2pm 21min 17sec)
        /// 02:15               (2am 15min 0sec)
        /// 2:15                (2am 15min 0sec)
        /// 2/1/2017 14:21      (2pm 21min 0sec)
        /// TimeOfDay=15:13:12  (3pm 13min 12sec)
        /// </summary>
        public static TimeOfDay Parse(string s)
        {
            // We will parse any section of the text that matches this
            // pattern: dd:dd or dd:dd:dd where the first doublet can
            // be one or two digits for the hour.  But minute and second
            // must be two digits.

            Match m = _TodRegex.Match(s);
            string text = m.Value;
            string[] fields = text.Split(':');
            if (fields.Length < 2) { throw new ArgumentException("No valid time of day pattern found in input text"); }
            int hour = Convert.ToInt32(fields[0]);
            int min = Convert.ToInt32(fields[1]);
            int sec = fields.Length > 2 ? Convert.ToInt32(fields[2]) : 0;

            return new TimeOfDay(hour, min, sec);
        }
        #endregion

        private void Init(int hour, int minute, int second)
        {
            if (hour < 0 || hour > 23) { throw new ArgumentException("Invalid hour, must be from 0 to 23."); }
            if (minute < 0 || minute > 59) { throw new ArgumentException("Invalid minute, must be from 0 to 59."); }
            if (second < 0 || second > 59) { throw new ArgumentException("Invalid second, must be from 0 to 59."); }
            Hour = hour;
            Minute = minute;
            Second = second;
        }
        private void Init(int hhmmss)
        {
            int hour = hhmmss / 10000;
            int min = (hhmmss - hour * 10000) / 100;
            int sec = (hhmmss - hour * 10000 - min * 100);
            Init(hour, min, sec);
        }
        private void Init(DateTime dt)
        {
            Init(dt.Hour, dt.Minute, dt.Second);
        }
    }
}


来源: stackexchange

问:
How can i use paramiko after it give me this error encode_point has been deprecated on EllipticCurvePublicNumbers
How can i use paramiko after it give me this error "paramiko\kex_ecdh_nist.py:39: CryptographyDeprecationWarning: encode_point has been deprecated on EllipticCurvePublicNumbers and will be removed in a future version. Please use EllipticCurvePublicKey.public_bytes to obtain both compressed and unco"</p>

答:
I had to disable gathering_facts to get past the warning. For some reason Ansible was getting stuck gathering facts.
After disabling gathering facts, I still get this warning, but Ansible is able to continue execution.

yaml file
gather_facts: no

ContentLicense: CC BY-SA 4.0


问:
echarts dataZoom event does not return timestamp but only percentages
I got a chart with a dataZoom component. The x-axis is of type time.
Zooming and roaming the chart works perfectly. But when I listen for the dataZoom event to hook into the zooming process I only get percentage values (0-100) from the event as current position.

the dataZoom config:

```<code>dataZoom: {
   start: 0,
   end: 3,
   showDetail: false
}
</code>```

my xAxis config:

```<code>xAxis: {
    type: 'time',
    boundaryGap: false,
    splitLine: {
        show: true,
        lineStyle: {
            color: '#ddd',
            type: 'dashed'
        }
    },
    axisLine: {
        show: false
    }
},
</code>```

I listen for the event like this:

```<code>myChart.on('dataZoom', function (evt) {
  console.log('zoom', evt);
})
</code>```

And I get this console output for evt:

```<code>{
  "type": "datazoom",
  "from": "viewComponent_17_0.8229841241707196",
  "dataZoomId": "\u0000\u0000-\u00000",
  "start": 1.6141473287753287,
  "end": 11.178346465795
}
</code>```

I would expect it to be something like:

```<code>"start" : "2012-12-01 15:30:00Z",
"end" : "2012-12-01 15:40:00Z"
</code>```

is this possible?

答:
I came across the same problem the following simple code works perfectly for me:</p>

```<code>myChart.on('dataZoom', function() {
  var option = myChart.getOption();
  console.log(option.dataZoom[0].startValue, option.dataZoom[0].endValue);
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I got a chart with a dataZoom component. The x-axis is of type time.
Zooming and roaming the chart works perfectly. But when I listen for the dataZoom event to hook into the zooming process I only get percentage values (0-100) from the event as current position.

the dataZoom config:

dataZoom: {
   start: 0,
   end: 3,
   showDetail: false
}

my xAxis config:

xAxis: {
    type: 'time',
    boundaryGap: false,
    splitLine: {
        show: true,
        lineStyle: {
            color: '#ddd',
            type: 'dashed'
        }
    },
    axisLine: {
        show: false
    }
},

I listen for the event like this:

myChart.on('dataZoom', function (evt) {
  console.log('zoom', evt);
})

And I get this console output for evt:

{
  "type": "datazoom",
  "from": "viewComponent_17_0.8229841241707196",
  "dataZoomId": "\u0000\u0000-\u00000",
  "start": 1.6141473287753287,
  "end": 11.178346465795
}

I would expect it to be something like:

"start" : "2012-12-01 15:30:00Z",
"end" : "2012-12-01 15:40:00Z"

is this possible?

Body:
I came across the same problem the following simple code works perfectly for me:

myChart.on('dataZoom', function() {
  var option = myChart.getOption();
  console.log(option.dataZoom[0].startValue, option.dataZoom[0].endValue);
});


问:
Python - Dataframe column conversion
I'm new on python and I'm trying to convert a column of a dataframe with strings (like 10,000+ or 1,000+) with regex in order to eliminate characters (+ and ,) and then convert them into integer.
How can I do that?

I've tried with regex functions but it doesn't work

```<code>convert_installs = re.compile('(?P<amount>\d*).(?P<unit>\d*)')
</code>```

is it correct for finding what I want to save?

enter image description here

答:
```<code>df['columnname'] = df['columnname'].str.replace('([+,])', '', regex = True).astype('int')
</code>```

Takes your column called columname, and replaces the + or , to nothing, then changes the type to integer.

Title: Python - Dataframe column conversion

Body:
I'm new on python and I'm trying to convert a column of a dataframe with strings (like 10,000+ or 1,000+) with regex in order to eliminate characters (+ and ,) and then convert them into integer.
How can I do that?

I've tried with regex functions but it doesn't work

convert_installs = re.compile('(?P<amount>\d*).(?P<unit>\d*)')

is it correct for finding what I want to save?

enter image description here

Body:
df['columnname'] = df['columnname'].str.replace('([+,])', '', regex = True).astype('int')

Takes your column called columname, and replaces the + or , to nothing, then changes the type to integer.


问:
Session must be bound error using Squeryl
Update:
Okay, I fixed the problem I was having, but I'm still not quite sure what I was doing wrong. In any case, I wrote the following method in IRCDB:

```<code>def tryit[T](p: => T) = {
    Class.forName("org.h2.Driver") //what's the point in this...?

    SessionFactory.concreteFactory = Some(() =>
        Session.create(java.sql.DriverManager.getConnection("jdbc:h2:~/irc","ScalaIRC",""), new H2Adapter))

    transaction {
        p
    }
}
</code>```

Then used it like so:

```<code> val query = from(IRCDB.channels)(c => select(c))
 IRCDB.tryit {
     for (r <- query) println("chan: " + r.name)
 }
</code>```

And it now works. From my understanding, I believed that once the session was created using the SessionFactory, I'd be able to use transaction { ... } anywhere that has the proper import. Apparently, my understanding is incorrect.

If anyone has anything to add please do.

So, I just started using Squeryl for a project I'm working on so this might just be an oversight on my part. So, first the code:

I have the following imports:

```<code>import org.squeryl.PrimitiveTypeMode._
import java.sql.Timestamp
import java.sql.DriverManager
import java.util.Date
import org.squeryl.adapters.H2Adapter
import org.squeryl.dsl.{OneToMany, ManyToOne, CompositeKey2}
import org.squeryl._
</code>```

I have the following table defined:

```<code>class ChannelTable(val id: Long, val name : String,
               val p_mode : Boolean, val s_mode : Boolean,
               val i_mode : Boolean, val t_mode : Boolean,
               val n_mode : Boolean, val m_mode : Boolean,
               val key : Option[String]) extends KeyedEntity[Long] {
    def this() = this(0,"", false, false, false, false, false, false, Some(""))

    lazy val bans:OneToMany[ChannelBanTable] = IRCDB.channelToChanBans.left(this)
    lazy val users = IRCDB.channelUsers.left(this)
    lazy val invites = IRCDB.channelInvites.left(this)
}
</code>```

And the following Schema defined:

```<code>object IRCDB extends Schema {
    val channels = table[ChannelTable]

    on(channels)(c => declare(
      c.p_mode defaultsTo(false),
      c.s_mode defaultsTo(false),
      c.i_mode defaultsTo(false),
      c.t_mode defaultsTo(false),
      c.n_mode defaultsTo(false),
      c.m_mode defaultsTo(false),
      c.name is(unique, indexed)
    ))

    def init {
        Class.forName("org.h2.Driver") //what's the point in this...?

        SessionFactory.concreteFactory = Some(() =>
          Session.create(DriverManager.getConnection("jdbc:h2:~/irc","ScalaIRC",""), new H2Adapter))
    }
    def getAllChannels = transaction { from(channels)(c => select(c))}
}
</code>```

I have been able to insert into the table with the following at the Console:

```<code>scala> import db._;import org.squeryl.PrimitiveTypeMode._
import db._
import org.squeryl.PrimitiveTypeMode._
scala> IRCDB.init
scala> transaction { IRCDB.channels.insert(new ChannelTable(0,"#chan_name", false, false, false, false, false, false, None)) }
res3: db.ChannelTable = db.ChannelTable@4
</code>```

I can confirm with the H2 Console that this does indeed occur. However, when I call IRCDB.getAllChannels (in both the Scala Console and in code) I get the following error:

```<code>java.lang.RuntimeException: no session is bound to current thread, a session must be created via Session.create
and bound to the thread via 'work' or 'bindToCurrentThread'
    at scala.Predef$.error(Predef.scala:58)
    at org.squeryl.Session$$anonfun$currentSession$1.apply(Session.scala:117)
    at org.squeryl.Session$$anonfun$currentSession$1.apply(Session.scala:117)
    at scala.Option.getOrElse(Option.scala:59)
    at org.squeryl.Session$.currentSession(Session.scala:116)
    at org.squeryl.dsl.AbstractQuery.org$squeryl$dsl$AbstractQuery$$_dbAdapter(AbstractQuery.scala:136)
    at org.squeryl.dsl.AbstractQuery$$anon$1.<init>(AbstractQuery.scala:140)
    at org.squeryl.dsl.AbstractQuery.iterator(AbstractQuery.scala:138)
    at scala.collection.IterableLike$class.foreach(IterableLike.scala:79)
    at org.squeryl.dsl.AbstractQuery.foreach(AbstractQuery.scala:27)
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:206)
    at org.squeryl.dsl.AbstractQuery.map(AbstractQuery.scala:27)
    at scala.runtime.ScalaRunTime$.inner$1(ScalaRunTime.scala:255)
    at scala.runtime.ScalaRunTime$.stringOf(ScalaRunTime.scala:258)
    at RequestResult$line7$object$.<init>(<console>:12)
    at RequestResult$line7$object$.<clinit>(<console>)
    at RequestResult$line7$object.scala_repl_result(<console>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun$apply$18.apply(Interpreter.scala:981)
    at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun$apply$18.apply(Interpreter.scala:981)
    at scala.util.control.Exception$Catch.apply(Exception.scala:79)
    at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1.apply(Interpreter.scala:980)
    at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1.apply(Interpreter.scala:980)
    at scala.util.control.Exception$Catch.apply(Exception.scala:79)
    at scala.tools.nsc.Interpreter$Request.loadAndRun(Interpreter.scala:979)
    at scala.tools.nsc.Interpreter.loadAndRunReq$1(Interpreter.scala:578)
    at scala.tools.nsc.Interpreter.interpret(Interpreter.scala:597)
    at scala.tools.nsc.Interpreter.interpret(Interpreter.scala:575)
    at scala.tools.nsc.InterpreterLoop.reallyInterpret$1(InterpreterLoop.scala:471)
    at scala.tools.nsc.InterpreterLoop.interpretStartingWith(InterpreterLoop.scala:514)
    at scala.tools.nsc.InterpreterLoop.command(InterpreterLoop.scala:361)
    at scala.tools.nsc.InterpreterLoop.processLine$1(InterpreterLoop.scala:242)
    at scala.tools.nsc.InterpreterLoop.repl(InterpreterLoop.scala:248)
    at scala.tools.nsc.InterpreterLoop.main(InterpreterLoop.scala:558)
    at scala.tools.nsc.InterpreterLoop.main(InterpreterLoop.scala:609)
    at org.jetbrains.plugins.scala.compiler.rt.ConsoleRunner.main(ConsoleRunner.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:115)
</code>```

I don't understand why I would be getting this error if I was able to insert rows into the table doing nearly the same way. If I try to execute transaction { from(IRCDB.channels)(c => select(c)) } at the Console I get the same error.

Edit: I've added the full stack trace. Also, I rewrote the getAllChannels function like this:

```<code>def getAllChannels = transaction {
  val ret = from(channels)(c => select(c))
  println("sql: " + ret)
  ret
}
</code>```

I still receive an error, but it does print the query out first -- I thought this may be useful:

```<code>sql: 'QueryExpressionNode[root:1a0d111]:rsm='ResultSetMapper:fdf48d()--
    'FieldSelectElement:ChannelTable1_name
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_i_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_s_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_key
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_n_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_m_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_id
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_t_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_p_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'ViewExpressionNode[sample:ChannelTable[16e3f87]]:rsm='ResultSetMapper:442b95($(1->ChannelTable.name:java.lang.String),$(2->ChannelTable.i_mode:java.lang.Boolean),$(3->ChannelTable.s_mode:java.lang.Boolean),$(4->ChannelTable.key:Option[java.lang.String]),$(5->ChannelTable.n_mode:java.lang.Boolean),$(6->ChannelTable.m_mode:java.lang.Boolean),$(7->ChannelTable.id:java.lang.Long),$(8->ChannelTable.t_mode:java.lang.Boolean),$(9->ChannelTable.p_mode:java.lang.Boolean))--*

Select
  ChannelTable1.name as ChannelTable1_name,
  ChannelTable1.i_mode as ChannelTable1_i_mode,
  ChannelTable1.s_mode as ChannelTable1_s_mode,
  ChannelTable1.key as ChannelTable1_key,
  ChannelTable1.n_mode as ChannelTable1_n_mode,
  ChannelTable1.m_mode as ChannelTable1_m_mode,
  ChannelTable1.id as ChannelTable1_id,
  ChannelTable1.t_mode as ChannelTable1_t_mode,
  ChannelTable1.p_mode as ChannelTable1_p_mode
From
  ChannelTable ChannelTable1
java.lang.RuntimeException: no session is bound to current thread, a session must be created via Session.create
and bound to the thread via 'work' or 'bindToCurrentThread'
    at scala.Predef$.error(Predef.scala:58)
    at org.squeryl.Session$$anonfun$currentSession$1.apply(Session.scala:117)
    at org.squeryl.Session$$anonfun$currentSession$1.apply(Session.scala:117)
    at scala.Option.getOrElse(Option.scala:59)
    at org.squeryl.Session$.currentSession(Session.scala:116)
    at org.squeryl.dsl.AbstractQuery.org$squeryl$dsl$AbstractQuery$$_dbAdapter(AbstractQuery.scala:136)
    at org.squeryl.dsl.AbstractQuery$$anon$1.<init>(AbstractQuery.scala:140)
    at org.squeryl.dsl.AbstractQuery.iterator(AbstractQuery.scala:138)
    at scala.collection.IterableLike$class.foreach(IterableLike.scala:79)
    at org.squeryl....
</code>```

答:
Here's what I suspect, your method :

def getAllChannels = transaction { from(channels)(c => select(c))}

is returning an unevaluated query, i.e.
the return type of

from(channels)(c => select(c))

is Query[ChannelTable]
so the method returns, the transaction is ended, the console tries to print it,
which triggers an evaluation :

```<code>at org.squeryl.dsl.AbstractQuery.map(AbstractQuery.scala:27)
at scala.runtime.ScalaRunTime$.inner$1(ScalaRunTime.scala:255)
at scala.runtime.ScalaRunTime$.stringOf(ScalaRunTime.scala:258)
at RequestResult$line7$object$.<init>(<console>:12)
at RequestResult$line7$object$.<clinit>(<console>)
at RequestResult$line7$object.scala_repl_result(<console>)
</code>```

since the transaction is ended, you get the message you are getting.

Try this :

```<code>
def getAllChannels = transaction {
  val q = from(channels)(c => select(c))
  for(z <- q) {
    println(z)
  }
}
</code>```

Body:
Update:
Okay, I fixed the problem I was having, but I'm still not quite sure what I was doing wrong. In any case, I wrote the following method in IRCDB:

def tryit[T](p: => T) = {
    Class.forName("org.h2.Driver") //what's the point in this...?

    SessionFactory.concreteFactory = Some(() =>
        Session.create(java.sql.DriverManager.getConnection("jdbc:h2:~/irc","ScalaIRC",""), new H2Adapter))

    transaction {
        p
    }
}

Then used it like so:

 val query = from(IRCDB.channels)(c => select(c))
 IRCDB.tryit {
     for (r <- query) println("chan: " + r.name)
 }

And it now works. From my understanding, I believed that once the session was created using the SessionFactory, I'd be able to use transaction { ... } anywhere that has the proper import. Apparently, my understanding is incorrect.

If anyone has anything to add please do.

So, I just started using Squeryl for a project I'm working on so this might just be an oversight on my part. So, first the code:

I have the following imports:

import org.squeryl.PrimitiveTypeMode._
import java.sql.Timestamp
import java.sql.DriverManager
import java.util.Date
import org.squeryl.adapters.H2Adapter
import org.squeryl.dsl.{OneToMany, ManyToOne, CompositeKey2}
import org.squeryl._

I have the following table defined:

class ChannelTable(val id: Long, val name : String,
               val p_mode : Boolean, val s_mode : Boolean,
               val i_mode : Boolean, val t_mode : Boolean,
               val n_mode : Boolean, val m_mode : Boolean,
               val key : Option[String]) extends KeyedEntity[Long] {
    def this() = this(0,"", false, false, false, false, false, false, Some(""))

    lazy val bans:OneToMany[ChannelBanTable] = IRCDB.channelToChanBans.left(this)
    lazy val users = IRCDB.channelUsers.left(this)
    lazy val invites = IRCDB.channelInvites.left(this)
}

And the following Schema defined:

object IRCDB extends Schema {
    val channels = table[ChannelTable]

    on(channels)(c => declare(
      c.p_mode defaultsTo(false),
      c.s_mode defaultsTo(false),
      c.i_mode defaultsTo(false),
      c.t_mode defaultsTo(false),
      c.n_mode defaultsTo(false),
      c.m_mode defaultsTo(false),
      c.name is(unique, indexed)
    ))

    def init {
        Class.forName("org.h2.Driver") //what's the point in this...?

        SessionFactory.concreteFactory = Some(() =>
          Session.create(DriverManager.getConnection("jdbc:h2:~/irc","ScalaIRC",""), new H2Adapter))
    }
    def getAllChannels = transaction { from(channels)(c => select(c))}
}

I have been able to insert into the table with the following at the Console:

scala> import db._;import org.squeryl.PrimitiveTypeMode._
import db._
import org.squeryl.PrimitiveTypeMode._
scala> IRCDB.init
scala> transaction { IRCDB.channels.insert(new ChannelTable(0,"#chan_name", false, false, false, false, false, false, None)) }
res3: db.ChannelTable = db.ChannelTable@4

I can confirm with the H2 Console that this does indeed occur. However, when I call IRCDB.getAllChannels (in both the Scala Console and in code) I get the following error:

java.lang.RuntimeException: no session is bound to current thread, a session must be created via Session.create
and bound to the thread via 'work' or 'bindToCurrentThread'
    at scala.Predef$.error(Predef.scala:58)
    at org.squeryl.Session$$anonfun$currentSession$1.apply(Session.scala:117)
    at org.squeryl.Session$$anonfun$currentSession$1.apply(Session.scala:117)
    at scala.Option.getOrElse(Option.scala:59)
    at org.squeryl.Session$.currentSession(Session.scala:116)
    at org.squeryl.dsl.AbstractQuery.org$squeryl$dsl$AbstractQuery$$_dbAdapter(AbstractQuery.scala:136)
    at org.squeryl.dsl.AbstractQuery$$anon$1.<init>(AbstractQuery.scala:140)
    at org.squeryl.dsl.AbstractQuery.iterator(AbstractQuery.scala:138)
    at scala.collection.IterableLike$class.foreach(IterableLike.scala:79)
    at org.squeryl.dsl.AbstractQuery.foreach(AbstractQuery.scala:27)
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:206)
    at org.squeryl.dsl.AbstractQuery.map(AbstractQuery.scala:27)
    at scala.runtime.ScalaRunTime$.inner$1(ScalaRunTime.scala:255)
    at scala.runtime.ScalaRunTime$.stringOf(ScalaRunTime.scala:258)
    at RequestResult$line7$object$.<init>(<console>:12)
    at RequestResult$line7$object$.<clinit>(<console>)
    at RequestResult$line7$object.scala_repl_result(<console>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun$apply$18.apply(Interpreter.scala:981)
    at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun$apply$18.apply(Interpreter.scala:981)
    at scala.util.control.Exception$Catch.apply(Exception.scala:79)
    at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1.apply(Interpreter.scala:980)
    at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1.apply(Interpreter.scala:980)
    at scala.util.control.Exception$Catch.apply(Exception.scala:79)
    at scala.tools.nsc.Interpreter$Request.loadAndRun(Interpreter.scala:979)
    at scala.tools.nsc.Interpreter.loadAndRunReq$1(Interpreter.scala:578)
    at scala.tools.nsc.Interpreter.interpret(Interpreter.scala:597)
    at scala.tools.nsc.Interpreter.interpret(Interpreter.scala:575)
    at scala.tools.nsc.InterpreterLoop.reallyInterpret$1(InterpreterLoop.scala:471)
    at scala.tools.nsc.InterpreterLoop.interpretStartingWith(InterpreterLoop.scala:514)
    at scala.tools.nsc.InterpreterLoop.command(InterpreterLoop.scala:361)
    at scala.tools.nsc.InterpreterLoop.processLine$1(InterpreterLoop.scala:242)
    at scala.tools.nsc.InterpreterLoop.repl(InterpreterLoop.scala:248)
    at scala.tools.nsc.InterpreterLoop.main(InterpreterLoop.scala:558)
    at scala.tools.nsc.InterpreterLoop.main(InterpreterLoop.scala:609)
    at org.jetbrains.plugins.scala.compiler.rt.ConsoleRunner.main(ConsoleRunner.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:115)

I don't understand why I would be getting this error if I was able to insert rows into the table doing nearly the same way. If I try to execute transaction { from(IRCDB.channels)(c => select(c)) } at the Console I get the same error.

Edit: I've added the full stack trace. Also, I rewrote the getAllChannels function like this:

def getAllChannels = transaction {
  val ret = from(channels)(c => select(c))
  println("sql: " + ret)
  ret
}

I still receive an error, but it does print the query out first -- I thought this may be useful:

sql: 'QueryExpressionNode[root:1a0d111]:rsm='ResultSetMapper:fdf48d()--
    'FieldSelectElement:ChannelTable1_name
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_i_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_s_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_key
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_n_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_m_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_id
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_t_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'FieldSelectElement:ChannelTable1_p_mode
        org.squeryl.dsl.ast.FieldSelectElement$$anon$3
    'ViewExpressionNode[sample:ChannelTable[16e3f87]]:rsm='ResultSetMapper:442b95($(1->ChannelTable.name:java.lang.String),$(2->ChannelTable.i_mode:java.lang.Boolean),$(3->ChannelTable.s_mode:java.lang.Boolean),$(4->ChannelTable.key:Option[java.lang.String]),$(5->ChannelTable.n_mode:java.lang.Boolean),$(6->ChannelTable.m_mode:java.lang.Boolean),$(7->ChannelTable.id:java.lang.Long),$(8->ChannelTable.t_mode:java.lang.Boolean),$(9->ChannelTable.p_mode:java.lang.Boolean))--*

Select
  ChannelTable1.name as ChannelTable1_name,
  ChannelTable1.i_mode as ChannelTable1_i_mode,
  ChannelTable1.s_mode as ChannelTable1_s_mode,
  ChannelTable1.key as ChannelTable1_key,
  ChannelTable1.n_mode as ChannelTable1_n_mode,
  ChannelTable1.m_mode as ChannelTable1_m_mode,
  ChannelTable1.id as ChannelTable1_id,
  ChannelTable1.t_mode as ChannelTable1_t_mode,
  ChannelTable1.p_mode as ChannelTable1_p_mode
From
  ChannelTable ChannelTable1
java.lang.RuntimeException: no session is bound to current thread, a session must be created via Session.create
and bound to the thread via 'work' or 'bindToCurrentThread'
    at scala.Predef$.error(Predef.scala:58)
    at org.squeryl.Session$$anonfun$currentSession$1.apply(Session.scala:117)
    at org.squeryl.Session$$anonfun$currentSession$1.apply(Session.scala:117)
    at scala.Option.getOrElse(Option.scala:59)
    at org.squeryl.Session$.currentSession(Session.scala:116)
    at org.squeryl.dsl.AbstractQuery.org$squeryl$dsl$AbstractQuery$$_dbAdapter(AbstractQuery.scala:136)
    at org.squeryl.dsl.AbstractQuery$$anon$1.<init>(AbstractQuery.scala:140)
    at org.squeryl.dsl.AbstractQuery.iterator(AbstractQuery.scala:138)
    at scala.collection.IterableLike$class.foreach(IterableLike.scala:79)
    at org.squeryl....

Body:
Here's what I suspect, your method :

def getAllChannels = transaction { from(channels)(c => select(c))}

is returning an unevaluated query, i.e.
the return type of

from(channels)(c => select(c))

is Query[ChannelTable]
so the method returns, the transaction is ended, the console tries to print it,
which triggers an evaluation :

at org.squeryl.dsl.AbstractQuery.map(AbstractQuery.scala:27)
at scala.runtime.ScalaRunTime$.inner$1(ScalaRunTime.scala:255)
at scala.runtime.ScalaRunTime$.stringOf(ScalaRunTime.scala:258)
at RequestResult$line7$object$.<init>(<console>:12)
at RequestResult$line7$object$.<clinit>(<console>)
at RequestResult$line7$object.scala_repl_result(<console>)

since the transaction is ended, you get the message you are getting.

Try this :

def getAllChannels = transaction {
  val q = from(channels)(c => select(c))
  for(z <- q) {
    println(z)
  }
}


问:
How to schedule a retrain of a sagemaker pipeline model using airflow
I have already implemented a sagemaker pipeline model. In particular for an end-to-end notebook that trains a model, builds a pipeline model and deploys it, I have followed this sample notebook.

Now I would like to retrain and deploy the entire pipeline every day using Airflow, but I have seen here the possibility to retrain and deploy only a single sagemaker model.

Is there a way to retrain and deploy the entire pipeline? Thanks

答:
SageMaker provides 2 options for users to do Airflow stuff:

Use the APIs in SageMaker Python SDK to generate input of all SageMaker operators in Airflow. The blog you linked goes this way. For example, they use API training_config in SageMaker Python SDK and operator SageMakerTrainingOperator in Airflow.

Use PythonOperator provided by Airflow and write Python codes to do what you want.

For 1, SageMaker only implemented APIs related to training, tuning, single model deployment and transform. Hence you are doing pipeline model, I don't think it has the API you want.

But for 2, if you can finish what you want in whatever Python codes with SageMaker. You should be able to adapt it as Python callables and make them work with PythonOperators. Here's an example for training in this way provided by SageMaker:

https://sagemaker.readthedocs.io/en/stable/using_workflow.html#using-airflow-python-operator

I think you can do similar things to make Airflow work with your pipeline model.


问:
How to move up the values of each column in a matrix in R
I'm looking for a general way to do the following,
I have a triangular matrix of nxn, for example:

```<code>a NA NA
b  d NA
c  e f
</code>```

and convert it in:

```<code>a d f
b e NA
c NA NA
</code>```

The idea is: for each column move the values, until the first non-NA value is in the first row

I imagine that it is done with a for, for each column, so that it goes up, but I do not know how to make it ...

答:
Here's a way with a custom function -</p>

```<code>m <- structure(c("a", "b", "c", NA, "d", "e", NA, NA, "f"), .Dim = c(3L,
3L), .Dimnames = list(NULL, c("V1", "V2", "V3")))

custom_shift <- function(x) {
  y <- x[!is.na(x)]
  length(y) <- length(x)
  y
}

apply(m, 2, function(a) custom_shift(a))

     V1  V2  V3
[1,] "a" "d" "f"
[2,] "b" "e" NA
[3,] "c" NA  NA
</code>```

Body:
I'm looking for a general way to do the following,
I have a triangular matrix of nxn, for example:

a NA NA
b  d NA
c  e f

and convert it in:

a d f
b e NA
c NA NA

The idea is: for each column move the values, until the first non-NA value is in the first row

I imagine that it is done with a for, for each column, so that it goes up, but I do not know how to make it ...

Body:
Here's a way with a custom function -

m <- structure(c("a", "b", "c", NA, "d", "e", NA, NA, "f"), .Dim = c(3L,
3L), .Dimnames = list(NULL, c("V1", "V2", "V3")))

custom_shift <- function(x) {
  y <- x[!is.na(x)]
  length(y) <- length(x)
  y
}

apply(m, 2, function(a) custom_shift(a))

     V1  V2  V3
[1,] "a" "d" "f"
[2,] "b" "e" NA
[3,] "c" NA  NA


问:
PHP ImagickException: not authorized
Any ideas how to fix this ?

```<code> ImagickException: not authorized `/tmp/magick-1552lvf2nIjaqx1W' @ error/constitute.c/ReadImage/412
</code>```

I thought it was a permission issue so just to test it out i set my /tmp dir to 777. No change. Its driving me crazy.

The command :

```<code><?php

$image = new \Imagick();
$image->readImageBlob('<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . $graph);
</code>```

答:
i hope this solution will help you
I'm facing the same issue and I'm on the live server i'm trying to follow above Mikel Annjuk and hakre answer so i cannot the change the file /etc/ImageMagick/policy.xml so i contact to the server provider to edit file and send this url to follow step but there is answering me

" I am still working on this. The solution given in above link requires root access to the server  which is not possible in a shared server. But imagick is related to php. So let me try changing php version and see if that helps"

when i tired to resolve this on that time i have idea may be the issue of the file path where  I'm saving the file so I change to base path to FCPATH and the matter is solved.
i'm using Codeigniter base_url() to php FCPATH this is the point to solve this issue

but on svg converter show "no decode delegate" issue

add the following lines in the start of file or code

like this

```<code>$usmap = file_get_contents(base_url('convert/plus.svg'));
     $find_string   = '<svg';
$position = strpos($usmap, $find_string);

   $svg_file_new ='<?xml version="1.0" encoding="UTF-8" standalone="no"?>'.substr($usmap, $position).'</svg>';
       file_put_contents(FCPATH.'convert/plus.svg', $svg_file_new);

        $usmap = base_url('convert/plus.svg');
$im = new Imagick($usmap);
$im->setImageFormat("jpg");

$im->writeImage(FCPATH .'convert/plus.jpg');
$im->clear();
$im->destroy();
</code>```

above code first, get the SVG code from the file and add XML version code then put it into the file and then convert SVG to any type of image like jpg

sorry for my English

Title: PHP ImagickException: not authorized

Body:
Any ideas how to fix this ?

 ImagickException: not authorized `/tmp/magick-1552lvf2nIjaqx1W' @ error/constitute.c/ReadImage/412

I thought it was a permission issue so just to test it out i set my /tmp dir to 777. No change. Its driving me crazy.

The command :

<?php

$image = new \Imagick();
$image->readImageBlob('<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . $graph);

Body:
i hope this solution will help you
I'm facing the same issue and I'm on the live server i'm trying to follow above Mikel Annjuk and hakre answer so i cannot the change the file /etc/ImageMagick/policy.xml so i contact to the server provider to edit file and send this url to follow step but there is answering me

" I am still working on this. The solution given in above link requires root access to the server  which is not possible in a shared server. But imagick is related to php. So let me try changing php version and see if that helps"

when i tired to resolve this on that time i have idea may be the issue of the file path where  I'm saving the file so I change to base path to FCPATH and the matter is solved.
i'm using Codeigniter base_url() to php FCPATH this is the point to solve this issue

but on svg converter show "no decode delegate" issue

add the following lines in the start of file or code

like this

$usmap = file_get_contents(base_url('convert/plus.svg'));
     $find_string   = '<svg';
$position = strpos($usmap, $find_string);

   $svg_file_new ='<?xml version="1.0" encoding="UTF-8" standalone="no"?>'.substr($usmap, $position).'</svg>';
       file_put_contents(FCPATH.'convert/plus.svg', $svg_file_new);

        $usmap = base_url('convert/plus.svg');
$im = new Imagick($usmap);
$im->setImageFormat("jpg");

$im->writeImage(FCPATH .'convert/plus.jpg');
$im->clear();
$im->destroy();

above code first, get the SVG code from the file and add XML version code then put it into the file and then convert SVG to any type of image like jpg

sorry for my English


问:
Convert a list into multiple CSV files with python
I would like to create a scalable code to import multiple CSV files, standardize the order of the colnumns based on the colnames and re-write CSV files.

```<code>import glob
import pandas as pd

# Get a list of all the csv files
csv_files = glob.glob('*.csv')

# List comprehension that loads of all the files
dfs = [pd.read_csv(x,delimiter=";") for x in csv_files]

A=pd.DataFrame(dfs[0])
B=pd.DataFrame(dfs[1])
alpha=A.columns.values.tolist()
print([pd.DataFrame(x[alpha]) for x in dfs])
</code>```

I would like to be able to split this object and write CSV for each of the file and rename them with the original names. is that easily possible with python? Thansk for your help.

答:
If you want to reorder columns by a consistent order, assuming that all csv's have the same column names but in a different order, you can sort one of the column name lists and then order the other ones by that list. Using your example:

csv_files = glob.glob('*.csv')
sorted_columns = []
for e,x in enumerate(csv_files):
    df = pd.read_csv(x,delimiter=";")
    if e==0:
        sorted_columns = sorted(df.columns.values.tolist())
    df[sorted_columns].to_csv(x, sep=";")
```

Body:
I would like to create a scalable code to import multiple CSV files, standardize the order of the colnumns based on the colnames and re-write CSV files.

import glob
import pandas as pd

# Get a list of all the csv files
csv_files = glob.glob('*.csv')

# List comprehension that loads of all the files
dfs = [pd.read_csv(x,delimiter=";") for x in csv_files]

A=pd.DataFrame(dfs[0])
B=pd.DataFrame(dfs[1])
alpha=A.columns.values.tolist()
print([pd.DataFrame(x[alpha]) for x in dfs])

I would like to be able to split this object and write CSV for each of the file and rename them with the original names. is that easily possible with python? Thansk for your help.


问:
Is it feasible to run a Support Vector Machine Kernel on a device with <= 1 MB RAM and <= 10 MB ROM?
Some preliminary testing shows that a project I'm working on could potentially benefit from the use of a Support-Vector-Machine to solve a tricky problem. The concern that I have is that there will be major memory constraints. Prototyping and testing is being done in python with scikit-learn. The final version will be custom written in C. The model would be pre-trained and only the decision function would be stored on the final product. There would be <= 10 training features, and <= 5000 training data-points. I've been reading mixed things regarding SVM memory, and I know the default sklearn memory cache is 200 MB. (Much larger than what I have available) Is this feasible? I know there are multiple different types of SVM kernel and that the kernel's can also be custom written. What kernel types could this potentially work with, if any?</p>

答:
If you're that strapped for space, you'll probably want to skip scikit and simply implement the math yourself.  That way, you can cycle through the data in structures of your own choosing.  Memory requirements depend on the class of SVM you're using; a two-class linear SVM can be done with a single pass through the data, considering only one observation at a time as you accumulate sum-of-products, so your command logic would take far more space than the data requirements.

If you need to keep the entire data set in memory for multiple passes, that's "only" 5000*10*8 bytes for floats, or 400k of your 1Mb, which might be enough room to do your manipulations.  Also consider a slow training process, re-reading the data on each pass, as this reduces the 400k to a triviality at the cost of wall-clock time.

All of this is under your control if you look up a usable SVM implementation and alter the I/O portions as needed.

Does that help?


问:
Using JENA API - Getting all the classes from OWL file
Is it possible to get name of all the classes present in OWL file using JENA and store in the Array List?</p>

```<code>   OntModel base = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, null);
    OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_MICRO_RULE_INF, null);

    String NS = "http://www.abc.com/abcportal/abc.owl" + "#";

base.read("file:abcInstance.owl");
    ExtendedIterator<OntClass> iter = base.listClasses();

    while ( iter.hasNext()){
        System.out.println(iter.next());
    }
</code>```

答: Yes it is, see the Javadoc for OntModel.listClasses. You can easily copy the contents of the Iterator into an array or List. That you're asking the question suggests that you'll probably benefit from reading the Jena ontology API documentation

Body:
Is it possible to get name of all the classes present in OWL file using JENA and store in the Array List?

   OntModel base = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, null);
    OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_MICRO_RULE_INF, null);

    String NS = "http://www.abc.com/abcportal/abc.owl" + "#";

base.read("file:abcInstance.owl");
    ExtendedIterator<OntClass> iter = base.listClasses();

    while ( iter.hasNext()){
        System.out.println(iter.next());
    }


问:
BMI Calculator with name, weight, height, BMI and text using Array and for cycle
I would like to ask how do I do that when the cycle starts and go over again, the string variable name will increase by 1. This program is supposed to ask you how many patients are you going to write. If you write for ex. 10, then the cycle will go for 10 times and it will ask all those information I want and then add them to the array which I have already created called BMI. This whole program is supposed to print you a table which contains Name, Height in meters, weight in Kg, your calculated BMI and then text in what state of BMI are you ATM. The problem is how do I do it? I just started learning arrays and stuff like that and my teacher gave me this homework. I don't think that this homework is hard but just hard to understand what to do.

Things I already tried is creating a for cycle with String called name something like this: String name(); but that obviously did not work.

```<code>import java.util.Scanner;
class Pacient {
    public static void main(String args[]){
        int pole;
        Scanner input = new Scanner(System.in);
        String pacient;

        System.out.print("Zadej kolik bude pacientu: "); //How many patients do you want? For ex. 10

        pacient = input.nextLine();
        input.nextLine();
        pole = Integer.parseInt(pacient);

        String[][] bmi = new String[4][pole]; //This is supposed to make an array with my patients.

        double vaha; //weight
        double vyska; //height
        String jmeno; //name
        double telo1, telo2; //body for calc.
        String vysledek; //result
        int i,x=0,j, pa=0, k=0; //some variables

        bmi[0][0] = "Jmeno"; //First line of final table NAME
        bmi[0][1] = "Vaha"; // WEIGHT
        bmi[0][2] = "Vyska"; //HEIGHT
        bmi[0][3] = "BMI"; //BMI based on calc.
        bmi[0][4] = "Text"; //Final result

        for(int y=1;y<pole;y++){
            pa++;
            x++;

            System.out.print("Zadej svoje krestni jmeno: ");
            jmeno = input.nextLine();

            System.out.print("Zadej svoji vahu v Kg: ");
            vaha = input.nextDouble();

            System.out.print("Zadej svoji vysku v m: ");
            vyska = input.nextDouble();

            System.out.println("Vase informace byly uspesne ulozeny! ");

            bmi[1][0] = jmeno; //These values should somehow increase but idk
                                 how atm and be assign with the patient which
                                 will be printed at the end.
            bmi[1][1] = vaha2;
            bmi[1][2] = vyska2;
            bmi[1][3] = telo3;
            bmi[1][4] = vysledek;

        }

        // System.out.println("Tisknu tabulku");

        // telo1 = vyska * vyska; //Some calc. of BMI
        // telo2 = vaha / telo1;

        // if (telo2 < 18.5) { //Adding text to the result variable
        //     vysledek = "mate podvahu";
        // } else if (telo2 < 25) {
        //     vysledek = "Jste v normach";
        // } else if (telo2 < 30) {
        //     vysledek = "Nadvaha";
        // } else {
        //     vysledek = "Obezita";
        // }

        // String telo3 = String.valueOf(telo2); //Converting to strings
        // String vyska2 = String.valueOf(vyska);
        // String vaha2 = String.valueOf(vaha);

        System.out.println("--------------------------------------------------");

        for(i=0;i<pole;i++) {
            for(j = 0; j<5; j++) System.out.print(bmi[i][j] + " ");
                System.out.println();
        }
        System.out.println("--------------------------------------------------");
    }
}
</code>```

Atm the program is just printing most of the time NULL NULL NULL NULL, and it does not match with the patient number. How do add all this code to for cycle and make it automatic convert int and double to strings and then print them correctly and assign them to the BMI Array. If you have any further questing, feel free to ask.

答:
Your declaration of array and implementation is conflicting. You've fixed the first dimension and kept the second, variable. But you're using as if the first one is variable and second is fixed.

You should declare your array like

String[][] bmi = new String[pole+1][4];

pole+1 because you're using first row for table headings

Your first loop should look like this

```<code>for(int y = 1; y < pole+1; y++){
    for(int z = 0; z < 4; z++){
        String data="ask user for data";
        bmi[y][z] = data; //similar for all
    }
}
</code>```

Your output for loop will also look like above.

Body:
I would like to ask how do I do that when the cycle starts and go over again, the string variable name will increase by 1. This program is supposed to ask you how many patients are you going to write. If you write for ex. 10, then the cycle will go for 10 times and it will ask all those information I want and then add them to the array which I have already created called BMI. This whole program is supposed to print you a table which contains Name, Height in meters, weight in Kg, your calculated BMI and then text in what state of BMI are you ATM. The problem is how do I do it? I just started learning arrays and stuff like that and my teacher gave me this homework. I don't think that this homework is hard but just hard to understand what to do.

Things I already tried is creating a for cycle with String called name something like this: String name(); but that obviously did not work.

import java.util.Scanner;
class Pacient {
    public static void main(String args[]){
        int pole;
        Scanner input = new Scanner(System.in);
        String pacient;

        System.out.print("Zadej kolik bude pacientu: "); //How many patients do you want? For ex. 10

        pacient = input.nextLine();
        input.nextLine();
        pole = Integer.parseInt(pacient);

        String[][] bmi = new String[4][pole]; //This is supposed to make an array with my patients.

        double vaha; //weight
        double vyska; //height
        String jmeno; //name
        double telo1, telo2; //body for calc.
        String vysledek; //result
        int i,x=0,j, pa=0, k=0; //some variables

        bmi[0][0] = "Jmeno"; //First line of final table NAME
        bmi[0][1] = "Vaha"; // WEIGHT
        bmi[0][2] = "Vyska"; //HEIGHT
        bmi[0][3] = "BMI"; //BMI based on calc.
        bmi[0][4] = "Text"; //Final result

        for(int y=1;y<pole;y++){
            pa++;
            x++;

            System.out.print("Zadej svoje krestni jmeno: ");
            jmeno = input.nextLine();

            System.out.print("Zadej svoji vahu v Kg: ");
            vaha = input.nextDouble();

            System.out.print("Zadej svoji vysku v m: ");
            vyska = input.nextDouble();

            System.out.println("Vase informace byly uspesne ulozeny! ");

            bmi[1][0] = jmeno; //These values should somehow increase but idk
                                 how atm and be assign with the patient which
                                 will be printed at the end.
            bmi[1][1] = vaha2;
            bmi[1][2] = vyska2;
            bmi[1][3] = telo3;
            bmi[1][4] = vysledek;

        }

        // System.out.println("Tisknu tabulku");

        // telo1 = vyska * vyska; //Some calc. of BMI
        // telo2 = vaha / telo1;

        // if (telo2 < 18.5) { //Adding text to the result variable
        //     vysledek = "mate podvahu";
        // } else if (telo2 < 25) {
        //     vysledek = "Jste v normach";
        // } else if (telo2 < 30) {
        //     vysledek = "Nadvaha";
        // } else {
        //     vysledek = "Obezita";
        // }

        // String telo3 = String.valueOf(telo2); //Converting to strings
        // String vyska2 = String.valueOf(vyska);
        // String vaha2 = String.valueOf(vaha);

        System.out.println("--------------------------------------------------");

        for(i=0;i<pole;i++) {
            for(j = 0; j<5; j++) System.out.print(bmi[i][j] + " ");
                System.out.println();
        }
        System.out.println("--------------------------------------------------");
    }
}

Atm the program is just printing most of the time NULL NULL NULL NULL, and it does not match with the patient number. How do add all this code to for cycle and make it automatic convert int and double to strings and then print them correctly and assign them to the BMI Array. If you have any further questing, feel free to ask.

Body:
Your declaration of array and implementation is conflicting. You've fixed the first dimension and kept the second, variable. But you're using as if the first one is variable and second is fixed.

You should declare your array like

String[][] bmi = new String[pole+1][4];

pole+1 because you're using first row for table headings

Your first loop should look like this

for(int y = 1; y < pole+1; y++){
    for(int z = 0; z < 4; z++){
        String data="ask user for data";
        bmi[y][z] = data; //similar for all
    }
}

Your output for loop will also look like above.


问:
Import json file from Firebase Admin SDK
I can update the whole database (Real Database) by importing a json file in Firebase Console:

How can I do it programmatically from server side (with Firebase Admin)?

I tried

```<code>private void uploadFirebaseDatabaseFile(JsonObject jsonObject) {
    // As an admin, the app has access to read and write all data, regardless of Security Rules
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    ref.setValue(jsonObject, (error, ref1) -> System.out.println(error + " " + ref1));
}
</code>```

But it throws java.lang.RuntimeException: java.lang.reflect.InvocationTargetException ... Caused by: java.lang.IllegalStateException: Not a JSON Primitive: { ...

答:
Solved it:</p>

```<code>private void uploadFirebaseDatabaseFile(Gson gson, JsonObject jsonObject) throws Exception {
    // As an admin, the app has access to read and write all data, regardless of Security Rules
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    CountDownLatch done = new CountDownLatch(1);
    // we must convert our JsonObject and its all nested children to Map<String, Object>
    ref.setValue(gson.fromJson(jsonObject, Map.class), (error, ref1) -> {
            System.out.println(error + " " + ref1);
        done.countDown();
    });
    done.await();
}
</code>```

Body:
I can update the whole database (Real Database) by importing a json file in Firebase Console:

How can I do it programmatically from server side (with Firebase Admin)?

I tried

private void uploadFirebaseDatabaseFile(JsonObject jsonObject) {
    // As an admin, the app has access to read and write all data, regardless of Security Rules
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    ref.setValue(jsonObject, (error, ref1) -> System.out.println(error + " " + ref1));
}

But it throws java.lang.RuntimeException: java.lang.reflect.InvocationTargetException ... Caused by: java.lang.IllegalStateException: Not a JSON Primitive: { ...

Body:
Solved it:

private void uploadFirebaseDatabaseFile(Gson gson, JsonObject jsonObject) throws Exception {
    // As an admin, the app has access to read and write all data, regardless of Security Rules
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    CountDownLatch done = new CountDownLatch(1);
    // we must convert our JsonObject and its all nested children to Map<String, Object>
    ref.setValue(gson.fromJson(jsonObject, Map.class), (error, ref1) -> {
            System.out.println(error + " " + ref1);
        done.countDown();
    });
    done.await();
}


问:
Interrupts do not fire
Question will be deleted shortly. Made a stupid mistake,these IRQs are supposed to be triggered by buttons. I meant to ask why don't they fire on their own automatically.

Interrupt handlers are not triggered. That's a book code
for the most part. Board based on : stm32f411RE Nucleo.

The code is meant for f429 but form my research it looks like it should be
fine.

Edit:
Adding this line makes it fire, but only once:

```<code>EXTI->SWIER = EXTI_SWIER_SWIER0|EXTI_SWIER_SWIER2;
</code>```

So I need to reset a flag for this somehow.
But why the original hardware interrupts do not trigger.

```<code>
int main(void)
{
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN | RCC_AHB1ENR_GPIOBEN;
RCC->APB2ENR = RCC_APB2ENR_SYSCFGEN;
__DSB();

GPIOA->MODER |= GPIO_MODER_MODE5_0;
GPIOB->PUPDR |= GPIO_PUPDR_PUPD2_0;

    SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI0_PB | SYSCFG_EXTICR1_EXTI2_PB ;

    EXTI->FTSR = EXTI_FTSR_TR2;
    EXTI->RTSR = EXTI_RTSR_TR0;
    EXTI->IMR = EXTI_IMR_MR0 | EXTI_IMR_MR2;

    NVIC_EnableIRQ(EXTI0_IRQn);
    NVIC_EnableIRQ(EXTI2_IRQn);

    while (1);
    }
/* main */
void EXTI0_IRQHandler(void)
{
        if ( EXTI->PR & EXTI_PR_PR0)
        {
            EXTI->PR = EXTI_PR_PR0;

            GPIOA->ODR ^= GPIO_ODR_OD5;    }

}

void EXTI2_IRQHandler(void)
{
        if ( EXTI->PR & EXTI_PR_PR2)
        {
            EXTI->PR = EXTI_PR_PR2;
            GPIOA->ODR ^= GPIO_ODR_OD5;
        }
}
</code>```

答:
You also have to clear the pending IRQ in the NVIC, something like

NVIC_ClearPendingIRQ(EXTI0_IRQn);

In addition, you need to make sure the interrupt vector table have the correct entries for your handlers. Usually the interrupt vector table is in the startup file, but it depends on your system.

Title: Interrupts do not fire

Body:
Question will be deleted shortly. Made a stupid mistake,these IRQs are supposed to be triggered by buttons. I meant to ask why don't they fire on their own automatically.

Interrupt handlers are not triggered. That's a book code
for the most part. Board based on : stm32f411RE Nucleo.

The code is meant for f429 but form my research it looks like it should be
fine.

Edit:
Adding this line makes it fire, but only once:

EXTI->SWIER = EXTI_SWIER_SWIER0|EXTI_SWIER_SWIER2;

So I need to reset a flag for this somehow.
But why the original hardware interrupts do not trigger.

int main(void)
{
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN | RCC_AHB1ENR_GPIOBEN;
RCC->APB2ENR = RCC_APB2ENR_SYSCFGEN;
__DSB();

GPIOA->MODER |= GPIO_MODER_MODE5_0;
GPIOB->PUPDR |= GPIO_PUPDR_PUPD2_0;

    SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI0_PB | SYSCFG_EXTICR1_EXTI2_PB ;

    EXTI->FTSR = EXTI_FTSR_TR2;
    EXTI->RTSR = EXTI_RTSR_TR0;
    EXTI->IMR = EXTI_IMR_MR0 | EXTI_IMR_MR2;

    NVIC_EnableIRQ(EXTI0_IRQn);
    NVIC_EnableIRQ(EXTI2_IRQn);

    while (1);
    }
/* main */
void EXTI0_IRQHandler(void)
{
        if ( EXTI->PR & EXTI_PR_PR0)
        {
            EXTI->PR = EXTI_PR_PR0;

            GPIOA->ODR ^= GPIO_ODR_OD5;    }

}

void EXTI2_IRQHandler(void)
{
        if ( EXTI->PR & EXTI_PR_PR2)
        {
            EXTI->PR = EXTI_PR_PR2;
            GPIOA->ODR ^= GPIO_ODR_OD5;
        }
}


问:
Angular 7 rxjs 6 bind to certain elements only
I am building a new web application in Angular7.

I have a data table and I want to build server-side search functionality based on search values for each column. I have an input element at the top of each column in the data table. The search filtering should be triggered each time the search value changes in any of the input boxes.

I think I need to bind the keyup event to detect the change of value. I am using rxjs fromEvent and this does work, however, it detects the keyup of ANY keyboard event, not just the events tied to the relevant input boxes. I want to avoid unnecessary events since this will call the server-side filtering each time.

HTML

```<code><table mat-table [dataSource]="data" class="example-table" matSort>
  <!-- ItemID Column -->
  <ng-container matColumnDef="ItemID">
    <th class="header" mat-header-cell *matHeaderCellDef>
      <div mat-sort-header>ItemID</div>
      <mat-form-field class="filter" floatLabel="never">
        <input
          matInput
          placeholder="Search ItemID"
          #input
          [(ngModel)]="searchValues.ItemID"
        >
      </mat-form-field>
    </th>
    <td mat-cell *matCellDef="let row">{{row.ItemID}}</td>
  </ng-container>

  <!-- IdentificationID Column -->
  <ng-container matColumnDef="IdentificationID">
    <th class="header" mat-header-cell *matHeaderCellDef>
      <div mat-sort-header>IdentificationID</div>
      <mat-form-field class="filter" floatLabel="never">
        <input
          matInput
          placeholder="Search IdentificationID"
          #input
          [(ngModel)]="searchValues.IdentificationID"
        >
      </mat-form-field>
    </th>
    <td mat-cell *matCellDef="let row">{{row.IdentificationID}}</td>
  </ng-container>
</table>
</code>```

TS component

```<code>// TODO: bind to relevant input elements only
fromEvent<KeyboardEvent>(document, 'keyup')
  .pipe(
    debounceTime(150),
    distinctUntilChanged(),
    tap(() => {

      // call search function

    })
  )
  .subscribe();
</code>```

答:
If you want to user fromEvent you can filter all events by tag name. In your case it will be like below:

```<code>// TODO: bind to relevant input elements only
fromEvent<KeyboardEvent>(document, 'keyup')
  .pipe(
    filter(e => e.target && e.target.tagName === 'INPUT') // filters only observables from INPUT
    debounceTime(150),
    distinctUntilChanged(),
    tap(() => {

      // call search function

    })
  )
  .subscribe();
</code>```

Please pay attention on filter() operator which I added.

If you don't want to use fromEvent you can use angular built in bindings to bind input's keyup event:

```<code><input (keyup)="searchTable($event)">
</code>```

I prefer second option.

Body:
I am building a new web application in Angular7.

I have a data table and I want to build server-side search functionality based on search values for each column. I have an input element at the top of each column in the data table. The search filtering should be triggered each time the search value changes in any of the input boxes.

I think I need to bind the keyup event to detect the change of value. I am using rxjs fromEvent and this does work, however, it detects the keyup of ANY keyboard event, not just the events tied to the relevant input boxes. I want to avoid unnecessary events since this will call the server-side filtering each time.

HTML

  <ng-container matColumnDef="ItemID">

ItemID

      <mat-form-field class="filter" floatLabel="never">
        <input
          matInput
          placeholder="Search ItemID"
          #input
          [(ngModel)]="searchValues.ItemID"
        >
      </mat-form-field>

    {{row.ItemID}}
  </ng-container>

  <ng-container matColumnDef="IdentificationID">

IdentificationID

      <mat-form-field class="filter" floatLabel="never">
        <input
          matInput
          placeholder="Search IdentificationID"
          #input
          [(ngModel)]="searchValues.IdentificationID"
        >
      </mat-form-field>

    {{row.IdentificationID}}
  </ng-container>

TS component

// TODO: bind to relevant input elements only
fromEvent<KeyboardEvent>(document, 'keyup')
  .pipe(
    debounceTime(150),
    distinctUntilChanged(),
    tap(() => {

      // call search function

    })
  )
  .subscribe();

Body:
If you want to user fromEvent you can filter all events by tag name. In your case it will be like below:

// TODO: bind to relevant input elements only
fromEvent<KeyboardEvent>(document, 'keyup')
  .pipe(
    filter(e => e.target && e.target.tagName === 'INPUT') // filters only observables from INPUT
    debounceTime(150),
    distinctUntilChanged(),
    tap(() => {

      // call search function

    })
  )
  .subscribe();

Please pay attention on filter() operator which I added.

If you don't want to use fromEvent you can use angular built in bindings to bind input's keyup event:

<input (keyup)="searchTable($event)">

I prefer second option.


问:
SCSS sum of two rem units added together outputs the operation not the value
I am attempting to subtract the value of two rem units form a margin in scss however the css outputs the operation instead of the value. Is this even possible?

I have a rem value and a pixel value which I use a function to convert to rem then try to subtract the sum of them added together. Thanks for some help

```<code>$size-md: 1.25rem;
$border-md: 2px;

@function calculateRem($size) {
  $remSize: $size / 16px;
  @return #{$remSize}rem;
}

p {
  margin-right: - (#{$size-md} + #{calculateRem($border-md)});
</code>```

CSS Output

```<code>p { margin-right: 1.25rem + 0.125rem; }
</code>```

Sassmeister Code

https://www.sassmeister.com/gist/3d3456752f0d82071e75e1afb54ab7f5

答:
The main issue is the string interpolation using #{$variable}.

Once something is interpolated into a string, that is how the sass compiler will continue to treat it.

There area few options:

1. Wrap the string calculation with calc() and allow the browser to just add the two numbers.

Input:

```<code>p { margin-right: calc(#{$size-md} + #{calculateRem($border-md)});
</code>```

Output:

```<code>p { margin-right: calc(1.25rem + 0.125rem); }
</code>```

2. Use a custom sass function to convert the string back to numbers.

Refer to https://hugogiraudel.com/2014/01/15/sass-string-to-number/

Input:

```<code>p { margin-right: (number($size-md) + number(calculateRem($border-md)));
</code>```

Output:

```<code>p { margin-right: 1.375rem; }
</code>```

3. Remove the string interpolation

Input:

```<code>@function calculateRem($size) {
  $remSize: $size / 16px;
  @return $remSize * 1rem; // removed string interpolation, use * 1rem to convert to rems
}

p { margin-right: ($size-md + calculateRem($border-md)); // removed string interpolation to allow number calculations
</code>```

Output:

```<code>p { margin-right: 1.375rem; }
</code>```

I think #3 is the best option, but it will depend on your codebase.

Body:
I am attempting to subtract the value of two rem units form a margin in scss however the css outputs the operation instead of the value. Is this even possible?

I have a rem value and a pixel value which I use a function to convert to rem then try to subtract the sum of them added together. Thanks for some help

$size-md: 1.25rem;
$border-md: 2px;

@function calculateRem($size) {
  $remSize: $size / 16px;
  @return #{$remSize}rem;
}

p {
  margin-right: - (#{$size-md} + #{calculateRem($border-md)});

CSS Output

p { margin-right: 1.25rem + 0.125rem; }

Sassmeister Code

https://www.sassmeister.com/gist/3d3456752f0d82071e75e1afb54ab7f5

Body:
The main issue is the string interpolation using #{$variable}.

Once something is interpolated into a string, that is how the sass compiler will continue to treat it.

There area few options:

1. Wrap the string calculation with calc() and allow the browser to just add the two numbers.

Input:

p { margin-right: calc(#{$size-md} + #{calculateRem($border-md)});

Output:

p { margin-right: calc(1.25rem + 0.125rem); }

2. Use a custom sass function to convert the string back to numbers.

Refer to https://hugogiraudel.com/2014/01/15/sass-string-to-number/

Input:

p { margin-right: (number($size-md) + number(calculateRem($border-md)));

Output:

p { margin-right: 1.375rem; }

3. Remove the string interpolation

Input:

@function calculateRem($size) {
  $remSize: $size / 16px;
  @return $remSize * 1rem; // removed string interpolation, use * 1rem to convert to rems
}

p { margin-right: ($size-md + calculateRem($border-md)); // removed string interpolation to allow number calculations

Output:

p { margin-right: 1.375rem; }

I think #3 is the best option, but it will depend on your codebase.


问:
Issue with navigateTo in NativeScript Vue modal
I am attempting to use navigateTo() within a modal in my NativeScript Vue application.

My modal components is wrapped in a <Frame>, which I understand is how to allow it to be a navigation controller. However, when I attempt to navigate to the sub-component of the modal, it actually opens behind the modal in the main frame.

You can see this behavior here: https://play.nativescript.org/?template=play-vue&id=azowAE&v=3

Click the "Open Modal" button and then click the "Show subpage" button. Seemingly nothing happens, but if you then click the "Close" button, you'll see the sub page opened behind the modal.

答:
Another cause for this same issue is when the sub-component that the modal is navigating to isn't wrapped in a <Page> tag.

When you add a catch to your navigate code then it gives the following errors, depending on whether you use the ref or id.

```<code>this.$navigateTo(NewModal, {
  frame: "frame-id" // or "frame-ref"
}).catch(e => console.log(e));
</code>```

"frame-ref" throws TypeError: Cannot read property 'id' of undefined

"frame-id" throws TypeError: backstackEntry.resolvedPage.onNavigatingTo is not a function

Body:
Another cause for this same issue is when the sub-component that the modal is navigating to isn't wrapped in a <Page> tag.

When you add a catch to your navigate code then it gives the following errors, depending on whether you use the ref or id.

this.$navigateTo(NewModal, {
  frame: "frame-id" // or "frame-ref"
}).catch(e => console.log(e));

"frame-ref" throws TypeError: Cannot read property 'id' of undefined

"frame-id" throws TypeError: backstackEntry.resolvedPage.onNavigatingTo is not a function


问:
Deploying an AWS Lambda from a different account
I have a Lambda .jar that I build from a Jenkins box in an AWS account ("Account_Bld"). Once built, I copy the .jar over to an S3 bucket in a different AWS account ("Account_Dst"), and I attempt to update the Lambda in Account_Dst based on the newly copied .jar in S3.

I'm using this command as part of my deploy script, which is a slight modification of another version that works when everything is located in the same account:

aws lambda update-function-code --function-name arn:aws:lambda:us-east-1:{Account_Dst_Id}:function:{lambda_function_name} --zip-file fileb://{jar_file_relative_path} --region us-east-1

Not surprisingly, I get this error:

An error occurred (AccessDeniedException) when calling the UpdateFunctionCode operation: User: arn:aws:sts::{Account_Bld_Id}:assumed-role/{jenkins_ec2_role}/{jenkins_ec2_instance_id} is not authorized to perform: lambda:UpdateFunctionCode on resource: arn:aws:lambda:us-east-1:{Account_Dst_Id}:function:{lambda_function_name}

I have given jenkins_ec2_role rights to update the Lambda in the other account, but it makes sense that I would need to reciprocate those rights somewhere in Account_Dst -- assuming there is a simple solution to this problem.

Now, possible resolutions. I could assume a role in Account_Dst that has the correct rights and update the Lambda, but that's more setup hassle than it is worth to me right now. I've seen some Google suggestions that I could use CodePipeline, but obviously I'm using Jenkins, so that doesn't seem like a good solution, either.

So, the question is, is there an easy solution here that I am missing?

答:
Granting permissions in Account_Bld to access Account_Dst is not sufficient to gain access to another account. This is good, because you wouldn't want people granting themselves access to other people's accounts.

The destination account needs to accept the incoming request. The method varies by service. For example, Amazon S3 can create a Bucket Policy to permit access from other accounts, as can Amazon SQS.

However, there is no such concept in Lambda to configure incoming requests from other accounts. There is simply nowhere that can be configured to allow update-function-code from another account.

Therefore, you will need to do as you suggested:

Create an IAM User or IAM Role in Account_Dst

Use the credentials from the Account_Dst IAM User (simplest) or use the existing Account_Bld credentials to assume the Role in Account_Dst (a few more lines of code)

Call update-function-code using those credentials


问:
OCaml: Using `try` and `with` for larger programs
Suppose you have a sequence of expressions that potentially raise an exception.  If it does, you want some long process to take place.  If it doesn't you want a different long process to take place.  In imperative languages you can usually do something like

```<code>try:
    ...
except:
    ...
</code>```

but I can't seem to reproduce this in OCaml, because it seems like you can only check a single expression at a time for an exception.  I also don't see how you can use the value, if it exists, or do something else if it doesn't.

For a more concrete, if trivial example:  I have a function list_max that returns the max of a list if it's non-empty and raises an exception if it is empty.  Suppose I have a list and want to assert that its max is 4, but I'm wrong and it's really an empty list.  I can't seem to get the syntax right from explanations that I've found.  I've tried the following and many permutations on it:

```<code>try (list_max [])
with
| Failure s -> -1
| _ -> assert (list_max [] = 4);;
</code>```

[Edit: rather than the contrived example above, perhaps one that makes more sense would be:  Suppose I want to unit test this list_max function.  I know I can do

```<code>assert ( (list_max [1;2;3] = 3 );;
</code>```

But how would I test that list_max correctly throws an exception on an empty list?]

答:
You can do the assert in the try expression, as long as it raises an exception that you don't catch. Any other exception, such as Assert_failure in this case, will pass through.

```<code>try assert (list_max [] = 4) with
| Failure s -> -1
</code>```

But assert returns unit so this will be a type error in any case.

An alternative is to use the exception case in pattern matching:

```<code>match list_max [] with
| exception (Failure _) -> -1
| _ -> assert (list_max [] = 4)
</code>```

(This still has a type error)

Finally, you might want to use the option or result type instead of exceptions, since they're much safer. The compiler won't let you just forget about the error conditions then. If list_max had returned an option, this would be:

```<code>match list_max [] with
| None -> -1
| Some _ -> assert (list_max [] = 4)
</code>```

(Still has the type error though)

Body:
Suppose you have a sequence of expressions that potentially raise an exception.  If it does, you want some long process to take place.  If it doesn't you want a different long process to take place.  In imperative languages you can usually do something like

try:
    ...
except:
    ...

but I can't seem to reproduce this in OCaml, because it seems like you can only check a single expression at a time for an exception.  I also don't see how you can use the value, if it exists, or do something else if it doesn't.

For a more concrete, if trivial example:  I have a function list_max that returns the max of a list if it's non-empty and raises an exception if it is empty.  Suppose I have a list and want to assert that its max is 4, but I'm wrong and it's really an empty list.  I can't seem to get the syntax right from explanations that I've found.  I've tried the following and many permutations on it:

try (list_max [])
with
| Failure s -> -1
| _ -> assert (list_max [] = 4);;

[Edit: rather than the contrived example above, perhaps one that makes more sense would be:  Suppose I want to unit test this list_max function.  I know I can do

assert ( (list_max [1;2;3] = 3 );;

But how would I test that list_max correctly throws an exception on an empty list?]

Body:
You can do the assert in the try expression, as long as it raises an exception that you don't catch. Any other exception, such as Assert_failure in this case, will pass through.

try assert (list_max [] = 4) with
| Failure s -> -1

But assert returns unit so this will be a type error in any case.

An alternative is to use the exception case in pattern matching:

match list_max [] with
| exception (Failure _) -> -1
| _ -> assert (list_max [] = 4)

(This still has a type error)

Finally, you might want to use the option or result type instead of exceptions, since they're much safer. The compiler won't let you just forget about the error conditions then. If list_max had returned an option, this would be:

match list_max [] with
| None -> -1
| Some _ -> assert (list_max [] = 4)

(Still has the type error though)


问:
How to expand all the subsections on the sidebar toctree in Sphinx?
I was wondering if there is a way to expand all the subsections under the headers that are included in the index.rst file?

As an example, here is how it is:

```<code>Section 1
Section 2
Section 3
</code>```

And here is how I would like it to be:

```<code>Section 1
  Subsection 1.1
  Subsection 1.2
  Subsection 1.3
Section 2
  Subsection 2.1
  Subsection 2.2
  Subsection 2.3
Section 3
  Subsection 3.1
  Subsection 3.2
  Subsection 3.3
</code>```

If I click on Section 1, it shows what's under that, but if I click on Section 2, contents of section 1 are hidden and only 2 is shown. I would like all 2 sections to be expanded every time I'm on the index page. I've tried adding toctree and maxdepth, nothing works.

答:
If you are using sphinx_rtd_theme, you can change the maximum depth of the sidebar menu in the html page by changing the 'toctree maxdepth' value defined in the file layout.html. This file is usually located in the directory source/_themes/sphinx_rtd_theme. There are several solutions:

The simplest, fastest solution: Show deeper toctree in sidebar

You are using an old version of the theme. Then you can set a new 'maxdepth' value (e.g., 3) in the line that says:

```<code>{% set toctree = toctree(maxdepth=3, collapse=False, includehidden=True) %}
</code>```

You are using a newest version of the theme. Then you may have these lines in the file layout.html:

```<code>{% set global_toc = toctree(maxdepth=theme_navigation_depth|int,
                            collapse=theme_collapse_navigation|tobool,
                            includehidden=theme_includehidden|tobool,
                            titles_only=theme_titles_only|tobool) %}
</code>```

In this case, you may define 'theme_navigation_depth' in theme.conf:

```<code>[options]
theme_navigation_depth = 3
</code>```

Recompile after the change is done... and don't forget to enjoy the Sun!

Body:
I was wondering if there is a way to expand all the subsections under the headers that are included in the index.rst file?

As an example, here is how it is:

Section 1
Section 2
Section 3

And here is how I would like it to be:

Section 1
  Subsection 1.1
  Subsection 1.2
  Subsection 1.3
Section 2
  Subsection 2.1
  Subsection 2.2
  Subsection 2.3
Section 3
  Subsection 3.1
  Subsection 3.2
  Subsection 3.3

If I click on Section 1, it shows what's under that, but if I click on Section 2, contents of section 1 are hidden and only 2 is shown. I would like all 2 sections to be expanded every time I'm on the index page. I've tried adding toctree and maxdepth, nothing works.

Body:
If you are using sphinx_rtd_theme, you can change the maximum depth of the sidebar menu in the html page by changing the 'toctree maxdepth' value defined in the file layout.html. This file is usually located in the directory source/_themes/sphinx_rtd_theme. There are several solutions:

The simplest, fastest solution: Show deeper toctree in sidebar

You are using an old version of the theme. Then you can set a new 'maxdepth' value (e.g., 3) in the line that says:

{% set toctree = toctree(maxdepth=3, collapse=False, includehidden=True) %}

You are using a newest version of the theme. Then you may have these lines in the file layout.html:

{% set global_toc = toctree(maxdepth=theme_navigation_depth|int,
                            collapse=theme_collapse_navigation|tobool,
                            includehidden=theme_includehidden|tobool,
                            titles_only=theme_titles_only|tobool) %}

In this case, you may define 'theme_navigation_depth' in theme.conf:

[options]
theme_navigation_depth = 3

Recompile after the change is done... and don't forget to enjoy the Sun!