问:
How can I find the latest commit from forked repos on github?
For example I find a framework that is not maintained anymore but lots of forks. I want to see the more recent forks only. Network Graph is not available if its large.

答:
You can do it with a curl:

```<code>curl -X GET https://api.github.com/repos/<owner>/<repo>/forks
</code>```

For instance, the angular forks are:

```<code>curl -X GET https://api.github.com/repos/angular/angular/forks
</code>```

You can add a sort parameter ?sort=<oldest|newest|stargazers>, but the default one is the newest.

Body:
You can do it with a curl:

curl -X GET https://api.github.com/repos/<owner>/<repo>/forks

For instance, the angular forks are:

curl -X GET https://api.github.com/repos/angular/angular/forks

You can add a sort parameter ?sort=<oldest|newest|stargazers>, but the default one is the newest.


来源: stackexchange

问:
Regex for dd-mmm-yy date format in ColdFusion
I want to ensure that the user uploaded csv have date in the format dd-mmm-yy (10-Feb-14). I have did my research and I could see that none of the ColdFusion date functions help me to resolve this.

I can use IsValid function with a regular expression validation. I am not good in writing regex. Your help appreciated.

ContentLicense: CC BY-SA 3.0

Body:
use regex
for date="^\d\d\d\d-(0[1-9]|1[0-2])-([0][1-9]|[12][0-9]|3[01])$"
 for datetime="^\d\d\d\d-(0[1-9]|1[0-2])-([0][1-9]|[12][0-9]|3[01]) (00|[0][0-9]|1[0-9]|2[0-3]):([0][0-9]|[0-5][0-9]):([0][0-9]|[0-5][0-9])$"

it will strictly follow YYYY-mm-dd it will not allow yy-mm-dd or yyyy-m-dd oryyyy-mm-d or dd-mm-yyyy.
it will not allow h:m:sor h:mm:s or hh:mm:s it will allow only  (YYYY-MM-DD HH:mm:ss)


问:
Dynamically create HTML table in C#
Is there more efficient way to build HTML table than the one I'm trying on right now?

I'm getting an object and it has some list of entities in it. So I need to pass through each of them and build first a cell and then add it to an row and finally adding it in table.

The thing I'm trying on is totally messy, kind of works, but it has too much of redundant code.

```<code>public static string CreateNotificationMailMessage(NotificationMailMessage mailMessageObject)
{
    var table = new HtmlTable();
    var mailMessage = new StringBuilder();
    string html;

    if (mailMessageObject.InvalidCompanies.Any())
    {
        HtmlTableRow row;
        HtmlTableCell cell;

        foreach (var invalidCompany in mailMessageObject.InvalidCompanies)
        {
            row = new HtmlTableRow();
            cell = new HtmlTableCell();
            cell.InnerText = invalidCompany.BusinessName;
            row.Cells.Add(cell);
            cell.InnerText = invalidCompany.SwiftBIC;
            row.Cells.Add(cell);
            cell.InnerText = invalidCompany.IBAN;
            row.Cells.Add(cell);
            table.Rows.Add(row);
        }
    }
    using (var sw = new StringWriter())
    {
        table.RenderControl(new HtmlTextWriter(sw));
        html = sw.ToString();
    }

    mailMessage.AppendFormat(html);
    return mailMessage.ToString();
}
</code>```

At the end I want to return text version of created HTML table.
The problem is that I have much more properties than those 3 (BusinessName, SwiftBIC and IBAN) and plus I have one more list of objects inside of mailMessageObject, so the code would be terrible.

Anybody has an idea how to solve this in simpler and cleaner way?

答:
I would just like to supplement Steve Harris' answer with a class library that is a little more built out. His answer is a totally elegant solution that made a windows service I was creating not have to reference System.Web for no good reason!

Classes Defined:

```<code>  public static class Html
  {
    public class Table : HtmlBase, IDisposable
    {
      public Table(StringBuilder sb, string classAttributes = "", string id = "") : base(sb)
      {
        Append("<table");
        AddOptionalAttributes(classAttributes, id);
      }

      public void StartHead(string classAttributes = "", string id = "")
      {
        Append("<thead");
        AddOptionalAttributes(classAttributes, id);
      }

      public void EndHead()
      {
        Append("</thead>");
      }

      public void StartFoot(string classAttributes = "", string id = "")
      {
        Append("<tfoot");
        AddOptionalAttributes(classAttributes, id);
      }

      public void EndFoot()
      {
        Append("</tfoot>");
      }

      public void StartBody(string classAttributes = "", string id = "")
      {
        Append("<tbody");
        AddOptionalAttributes(classAttributes, id);
      }

      public void EndBody()
      {
        Append("</tbody>");
      }

      public void Dispose()
      {
        Append("</table>");
      }

      public Row AddRow(string classAttributes = "", string id = "")
      {
        return new Row(GetBuilder(), classAttributes, id);
      }
    }

    public class Row : HtmlBase, IDisposable
    {
      public Row(StringBuilder sb, string classAttributes = "", string id = "") : base(sb)
      {
        Append("<tr");
        AddOptionalAttributes(classAttributes, id);
      }
      public void Dispose()
      {
        Append("</tr>");
      }
      public void AddCell(string innerText, string classAttributes = "", string id = "", string colSpan = "")
      {
        Append("<td");
        AddOptionalAttributes(classAttributes, id, colSpan);
        Append(innerText);
        Append("</td>");
      }
    }

    public abstract class HtmlBase
    {
      private StringBuilder _sb;

      protected HtmlBase(StringBuilder sb)
      {
        _sb = sb;
      }

      public StringBuilder GetBuilder()
      {
        return _sb;
      }

      protected void Append(string toAppend)
      {
        _sb.Append(toAppend);
      }

      protected void AddOptionalAttributes(string className = "", string id = "", string colSpan = "")
      {

        if (!id.IsNullOrEmpty())
        {
          _sb.Append($" id=\"{id}\"");
        }
        if (!className.IsNullOrEmpty())
        {
          _sb.Append($" class=\"{className}\"");
        }
        if (!colSpan.IsNullOrEmpty())
        {
          _sb.Append($" colspan=\"{colSpan}\"");
        }
        _sb.Append(">");
      }
    }
  }
</code>```

Usage:

```<code>StringBuilder sb = new StringBuilder();
      using (Html.Table table = new Html.Table(sb, id: "some-id"))
      {
        table.StartHead();
        using (var thead = table.AddRow())
        {
          thead.AddCell("Category Description");
          thead.AddCell("Item Description");
          thead.AddCell("Due Date");
          thead.AddCell("Amount Budgeted");
          thead.AddCell("Amount Remaining");
        }
        table.EndHead();
        table.StartBody();
        foreach (var alert in alertsForUser)
        {
          using (var tr = table.AddRow(classAttributes: "someattributes"))
          {
           tr.AddCell(alert.ExtendedInfo.CategoryDescription);
            tr.AddCell(alert.ExtendedInfo.ItemDescription);
            tr.AddCell(alert.ExtendedInfo.DueDate.ToShortDateString());
            tr.AddCell(alert.ExtendedInfo.AmountBudgeted.ToString("C"));
            tr.AddCell(alert.ExtendedInfo.ItemRemaining.ToString("C"));
          }
        }
        table.EndBody();
      }
      return sb.ToString();
</code>```

Title: Dynamically create HTML table in C#

Body:
Is there more efficient way to build HTML table than the one I'm trying on right now?

I'm getting an object and it has some list of entities in it. So I need to pass through each of them and build first a cell and then add it to an row and finally adding it in table.

The thing I'm trying on is totally messy, kind of works, but it has too much of redundant code.

public static string CreateNotificationMailMessage(NotificationMailMessage mailMessageObject)
{
    var table = new HtmlTable();
    var mailMessage = new StringBuilder();
    string html;

    if (mailMessageObject.InvalidCompanies.Any())
    {
        HtmlTableRow row;
        HtmlTableCell cell;

        foreach (var invalidCompany in mailMessageObject.InvalidCompanies)
        {
            row = new HtmlTableRow();
            cell = new HtmlTableCell();
            cell.InnerText = invalidCompany.BusinessName;
            row.Cells.Add(cell);
            cell.InnerText = invalidCompany.SwiftBIC;
            row.Cells.Add(cell);
            cell.InnerText = invalidCompany.IBAN;
            row.Cells.Add(cell);
            table.Rows.Add(row);
        }
    }
    using (var sw = new StringWriter())
    {
        table.RenderControl(new HtmlTextWriter(sw));
        html = sw.ToString();
    }

    mailMessage.AppendFormat(html);
    return mailMessage.ToString();
}

At the end I want to return text version of created HTML table.
The problem is that I have much more properties than those 3 (BusinessName, SwiftBIC and IBAN) and plus I have one more list of objects inside of mailMessageObject, so the code would be terrible.

Anybody has an idea how to solve this in simpler and cleaner way?

Body:
I would just like to supplement Steve Harris' answer with a class library that is a little more built out. His answer is a totally elegant solution that made a windows service I was creating not have to reference System.Web for no good reason!

Classes Defined:

  public static class Html
  {
    public class Table : HtmlBase, IDisposable
    {
      public Table(StringBuilder sb, string classAttributes = "", string id = "") : base(sb)
      {
        Append("<table");
        AddOptionalAttributes(classAttributes, id);
      }

      public void StartHead(string classAttributes = "", string id = "")
      {
        Append("<thead");
        AddOptionalAttributes(classAttributes, id);
      }

      public void EndHead()
      {
        Append("</thead>");
      }

      public void StartFoot(string classAttributes = "", string id = "")
      {
        Append("<tfoot");
        AddOptionalAttributes(classAttributes, id);
      }

      public void EndFoot()
      {
        Append("</tfoot>");
      }

      public void StartBody(string classAttributes = "", string id = "")
      {
        Append("<tbody");
        AddOptionalAttributes(classAttributes, id);
      }

      public void EndBody()
      {
        Append("</tbody>");
      }

      public void Dispose()
      {
        Append("</table>");
      }

      public Row AddRow(string classAttributes = "", string id = "")
      {
        return new Row(GetBuilder(), classAttributes, id);
      }
    }

    public class Row : HtmlBase, IDisposable
    {
      public Row(StringBuilder sb, string classAttributes = "", string id = "") : base(sb)
      {
        Append("<tr");
        AddOptionalAttributes(classAttributes, id);
      }
      public void Dispose()
      {
        Append("</tr>");
      }
      public void AddCell(string innerText, string classAttributes = "", string id = "", string colSpan = "")
      {
        Append("<td");
        AddOptionalAttributes(classAttributes, id, colSpan);
        Append(innerText);
        Append("</td>");
      }
    }

    public abstract class HtmlBase
    {
      private StringBuilder _sb;

      protected HtmlBase(StringBuilder sb)
      {
        _sb = sb;
      }

      public StringBuilder GetBuilder()
      {
        return _sb;
      }

      protected void Append(string toAppend)
      {
        _sb.Append(toAppend);
      }

      protected void AddOptionalAttributes(string className = "", string id = "", string colSpan = "")
      {

        if (!id.IsNullOrEmpty())
        {
          _sb.Append($" id=\"{id}\"");
        }
        if (!className.IsNullOrEmpty())
        {
          _sb.Append($" class=\"{className}\"");
        }
        if (!colSpan.IsNullOrEmpty())
        {
          _sb.Append($" colspan=\"{colSpan}\"");
        }
        _sb.Append(">");
      }
    }
  }

Usage:

