问:
C# Class with list and non list items
How would I add data to the below class lists. Both the lists are dynamic and the dailyclockings list can be different for each item of the clockings list.
I'm currently able to add data to each list, clockings and dailyclockings but the data in dailyclockings does not pulls through to clockings[1].dailyclockings[1]. I can only see data in clockings[1].name and dailyclockings[1].clockingdate but if I display clockings[1].dailyclocking[1].clockingdate the value is null.

What I'm try to achieve is the following

```<code> Clockings[1].Department = "Testing"
 Clockings[1].Name = "Fred"
 Clockings[1].DailyClockings[1].ClockingDate = "2017/11/01"
 Clockings[1].DailyClockings[1].InClockingTime = "08:00"
 Clockings[1].DailyClockings[1].OutClockingTime = "14:00"
 Clockings[1].DailyClockings[2].ClockingDate = "2017/11/02"
 Clockings[1].DailyClockings[2].InClockingTime = "08:00"
 Clockings[1].DailyClockings[2].OutClockingTime = "14:00"
 Clockings[1].DailyClockings[3].ClockingDate = "2017/11/03"
 Clockings[1].DailyClockings[3].InClockingTime = "08:00"
 Clockings[1].DailyClockings[3].OutClockingTime = "14:00"
 Clockings[1].DailyClockings[4].ClockingDate = "2017/11/06"
 Clockings[1].DailyClockings[4].InClockingTime = "08:00"
 Clockings[1].DailyClockings[4].OutClockingTime = "14:00"

  public class Clockings
    {

        public string Department { get; set; }
        public string UserName { get; set; }
        public string StartTime { get; set; }
        public int NoofDaysClocked { get; set; }

        public List<DailyClocking> DailyClockings { get; set; }

    }

    public class DailyClocking
    {
        public string InClockingTime { get; set; }
        public string OutClockingTime { get; set; }
        public string ClockingDate { get; set; }
        public string DayofTheWeek { get; set; }
        public string MinInEarly { get; set; }
        public string MinOutEarly { get; set; }
    }

 public List<Clockings> clockingTime()
        {
            List<Clockings> f = new List<Clockings>() ;

            Clockings d = new Clockings();

            DailyClocking d1 = new DailyClocking();
            List<DailyClocking> d2 = new List<DailyClocking>();

            float noofusers =1;
            int col = 0;
            int tmpemp = 0;
            int n =0, x = 0;

            var cmd = db.Database.Connection.CreateCommand();

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "[dbo].LateClocking";

            SqlParameter param = new SqlParameter();
            param.ParameterName = "@StartDate";
            param.Value = 20170901;
            cmd.Parameters.Add(param);

            SqlParameter param1 = new SqlParameter();
            param1.ParameterName = "@EndDate";
            param1.Value = 20170930;
            cmd.Parameters.Add(param1);

            SqlParameter param2 = new SqlParameter();
            param2.ParameterName = "@Branch";
            param2.Value = "";
            cmd.Parameters.Add(param2);

            SqlParameter param3 = new SqlParameter();
            param3.ParameterName = "@department";
            param3.Value = "";
            cmd.Parameters.Add(param3);

            SqlParameter param4 = new SqlParameter();
            param4.ParameterName = "@Nme";
            param4.Value = "Fred Smith";
            cmd.Parameters.Add(param4);

            try
            {
                cmd.Connection.Open();
                var reader = cmd.ExecuteReader();

                if (reader.HasRows)
                {

                    while (reader.Read())
                    {
                        if (tmpemp == int.Parse( reader["mst_sq"].ToString() ) )
                        {}
                        else
                        {
                            if (noofusers >1)
                            {
                                f.Add(d);
                            }
                            col = 0;
                            noofusers = noofusers + 1;
                            tmpemp = int.Parse(reader["mst_sq"].ToString());
                            d.UserName = reader["mst_firstname"].ToString() + " " + reader["mst_lastname"].ToString();
                            d.StartTime = reader["starttime"].ToString();
                            d.Department = reader["dept_name"].ToString();
                        }
                        if (reader["dy"].Equals(System.DBNull.Value))
                        {}
                        else
                        {
                            d1.ClockingDate = reader["dy"].ToString().Substring(0, 4) + reader["dy"].ToString().Substring(5, 2) + reader["dy"].ToString().Substring(8, 2);
                            d1.MinInEarly = reader["mnearly"].ToString();
                            d1.MinInEarly = reader["mnlate"].ToString();
                            d1.InClockingTime = reader["tmeclocked"].ToString().Substring(11, 5);
                            d1.OutClockingTime = reader["earlyclocked"].ToString().Substring(11, 5);
                            d2.Add(d1);
                        }
                        col = col + 1;
                        d.NoofDaysClocked = col;

                    }
                    f.Add(new f.DailyClockings( d2));
                    f.Add(d);
                }

            }
            catch (Exception ex)
            {
                // your handling code here

            }

            return (f);
        }
</code>```

答:
There is a big misunderstanding in your code:

```<code>            if (reader.HasRows)
            {

                while (reader.Read())
                {
                    if (tmpemp == int.Parse( reader["mst_sq"].ToString() ) )
                    {}
                    else
                    {
                        if (noofusers >1)
                        {
                            f.Add(d);
                        }
                        col = 0;
                        noofusers = noofusers + 1;
                        tmpemp = int.Parse(reader["mst_sq"].ToString());
                        d.UserName = reader["mst_firstname"].ToString() + " " + reader["mst_lastname"].ToString();
                        d.StartTime = reader["starttime"].ToString();
                        d.Department = reader["dept_name"].ToString();
                    }
                    if (reader["dy"].Equals(System.DBNull.Value))
                    {}
                    else
                    {
                        d1.ClockingDate = reader["dy"].ToString().Substring(0, 4) + reader["dy"].ToString().Substring(5, 2) + reader["dy"].ToString().Substring(8, 2);
                        d1.MinInEarly = reader["mnearly"].ToString();
                        d1.MinInEarly = reader["mnlate"].ToString();
                        d1.InClockingTime = reader["tmeclocked"].ToString().Substring(11, 5);
                        d1.OutClockingTime = reader["earlyclocked"].ToString().Substring(11, 5);
                        d2.Add(d1);
                    }
                    col = col + 1;
                    d.NoofDaysClocked = col;

                }
                f.Add(new f.DailyClockings( d2));
                f.Add(d);
</code>```

1) please add logs, or exception handling.
at:

```<code>   if (tmpemp == int.Parse( reader["mst_sq"].ToString() ) )
                    {}
</code>```

Or at:

```<code>     if (reader["dy"].Equals(System.DBNull.Value))
            {}
</code>```

There might be an error or db Null, so one of your lists won't get populated and you won't even know about it, which will result in null values.

2) Do not initialize objects inside your list:

```<code>f.Add(new f.DailyClockings( d2));
</code>```

You might be loosing your data in the process of instantiating a new object.

Use it like this:

```<code>f.DailyClockings dailyClockingsList = new List<DailyClockings>

  dailyClockingsList.Add(d2);
                    f.Add(d);
</code>```

Title: C# Class with list and non list items

Body:
How would I add data to the below class lists. Both the lists are dynamic and the dailyclockings list can be different for each item of the clockings list.
I'm currently able to add data to each list, clockings and dailyclockings but the data in dailyclockings does not pulls through to clockings[1].dailyclockings[1]. I can only see data in clockings[1].name and dailyclockings[1].clockingdate but if I display clockings[1].dailyclocking[1].clockingdate the value is null.

What I'm try to achieve is the following

 Clockings[1].Department = "Testing"
 Clockings[1].Name = "Fred"
 Clockings[1].DailyClockings[1].ClockingDate = "2017/11/01"
 Clockings[1].DailyClockings[1].InClockingTime = "08:00"
 Clockings[1].DailyClockings[1].OutClockingTime = "14:00"
 Clockings[1].DailyClockings[2].ClockingDate = "2017/11/02"
 Clockings[1].DailyClockings[2].InClockingTime = "08:00"
 Clockings[1].DailyClockings[2].OutClockingTime = "14:00"
 Clockings[1].DailyClockings[3].ClockingDate = "2017/11/03"
 Clockings[1].DailyClockings[3].InClockingTime = "08:00"
 Clockings[1].DailyClockings[3].OutClockingTime = "14:00"
 Clockings[1].DailyClockings[4].ClockingDate = "2017/11/06"
 Clockings[1].DailyClockings[4].InClockingTime = "08:00"
 Clockings[1].DailyClockings[4].OutClockingTime = "14:00"

  public class Clockings
    {

        public string Department { get; set; }
        public string UserName { get; set; }
        public string StartTime { get; set; }
        public int NoofDaysClocked { get; set; }

        public List<DailyClocking> DailyClockings { get; set; }

    }

    public class DailyClocking
    {
        public string InClockingTime { get; set; }
        public string OutClockingTime { get; set; }
        public string ClockingDate { get; set; }
        public string DayofTheWeek { get; set; }
        public string MinInEarly { get; set; }
        public string MinOutEarly { get; set; }
    }

 public List<Clockings> clockingTime()
        {
            List<Clockings> f = new List<Clockings>() ;

            Clockings d = new Clockings();

            DailyClocking d1 = new DailyClocking();
            List<DailyClocking> d2 = new List<DailyClocking>();

            float noofusers =1;
            int col = 0;
            int tmpemp = 0;
            int n =0, x = 0;

            var cmd = db.Database.Connection.CreateCommand();

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "[dbo].LateClocking";

            SqlParameter param = new SqlParameter();
            param.ParameterName = "@StartDate";
            param.Value = 20170901;
            cmd.Parameters.Add(param);

            SqlParameter param1 = new SqlParameter();
            param1.ParameterName = "@EndDate";
            param1.Value = 20170930;
            cmd.Parameters.Add(param1);

            SqlParameter param2 = new SqlParameter();
            param2.ParameterName = "@Branch";
            param2.Value = "";
            cmd.Parameters.Add(param2);

            SqlParameter param3 = new SqlParameter();
            param3.ParameterName = "@department";
            param3.Value = "";
            cmd.Parameters.Add(param3);

            SqlParameter param4 = new SqlParameter();
            param4.ParameterName = "@Nme";
            param4.Value = "Fred Smith";
            cmd.Parameters.Add(param4);

            try
            {
                cmd.Connection.Open();
                var reader = cmd.ExecuteReader();

                if (reader.HasRows)
                {

                    while (reader.Read())
                    {
                        if (tmpemp == int.Parse( reader["mst_sq"].ToString() ) )
                        {}
                        else
                        {
                            if (noofusers >1)
                            {
                                f.Add(d);
                            }
                            col = 0;
                            noofusers = noofusers + 1;
                            tmpemp = int.Parse(reader["mst_sq"].ToString());
                            d.UserName = reader["mst_firstname"].ToString() + " " + reader["mst_lastname"].ToString();
                            d.StartTime = reader["starttime"].ToString();
                            d.Department = reader["dept_name"].ToString();
                        }
                        if (reader["dy"].Equals(System.DBNull.Value))
                        {}
                        else
                        {
                            d1.ClockingDate = reader["dy"].ToString().Substring(0, 4) + reader["dy"].ToString().Substring(5, 2) + reader["dy"].ToString().Substring(8, 2);
                            d1.MinInEarly = reader["mnearly"].ToString();
                            d1.MinInEarly = reader["mnlate"].ToString();
                            d1.InClockingTime = reader["tmeclocked"].ToString().Substring(11, 5);
                            d1.OutClockingTime = reader["earlyclocked"].ToString().Substring(11, 5);
                            d2.Add(d1);
                        }
                        col = col + 1;
                        d.NoofDaysClocked = col;

                    }
                    f.Add(new f.DailyClockings( d2));
                    f.Add(d);
                }

            }
            catch (Exception ex)
            {
                // your handling code here

            }

            return (f);
        }

