问:
What is the difference between using /[,]/ and /(|)/ while matching pattern to split in Perl?
I'm trying to split variable below to get only the part before ":2|". Why pattern matching to do so works in the variable @name1, but not @name2?

```<code>$a = "NB501373:45:HFH3CBGXY:4:11401:17564:1786:2|DS-R2Dec3|Dor|23-12-2013|0m|GFF";

@name1 = split (/(\:1\|DS\-|\:2\|DS\-)/, $a);
@name2 = split (/[\:1\|DS\-,\:2\|DS\-]/, $a);
</code>```

答:
If you want the match operator to return the "captured" sections of your regex, then you need to include capturing brackets in your regex.

Capturing brackets are parentheses like ( ... ).

Square brackets ([ ... ]) are used to define character classes. That is, they mean "match any one of the characters between the two brackets". They do not capture text.

Your first example includes capturing brackets - therefore the captured matches are returned and stored in @name1.

Your second example includes a character class and no capturing brackets - therefore no matches are returned and stored in @name2.

Body:
I'm trying to split variable below to get only the part before ":2|". Why pattern matching to do so works in the variable @name1, but not @name2?

$a = "NB501373:45:HFH3CBGXY:4:11401:17564:1786:2|DS-R2Dec3|Dor|23-12-2013|0m|GFF";

@name1 = split (/(\:1\|DS\-|\:2\|DS\-)/, $a);
@name2 = split (/[\:1\|DS\-,\:2\|DS\-]/, $a);


来源: stackexchange

问:
Update bar chart in d3 based on user input

I'm trying to update the bar chart in d3 based on the input selected by the user. The updated data is being displayed but it is being displayed on the old SVG elements. I tried using exit().remove() but it did not work.
Can anyone edit the code attached below so that the old SVG elements are removed.
</p>

```<code>    <html>
<head>
<script src="https://d3js.org/d3.v4.min.js" charset="utf-8"></script>
<style>
.rect {
  fill: steelblue;
}

.text {
  fill: white;
  font: 10px sans-serif;
  text-anchor: middle;
}
</style>
</head>
<body>
<select id = "variable">
                    <option >select</option>
                    <option value="AZ">Arizona</option>
                    <option value="IL">Illinois</option>
                    <option value="NV">NV</option>
</select>
<script>
var margin = {top: 20, right: 20, bottom: 70, left: 40},
        width = 500 - margin.left - margin.right,
        height = 400 - margin.top - margin.bottom;
var y = d3.scaleLinear()
        .domain([0,5])
        .range([height, 0]);
var yAxis = d3.axisLeft(y)
                .ticks(10);
var svg = d3.select("body")
            .append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
            .append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var bar;

function update(state)
{
d3.csv("test3.csv", function(error, data)
    {
            data = data.filter(function(d, i)
                                {
                                    if (d['b_state'] == state)
                                    {
                                    return d;
                                    }
                                });
            data = data.filter(function(d, i)
                                {
                                    if (i<10)
                                    {
                                    return d;
                                    }
                                });

            var barWidth = width / data.length;

            svg.append("g")
                 .attr("class", "y axis")
                 .call(yAxis)
                 .append("text")
                 .attr("transform", "rotate(-90)")
                 .attr("y", 6)
                 .attr("dy", ".71em")
                 .style("text-anchor", "end")
                 .text("Stars");

                bar = svg.selectAll("bar")
                          .data(data)
                          .enter()
                          .append("g")
                          .attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; });

                bar.append("rect")
                   .attr("y", function(d) { return y(d.b_stars); })
                   .attr("height", function(d) { return height - y(d.b_stars); })
                   .attr("width", barWidth - 1)
                   .attr("fill", "steelblue");

                bar.append("text")
                      .attr("x", function(d) { return height - y(d.b_stars); })
                      .attr("y", -40)
                      .attr("dy", ".75em")
                      .text(function(d) { return d.b_name; })
                      .attr("transform", "rotate(90)" );
});
svg.exit().remove();
bar.exit().remove();
}
d3.select("#variable")// selects the variable
  .on("change", function() {// function that is called on changing
    var variableName = document.getElementById("variable").value;// reads the variable value selected into another variable
    update(variableName);});
</script>
</body>
</code>```

答:
Your problem here is about your bar selection. You can have a look to this part of the d3 documentation: Joining data.

By writing

```<code>bar = svg.selectAll("bar")
    .data(data)
    .enter()
</code>```