StringBuilder sb = new StringBuilder();
      using (Html.Table table = new Html.Table(sb, id: "some-id"))
      {
        table.StartHead();
        using (var thead = table.AddRow())
        {
          thead.AddCell("Category Description");
          thead.AddCell("Item Description");
          thead.AddCell("Due Date");
          thead.AddCell("Amount Budgeted");
          thead.AddCell("Amount Remaining");
        }
        table.EndHead();
        table.StartBody();
        foreach (var alert in alertsForUser)
        {
          using (var tr = table.AddRow(classAttributes: "someattributes"))
          {
           tr.AddCell(alert.ExtendedInfo.CategoryDescription);
            tr.AddCell(alert.ExtendedInfo.ItemDescription);
            tr.AddCell(alert.ExtendedInfo.DueDate.ToShortDateString());
            tr.AddCell(alert.ExtendedInfo.AmountBudgeted.ToString("C"));
            tr.AddCell(alert.ExtendedInfo.ItemRemaining.ToString("C"));
          }
        }
        table.EndBody();
      }
      return sb.ToString();


问:
how to write a systemd service file for crate
I want to set crate boot with the redhat,so I write a systemd service file for crate:

crate version: 1.1.2

following is crate.service:

```<code>[Unit]
Description=crate daemon
After=network.target
[Service]
Type=forking
ExecStart=/usr/bin/su - hadmin -c '/home/hadmin/aisinofp/crate/bin/crate.sh start'
ExecStop=/usr/bin/su - hadmin -c '/home/hadmin/aisinofp/crate/bin/crate.sh stop'
Restart=always
[Install]
WantedBy=multi-user.target
</code>```

the crate.sh is:

```<code>#!/bin/bash

source /home/hadmin/myproject/conf/env.sh
if [ "$1" = "start" ]
then
$CRATE_HOME/bin/crate -d
elif [ "$1" = "stop" ]
then
pid=$(ps -ef|grep io.crate.bootstrap.CrateDB |grep jar |awk '{print $2}')
echo "KILLING cratedb PROCESS "$pid
kill -9 $pid
fi
</code>```

the env.sh is:

```<code>#!/bin/bash

# set ulimit
#ulimit -n 655360

export JAVA_HOME=/usr/java/default
export JRE_HOME=/usr/java/default
PATH=$JAVA_HOME/bin:$PATH

# environment for all Projects
export TD_BASE=/home/hadmin
export TD_HOME=$TD_BASE/myproject
export TD_DATA=$TD_BASE/data

# zookeeper environment
export ZOO_HOME=$TD_BASE/zookeeper
export ZOO_LOG_DIR=$ZOO_HOME/logs
PATH=$ZOO_HOME/bin:$PATH

# cratedb environment
export CRATE_HEAP_SIZE=4g
export CRATE_HOME=/home/hadmin/crate
PATH=$CRATE_HOME/bin:$PATH

# activemq environment
export activemq_data=/home/hadmin/data/activemq
export activemq_base=/home/hadmin/activemq
export activemq_conf=$activemq_base/conf
PATH=$activemq_base/bin:$PATH

export PATH
</code>```

when I finish writing these files, I start using "systemctl start crate.service",but I got messages like this in /var/logs/message:

I can see that the crate daemon has being restarting all the time, I don't know why it would be killed after started

thanks

答:
Crate already provides an official RPM package for Red Hat Linux that uses systemd. There is no need to write your own service file.

See documentation: https://crate.io/docs/install/local/linux/#red-hat

Body:
I want to set crate boot with the redhat,so I write a systemd service file for crate:

crate version: 1.1.2

following is crate.service:

[Unit]
Description=crate daemon
After=network.target
[Service]
Type=forking
ExecStart=/usr/bin/su - hadmin -c '/home/hadmin/aisinofp/crate/bin/crate.sh start'
ExecStop=/usr/bin/su - hadmin -c '/home/hadmin/aisinofp/crate/bin/crate.sh stop'
Restart=always
[Install]
WantedBy=multi-user.target

the crate.sh is:

#!/bin/bash

source /home/hadmin/myproject/conf/env.sh
if [ "$1" = "start" ]
then
$CRATE_HOME/bin/crate -d
elif [ "$1" = "stop" ]
then
pid=$(ps -ef|grep io.crate.bootstrap.CrateDB |grep jar |awk '{print $2}')
echo "KILLING cratedb PROCESS "$pid
kill -9 $pid
fi

the env.sh is:

#!/bin/bash

# set ulimit
#ulimit -n 655360

export JAVA_HOME=/usr/java/default
export JRE_HOME=/usr/java/default
PATH=$JAVA_HOME/bin:$PATH

# environment for all Projects
export TD_BASE=/home/hadmin
export TD_HOME=$TD_BASE/myproject
export TD_DATA=$TD_BASE/data

# zookeeper environment
export ZOO_HOME=$TD_BASE/zookeeper
export ZOO_LOG_DIR=$ZOO_HOME/logs
PATH=$ZOO_HOME/bin:$PATH

# cratedb environment
export CRATE_HEAP_SIZE=4g
export CRATE_HOME=/home/hadmin/crate
PATH=$CRATE_HOME/bin:$PATH

# activemq environment
export activemq_data=/home/hadmin/data/activemq
export activemq_base=/home/hadmin/activemq
export activemq_conf=$activemq_base/conf
PATH=$activemq_base/bin:$PATH

export PATH

when I finish writing these files, I start using "systemctl start crate.service",but I got messages like this in /var/logs/message:

I can see that the crate daemon has being restarting all the time, I don't know why it would be killed after started

thanks


问:
how to plot pie chart in R
I have following dataframe in R and want to make pie chart out of it

```<code>berth_day count
Friday    74
Monday    95
Saturday  126
Sunday    114
Thursday  62
Tuesday   85
</code>```

I am doing following in R

```<code>ggplot(aes(x=berth_day, y=count))+
geom_bar(width =1)
+ coord_polar(theta = "y")
</code>```

But,it gives me following error

```<code>> ggplot(aes(x=berth_day, y=count))+
+   geom_bar(width =1)
Error: ggplot2 doesn't know how to deal with data of class uneval
>   + coord_polar(theta = "y")
Error in +coord_polar(theta = "y") : invalid argument to unary operator
</code>```

How can I do it in R ?

答:
It is not clear whether the OP's data comes from a pipe or forgot to add in the ggplot call

```<code>df1N <- df1 %>% mutate(berth_day = factor(berth_day))

ggplot(df1N,  aes(x=berth_day, y=count, fill = berth_day))+
    geom_bar(width =1, stat = "identity")+
    coord_polar(theta = "y")
</code>```

As @GGamba said in the comments, geom_bar is deprecated instead use geom_col

```<code>ggplot(df1N,  aes(x=berth_day, y=count, fill = berth_day))+
    geom_col(width=1)+
    coord_polar(theta = "y")
</code>```

Title: how to plot pie chart in R

Body:
I have following dataframe in R and want to make pie chart out of it

berth_day count
Friday    74
Monday    95
Saturday  126
Sunday    114
Thursday  62
Tuesday   85

I am doing following in R

ggplot(aes(x=berth_day, y=count))+
geom_bar(width =1)
+ coord_polar(theta = "y")

But,it gives me following error

> ggplot(aes(x=berth_day, y=count))+
+   geom_bar(width =1)
Error: ggplot2 doesn't know how to deal with data of class uneval
>   + coord_polar(theta = "y")
Error in +coord_polar(theta = "y") : invalid argument to unary operator

How can I do it in R ?

Body:
It is not clear whether the OP's data comes from a pipe or forgot to add in the ggplot call

df1N <- df1 %>% mutate(berth_day = factor(berth_day))

ggplot(df1N,  aes(x=berth_day, y=count, fill = berth_day))+
    geom_bar(width =1, stat = "identity")+
    coord_polar(theta = "y")

As @GGamba said in the comments, geom_bar is deprecated instead use geom_col

ggplot(df1N,  aes(x=berth_day, y=count, fill = berth_day))+
    geom_col(width=1)+
    coord_polar(theta = "y")


问:
Database Design - Optional Bit Fields
I'm building a database that will be used to store Questions and Answers.  There are varying Question types that deal so far with a DateTime answer, Free Text, DropDownList, and some that link to other tables in the database.  My design question is this:  Some Question types have other boolean attributes that are unique to that type.  Is it better to have the boolean column in the generic Questions table or create some sort of Flag table for each question type?

As an example, a DropDownList Question might have a boolean attribute to tell whether or not to display a TextBox when a value "Other" is selected, but a Free Text Question would have no use for this.

Thanks heaps

EDIT:

I guess it seems to be boiling down to is it better to store unused columns in a generic Questions table to extend out for each Question type and have lots of keys back to the Question table using Views to access the data for various Question types.

答:
I am mulling this over as a possible solution, seems more abstracted to me and allows for the most future extension.</p>

```<code>CREATE TABLE dbo.QuestionTypes
(
    Id      INT             IDENTITY(1, 1) PRIMARY KEY,
    Type    VARCHAR(256)    NOT NULL
);

CREATE TABLE dbo.TypeSpecificFlags
(
    Id        INT             IDENTITY(1, 1) PRIMARY KEY,
    TypeId    INT             REFERENCES dbo.QuestionTypes(Id) NOT NULL,
    Flag      VARCHAR(256)    NOT NULL
)

CREATE TABLE dbo.Questions
(
    Id            INT             IDENTITY(1, 1) PRIMARY KEY,
    Name          VARCHAR(256)    NOT NULL,
    ShortName     VARCHAR(32),
    TypeId        INT             REFERENCES QuestionTypes(Id) NOT NULL,
    AllowNulls    BIT             NOT NULL DEFAULT 1,
    Sort          INT
);

CREATE TABLE dbo.QuestionsFlags
(
    Id            INT    IDENTITY(1, 1) PRIMARY KEY,
    QuestionId    INT    REFERENCES dbo.Questions(Id) NOT NULL,
    FlagId        INT    REFERENCES dbo.TypeSpecificFlags(Id) NOT NULL,
    Answer        BIT    NOT NULL
);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Database Design - Optional Bit Fields

Body:
I am mulling this over as a possible solution, seems more abstracted to me and allows for the most future extension.

CREATE TABLE dbo.QuestionTypes
(
    Id      INT             IDENTITY(1, 1) PRIMARY KEY,
    Type    VARCHAR(256)    NOT NULL
);

CREATE TABLE dbo.TypeSpecificFlags
(
    Id        INT             IDENTITY(1, 1) PRIMARY KEY,
    TypeId    INT             REFERENCES dbo.QuestionTypes(Id) NOT NULL,
    Flag      VARCHAR(256)    NOT NULL
)

CREATE TABLE dbo.Questions
(
    Id            INT             IDENTITY(1, 1) PRIMARY KEY,
    Name          VARCHAR(256)    NOT NULL,
    ShortName     VARCHAR(32),
    TypeId        INT             REFERENCES QuestionTypes(Id) NOT NULL,
    AllowNulls    BIT             NOT NULL DEFAULT 1,
    Sort          INT
);

CREATE TABLE dbo.QuestionsFlags
(
    Id            INT    IDENTITY(1, 1) PRIMARY KEY,
    QuestionId    INT    REFERENCES dbo.Questions(Id) NOT NULL,
    FlagId        INT    REFERENCES dbo.TypeSpecificFlags(Id) NOT NULL,
    Answer        BIT    NOT NULL
);


问:
Image not getting empty when cancel is clicked on file input?
Im using Croppie plugin for this crop image function. Input text field becomes empty and the image is not getting empty when a user clicks the cancel on file input. I want to remove the image too when a user clicks the cancel button on file input.

DEMO

HTML

```<code><form action="test-image.php" id="form" method="post">
  <input type="file" id="upload" value="Choose a file">
  <div id="upload-demo"></div>
  <input type="hidden" id="imagebase64" name="imagebase64">
  <a href="#" class="upload-result">Send</a>