Body:
There is a big misunderstanding in your code:

            if (reader.HasRows)
            {

                while (reader.Read())
                {
                    if (tmpemp == int.Parse( reader["mst_sq"].ToString() ) )
                    {}
                    else
                    {
                        if (noofusers >1)
                        {
                            f.Add(d);
                        }
                        col = 0;
                        noofusers = noofusers + 1;
                        tmpemp = int.Parse(reader["mst_sq"].ToString());
                        d.UserName = reader["mst_firstname"].ToString() + " " + reader["mst_lastname"].ToString();
                        d.StartTime = reader["starttime"].ToString();
                        d.Department = reader["dept_name"].ToString();
                    }
                    if (reader["dy"].Equals(System.DBNull.Value))
                    {}
                    else
                    {
                        d1.ClockingDate = reader["dy"].ToString().Substring(0, 4) + reader["dy"].ToString().Substring(5, 2) + reader["dy"].ToString().Substring(8, 2);
                        d1.MinInEarly = reader["mnearly"].ToString();
                        d1.MinInEarly = reader["mnlate"].ToString();
                        d1.InClockingTime = reader["tmeclocked"].ToString().Substring(11, 5);
                        d1.OutClockingTime = reader["earlyclocked"].ToString().Substring(11, 5);
                        d2.Add(d1);
                    }
                    col = col + 1;
                    d.NoofDaysClocked = col;

                }
                f.Add(new f.DailyClockings( d2));
                f.Add(d);

1) please add logs, or exception handling.
at:

   if (tmpemp == int.Parse( reader["mst_sq"].ToString() ) )
                    {}

Or at:

     if (reader["dy"].Equals(System.DBNull.Value))
            {}

There might be an error or db Null, so one of your lists won't get populated and you won't even know about it, which will result in null values.

2) Do not initialize objects inside your list:

f.Add(new f.DailyClockings( d2));

You might be loosing your data in the process of instantiating a new object.

Use it like this:

f.DailyClockings dailyClockingsList = new List<DailyClockings>

  dailyClockingsList.Add(d2);
                    f.Add(d);


来源: stackexchange

问:
<activity> vs. <activity/>. What is the difference?
When looking at most sites (including SO), most of them use:

```<code><activity android:name=".MainActivity" />
</code>```

insted of

```<code> <activity android:name=".Complaints"> </activity>
</code>```

What are the main differences between the two, if any?

Are there valid reasons to use one instead of the other?

Are there valid reasons to use combine them?
Does using  come with compatibility issues, seeing it is not very widely used?

答:
What are the main differences between the two, if any?

No there is no difference between both of them both are valid

1. The XML Schema of the AndroidManifest file allows empty-elements. An element with no content is said to be empty. The representation of an empty element is either a start-tag immediately followed by an end-tag

<activity android:name=".MainActivity" />

2. when you need to supports nested inner tags in your <activity> tag than you should use  for example

```<code><activity android:name=".Complaints">
        <intent-filter>

        </intent-filter>
   </activity>`
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When looking at most sites (including SO), most of them use:

<activity android:name=".MainActivity" />

insted of

 <activity android:name=".Complaints"> </activity>

What are the main differences between the two, if any?

Are there valid reasons to use one instead of the other?

Are there valid reasons to use combine them?
Does using  come with compatibility issues, seeing it is not very widely used?

Body:
What are the main differences between the two, if any?

No there is no difference between both of them both are valid

1. The XML Schema of the AndroidManifest file allows empty-elements. An element with no content is said to be empty. The representation of an empty element is either a start-tag immediately followed by an end-tag

<activity android:name=".MainActivity" />

2. when you need to supports nested inner tags in your <activity> tag than you should use  for example

<activity android:name=".Complaints">
        <intent-filter>

        </intent-filter>
   </activity>`


问:
jQuery click hide all modal
I have a few buttons that open modals by click and close them by the second click on the very same button. I need to achieve a behaviour when I can click on that button OR anywhere outside of the modal window and that windows will close.
Also, if I click another button, if any modal is open, it should close and new modal should appear instead.

This is what I have so far (I need to keep those functions separated due to there will be additional logic for each of them):

```<code><div class="container">
  <div class="box red"></div>
  <div class="box green"></div>
  <div class="box blue"></div>
  <div class="modal red"></div>
  <div class="modal green"></div>
  <div class="modal blue"></div>
</div>

<script>
// red
function redBoxShow() {
    $('.modal.red').animate({opacity: 1, top: '40'}, 400);
    $(this).one("click", redBoxHide);
}
function redBoxHide() {
    $('.modal.red').animate({opacity: 0, top: '-200px'}, 400);
    $(this).one("click", redBoxShow);
}
// green
function greenBoxShow() {
  $('.modal.green').animate({opacity: 1, top: '40'}, 400);
  $(this).one("click", greenBoxHide);
}
function greenBoxHide() {
  $('.modal.green').animate({opacity: 0, top: '-200px'}, 400);
  $(this).one("click", greenBoxShow);
}
// blue
function blueBoxShow() {
  $('.modal.blue').animate({opacity: 1, top: '40'}, 400);
  $(this).one("click", blueBoxHide);
}
function blueBoxHide() {
  $('.modal.blue').animate({opacity: 0, top: '-200px'}, 400);
  $(this).one("click", blueBoxShow);
}
$(".box.red").one("click", redBoxShow);
$(".box.green").one("click", greenBoxShow);
$(".box.blue").one("click", blueBoxShow);
</script>
</code>```

https://jsfiddle.net/8wfgbpau/9/

答:
Updated fiddle including: animation done by css, handling clicks anywhere and not closing when open modal clicked.

$(".box").on("click", function(e){
  var $this = $(this);
  var $modals = $(".container .modal");
  var $modal;
  if ($this.hasClass("red")) {
   $modal = $modals.filter(".red");
  } else if ($this.hasClass("green")) {
   $modal = $modals.filter(".green");
  }else if ($this.hasClass("blue")) {
   $modal = $modals.filter(".blue");
  } else {
   return;
  }

  if (!$modal.hasClass("open")) {
   $modals.removeClass("open");
   $modal.addClass("open");
    e.stopPropagation();
 }
});

$(document).on("click", ".container .modal.open", function(e){
  e.stopPropagation();
});

$(window).on("click", function(e){
  $(".container .modal.open").removeClass("open");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  width: 300px;
  text-align: center;
  position: relative;
}
.red{background:red;}
.green{background:green;}
.blue{background:blue;}
.modal {
  position: absolute;
  opacity: 0;
  top: -200px;
  transition: opacity linear 400ms, top linear 400ms;

}
.box {
  width: 30px;
  height: 30px;
  display: inline-block;
  margin-left: 10px;
}
.box:hover {
  cursor:pointer;
  opacity:0.8;
}
.modal {
  width: 150px;
  height: 150px;
}
.modal.red {
  left: 0;
}
.modal.green {
  left: calc(50% - 75px);
}
.modal.blue {
  right: 0;
}

.modal.open {
  opacity: 1;
  top: 40px;
}</code>```