You are selecting all bar elements, joining them data, and with this enter(), you are getting all the data items not linked to a bar element (enter() documentation).
But, your bar selector matches nothing. The parameter of the select()/selectAll() has to be a selector (element, class with ., id with #...). That is why the enter() your enter() selection is creating always new elements above the old ones instead of updating them.

So the first step is to rewrite this selection and creating the DOM elements that will match later this selection:

```<code>bar = svg.selectAll(".bar")
    .data(data)
    .enter()
    .append("g")
    .attr('class', 'bar')
    .attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; });
</code>```

Here, we are selecting all elements with the bar class. If there is no DOM element linked to an item from data, so we are creating it (in the enter() selection), as a new g with the bar class.

With the selection written like this, on the next call of your update, the selectAll('.bar') will match all the g previously created and not apply the enter() selection for existing elements.

To update or remove your existing bars, you can write your code like this:

```<code>var barData = svg.selectAll(".bar")
    .data(data)

// Bars creation
var barEnter = barData.enter()
    .append("g")
    .attr('class', 'bar')
    .attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; });

barEnter.append("rect")
    .attr("y", function(d) { return y(d.b_stars); })
    .attr("height", function(d) { return height - y(d.b_stars); })
    .attr("width", barWidth - 1)
    .attr("fill", "steelblue");

barEnter.append("text")
    .attr("x", function(d) { return height - y(d.b_stars); })
    .attr("y", -40)
    .attr("dy", ".75em")
    .text(function(d) { return d.b_name; })
    .attr("transform", "rotate(90)" );

// Update the bar if the item in data is modified and already linked to a .bar element
barData.select('rect')
    .attr("height", function(d) { return height - y(d.b_stars); })

// Remove the DOM elements linked to data items which are not anymore in the data array
barData.exit().remove()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to update the bar chart in d3 based on the input selected by the user. The updated data is being displayed but it is being displayed on the old SVG elements. I tried using exit().remove() but it did not work.
Can anyone edit the code attached below so that the old SVG elements are removed.

<select id = "variable">
                    <option >select</option>
                    <option value="AZ">Arizona</option>
                    <option value="IL">Illinois</option>
                    <option value="NV">NV</option>
</select>

Body:
Your problem here is about your bar selection. You can have a look to this part of the d3 documentation: Joining data.

By writing

bar = svg.selectAll("bar")
    .data(data)
    .enter()

You are selecting all bar elements, joining them data, and with this enter(), you are getting all the data items not linked to a bar element (enter() documentation).
But, your bar selector matches nothing. The parameter of the select()/selectAll() has to be a selector (element, class with ., id with #...). That is why the enter() your enter() selection is creating always new elements above the old ones instead of updating them.

So the first step is to rewrite this selection and creating the DOM elements that will match later this selection:

bar = svg.selectAll(".bar")
    .data(data)
    .enter()
    .append("g")
    .attr('class', 'bar')
    .attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; });

Here, we are selecting all elements with the bar class. If there is no DOM element linked to an item from data, so we are creating it (in the enter() selection), as a new g with the bar class.

With the selection written like this, on the next call of your update, the selectAll('.bar') will match all the g previously created and not apply the enter() selection for existing elements.

To update or remove your existing bars, you can write your code like this:

var barData = svg.selectAll(".bar")
    .data(data)

// Bars creation
var barEnter = barData.enter()
    .append("g")
    .attr('class', 'bar')
    .attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; });

barEnter.append("rect")
    .attr("y", function(d) { return y(d.b_stars); })
    .attr("height", function(d) { return height - y(d.b_stars); })
    .attr("width", barWidth - 1)
    .attr("fill", "steelblue");

barEnter.append("text")
    .attr("x", function(d) { return height - y(d.b_stars); })
    .attr("y", -40)
    .attr("dy", ".75em")
    .text(function(d) { return d.b_name; })
    .attr("transform", "rotate(90)" );

// Update the bar if the item in data is modified and already linked to a .bar element
barData.select('rect')
    .attr("height", function(d) { return height - y(d.b_stars); })

// Remove the DOM elements linked to data items which are not anymore in the data array
barData.exit().remove()


问:
How to consume ajax returned json data in DataTables and have a form in each row
I want to consume ajax returned data in my JQuery DataTables. I have created loop to view every row and also need to add a view button for them. I pass all data to JQuery DataTables. I cannot understand how to do that.

This is my ajax request

```<code>  <script>
        $(document).ready(function () {
            $("#searchArea").show();
            var uID = $("#userName").val();

            var tableProduct = $('#dataTbl').DataTable({
                "bSort": false
                , "oLanguage": {"sZeroRecords": "", "sEmptyTable": ""}
            });
            $.ajax({
                type: 'GET',
                url: '${pageContext.request.contextPath}/restservice/viewApplication/' + uID,
                success: function (result) {
                    var jString = JSON.stringify(result);
                    var jdata = JSON.parse(jString);

                    for (var x = 0; x < jdata.length; x++) {

                        var td1 = jdata[x].snumber;
                        var td2 = jdata[x].date;
                        var td3 = jdata[x].slsNo + " in " + jdata[x].slsiUnit;
                        var td4 = jdata[x].productDesc;
                        var td5 = jdata[x].status;
                        var td6 = "view btn1";
                        var td7 = "view btn2";
                        var td8 = "view btn3";
                        tableProduct.row.add([td1, td2, td3, td4, td5, td6, td7, td8]).draw(true);
                    }
                }
            });

        });
    </script>
</code>```

I want to add this code for every row. How can I do that ?

```<code> <form method="post" action="${pageContext.request.contextPath}/viewApplication" target="_blank">
     <input type="hidden" name="snumber" value="jdata[x].snumber"/>
     <input type="submit" class="btn btn-primary btn-block" value="View" />
     <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
 </form>
</code>```

答:
Consuming Ajax data in DataTables

There is already a handy feature in DataTables to fetch data from ajax and consume them as you configure your table. Just use the ajax option and tell about the data source you want to consume

```<code>$('#dataList').DataTable({
    ajax: {
            url: 'url',
            type: 'GET',
            dataSrc: ''
    }
}
</code>```

See this documentation for complete guideline.

Note: here passing dataSrc option as empty tells dataTable to expect an array rather than objects from ajax response

Following is a example that depicts a senario where datatable is configured to consume a api response. For demonastration purpose I used a public dummy api service that returned an json array. See this dummy api response.

$(function() {
  var columnArray = [{
      title: "Photo ID",
      data: "id",
      targets: 0
    },
    {
      title: "Photo Title",
      data: "title",
      targets: 1
    }
  ];

  $('#dataList').DataTable({
    ajax: {
      url: 'https://jsonplaceholder.typicode.com/photos',
      type: 'GET',
      dataSrc: ''
    },
    bBootstrapLayout: true,
    columns: columnArray,
    columnDefs: [{
      render: function(data, type, row) {
        return data + ' (' + row['albumId'] + ')';
      },
      targets: 0
    }, {
      render: function(data, type, row) {
        var html = '<button>view</button>';

        return html;
      },
      targets: 2
    }]
  });
});

  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
  <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
  <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />

  <head>

    <body>
      <br>
      <br>
      <div class="row">
        <div class="col-lg-1"></div>
        <div class="col-lg-6">
          <div>
            <table id="dataList" class="table" data-page-length="1" cellspacing="0" width="100%" />
          </div>
        </div>
      </div>
    </body></code>```

Having Custom button or form in row

In your datatable you can configure each column rendering logic. Like the case you are dealing, you want separate columns of button behave as form submission.
You  should tell this in columnDefs option as passing an array of definations.

In the code snippet above I also showed how you can achive that. In that example I added 3rd column (target: 2) by defining its rendering logic. In render callback you can return html that should be placed in that column. I only added <button>view</button> but as you see you can return any html like forms with input fields and buttons and whats not. render option takes a function that is provided with data, type, row parameters. Hence you can exploit these data for rendering your column html or any logic you what. Thats a lot of flexibility, isn't it ?

You will find a complementary guildline from this columnDefs documentation.

Body:
I want to consume ajax returned data in my JQuery DataTables. I have created loop to view every row and also need to add a view button for them. I pass all data to JQuery DataTables. I cannot understand how to do that.

This is my ajax request

I want to add this code for every row. How can I do that ?

 <form method="post" action="${pageContext.request.contextPath}/viewApplication" target="_blank">
     <input type="hidden" name="snumber" value="jdata[x].snumber"/>
     <input type="submit" class="btn btn-primary btn-block" value="View" />
     <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
 </form>

Body:
Consuming Ajax data in DataTables

There is already a handy feature in DataTables to fetch data from ajax and consume them as you configure your table. Just use the ajax option and tell about the data source you want to consume

$('#dataList').DataTable({
    ajax: {
            url: 'url',
            type: 'GET',
            dataSrc: ''
    }
}

See this documentation for complete guideline.

Note: here passing dataSrc option as empty tells dataTable to expect an array rather than objects from ajax response

Following is a example that depicts a senario where datatable is configured to consume a api response. For demonastration purpose I used a public dummy api service that returned an json array. See this dummy api response.

$(function() {
  var columnArray = [{
      title: "Photo ID",
      data: "id",
      targets: 0
    },
    {
      title: "Photo Title",
      data: "title",
      targets: 1
    }
  ];

  $('#dataList').DataTable({
    ajax: {
      url: 'https://jsonplaceholder.typicode.com/photos',
      type: 'GET',
      dataSrc: ''
    },
    bBootstrapLayout: true,
    columns: columnArray,
    columnDefs: [{
      render: function(data, type, row) {
        return data + ' (' + row['albumId'] + ')';
      },
      targets: 0
    }, {
      render: function(data, type, row) {
        var html = '<button>view</button>';

        return html;
      },
      targets: 2
    }]
  });
});

<head>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
  <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
  <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />

  <head>

    <body>
      <br>
      <br>
      <div class="row">
        <div class="col-lg-1"></div>
        <div class="col-lg-6">
          <div>
            <table id="dataList" class="table" data-page-length="1" cellspacing="0" width="100%" />
          </div>
        </div>
      </div>
    </body>

Having Custom button or form in row

In your datatable you can configure each column rendering logic. Like the case you are dealing, you want separate columns of button behave as form submission.
You  should tell this in columnDefs option as passing an array of definations.

In the code snippet above I also showed how you can achive that. In that example I added 3rd column (target: 2) by defining its rendering logic. In render callback you can return html that should be placed in that column. I only added <button>view</button> but as you see you can return any html like forms with input fields and buttons and whats not. render option takes a function that is provided with data, type, row parameters. Hence you can exploit these data for rendering your column html or any logic you what. Thats a lot of flexibility, isn't it ?

You will find a complementary guildline from this columnDefs documentation.


问:
Visual Studio 2010 script debugger doesn't work for me
I just installed VS 2010 Beta 2 and wanted to play with an ASP.NET MVC 2 project.  I simply added some script (alert('hello');) into the Home controller's index.aspx view, and I can see it executing.  When I try to set a breakpoint, however, it never gets hit.  I also tried to use the "debugger" keyword, and when I do, I get a disappointing "there is no source code available for the current location" message.  I also get this message when I try to independently attach to an IE process where my app is running.

What do I need to do to get a friendly script debugging experience?  (I have successfully used Firebug to debug this, but for some reason I prefer the VS debugger.)

Here are some details of my configuration:

I am launching my stuff in VS 2010 Beta 2.

IE8 version 8.0.7600.16385 is my default browser.

The "Disable script debugging (Internet Explorer)" advanced option is unchecked.

The "Disable script debugging (Other)" option is unchecked.

In my ASP.NET MVC 2 project's "web" properties tab, the ASP.NET debugger is checked.  All others are unchecked.

Visual Studio 2008 script debugging seems to work just fine.

答:
The debugger cannot debug both Silverlight code and Script code at the same time, if the Silverlight debugger is selected JavaScript debugging is switched off.

Go to the Project's Properties (Alt+Enter).

For a Web Site Project: Select "Start Options". Or for a Web Appliction: Go to the Web tab and at the bottom you will see the Debuggers option.

Check that the Silverlight checkbox is NOT ticked if you want to be able to debug JavaScript.  (It is unfortunate that the UI here is not clear about this side effect.)

ContentLicense: CC BY-SA 2.5


问:
Is it possible to set input field of react-day-picker as required?
I have two DayPickerInput fields in a form and would like to mark them as required field but don't know how. Can anybody please help?

```<code>        <FormGroup row>
            <Col md="4">
                <Label htmlFor="begin">Begin</Label>
            </Col>
            <Col xs="12" md="8">
                <DayPickerInput value={this.state.begin}
                                format={settings.formatDate} />
            </Col>
        </FormGroup>
        <FormGroup row>
            <Col md="4">
                <Label htmlFor="end">End</Label>
            </Col>
            <Col xs="12" md="8">
                <DayPickerInput value={this.state.end}
                                format={settings.formatDate} />
            </Col>
        </FormGroup>
</code>```

UPDATE: I tried with inputProps:

```<code><DayPickerInput inputProps={required} />
</code>```

but got error:

```<code>ReferenceError: required is not defined
</code>```

答:
You have to implement it at form-validation-level. Checkout Formik:

https://github.com/jaredpalmer/formik

Body:
I have two DayPickerInput fields in a form and would like to mark them as required field but don't know how. Can anybody please help?

        <FormGroup row>
            <Col md="4">
                Begin
            </Col>
            <Col xs="12" md="8">
                <DayPickerInput value={this.state.begin}
                                format={settings.formatDate} />
            </Col>
        </FormGroup>
        <FormGroup row>
            <Col md="4">
                End
            </Col>
            <Col xs="12" md="8">
                <DayPickerInput value={this.state.end}
                                format={settings.formatDate} />
            </Col>
        </FormGroup>

UPDATE: I tried with inputProps:

<DayPickerInput inputProps={required} />

but got error:

ReferenceError: required is not defined


问:
Optimizer does not optimize any variable
I would like to solve my optimization problem but the optimizer does not work. I expect an array of solutions with minimum difference to the given value, but my calculated softmax function is 1 all the time, because the weights and biases are not updated in the iterations. They are both tensors of zeros. How can I fix this problem?</p>

```<code>#KI-Model
x = tf.placeholder(tf.float32, [None, 5], name='input') #x_1-x_5

#Init
W = tf.Variable(tf.zeros([5,1]), dtype=tf.float32)
b = tf.Variable(tf.zeros([1]), dtype=tf.float32)

#Sigmoid
y = tf.nn.softmax(tf.matmul(x, W) + b)

#Training
y_tensor = tf.placeholder(tf.float32, [None, 1], name='output')

loss = y-y_tensor
cost = tf.square(loss)
optimizer = tf.train.GradientDescentOptimizer(0.003).minimize(cost)

#Start
session = tf.Session()
init = tf.global_variables_initializer()
session.run(init)

#init first 1000 training_batches
for i in range(1000):
    batch_xs.append([dataA[i], dataB[i], dataC[i], dataD[i],
              dataE[i]])
    batch_ys.append([solution[i]])

for i in range(10000):

    session.run(optimizer, feed_dict={x:batch_xs, y_tensor:batch_ys})

print(session.run(y, feed_dict={x:batch_xs, y_tensor:batch_ys}) )
</code>```

答:
You didn't compute and applied the gradients.
These lines have been missing:

```<code>gradients = optimizer.compute_gradients(loss=cost)
train_step = optimizer.apply_gradients(grads_and_vars=gradients)
</code>```

You also need to run the train step on each iteration, with this line:

```<code>session.run(train_step, feed_dict={x:batch_xs, y_tensor:batch_ys})
</code>```

The full correct code:

```<code>#KI-Model
x = tf.placeholder(tf.float32, [None, 5], name='input') #x_1-x_5

#Init
W = tf.Variable(tf.zeros([5,1]), dtype=tf.float32)
b = tf.Variable(tf.zeros([1]), dtype=tf.float32)

#Sigmoid
y = tf.nn.softmax(tf.matmul(x, W) + b)

#Training
y_tensor = tf.placeholder(tf.float32, [None, 1], name='output')

loss = y-y_tensor
cost = tf.square(loss)
optimizer = tf.train.GradientDescentOptimizer(0.003)
gradients = optimizer.compute_gradients(loss=cost)
train_step = optimizer.apply_gradients(grads_and_vars=gradients)

#Start
session = tf.Session()
init = tf.global_variables_initializer()
session.run(init)

#init first 1000 training_batches
for i in range(1000):
    batch_xs.append([dataA[i], dataB[i], dataC[i], dataD[i],
              dataE[i]])
    batch_ys.append([solution[i]])

for i in range(10000):

    session.run(train_step, feed_dict={x:batch_xs, y_tensor:batch_ys})

print(session.run(y, feed_dict={x:batch_xs, y_tensor:batch_ys}) )
</code>```

Body:
I would like to solve my optimization problem but the optimizer does not work. I expect an array of solutions with minimum difference to the given value, but my calculated softmax function is 1 all the time, because the weights and biases are not updated in the iterations. They are both tensors of zeros. How can I fix this problem?

#KI-Model
x = tf.placeholder(tf.float32, [None, 5], name='input') #x_1-x_5

#Init
W = tf.Variable(tf.zeros([5,1]), dtype=tf.float32)
b = tf.Variable(tf.zeros([1]), dtype=tf.float32)

#Sigmoid
y = tf.nn.softmax(tf.matmul(x, W) + b)

#Training
y_tensor = tf.placeholder(tf.float32, [None, 1], name='output')

loss = y-y_tensor
cost = tf.square(loss)
optimizer = tf.train.GradientDescentOptimizer(0.003).minimize(cost)

#Start
session = tf.Session()
init = tf.global_variables_initializer()
session.run(init)

#init first 1000 training_batches
for i in range(1000):
    batch_xs.append([dataA[i], dataB[i], dataC[i], dataD[i],
              dataE[i]])
    batch_ys.append([solution[i]])

for i in range(10000):

    session.run(optimizer, feed_dict={x:batch_xs, y_tensor:batch_ys})

print(session.run(y, feed_dict={x:batch_xs, y_tensor:batch_ys}) )

Body:
You didn't compute and applied the gradients.
These lines have been missing:

gradients = optimizer.compute_gradients(loss=cost)
train_step = optimizer.apply_gradients(grads_and_vars=gradients)

You also need to run the train step on each iteration, with this line:

session.run(train_step, feed_dict={x:batch_xs, y_tensor:batch_ys})

The full correct code:

#KI-Model
x = tf.placeholder(tf.float32, [None, 5], name='input') #x_1-x_5

#Init
W = tf.Variable(tf.zeros([5,1]), dtype=tf.float32)
b = tf.Variable(tf.zeros([1]), dtype=tf.float32)

#Sigmoid
y = tf.nn.softmax(tf.matmul(x, W) + b)

#Training
y_tensor = tf.placeholder(tf.float32, [None, 1], name='output')

loss = y-y_tensor
cost = tf.square(loss)
optimizer = tf.train.GradientDescentOptimizer(0.003)
gradients = optimizer.compute_gradients(loss=cost)
train_step = optimizer.apply_gradients(grads_and_vars=gradients)

#Start
session = tf.Session()
init = tf.global_variables_initializer()
session.run(init)

#init first 1000 training_batches
for i in range(1000):
    batch_xs.append([dataA[i], dataB[i], dataC[i], dataD[i],
              dataE[i]])
    batch_ys.append([solution[i]])

for i in range(10000):

    session.run(train_step, feed_dict={x:batch_xs, y_tensor:batch_ys})

print(session.run(y, feed_dict={x:batch_xs, y_tensor:batch_ys}) )


问:
Populate form fields with Django forms after raise validation error
i need help, im new with django forms o how its work.Have a html form and i encrypted the values with javascript when the form is submited like this

```<code>$("#form").submit(function(){
    //remplace the original value and send to the server the encrypted data
    $("#field1").val(encrypted_data);
    $("#field2").val(encrypted_data);
return true
});
</code>```

I have this class in my django project

```<code>class SomeForm(forms.Form):

field1 = forms.CharField(label="field 1")
field2 = forms.CharField(label="field 1")

clean_field1(self):
 data = decrypt_text(self.cleaned_data['field1'])
 p = re.compile(r'[\d]{8}')
 #validate decrypt data is a number and his lengt is more than 8
 if p.match(data) is None:
    raise forms.ValidationError("Error")

 return data
</code>```

this work fine, the problem is when the data es invalid, i need pass to the field the original value, and currently returns the field with de encrypted value.

thanks in advance!!

答:
This is how you do it:
In your post() method in the class based view, you will have this condition

```<code>if form.is_valid():
# you do whatever you want with this form
else:
# when your form raises a validation error, this snippet gets executed
#so you need to write the following lines in the else condition to
#repopulate your form:
context['form'] = self.form_class(self.request.POST)
return render(request, self.template_name, context)
</code>```

Now when you have a validation error, you can see it there in the template as well.
Hope you found this useful

Body:
i need help, im new with django forms o how its work.Have a html form and i encrypted the values with javascript when the form is submited like this

$("#form").submit(function(){
    //remplace the original value and send to the server the encrypted data
    $("#field1").val(encrypted_data);
    $("#field2").val(encrypted_data);
return true
});

I have this class in my django project

class SomeForm(forms.Form):

field1 = forms.CharField(label="field 1")
field2 = forms.CharField(label="field 1")

clean_field1(self):
 data = decrypt_text(self.cleaned_data['field1'])
 p = re.compile(r'[\d]{8}')
 #validate decrypt data is a number and his lengt is more than 8
 if p.match(data) is None:
    raise forms.ValidationError("Error")

 return data

this work fine, the problem is when the data es invalid, i need pass to the field the original value, and currently returns the field with de encrypted value.

thanks in advance!!

Body:
This is how you do it:
In your post() method in the class based view, you will have this condition

if form.is_valid():
# you do whatever you want with this form
else:
# when your form raises a validation error, this snippet gets executed
#so you need to write the following lines in the else condition to
#repopulate your form:
context['form'] = self.form_class(self.request.POST)
return render(request, self.template_name, context)

Now when you have a validation error, you can see it there in the template as well.
Hope you found this useful


问:
Replace static JSON data with $HTTP request in AngularJS factory
Have some troubles with replacing static JSON data in AngularJS factory, here is example with static data:

```<code>    angular.module('starter.services', [])
    .factory('catgs', function($http) {
      var catgs = [{
        id: 19,
        name: 'CATG20'
},{
        id: 20,
        name: 'CATG21'
      }];
      return {
        all: function() {
          return catgs;
        },
        remove: function(catg) {
          catgs.splice(catgs.indexOf(catg), 1);
        },
        get: function(catgId) {
          for (var i = 0; i < catgs.length; i++) {
            if (catgs[i].id === parseInt(catgId)) {
              return catgs[i];
            }
          }
          return null;
        }
      };
    });
</code>```

Need replace static var catgs with $http.get from json data url. I'm new in Angular and need help with this issue.

答:
What about    </p>

```<code> angular.module('starter.services', [])
        .factory('catgs', function($http) {
          var catgs =null;
          return {
            all: function() {
              if(catgs != null)
              return catgs;
              $http.get('myurl').then(function(res){
               catgs=res.data;//
               return catgs;
             })
            },
            remove: function(catg) {
              catgs.splice(catgs.indexOf(catg), 1);
            },
            get: function(catgId) {
              for (var i = 0; i < catgs.length; i++) {
                if (catgs[i].id === parseInt(catgId)) {
                  return catgs[i];
                }
              }
              return null;
            }
          };
        });
</code>```

Body:
Have some troubles with replacing static JSON data in AngularJS factory, here is example with static data:

    angular.module('starter.services', [])
    .factory('catgs', function($http) {
      var catgs = [{
        id: 19,
        name: 'CATG20'
},{
        id: 20,
        name: 'CATG21'
      }];
      return {
        all: function() {
          return catgs;
        },
        remove: function(catg) {
          catgs.splice(catgs.indexOf(catg), 1);
        },
        get: function(catgId) {
          for (var i = 0; i < catgs.length; i++) {
            if (catgs[i].id === parseInt(catgId)) {
              return catgs[i];
            }
          }
          return null;
        }
      };
    });

Need replace static var catgs with $http.get from json data url. I'm new in Angular and need help with this issue.

Body:
What about

 angular.module('starter.services', [])
        .factory('catgs', function($http) {
          var catgs =null;
          return {
            all: function() {
              if(catgs != null)
              return catgs;
              $http.get('myurl').then(function(res){
               catgs=res.data;//
               return catgs;
             })
            },
            remove: function(catg) {
              catgs.splice(catgs.indexOf(catg), 1);
            },
            get: function(catgId) {
              for (var i = 0; i < catgs.length; i++) {
                if (catgs[i].id === parseInt(catgId)) {
                  return catgs[i];
                }
              }
              return null;
            }
          };
        });


问:
What are the thing we need to configure to implement live notification module (using redis and socket.io) in https server?
I have done a successfully live notification module in my local machine. I need to implement this module in live server. Live server is https. I don't know what are the things we need to change for https. Please check my code and help to integrate this on https server. Thanks.

ssl files

```<code>SSLCertificateFile /etc/letsencrypt/live/dev.test.de/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/dev.test.de/privkey.pem
</code>```

socket.js

```<code>var app   = require('express')();
var http  = require('http').Server(app);
var io    = require('socket.io')(http);
var redis = require('redis');

io.on('connection', function(socket){
    console.log('a user connected');

    var redisClient = redis.createClient();

    /* Realtime message subscribe */
    redisClient.subscribe('message');
    redisClient.on('message', function(channel, message){
        /*console.log('new message in queue', channel, message);*/
        socket.emit(channel, message);
    });

    /* Realtime inquiry subscribe */
    redisClient.subscribe('inquiryCount');
    redisClient.on('inquiryCount', function(channel, message){
        /*console.log('new inquiry in queue', channel, message);*/
        socket.emit(channel, message);
    });

    socket.on('disconnect', function(){
        redisClient.quit();
        console.log('user disconnected');
    });
});

http.listen(3000, function(){
    console.log('listening on *:3000');
});
</code>```

app.blade.php

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script>
    <script>
        var socket = io('{{env('APP_URL')}}:3000');
        /* Realtime message notification */
        socket.on('message', function(data){
           if(data){
               /* var res = $.parseJSON(data);*/
               $('.messages-menu').empty();
               $('.messages-menu').html(data);
           }
        });
        /* Realtime inquiry notification */
        socket.on('inquiryCount', function(data){
            if(data){
                $('.tasks-menu').empty();
                $('.tasks-menu').html(data);
            }
        });
    </script>
</code>```

DashboardController.php

```<code>public function privateMessageAPICount($id)
{
      $message = 'taking count of data';
      if(count($message) > 0){
           $redis = Redis::connection();
                $redis->publish('message', $message);
                return response()->json(['status' => 'success'], 200);
        }
        else {
            return response()->json(['status' => 'No Result'], 404);
        }
 }

public function inquiryAPIUnreadCount($id)
{
   $inquiryCount .= 'taking count of data';
   if(count($inquiryCount ) > 0){
         $redis = Redis::connection();
          $redis->publish('inquiryCount', $inquiryCount);
          return response()->json(['status' => 'success'], 200);
        }
        else {
            return response()->json(['status' => 'No Result'], 404);
        }
 }
</code>```

答:
This is my working socket_https.js :

```<code>const fs = require('fs');

const options = {
    key: fs.readFileSync('/etc/letsencrypt/live/dev.test.de/privkey.pem'),
    cert: fs.readFileSync('/etc/letsencrypt/live/dev.test.de/fullchain.pem'),
    NPNProtocols: ['http/2.0', 'spdy', 'http/1.1', 'http/1.0']
};

var server = require('https').Server(options);

var io = require('socket.io')(server);

var Redis = require('ioredis');
var redis = new Redis();

redis.subscribe('message-channel');

redis.on('message', function (channel, message) {
    console.log('Message Receive');
    console.log(message);
    message = JSON.parse(message);

    io.emit(channel + ':' + message.event, message.data);
});

server.listen(4000);
</code>```

Then When I want to publish to redis :

```<code>$data = [
      'event' => 'someEvent',
      'data'  => [
                      'id' => $id,
                      [...]
                  ]
];

Redis::publish('my-channel', json_encode($data));
</code>```

Body:
I have done a successfully live notification module in my local machine. I need to implement this module in live server. Live server is https. I don't know what are the things we need to change for https. Please check my code and help to integrate this on https server. Thanks.

ssl files

SSLCertificateFile /etc/letsencrypt/live/dev.test.de/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/dev.test.de/privkey.pem

socket.js

var app   = require('express')();
var http  = require('http').Server(app);
var io    = require('socket.io')(http);
var redis = require('redis');

io.on('connection', function(socket){
    console.log('a user connected');

    var redisClient = redis.createClient();

    /* Realtime message subscribe */
    redisClient.subscribe('message');
    redisClient.on('message', function(channel, message){
        /*console.log('new message in queue', channel, message);*/
        socket.emit(channel, message);
    });

    /* Realtime inquiry subscribe */
    redisClient.subscribe('inquiryCount');
    redisClient.on('inquiryCount', function(channel, message){
        /*console.log('new inquiry in queue', channel, message);*/
        socket.emit(channel, message);
    });

    socket.on('disconnect', function(){
        redisClient.quit();
        console.log('user disconnected');
    });
});

http.listen(3000, function(){
    console.log('listening on *:3000');
});

app.blade.php

DashboardController.php

public function privateMessageAPICount($id)
{
      $message = 'taking count of data';
      if(count($message) > 0){
           $redis = Redis::connection();
                $redis->publish('message', $message);
                return response()->json(['status' => 'success'], 200);
        }
        else {
            return response()->json(['status' => 'No Result'], 404);
        }
 }

public function inquiryAPIUnreadCount($id)
{
   $inquiryCount .= 'taking count of data';
   if(count($inquiryCount ) > 0){
         $redis = Redis::connection();
          $redis->publish('inquiryCount', $inquiryCount);
          return response()->json(['status' => 'success'], 200);
        }
        else {
            return response()->json(['status' => 'No Result'], 404);
        }
 }

Body:
This is my working socket_https.js :

const fs = require('fs');

const options = {
    key: fs.readFileSync('/etc/letsencrypt/live/dev.test.de/privkey.pem'),
    cert: fs.readFileSync('/etc/letsencrypt/live/dev.test.de/fullchain.pem'),
    NPNProtocols: ['http/2.0', 'spdy', 'http/1.1', 'http/1.0']
};

var server = require('https').Server(options);

var io = require('socket.io')(server);

var Redis = require('ioredis');
var redis = new Redis();

redis.subscribe('message-channel');

redis.on('message', function (channel, message) {
    console.log('Message Receive');
    console.log(message);
    message = JSON.parse(message);

    io.emit(channel + ':' + message.event, message.data);
});

server.listen(4000);

Then When I want to publish to redis :

$data = [
      'event' => 'someEvent',
      'data'  => [
                      'id' => $id,
                      [...]
                  ]
];

Redis::publish('my-channel', json_encode($data));


问:
UWP: crash report and events tracing
I've developed an UWP app for a client: as we encountered some bugs that I can't reproduce on my device, we've implemented a crash reporting solution.

HockeyApp

In a first time, I used HockeyApp like this to use crash report:

```<code>HockeyClient.Current.Configure("xxxxxx",
  new TelemetryConfiguration() { EnableDiagnostics = true })
    .SetExceptionDescriptionLoader((Exception ex) =>
    {
      return "Exception HResult: " + ex.HResult.ToString();
    });
</code>```

But as explained on another topic, the crashes were reported, but this didn't  allow me to identify the problems as I didn't get enough details.

So as someone suggested I've uploaded the .pdb files from the Store to HockeyApp: but this time the symbols from the crashes and the .pdf files don't match.

I decided to use TrackEvent to analyze the problems. I've done somes tests on a function by adding:

```<code>Microsoft.HockeyApp.HockeyClient.Current.TrackTrace("MyViewModel - CheckUser()");
</code>```

But the events are not reported in HockeyApp...

=> Would you have an explanation? Did I forgot anything? I will publish a new package on the Store and re-upload the .pdb files to HockeyApp, but I don't see what I could do else...

AppCenter

As AppCenter is now avaiable for UWP, I've done the same tests. I've implemented AppCenter like this:

```<code>AppCenter.Start("xxxxxx-xxx"
  , typeof(Analytics)
  , typeof(Crashes));
</code>```

But unlike HockeyApp, crashes are not reported at all. AppCenter identifies well the app, as an entry is added on the "Crashes" tab with the current version number when the app is launched.

I also added Events with:

```<code>Analytics.TrackEvent("MyViewModel - CheckUser()");
</code>```

But this time the events are well reported in AppCenter.

=> Did anyone ever use AppCenter for Crash Report on UWP? Is there anything else to add?

Conclusion

For now I have to use 2 tools, but it's not really helpful:

HockeyApp for crash report

AppCenter for Events

=>Do you have any other suggestions or tools that could help me?

答:
I decided to use TrackEvent to analyze the problems...But the events are not reported in HockeyApp...

If you want to use TrackEvent, you need to use TrackEvent() API instead of TrackTrace().

```<code>HockeyClient.Current.TrackEvent("Button Clicked");
</code>```

You can check the custom events in your HockeyApp dashboard by log in your account -> click the app -> Events.

Notice that the custom event will not show immediately, usually it takes around 10-15 minutes. Also it has limits. see here.

As you mentioned, you need to upload the right .pdb files to HockeyApp dashboard, after that the crashes will be symbolicated.

It seems the app you uploaded is a store version.Therefore you need to download the .pdb files from Windows Dev Store. see here.

You can check whether it is a right one by comparing the Id of the.pdb and the Binary Image in your crash. For example,
Both are e5502c5ddc5748a899a8182d8a52a659, it means the .pdb files are the right one.

Also in order to get symbolicated crashes, you need to make sure the crashes you made are from Store version (download from Windows Store).You cannot crash your app with the beta version or directly from Visual Studio with the .pdb from Store.

As for AppCenter, it is the next generation of HockeyApp and it is still in the preview. Crash reporting on windows now requires the app to be distributed through the Windows Store, crash for sideload is not supported yet.
You can refer to the official doc here.
However it will take place of HockeyApp in the long run, therefore you can wait for the official release of App Center.

Title: UWP: crash report and events tracing

Body:
I've developed an UWP app for a client: as we encountered some bugs that I can't reproduce on my device, we've implemented a crash reporting solution.

HockeyApp

In a first time, I used HockeyApp like this to use crash report:

HockeyClient.Current.Configure("xxxxxx",
  new TelemetryConfiguration() { EnableDiagnostics = true })
    .SetExceptionDescriptionLoader((Exception ex) =>
    {
      return "Exception HResult: " + ex.HResult.ToString();
    });

But as explained on another topic, the crashes were reported, but this didn't  allow me to identify the problems as I didn't get enough details.

So as someone suggested I've uploaded the .pdb files from the Store to HockeyApp: but this time the symbols from the crashes and the .pdf files don't match.

I decided to use TrackEvent to analyze the problems. I've done somes tests on a function by adding:

Microsoft.HockeyApp.HockeyClient.Current.TrackTrace("MyViewModel - CheckUser()");

But the events are not reported in HockeyApp...

=> Would you have an explanation? Did I forgot anything? I will publish a new package on the Store and re-upload the .pdb files to HockeyApp, but I don't see what I could do else...

AppCenter

As AppCenter is now avaiable for UWP, I've done the same tests. I've implemented AppCenter like this:

AppCenter.Start("xxxxxx-xxx"
  , typeof(Analytics)
  , typeof(Crashes));

But unlike HockeyApp, crashes are not reported at all. AppCenter identifies well the app, as an entry is added on the "Crashes" tab with the current version number when the app is launched.

I also added Events with:

Analytics.TrackEvent("MyViewModel - CheckUser()");

But this time the events are well reported in AppCenter.

=> Did anyone ever use AppCenter for Crash Report on UWP? Is there anything else to add?

Conclusion

For now I have to use 2 tools, but it's not really helpful:

HockeyApp for crash report

AppCenter for Events

=>Do you have any other suggestions or tools that could help me?

Body:
I decided to use TrackEvent to analyze the problems...But the events are not reported in HockeyApp...

If you want to use TrackEvent, you need to use TrackEvent() API instead of TrackTrace().

HockeyClient.Current.TrackEvent("Button Clicked");

You can check the custom events in your HockeyApp dashboard by log in your account -> click the app -> Events.

Notice that the custom event will not show immediately, usually it takes around 10-15 minutes. Also it has limits. see here.

As you mentioned, you need to upload the right .pdb files to HockeyApp dashboard, after that the crashes will be symbolicated.

It seems the app you uploaded is a store version.Therefore you need to download the .pdb files from Windows Dev Store. see here.

You can check whether it is a right one by comparing the Id of the.pdb and the Binary Image in your crash. For example,
Both are e5502c5ddc5748a899a8182d8a52a659, it means the .pdb files are the right one.

Also in order to get symbolicated crashes, you need to make sure the crashes you made are from Store version (download from Windows Store).You cannot crash your app with the beta version or directly from Visual Studio with the .pdb from Store.

As for AppCenter, it is the next generation of HockeyApp and it is still in the preview. Crash reporting on windows now requires the app to be distributed through the Windows Store, crash for sideload is not supported yet.
You can refer to the official doc here.
However it will take place of HockeyApp in the long run, therefore you can wait for the official release of App Center.


问:
MPAndroid Group bar chart is not showing
Here is the code i used for group bar_chart using MPAndroid library version 3. I've tried group bar chart in lower version and it works fine but the BarData constructor is changed in latest version. And this code doesn't works. There is no crashes and error logs, still graph is loading and no data shows in it. Help me to find ma flaws

```<code>        List<BarEntry> entriesGroup1 = new ArrayList<>();
        List<BarEntry> entriesGroup2 = new ArrayList<>();
        List<BarEntry> entriesGroup3 = new ArrayList<>();

        entriesGroup1.add(new BarEntry(0, 8f));
        entriesGroup1.add(new BarEntry(1, 2f));
        entriesGroup1.add(new BarEntry(2, 5f));
        entriesGroup1.add(new BarEntry(3, 20f));
        entriesGroup1.add(new BarEntry(4, 15f));
        entriesGroup1.add(new BarEntry(5, 19f));

        entriesGroup2.add(new BarEntry(0, 6f));
        entriesGroup2.add(new BarEntry(1, 10f));
        entriesGroup2.add(new BarEntry(2, 5f));
        entriesGroup2.add(new BarEntry(3, 25f));
        entriesGroup2.add(new BarEntry(4, 4f));
        entriesGroup2.add(new BarEntry(5, 17f));

        entriesGroup3.add(new BarEntry(0, 9f));
        entriesGroup3.add(new BarEntry(1, 1f));
        entriesGroup3.add(new BarEntry(2, 15f));
        entriesGroup3.add(new BarEntry(3, 13f));
        entriesGroup3.add(new BarEntry(4, 40f));
        entriesGroup3.add(new BarEntry(5, 25f));

        BarDataSet set1 = new BarDataSet(entriesGroup1, "Group 1");
        BarDataSet set2 = new BarDataSet(entriesGroup2, "Group 2");
        BarDataSet set3 = new BarDataSet(entriesGroup3, "Group 3");

        final ArrayList<String> labels = new ArrayList<String>();
        labels.add("2016");
        labels.add("2015");
        labels.add("2014");
        labels.add("2013");
        labels.add("2012");
        labels.add("2011");
        IAxisValueFormatter formatter = new IAxisValueFormatter() {

            @Override
            public String getFormattedValue(float value, AxisBase axis) {

                if((int) value < 0 || (int) value >= labels.size()){
                    return "";
                }else{
                    return labels.get((int) value);
                }
            }

            // we don't draw numbers, so no decimal digits needed
            @Override
            public int getDecimalDigits() {  return 0; }
        };

        set1.setColor(Color.parseColor("#cd5080"));
        set2.setColor(Color.parseColor("#0d5080"));
        set3.setColor(Color.parseColor("#fc5080"));;

        float groupSpace = 0.06f;
        float barSpace = 0.02f; // x2 dataset
        float barWidth = 0.45f; // x2 dataset
// (0.02 + 0.45) * 2 + 0.06 = 1.00 -> interval per "group"

        XAxis xAxis = barChart.getXAxis();
        xAxis.setCenterAxisLabels(true);
        xAxis.setGranularity(1f); // minimum axis-step (interval) is 1
        xAxis.setValueFormatter(formatter);

        BarData data = new BarData(set1, set2, set3);
        data.setBarWidth(barWidth); // set the width of each bar
        barChart.setData(data);
        barChart.groupBars(2016, groupSpace, barSpace);
        barChart.invalidate(); // refresh

        barChart.animateY(5000);
</code>```

Nb: I'm edited my current question since i'm banned to ask new questions. But its important for me. Thanks everyone.

答:
Use blow code :

```<code>    public boolean isActivityRunning(Context context) {
   boolean isActivityFound = false;
    ActivityManager activityManager = (ActivityManager)context.getSystemService (Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> activitys = activityManager.getRunningTasks(Integer.MAX_VALUE);

    for (int i = 0; i < activitys.size(); i++) {
        if (activitys.get(i).topActivity.toString().equalsIgnoreCase("ComponentInfo{com.example.testapp/com.example.testapp.Your_Activity_Name}")) {
            isActivityFound = true;
        }
    }
    return isActivityFound;
}
</code>```

here com.example.testapp is your package name

need to add the permission to your manifest..

```<code><uses-permission  android:name="android.permission.GET_TASKS"/>
</code>```

it returns u activity running or not by using name on it and also change as your requirement .

UPDATE

```<code>public static ArrayList<ActivityInfo> getAllRunningActivities(Context context) {
try {
    PackageInfo pi = context.getPackageManager().getPackageInfo(
            context.getPackageName(), PackageManager.GET_ACTIVITIES);

    return new ArrayList<>(Arrays.asList(pi.activities));

} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
    return null;
}
}
</code>```

This method give u list of all running activitys in your project

Body:
Here is the code i used for group bar_chart using MPAndroid library version 3. I've tried group bar chart in lower version and it works fine but the BarData constructor is changed in latest version. And this code doesn't works. There is no crashes and error logs, still graph is loading and no data shows in it. Help me to find ma flaws

        List<BarEntry> entriesGroup1 = new ArrayList<>();
        List<BarEntry> entriesGroup2 = new ArrayList<>();
        List<BarEntry> entriesGroup3 = new ArrayList<>();

        entriesGroup1.add(new BarEntry(0, 8f));
        entriesGroup1.add(new BarEntry(1, 2f));
        entriesGroup1.add(new BarEntry(2, 5f));
        entriesGroup1.add(new BarEntry(3, 20f));
        entriesGroup1.add(new BarEntry(4, 15f));
        entriesGroup1.add(new BarEntry(5, 19f));

        entriesGroup2.add(new BarEntry(0, 6f));
        entriesGroup2.add(new BarEntry(1, 10f));
        entriesGroup2.add(new BarEntry(2, 5f));
        entriesGroup2.add(new BarEntry(3, 25f));
        entriesGroup2.add(new BarEntry(4, 4f));
        entriesGroup2.add(new BarEntry(5, 17f));

        entriesGroup3.add(new BarEntry(0, 9f));
        entriesGroup3.add(new BarEntry(1, 1f));
        entriesGroup3.add(new BarEntry(2, 15f));
        entriesGroup3.add(new BarEntry(3, 13f));
        entriesGroup3.add(new BarEntry(4, 40f));
        entriesGroup3.add(new BarEntry(5, 25f));

        BarDataSet set1 = new BarDataSet(entriesGroup1, "Group 1");
        BarDataSet set2 = new BarDataSet(entriesGroup2, "Group 2");
        BarDataSet set3 = new BarDataSet(entriesGroup3, "Group 3");

        final ArrayList<String> labels = new ArrayList<String>();
        labels.add("2016");
        labels.add("2015");
        labels.add("2014");
        labels.add("2013");
        labels.add("2012");
        labels.add("2011");
        IAxisValueFormatter formatter = new IAxisValueFormatter() {

            @Override
            public String getFormattedValue(float value, AxisBase axis) {

                if((int) value < 0 || (int) value >= labels.size()){
                    return "";
                }else{
                    return labels.get((int) value);
                }
            }

            // we don't draw numbers, so no decimal digits needed
            @Override
            public int getDecimalDigits() {  return 0; }
        };

        set1.setColor(Color.parseColor("#cd5080"));
        set2.setColor(Color.parseColor("#0d5080"));
        set3.setColor(Color.parseColor("#fc5080"));;

        float groupSpace = 0.06f;
        float barSpace = 0.02f; // x2 dataset
        float barWidth = 0.45f; // x2 dataset
// (0.02 + 0.45) * 2 + 0.06 = 1.00 -> interval per "group"

        XAxis xAxis = barChart.getXAxis();
        xAxis.setCenterAxisLabels(true);
        xAxis.setGranularity(1f); // minimum axis-step (interval) is 1
        xAxis.setValueFormatter(formatter);

        BarData data = new BarData(set1, set2, set3);
        data.setBarWidth(barWidth); // set the width of each bar
        barChart.setData(data);
        barChart.groupBars(2016, groupSpace, barSpace);
        barChart.invalidate(); // refresh

        barChart.animateY(5000);

Nb: I'm edited my current question since i'm banned to ask new questions. But its important for me. Thanks everyone.

Body:
Use blow code :

    public boolean isActivityRunning(Context context) {
   boolean isActivityFound = false;
    ActivityManager activityManager = (ActivityManager)context.getSystemService (Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> activitys = activityManager.getRunningTasks(Integer.MAX_VALUE);

    for (int i = 0; i < activitys.size(); i++) {
        if (activitys.get(i).topActivity.toString().equalsIgnoreCase("ComponentInfo{com.example.testapp/com.example.testapp.Your_Activity_Name}")) {
            isActivityFound = true;
        }
    }
    return isActivityFound;
}

here com.example.testapp is your package name

need to add the permission to your manifest..

<uses-permission  android:name="android.permission.GET_TASKS"/>

it returns u activity running or not by using name on it and also change as your requirement .

UPDATE

public static ArrayList<ActivityInfo> getAllRunningActivities(Context context) {
try {
    PackageInfo pi = context.getPackageManager().getPackageInfo(
            context.getPackageName(), PackageManager.GET_ACTIVITIES);

    return new ArrayList<>(Arrays.asList(pi.activities));

} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
    return null;
}
}

This method give u list of all running activitys in your project


问:
Angular 2 component doesnt render even if i put it in NgModule
I have a problem with rendering custom component. Even if i put my shared module in NgModule it doesnt render. I get an error where it says that i should add component to NgModule or add property schemas with parameter CUSTOM_ELEMENTS_SCHEMA. As i said i added component to shared module and shared module to component where i want to use it. And then i tried with CUSTOM_ELEMENTS_SCHEMA and i got rid of and error but it doesnt render the content of "custom" component it just renders the tag od the comp.

Custom component module

checkbox.module.ts

```<code>import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms';

import { CheckboxComponent } from './checkbox.component';

@NgModule({
    imports: [FormsModule],
    exports: [CheckboxComponent],
    declarations: [CheckboxComponent]
})
export class CheckboxModule { }
</code>```

Shared module

shared.module.ts

Edit:

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CheckboxModule, CheckboxComponent } from '../components/checkbox';
@NgModule({
    imports: [
        CommonModule,
        CheckboxModule
    ],
    declarations: [],
    exports: [ CheckboxComponent ]
})
export class SharedModule { }
</code>```

Module where i am trying to use shared module and custom component tag:

dashboard.module.ts

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DashboardComponent } from './dashboard.component';
import { SharedModule } from '../shared/shared.module';
@NgModule({
    imports: [
        SharedModule,
        CommonModule
    ],
   declarations: [DashboardComponent]
})

export class DashboardModule { }
</code>```

And it renders like a tag with no content

```<code><app-checkbox _ngcontent-c1 name="sth"></app-checkbox>
</code>```

答: You are declaring CheckboxComponent in two modules. It should be enough to declare it in shared module</p>

Body:
I have a problem with rendering custom component. Even if i put my shared module in NgModule it doesnt render. I get an error where it says that i should add component to NgModule or add property schemas with parameter CUSTOM_ELEMENTS_SCHEMA. As i said i added component to shared module and shared module to component where i want to use it. And then i tried with CUSTOM_ELEMENTS_SCHEMA and i got rid of and error but it doesnt render the content of "custom" component it just renders the tag od the comp.

Custom component module

checkbox.module.ts

import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms';

import { CheckboxComponent } from './checkbox.component';

@NgModule({
    imports: [FormsModule],
    exports: [CheckboxComponent],
    declarations: [CheckboxComponent]
})
export class CheckboxModule { }

Shared module

shared.module.ts

Edit:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CheckboxModule, CheckboxComponent } from '../components/checkbox';
@NgModule({
    imports: [
        CommonModule,
        CheckboxModule
    ],
    declarations: [],
    exports: [ CheckboxComponent ]
})
export class SharedModule { }

Module where i am trying to use shared module and custom component tag:

dashboard.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DashboardComponent } from './dashboard.component';
import { SharedModule } from '../shared/shared.module';
@NgModule({
    imports: [
        SharedModule,
        CommonModule
    ],
   declarations: [DashboardComponent]
})

export class DashboardModule { }

And it renders like a tag with no content

<app-checkbox _ngcontent-c1 name="sth"></app-checkbox>


问:
binding not working in knockout JS
HTML code.

```<code><ul id="cat-list" data-bind="foreach: catList()">
    <li data-bind="text: name, click: $parent.setCurrentCat"> </li>
</ul>
<div id="cat" data-bind="with: currentCat()">

    <h2 data-bind="text: name" id="cat-name"></h2>

    <div data-bind="text: clickCount" id="cat-count"></div>
    <img src="" data-bind="click: $parent.incrementCount, attr: {src: imgSrc}" id="cat-img" alt="cute cat">
    <h4>NickNames</h4>
    <ul data-bind="foreach: nickNames">
        <li data-bind="text: $data"></li>
    </ul>

</div>
<script src="js/lib/knockout-3.2.0.js"></script>
<script src="js/app.js"></script>
</code>```

The JS code:

```<code>var ViewModel = function() {
     var self = this;

    this.catList = ko.observableArray([]);
    initialCats.forEach(function(catItem) {
        self.catList.push( new Cat(catItem) );
    });

    this.currentCat = ko.observable( this.catList()[0]);

    this.incrementCount = function(){
        self.currentCat().clickCount(self.currentCat().clickCount()+1);
    };
    this.setCurrentCat = function(cat) {

    self.currentCat = ko.observable(cat);
    console.log(self.currentCat);
}

var Cat = function(data) {
    this.clickCount = ko.observable(data.clickCount);
    this.name = ko.observable(data.name);
    this.imgSrc = ko.observable(data.imgSrc);
    this.imgAttribution = ko.observable(data.imgAttribution);
    this.nickNames = ko.observable(data.nickNames);
}

ko.applyBindings(new ViewModel())
</code>```

The initialCats in ViewModel is an array with all cat information.
An example element of catlist is

```<code>{
    clickCount: 0,
    name: 'Tabby',
    imgSrc: 'tabby.jpg',
    imgAttribution: 'Aman',
    nickNames: ['Tabtab', 'T-bone', 'Mr. T', 'Tabitha Tab Tabby']
}
</code>```

Althouch clicking on the li elements change the current cat but the corresponding view is not rendered. And the default cat (the first cat) in only rendered. Did i miss something. ?

答:
It's not working probably because you're overwriting currentCat observable instead of just updating the inner object inside setCurrentCat. So, change self.currentCat = ko.observable(cat) to self.currentCat(cat);

Here's a working snippet:

var initialCats = [{
  clickCount: 0,
  name: 'Tabby',
  imgSrc: 'https://s20.postimg.org/owgnoq5c9/cat_1.jpg',
  imgAttribution: 'Aman',
  nickNames: ['Tabtab', 'T-bone', 'Mr. T', 'Tabitha Tab Tabby']
}, {
  clickCount: 0,
  name: 'Tom',
  imgSrc: 'https://s20.postimg.org/f9d5f0ccp/cat_2.jpg',
  imgAttribution: 'Aman',
  nickNames: ['Tommy', 'Timmy']
}]

var ViewModel = function() {
  var self = this;

  this.catList = ko.observableArray([]);
  initialCats.forEach(function(catItem) {
    self.catList.push(new Cat(catItem));
  });

  this.currentCat = ko.observable(this.catList()[0]);

  this.incrementCount = function() {
    self.currentCat().clickCount(self.currentCat().clickCount() + 1);
  };
  this.setCurrentCat = function(cat) {
    // change here
    self.currentCat(cat);
  }
}
var Cat = function(data) {
  this.clickCount = ko.observable(data.clickCount);
  this.name = ko.observable(data.name);
  this.imgSrc = ko.observable(data.imgSrc);
  this.imgAttribution = ko.observable(data.imgAttribution);
  this.nickNames = ko.observable(data.nickNames);
}

ko.applyBindings(new ViewModel())```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<ul id="cat-list" data-bind="foreach: catList()">
  <li data-bind="text: name, click: $parent.setCurrentCat"> </li>
</ul>
<div id="cat" data-bind="with: currentCat()">

  <h2 data-bind="text: name" id="cat-name"></h2>

  <div data-bind="text: clickCount" id="cat-count"></div>
  <img src="" data-bind="click: $parent.incrementCount, attr: {src: imgSrc}" id="cat-img" alt="cute cat">
  <h4>NickNames</h4>
  <ul data-bind="foreach: nickNames">
    <li data-bind="text: $data"></li>
  </ul>

</div></code>```

Here's a working fiddle

Title: binding not working in knockout JS

Body:
HTML code.

NickNames

The JS code:

var ViewModel = function() {
     var self = this;

    this.catList = ko.observableArray([]);
    initialCats.forEach(function(catItem) {
        self.catList.push( new Cat(catItem) );
    });

    this.currentCat = ko.observable( this.catList()[0]);

    this.incrementCount = function(){
        self.currentCat().clickCount(self.currentCat().clickCount()+1);
    };
    this.setCurrentCat = function(cat) {

    self.currentCat = ko.observable(cat);
    console.log(self.currentCat);
}

var Cat = function(data) {
    this.clickCount = ko.observable(data.clickCount);
    this.name = ko.observable(data.name);
    this.imgSrc = ko.observable(data.imgSrc);
    this.imgAttribution = ko.observable(data.imgAttribution);
    this.nickNames = ko.observable(data.nickNames);
}

ko.applyBindings(new ViewModel())

The initialCats in ViewModel is an array with all cat information.
An example element of catlist is

{
    clickCount: 0,
    name: 'Tabby',
    imgSrc: 'tabby.jpg',
    imgAttribution: 'Aman',
    nickNames: ['Tabtab', 'T-bone', 'Mr. T', 'Tabitha Tab Tabby']
}

Althouch clicking on the li elements change the current cat but the corresponding view is not rendered. And the default cat (the first cat) in only rendered. Did i miss something. ?

Body:
It's not working probably because you're overwriting currentCat observable instead of just updating the inner object inside setCurrentCat. So, change self.currentCat = ko.observable(cat) to self.currentCat(cat);

Here's a working snippet:

var initialCats = [{
  clickCount: 0,
  name: 'Tabby',
  imgSrc: 'https://s20.postimg.org/owgnoq5c9/cat_1.jpg',
  imgAttribution: 'Aman',
  nickNames: ['Tabtab', 'T-bone', 'Mr. T', 'Tabitha Tab Tabby']
}, {
  clickCount: 0,
  name: 'Tom',
  imgSrc: 'https://s20.postimg.org/f9d5f0ccp/cat_2.jpg',
  imgAttribution: 'Aman',
  nickNames: ['Tommy', 'Timmy']
}]

var ViewModel = function() {
  var self = this;

  this.catList = ko.observableArray([]);
  initialCats.forEach(function(catItem) {
    self.catList.push(new Cat(catItem));
  });

  this.currentCat = ko.observable(this.catList()[0]);

  this.incrementCount = function() {
    self.currentCat().clickCount(self.currentCat().clickCount() + 1);
  };
  this.setCurrentCat = function(cat) {
    // change here
    self.currentCat(cat);
  }
}
var Cat = function(data) {
  this.clickCount = ko.observable(data.clickCount);
  this.name = ko.observable(data.name);
  this.imgSrc = ko.observable(data.imgSrc);
  this.imgAttribution = ko.observable(data.imgAttribution);
  this.nickNames = ko.observable(data.nickNames);
}

ko.applyBindings(new ViewModel())

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<ul id="cat-list" data-bind="foreach: catList()">
  <li data-bind="text: name, click: $parent.setCurrentCat"> </li>
</ul>
<div id="cat" data-bind="with: currentCat()">

  <h2 data-bind="text: name" id="cat-name"></h2>

  <div data-bind="text: clickCount" id="cat-count"></div>
  <img src="" data-bind="click: $parent.incrementCount, attr: {src: imgSrc}" id="cat-img" alt="cute cat">
  <h4>NickNames</h4>
  <ul data-bind="foreach: nickNames">
    <li data-bind="text: $data"></li>
  </ul>

</div>

Here's a working fiddle


问:
How to aggregate an array data in mongodb
I've some problems to make an aggregation query work fine in MongoDB.

I've this json schema:

```<code>{
    "_id" : 11,
    "name": "A green door",
    "price": 12.50,
    "tags": ["home", "green"],
    "pools" : [
        {
            "score" : 2,
            "language" : "en",
            "option" : "Have problems to close!",
            "time" : "2017-06-06"
        },
        {
            "score" : 1,
            "language" : "en",
            "option" : "I can't close this door!",
            "time" : "2017-06-06"
        },
        {
            "score" : 4,
            "language" : "en",
            "option" : "After some time, I'm able to install this door. Works fine!",
            "time" : "2017-06-06"
        },
        {
            "score" : 5,
            "language" : "fr",
            "option" : "Très difficile à installer, mais ça marche quand même.",
            "time" : "2017-06-06"
        },
        {
            "score" : 1,
            "language" : "es",
            "option" : "Perdí mucho tiempo para instalar.",
            "time" : "2017-06-06"
        }
    ]
}
</code>```

I would like to filter only the registries that have language in English ("en") and score equal or greater than 3. So, I try this:

```<code>db.test.aggregate(
    { $match: { "pools.language": "en" }},
    { $match: {"pools.score": { $gte : 3 }}},
    { $unwind: '$pools'})
</code>```

However, I always get results in other languages and incoherent scores.

So, how to write this correctly?

答:
From https://docs.mongodb.com/v3.4/reference/operator/aggregation/

In the db.collection.aggregate method, pipeline stages appear in an array. Documents pass through the stages in sequence

So you should first unwind, and multiple matches can use $and operator:

```<code>db.test.aggregate(
  { $unwind: '$pools' },
  { $match:
    { $and: [{ "pools.language": "en" }, { "pools.score": { $gte: 3 } }]}
  }
)
</code>```

Body:
I've some problems to make an aggregation query work fine in MongoDB.

I've this json schema:

{
    "_id" : 11,
    "name": "A green door",
    "price": 12.50,
    "tags": ["home", "green"],
    "pools" : [
        {
            "score" : 2,
            "language" : "en",
            "option" : "Have problems to close!",
            "time" : "2017-06-06"
        },
        {
            "score" : 1,
            "language" : "en",
            "option" : "I can't close this door!",
            "time" : "2017-06-06"
        },
        {
            "score" : 4,
            "language" : "en",
            "option" : "After some time, I'm able to install this door. Works fine!",
            "time" : "2017-06-06"
        },
        {
            "score" : 5,
            "language" : "fr",
            "option" : "Très difficile à installer, mais ça marche quand même.",
            "time" : "2017-06-06"
        },
        {
            "score" : 1,
            "language" : "es",
            "option" : "Perdí mucho tiempo para instalar.",
            "time" : "2017-06-06"
        }
    ]
}

I would like to filter only the registries that have language in English ("en") and score equal or greater than 3. So, I try this:

db.test.aggregate(
    { $match: { "pools.language": "en" }},
    { $match: {"pools.score": { $gte : 3 }}},
    { $unwind: '$pools'})

However, I always get results in other languages and incoherent scores.

So, how to write this correctly?

Body:
From https://docs.mongodb.com/v3.4/reference/operator/aggregation/

In the db.collection.aggregate method, pipeline stages appear in an array. Documents pass through the stages in sequence

So you should first unwind, and multiple matches can use $and operator:

db.test.aggregate(
  { $unwind: '$pools' },
  { $match:
    { $and: [{ "pools.language": "en" }, { "pools.score": { $gte: 3 } }]}
  }
)


答:
You have declared the same component too many times.  Based on your use case, every component should be declared in exactly one module.  Think of it the same way as declaring a variable - you only do it once, and then you can start using it.   If a component is declared and exported from the same module, then the component can also be used downstream as well and not just the module where it was declared.

Since you already declared CheckboxComponent from FormsModule, you don't need to declare or export it again. That being said, you may want to consider exporting the entire module if it makes sense to do so:

```<code>import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms';

import { CheckboxComponent } from './checkbox.component';

@NgModule({
    imports: [FormsModule],
    exports: [FormsModule]
})
export class CheckboxModule { }
</code>```

Title: Angular 2 component doesnt render even if i put it in NgModule

Body:
You have declared the same component too many times.  Based on your use case, every component should be declared in exactly one module.  Think of it the same way as declaring a variable - you only do it once, and then you can start using it.   If a component is declared and exported from the same module, then the component can also be used downstream as well and not just the module where it was declared.

Since you already declared CheckboxComponent from FormsModule, you don't need to declare or export it again. That being said, you may want to consider exporting the entire module if it makes sense to do so:

import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms';

import { CheckboxComponent } from './checkbox.component';

@NgModule({
    imports: [FormsModule],
    exports: [FormsModule]
})
export class CheckboxModule { }


答:
Try this simple solution to convert file to base64 string</p>

```<code>String base64String = imageFileToByte(file);

public String imageFileToByte(File file){

    Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
    byte[] b = baos.toByteArray();
    return Base64.encodeToString(b, Base64.DEFAULT);
}
</code>```

Title: How to convert image into byte array and byte array to base64 String in android?

Body:
Can someone tell me the code to convert image into byte array and that byte array into base64 string.
i write the below code not getting proper result .

  String filepath = "/sdcard/Image/ic_launcher.jpg";
   File imagefile = new File(filepath);
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(imagefile);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Bitmap bm = BitmapFactory.decodeStream(fis);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);
        byte[] b = baos.toByteArray();

        String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);

result im getting is

 [-1, -40, -1, -32, 0, 16, 74, 70, 73, 70, 0, 1, 1, 1, 0, 72, 0, 72, 0, 0, -1, -20, 4, -7, 68, 117, 99, 107, 121, 0, 1, 0, 4, 0, 0, 0, 75, 0, 2, 4, -28, 0, 0, 2, 112, 0, 68, 0, 111, 0, 110, 0, 110, 0, 97, 0, 32, 0, 83, 0, 105, 0, 109, 0, 112, 0, 115, 0, 111, 0, 110, 0, 32, 0, 117, 0, 115, 0, 101, 0, 115, 0, 32, 0, 97, 0, 32, 0, 99, 0, 111, 0, 109, 0, 112, 0, 117, 0, 116, 0, 101, 0, 114, 0, 32, 0, 116, 0, 111, 0, 32, 0, 99, 0, 104, 0, 101, 0, 99, 0, 107, 0, 32, 0, 97, 0, 32, 0, 115, 0, 105, 0, 116, 0, 101, 0, 32, 0, 116, 0, 104, 0, 97, 0, 116, 0, 32, 0, 112, 0, 97, 0, 121, 0, 115, 0, 32, 0, 104, 0, 101, 0, 114, 0, 32, 0, 109, 0, 111, 0, 110, 0, 101, 0, 121, 0, 32, 0, 116, 0, 111, 0, 32, 0, 117, 0, 112, 0, 108, 0, 111, 0, 97, 0, 100, 0, 32, 0, 118, 0, 105, 0, 100, 0, 101, 0, 111, 0, 32, 0, 99, 0, 108, 0, 105, 0, 112, 0, 115, 0, 32, 0, 111, 0, 102, 0, 32, 0, 104, 0, 101, 0, 114, 0, 32, 0, 101, 0, 97, 0, 116, 0, 105, 0, 110, 0, 103, 0, 32, 0, 97, 0, 116, 0, 32, 0, 104, 0, 101, 0, 114, 0, 32, 0, 104, 0, 111, 0, 109, 0, 101, 0, 32, 0, 105, 0, 110, 0, 32, 0, 79, 0, 108, 0, 100, 0, 32, 0, 66, 0, 114, 0, 105, 0, 100, 0, 103, 0, 101, 0, 44, 0, 32, 0, 78, 0, 101, 0, 119, 0, 32, 0, 74, 0, 101, 0, 114, 0, 115, 0, 101, 0, 121, 0, 46, 0, 46, 0, 46, 0, 68, 0, 111, 0, 110, 0, 110, 0, 97, 0, 32, 0, 83, 0, 105, 0, 109, 0, 112, 0, 115, 0, 111, 0, 110, 0, 32, 0, 117, 0, 115, 0, 101, 0, 115, 0, 32, 0, 97, 0, 32, 0, 99, 0, 111, 0, 109, 0, 112, 0, 117, 0, 116, 0, 101, 0, 114, 0, 32, 0, 116, 0, 111, 0, 32, 0, 99, 0, 104, 0, 101, 0, 99, 0, 107, 0, 32, 0, 97, 0, 32, 0, 115, 0, 105, 0, 116, 0, 101, 0, 32, 0, 116, 0, 104, 0, 97, 0, 116, 0, 32, 0, 112, 0, 97, 0, 121, 0, 115, 0, 32, 0, 104, 0, 101, 0, 114, 0, 32, 0, 109, 0, 111, 0, 110, 0, 101, 0, 121, 0, 32, 0, 116, 0, 111, 0, 32, 0, 117, 0, 112, 0, 108, 0, 111, 0, 97, 0, 100, 0, 32, 0, 118, 0, 105, 0, 100, 0, 101, 0, 111, 0, 32, 0, 99, 0, 108, 0, 105, 0, 112, 0, 115, 0, 32, 0, 111, 0, 102, 0, 32, 0, 104, 0, 101, 0, 114, 0, 32, 0, 101, 0, 97, 0, 116, 0, 105, 0, 110, 0, 103, 0, 32, 0, 97, 0, 116, 0, 32, 0, 104, 0, 101, 0, 114, 0, 32, 0, 104, 0, 111, 0, 109, 0, 101, 0, 32, 0, 105, 0, 110, 0, 32, 0, 79, 0, 108, 0, 100, 0, 32, 0, 66, 0, 114, 0, 105, 0, 100, 0, 103, 0, 101, 0, 44, 0, 32, 0, 78, 0, 101, 0, 119, 0, 32, 0, 74, 0, 101, 0, 114, 0, 115, 0, 101, 0, 121, 0, 32, 0, 74, 0, 117, 0, 110, 0, 101, 0, 32, 0, 56, 0, 44, 0, 32, 0, 50, 0, 48, 0, 49, 0, 48, 0, 46, 0, 32, 0, 83, 0, 105, 0, 109, 0, 112, 0, 115, 0, 111, 0, 110, 0, 44, 0, 32, 0, 52, 0, 50, 0, 44, 0, 32, 0, 119, 0, 104, 0, 111, 0, 32, 0, 119, 0, 101, 0, 105, 0, 103, 0, 104, 0, 115, 0, 32, 0, 109, 0, 111, 0, 114, 0, 101, 0, 32, 0, 116, 0, 104, 0, 97, 0, 110, 0, 32, 0, 54, 0, 48, 0, 48, 0, 32, 0, 112, 0, 111, 0, 117, 0, 110, 0, 100, 0, 115, 0, 32, 0, 40, 0, 50, 0, 55, 0, 50, 0, 32, 0, 107, 0, 103, 0, 41, 0, 32, 0, 97, 0, 110, 0, 100, 0, 32, 0, 97, 0, 105, 0, 109, 0, 115, 0, 32, 0, 116, 0, 111, 0, 32, 0, 114, 0, 101, 0, 97, 0, 99, 0, 104, 0, 32, 0, 49, 0, 44, 0, 48, 0, 48, 0, 48, 0, 32, 0, 112, 0, 111, 0, 117, 0, 110, 0, 100, 0, 115, 0, 32, 0, 40, 0, 52, 0, 53, 0, 53, 0, 32, 0, 107, 0, 103, 0, 41, 0, 44, 0, 32, 0, 105, 0, 115, 0, 32, 0, 119, 0, 97, 0, 103, 0, 105, 0, 110, 0, 103, 0, 32, 0, 97, 0, 32, 0, 99, 0, 97, 0, 109, 0, 112, 0, 97, 0, 105, 0, 103, 0, 110, 0, 32, 0, 116, 0, 111, 0, 32, 0, 98, 0, 101, 0, 99, 0, 111, 0, 109, 0, 101, 0, 32, 0, 116, 0, 104, 0, 101, 0, 32, 0, 119, 0, 111, 0, 114, 0, 108, 0, 100, 0, 39, 0, 115, 0, 32, 0, 104, 0, 101, 0, 97, 0, 118, 0, 105, 0, 101, 0, 115, 0, 116, 0, 32, 0, 108, 0, 105, 0, 118, 0, 105, 0, 110, 0, 103, 0, 32, 0, 119, 0, 111, 0, 109, 0, 97, 0, 110, 0, 44, 0, 32, 0, 97, 0, 100, 0, 109, 0, 105, 0, 116, 0, 116, 0, 105, 0, 110, 0, 103, 0, 32, 0, 116, 0, 104, 0, 97, 0, 116, 0, 32, 0, 115, 0, 104, 0, 101, 0, 32, 0, 105, 0, 115, 0, 32, 0, 97, 0, 115, 0, 32, 0, 104, 0, 117, 0, 110, 0, 103, 0, 114, 0, 121, 0, 32, 0, 102, 0, 111, 0, 114, 0, 32, 0, 97, 0, 116, 0, 116, 0, 101, 0, 110, 0, 116, 0, 105, 0, 111, 0, 110, 0, 32, 0, 97, 0, 115, 0, 32, 0, 115, 0, 104, 0, 101, 0, 32, 0, 105, 0, 115, 0, 32, 0, 102, 0, 111, 0, 114, 0, 32, 0, 99, 0, 97, 0, 108, 0, 111, 0, 114, 0, 105, 0, 101, 0, 45, 0, 114, 0, 105, 0, 99, 0, 104, 0, 32, 0, 102, 0, 111, 0, 111, 0, 100, 0, 46, 0, 32, 0, 80, 0, 105, 0, 99, 0, 116, 0, 117, 0, 114, 0, 101, 0, 32, 0, 116, 0, 97, 0, 107, 0, 101, 0, 110, 0, 32, 0, 74, 0, 117, 0, 110, 0, 101, 0, 32, 0, 56, 0, 44, 0, 32, 0, 50, 0, 48, 0, 49, 0, 48, 0, 46, 0, 32, 0, 82, 0, 69, 0, 85, 0, 84, 0, 69, 0, 82, 0, 83, 0, 47, 0, 76, 0, 117, 0, 99, 0, 97, 0, 115, 0, 32, 0, 74, 0, 97, 0, 99, 0, 107, 0, 115, 0, 111, 0, 110, 0, 32, 0, 40, 0, 85, 0, 78, 0, 73, 0, 84, 0, 69, 0, 68, 0, 32, 0, 83, 0, 84, 0, 65, 0, 84, 0, 69, 0, 83, 0, 32, 0, 45, 0, 32, 0, 84, 0, 97, 0, 103, 0, 115, 0, 58, 0, 32, 0, 72, 0, 69, 0, 65, 0, 76, 0, 84, 0, 72, 0, 32, 0, 83, 0, 79, 0, 67, 0, 73, 0, 69, 0, 84, 0, 89, 0, 41, 0, 0, -1, -37, 0, 67, 0, 8, 6, 6, 7, 6, 5, 8, 7, 7, 7, 9, 9, 8, 10, 12, 20, 13, 12, 11, 11, 12, 25, 18, 19, 15, 20, 29, 26, 31, 30, 29, 26, 28, 28, 32, 36, 46, 39, 32, 34, 44, 35, 28, 28, 40, 55, 41, 44, 48, 49, 52, 52, 52, 31, 39, 57, 61, 56, 50, 60, 46, 51, 52, 50, -1, -37, 0, 67, 1, 9, 9, 9, 12, 11, 12, 24, 13, 13, 24, 50, 33, 28, 33, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, -1, -64, 0, 17, 8, 1, 32, 1, -52, 3, 1, 34, 0, 2, 17, 1, 3, 17, 1, -1, -60, 0, 28, 0, 0, 0, 7, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, -1, -60, 0, 76, 16, 0, 1, 3, 2, 4, 3, 6, 3, 5, 4, 8, 4, 5, 2, 7, 0, 1, 2, 3, 17, 0, 4, 5, 18, 33, 49, 6, 65, 81, 19, 34, 97, 113, -127, -111, 20, 50, -95, 7, 66, -79, -63, -16, 21, 35, 82, -47, 36, 51, 98, 114, -126, -94, -31, -15, 22, 83, -62, -46, 37, 99, -110, -109, -78, 8, 115, 52, 53, 68, 85, 100, -77, -30, -1, -60, 0, 26, 1, 0, 3, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, -1, -60, 0, 45, 17, 0, 2, 2, 2, 2, 2, 1, 3, 3, 3, 5, 1, 0, 0, 0, 0, 0, 1, 2, 17, 3, 33, 18, 49, 4, 65, 81, 19, 34, 97, 113, -79, -16, 20, -111, -47, 5, 35, 50, 66, -95, -31, -1, -38, 0, 12, 3, 1, 0, 2, 17, 3, 17, 0, 63, 0, -21, -96, -17, 64, -11, -92, -125, 74, -98, -75, -56, 116, 7, -17, 71, -52, -46, 65, -97, 10, 85, 0, 40, 80, -102, 33, 52, 40, 1, 92, -7, 82, 78, -44, 13, 36, -21, 64, 7, 67, -42, -109, 71, 64, 7, -46, -114, -109, -45, 106, 51, 64, 2, -116, -47, 80, 39, 77, 77, 0, 42, -118, -123, 9, -96, 3, -94, -10, -95, -25, 68, 117, -38, -104, 7, 66, -118, 104, 82, 0, 80, -95, -27, 69, 76, 0, 104, -89, -91, 3, 69, 64, 7, -67, 23, -67, 9, -94, -25, 64, 3, -34, -116, -111, 73, 49, 52, 9, 20, 0, 40, -113, -42, -118, -121, -122, -76, -64, 26, -46, 105, 81, 69, 20, -128, 17, -54, -123, 8, -93, -118, 64, 20, 82, -94, -124, 82, -128, -96, 4, -88, 119, 23, -24, 40, -109, 78, 44, 119, 21, 61, 69, 36, 10, 98, 22, -102, 113, 59, 82, 6, -44, -32, -90, -124, 56, 41, 66, -110, 41, 66, -87, 0, -79, 71, 69, 70, 61, 106, -47, 33, -51, 28, -47, 80, -96, 66, -88, -26, -109, 64, 26, 0, 57, -42, -114, 105, 51, 66, 105, 5, 11, -102, 20, -112, 124, 69, 29, 0, 42, -118, 104, 10, 28, -88, 0, 81, 107, 71, 66, -99, 0, 40, 81, 80, -102, 64, 84, -125, -46, -107, 34, -112, 15, -123, 43, 88, -48, 86, 38, -95, -119, -91, -45, 114, 121, -46, -3, -88, 0, -63, -93, -102, 42, 20, 0, 9, -92, -88, -47, -103, -92, 19, -50, -128, 20, 40, 77, 36, 31, 42, 19, -42, -128, 21, 52, 116, -119, -93, -15, -96, 5, 80, 59, 122, -47, 10, 7, 97, -74, -30, -128, 21, 52, 38, -109, 71, 64, 7, 66, -110, 77, 28, -48, 1, -48, -102, 76, -48, -96, 3, -102, 34, 104, 81, 19, 64, 2, -123, 10, 34, 69, 48, 4, -47, 19, 66, -128, -96, 2, 62, -76, -103, -91, 30, -76, -104, -90, 0, 20, 98, -120, 80, 19, 72, 5, 77, 39, -54, -124, -51, 21, 0, 44, 80, -46, -117, 125, -23, 67, 90, 64, 24, 20, -80, 5, 36, 68, -46, -58, -76, -60, 18, -57, 113, 95, -34, 20, -108, -118, 91, -122, 19, 29, 85, -7, 82, 69, 0, 44, 82, -59, 32, 82, -59, 52, 38, 44, 82, -123, 32, 82, -22, -48, -123, 81, -118, 64, -91, 77, 82, 1, 84, 116, 83, 66, -104, -125, -25, 67, -107, 21, 0, 117, -92, 1, -125, 66, 104, -124, -64, -95, 53, 32, 40, 116, -93, -92, -47, -118, 96, 42, 69, 9, -94, -95, 62, 84, 8, 30, -15, -46, -114, -118, 104, 72, -102, 96, 15, 57, -94, -34, -124, -47, 122, -48, 5, 35, 119, -115, 56, -128, -76, 25, 73, -25, 75, 23, 41, -102, -95, -78, 37, 41, 82, 12, 127, 16, -4, -22, 88, -41, 104, -84, 104, -44, -79, 114, -19, 73, 0, 54, -62, -100, 81, -97, -68, 18, 7, -103, -2, 64, -46, 62, 42, -20, 110, -59, -78, -68, 3, -85, 7, -36, -93, -14, -88, 15, 57, -39, 50, -73, 114, 41, 121, 6, 108, -88, 65, 82, -107, -32, 0, -44, -97, 42, -120, -116, 102, -43, 87, 1, -91, 118, -19, 44, -126, 66, 87, 106, -24, 49, -44, -9, 96, 122, -47, 64, -109, 52, 45, 92, -123, -50, 102, -36, 105, 67, 112, -79, -89, -95, 26, 31, -44, -45, -95, -44, -98, -66, -43, 66, 47, -112, -30, 101, -112, -91, 13, -91, 64, -89, -24, 105, 11, 122, -31, 99, -25, 41, 7, -110, 52, -94, -128, -48, 41, 99, -81, -91, 37, 74, 51, 89, -26, -46, -92, -72, 12, -86, 100, 107, 52, -1, 0, 15, 37, 45, 96, -84, -74, -128, 18, -128, -91, -108, -92, 108, 37, 68, -97, -87, 38, -114, -128, -71, -111, 66, 105, -68, -38, 81, -51, 32, 28, -109, 67, 53, 34, 122, -5, 81, -125, 64, 14, 77, 2, 118, -13, 20, -119, -91, 125, -47, -3, -31, 52, 0, -70, 42, 41, 52, 38, -128, 12, -102, 20, -109, 66, -104, 10, -96, 77, 36, -102, 18, 104, 1, 83, 68, 72, -25, 73, -102, 19, 64, 7, 52, 71, 78, -108, 38, -123, 0, 20, -7, -47, -47, 81, -19, 69, -128, 41, 42, -93, -92, -109, -19, 64, 21, 92, 65, -60, -104, 95, 12, -39, 11, -84, 73, -41, 6, 109, 27, 101, -122, -13, -72, -28, 111, 3, 64, 7, -119, 32, 120, -51, 115, 59, -1, 0, -74, -53, -27, -87, 67, 9, -64, -20, -38, 108, 24, 11, -67, 121, 110, -85, -52, -124, 101, 3, -36, -7, -42, -17, -120, -101, -73, -65, -62, -18, 123, 118, -112, -76, 40, 110, -95, 48, 6, -43, -61, 113, -101, 70, -84, -18, 22, -106, -13, -72, -127, -79, 73, 76, 15, 45, -87, -82, -10...

and at end of this byte array im getting this 3 dots and array is not completed ,so how can i get correct byte array

base64 string is

[encoded data, 9804 characters]
AOujj7Nl/wDWSbSPMOE/eJLuX5p/N/02hGMhPs4LllhIGQm//jyPOTIPulcAmXcW+9N...

Body:
Try this simple solution to convert file to base64 string

String base64String = imageFileToByte(file);

public String imageFileToByte(File file){

    Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
    byte[] b = baos.toByteArray();
    return Base64.encodeToString(b, Base64.DEFAULT);
}


问:
CMake library not found

I try to run the makefile that using cmake produced. It generate an error

```<code>ld: library not found for -lhello
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

the file directory is:

the cmakelists.txt is:

the main.c file is:

the ERROR:

I think I set the right directory. How to solve this ERROR?

答:
CMake has a system if you want to link libraries. For many standard libraries we have cmake modules which will allow you to use the find_package command. This will set some variables for include directories and libraries. If there is no such thing for your library you can use find_path for the include files and find_library to search for a library.

Here is what you could do (untested, just out of my head):

```<code>add_executable(main main.c)

target_include_directories(
    PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}
    PUBLIC ${CMAKE_SOURCE_DIR}/include/hello
)

find_library (
    HELLO_LIB
    NAMES hello libhello # what to look for
    HINTS "${CMAKE_SOURCE_DIR}/lib" # where to look
    NO_DEFAULT_PATH # do not search system default paths
)

# check if we found the library
message(STATUS "HELLO_LIB: [${HELLO_LIB}]")

if (NOT HELLO_LIB)
    message(SEND_ERROR "Did not find lib hello")
endif

target_link_libraries(main
    ${HELLO_LIB}
)
</code>```

Use message to debug your cmake files. If you define the library in cmake as well you can link directly against the cmake target.

Title: CMake library not found

Body:
I try to run the makefile that using cmake produced. It generate an error

ld: library not found for -lhello
clang: error: linker command failed with exit code 1 (use -v to see invocation)

the file directory is:

the cmakelists.txt is:

the main.c file is:

the ERROR:

I think I set the right directory. How to solve this ERROR?

Body:
CMake has a system if you want to link libraries. For many standard libraries we have cmake modules which will allow you to use the find_package command. This will set some variables for include directories and libraries. If there is no such thing for your library you can use find_path for the include files and find_library to search for a library.

Here is what you could do (untested, just out of my head):

add_executable(main main.c)

target_include_directories(
    PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}
    PUBLIC ${CMAKE_SOURCE_DIR}/include/hello
)

find_library (
    HELLO_LIB
    NAMES hello libhello # what to look for
    HINTS "${CMAKE_SOURCE_DIR}/lib" # where to look
    NO_DEFAULT_PATH # do not search system default paths
)

# check if we found the library
message(STATUS "HELLO_LIB: [${HELLO_LIB}]")

if (NOT HELLO_LIB)
    message(SEND_ERROR "Did not find lib hello")
endif

target_link_libraries(main
    ${HELLO_LIB}
)

Use message to debug your cmake files. If you define the library in cmake as well you can link directly against the cmake target.

ContentLicense: CC BY-SA 4.0


问:
UserName or guid UserID?
When saving data in different sql tables, is it best to use the GUID userID or simply use the username? is there a performance difference when using guid?</p>

答:
I saw a lot of discussions about performance in GUID vs. INT (auto increment). But I could recommend you use GUID.

Hm.. Are you asking about field used as primary or about using/not a relations (insert a GUID into a table having another table with GUID and user name associations) ?

OwnerDisplayName: zsharp

Title: UserName or guid UserID?

OwnerDisplayName: abatishchev


问:
How do I fill a rectangle with the exception of a area
I am trying to fill a rectangle in a winforms application less a ellipse in the center that allows the image in the background to show through.

can anyone give me a hint on which way to go on this,

thanks.

this is what I have come up with so far:

```<code>  path.AddRectangle(new Rectangle(30, 30, 100, 100));
  path.AddEllipse(new Rectangle(50, 50, 60, 60));
  gfx.FillPath(new SolidBrush(Color.Black), path);
</code>```

答:
```<code>protected override void OnPaint(PaintEventArgs e){
    var rgn  = new Region(new Rectangle(50, 50, 200, 100));
    var path = new GraphicsPath();
    path.AddEllipse(60, 60, 180, 80);
    rgn.Exclude(path);
    e.Graphics.FillRegion(Brushes.Blue, rgn);
}
</code>```

Body:
I am trying to fill a rectangle in a winforms application less a ellipse in the center that allows the image in the background to show through.

can anyone give me a hint on which way to go on this,

thanks.

this is what I have come up with so far:

  path.AddRectangle(new Rectangle(30, 30, 100, 100));
  path.AddEllipse(new Rectangle(50, 50, 60, 60));
  gfx.FillPath(new SolidBrush(Color.Black), path);


问:
Could not find com.android.tools.build.gradle:3.0.0-alpha7
I update the gradle plugin to the latest, and i'm getting this error:

```<code>Error:Could not find com.android.tools.build.gradle:3.0.0-alpha7:.
Searched in the following locations:
    file:/C:/Users/dmin/Documents/android-studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha7//3.0.0-alpha7-.pom
    file:/C:/Users/dmin/Documents/android-studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha7//3.0.0-alpha7-.jar
    https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha7//3.0.0-alpha7-.pom
    https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha7//3.0.0-alpha7-.jar
    https://maven.google.com/com/android/tools/build/gradle/3.0.0-alpha7//3.0.0-alpha7-.pom
    https://maven.google.com/com/android/tools/build/gradle/3.0.0-alpha7//3.0.0-alpha7-.jar
</code>```

Here's my build.gradle

```<code>buildscript {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
    }
    dependencies {
        classpath 'com.android.tools.build.gradle:3.0.0-alpha7'
        classpath 'com.google.gms:google-services:3.1.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}
</code>```

Where i'm getting wrong? since i modified my gradle.build according to the question Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci
 thank you!!

-- Updated the build.gradle according to Mr Tim, but i'm still having the same error

```<code>buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build.gradle:3.0.0-alpha7'
        classpath 'com.google.gms:google-services:3.1.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}
</code>```

答:
You try :

```<code>buildscript {
    repositories {
        ...
        // You need to add the following repository to download the
        // new plugin.
        google()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}
</code>```

Credits: https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html

Body:
I update the gradle plugin to the latest, and i'm getting this error:

Error:Could not find com.android.tools.build.gradle:3.0.0-alpha7:.
Searched in the following locations:
    file:/C:/Users/dmin/Documents/android-studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha7//3.0.0-alpha7-.pom
    file:/C:/Users/dmin/Documents/android-studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha7//3.0.0-alpha7-.jar
    https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha7//3.0.0-alpha7-.pom
    https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha7//3.0.0-alpha7-.jar
    https://maven.google.com/com/android/tools/build/gradle/3.0.0-alpha7//3.0.0-alpha7-.pom
    https://maven.google.com/com/android/tools/build/gradle/3.0.0-alpha7//3.0.0-alpha7-.jar

Here's my build.gradle

buildscript {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
    }
    dependencies {
        classpath 'com.android.tools.build.gradle:3.0.0-alpha7'
        classpath 'com.google.gms:google-services:3.1.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Where i'm getting wrong? since i modified my gradle.build according to the question Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci
 thank you!!

-- Updated the build.gradle according to Mr Tim, but i'm still having the same error

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build.gradle:3.0.0-alpha7'
        classpath 'com.google.gms:google-services:3.1.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Body:
You try :

buildscript {
    repositories {
        ...
        // You need to add the following repository to download the
        // new plugin.
        google()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

Credits: https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html