</form>
</code>```

JS

```<code>$(document).ready(function() {
  var $uploadCrop;

  function readFile(input) {
    if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function(e) {
        $uploadCrop.croppie('bind', {
          url: e.target.result
        });
        $('.upload-demo').addClass('ready');
      }
      reader.readAsDataURL(input.files[0]);
    }
  }
  $uploadCrop = $('#upload-demo').croppie({
    viewport: {
      width: 200,
      height: 200,
      type: 'circle'
    },
    boundary: {
      width: 300,
      height: 300
    }
  });
  $('#upload').on('change', function() {
    readFile(this);
  });
  $('.upload-result').on('click', function(ev) {
    $uploadCrop.croppie('result', {
      type: 'canvas',
      size: 'original'
    }).then(function(resp) {
      $('#imagebase64').val(resp);
      $('#form').submit();
    });
  });
});
</code>```

答:
THis would help you

$( document ).ready(function() {
    var $uploadCrop;

    function readFile(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $uploadCrop.croppie('bind', {
                    url: e.target.result
                });
                $('.upload-demo').addClass('ready');
            }
            reader.readAsDataURL(input.files[0]);
        }
    }

    $uploadCrop = $('#upload-demo').croppie({
        viewport: {
            width: 200,
            height: 200,
            type: 'circle'
        },
        boundary: {
            width: 300,
            height: 300
        }
    });

    $('#upload').on('change', function () { readFile(this); });
    $('.upload-result').on('click', function (ev) {
        $uploadCrop.croppie('result', {
            type: 'canvas',
            size: 'original'
        }).then(function (resp) {
            $('#imagebase64').val(resp);
            $('#form').submit();
        });
    });

    $('.reset').on('click', function(){
       $('input').val('');
       $('.cr-viewport').html('');
       $('.cr-image').attr('src','');
    });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="test-image.php" id="form" method="post">
<input type="file" id="upload" value="Choose a file">
<div id="upload-demo"></div>
<input type="hidden" id="imagebase64" name="imagebase64">
Send
</form>

cancel</code>```

Body:
Im using Croppie plugin for this crop image function. Input text field becomes empty and the image is not getting empty when a user clicks the cancel on file input. I want to remove the image too when a user clicks the cancel button on file input.

DEMO

HTML

<form action="test-image.php" id="form" method="post">
  <input type="file" id="upload" value="Choose a file">

  <input type="hidden" id="imagebase64" name="imagebase64">
  Send
</form>

JS

$(document).ready(function() {
  var $uploadCrop;

  function readFile(input) {
    if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function(e) {
        $uploadCrop.croppie('bind', {
          url: e.target.result
        });
        $('.upload-demo').addClass('ready');
      }
      reader.readAsDataURL(input.files[0]);
    }
  }
  $uploadCrop = $('#upload-demo').croppie({
    viewport: {
      width: 200,
      height: 200,
      type: 'circle'
    },
    boundary: {
      width: 300,
      height: 300
    }
  });
  $('#upload').on('change', function() {
    readFile(this);
  });
  $('.upload-result').on('click', function(ev) {
    $uploadCrop.croppie('result', {
      type: 'canvas',
      size: 'original'
    }).then(function(resp) {
      $('#imagebase64').val(resp);
      $('#form').submit();
    });
  });
});

Body:
THis would help you

$( document ).ready(function() {
    var $uploadCrop;

    function readFile(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $uploadCrop.croppie('bind', {
                    url: e.target.result
                });
                $('.upload-demo').addClass('ready');
            }
            reader.readAsDataURL(input.files[0]);
        }
    }

    $uploadCrop = $('#upload-demo').croppie({
        viewport: {
            width: 200,
            height: 200,
            type: 'circle'
        },
        boundary: {
            width: 300,
            height: 300
        }
    });

    $('#upload').on('change', function () { readFile(this); });
    $('.upload-result').on('click', function (ev) {
        $uploadCrop.croppie('result', {
            type: 'canvas',
            size: 'original'
        }).then(function (resp) {
            $('#imagebase64').val(resp);
            $('#form').submit();
        });
    });

    $('.reset').on('click', function(){
       $('input').val('');
       $('.cr-viewport').html('');
       $('.cr-image').attr('src','');
    });

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="test-image.php" id="form" method="post">
<input type="file" id="upload" value="Choose a file">
<div id="upload-demo"></div>
<input type="hidden" id="imagebase64" name="imagebase64">
<a href="#" class="upload-result">Send</a>
</form>

<a class="reset">cancel</a>


问:
Two rows in one in SQL server
The answer is too close, Thanks
But
The problem is that if too many records to be entered

```<code>           |    id   |    name   |    age    |   Tel
------------------------------------------
      1    |    1   |   Frank   |    40     |   null
      2    |    1   |   null    |    50     |   7834xx
      3    |    1   |   Alex    |    null   |   null
      4    |    1   |   null    |    20     |   null
      5    |    2   |   James   |    null   |   4121xx
</code>```

Query return the Maximum value
Like:

```<code>           |    id   |   name    |    age    |   Tel
------------------------------------------
      1    |    1    |   Frank   |    50     |  7834xx
</code>```

i need Select Query like this:

```<code>           |    id   |   name    |    age    |   Tel
------------------------------------------
      1    |    1    |   Alex    |    20     |  7834xx
</code>```

what do I do? Plz?

答:
thanks for answering and helping.
i find this query:

SELECT TOP 10

    (SELECT top(1) name FROM test1 where id=1 and name is not null order by autoID desc) as name
    ,(SELECT top(1) age FROM test1 where id=1 and age is not null order by autoID desc) as Age
,(SELECT top(1) Tel FROM test1 where id=1 and Tel is not null order by autoID desc) as Telephon
    FROM [dbo].[test1]
    group by id

its worked !!!
but i thing there are another Easy Way , maybe like this:

Select Id, NotNull(name) as [Name], NotNull(age) as Age, NotNull(Tel) as Tel
 from yourtable Group by Id

???

Title: Two rows in one in SQL server

Body:
The answer is too close, Thanks
But
The problem is that if too many records to be entered

           |    id   |    name   |    age    |   Tel
------------------------------------------
      1    |    1   |   Frank   |    40     |   null
      2    |    1   |   null    |    50     |   7834xx
      3    |    1   |   Alex    |    null   |   null
      4    |    1   |   null    |    20     |   null
      5    |    2   |   James   |    null   |   4121xx

Query return the Maximum value
Like:

           |    id   |   name    |    age    |   Tel
------------------------------------------
      1    |    1    |   Frank   |    50     |  7834xx

i need Select Query like this:

           |    id   |   name    |    age    |   Tel
------------------------------------------
      1    |    1    |   Alex    |    20     |  7834xx

what do I do? Plz?


问:
why use wireshark capture a c# ssl server/client program got TCP package?
I have write a ssl server/client program:

server:

```<code>static void Main(string[] args)
{
    var store = new X509Store(StoreName.Root);
    store.Open(OpenFlags.ReadWrite);
    var certs = store.Certificates.Find(X509FindType.FindBySubjectName, "TestServer", false);
    var x509 = certs[0];

    var listener = new TcpListener(IPAddress.Parse("192.168.97.2"), 2000);
    listener.Start();

    while (true)
    {
      var client = listener.AcceptTcpClient();
      var sslStream = new SslStream(client.GetStream(), false);
      sslStream.AuthenticateAsServer(x509, false, SslProtocols.Tls, true);
      Console.WriteLine(ReadMessage(sslStream));
    }
}
</code>```

client:

```<code>static void Main(string[] args)
{
  var client = new TcpClient("192.168.97.2",2000);
  var ssl = new SslStream(client.GetStream(), false, new    RemoteCertificateValidationCallback(ValidateServerCertificate), null);
  ssl.AuthenticateAsClient("TestServer");
  byte[] message = Encoding.UTF8.GetBytes("abc");
  ssl.Write(message);
  ssl.Flush();
  client.Close();
}
</code>```

it work's fine,but when I try to capture network packages by wireshark,I got TCP package between server and client.

I think I should got TLS package,I don't know why.

答:
SSL handshake is in application layer not TCP/IP layer

and as you know wireshark monitors TCP/IP layer, So you can see Tcp process of handshake with some ambiguous data because it is encrypted with SSL public or private key.
So you can not monitor exact SSL handshake process with Wireshark(Although I work so many time with SSL I can not find any tools for monitoring exactly ssl handshake process).
good luck.

Body:
I have write a ssl server/client program:

server:

static void Main(string[] args)
{
    var store = new X509Store(StoreName.Root);
    store.Open(OpenFlags.ReadWrite);
    var certs = store.Certificates.Find(X509FindType.FindBySubjectName, "TestServer", false);
    var x509 = certs[0];

    var listener = new TcpListener(IPAddress.Parse("192.168.97.2"), 2000);
    listener.Start();

    while (true)
    {
      var client = listener.AcceptTcpClient();
      var sslStream = new SslStream(client.GetStream(), false);
      sslStream.AuthenticateAsServer(x509, false, SslProtocols.Tls, true);
      Console.WriteLine(ReadMessage(sslStream));
    }
}

client:

static void Main(string[] args)
{
  var client = new TcpClient("192.168.97.2",2000);
  var ssl = new SslStream(client.GetStream(), false, new    RemoteCertificateValidationCallback(ValidateServerCertificate), null);
  ssl.AuthenticateAsClient("TestServer");
  byte[] message = Encoding.UTF8.GetBytes("abc");
  ssl.Write(message);
  ssl.Flush();
  client.Close();
}

it work's fine,but when I try to capture network packages by wireshark,I got TCP package between server and client.

I think I should got TLS package,I don't know why.


问:
Symbol addresses during load-time linking vs run-time linking in Linux
I am trying to understand the difference in the mechanisms underlying load-time linking (using gcc -l) versus run-time linking (using dlopen(), dlsym()) of dynamic libraries in Linux, and how these mechanisms affect the state of the library and the addresses of its symbols.

The experiment

I have three simple files:

libhello.c:

```<code>int var;
int func() {
    return 7;
}
</code>```

libhello.h:

```<code>extern int var;
int func();
</code>```

main.c:

```<code>#include <inttypes.h>
#include <stdio.h>
#include <stdint.h>
#include <dlfcn.h>
#include "libhello.h"

int main() {
    void* h = dlopen("libhello.so", RTLD_NOW);
    printf("Address  Load-time linking    Run-time linking\n");
    printf("-------  -----------------    ----------------\n");
    printf("&var     0x%016" PRIxPTR "   0x%016" PRIxPTR "\n", (uintptr_t)&var , (uintptr_t)dlsym(h, "var" ));
    printf("&func    0x%016" PRIxPTR "   0x%016" PRIxPTR "\n", (uintptr_t)&func, (uintptr_t)dlsym(h, "func"));
}
</code>```

I compile libhello.c with the command gcc -shared -o libhello.so -fPIC libhello.c

I compile main.c with the command gcc main.c -L. -lhello -ldl

The observation

Running the main.c executable prints something like this:

```<code>Address  Load-time linking    Run-time linking
-------  -----------------    ----------------
&var     0x0000000000601060   0x00007fdb4acb1034
&func    0x0000000000400700   0x00007fdb4aab0695
</code>```

The load-time linking addresses remain the same, but the run-time linking addresses change every run.

The questions

Why do the run-time addresses change every run? Do they change due to Address space layout randomization?

If this is the case, why don't addresses change for load-time linking? Isn't load-time linking vulnerable to the same attacks that address randomization aims to protect against?

In the above program, the same library is loaded twice - once at load-time and then at run-time using dlopen(). The second load does not copy the state of the first load. I.e. if the value of var is changed before dlopen(), this value isn't reflected in the version of var loaded via dlsym(). Is there any way to retain this state during the second load?