```

Title: jQuery click hide all modal

Body:
I have a few buttons that open modals by click and close them by the second click on the very same button. I need to achieve a behaviour when I can click on that button OR anywhere outside of the modal window and that windows will close.
Also, if I click another button, if any modal is open, it should close and new modal should appear instead.

This is what I have so far (I need to keep those functions separated due to there will be additional logic for each of them):

https://jsfiddle.net/8wfgbpau/9/

Body:
Updated fiddle including: animation done by css, handling clicks anywhere and not closing when open modal clicked.

$(".box").on("click", function(e){
  var $this = $(this);
  var $modals = $(".container .modal");
  var $modal;
  if ($this.hasClass("red")) {
   $modal = $modals.filter(".red");
  } else if ($this.hasClass("green")) {
   $modal = $modals.filter(".green");
  }else if ($this.hasClass("blue")) {
   $modal = $modals.filter(".blue");
  } else {
   return;
  }

  if (!$modal.hasClass("open")) {
   $modals.removeClass("open");
   $modal.addClass("open");
    e.stopPropagation();
 }
});

$(document).on("click", ".container .modal.open", function(e){
  e.stopPropagation();
});

$(window).on("click", function(e){
  $(".container .modal.open").removeClass("open");
});

.container {
  width: 300px;
  text-align: center;
  position: relative;
}
.red{background:red;}
.green{background:green;}
.blue{background:blue;}
.modal {
  position: absolute;
  opacity: 0;
  top: -200px;
  transition: opacity linear 400ms, top linear 400ms;

}
.box {
  width: 30px;
  height: 30px;
  display: inline-block;
  margin-left: 10px;
}
.box:hover {
  cursor:pointer;
  opacity:0.8;
}
.modal {
  width: 150px;
  height: 150px;
}
.modal.red {
  left: 0;
}
.modal.green {
  left: calc(50% - 75px);
}
.modal.blue {
  right: 0;
}

.modal.open {
  opacity: 1;
  top: 40px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
  <div class="box red"></div>
  <div class="box green"></div>
  <div class="box blue"></div>
  <div class="modal red"></div>
  <div class="modal green"></div>
  <div class="modal blue"></div>
</div>


问:
SAP: minimal deployment for interacting with SharePoint through Duet Enterprise
I’m ramping-up on Duet, went through bunch of docs, so I’m ready for some fun. I have my WS 2008 x64 virtual machine ready with SharePoint 2010 on it and ready to install Duet Enterprise.

How should I proceed with the SAP side of the equation? As I’m not familiar with it, is there a download + guide for getting the minimal required SAP installation up & running to try Duet?

Thanks!

答:
I'm not familiar with Duet, but you can get a trial edition of SAP from here. It's called developer edition and it's a stripped down version of SAP system mainly designed for developers to play around. It has the ABAP stack (ABAP is a SAP owned programming language) and a dbms (I cannot remember which one). I don't know what are the minimum requirements to work with Duet, like any extra modules, so you'll have to find this out. </p>

<p>Bear in mind that it's not a simple installation. It's very demanding in hard drive space and it will work better on Windows XP, without anything else installed, as it tends to conflict (especially with other dbms'). Maybe a virtual machine is a solution. </p>

ContentLicense: CC BY-SA 2.5

Body:
I'm not familiar with Duet, but you can get a trial edition of SAP from here. It's called developer edition and it's a stripped down version of SAP system mainly designed for developers to play around. It has the ABAP stack (ABAP is a SAP owned programming language) and a dbms (I cannot remember which one). I don't know what are the minimum requirements to work with Duet, like any extra modules, so you'll have to find this out.

Bear in mind that it's not a simple installation. It's very demanding in hard drive space and it will work better on Windows XP, without anything else installed, as it tends to conflict (especially with other dbms'). Maybe a virtual machine is a solution.


问:
Injecting new field to riemann event
I'm probably not understanding some key concepts in riemann/clojure.
I'm trying to parse field :service from event which is in format "aaa:1234.bbbb.cccc.ddddd", and add new field pid to the event using function "with".
Anybody can explain to me why this code in riemann.config is throwing exception:

```<code>...
(let [index (default :ttl 300 (update-index (index)))]

 ; Inbound events will be passed to these streams:
 (streams
 index
 (where (service #"(\w+):(\d+)\.(\w+)\.(\w+)\.(\w+)")
   (with :pid (str/replace service #"(\w+):(\d+)\.(\w+)\.(\w+)\.(\w+)" "$2")
)
)
...

user=> (riemann.bin/reload!)
#error {
 :cause "Unable to resolve symbol: service in this context"
 :via
 [{:type clojure.lang.Compiler$CompilerException
 :message "java.lang.RuntimeException: Unable to resolve symbol: service in this context, compiling:(/etc/riemann/riemann.config:73:19)"
</code>```

答:
I guess (where (service ,,,)) is just syntactic sugar by the where macro for (where* (fn [event] (let [service (:service event)] ,,,))), which is why you can't use service in the body of where: it is not a defined name there.

Looking at the documentation for with, it seems to me you should use smap:

```<code>(where (service #"(\w+):(\d+)\.(\w+)\.(\w+)\.(\w+)")
   (smap (fn [e] (assoc e :pid (str/replace (:service e) #"(\w+):(\d+)\.(\w+)\.(\w+)\.(\w+)" "$2")))))
</code>```

Title: Injecting new field to riemann event

Body:
I'm probably not understanding some key concepts in riemann/clojure.
I'm trying to parse field :service from event which is in format "aaa:1234.bbbb.cccc.ddddd", and add new field pid to the event using function "with".
Anybody can explain to me why this code in riemann.config is throwing exception:

...
(let [index (default :ttl 300 (update-index (index)))]

 ; Inbound events will be passed to these streams:
 (streams
 index
 (where (service #"(\w+):(\d+)\.(\w+)\.(\w+)\.(\w+)")
   (with :pid (str/replace service #"(\w+):(\d+)\.(\w+)\.(\w+)\.(\w+)" "$2")
)
)
...

user=> (riemann.bin/reload!)
#error {
 :cause "Unable to resolve symbol: service in this context"
 :via
 [{:type clojure.lang.Compiler$CompilerException
 :message "java.lang.RuntimeException: Unable to resolve symbol: service in this context, compiling:(/etc/riemann/riemann.config:73:19)"

Body:
I guess (where (service ,,,)) is just syntactic sugar by the where macro for (where* (fn [event] (let [service (:service event)] ,,,))), which is why you can't use service in the body of where: it is not a defined name there.

Looking at the documentation for with, it seems to me you should use smap:

(where (service #"(\w+):(\d+)\.(\w+)\.(\w+)\.(\w+)")
   (smap (fn [e] (assoc e :pid (str/replace (:service e) #"(\w+):(\d+)\.(\w+)\.(\w+)\.(\w+)" "$2")))))


问:
My app crashes fatal exception Unable to add window
I am very new to Android development and I have created this quiz game. My problem is the app randomly crashes after a few minutes it has been opened. The crashes are at random times so I can't figure out what causes the crashing. Below is the logcat error code whenever the app crashes

```<code>11-16 18:39:10.573 19023-19023/com.noxeternal.quizgame E/AndroidRuntime: FATAL EXCEPTION: main
                                                                     Process: com.noxeternal.quizgame, PID: 19023
                                                                     android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@d70d3e4 is not valid; is your activity running?
                                                                         at android.view.ViewRootImpl.setView(ViewRootImpl.java:679)
                                                                         at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
                                                                         at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
                                                                         at android.app.Dialog.show(Dialog.java:322)
                                                                         at com.noxeternal.quizgame.MainActivity.gameOver(MainActivity.java:287)
                                                                         at com.noxeternal.quizgame.MainActivity.access$300(MainActivity.java:19)
                                                                         at com.noxeternal.quizgame.MainActivity$9.onFinish(MainActivity.java:307)
                                                                         at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                         at android.os.Looper.loop(Looper.java:154)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:6176)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
</code>```

Here are the codes mentioned at the logcat.

```<code>private void gameOver(){
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
    alertDialogBuilder
            .setMessage("Game over! Your score is " + mScore + " points.")
            .setCancelable(false)
            .setPositiveButton("NEW GAME",
                    new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i){
                            finish();
                            startActivity(new Intent(getApplicationContext(),MainActivity.class));
                        }
                    })
            .setNegativeButton("Exit",
                    new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i){
                            Intent intent = new Intent(MainActivity.this, MainMenu.class);
                            startActivity(intent);
                            finish();
                        }
                    });
    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
}

private void startTimer(){
    long millisInFuture = 60000;
    long countDownInterval = 1000;

    timer.setText("Time remaining: " + timer);
    countDownTimer = new CountDownTimer(millisInFuture, countDownInterval) {
        @Override
        public void onTick(long millisUntilFinished) {
            if(isPaused){
                cancel();
            } else {
                timer.setText("Time remaining: " + millisUntilFinished / 1000);
                remainingTime = millisUntilFinished;
            }
        }
        @Override
        public void onFinish() {
            gameOver();
        }
    };
    countDownTimer.start();
}
</code>```

Thank you!

答:
when you look at the error, you may find some "links" from the lines that are giving error, you can click and find out. In your case, the errors are in:

MainActivity.class on line 287: MainActivity.java:287

MainActivity.class on line 19: MainActivity.java:19

MainActivity.class on line 307: MainActivity.java:307

I think this may help to identify the error.

Body:
I am very new to Android development and I have created this quiz game. My problem is the app randomly crashes after a few minutes it has been opened. The crashes are at random times so I can't figure out what causes the crashing. Below is the logcat error code whenever the app crashes

11-16 18:39:10.573 19023-19023/com.noxeternal.quizgame E/AndroidRuntime: FATAL EXCEPTION: main
                                                                     Process: com.noxeternal.quizgame, PID: 19023
                                                                     android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@d70d3e4 is not valid; is your activity running?
                                                                         at android.view.ViewRootImpl.setView(ViewRootImpl.java:679)
                                                                         at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
                                                                         at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
                                                                         at android.app.Dialog.show(Dialog.java:322)
                                                                         at com.noxeternal.quizgame.MainActivity.gameOver(MainActivity.java:287)
                                                                         at com.noxeternal.quizgame.MainActivity.access$300(MainActivity.java:19)
                                                                         at com.noxeternal.quizgame.MainActivity$9.onFinish(MainActivity.java:307)
                                                                         at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                         at android.os.Looper.loop(Looper.java:154)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:6176)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)

Here are the codes mentioned at the logcat.

private void gameOver(){
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
    alertDialogBuilder
            .setMessage("Game over! Your score is " + mScore + " points.")
            .setCancelable(false)
            .setPositiveButton("NEW GAME",
                    new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i){
                            finish();
                            startActivity(new Intent(getApplicationContext(),MainActivity.class));
                        }
                    })
            .setNegativeButton("Exit",
                    new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i){
                            Intent intent = new Intent(MainActivity.this, MainMenu.class);
                            startActivity(intent);
                            finish();
                        }
                    });
    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
}

private void startTimer(){
    long millisInFuture = 60000;
    long countDownInterval = 1000;

    timer.setText("Time remaining: " + timer);
    countDownTimer = new CountDownTimer(millisInFuture, countDownInterval) {
        @Override
        public void onTick(long millisUntilFinished) {
            if(isPaused){
                cancel();
            } else {
                timer.setText("Time remaining: " + millisUntilFinished / 1000);
                remainingTime = millisUntilFinished;
            }
        }
        @Override
        public void onFinish() {
            gameOver();
        }
    };
    countDownTimer.start();
}

Thank you!


问:
Can opengl calls run without a GPU present?
I know that opengl is a library that allows certain tasks/calls (like shading) to be executed on the GPU for faster computation (hardware accelerated). I've been reading on the internet about it and am wondering if calls to opengl will run without a GPU present. For example, someone on this forum (https://www.gamedev.net/forums/topic/638883-will-opengl-3d-games-run-in-a-pc-without-a-dedicated-video-card/) mentioned that it can run as a software emulation. Can anyone speak to this?</p>

答:
Strictly speaking OpenGL is not a library but only a programming interface (API). The specific details of how this API is implemented on a particular machine are left open and are at the disposal of the system implementors. It might be a software rasterizer, it might be an interface to dedicated hardware.

OpenGL has been part of the ABI (i.e. the set of things that applications can be sure of to be available on a system) of Windows, LSB4/Desktop (Linux Standard Base / Desktop requirements) and MacOS. As such the system must make sure that there's always a some way to have at least a minimal set of OpenGL functionality (we're speaking OpenGL-1.x here), even if there's not hardware acceleration for it.

It should be noted that all these ABIs are writting against the assumption, that it is used to render things to a display device:

The Windows fallback software rasterizer implementation (which is horribly slow BTW) does allow rendering to GDI bitmaps, but does not have support for PBuffers; and don't even think about framebuffer objects.

The Mesa software rasterizer is pretty much OpenGL-3.x feature complete.


问:
Data providers issue in phpunit
This is my data provider function:

```<code>public function addDataProvider() {
    return [
        [
            [
                'currency' => 'eur',
                'amount' => 800,
            ],
            [
                'currency' => '12312k',
                'amount' => 1201,
            ],
            [
                'currency' => 'DKK',
                'amount' => 1200.01
            ],
            [
                'currency' => 'SEK  ',
                'amount' => 1200.01
            ]
        ],
    ];
}
</code>```

This is my test function:

```<code>/**
 * Test case
 * @covers AmountPerCustomer::checkAmounts()
 * @dataProvider addDataProvider
 */
public function testCheckAmountUsingCurrency($query)
{
        ....
        try {
            $ordersPerCustomer->checkAmounts($query['amount'], $query['currency'], $dateInterval);
            $this->fail("Expected Exception has not been raised.");
        }catch (\Exception $error) {
            $this->assertEquals($error->getMessage(), "Total order amount event given parameters exceed sum {$query['amount']} since {$dateInterval->format('H:i d-m-Y')} from source {$source}");
        }
}
</code>```

I am getting this success mesage: OK (1 test, 1 assertion) , My question why I have only one assertion. I have multiple array values in my provider . What am I doing wrong ?

Thank you!

答:
As @localheinz suggested in the comments, it is a depth of array issue. This is how my array should look like:</p>

```<code>public function addDataProvider() {
    return [
        [
            [
                'currency' => 'eur',
                'amount' => 800,
            ]
        ],
        [
            [
                'currency' => 'dkk',
                'amount' => 1201,
            ],
        ],
        [
            [
                'currency' => 'GBP',
                'amount' => 1201,
            ],
        ],
        [
            [
                'currency' => 'sek',
                'amount' => 1200.01,
            ],
        ],
    ];
}
</code>```

Title: Data providers issue in phpunit

Body:
This is my data provider function:

public function addDataProvider() {
    return [
        [
            [
                'currency' => 'eur',
                'amount' => 800,
            ],
            [
                'currency' => '12312k',
                'amount' => 1201,
            ],
            [
                'currency' => 'DKK',
                'amount' => 1200.01
            ],
            [
                'currency' => 'SEK  ',
                'amount' => 1200.01
            ]
        ],
    ];
}

This is my test function:

/**
 * Test case
 * @covers AmountPerCustomer::checkAmounts()
 * @dataProvider addDataProvider
 */
public function testCheckAmountUsingCurrency($query)
{
        ....
        try {
            $ordersPerCustomer->checkAmounts($query['amount'], $query['currency'], $dateInterval);
            $this->fail("Expected Exception has not been raised.");
        }catch (\Exception $error) {
            $this->assertEquals($error->getMessage(), "Total order amount event given parameters exceed sum {$query['amount']} since {$dateInterval->format('H:i d-m-Y')} from source {$source}");
        }
}

I am getting this success mesage: OK (1 test, 1 assertion) , My question why I have only one assertion. I have multiple array values in my provider . What am I doing wrong ?

Thank you!

Body:
As @localheinz suggested in the comments, it is a depth of array issue. This is how my array should look like:

public function addDataProvider() {
    return [
        [
            [
                'currency' => 'eur',
                'amount' => 800,
            ]
        ],
        [
            [
                'currency' => 'dkk',
                'amount' => 1201,
            ],
        ],
        [
            [
                'currency' => 'GBP',
                'amount' => 1201,
            ],
        ],
        [
            [
                'currency' => 'sek',
                'amount' => 1200.01,
            ],
        ],
    ];
}


问:
HTML for list with dashes and custom font colour
I am finalising a Wordpress website, but my last challenge is to create a bullet list with dashes instead of dots - the dashes must also be in white to match the font colour.

I've tried a few answers here but nothing seems to work right!

Text and dashes must be white (as it's on a blue background)

– sustainable growth,

– increase profits,

– expand market share and

– improve efficiency

答:
If you are using UL -> LI, then you can follow these steps:

1) Draw the hyphen in paint.
2) Save it as a png
3) In css, for your UL, you can apply this style:

```<code>ul {
  list-style-image: url('hyphen.png');
}
</code>```

Hope this helps :)

Body:
If you are using UL -> LI, then you can follow these steps:

1) Draw the hyphen in paint.
2) Save it as a png
3) In css, for your UL, you can apply this style:

ul {
  list-style-image: url('hyphen.png');
}

Hope this helps :)


问:
Using regex extract a particular text from a paragraph
I have used the below to extract a string from a paragraph.

```<code>data = '''actions/steps to (re-) produce the problem:
1) Media--> Music collectio--> on right side--> click on Add Favourite icon--> on clicking Add from Favourite icon--> (Delete from favourite ) will display--> again click on Delete the favourite

expected result/behaviour:
it should display the track as well

observed result/behavior:
1st track list will display then
2nd list of songs will display
3rd no records will display
this behaviour will appear again and again

possible impact:
this can be an issue while driving

actions/steps to recover from error:
software version tested (including supplied software or CAF version if relevant):

MGU :- 17w.25.4-2'''

observed=[]

for i in data["Error Description"]:
    if len(re.findall(r'(Observed result\/behavior:|observed result\/behavior:)([^(]*)Possible impact:', i))==1:
        observed.append((re.findall(r'(Observed result\/behavior:|observed result\/behavior:)([^(]*)Possible impact:', i))[0][1])
    else:
        observed.append(" ".join((re.findall(r'(Observed result\/behavior:|observed result\/behavior:)([^(]*)Possible impact:', i))))
</code>```

OUTPUT :

It shows nothing as the "observed:" has 4 lines. If it generally has one line and the immediate preceding is "possible impact:" then it displays the output.

I need my output though if the observed has n no of lines

Please help.

答:
This should work on the assumption that observed result/behavior: will have one blank line before the next paragraph:

```<code>begin = data.index('observed result/behavior:')
end = data[begin:].index('\n\n')
output = data[begin:(begin+end)]

print(output)

observed result/behavior:
1st track list will display then
2nd list of songs will display
3rd no records will display
this behaviour will appear again and again
</code>```

Body:
I have used the below to extract a string from a paragraph.

data = '''actions/steps to (re-) produce the problem:
1) Media--> Music collectio--> on right side--> click on Add Favourite icon--> on clicking Add from Favourite icon--> (Delete from favourite ) will display--> again click on Delete the favourite

expected result/behaviour:
it should display the track as well

observed result/behavior:
1st track list will display then
2nd list of songs will display
3rd no records will display
this behaviour will appear again and again

possible impact:
this can be an issue while driving

actions/steps to recover from error:
software version tested (including supplied software or CAF version if relevant):

MGU :- 17w.25.4-2'''

observed=[]

for i in data["Error Description"]:
    if len(re.findall(r'(Observed result\/behavior:|observed result\/behavior:)([^(]*)Possible impact:', i))==1:
        observed.append((re.findall(r'(Observed result\/behavior:|observed result\/behavior:)([^(]*)Possible impact:', i))[0][1])
    else:
        observed.append(" ".join((re.findall(r'(Observed result\/behavior:|observed result\/behavior:)([^(]*)Possible impact:', i))))

OUTPUT :

It shows nothing as the "observed:" has 4 lines. If it generally has one line and the immediate preceding is "possible impact:" then it displays the output.

I need my output though if the observed has n no of lines

Please help.

Body:
This should work on the assumption that observed result/behavior: will have one blank line before the next paragraph:

begin = data.index('observed result/behavior:')
end = data[begin:].index('\n\n')
output = data[begin:(begin+end)]

print(output)

observed result/behavior:
1st track list will display then
2nd list of songs will display
3rd no records will display
this behaviour will appear again and again


问:
make delay after each() function in jQuery
I want to animate each .dot after a 3 seconds delay after previous .dot
Here is the code I used. But it doesn't work.

```<code>var time = 3000;

$(".dot").each(function() {
  setTimeout(function() {
    $(this).addClass("animate");
    $(this).find(".num").addClass("animate");
  }, time)
  time += 3000;
});
</code>```

答:
this doesn't refers to element in setTimeout(), hence its not working.

You can pass parameters to the function

```<code>var time = 3000;
$(".dot").each(function (i) {
    setTimeout(function (self) {
        self.addClass("animate");
        self.find(".num").addClass("animate");
    }, (i + 1) * time, $(this));
});
</code>```

Body:
I want to animate each .dot after a 3 seconds delay after previous .dot
Here is the code I used. But it doesn't work.

var time = 3000;

$(".dot").each(function() {
  setTimeout(function() {
    $(this).addClass("animate");
    $(this).find(".num").addClass("animate");
  }, time)
  time += 3000;
});

Body:
this doesn't refers to element in setTimeout(), hence its not working.

You can pass parameters to the function

var time = 3000;
$(".dot").each(function (i) {
    setTimeout(function (self) {
        self.addClass("animate");
        self.find(".num").addClass("animate");
    }, (i + 1) * time, $(this));
});


问:
Firebase Functions returns and promises do not exit the function
I am still a beginner in the Firebase world and I have been trying to figure out what the problem is with the below code but I failed in all possible ways.

The code is supposed to retrieve the uid from the user profile in the database, then use it to update the authentication profile, then again to update the database profile if the authentication profile update was successful.

In index.js I have defined an exported function to deal with POSTed params from HTML forms. The code below defines the handler function in another module file:

```<code> exports.auUpdateUserByEmail = (req, res) => {
  // This handler function will retrieve the POSTed params of user profile
  // and will attempt to update the existing user authentication as well as
  // the database profiles.
  //
  // This function accepts the following params:
  // 1. User email   // 2. Phone number   // 3. password   // 4. Display name
  // 5. Photo url   // 6. Disabled Flag
  //

  var db = admin.firestore();

  var uEmail = req.body.userEmail;
  var dName = req.body.displayName;
  var userId = "";

  var newuser = {
    displayName: dName
  }

  console.log("Email passed: " + uEmail);

  // Fetch the user UID by user email...
  res.write('User UID: ' + userId);
  console.log('User UID: ' + userId);

  // attempt to update the user authentication profile...
  return db.collection('Users').where('email', '==', email).get()
  .then(snapshot => {
    snapshot.forEach(doc => {
        var d = doc.data();
        console.log("doc.id: " + doc.id + " - d.email: " + d.email);
        if(d.email == email)
        {
          userId = d.uid;
        }
    });

    return admin.auth().updateUser(userId, newuser);
  }).then(function(userRecord) {
    // The updating was successful... Attempt to update User Details in
    // database User Profile...
    console.log("User Updated Successfully. UID: " + userRecord.uid);
    retUid = userRecord.uid;

    // Create a reference to the Users Database...
    var docRef = db.collection('Users');

    // Update the user profile document.
    return docRef.doc(userRecord.uid).update(newuser);
  }).then(result => {
    // everything went fine... return User UID as a successful result...
    res.write(userId);

    return res.end();

  }).catch(function(error) {
    console.log("doc.update - Error updating user profile in database:", error);
    return res.end();

  });
}
</code>```

In index.js, I have the following exports definition:

```<code>var appAuth = express();
//Here we are configuring express to use body-parser as middle-ware.
appAuth.use(bodyParser.urlencoded({ extended: false }));
appAuth.use(bodyParser.json());

appAuth.post('/updateUserByEmail', authusers.auUpdateUserByEmail);

exports.usersAuthFunctions = functions.https.onRequest(appAuth);
</code>```

I have to say that I got it to work fine to get the uid, update the auth profile, and then update database profile, but it keeps on waiting for the function return.

Appreciate your valuable help. Thanks.

I have updated the code as below and it does the jobs but returns a blank page as the HTTPS exits before the promises are complete which fires "Error: write after end" error.

```<code>var fetch_uid = db.collection('Users').where('email', '==', uEmail).get()
  .then(snapshot => {
    // var userId = snapshot.data.uid;

    snapshot.forEach(doc => {
        var d = doc.data();
        console.log("doc.id: " + doc.id + " - d.email: " + d.email);
        if(d.email == uEmail)
        {
          userId = d.uid;

          res.write('User UID: ' + userId);
          console.log('User UID: ' + userId);

        }
    });

    return admin.auth().updateUser(userId, newuser);
  }).then(function(userRecord) {
    // The updating was successful... Attempt to update User Details in
    // database User Profile...
    console.log("User Updated Successfully. UID: " + userRecord.uid);
    retUid = userRecord.uid;

    // Create a reference to the Users Database...
    var docRef = db.collection('Users');

    // Update the user profile document.
    return docRef.doc(userRecord.uid).update(newuser);
  }).then(result => {
    // everything went fine... return User UID as a successful result...
    res.write(userId);

    return;

  }).catch(function(error) {
    console.log("doc.update - Error updating user profile in database:", error);
    return;

  });

  res.end();
</code>```

答:
A previous answer of mine on Cloud Functions for Firebase HTTP timeout might be of help here:

Cloud Functions triggered by HTTP requests need to be terminated by
  ending them with a send(), redirect(), or end(), otherwise they
  will continue running and reach the timeout.

From your code examples, it looks like your then(){} promise returns are ending with res.end(), but the entire function is returning the Promise from:

```<code>return db.collection('Users').where('email', '==', email).get()
</code>```

Which could be stopping it from ending when you want it to. With HTTPS triggers, you don't need to return a Promise to keep the function running, only a result.

Try removing the return statement from this line:

```<code>db.collection('Users').where('email', '==', email).get()
</code>```

Then you just need to ensure that all exit routes (or termination points) end with res.end() or similar, so currently you have 2 termination points:

```<code>  }).then(result => {
    // everything went fine... return User UID as a successful result...
    res.write(userId);

    res.status(200).end();
  }).catch(function(error) {
    console.log("doc.update - Error updating user profile in database:", error);

    res.status(500).end();
  });
</code>```

Body:
I am still a beginner in the Firebase world and I have been trying to figure out what the problem is with the below code but I failed in all possible ways.

The code is supposed to retrieve the uid from the user profile in the database, then use it to update the authentication profile, then again to update the database profile if the authentication profile update was successful.

In index.js I have defined an exported function to deal with POSTed params from HTML forms. The code below defines the handler function in another module file:

 exports.auUpdateUserByEmail = (req, res) => {
  // This handler function will retrieve the POSTed params of user profile
  // and will attempt to update the existing user authentication as well as
  // the database profiles.
  //
  // This function accepts the following params:
  // 1. User email   // 2. Phone number   // 3. password   // 4. Display name
  // 5. Photo url   // 6. Disabled Flag
  //

  var db = admin.firestore();

  var uEmail = req.body.userEmail;
  var dName = req.body.displayName;
  var userId = "";

  var newuser = {
    displayName: dName
  }

  console.log("Email passed: " + uEmail);

  // Fetch the user UID by user email...
  res.write('User UID: ' + userId);
  console.log('User UID: ' + userId);

  // attempt to update the user authentication profile...
  return db.collection('Users').where('email', '==', email).get()
  .then(snapshot => {
    snapshot.forEach(doc => {
        var d = doc.data();
        console.log("doc.id: " + doc.id + " - d.email: " + d.email);
        if(d.email == email)
        {
          userId = d.uid;
        }
    });

    return admin.auth().updateUser(userId, newuser);
  }).then(function(userRecord) {
    // The updating was successful... Attempt to update User Details in
    // database User Profile...
    console.log("User Updated Successfully. UID: " + userRecord.uid);
    retUid = userRecord.uid;

    // Create a reference to the Users Database...
    var docRef = db.collection('Users');

    // Update the user profile document.
    return docRef.doc(userRecord.uid).update(newuser);
  }).then(result => {
    // everything went fine... return User UID as a successful result...
    res.write(userId);

    return res.end();

  }).catch(function(error) {
    console.log("doc.update - Error updating user profile in database:", error);
    return res.end();

  });
}

In index.js, I have the following exports definition:

var appAuth = express();
//Here we are configuring express to use body-parser as middle-ware.
appAuth.use(bodyParser.urlencoded({ extended: false }));
appAuth.use(bodyParser.json());

appAuth.post('/updateUserByEmail', authusers.auUpdateUserByEmail);

exports.usersAuthFunctions = functions.https.onRequest(appAuth);

I have to say that I got it to work fine to get the uid, update the auth profile, and then update database profile, but it keeps on waiting for the function return.

Appreciate your valuable help. Thanks.

I have updated the code as below and it does the jobs but returns a blank page as the HTTPS exits before the promises are complete which fires "Error: write after end" error.

var fetch_uid = db.collection('Users').where('email', '==', uEmail).get()
  .then(snapshot => {
    // var userId = snapshot.data.uid;

    snapshot.forEach(doc => {
        var d = doc.data();
        console.log("doc.id: " + doc.id + " - d.email: " + d.email);
        if(d.email == uEmail)
        {
          userId = d.uid;

          res.write('User UID: ' + userId);
          console.log('User UID: ' + userId);

        }
    });

    return admin.auth().updateUser(userId, newuser);
  }).then(function(userRecord) {
    // The updating was successful... Attempt to update User Details in
    // database User Profile...
    console.log("User Updated Successfully. UID: " + userRecord.uid);
    retUid = userRecord.uid;

    // Create a reference to the Users Database...
    var docRef = db.collection('Users');

    // Update the user profile document.
    return docRef.doc(userRecord.uid).update(newuser);
  }).then(result => {
    // everything went fine... return User UID as a successful result...
    res.write(userId);

    return;

  }).catch(function(error) {
    console.log("doc.update - Error updating user profile in database:", error);
    return;

  });

  res.end();

Body:
A previous answer of mine on Cloud Functions for Firebase HTTP timeout might be of help here:

Cloud Functions triggered by HTTP requests need to be terminated by
  ending them with a send(), redirect(), or end(), otherwise they
  will continue running and reach the timeout.

From your code examples, it looks like your then(){} promise returns are ending with res.end(), but the entire function is returning the Promise from:

return db.collection('Users').where('email', '==', email).get()

Which could be stopping it from ending when you want it to. With HTTPS triggers, you don't need to return a Promise to keep the function running, only a result.

Try removing the return statement from this line:

db.collection('Users').where('email', '==', email).get()

Then you just need to ensure that all exit routes (or termination points) end with res.end() or similar, so currently you have 2 termination points:

  }).then(result => {
    // everything went fine... return User UID as a successful result...
    res.write(userId);

    res.status(200).end();
  }).catch(function(error) {
    console.log("doc.update - Error updating user profile in database:", error);

    res.status(500).end();
  });


问:
why "abc" + null results abcnull
why "abc" + null  results abcnull

```<code>String s1 = "abc";
String s2 = null;
String s3 = s1+ s2;

System.out.println(s3);
</code>```

Result: abcnull

答:
This is how Java Concatenation works.
It treats null objects as "null".

Please see this link

Title: why "abc" + null results abcnull

Body:
why "abc" + null  results abcnull

String s1 = "abc";
String s2 = null;
String s3 = s1+ s2;

System.out.println(s3);

Result: abcnull


问:
Rails 5 ActionView::Helpers capture method
I'm new in ruby on rails, and I want to practice it.
I'm stuck when I want to include a view into antoher view.
I want by doing that to have my posts into another view than of posts/index

posts/index

method:

```<code>def index
    @Posts = Post.all
end
</code>```

view:

```<code><% @posts = capture do %>

   <% @posts.each do |post| %>
     <h3>
      <%= post.title %>
     </h3>
    <p>
     <%= post.content %>
    </p>
  <% end %>

<% end %>
</code>```

pages/index

```<code><h1> Index Of another pages </h1>
<%= @posts %>
</code>```

答:
If you want to force your index action to render another view, then go with follow code:

```<code>def index
  @Posts = Post.all
  render 'pages/index'
end
</code>```

Correct me if I haven't get you

Body:
I'm new in ruby on rails, and I want to practice it.
I'm stuck when I want to include a view into antoher view.
I want by doing that to have my posts into another view than of posts/index

posts/index

method:

def index
    @Posts = Post.all
end

view:

<% @posts = capture do %>

   <% @posts.each do |post| %>

      <%= post.title %>

     <%= post.content %>

  <% end %>

<% end %>

pages/index

 Index Of another pages

<%= @posts %>

Body:
If you want to force your index action to render another view, then go with follow code:

def index
  @Posts = Post.all
  render 'pages/index'
end

Correct me if I haven't get you


问:
DQL/SQL GROUP BY MONTH()
Is it possible to GROUP BY month having only date as a column? This can be achieved by PHP loop but I would prefer to use SQL. Live code below:</p>

```<code>    $query = $this->em
            ->createQuery("SELECT Month(p.planDate), SUM(ROUND(p.ndata5/1000)) AS volume "
                    . "FROM NTPBundle:ParagonData p WHERE p.planDate >= :startDate AND p.ndata5<>0 GROUP BY Month(p.planDate) ORDER BY p.planDate")
            ->setParameter('startDate', $this->startDate->format('Y-m-d'));
</code>```

答:
Right sort it you have to name select then ORDER BY this name like:

```<code> $query = $this->em
            ->createQuery("SELECT Month(p.planDate) as monthPlan, SUM(ROUND(p.ndata5/1000)) AS volume "
                    . "FROM NTPBundle:ParagonData p WHERE p.planDate >= :startDate AND p.ndata5<>0 "
                    . "GROUP BY monthPlan "
                    . "ORDER BY p.planDate")
            ->setParameter('startDate', $this->startDate->format('Y-m-d'));
</code>```

thanks for clues

Title: DQL/SQL GROUP BY MONTH()

Body:
Is it possible to GROUP BY month having only date as a column? This can be achieved by PHP loop but I would prefer to use SQL. Live code below:

    $query = $this->em
            ->createQuery("SELECT Month(p.planDate), SUM(ROUND(p.ndata5/1000)) AS volume "
                    . "FROM NTPBundle:ParagonData p WHERE p.planDate >= :startDate AND p.ndata5<>0 GROUP BY Month(p.planDate) ORDER BY p.planDate")
            ->setParameter('startDate', $this->startDate->format('Y-m-d'));

Body:
Right sort it you have to name select then ORDER BY this name like:

 $query = $this->em
            ->createQuery("SELECT Month(p.planDate) as monthPlan, SUM(ROUND(p.ndata5/1000)) AS volume "
                    . "FROM NTPBundle:ParagonData p WHERE p.planDate >= :startDate AND p.ndata5<>0 "
                    . "GROUP BY monthPlan "
                    . "ORDER BY p.planDate")
            ->setParameter('startDate', $this->startDate->format('Y-m-d'));

thanks for clues


问:
How to Solve Java selenium error in testing?
I am new in software testing and following this course from utest.com
https://www.utest.com/courses/selenium-basics-part-4-create-java-project-add-recorded-test-case-run-project
when following steps while the instructor was testing the code the test case worked with him and give me error as in this photo
screen shot of the error

how can i solve it ?

答:
By looking at the screen shot attached, the error might be because of below mentioned reasons

1) Selenium Server Standalone file is not properly configured, make sure you use the correct version of the file that is compatible with your local system

2) There might be chance that the port has been occupied by some other process, make sure the port which listens to Selenium Server Standalone is free or u can forcefully assign some other port which is not occupied to Selenium Server Standalone

Hope this will work


问:
Emit change or bind to model not working
I am currently learning the way components are suppose to be used and when they should be created.

I have learnt that for example when creating a Task List the best way to go about this would be to have a stateless wrapper and then a stateful task list item and checkbox components. (See Below)

Example of Task stateful and stateless

The issue I am currently having is figuring out the best practice on the issue and putting it into practice.

Emitting the (change) event from the checkbox to the stateless components and then setting the Model.Done flag to True or False.

Binding the Model.Done to the Checkbox component so that it will change automatically.

Example of 2:

Task.component

```<code><div fxFlex='20' style="background: #C3C3C3">
  <app-task-list-item *ngFor="let task of tasks" [task]="task"></app-task-list-item>
</div>
</code>```

Task-List-Item.component

```<code><div style="display: flex;">
  <p style="padding-right: 2em;">{{task.date}}</p>
  <p style="padding-right: 2em;">{{task.description}}</p>
  <app-task-list-checkbox [checked]="task.done"></app-task-list-checkbox>
</div>
</code>```

Task-List-Checkbox.component

```<code><input type="checkbox" [checked]="checked">
</code>```

The question I am asking is:

Would you emit the change of the checkbox to the stateless component?

Would you create a checkbox component or add that to the Task-List-Item.component?

答:
You don't have to emit anything to your stateless component. Just use two-way data binding with your checkbox. Because of object reference, each task in array tasks will have its done property changed when you toggle your checkbox. You don't also have to create a component for a single checkbox, just put it into your Task-List-Item.component

Task-List-Item.component:

```<code><div style="display: flex;">
    <p style="padding-right: 2em;">{{task.date}}</p>
    <p style="padding-right: 2em;">{{task.description}}</p>
    <input [(ngModel)]="task.done" type="checkbox"/>
</div>
</code>```

Body:
I am currently learning the way components are suppose to be used and when they should be created.

I have learnt that for example when creating a Task List the best way to go about this would be to have a stateless wrapper and then a stateful task list item and checkbox components. (See Below)

Example of Task stateful and stateless

The issue I am currently having is figuring out the best practice on the issue and putting it into practice.

Emitting the (change) event from the checkbox to the stateless components and then setting the Model.Done flag to True or False.

Binding the Model.Done to the Checkbox component so that it will change automatically.

Example of 2:

Task.component

  <app-task-list-item *ngFor="let task of tasks" [task]="task"></app-task-list-item>

Task-List-Item.component

{{task.date}}

{{task.description}}

  <app-task-list-checkbox [checked]="task.done"></app-task-list-checkbox>

Task-List-Checkbox.component

<input type="checkbox" [checked]="checked">

The question I am asking is:

Would you emit the change of the checkbox to the stateless component?

Would you create a checkbox component or add that to the Task-List-Item.component?

Body:
You don't have to emit anything to your stateless component. Just use two-way data binding with your checkbox. Because of object reference, each task in array tasks will have its done property changed when you toggle your checkbox. You don't also have to create a component for a single checkbox, just put it into your Task-List-Item.component

Task-List-Item.component:

<div style="display: flex;">
    <p style="padding-right: 2em;">{{task.date}}</p>
    <p style="padding-right: 2em;">{{task.description}}</p>
    <input [(ngModel)]="task.done" type="checkbox"/>
</div>


问:
Why in XAML XmlDataProvider do we have to say "x:Key" instead of "Key"?
What is the function of the namespace here?

I would think in this simple example I would be able to put "Key" and "XData" instead of "x:Key" and "x:XData" but when I do it says "Key" was not found in XmlDataProvider.

```<code><Window x:Class="DataBindingWPF.XmlBinding"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="DataBindingWPF" Height="300" Width="300"
    >
    <StackPanel>
        <StackPanel.Resources>
            <XmlDataProvider x:Key="Colors" Source="Colors.xml"  XPath="/colors"></XmlDataProvider>
            <XmlDataProvider x:Key="MoreColors" XPath="/colors">
                <x:XData>
...
</code>```

答:
Did you also remove the :x from

```<code>xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
</code>```

so it reads

```<code>xmlns="http://schemas.microsoft.com/winfx/2006/xaml"
</code>```

OwnerDisplayName: Edward Tanguay

Body:
What is the function of the namespace here?

I would think in this simple example I would be able to put "Key" and "XData" instead of "x:Key" and "x:XData" but when I do it says "Key" was not found in XmlDataProvider.

<Window x:Class="DataBindingWPF.XmlBinding"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="DataBindingWPF" Height="300" Width="300"
    >
    <StackPanel>
        <StackPanel.Resources>
            <XmlDataProvider x:Key="Colors" Source="Colors.xml"  XPath="/colors"></XmlDataProvider>
            <XmlDataProvider x:Key="MoreColors" XPath="/colors">
                <x:XData>
...

Body:
Did you also remove the :x from

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

so it reads

xmlns="http://schemas.microsoft.com/winfx/2006/xaml"

OwnerDisplayName: James Curran


问:
THREAD 1: EXC_BREAKPOINT CALayer removeAllAnimations message sent to deallocated
There are a lot of question with the same title but somehow I felt that every case is different as my problem is still not resolved and I've no clue why and also there are not enough solutions for Swift. So here is my scenerio:

I've used CarbonKit to show 4 view controllers in a single view controller. The FourthViewController sends a get call using AlamoFire. It successfully loads the data and reload tableView. However when I drag this table view my app crashes and I get EXC_BREAKPOINT and sometimes EXC_BAD_ACCESS for the same thing.

Here is what I've tried:

Upon searching I came to know about zombies. So I enabled it and when the app gives me EXC I get this:

-[CALayer removeAllAnimations]: message sent to deallocated instance

So as I checked there was no animation I might have been using in this class. But considering it's inside CarbonKit they might have something to do with it but I'm unable to figure it out.

I run Product > Analyze from xCode and the most of the blue icons are on FBSDK which have nothing to do with this class so it was not useful to debug at all.

Here are the screenshots:
 and
and here is what Instruments 9.0 zombies message gave me:
 and

I get this in console of xCode:

If you need more information I'll update my questions.

UPDATE

Here is my code when I'm getting the data from web using Alamofire. Now this call runs successfully and I can scroll down to view all the data that is loaded in the table. But when i scroll up then it crashes with the above errors.

```<code>let headers = [
            "security-token": "MY_SECURITY_CODE_HERE",
            "Content-Type": "application/x-www-form-urlencoded"
        ]

        let url = "URL_GOES_HERE"
        //print(url)
        Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { response in

            if let result = response.result.value as? [String: AnyObject] {

                switch response.result {
                case .success:
                    if result["status"] as! Int == 0
                    {
                        self.clearAllNotice()
                        let alert = UIAlertController(title: "Error",
                                                      message: "\(result["msg"] ?? "Our Server is not responding at the moment. Try again later!" as AnyObject)",
                            preferredStyle: UIAlertControllerStyle.alert)

                        let cancelAction = UIAlertAction(title: "OK",
                                                         style: .cancel, handler: nil)

                        alert.addAction(cancelAction)
                        self.present(alert, animated: true)
                    }
                    else
                    {
                        self.clearAllNotice()

                        for docReviewDict in (result["data"] as! [AnyObject]) {

                            let docReview = DoctorReview(dict: docReviewDict as! [String : AnyObject])
                            self.mainDoctorReviewsArray.append(docReview)
                        }

                        self.tableView.reloadData()
                    }
                case .failure(let error):
                    self.clearAllNotice()
                    let alert = UIAlertController(title: "Something is wrong",
                                                  message: error.localizedDescription,
                                                  preferredStyle: UIAlertControllerStyle.alert)

                    let cancelAction = UIAlertAction(title: "OK",
                                                     style: .cancel, handler: nil)

                    alert.addAction(cancelAction)
                    self.present(alert, animated: true)
                }
            } else {
              print("Somethins is wrong with the URL")
            }
        }
</code>```

Just in case here is the cell which is loaded in the tableview.

Latest:

Based on the comment I've done this:

```<code>DispatchQueue.main.async {
                        self.tableView.reloadData()
                        }
</code>```

but still the same result I'am getting

Thread 1: EXC_BAD_ACCESS (code=1, address=0xb4c4beb8)

on let cell = tableView.dequeueReusableCell(withIdentifier: "ReviewCell") as! ReviewsTableViewCell line when I drag down on table view.

IMPLEMENTATION OF CELL

The class name is ReviewsViewController which has a @IBOutlet fileprivate var tableView: UITableView!.

Then in viewDidLoad():

```<code>tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
</code>```

Then I've table view delegate and datasource:

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mainDoctorReviewsArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "ReviewCell") as! ReviewsTableViewCell //WHEN THE APP IS CRASHED AS I DRAG THE TABLE VIEW IT CRASH ON THIS LINE. As this line is highlighted in red with message "Thread 1: EXC_BREAKPOINT (code=1, subcode=0x186ddd61c)"

        cell.userPhoto.layer.cornerRadius = cell.userPhoto.frame.width / 2;
        cell.userPhoto.layer.masksToBounds = true

        cell.userName.text = mainDoctorReviewsArray[indexPath.row].name

        cell.starRating.settings.fillMode = .precise

        if let rate = mainDoctorReviewsArray[indexPath.row].rating
        {
            cell.starRating.rating = Double(rate)!
        }
        else {
            cell.starRating.rating = 0
        }

        cell.desc.text = mainDoctorReviewsArray[indexPath.row].feedback
        cell.dateOfReview.text = mainDoctorReviewsArray[indexPath.row].dates
        cell.timeOfReview.text = mainDoctorReviewsArray[indexPath.row].times

        return cell
    }
</code>```

and in the cell class there is just:

```<code>import UIKit
import Cosmos

class ReviewsTableViewCell: UITableViewCell {

    @IBOutlet var timeOfReview: UILabel!
    @IBOutlet var dateOfReview: UILabel!
    @IBOutlet var desc: UITextView!
    @IBOutlet var starRating: CosmosView!
    @IBOutlet var userName: UILabel!
    @IBOutlet var userPhoto: UIImageView!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}
</code>```

The screenshot of tableView is above in this question.

This is the parent class under which 4 ViewControllers loads: dropbox.com/s/d5sh4ej1ssv6873/… And this is the class which has the tableview is and on scroll it crashed the app: dropbox.com/s/3kiju9hn3uewzar/ReviewsViewController.swift?dl=0

答:
Did you register the cell class type?

If not add in viewDidLoad:

```<code>self.tableView.register(ReviewsTableViewCell.self, forCellReuseIdentifier: "ReviewCell")
</code>```

Next just dequeue it in cellForRow:

```<code>let cell = tableView.dequeueReusableCellFor(identifier: "ReviewCell", indexPath: indexPath) as! ReviewsTableViewCell
</code>```

Check if the error is still happening

Body:
There are a lot of question with the same title but somehow I felt that every case is different as my problem is still not resolved and I've no clue why and also there are not enough solutions for Swift. So here is my scenerio:

I've used CarbonKit to show 4 view controllers in a single view controller. The FourthViewController sends a get call using AlamoFire. It successfully loads the data and reload tableView. However when I drag this table view my app crashes and I get EXC_BREAKPOINT and sometimes EXC_BAD_ACCESS for the same thing.

Here is what I've tried:

Upon searching I came to know about zombies. So I enabled it and when the app gives me EXC I get this:

-[CALayer removeAllAnimations]: message sent to deallocated instance

So as I checked there was no animation I might have been using in this class. But considering it's inside CarbonKit they might have something to do with it but I'm unable to figure it out.

I run Product > Analyze from xCode and the most of the blue icons are on FBSDK which have nothing to do with this class so it was not useful to debug at all.

Here are the screenshots:
 and
and here is what Instruments 9.0 zombies message gave me:
 and

I get this in console of xCode:

If you need more information I'll update my questions.

UPDATE

Here is my code when I'm getting the data from web using Alamofire. Now this call runs successfully and I can scroll down to view all the data that is loaded in the table. But when i scroll up then it crashes with the above errors.

let headers = [
            "security-token": "MY_SECURITY_CODE_HERE",
            "Content-Type": "application/x-www-form-urlencoded"
        ]

        let url = "URL_GOES_HERE"
        //print(url)
        Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { response in

            if let result = response.result.value as? [String: AnyObject] {

                switch response.result {
                case .success:
                    if result["status"] as! Int == 0
                    {
                        self.clearAllNotice()
                        let alert = UIAlertController(title: "Error",
                                                      message: "\(result["msg"] ?? "Our Server is not responding at the moment. Try again later!" as AnyObject)",
                            preferredStyle: UIAlertControllerStyle.alert)

                        let cancelAction = UIAlertAction(title: "OK",
                                                         style: .cancel, handler: nil)

                        alert.addAction(cancelAction)
                        self.present(alert, animated: true)
                    }
                    else
                    {
                        self.clearAllNotice()

                        for docReviewDict in (result["data"] as! [AnyObject]) {

                            let docReview = DoctorReview(dict: docReviewDict as! [String : AnyObject])
                            self.mainDoctorReviewsArray.append(docReview)
                        }

                        self.tableView.reloadData()
                    }
                case .failure(let error):
                    self.clearAllNotice()
                    let alert = UIAlertController(title: "Something is wrong",
                                                  message: error.localizedDescription,
                                                  preferredStyle: UIAlertControllerStyle.alert)

                    let cancelAction = UIAlertAction(title: "OK",
                                                     style: .cancel, handler: nil)

                    alert.addAction(cancelAction)
                    self.present(alert, animated: true)
                }
            } else {
              print("Somethins is wrong with the URL")
            }
        }

Just in case here is the cell which is loaded in the tableview.

Latest:

Based on the comment I've done this:

DispatchQueue.main.async {
                        self.tableView.reloadData()
                        }

but still the same result I'am getting

Thread 1: EXC_BAD_ACCESS (code=1, address=0xb4c4beb8)

on let cell = tableView.dequeueReusableCell(withIdentifier: "ReviewCell") as! ReviewsTableViewCell line when I drag down on table view.

IMPLEMENTATION OF CELL

The class name is ReviewsViewController which has a @IBOutlet fileprivate var tableView: UITableView!.

Then in viewDidLoad():

tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()

Then I've table view delegate and datasource:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mainDoctorReviewsArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "ReviewCell") as! ReviewsTableViewCell //WHEN THE APP IS CRASHED AS I DRAG THE TABLE VIEW IT CRASH ON THIS LINE. As this line is highlighted in red with message "Thread 1: EXC_BREAKPOINT (code=1, subcode=0x186ddd61c)"

        cell.userPhoto.layer.cornerRadius = cell.userPhoto.frame.width / 2;
        cell.userPhoto.layer.masksToBounds = true

        cell.userName.text = mainDoctorReviewsArray[indexPath.row].name

        cell.starRating.settings.fillMode = .precise

        if let rate = mainDoctorReviewsArray[indexPath.row].rating
        {
            cell.starRating.rating = Double(rate)!
        }
        else {
            cell.starRating.rating = 0
        }

        cell.desc.text = mainDoctorReviewsArray[indexPath.row].feedback
        cell.dateOfReview.text = mainDoctorReviewsArray[indexPath.row].dates
        cell.timeOfReview.text = mainDoctorReviewsArray[indexPath.row].times

        return cell
    }

and in the cell class there is just:

import UIKit
import Cosmos

class ReviewsTableViewCell: UITableViewCell {

    @IBOutlet var timeOfReview: UILabel!
    @IBOutlet var dateOfReview: UILabel!
    @IBOutlet var desc: UITextView!
    @IBOutlet var starRating: CosmosView!
    @IBOutlet var userName: UILabel!
    @IBOutlet var userPhoto: UIImageView!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

The screenshot of tableView is above in this question.

This is the parent class under which 4 ViewControllers loads: dropbox.com/s/d5sh4ej1ssv6873/… And this is the class which has the tableview is and on scroll it crashed the app: dropbox.com/s/3kiju9hn3uewzar/ReviewsViewController.swift?dl=0

Body:
Did you register the cell class type?

If not add in viewDidLoad:

self.tableView.register(ReviewsTableViewCell.self, forCellReuseIdentifier: "ReviewCell")

Next just dequeue it in cellForRow:

let cell = tableView.dequeueReusableCellFor(identifier: "ReviewCell", indexPath: indexPath) as! ReviewsTableViewCell

Check if the error is still happening


问:
Get/display individual fields from doc.data() , eg: display the (cost :) field in doc.data()
```<code>firestore.collection("products").where("Product", "==", inputx)
    .get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            console.log(doc.id, " => ", doc.data());
        });
    })
</code>```

here is my database

答: It's easy, just do doc.data().cost.

Body:
firestore.collection("products").where("Product", "==", inputx)
    .get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            console.log(doc.id, " => ", doc.data());
        });
    })

here is my database

Body: It's easy, just do doc.data().cost.


问:
How does one remove a Docker image?
I'm running Docker under Vagrant under OS X 10.8.4  (Mountain Lion), and whenever I try to delete a saved image, I get an error:

```<code>$ docker rmi some-image-id
2013/07/15 hh:mm:ss unexpected JSON input
</code>```

According to the rmi help, the proper syntax is docker rmi IMAGE [IMAGE...], and I'm not sure what to make of that.

How can I delete an image?

```<code>$ docker version
Client version: 0.4.8
Server version: 0.4.8
Go version: go1.1
</code>```

```<code>$docker info
Containers: 1
Images: 3
</code>```

Interestingly, when I run docker ps, no containers show up at all. Running docker images shows four (4) base images and one (1) node image.

答:
For versions 1.13 and higher:

```<code>docker image rm [OPTIONS] IMAGE [IMAGE...]
</code>```

Comparing:

the documention of docker image rm and

the documentation of docker rmi,

the [OPTIONS] seem to have no difference.

```<code>--force , -f        Force removal of the image
--no-prune          Do not delete untagged parents
</code>```

From: Introducing Docker 1.13

CLI restructured

In Docker 1.13, we regrouped every command to sit under the logical object it’s interacting with. For example list and start of containers are now subcommands of docker container and history is a subcommand of docker image.

These changes let us clean up the Docker CLI syntax, improve help text and make Docker simpler to use. The old command syntax is still supported, but we encourage everybody to adopt the new syntax.

ContentLicense: CC BY-SA 4.0

Title: How does one remove a Docker image?

Body:
I'm running Docker under Vagrant under OS X 10.8.4  (Mountain Lion), and whenever I try to delete a saved image, I get an error:

$ docker rmi some-image-id
2013/07/15 hh:mm:ss unexpected JSON input

According to the rmi help, the proper syntax is docker rmi IMAGE [IMAGE...], and I'm not sure what to make of that.

How can I delete an image?

$ docker version
Client version: 0.4.8
Server version: 0.4.8
Go version: go1.1

$docker info
Containers: 1
Images: 3

Interestingly, when I run docker ps, no containers show up at all. Running docker images shows four (4) base images and one (1) node image.

Body:
For versions 1.13 and higher:

docker image rm [OPTIONS] IMAGE [IMAGE...]

Comparing:

the documention of docker image rm and

the documentation of docker rmi,

the [OPTIONS] seem to have no difference.

--force , -f        Force removal of the image
--no-prune          Do not delete untagged parents

From: Introducing Docker 1.13

CLI restructured

In Docker 1.13, we regrouped every command to sit under the logical object it’s interacting with. For example list and start of containers are now subcommands of docker container and history is a subcommand of docker image.

These changes let us clean up the Docker CLI syntax, improve help text and make Docker simpler to use. The old command syntax is still supported, but we encourage everybody to adopt the new syntax.


问:
What is real meaning of suiteName in UserDefaults initializer?
I attempting to grasp some kind of unit tests, so we create mock user defaults.

```<code>class MockUserDefaults: UserDefaults {
var gameStyleChanged = 0
override func set(_ value: Int, forKey defaultName: String) {
if defaultName == "something" {
  someStyleChanged += 1
}
}
}
</code>```

right after in setup() i create

```<code>mockUserDefaults = MockUserDefaults(suiteName: "testing")!
</code>```

So i confused i can't understand full meaning of suiteName i've read official documentation but it is not clear enough, please help

答: suiteName:is kind of an identifier which helps you create preferences(UserDefaults) store. By using a particular suiteName, you are creating a preferences store, that is not bounded to a particular application (whereas standard UserDefaults are different for every application). Because of this reason, you can create a store, that can be shared between different app/extensions. </p>

Body:
I attempting to grasp some kind of unit tests, so we create mock user defaults.

class MockUserDefaults: UserDefaults {
var gameStyleChanged = 0
override func set(_ value: Int, forKey defaultName: String) {
if defaultName == "something" {
  someStyleChanged += 1
}
}
}

right after in setup() i create

mockUserDefaults = MockUserDefaults(suiteName: "testing")!

So i confused i can't understand full meaning of suiteName i've read official documentation but it is not clear enough, please help


问:
Unable to connect to remote SQL Server 2005
I have created my asp.net website using database ASPNETDB.MDF but when I try to host my site on server ...

The SQL Server 2005 hosting provider issue me the

```<code>database name dobriyalji
server ip : 69.112.222.220
database username : XXXX
database password : XXXX
</code>```

I have imported all of my ASPNETDB.MDF tables to my server database dobriyalji ...

And I empty the Appdata.mdf and aspnetdb.log file from App_Data Folder ...

When I try to run my site the following error occurs ...

An attempt to attach an auto-named database for file
  Users\Ashish Dobriyal\Documents\Visual Studio
  2008\WebSites\VOLVO\App_Data\ASPNETDB.MDF

failed. A database with the same name exists, or specified file cannot
  be opened, or it is located on UNC share.

MY LOCALHOST CONNECTION STRING :

```<code><connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
</code>```

MY REMOTE HOST CONNECTION STRING :

```<code><connectionStrings>
    <add name="vbi_india2kConnectionString" connectionString="Data Source=69.112.222.220;Initial Catalog=dobriyalji;Persist Security Info=True;User ID=XXXX;Password=XXXX" providerName="System.Data.SqlClient"/>
  </connectionStrings>
</code>```

答: You have to use publish database wizard to deploy local database to your production database server.</p>

Body:
I have created my asp.net website using database ASPNETDB.MDF but when I try to host my site on server ...

The SQL Server 2005 hosting provider issue me the

database name dobriyalji
server ip : 69.112.222.220
database username : XXXX
database password : XXXX

I have imported all of my ASPNETDB.MDF tables to my server database dobriyalji ...

And I empty the Appdata.mdf and aspnetdb.log file from App_Data Folder ...

When I try to run my site the following error occurs ...

An attempt to attach an auto-named database for file
  Users\Ashish Dobriyal\Documents\Visual Studio
  2008\WebSites\VOLVO\App_Data\ASPNETDB.MDF

failed. A database with the same name exists, or specified file cannot
  be opened, or it is located on UNC share.

MY LOCALHOST CONNECTION STRING :

<connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>

MY REMOTE HOST CONNECTION STRING :

<connectionStrings>
    <add name="vbi_india2kConnectionString" connectionString="Data Source=69.112.222.220;Initial Catalog=dobriyalji;Persist Security Info=True;User ID=XXXX;Password=XXXX" providerName="System.Data.SqlClient"/>
  </connectionStrings>


问:
How to resolve CVS error: cannot rename file CVS/Entries.Extra.Backup to CVS/Entries.Extra: Bad address
I've checked out a module from CVS onto a newly installed Windows 7 machine. The virus scanner has not yet been installed.

Later, when I try to do an update, I get the following error message:

cannot rename file CVS/Entries.Extra.Backup to CVS/Entries.Extra: Bad address

Has anyone seen and resolved this issue before?

答: I had the same problem. After disabling antivirus/malware protection tool, I was able to resolve the problem. Also, ensure that cvsnt.exe should be running in an elevated mode.


问:
how to find extreme point of the contour opencv c++
I have this image:

How do i can implement the extreme point finder code in OpenCv c++ like in the picture?

Anyone have any idea please??

```<code># determine the most extreme points along the contour

leftmost = tuple(cnt [cnt[:,:,0].argmin()][0]);
rightmost = tuple(cnt [cnt[:,:,0].argmax()][0]);
topmost = tuple(cnt [cnt[:,:,1].argmin()][0]);
bottommost = tuple(cnt [cnt[:,:,1].argmax()][0]);
</code>```

答:
Assuming you already have the contour and it is as a vector of points, you can use the std::minmax_element function for the same end. It supports a comparison method that can be whatever you want if it follows the signature. So a simple code similar to what you do would be:

```<code>#include <iostream>
#include <vector>
#include <algorithm>

// this is not necessary, just for testing (OpenCV Points should be used instead)
struct Point
{
    int x;
    int y;

    Point():
    x(0), y(0){}
    Point(int xVal, int yVal):
    x(xVal), y(yVal){}
};

int main()
{
    std::vector<Point> cnt = {
        {1,2},{4,5},{1,6}, {7,8}, {9,3}, {2,6}
    };

    // compare x axis
    auto val = std::minmax_element(cnt.begin(), cnt.end(), [](Point const& a, Point const& b){
        return a.x < b.x;
    });

    std::cout << " leftMost [ " << val.first->x << ", " << val.first->y << " ]" << std::endl;
    std::cout << " RightMost [ " << val.second->x << ", " << val.second->y << " ]" << std::endl;

    // compare y axis
    val = std::minmax_element(cnt.begin(), cnt.end(), [](Point const& a, Point const& b){
        return a.y < b.y;
    });

    std::cout << " TopMost [ " << val.first->x << ", " << val.first->y << " ]" << std::endl;
    std::cout << " BottomMost [ " << val.second->x << ", " << val.second->y << " ]" << std::endl;

    return 0;
}
</code>```

Here is a link to run it.

In this example the Point struct is just to simulate OpenCV one, but it will work exactly the same. The I create a test vector, run minmax_element comparing only the x axis and print the results. I do the same with the y axis.

This function returns a pair of iterators to such objects, if you need them to be returned make sure to copy them :)