Body:
I am trying to understand the difference in the mechanisms underlying load-time linking (using gcc -l) versus run-time linking (using dlopen(), dlsym()) of dynamic libraries in Linux, and how these mechanisms affect the state of the library and the addresses of its symbols.

The experiment

I have three simple files:

libhello.c:

int var;
int func() {
    return 7;
}

libhello.h:

extern int var;
int func();

main.c:

#include <inttypes.h>
#include <stdio.h>
#include <stdint.h>
#include <dlfcn.h>
#include "libhello.h"

int main() {
    void* h = dlopen("libhello.so", RTLD_NOW);
    printf("Address  Load-time linking    Run-time linking\n");
    printf("-------  -----------------    ----------------\n");
    printf("&var     0x%016" PRIxPTR "   0x%016" PRIxPTR "\n", (uintptr_t)&var , (uintptr_t)dlsym(h, "var" ));
    printf("&func    0x%016" PRIxPTR "   0x%016" PRIxPTR "\n", (uintptr_t)&func, (uintptr_t)dlsym(h, "func"));
}

I compile libhello.c with the command gcc -shared -o libhello.so -fPIC libhello.c

I compile main.c with the command gcc main.c -L. -lhello -ldl

The observation

Running the main.c executable prints something like this:

Address  Load-time linking    Run-time linking
-------  -----------------    ----------------
&var     0x0000000000601060   0x00007fdb4acb1034
&func    0x0000000000400700   0x00007fdb4aab0695

The load-time linking addresses remain the same, but the run-time linking addresses change every run.

The questions

Why do the run-time addresses change every run? Do they change due to Address space layout randomization?

If this is the case, why don't addresses change for load-time linking? Isn't load-time linking vulnerable to the same attacks that address randomization aims to protect against?

In the above program, the same library is loaded twice - once at load-time and then at run-time using dlopen(). The second load does not copy the state of the first load. I.e. if the value of var is changed before dlopen(), this value isn't reflected in the version of var loaded via dlsym(). Is there any way to retain this state during the second load?

Body:
I hope this hint can help you.

The main program is an ELF file, and need to relocation. And the relocation occurs at the loading time. So the var and func address in the main program has relocated before you call the dlsym.

the dlsym func return the symbol address in the OS ad runtime without relocation， this address is in the SO mapping region.

And you can use the mapping info to find the different:

wutiejun@linux-00343520:~/Temp/sotest> LD_LIBRARY_PATH=./ ./test
Address  Load-time linking    Run-time linking
-------  -----------------    ----------------
&var     0x000000000804a028   0x00000000f77a9014
&func    0x0000000008048568   0x00000000f77a744c

wutiejun@linux-00343520:~> cat /proc/7137/maps
08048000-08049000 r-xp 00000000 08:02 46924194                           /home/wutiejun/Temp/sotest/test
08049000-0804a000 r--p 00000000 08:02 46924194                           /home/wutiejun/Temp/sotest/test
0804a000-0804b000 rw-p 00001000 08:02 46924194                           /home/wutiejun/Temp/sotest/test
0804b000-0806c000 rw-p 00000000 00:00 0                                  [heap]
f75d3000-f7736000 r-xp 00000000 08:02 68395411                           /lib/libc-2.11.3.so
f7736000-f7738000 r--p 00162000 08:02 68395411                           /lib/libc-2.11.3.so
f7738000-f7739000 rw-p 00164000 08:02 68395411                           /lib/libc-2.11.3.so
f7739000-f773c000 rw-p 00000000 00:00 0
f773c000-f7740000 r-xp 00000000 08:02 68395554                           /lib/libachk.so
f7740000-f7741000 r--p 00003000 08:02 68395554                           /lib/libachk.so
f7741000-f7742000 rw-p 00004000 08:02 68395554                           /lib/libachk.so
f777a000-f777c000 rw-p 00000000 00:00 0
f777c000-f7784000 r-xp 00000000 08:02 68395441                           /lib/librt-2.11.3.so
f7784000-f7785000 r--p 00007000 08:02 68395441                           /lib/librt-2.11.3.so
f7785000-f7786000 rw-p 00008000 08:02 68395441                           /lib/librt-2.11.3.so
f7786000-f779d000 r-xp 00000000 08:02 68395437                           /lib/libpthread-2.11.3.so
f779d000-f779e000 r--p 00016000 08:02 68395437                           /lib/libpthread-2.11.3.so
f779e000-f779f000 rw-p 00017000 08:02 68395437                           /lib/libpthread-2.11.3.so
f779f000-f77a2000 rw-p 00000000 00:00 0
f77a2000-f77a5000 r-xp 00000000 08:02 68395417                           /lib/libdl-2.11.3.so
f77a5000-f77a6000 r--p 00002000 08:02 68395417                           /lib/libdl-2.11.3.so
f77a6000-f77a7000 rw-p 00003000 08:02 68395417                           /lib/libdl-2.11.3.so
f77a7000-f77a8000 r-xp 00000000 08:02 46924193                           /home/wutiejun/Temp/sotest/libhello.so
f77a8000-f77a9000 r--p 00000000 08:02 46924193                           /home/wutiejun/Temp/sotest/libhello.so
f77a9000-f77aa000 rw-p 00001000 08:02 46924193                           /home/wutiejun/Temp/sotest/libhello.so
f77aa000-f77ab000 rw-p 00000000 00:00 0
f77ab000-f77ca000 r-xp 00000000 08:02 68395404                           /lib/ld-2.11.3.so
f77ca000-f77cb000 r--p 0001e000 08:02 68395404                           /lib/ld-2.11.3.so
f77cb000-f77cc000 rw-p 0001f000 08:02 68395404                           /lib/ld-2.11.3.so
ffd99000-ffdba000 rw-p 00000000 00:00 0                                  [stack]
ffffe000-fffff000 r-xp 00000000 00:00 0                                  [vdso]
wutiejun@linux-00343520:~>


问:
Cannot perform operation ".isEmpty" on org.datanucleus.store.rdbms.sql.expression.SubqueryExpression
I have a subquery that looks like this:
(It was rewrited from contains, because of perfomance issues)

...(select  from RecoLock lock where mpiSubscriptionId == this.mpiSubscriptionId).isEmpty())

And datanucleus throws me a

Cannot perform operation ".isEmpty" on org.datanucleus.store.rdbms.sql.expression.SubqueryExpression

But in datanucleus documentation there are examples where similiar code workds well. What am I doing wrong?

datanucleus version is 4.1.0

答:
From what I see of the DataNucleus JDOQL support for {subquery}.isEmpty() this is only supported from v5.0.

If using v4.x (or earlier) you can transform your query to do

```<code>... (select COUNT(lock) from RecoLock lock where mpiSubscriptionId == this.mpiSubscriptionId) == 0)
</code>```

which should equate to the same thing as "size == 0" (i.e "empty")

Body:
From what I see of the DataNucleus JDOQL support for {subquery}.isEmpty() this is only supported from v5.0.

If using v4.x (or earlier) you can transform your query to do

... (select COUNT(lock) from RecoLock lock where mpiSubscriptionId == this.mpiSubscriptionId) == 0)

which should equate to the same thing as "size == 0" (i.e "empty")


答:
Yes, it's ASLR.

Because PIE (Position Independent Executables) is quite expensive (in performance). So many systems do the tradeoff where they randomize libraries because they have to be position independent anyway, but don't randomize executables because it costs too much performance. Yes, it is more vulnerable this way, but most security is a tradeoff.

Yes, don't search symbols through the handle, instead use RTLD_DEFAULT. It's generally a bad idea to have two instances of the same dynamic library loaded like this. Some systems can just skip loading a library in dlopen if they know the same library is already loaded and what the dynamic linker considers "the same library" can change depending on your library path. You're very much in the territory of quite badly/weakly defined behavior here that has evolved over the years more to deal with bugs and problems and less through deliberate design.

Note that RTLD_DEFAULT will return the address of the symbol in the main executable or the first (load time) loaded dynamic library and the dynamically loaded library will be ignored.

Also, another thing worth keeping in mind is that if you reference var in libhello it will always resolve the symbol from the load time version of the library even in the dlopen:ed version. I modified func to return var and added this code to your example code:

```<code>int (*fn)(void) = dlsym(h, "func");
int *vp;

var = 17;
printf("%d %d %d %p\n", var, func(), fn(), vp);

vp = dlsym(h, "var");
*vp = 4711;
printf("%d %d %d %p\n", var, func(), fn(), vp);

vp = dlsym(RTLD_DEFAULT, "var");
*vp = 42;
printf("%d %d %d %p\n", var, func(), fn(), vp);
</code>```

and get this output:

```<code>$ gcc main.c -L. -lhello -ldl && LD_LIBRARY_PATH=. ./a.out
17 17 17 0x7f2e11bec02c
17 17 17 0x7f2e11bec02c
42 42 42 0x601054
Address  Load-time linking    Run-time linking
-------  -----------------    ----------------
&var     0x0000000000601054   0x0000000000601054
&func    0x0000000000400700   0x0000000000400700
</code>```

Title: Symbol addresses during load-time linking vs run-time linking in Linux

Body:
Yes, it's ASLR.

Because PIE (Position Independent Executables) is quite expensive (in performance). So many systems do the tradeoff where they randomize libraries because they have to be position independent anyway, but don't randomize executables because it costs too much performance. Yes, it is more vulnerable this way, but most security is a tradeoff.

Yes, don't search symbols through the handle, instead use RTLD_DEFAULT. It's generally a bad idea to have two instances of the same dynamic library loaded like this. Some systems can just skip loading a library in dlopen if they know the same library is already loaded and what the dynamic linker considers "the same library" can change depending on your library path. You're very much in the territory of quite badly/weakly defined behavior here that has evolved over the years more to deal with bugs and problems and less through deliberate design.

Note that RTLD_DEFAULT will return the address of the symbol in the main executable or the first (load time) loaded dynamic library and the dynamically loaded library will be ignored.

Also, another thing worth keeping in mind is that if you reference var in libhello it will always resolve the symbol from the load time version of the library even in the dlopen:ed version. I modified func to return var and added this code to your example code:

int (*fn)(void) = dlsym(h, "func");
int *vp;

var = 17;
printf("%d %d %d %p\n", var, func(), fn(), vp);

vp = dlsym(h, "var");
*vp = 4711;
printf("%d %d %d %p\n", var, func(), fn(), vp);

vp = dlsym(RTLD_DEFAULT, "var");
*vp = 42;
printf("%d %d %d %p\n", var, func(), fn(), vp);

and get this output:

$ gcc main.c -L. -lhello -ldl && LD_LIBRARY_PATH=. ./a.out
17 17 17 0x7f2e11bec02c
17 17 17 0x7f2e11bec02c
42 42 42 0x601054
Address  Load-time linking    Run-time linking
-------  -----------------    ----------------
&var     0x0000000000601054   0x0000000000601054
&func    0x0000000000400700   0x0000000000400700


问:
error: incompatible types: Object cannot be converted to MyClass
I want to use @Parcel annotation instead of implementing Parcelable.

So my class is :

```<code>@Parcel
public class UserSkillSpec {
    private final String TAG = getClass().getSimpleName();

    private Skill skill;
    private int endorses = 0;
    private boolean endorsed = false;
    private List<User> endorsers = new LinkedList<>();
    private int proficiency = 0;
    private boolean verified = false;

    @ParcelConstructor
    public UserSkillSpec(Skill skill, int proficiency) {
        this.skill = skill;
        this.proficiency = proficiency;
    }

}
</code>```

when I want to build project, this error will appears in MessageBox

```<code>Error:(62, 109) error: incompatible types: Object cannot be converted to User
</code>```

and User source code is :

```<code>@Parcel
@RealmClass
public class User extends RealmObject {
    @PrimaryKey
    private String id;

    private String firstName;
    private String lastName;
    private String name;
   //and something else

    public User() {
    }
}
</code>```

Apparently this issue related to List.

How can I fix my problem?

Thanks.

EDIT1:
I changed User class as below code:

```<code>@Parcel(implementations = {UserRealmProxy.class},
        value = Parcel.Serialization.BEAN,
        analyze = {User.class})
@RealmClass
public class User implements RealmModel {
    @PrimaryKey
    private String id;

    private String firstName;
    private String lastName;
    private String name;
    //somethings else

    public User() {
    }
}
</code>```

in automatically generated class UserSkillSpec$$Parcelable by Parceler library,the error happened in for section :

```<code>public static void write(UserSkillSpec userSkillSpec$$1, android.os.Parcel parcel$$1, int flags$$0, IdentityCollection identityMap$$0) {
        int identity$$0 = identityMap$$0 .getKey(userSkillSpec$$1);
        if (identity$$0 != -1) {
            parcel$$1 .writeInt(identity$$0);
        } else {
            parcel$$1 .writeInt(identityMap$$0 .put(userSkillSpec$$1));
            Skill$$Parcelable.write(InjectionUtil.getField(Skill.class, UserSkillSpec.class, userSkillSpec$$1, "skill"), parcel$$1, flags$$0, identityMap$$0);
            parcel$$1 .writeInt(InjectionUtil.getField(int.class, UserSkillSpec.class, userSkillSpec$$1, "proficiency"));
            if (InjectionUtil.getField(List.class, UserSkillSpec.class, userSkillSpec$$1, "endorsers") == null) {
                parcel$$1 .writeInt(-1);
            } else {
                parcel$$1 .writeInt(InjectionUtil.getField(List.class, UserSkillSpec.class, userSkillSpec$$1, "endorsers").size());
                for (User user$$0 : InjectionUtil.getField(List.class, UserSkillSpec.class, userSkillSpec$$1, "endorsers")) {
                    User$$Parcelable.write(user$$0, parcel$$1, flags$$0, identityMap$$0);
                }
            }
            parcel$$1 .writeInt((InjectionUtil.getField(boolean.class, UserSkillSpec.class, userSkillSpec$$1, "verified")? 1 : 0));
            parcel$$1 .writeInt(InjectionUtil.getField(int.class, UserSkillSpec.class, userSkillSpec$$1, "endorses"));
            parcel$$1 .writeString(InjectionUtil.getField(String.class, UserSkillSpec.class, userSkillSpec$$1, "TAG"));
            parcel$$1 .writeInt((InjectionUtil.getField(boolean.class, UserSkillSpec.class, userSkillSpec$$1, "endorsed")? 1 : 0));
        }
    }
</code>```

答:
You should probably use implements over extend for your user, because your parent class is not parcelable.

Tips

You should consider to implement your custom creator like this

Body:
I want to use @Parcel annotation instead of implementing Parcelable.

So my class is :

@Parcel
public class UserSkillSpec {
    private final String TAG = getClass().getSimpleName();

    private Skill skill;
    private int endorses = 0;
    private boolean endorsed = false;
    private List<User> endorsers = new LinkedList<>();
    private int proficiency = 0;
    private boolean verified = false;

    @ParcelConstructor
    public UserSkillSpec(Skill skill, int proficiency) {
        this.skill = skill;
        this.proficiency = proficiency;
    }

}

when I want to build project, this error will appears in MessageBox

Error:(62, 109) error: incompatible types: Object cannot be converted to User

and User source code is :

@Parcel
@RealmClass
public class User extends RealmObject {
    @PrimaryKey
    private String id;

    private String firstName;
    private String lastName;
    private String name;
   //and something else

    public User() {
    }
}

Apparently this issue related to List.

How can I fix my problem?

Thanks.

EDIT1:
I changed User class as below code:

@Parcel(implementations = {UserRealmProxy.class},
        value = Parcel.Serialization.BEAN,
        analyze = {User.class})
@RealmClass
public class User implements RealmModel {
    @PrimaryKey
    private String id;

    private String firstName;
    private String lastName;
    private String name;
    //somethings else

    public User() {
    }
}

in automatically generated class UserSkillSpec$$Parcelable by Parceler library,the error happened in for section :

public static void write(UserSkillSpec userSkillSpec$$1, android.os.Parcel parcel$$1, int flags$$0, IdentityCollection identityMap$$0) {
        int identity$$0 = identityMap$$0 .getKey(userSkillSpec$$1);
        if (identity$$0 != -1) {
            parcel$$1 .writeInt(identity$$0);
        } else {
            parcel$$1 .writeInt(identityMap$$0 .put(userSkillSpec$$1));
            Skill$$Parcelable.write(InjectionUtil.getField(Skill.class, UserSkillSpec.class, userSkillSpec$$1, "skill"), parcel$$1, flags$$0, identityMap$$0);
            parcel$$1 .writeInt(InjectionUtil.getField(int.class, UserSkillSpec.class, userSkillSpec$$1, "proficiency"));
            if (InjectionUtil.getField(List.class, UserSkillSpec.class, userSkillSpec$$1, "endorsers") == null) {
                parcel$$1 .writeInt(-1);
            } else {
                parcel$$1 .writeInt(InjectionUtil.getField(List.class, UserSkillSpec.class, userSkillSpec$$1, "endorsers").size());
                for (User user$$0 : InjectionUtil.getField(List.class, UserSkillSpec.class, userSkillSpec$$1, "endorsers")) {
                    User$$Parcelable.write(user$$0, parcel$$1, flags$$0, identityMap$$0);
                }
            }
            parcel$$1 .writeInt((InjectionUtil.getField(boolean.class, UserSkillSpec.class, userSkillSpec$$1, "verified")? 1 : 0));
            parcel$$1 .writeInt(InjectionUtil.getField(int.class, UserSkillSpec.class, userSkillSpec$$1, "endorses"));
            parcel$$1 .writeString(InjectionUtil.getField(String.class, UserSkillSpec.class, userSkillSpec$$1, "TAG"));
            parcel$$1 .writeInt((InjectionUtil.getField(boolean.class, UserSkillSpec.class, userSkillSpec$$1, "endorsed")? 1 : 0));
        }
    }


问:
Need advice before I develop a bad habit
I have a controller called AuctionsController. In it I have Actions called Index() and AuctionCategoryListing():

```<code>//Used for displaying all auctions.
public ActionResult Index()
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions();
    return View(auctions);
}

//Used for displaying auctions for a single category.
public ActionResult AuctionCategoryListing(string categoryName)
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions()
                       .Where(c => c.Subcategory.Category.Name == categoryName);
    return View("Index", auctions);
}
</code>```

As you can tell, they both invoke the same View (is this action called 'to invoke a view'. What is it's proper name?).

```<code>@model IEnumerable<Cumavi.Models.Auction>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th></th>
        <th>
            IDSubcategory
        </th>
        <th>
            IDCity
        </th>
        <th>
            IDPerson
        </th>
        <th>
            Title
        </th>
        <th>
            TextBody
        </th>
        <th>
            ContactNumber
        </th>
        <th>
            AskingPrice
        </th>
        <th>
            AddressDirection
        </th>
        <th>
            LatestUpdateDate
        </th>
        <th>
            VisitCount
        </th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
        <td>
            @item.IDSubcategory
        </td>
        <td>
            @item.IDCity
        </td>
        <td>
            @item.IDPerson
        </td>
        <td>
            @item.Title
        </td>
        <td>
            @item.TextBody
        </td>
        <td>
            @item.ContactNumber
        </td>
        <td>
            @String.Format("{0:F}", item.AskingPrice)
        </td>
        <td>
            @item.AddressDirection
        </td>
        <td>
            @String.Format("{0:g}", item.LatestUpdateDate)
        </td>
        <td>
            @item.VisitCount
        </td>
    </tr>
}

</table>
</code>```

They both inherit from the same Model.

My question is, am I doing things the right appropriate way? Or is this just a hack I managed to scrape together. Help me before I learn a bad habit.

答:
I would prefer the repo to do things like filtering and pagination for the sake of performance and DRY concept

```<code>public ActionResult Index(string categoryName)
    {
        AuctionRepository auctionRepo = new AuctionRepository();

    //Let the Repo Handle things like filtering and pagination, avoiding performance issues

        var auctions = auctionRepo.FindAllAuctions(categoryName);

        return View(auctions);
    }
</code>```

DAL should be responsible for this tasks.

OwnerDisplayName: delete

LastEditorDisplayName: delete

Body:
I have a controller called AuctionsController. In it I have Actions called Index() and AuctionCategoryListing():

//Used for displaying all auctions.
public ActionResult Index()
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions();
    return View(auctions);
}

//Used for displaying auctions for a single category.
public ActionResult AuctionCategoryListing(string categoryName)
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions()
                       .Where(c => c.Subcategory.Category.Name == categoryName);
    return View("Index", auctions);
}

As you can tell, they both invoke the same View (is this action called 'to invoke a view'. What is it's proper name?).

@model IEnumerable<Cumavi.Models.Auction>

@{
    ViewBag.Title = "Index";
}

Index

    @Html.ActionLink("Create New", "Create")

            IDSubcategory

            IDCity

            IDPerson

            Title

            TextBody

            ContactNumber

            AskingPrice

            AddressDirection

            LatestUpdateDate

            VisitCount

@foreach (var item in Model) {

            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })

            @item.IDSubcategory

            @item.IDCity

            @item.IDPerson

            @item.Title

            @item.TextBody

            @item.ContactNumber

            @String.Format("{0:F}", item.AskingPrice)

            @item.AddressDirection

            @String.Format("{0:g}", item.LatestUpdateDate)

            @item.VisitCount

}

They both inherit from the same Model.

My question is, am I doing things the right appropriate way? Or is this just a hack I managed to scrape together. Help me before I learn a bad habit.

Body:
I would prefer the repo to do things like filtering and pagination for the sake of performance and DRY concept

public ActionResult Index(string categoryName)
    {
        AuctionRepository auctionRepo = new AuctionRepository();

    //Let the Repo Handle things like filtering and pagination, avoiding performance issues

        var auctions = auctionRepo.FindAllAuctions(categoryName);

        return View(auctions);
    }

DAL should be responsible for this tasks.


问:
Need to generate a 2D python list with each column having 2 possibilities, for each row
I need to generate a two-dimensional python list. It would consist of 10 columns, with each column value being either '1' or '0'. Given these conditions, my list needs to be an exhaustive list of all the combinations that can be formed in this way. It'd naturally end up being 1024 rows long (2^10). However, I have no clue where to get started on this. Can anyone help?</p>

答:
You should use numpy for this. For array creation, you could do:

```<code>import numpy as np
rows, cols = 1024, 10
arr = np.zeros((rows, cols))
</code>```

Now, for setting certain values to 1 based on your condition, this could be used:

```<code># this should be changed based on your needs
arr[arr > 0] = 1 # set all values greater than 0 to 1
</code>```

If you need to create an array initialized with random binary data, you could do:

```<code>arr = np.random.randint(2, size=(rows,cols))
</code>```

Body:
You should use numpy for this. For array creation, you could do:

import numpy as np
rows, cols = 1024, 10
arr = np.zeros((rows, cols))

Now, for setting certain values to 1 based on your condition, this could be used:

# this should be changed based on your needs
arr[arr > 0] = 1 # set all values greater than 0 to 1

If you need to create an array initialized with random binary data, you could do:

arr = np.random.randint(2, size=(rows,cols))


问:
Triggering email verification
I am using custom policies.

The user journey desired is:

User enters the email/password on screen 1.

On successful validation of screen 1, the user is sent to screen 2. In screen 2 user has to enter a code sent to their email. (Note the user has already verified the email during sign up)

I am stuck at getting 2 to work.
The current policy looks like this:
Step 1 outputs email claim.