Body:
I have this image:

How do i can implement the extreme point finder code in OpenCv c++ like in the picture?

Anyone have any idea please??

# determine the most extreme points along the contour

leftmost = tuple(cnt [cnt[:,:,0].argmin()][0]);
rightmost = tuple(cnt [cnt[:,:,0].argmax()][0]);
topmost = tuple(cnt [cnt[:,:,1].argmin()][0]);
bottommost = tuple(cnt [cnt[:,:,1].argmax()][0]);

Body:
Assuming you already have the contour and it is as a vector of points, you can use the std::minmax_element function for the same end. It supports a comparison method that can be whatever you want if it follows the signature. So a simple code similar to what you do would be:

#include <iostream>
#include <vector>
#include <algorithm>

// this is not necessary, just for testing (OpenCV Points should be used instead)
struct Point
{
    int x;
    int y;

    Point():
    x(0), y(0){}
    Point(int xVal, int yVal):
    x(xVal), y(yVal){}
};

int main()
{
    std::vector<Point> cnt = {
        {1,2},{4,5},{1,6}, {7,8}, {9,3}, {2,6}
    };

    // compare x axis
    auto val = std::minmax_element(cnt.begin(), cnt.end(), [](Point const& a, Point const& b){
        return a.x < b.x;
    });

    std::cout << " leftMost [ " << val.first->x << ", " << val.first->y << " ]" << std::endl;
    std::cout << " RightMost [ " << val.second->x << ", " << val.second->y << " ]" << std::endl;

    // compare y axis
    val = std::minmax_element(cnt.begin(), cnt.end(), [](Point const& a, Point const& b){
        return a.y < b.y;
    });

    std::cout << " TopMost [ " << val.first->x << ", " << val.first->y << " ]" << std::endl;
    std::cout << " BottomMost [ " << val.second->x << ", " << val.second->y << " ]" << std::endl;

    return 0;
}

Here is a link to run it.

In this example the Point struct is just to simulate OpenCV one, but it will work exactly the same. The I create a test vector, run minmax_element comparing only the x axis and print the results. I do the same with the y axis.

This function returns a pair of iterators to such objects, if you need them to be returned make sure to copy them :)