Step 2 takes the email claim as input.

In step 2 an editable text box with email prefilled is presented. No code is asked for. However, if the email is edited a code is asked for.

<TechnicalProfile Id="VerifyEmailAddress">
  <DisplayName>Local Account Signin</DisplayName>
  <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
  <Metadata>
    <Item Key="ContentDefinitionReferenceId">api.selfasserted</Item>
  </Metadata>
  <IncludeInSso>false</IncludeInSso>
  <InputClaims>
    <InputClaim ClaimTypeReferenceId="signInName" />
  </InputClaims>
  <OutputClaims>
    <OutputClaim ClaimTypeReferenceId="signInName" PartnerClaimType="Verified.Email" Required="true"/>
    <OutputClaim ClaimTypeReferenceId="objectId" />
    <OutputClaim ClaimTypeReferenceId="userPrincipalName" />
    <OutputClaim ClaimTypeReferenceId="authenticationSource" />
  </OutputClaims>
  <ValidationTechnicalProfiles>
    <ValidationTechnicalProfile ReferenceId="AAD-UserReadUsingEmailAddress" />
  </ValidationTechnicalProfiles>
</TechnicalProfile>
```

答:
Yeah that caused me lots of trouble,

I basically use a claims transformation to do it

<InputClaimsTransformations>
   <InputClaimsTransformation ReferenceId="CopyClaimToreadOnly" />
</InputClaimsTransformations>
<InputClaims>
 <InputClaim ClaimTypeReferenceId="myAlreadyPopulatedClaim" />
 <InputClaim ClaimTypeReferenceId="myAlreadyPopulatedClaim-Readonly" />
</InputClaims>
<OutputClaims>
   <OutputClaim ClaimTypeReferenceId="myAlreadyPopulatedClaim-Readonly"
PartnerClaimType="Verified.Email" />
 </OutputClaims>
```

The control isnt smart enough to realize that you populated the claim and you still want to do verification, it expects email entry and verification to be performed on the same page, when you split it you must do this claim copying

Hope this helps

Title: Triggering email verification

Body:
Yeah that caused me lots of trouble,

I basically use a claims transformation to do it

<InputClaimsTransformations>
   <InputClaimsTransformation ReferenceId="CopyClaimToreadOnly" />
</InputClaimsTransformations>
<InputClaims>
 <InputClaim ClaimTypeReferenceId="myAlreadyPopulatedClaim" />
 <InputClaim ClaimTypeReferenceId="myAlreadyPopulatedClaim-Readonly" />
</InputClaims>
<OutputClaims>
   <OutputClaim ClaimTypeReferenceId="myAlreadyPopulatedClaim-Readonly"
PartnerClaimType="Verified.Email" />
 </OutputClaims>

The control isnt smart enough to realize that you populated the claim and you still want to do verification, it expects email entry and verification to be performed on the same page, when you split it you must do this claim copying

Hope this helps


问:
It is possible to render a DOM in a div?
I am working with email services and the services gives me the body of the message in the following form

```<code> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.= w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns=3D "http://www.w3.= org/1999/xhtml">

<head>
    <meta http-equiv=3D "Content-Type" content=3D "text/html; charset=3Dutf-8">
    <title>How's it going? </title>
    <style>
        @import url(https://fonts.googleapis.com/css?family=3DRoboto:300);
        /*Calling our web font*/
        /* Some resets and issue fixes */

        #outlook a {
            padding: 0;
        }
        body {
            width: 100% !important;
            -webkit-text;
            size-adjust: 100%;
            -ms-te xt-size-adjust: 100%;
            margin: 0;
            padding: 0;
        }
        =20 .ReadMsgBody {
            width: 100%;
        }
        .ExternalClass {
            width: 100%;
        }
        =20 .backgroundTable {
            margin: 0 auto;
            padding: 0;
            width: 100%;
            !important;
        }
         =20 table td {
            border-collapse: collapse;
        }
        .ExternalClass * {
            line-height: 115%;
        }
        =20=20
        /* End reset */

        =20
        /* These are our tablet/medium screen media queries */

        @media screen and (max-width: 630px) {
            =20
            /* Display block allows us to stack elements */

             =20 *[class=3D"mobile-column"] {
                display: block;
            }
            =20=20
            /* Some more stacking elements */

            *[class=3D"mob-column"] {
                float: none !important;
                width: 100% !im portant;
            }
            =20=20
            /* Hide stuff */

            *[class=3D"hide"] {
                display: none !important;
            }
            =20=20
            /* This sets elements to 100% width and fixes the height issues= too, a god send */

            *[class=3D"100p"] {
                width: 100% !important;
                height: auto !importan t;
            }
            =20=20
            /* For the 2x2 stack */

            =20 *[class=3D"condensed"] {
                padding-bottom: 40px !important;
                display : block;
            }
            =20
            /* Centers content on mobile */

            *[class=3D"center"] {
                text-align: center !important;
                width: 100% ! important;
                height: auto !important;
            }
            =20=20
            /* 100percent width section with 20px padding */

            *[class=3D"100pad"] {
                width: 100% !important;
                padding: 20px;
            }
            =20=20
            /* 100percent width section with 20px padding left & right */

            *[class=3D"100padleftright"] {
                width: 100% !important;
                padding: 0 20px 0 20px;
            }
            =20=20
            /* 100percent width section with 20px padding top & bottom */

            *[class=3D"100padtopbottom"] {
                width: 100% !important;
                padding: 20 px 0px 20px 0px;
            }
            =20=20=20
        }
    </style>
    <style type=3D "text/css">
    </style>
</head>

<body> =20
    <table>
        <tr>
            <td style=3D "padding: 0 10px;"> =20
                <div class=3D "mktEditable" id=3D "content" style=3D "font-family: Arial, = sans-serif; font-size:14px; line-height:20px; color:#2e2e2e; font-weight:no= rmal; ">
                    <p style=3D "font-size: 12px;"> </p>
                    <p> =20 Hey,
                        <br> Thanks for taking the time to evaluate amoCRM. Our mission is helping sales= teams accomplish more by giving them the proper place to manage their work= . I hope we can do that for you too. </p>
                    <p> I was told that you aren=E2=80=99t really enjoying the first days of your t= rial - just hit reply, and let me know about your main goal. I=E2=80=99ll c= onnect you with the right person to fine-tune amoCRM to fit your needs. </p=> Thank you and best regards,
                        <br> Egor Kovalchuk
                        <br> CEO, amoCRM </div>
            </td>
        </tr>
    </table> =20 <img src=3D "https://mandrillapp.com/track/open.php?u=3D30051581&id=3Dd8= bfb7221bf8403c8d63e2375a2dd6a4" height=3D "1" width=3D "1">
    <center>
        <br>
        <br>
        <br>
        <br>
        <br>
        <br>
        <table border=3D "0" cellpadding=3D "0" cellspacing=3D "0" width=3D "100%"=i d=3D "canspamBarWrapper" style=3D "background-color:#FFFFFF; border-top:1px = solid #E5E5E5;">
            <tr>
                <td align=3D "center" valign=3D "top" style=3D "padding-top:20px; = padding-bottom:20px;">
                    <table border=3D "0" cellpadding=3D "0" cellspacing=3D "0" id==3D "canspamBar">
                        <tr>
                            <td align=3D "center" valign=3D "top" style=3D "color:= #606060; font-family:Helvetica, Arial, sans-serif; font-size:11px; line-hei= ght:150%; padding-right:20px; padding-bottom:5px; padding-left:20px; text-a= lign:center;"> This email was sent to <a href=3D "mailto:vasily= ev.alexander@hotmail.com" target=3D "_blank" style=3D "color:#404040 !importa= nt;">vasilyev.alexander@hotmail.com</a>    <a href=3D "https://mandrillapp.com/track/click/= 30051581/mandrillapp.com?p=3DeyJzIjoiRVA5WWVBVkt3eVl4UEI2TmJfWkdNUU9UcVg0Ii= widiI6MSwicCI6IntcInVcIjozMDA1MTU4MSxcInZcIjoxLFwidXJsXCI6XCJodHRwOlxcXC9cX= FwvbWFuZHJpbGxhcHAuY29tXFxcL3RyYWNrXFxcL3Vuc3ViLnBocD91PTMwMDUxNTgxJmlkPWQ4= YmZiNzIyMWJmODQwM2M4ZDYzZTIzNzVhMmRkNmE0Lmp6WlBnZVVWRWg1Y01nRTNLJTJCbFlqaDh= QbVE0JTNEJnI9aHR0cHMlM0ElMkYlMkZtYW5kcmlsbGFwcC5jb20lMkZ1bnN1YiUzRm1kX2VtYW= lsJTNEdmFzaWx5ZXYuYWxleGFuZGVyJTI1NDBob3RtYWlsLmNvbVwiLFwiaWRcIjpcImQ4YmZiN= zIyMWJmODQwM2M4ZDYzZTIzNzVhMmRkNmE0XCIsXCJ1cmxfaWRzXCI6W1wiODdmOTIzZjE4Mjg2= ZmM5NzgwMGE1NzA3ZWEyMDJjM2EwNDUwMGZhNFwiXX0ifQ" style=3D "color:#404040 !imp= ortant;">unsubscribe from this list</a> </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
        <style type=3D "text/css">
            @media only screen and (max-width: 480px) {
                table[id=3D"canspamBar"] td {
                    font-size: 14px !important;
                }
                table[id=3D"canspamBar"] td a {
                    display: block !important;
                    margin- top: 10px !important;
                }
            }
        </style>
    </center>
</body>=20

</html>
</code>```

I need to render it as html under a div on my client page. Is there any possibility to do so

--edited for clarification, cant read this in a single line

答:
Why not use an iFrame? Here's how you can insert some HTML in your iFrame:

var insertTo = document.querySelector('div#emailContent');
var iframe = document.createElement('iframe');
document.body.appendChild(insertTo);
var emailDoc = iframe.contentWindow.document;
emailDoc.open();
emailDoc.write(
    '<!doctype html>' +
    '' +
    '' +
        '' +
    '' +
    '' +
    ''
);
emailDoc.close();
```

Body:
I am working with email services and the services gives me the body of the message in the following form

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.= w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv=3D "Content-Type" content=3D "text/html; charset=3Dutf-8">
    <title>How's it going? </title>

 =20

             =20

 =20 Hey,

 Thanks for taking the time to evaluate amoCRM. Our mission is helping sales= teams accomplish more by giving them the proper place to manage their work= . I hope we can do that for you too.

 I was told that you aren=E2=80=99t really enjoying the first days of your t= rial - just hit reply, and let me know about your main goal. I=E2=80=99ll c= onnect you with the right person to fine-tune amoCRM to fit your needs.
 Thank you and best regards,

 Egor Kovalchuk

 CEO, amoCRM

 =20

                             This email was sent to vasilyev.alexander@hotmail.com    <a href=3D "https://mandrillapp.com/track/click/= 30051581/mandrillapp.com?p=3DeyJzIjoiRVA5WWVBVkt3eVl4UEI2TmJfWkdNUU9UcVg0Ii= widiI6MSwicCI6IntcInVcIjozMDA1MTU4MSxcInZcIjoxLFwidXJsXCI6XCJodHRwOlxcXC9cX= FwvbWFuZHJpbGxhcHAuY29tXFxcL3RyYWNrXFxcL3Vuc3ViLnBocD91PTMwMDUxNTgxJmlkPWQ4= YmZiNzIyMWJmODQwM2M4ZDYzZTIzNzVhMmRkNmE0Lmp6WlBnZVVWRWg1Y01nRTNLJTJCbFlqaDh= QbVE0JTNEJnI9aHR0cHMlM0ElMkYlMkZtYW5kcmlsbGFwcC5jb20lMkZ1bnN1YiUzRm1kX2VtYW= lsJTNEdmFzaWx5ZXYuYWxleGFuZGVyJTI1NDBob3RtYWlsLmNvbVwiLFwiaWRcIjpcImQ4YmZiN= zIyMWJmODQwM2M4ZDYzZTIzNzVhMmRkNmE0XCIsXCJ1cmxfaWRzXCI6W1wiODdmOTIzZjE4Mjg2= ZmM5NzgwMGE1NzA3ZWEyMDJjM2EwNDUwMGZhNFwiXX0ifQ" style=3D "color:#404040 !imp= ortant;">unsubscribe from this list

=20

I need to render it as html under a div on my client page. Is there any possibility to do so

--edited for clarification, cant read this in a single line

Body:
Why not use an iFrame? Here's how you can insert some HTML in your iFrame:

var insertTo = document.querySelector('div#emailContent');
var iframe = document.createElement('iframe');
document.body.appendChild(insertTo);
var emailDoc = iframe.contentWindow.document;
emailDoc.open();
emailDoc.write(
    '<!doctype html>' +
    '<html>' +
    '<head>' +
        '<style>/* styles go here */</style>' +
    '</head>' +
    '<body><!-- content goes here ---></body>' +
    '</html>'
);
emailDoc.close();


问:
How will I know when to create an interface?
I'm at a point in my development learning where I feel like I must learn more about interfaces.

I frequently read about them but it just seems like I cannot grasp them.

I've read examples like: Animal base class, with IAnimal interface for things like 'Walk', 'Run', 'GetLegs', etc - but I've never been working on something and felt like "Hey I should use an interface here!"

What am I missing? Why is it such a hard concept for me to grasp! I am just intimidated by the fact that I might not ever realize a concrete need for one - mostly due to some missing aspect of understanding them! It makes me feel like I'm missing something up top in terms of being a developer! If anyone has had an experience like this and had a breakthrough I would appreciate some tips on how to understand this concept. Thank you.

答:
I like Jimmy's answer a lot, but I feel I need to add something to it.  The key to the whole thing is the "able" in IProcessable .  It indicates a capability (or property, but meaning "intrinsic quality", not in the sense of C# properties) of the object that implements the interface.  IAnimal is probably not a good example for an interface, but IWalkable might be a good interface to have if your system has many things that can walk.  You might have classes derived from Animal such as Dog, Cow, Fish, Snake.  The first two would probably implement IWalkable, the latter two don't walk, so they wouldn't.  Now you ask "why not just have another superclass, WalkingAnimal, that Dog and Cow derive from?".  The answer is when you have something completely outside the inheritance tree that also can walk, such as a robot.  Robot would implement IWalkable, but probably wouldn't derive from Animal.  If you want a list of things that can walk, you type it as IWalkable and you can put all walking animals plus robots in the list.

Now replace IWalkable with something more software-y like IPersistable, and the analogy becomes much closer to what you'd see in a real program.

LastEditorDisplayName: ALassek

OwnerDisplayName: rmeador


问:
How to do non-obtrusive number-crunching on mysql db?
Not sure how to state this question.

I have a very busy DB in production with close to 1 million hits daily.

Now I would like to do some research on the real-time data (edit: "real-time" can be a few minutes old).

What is the best way to do this without interrupting production?

Ideas:

in the unix shell, there is the nice concept. It lets me give a low priority to a specific thread so it only uses CPU when the other threads are idle. I am basically looking for the same in a mysql context.

Get a DB dump and do the research offline:

Doesn't that take down my site for the several minutes it takes to get the dump?

Is there a way to configure the dump command so it does the extraction in a nice way (see above)?

Do the SQL commands directly on the live DB:

Is there a way, again, to configure the commands so they are executed in a nice way?

Update: What are the arguments against Idea 2?

答:
From the comments on StackOverflow and in-person discussions, here's an answer for whoever gets here with the same question:

In MySQL, there seems not to be any nice type control over prioritization of processes (I hear there is in Oracle, for example)

Since any "number-crunching" is at most treated like one more visitor to my website, it won't take down the site performance-wise. So it can safely be run in production (read-only, of course...).


问:
Auto Increment in primary Key evenThough there is Constrain voilation Exception Mysql(5.6.34)
I have created a table User with following details

```<code>  {
       id , //autoincrment
       name
    }
</code>```

and Table Account which has a User with foreign key relation

```<code>Account {
 id , //autoincrement
 userid //foreign key reference to user
 }
</code>```

when i insert in to account with value userId which doesnot exist in user table
i get Constraint voilation Exception

```<code>Cannot add or update a child row: a foreign key constraint fails (`schema`.`account`, CONSTRAINT `constraint_name` FOREIGN KEY (`user_id`) REFERENCES `User` (`id`))
</code>```

but my AUTO increment Count for Account got increased.

what i meant to say is before exception  account table has max id of 100.
when i insert new record it fails with above described exception.i corrected query and insert with correct userid then i see accountid value as 102.

is it a correct behaviour from mysql.should it increment autoincrement value even though query execution fails?

答:
It's intended and correct, that auto_increment works outside the scope of transactions (like sequences in other database systems like oracle do as well). The reason is that two different transactions must not draw the same number, and a locking on such a neuralgic point as the key column of a table would have enormous performance impact in concurrent situations otherwise.

Cf. also this SO answer.

Body:
I have created a table User with following details

  {
       id , //autoincrment
       name
    }

and Table Account which has a User with foreign key relation

Account {
 id , //autoincrement
 userid //foreign key reference to user
 }

when i insert in to account with value userId which doesnot exist in user table
i get Constraint voilation Exception

Cannot add or update a child row: a foreign key constraint fails (`schema`.`account`, CONSTRAINT `constraint_name` FOREIGN KEY (`user_id`) REFERENCES `User` (`id`))

but my AUTO increment Count for Account got increased.

what i meant to say is before exception  account table has max id of 100.
when i insert new record it fails with above described exception.i corrected query and insert with correct userid then i see accountid value as 102.

is it a correct behaviour from mysql.should it increment autoincrement value even though query execution fails?


问:
What is "Super Loop" in Embedded C programming language?
What is Super Loop in Embedded C programming language?

答:
MCU is device which runs continuously or better, it executes instructions when power is on (in general).

So while loop is here to force MCU to do something, even if loop is empty, it will just circle around.

But it must do something as it is not the same as PC program where you have return at the end of main function.

If you wouldn't have super loop then MCU can get instruction from FLASH/RAM (whatever..) and do something stupid things as MCU don't know what it is executing. It just executes code you provide him.

By using super loop, you guarantee MCU won't just uncontrollable execute some instructions and maybe go to fail-safe area. Of course this can happen even if you have super loop but this is other topic.

```<code>int main() {
    //Init if you have something
    while (1) {
        //DO stuff always
    }
    return 0; //This should never happen!
}
</code>```

Body:
MCU is device which runs continuously or better, it executes instructions when power is on (in general).

So while loop is here to force MCU to do something, even if loop is empty, it will just circle around.

But it must do something as it is not the same as PC program where you have return at the end of main function.

If you wouldn't have super loop then MCU can get instruction from FLASH/RAM (whatever..) and do something stupid things as MCU don't know what it is executing. It just executes code you provide him.

By using super loop, you guarantee MCU won't just uncontrollable execute some instructions and maybe go to fail-safe area. Of course this can happen even if you have super loop but this is other topic.

int main() {
    //Init if you have something
    while (1) {
        //DO stuff always
    }
    return 0; //This should never happen!
}


答:
This refers to the eternal loop usually located in main() of a "bare metal" system (no OS), since such systems can never return from main. A typical bare metal embedded system looks like this:

```<code>void main (void)
{
  // various initializations

  for(;;) // "super loop" or "main loop"
  {
    // do stuff
  }
}
</code>```

Title: What is "Super Loop" in Embedded C programming language?

Body: What is Super Loop in Embedded C programming language?

Body:
This refers to the eternal loop usually located in main() of a "bare metal" system (no OS), since such systems can never return from main. A typical bare metal embedded system looks like this:

void main (void)
{
  // various initializations

  for(;;) // "super loop" or "main loop"
  {
    // do stuff
  }
}


问:
Jenkins Automation to push tarball into artifactory
I want to create tarball for npm build from jenkins (angular 2 project) and publish into artifactory . I have used artifactory plugin and it pushed code into Jfrog builds but not in artifactory.

How to publish tarball to artifactory from jenkins for npm project , solutions I am getting are for maven ,gradle and ivy.

答:
You can use Artifactory plugin to do this.

Configure you artiactory server in the manager jenkins area properly.

You will need to ticket Generic-Artifactory Integration in your job.
Then enter a file spec:

```<code>{
    "files": [
        {
            "pattern": "Build\build.tar",
            "target": "REPO name",
            "props": "test=banana"
        }
    ]
}
</code>```

Then your tar will be pushed to artifactory.

Body:
You can use Artifactory plugin to do this.

Configure you artiactory server in the manager jenkins area properly.

You will need to ticket Generic-Artifactory Integration in your job.
Then enter a file spec:

{
    "files": [
        {
            "pattern": "Build\build.tar",
            "target": "REPO name",
            "props": "test=banana"
        }
    ]
}

Then your tar will be pushed to artifactory.


问:
TensorFlow for Go demo example run failed
i have the issue.

environment

```<code>macbookpro:lib fredlee$ go version
go version go1.8.3 darwin/amd64
macbookpro:lib fredlee$ pwd
/usr/local/lib
macbookpro:lib fredlee$ ls -alh libtensorflow.so
-r-xr-xr-x  1 root  wheel   102M  1  1  1970 libtensorflow.so
macbookpro:lib fredlee$ file libtensorflow.so
libtensorflow.so: Mach-O 64-bit dynamically linked shared library x86_64
macbookpro:lib fredlee$
</code>```

issue

```<code>> macbookpro:~ fredlee$ go get
> github.com/tensorflow/tensorflow/tensorflow/go macbookpro:~ fredlee$
> go test github.com/tensorflow/tensorflow/tensorflow/go
> # github.com/tensorflow/tensorflow/tensorflow/go ld: library not found for -ltensorflow clang: error: linker command failed with exit code 1
> (use -v to see invocation)
> FAIL  github.com/tensorflow/tensorflow/tensorflow/go [build failed]
</code>```

anyone can help me make it works?

答:
I do not quit understand why you test a third-party package. But from your error, looks like a lib called ld is not found. If it is needed the the package, then I believe It should be installed in the $GOPATH/bin. So, please try:

```<code>export PATH=$PATH:$GOPATH/bin
</code>```

Body:
i have the issue.

environment

macbookpro:lib fredlee$ go version
go version go1.8.3 darwin/amd64
macbookpro:lib fredlee$ pwd
/usr/local/lib
macbookpro:lib fredlee$ ls -alh libtensorflow.so
-r-xr-xr-x  1 root  wheel   102M  1  1  1970 libtensorflow.so
macbookpro:lib fredlee$ file libtensorflow.so
libtensorflow.so: Mach-O 64-bit dynamically linked shared library x86_64
macbookpro:lib fredlee$

issue

> macbookpro:~ fredlee$ go get
> github.com/tensorflow/tensorflow/tensorflow/go macbookpro:~ fredlee$
> go test github.com/tensorflow/tensorflow/tensorflow/go
> # github.com/tensorflow/tensorflow/tensorflow/go ld: library not found for -ltensorflow clang: error: linker command failed with exit code 1
> (use -v to see invocation)
> FAIL  github.com/tensorflow/tensorflow/tensorflow/go [build failed]

anyone can help me make it works?

Body:
I do not quit understand why you test a third-party package. But from your error, looks like a lib called ld is not found. If it is needed the the package, then I believe It should be installed in the $GOPATH/bin. So, please try:

export PATH=$PATH:$GOPATH/bin


问:
VB script is not getting executed after I changed the path I see Windows script host prompt with a different path
I have created VBS script and am calling it in my Java program. This was working flawlessly until I changed the path.

I see the below error:

Things I did:

I changed the path in my VBS script

```<code>Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("GALE-GoEasy-QA\GoEasy\requiredSource\TestData1.xlsm")

objExcel.Application.Run "TestData1.xlsm!refreshXLS"
objExcel.ActiveWorkbook.Close

objExcel.Application.Quit
WScript.Quit
</code>```

My Java program calls this function to execute the program

```<code>public void refreshExcelData() throws IOException {

  Runtime.getRuntime().exec(new String[] {
    "C:\\Windows\\System32\\wscript.exe",
    "myVBS.vbs"
  });
}
</code>```

Also I have attached a picture of my project folder structure

PS: I wanted to use relative path instead of absolute

答:
Try the below code:    </p>

```<code>public void refreshExcelData() throws IOException {

Runtime.getRuntime().exec(new String[] {
      "C:\\Windows\\System32\\wscript.exe",
       System.getProperty("user.dir")+"\\requiredSource\\myVBS.vbs"
   });
}
</code>```

Body:
I have created VBS script and am calling it in my Java program. This was working flawlessly until I changed the path.

I see the below error:

Things I did:

I changed the path in my VBS script

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("GALE-GoEasy-QA\GoEasy\requiredSource\TestData1.xlsm")

objExcel.Application.Run "TestData1.xlsm!refreshXLS"
objExcel.ActiveWorkbook.Close

objExcel.Application.Quit
WScript.Quit

My Java program calls this function to execute the program

public void refreshExcelData() throws IOException {

  Runtime.getRuntime().exec(new String[] {
    "C:\\Windows\\System32\\wscript.exe",
    "myVBS.vbs"
  });
}

Also I have attached a picture of my project folder structure

PS: I wanted to use relative path instead of absolute

Body:
Try the below code:

public void refreshExcelData() throws IOException {

Runtime.getRuntime().exec(new String[] {
      "C:\\Windows\\System32\\wscript.exe",
       System.getProperty("user.dir")+"\\requiredSource\\myVBS.vbs"
   });
}


问:
google-api-python-client bug with media downloading
Used google-api-python-client==1.6.2

```<code>fh = io.BytesIO()
request = self.drive_service.files().export_media(
    fileId='1fwshPVKCACXgNxJtmGN94X-9RRrukiDs9q4s-n0nGlM',
    mimeType='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
)
downloader = MediaIoBaseDownload(fh, request, chunksize=1024)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print "Download ", status.progress(), downloader._progress, downloader._total_size, done
</code>```

Output:

```<code>Download  0.0 973060 None False
Download  0.0 1946120 None False
Download  0.0 2919180 None False
Download  0.0 3892240 None False
Download  0.0 4865300 None False
Download  0.0 5838360 None False
Download  0.0 6811420 None False
Download  0.0 7784480 None False
Download  0.0 8757540 None False
...
</code>```

File size of downloading file is 973060 bytes. So, the library ignores chunksize parameter and did not stop. Never stop.

So, anyone can tell me Are my requirements too high or Is the library so bad?

答:
The google-api-python-client library has a bug where downloads will never be considered done if the Content-length or Content-range header is missing.

And since drive.files.export does not support chunked downloads it does not return a Content-length or Content-range header.

You can download the file by simply calling execute on the HttpRequest since drive.files.export will always export the entire file in one request.

If you still want to use MediaIoBaseDownload for a more general workaround you can check if MediaDownloadProgress.total_size is None.

```<code>fh = io.BytesIO()
request = service.files().export_media(fileId=file_id, mimeType=mime_type)
downloader = MediaIoBaseDownload(fh, request)

done = False
while not done:
    status, done = downloader.next_chunk()
    if status.total_size is None:
        # https://github.com/google/google-api-python-client/issues/15
        done = True
</code>```

Body:
Used google-api-python-client==1.6.2

fh = io.BytesIO()
request = self.drive_service.files().export_media(
    fileId='1fwshPVKCACXgNxJtmGN94X-9RRrukiDs9q4s-n0nGlM',
    mimeType='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
)
downloader = MediaIoBaseDownload(fh, request, chunksize=1024)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print "Download ", status.progress(), downloader._progress, downloader._total_size, done

Output:

Download  0.0 973060 None False
Download  0.0 1946120 None False
Download  0.0 2919180 None False
Download  0.0 3892240 None False
Download  0.0 4865300 None False
Download  0.0 5838360 None False
Download  0.0 6811420 None False
Download  0.0 7784480 None False
Download  0.0 8757540 None False
...

File size of downloading file is 973060 bytes. So, the library ignores chunksize parameter and did not stop. Never stop.

So, anyone can tell me Are my requirements too high or Is the library so bad?

Body:
The google-api-python-client library has a bug where downloads will never be considered done if the Content-length or Content-range header is missing.

And since drive.files.export does not support chunked downloads it does not return a Content-length or Content-range header.

You can download the file by simply calling execute on the HttpRequest since drive.files.export will always export the entire file in one request.

If you still want to use MediaIoBaseDownload for a more general workaround you can check if MediaDownloadProgress.total_size is None.

fh = io.BytesIO()
request = service.files().export_media(fileId=file_id, mimeType=mime_type)
downloader = MediaIoBaseDownload(fh, request)

done = False
while not done:
    status, done = downloader.next_chunk()
    if status.total_size is None:
        # https://github.com/google/google-api-python-client/issues/15
        done = True


问:
RuntimeMXBean.getName() hangs on Mac OS X Sierra - how to fix?
If I run the following on OS X Sierra (JDK 8u111), it takes 5 seconds to run (as opposed to milliseconds on e.g. Linux):

```<code>import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;

public class BeanTest {
    public static void main (String[] args) {
        RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
        System.out.println(bean.getName());
    }
}
</code>```

This is causing a massive slowdown of a library that I use, whose newer versions call this bit of the management API. My first thought is that it's a DNS issue (the computer is on a local home NAT) but my attempt to resolve either my local hostname or my local IP address in the shell returns an (NXDOMAIN) answer instantly. Running dtruss on the Java process produced constant repetition of these lines for the duration of the 5 second lag:

```<code>  782/0x36f5:  psynch_cvwait(0x7FEE4170B968, 0x20100000300, 0x200)       = -1 Err#316
  782/0x36f5:  gettimeofday(0x7000039B4938, 0x0, 0x0)        = 0 0
</code>```

What is going on here and what can I do to unblock this bottleneck?

答:
I fix the problem by manually set HostName to LocalHostName, before this, HostName is not set:</p>

```<code>$ scutil --set HostName $(scutil --get LocalHostName)
</code>```

Body:
If I run the following on OS X Sierra (JDK 8u111), it takes 5 seconds to run (as opposed to milliseconds on e.g. Linux):

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;

public class BeanTest {
    public static void main (String[] args) {
        RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
        System.out.println(bean.getName());
    }
}

This is causing a massive slowdown of a library that I use, whose newer versions call this bit of the management API. My first thought is that it's a DNS issue (the computer is on a local home NAT) but my attempt to resolve either my local hostname or my local IP address in the shell returns an (NXDOMAIN) answer instantly. Running dtruss on the Java process produced constant repetition of these lines for the duration of the 5 second lag:

  782/0x36f5:  psynch_cvwait(0x7FEE4170B968, 0x20100000300, 0x200)       = -1 Err#316
  782/0x36f5:  gettimeofday(0x7000039B4938, 0x0, 0x0)        = 0 0

What is going on here and what can I do to unblock this bottleneck?

Body:
I fix the problem by manually set HostName to LocalHostName, before this, HostName is not set:

$ scutil --set HostName $(scutil --get LocalHostName)


问:
Spacing between columns in a table
I have a big problem with the spacing of columns in a table.
Here's what I'd like to get, spacing only between :

Not working with margin, padding  or border:

td {
  padding-left: 7.5px;
  padding-right: 7.5px;
}

td:first-child {
  padding-left: 0;
}

td:last-child {
  padding-right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><td></td>
<td></td>
<td></td>
<td></td></code>```

Not working with border-spacing:

And if use first-child and last-child, same problem as previous image.

Solution I found, but really dirty:

.spacer {
  width: 15px;
  height: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><td></td>
<div id="spacer"></div>
<td></td>
<div id="spacer"></div>
<td></td>
<div id="spacer"></div>
<td></td></code>```

答:
Try to use cellspacing attribute.

    Month
    Savings

    January
    $100

```

Title: Spacing between columns in a table

Body:
I have a big problem with the spacing of columns in a table.
Here's what I'd like to get, spacing only between :

Not working with margin, padding  or border:

td {
  padding-left: 7.5px;
  padding-right: 7.5px;
}

td:first-child {
  padding-left: 0;
}

td:last-child {
  padding-right: 0;
}

Not working with border-spacing:

And if use first-child and last-child, same problem as previous image.

Solution I found, but really dirty:

.spacer {
  width: 15px;
  height: 15px;
}

Body:
Try to use cellspacing attribute.

<table cellspacing="10">
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
</table>


问:
Average a certain column value in MySQL
I have this table structure:

```<code>id | code | rating
1  | 300  |   25
2  | 302  |   35
3  | 100  |   50
4  | 100  |   30
5  | 200  |   40
6  | 103  |   45
</code>```

Here's my query so far:

SELECT code, AVG(rating) FROM table GROUP BY code;

I want to average the rating of all codes greater than 300. I tried setting an IF on the SQL query but it seems it doesn't work. Also tried having two group BYs but it won't work. I want to achieve this result:

```<code>code         |  AVG (rating)
300+ (alias) |  30
100          |  40
200          |  40
103          |  45
</code>```

答:
According to description mentioned in above question please try executing following SQL select query as a solution to it.</p>

```<code> select code,avg(rating) from table where code < 300 group by code
 union
 select code,avg(rating) from table where code >= 300
</code>```

Title: Average a certain column value in MySQL

Body:
I have this table structure:

id | code | rating
1  | 300  |   25
2  | 302  |   35
3  | 100  |   50
4  | 100  |   30
5  | 200  |   40
6  | 103  |   45

Here's my query so far:

SELECT code, AVG(rating) FROM table GROUP BY code;

I want to average the rating of all codes greater than 300. I tried setting an IF on the SQL query but it seems it doesn't work. Also tried having two group BYs but it won't work. I want to achieve this result:

code         |  AVG (rating)
300+ (alias) |  30
100          |  40
200          |  40
103          |  45

Body:
According to description mentioned in above question please try executing following SQL select query as a solution to it.

 select code,avg(rating) from table where code < 300 group by code
 union
 select code,avg(rating) from table where code >= 300


问:
What is use of `""+` in setText
I have an example:

```<code> int num1 = Integer.parseInt(firstno.getText());
 int num2 = Integer.parseInt(secondno.getText());
 int num3 = num1+num2;
 result.setText(""+num3);
</code>```

what is use of "" in result.setText(""+num3);

答:
Plus operator ("+") for instances of String class is overridden and leads to concatenation. See spec.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java. For additional information on string concatenation and conversion, see Gosling, Joy, and Steele, The Java Language Specification.

So in your case, your second object is an instance of Integer, so to concatenate an empty String "" and the number num3 conversion of num3 to String should happen first.

The result of the concatenation is a new string which contains a string representation of your num3.

Title: What is use of `""+` in setText

Body:
I have an example:

 int num1 = Integer.parseInt(firstno.getText());
 int num2 = Integer.parseInt(secondno.getText());
 int num3 = num1+num2;
 result.setText(""+num3);

what is use of "" in result.setText(""+num3);