答:
You have to pass object in this way:

```<code>"series": [{
   "values": [3, 4, 11, 5, 19, 7]
 }, {
   "values": [9, 19, 15, 25, 12, 14]
 }, {
   "values": [15, 29, 19, 21, 25, 26]
 },{
   .........
 }]
</code>```

So you have to use map method in order to achive this array:

```<code>var chartD=chartData.map(function(item){
    var array=[item.time,item.dac,item.adc,item.voltage];
    return {"values":array};
});
</code>```

The last step is to assing array to series properties.

```<code>"series": chartD
</code>```

Here is working solution.

Title: Load JSON array for chart( ZingChart)

Body:
I tried to load this sample of data from external file to line zingchart, but nothing appears in chart, any suggestions ? thanks for answers.

var chartData = [{"time":"1706043693.219217:","dac":"3000,","adc":"406","voltage":"0.4956"},{"time":"1706043693.231481:","dac":"3000,","adc":"413","voltage":"0.5042"},{"time":"1706043693.242824:","dac":"3000,","adc":"409","voltage":"0.4993"},{"time":"1706043693.253953:","dac":"3000,","adc":"413","voltage":"0.5042"},{"time":"1706043693.265034:","dac":"3000,","adc":"406","voltage":"0.4956"},{"time":"1706043693.276092:","dac":"3000,","adc":"410","voltage":"0.5005"},{"time":"1706043693.287171:","dac":"3000,","adc":"409","voltage":"0.4993"},{"time":"1706043693.298221:","dac":"3000,","adc":"411","voltage":"0.5017"},{"time":"1706043693.309273:","dac":"3000,","adc":"411","voltage":"0.5017"},{"time":"1706043693.320340:","dac":"3000,","adc":"407","voltage":"0.4968"},{"time":"1706043693.331321:","dac":"3000,","adc":"410","voltage":"0.5005"},{"time":"1706043693.342464:","dac":"3000,","adc":"407","voltage":"0.4968"},{"time":"1706043693.353505:","dac":"3000,","adc":"406","voltage":"0.4956"},{"time":"1706043693.364545:","dac":"3000,","adc":"409","voltage":"0.4993"}];

var myConfig = {
  "type": "line",
  "legend": {},
   "plot":{
"aspect":"spline"
},
 "title": {
   "text":"Back heating"
},
  "preview":{ adjustLayout:true},
  "scale-x": {
    "zooming": true,
    "zoom-to": [0, 50],
    "item": {
      "font-size": 10
    }
  },
  "scale-x": {
    "zooming": true,
    "label": {
    "text": "axisX",
    "font-size": 16
    }
  },
  "scale-y": {
    "zooming": true,
    "guide": {
      "line-style": "dotted"
    },
    "item": {
      "font-size": 10
    },
    "label": {
    "text": "axisY",
    "font-size": 16
    }
  },
  "plot": {
    "line-width": 1,
    "aspect":"spline"
  },
  "crosshair-x": {
    "plot-label": {
      "text": "%v"
    },
    "scale-label": {
      "visible": false
    }
  },
  "crosshair-y": {
    "type": "multiple",
    "scale-label": {
      "visible": false
    }
  },
  "series": [{
    "values": chartData
  }
  ]
};

zingchart.render({
  id: 'myChart',
  data: myConfig,
  height: 400,
  width: 600
});

Body:
You have to pass object in this way:

"series": [{
   "values": [3, 4, 11, 5, 19, 7]
 }, {
   "values": [9, 19, 15, 25, 12, 14]
 }, {
   "values": [15, 29, 19, 21, 25, 26]
 },{
   .........
 }]

So you have to use map method in order to achive this array:

var chartD=chartData.map(function(item){
    var array=[item.time,item.dac,item.adc,item.voltage];
    return {"values":array};
});

The last step is to assing array to series properties.

"series": chartD

Here is working solution.


来源: stackexchange

问:
Regular expression that disallows spaces and limits length
I am trying to figure out a regex for following conditions

1) Must be at least 2 characters long
2) Must be no more than 30 characters long
3) Can't contain spaces

So far I found ^[a-zA-Z0-9]{2,30}$ which does good job at limiting length and not allowing spaces, but it also disallows symbols like &* etc, thats should be allowed. Same with emoji i.e.  should be valid for such regex.

答:
You can use \S to match non-space character

```<code>/^\S{2,30}$/
</code>```

\S matches anything other than a space, tab or newline.

Live Demo:

input:valid {
  color: green;
}

input:invalid {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" pattern="\S{2,30}" /></code>```

Note that in the HTML5 pattern attribute, anchors(^ and $) are implicit.

ContentLicense: CC BY-SA 3.0

Body:
You can use \S to match non-space character

/^\S{2,30}$/

\S matches anything other than a space, tab or newline.

Live Demo:

input:valid {
  color: green;
}

input:invalid {
  color: red;
}

<input type="text" pattern="\S{2,30}" />

Note that in the HTML5 pattern attribute, anchors(^ and $) are implicit.


问:
Infinite digest loop inside custom filter of angularJS
I am displaying a list of tables and each row is also expandable. I want to filter the list using the property of expandable table. For example if the main table show the general info of student and expandable table shows the marks of subject for that student. I want to filter the complete table by marks column. So the filtering should display the parent table with matched marks.

```<code>var students = [{
   name: "neha",
   address: "abc"
   marks: [{
      subject: "english",
      marks: 80
   }, {
      subject: "hindi",
      marks: 60
   }]
 }, {
   name: "sneha",
   address: "xyz"
   marks: [{
      subject: "english",
      marks: 70
   }, {
      subject: "math",
      marks: 50
   }]
 }
</code>```

For this
I am using custom filter to filter the list. Inside custom filter I am using "filterFilter" to filter the marks array.

filterBy is the property which keeps track of property against which the value will be tested.

For example the values can be
1) filterBy = {property: "marks.subject", value: "hindi"} //filter on nested table

2) filterBy = {property: "name": value: "neha"} //filter on parent table

```<code>var app = angular.module("MyApp", []);
app.filter("filterTable", function(filterFilter) {

    return function(list, filterBy) {
        var filteredList = [],
            len,
            i,
            j,
            property,
            present,
            tempList,
            listCopy,
            properties = [];

        //creating a copy as filter will update the list and rest filter will not work properly
        listCopy = angular.copy(list);
        len = listCopy.length;

        if(filterBy.value) {

            properties = filterBy.property.split(".");

            //if filter on nested table
            if(properties.length > 1) {
                property = properties[1];

                for ( i = 0; i < len; i++) {
                    tempList = {};
                    //using filterFilter defined by angularjs
                    listCopy[i].disks = filterFilter(list[i].disks, { [property] : filterBy.value });
                    console.log(list[i].disks);
                    if(listCopy[i].disks.length) {
                        filteredList.push(listCopy[i]);
                    }

                }
            } else {
                property = filterBy.property;

                for ( i = 0; i < len; i++) {

                    if(list[i][property].indexOf(filterBy.value) > 0) {
                        filteredList.push(list[i]);
                    }
                }
            }

            return filteredList;
        } else {
            return list;
        }
    };
});
</code>```

But this is going into infinite digest cycle. I have spent a long time on this and still not able to resolve. Please help me with it.
Thanks in advance.

答:
This happens because you are deep copy array.

Angular's ngRepeat doesn't realize that those objects are equal because ngRepeat tracks them by identity. New object leads to new identity. This makes Angular think that something has changed since the last check, which means that Angular should run another check (aka digest).

Try update logic of filter without angular.copy()

Update:

Instead of angular.copy use flat copy:

var newArray= oldArray.slice(); // clones the array and returns the reference to the new array.

Body:
I am displaying a list of tables and each row is also expandable. I want to filter the list using the property of expandable table. For example if the main table show the general info of student and expandable table shows the marks of subject for that student. I want to filter the complete table by marks column. So the filtering should display the parent table with matched marks.

var students = [{
   name: "neha",
   address: "abc"
   marks: [{
      subject: "english",
      marks: 80
   }, {
      subject: "hindi",
      marks: 60
   }]
 }, {
   name: "sneha",
   address: "xyz"
   marks: [{
      subject: "english",
      marks: 70
   }, {
      subject: "math",
      marks: 50
   }]
 }

For this
I am using custom filter to filter the list. Inside custom filter I am using "filterFilter" to filter the marks array.

filterBy is the property which keeps track of property against which the value will be tested.

For example the values can be
1) filterBy = {property: "marks.subject", value: "hindi"} //filter on nested table

2) filterBy = {property: "name": value: "neha"} //filter on parent table

var app = angular.module("MyApp", []);
app.filter("filterTable", function(filterFilter) {

    return function(list, filterBy) {
        var filteredList = [],
            len,
            i,
            j,
            property,
            present,
            tempList,
            listCopy,
            properties = [];

        //creating a copy as filter will update the list and rest filter will not work properly
        listCopy = angular.copy(list);
        len = listCopy.length;

        if(filterBy.value) {

            properties = filterBy.property.split(".");

            //if filter on nested table
            if(properties.length > 1) {
                property = properties[1];

                for ( i = 0; i < len; i++) {
                    tempList = {};
                    //using filterFilter defined by angularjs
                    listCopy[i].disks = filterFilter(list[i].disks, { [property] : filterBy.value });
                    console.log(list[i].disks);
                    if(listCopy[i].disks.length) {
                        filteredList.push(listCopy[i]);
                    }

                }
            } else {
                property = filterBy.property;

                for ( i = 0; i < len; i++) {

                    if(list[i][property].indexOf(filterBy.value) > 0) {
                        filteredList.push(list[i]);
                    }
                }
            }

            return filteredList;
        } else {
            return list;
        }
    };
});

But this is going into infinite digest cycle. I have spent a long time on this and still not able to resolve. Please help me with it.
Thanks in advance.


问:
spring mvc crud example without database
Is it possible to create a CRUD system without database in spring mvc framework?
If possible then which way?
I made an application where i can save and update a single value but i need to save and update a list of value.</p>

答: You Can recreate a CRUD operation using File Systems In Java using a File or Excel  as a Database and and then Using File Handling or Apache POI in order to Create Update or Delete.</p>


问:
Create zip style file without compression
I know that there are many free and not so free compression libraries out there, but for the project i am working on, i need to be able to take file data from a stream and put it into some kind zip or pack file, but without compression, because i will need to access these files quickly without having to wait for them to decompress.

Anyone know how this could be approached, or if there are some libraries out there that do this that i am not aware of?

答:
Perhaps just use a zip with compression set to "none"; SharpZipLib would suffice.

Be careful about assuming that compression is slower, though - it might actually (depending on the scenario) be quicker with compression, since you reduce the amount of physical IO and IPC (often a bottleneck), and simply do a bit more CPU work; but you generally have plenty of CPU.

OwnerDisplayName: Jason Miesionczek

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Marc Gravell


问:
PHP / MySQL - Need help with simple query
I need to write a query but am a newbie to writing querys that involve 2 tables.

the first table 'clients' has the following columns "id, archive_reason, name, phone" .. the second table, 'archive' has the following columns "id, archive_reason".

What i need to do is get the archive reason based on the archive_reason in the clients table if that makes sense ... and then return * from the clients table, including the archive reason from the arhive table.

Cheers,

答:
```<code>SELECT clients.*, archive.archive_reason FROM clients, archive WHERE clients.id=archive.id;
</code>```

Is that what you were asking for?

This is called a JOIN, and there are many more (and better) ways to do it:

http://www.w3schools.com/Sql/sql_join.asp

http://www.databasedev.co.uk/query_joins.html

Body:
SELECT clients.*, archive.archive_reason FROM clients, archive WHERE clients.id=archive.id;

Is that what you were asking for?

This is called a JOIN, and there are many more (and better) ways to do it:

http://www.w3schools.com/Sql/sql_join.asp

http://www.databasedev.co.uk/query_joins.html


问:
Return type required/ Cannot return a value from a method with a void result type
Im a beginner, can you tell me what am i doing wrong? Why can't i use those methods properly?

IDE shows: Return type required/ Cannot return a value from a method with a void result type

`        public class Human

```<code>{
    public int Age = 0;
    public int Weight = 0;
    public int Height = 0;
    private String name = "";
    boolean isMale;
}

public getAge()
{
    return Age;
}
public getWeight()
{
    return Weight;
}
public getHeight()
{
    return Height;
}
public Human(int Age, int Weight, int Height, String name, boolean
isMale)
{

}      `
</code>```

答:
You need to specify a return value after each method modifier.

For example,

 public int getAge() {
return age;}

Body:
Im a beginner, can you tell me what am i doing wrong? Why can't i use those methods properly?

IDE shows: Return type required/ Cannot return a value from a method with a void result type

`        public class Human

{
    public int Age = 0;
    public int Weight = 0;
    public int Height = 0;
    private String name = "";
    boolean isMale;
}

public getAge()
{
    return Age;
}
public getWeight()
{
    return Weight;
}
public getHeight()
{
    return Height;
}
public Human(int Age, int Weight, int Height, String name, boolean
isMale)
{

}      `


问:
Can Parallel.ForEach be used safely with CloudTableQuery
I have a reasonable number of records in an Azure Table that I'm attempting to do some one time data encryption on.  I thought that I could speed things up by using a Parallel.ForEach.  Also because there are more than 1K records and I don't want to mess around with continuation tokens myself I'm using a CloudTableQuery to get my enumerator.

My problem is that some of my records have been double encrypted and I realised that I'm not sure how thread safe the enumerator returned by CloudTableQuery.Execute() is.  Has anyone else out there had any experience with this combination?

答:
I would be willing to bet the answer to Execute returning a thread-safe IEnumerator implementation is highly unlikely. That said, this sounds like yet another case for the producer-consumer pattern.

In your specific scenario I would have the original thread that called Execute read the results off sequentially and stuff them into a BlockingCollection<T>. Before you start doing that though, you want to start a separate Task that will control the consumption of those items using Parallel::ForEach. Now, you will probably also want to look into using the GetConsumingPartitioner method of the ParallelExtensions library in order to be most efficient since the default partitioner will create more overhead than you want in this case.  You can read more about this from this blog post.

An added bonus of using BlockingCollection<T> over a raw ConcurrentQueueu<T> is that it offers the ability to set bounds which can help block the producer from adding more items to the collection than the consumers can keep up with. You will of course need to do some performance testing to find the sweet spot for your application.


问:
My HTML page does'nt see the controller and the node js request associed
Here is my HTML code. I just have created a controller just for the part of the code.

```<code><div class="mdl-grid" ng-controller="ValueController">
          <div class="mdl-card mdl-shadow--4dp mdl-cell--12-col">
              <div class="mdl-card__title">
                <h3 class="mdl-card__title-text">Modifier seuils sur la carte</h3>
              </div>
              <div class="mdl-card__supporting-text">
              <div class="mdl-grid">
                <div class="mdl-cell--12-col mdl-grid">
                  <div class="mdl-cell--3-col mdl-grid">
                  <label class="mdl-cell--6-col">Plateforme</label>
                  <select class="mdl-cell--6-col" ng-model="platformselect" ng-change="obtainDatas()">
                    <option value="adsl">ADSL</option>
                    <option value="cable">Cable</option>
                    <option value="fibre">Fibre</option>
                    <option value="ott">OTT</option>
                    <option value="others">Others</option>
                    <option value="satellite">Satellite</option>
                    <option value="tnt">Tnt</option>
                  </select>
                 </div>
                  <div class="mdl-cell--3-col mdl-grid">
                  <label class="mdl-cell--6-col">Jour de la semaine</label>
                  <select class="mdl-cell--6-col" ng-model="dayselect" ng-change="obtainDatas()">
                    <option value="1">Lundi</option>
                    <option value="2">Mardi</option>
                    <option value="3">Mercredi</option>
                    <option value="4">Jeudi</option>
                    <option value="5">Vendredi</option>
                    <option value="6">Samedi</option>
                    <option value="0">Dimanche</option>
                 </select>
                 </div>
                  <div class="mdl-cell--3-col mdl-grid">
                  <label class="mdl-cell--6-col">Tranche horaire</label>
                  <select class="mdl-cell--6-col" ng-model="hourselect" ng-change="obtainDatas()">
                    <option value="0">0h-1h</option>
                    <option value="1">1h-2h</option>
                    <option value="2">2h-3h</option>
                    <option value="3">3h-4h</option>
                    <option value="4">4h-5h</option>
                    <option value="5">5h-6h</option>
                    <option value="6">6h-7h</option>
                    <option value="7">7h-8h</option>
                    <option value="8">8h-9h</option>
                    <option value="9">9h-10h</option>
                    <option value="10">10h-11h</option>
                    <option value="11">11h-12h</option>
                    <option value="12">12h-13h</option>
                    <option value="13">13h-14h</option>
                    <option value="14">14h-15h</option>
                    <option value="15">15h-16h</option>
                    <option value="16">16h-17h</option>
                    <option value="17">17h-18h</option>
                    <option value="18">18h-19h</option>
                    <option value="19">19h-20h</option>
                    <option value="20">20h-21h</option>
                    <option value="21">21h-22h</option>
                    <option value="22">22h-23h</option>
                    <option value="23">23h-0h</option>
                  </select>
                  </div>
                  <div class="mdl-cell--3-col mdl-grid">
                  <label class="mdl-cell--6-col">Départements</label>
                  <select class="mdl-cell--6-col" ng-model='deptselect' ng-change="obtainDatas()">
                    <option value="0">01</option>
                    <option value="1">02</option>
                    <option value="2">03</option>
                    <option value="3">04</option>
                    <option value="4">05</option>
                    <option value="5">06</option>
                    <option value="6">07</option>
                    <option value="7">08</option>
                    <option value="8">09</option>
                    <option value="9">10</option>
                    <option value="10">11</option>
                    <option value="11">12</option>
                    <option value="12">13</option>
                    <option value="13">14</option>
                    <option value="14">15</option>
                    <option value="15">16</option>
                    <option value="16">17</option>
                    <option value="17">18</option>
                    <option value="18">19</option>
                    <option value="19">2A</option>
                    <option value="20">2B</option>
                    <option value="21">21</option>
                    <option value="22">22</option>
                    <option value="23">23</option>
                    <option value="24">24</option>
                    <option value="25">25</option>
                    <option value="26">26</option>
                    <option value="27">27</option>
                    <option value="28">28</option>
                    <option value="29">29</option>
                    <option value="30">30</option>
                    <option value="31">31</option>
                    <option value="32">32</option>
                    <option value="33">33</option>
                    <option value="34">34</option>
                    <option value="35">35</option>
                    <option value="36">36</option>
                    <option value="37">37</option>
                    <option value="38">38</option>
                    <option value="39">39</option>
                    <option value="40">40</option>
                    <option value="41">41</option>
                    <option value="42">42</option>
                    <option value="43">43</option>
                    <option value="44">44</option>
                    <option value="45">45</option>
                    <option value="46">46</option>
                    <option value="47">47</option>
                    <option value="48">48</option>
                    <option value="49">49</option>
                    <option value="50">50</option>
                    <option value="51">51</option>
                    <option value="52">52</option>
                    <option value="53">53</option>
                    <option value="54">54</option>
                    <option value="55">55</option>
                    <option value="56">56</option>
                    <option value="57">57</option>
                    <option value="58">58</option>
                    <option value="59">59</option>
                    <option value="60">60</option>
                    <option value="61">61</option>
                    <option value="62">62</option>
                    <option value="63">63</option>
                    <option value="64">64</option>
                    <option value="65">65</option>
                    <option value="66">66</option>
                    <option value="67">67</option>
                    <option value="68">68</option>
                    <option value="69">69</option>
                    <option value="70">70</option>
                    <option value="71">71</option>
                    <option value="72">72</option>
                    <option value="73">73</option>
                    <option value="74">74</option>
                    <option value="75">75</option>
                    <option value="76">76</option>
                    <option value="77">77</option>
                    <option value="78">78</option>
                    <option value="79">79</option>
                    <option value="80">80</option>
                    <option value="81">81</option>
                    <option value="82">82</option>
                    <option value="83">83</option>
                    <option value="84">84</option>
                    <option value="85">85</option>
                    <option value="86">86</option>
                    <option value="87">87</option>
                    <option value="88">88</option>
                    <option value="89">89</option>
                    <option value="90">90</option>
                    <option value="91">91</option>
                    <option value="92">92</option>
                    <option value="93">93</option>
                    <option value="94">94</option>
                    <option value="95">95</option>
                  </select>
                 </div>
                </div>
              </div>
              <div class="mdl-card__actions mdl-card--border mdl-grid">
                <div class="mdl-cell--4-col mdl-grid">
                  <label class="mdl-cell--5-col">Valeur attendue</label>
                  <input class="mdl-cell--7-col" type="text" style="background-color: #66BB6A" ng-model="normalvalue"></input>
                </div>
                <div class="mdl-cell--4-col mdl-grid">
                  <label class="mdl-cell--5-col">Haute valeur</label>
                  <input class="mdl-cell--7-col" type="text" style="background-color: #FFA726" ng-model="highvalue"></input>
                </div>
                <div class="mdl-cell--4-col mdl-grid">
                  <label class="mdl-cell--5-col">Très haute valeur</label>
                  <input class="mdl-cell--7-col" type="text" style="background-color: #EF5350" ng-model="veryhighvalue"></input>
                </div>
              </div>
              <div class="mdl-card__actions mdl-card--border mdl-grid">
                <div class='mdl-cell--12-col'>
                  <button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent" style="float: right" layout-align="end center">Valider</button>
                </div>
              </div>
              </div>
        </div>
</code>```

The controller i have created :

```<code>(function() {

angular.module('app').controller('ValueController', '$scope', ['forecastValue', function(forecastValue){

    $scope.obtainDatas = function() {

    forecastValue.getResults($scope.hourselect, $scope.dayselect, $scope.deptselect, $scope.platformselect)
      .then(function(report) {
       $scope.normalvalue = report.expected, $scope.highvalue = report.higherExpected, $scope.veryhighvalue = report.muchHigherExpected;
        }).catch(function(err) {
          $scope.result = '';
          console.error('Unable to fetch forecast report: ' + err);
          });
  };

}]);
})();
</code>```

The forecast function to have the data :

```<code>(function(){

    angular.module('app')
    .factory('forecastValue', ['$http', '$q', function($http, $q){

        var apiAddr="https://something.com/app/getForecastDept";

        var forecast ={};

        forecastValue.getResults = function(hr, dy, dt, plm)
        {
            var httpParams = {
                hour: hr,
                day: dy,
                dept : dt,
                platform: plm
            };

            return $http.get(apiAddr, {
                params: httpParams,
                cache: true
            }).then(function(result) {
            return result.data;
            });

        };

        return forecast;

    }]);
})();
</code>```

And there is the part of my node js code about this function :

```<code>app.get('/app/getForecastDept', function(req, res) {
  logger.info("GET /app/getForecastDept");
  if (req.query.hour && req.query.day && req.query.dept && req.query.platform){
    getForecastDept(res, req.query);
  } else {
    badCall(res, "getForecastDept");
  }
});
</code>```

So when i launch the HTML page, i have have no function from the controller lauched. It is like if i have coded nothing.

How to explain this comportment ?

答:
You need to make below changes:

when you create angular module, do it like angular.module('app',[]) only first time, else it will override your module.

Inject $scope in your controller.

Your factory method needs to be part of return object.

See this basic FIDDLER to get clarity.

Updated fiddler solution
Fiddle link

Body:
Here is my HTML code. I just have created a controller just for the part of the code.

Modifier seuils sur la carte

                  Plateforme
                  <select class="mdl-cell--6-col" ng-model="platformselect" ng-change="obtainDatas()">
                    <option value="adsl">ADSL</option>
                    <option value="cable">Cable</option>
                    <option value="fibre">Fibre</option>
                    <option value="ott">OTT</option>
                    <option value="others">Others</option>
                    <option value="satellite">Satellite</option>
                    <option value="tnt">Tnt</option>
                  </select>

                  Jour de la semaine
                  <select class="mdl-cell--6-col" ng-model="dayselect" ng-change="obtainDatas()">
                    <option value="1">Lundi</option>
                    <option value="2">Mardi</option>
                    <option value="3">Mercredi</option>
                    <option value="4">Jeudi</option>
                    <option value="5">Vendredi</option>
                    <option value="6">Samedi</option>
                    <option value="0">Dimanche</option>
                 </select>

                  Tranche horaire
                  <select class="mdl-cell--6-col" ng-model="hourselect" ng-change="obtainDatas()">
                    <option value="0">0h-1h</option>
                    <option value="1">1h-2h</option>
                    <option value="2">2h-3h</option>
                    <option value="3">3h-4h</option>
                    <option value="4">4h-5h</option>
                    <option value="5">5h-6h</option>
                    <option value="6">6h-7h</option>
                    <option value="7">7h-8h</option>
                    <option value="8">8h-9h</option>
                    <option value="9">9h-10h</option>
                    <option value="10">10h-11h</option>
                    <option value="11">11h-12h</option>
                    <option value="12">12h-13h</option>
                    <option value="13">13h-14h</option>
                    <option value="14">14h-15h</option>
                    <option value="15">15h-16h</option>
                    <option value="16">16h-17h</option>
                    <option value="17">17h-18h</option>
                    <option value="18">18h-19h</option>
                    <option value="19">19h-20h</option>
                    <option value="20">20h-21h</option>
                    <option value="21">21h-22h</option>
                    <option value="22">22h-23h</option>
                    <option value="23">23h-0h</option>
                  </select>

                  Départements
                  <select class="mdl-cell--6-col" ng-model='deptselect' ng-change="obtainDatas()">
                    <option value="0">01</option>
                    <option value="1">02</option>
                    <option value="2">03</option>
                    <option value="3">04</option>
                    <option value="4">05</option>
                    <option value="5">06</option>
                    <option value="6">07</option>
                    <option value="7">08</option>
                    <option value="8">09</option>
                    <option value="9">10</option>
                    <option value="10">11</option>
                    <option value="11">12</option>
                    <option value="12">13</option>
                    <option value="13">14</option>
                    <option value="14">15</option>
                    <option value="15">16</option>
                    <option value="16">17</option>
                    <option value="17">18</option>
                    <option value="18">19</option>
                    <option value="19">2A</option>
                    <option value="20">2B</option>
                    <option value="21">21</option>
                    <option value="22">22</option>
                    <option value="23">23</option>
                    <option value="24">24</option>
                    <option value="25">25</option>
                    <option value="26">26</option>
                    <option value="27">27</option>
                    <option value="28">28</option>
                    <option value="29">29</option>
                    <option value="30">30</option>
                    <option value="31">31</option>
                    <option value="32">32</option>
                    <option value="33">33</option>
                    <option value="34">34</option>
                    <option value="35">35</option>
                    <option value="36">36</option>
                    <option value="37">37</option>
                    <option value="38">38</option>
                    <option value="39">39</option>
                    <option value="40">40</option>
                    <option value="41">41</option>
                    <option value="42">42</option>
                    <option value="43">43</option>
                    <option value="44">44</option>
                    <option value="45">45</option>
                    <option value="46">46</option>
                    <option value="47">47</option>
                    <option value="48">48</option>
                    <option value="49">49</option>
                    <option value="50">50</option>
                    <option value="51">51</option>
                    <option value="52">52</option>
                    <option value="53">53</option>
                    <option value="54">54</option>
                    <option value="55">55</option>
                    <option value="56">56</option>
                    <option value="57">57</option>
                    <option value="58">58</option>
                    <option value="59">59</option>
                    <option value="60">60</option>
                    <option value="61">61</option>
                    <option value="62">62</option>
                    <option value="63">63</option>
                    <option value="64">64</option>
                    <option value="65">65</option>
                    <option value="66">66</option>
                    <option value="67">67</option>
                    <option value="68">68</option>
                    <option value="69">69</option>
                    <option value="70">70</option>
                    <option value="71">71</option>
                    <option value="72">72</option>
                    <option value="73">73</option>
                    <option value="74">74</option>
                    <option value="75">75</option>
                    <option value="76">76</option>
                    <option value="77">77</option>
                    <option value="78">78</option>
                    <option value="79">79</option>
                    <option value="80">80</option>
                    <option value="81">81</option>
                    <option value="82">82</option>
                    <option value="83">83</option>
                    <option value="84">84</option>
                    <option value="85">85</option>
                    <option value="86">86</option>
                    <option value="87">87</option>
                    <option value="88">88</option>
                    <option value="89">89</option>
                    <option value="90">90</option>
                    <option value="91">91</option>
                    <option value="92">92</option>
                    <option value="93">93</option>
                    <option value="94">94</option>
                    <option value="95">95</option>
                  </select>

                  Valeur attendue
                  <input class="mdl-cell--7-col" type="text" style="background-color: #66BB6A" ng-model="normalvalue"></input>

                  Haute valeur
                  <input class="mdl-cell--7-col" type="text" style="background-color: #FFA726" ng-model="highvalue"></input>

                  Très haute valeur
                  <input class="mdl-cell--7-col" type="text" style="background-color: #EF5350" ng-model="veryhighvalue"></input>

                  <button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent" style="float: right" layout-align="end center">Valider</button>

The controller i have created :

(function() {

angular.module('app').controller('ValueController', '$scope', ['forecastValue', function(forecastValue){

    $scope.obtainDatas = function() {

    forecastValue.getResults($scope.hourselect, $scope.dayselect, $scope.deptselect, $scope.platformselect)
      .then(function(report) {
       $scope.normalvalue = report.expected, $scope.highvalue = report.higherExpected, $scope.veryhighvalue = report.muchHigherExpected;
        }).catch(function(err) {
          $scope.result = '';
          console.error('Unable to fetch forecast report: ' + err);
          });
  };

}]);
})();

The forecast function to have the data :

(function(){

    angular.module('app')
    .factory('forecastValue', ['$http', '$q', function($http, $q){

        var apiAddr="https://something.com/app/getForecastDept";

        var forecast ={};

        forecastValue.getResults = function(hr, dy, dt, plm)
        {
            var httpParams = {
                hour: hr,
                day: dy,
                dept : dt,
                platform: plm
            };

            return $http.get(apiAddr, {
                params: httpParams,
                cache: true
            }).then(function(result) {
            return result.data;
            });

        };

        return forecast;

    }]);
})();

And there is the part of my node js code about this function :

app.get('/app/getForecastDept', function(req, res) {
  logger.info("GET /app/getForecastDept");
  if (req.query.hour && req.query.day && req.query.dept && req.query.platform){
    getForecastDept(res, req.query);
  } else {
    badCall(res, "getForecastDept");
  }
});

So when i launch the HTML page, i have have no function from the controller lauched. It is like if i have coded nothing.

How to explain this comportment ?


问:
Google code jam: sample contest
here is a link to the google contest that i'm trying to solve
https://code.google.com/codejam/contest/6254486/dashboard#s=p0
and i here is below the code that i did.
It works for me so please can someone help me to know if it responds to what is asked? </p>

```<code>public static void main(String[] args) {
    int x = 1692;
    int y = 0;
    int z;
    ArrayList<Character> digit = new ArrayList<>();
    char[] new_digit = {};
    boolean end_loop = true;

    do {
        z = x * y;
        new_digit = ("" + z).toCharArray();
        for (int k = 0; k < new_digit.length; k++) {
            if (!digit.contains(new_digit[k])) {
                digit.add(new_digit[k]);
            }
        }
        System.out.println(digit.contains('0'));
        boolean b = true;
        int i = 0;
        do {

            if (!digit.contains((""+i).charAt(0))) {
                b = false;
            }
            i++;
        } while (b == true && (i < 9));
        if (b == true) {
            end_loop = false;
        }
        y = y + 1;
    } while (end_loop == true);
    System.out.println(z);
</code>```

答:
I believe your program basically solves the problem except for a limited number of issues:

You don’t read any input. There is an input format specified.

Your program sometimes prints true, which is not a part of the required output.

You don’t print in the required output format, Case #x: y (for example, Case #2: 10).

You don’t print INSOMNIA in the case where Bleatrix counts forever.

Your program incorrectly includes 0 * N (that is, 0) in the numbers counted. If I set x to 9, expected output is 90, but you print 45.

You don’t check for the digit 9 having been seen. If I set x to 10, expected output is 90, you print 80.

Title: Google code jam: sample contest

Body:
here is a link to the google contest that i'm trying to solve
https://code.google.com/codejam/contest/6254486/dashboard#s=p0
and i here is below the code that i did.
It works for me so please can someone help me to know if it responds to what is asked?

public static void main(String[] args) {
    int x = 1692;
    int y = 0;
    int z;
    ArrayList<Character> digit = new ArrayList<>();
    char[] new_digit = {};
    boolean end_loop = true;

    do {
        z = x * y;
        new_digit = ("" + z).toCharArray();
        for (int k = 0; k < new_digit.length; k++) {
            if (!digit.contains(new_digit[k])) {
                digit.add(new_digit[k]);
            }
        }
        System.out.println(digit.contains('0'));
        boolean b = true;
        int i = 0;
        do {

            if (!digit.contains((""+i).charAt(0))) {
                b = false;
            }
            i++;
        } while (b == true && (i < 9));
        if (b == true) {
            end_loop = false;
        }
        y = y + 1;
    } while (end_loop == true);
    System.out.println(z);


问:
Delegated event doesn't work for elements after sort
I have this HTML element:

```<code><div class="row preview-pictogram">
  <div class="column3 col-xs-3" data-index="3">
    <span class="index">Spalte <span>3</span></span>
    <span class="dec p-2">-</span>
    <span class="width">3</span>
    <span class="inc p-2">+</span>
  </div>
  <div class="column1 col-xs-4" data-index="1">
    <span class="index">Spalte <span>1</span></span>
    <span class="dec p-2">-</span>
    <span class="width">4</span>
    <span class="inc p-2">+</span>
  </div>
  <div class="column4 col-xs-3" data-index="4">
    <span class="index">Spalte <span>4</span></span>
    <span class="dec p-2">-</span>
    <span class="width">3</span>
    <span class="inc p-2">+</span>
  </div>
  <div class="column2 col-xs-3" data-index="2">
    <span class="index">Spalte <span>2</span></span>
    <span class="dec p-2">-</span>
    <span class="width">3</span>
    <span class="inc p-2">+</span>
  </div>
</div>
</code>```

The is a (delegated) event that listens on the click event of the .dec and .inc classes:

```<code>$(".dec, .inc").on("click", this.overlay, function () {
  _this.updateWidth(this);
});
</code>```

This works fine. But at one point I'm sorting the columns by its class name with this code:

```<code>ColumnConfigurator.prototype.sortColumns = function (columns) {
  var items = $("div", columns).get();
  items.sort(sort_by_class);
  $(columns).html(items);
};

var sort_by_class = function(a, b) {
  return $(a).attr("class").localeCompare($(b).attr("class"));
};
</code>```

After that happened that delegated event from above doesn't work anymore. I wonder why that happens. I thought the point of delegated events is that they work also for new elements. this.overlay is an element that contains the HTML above and it doesn't change at all.

答:
EDIT:

After checking @noriMonsta answer I realized that I wrote a wrong code.
I update my answer but I give him all the credit.

I thought the point of delegated events is that they work also for new elements.

Yes, but you are not delegating the events, but attaching them directly to the target elements.

```<code>$("div span").on("click", ".dev, .inc", function () {
  _this.updateWidth(this);
});
</code>```

In the code above you are delegating the event to the div elements. As long as the divs exist all the time, your events will trigger even if you alter their inner HTML.

Cleaner, as noriMonsta wrote:

```<code>this.overlay.on("click", ".dec, .inc", function () {
  _this.updateWidth(this);
});
</code>```

Because, as you said, this.overlay is an element whose content doens't change never.

In the following snippet you can check how undelegated (or direct) events stop to work after the DOM manipulation:

$(".dec, .inc").on("click", function() {
  $("#results").append("not delegated
");
});
$(".column").on("click", ".dec, .inc", function() {
  $("#results").append("delegated
");
});
$("#alterDOM").on("click", function() {
  $(".column").html( $(".column").html() );
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="row">
  <div class="column">
    <span class="dec">dec</span>
    <span class="inc">inc</span>
  </div>
  <div class="column">
    <span class="dec">dec</span>
    <span class="inc">inc</span>
  </div>
</div>

<button id="alterDOM">Alter DOM</button>
<div id="results"></div></code>```

Body:
I have this HTML element:

    Spalte 3
    -
    3
    +

    Spalte 1
    -
    4
    +

    Spalte 4
    -
    3
    +

    Spalte 2
    -
    3
    +

The is a (delegated) event that listens on the click event of the .dec and .inc classes:

$(".dec, .inc").on("click", this.overlay, function () {
  _this.updateWidth(this);
});

This works fine. But at one point I'm sorting the columns by its class name with this code:

ColumnConfigurator.prototype.sortColumns = function (columns) {
  var items = $("div", columns).get();
  items.sort(sort_by_class);
  $(columns).html(items);
};

var sort_by_class = function(a, b) {
  return $(a).attr("class").localeCompare($(b).attr("class"));
};

After that happened that delegated event from above doesn't work anymore. I wonder why that happens. I thought the point of delegated events is that they work also for new elements. this.overlay is an element that contains the HTML above and it doesn't change at all.

Body:
EDIT:

After checking @noriMonsta answer I realized that I wrote a wrong code.
I update my answer but I give him all the credit.

I thought the point of delegated events is that they work also for new elements.

Yes, but you are not delegating the events, but attaching them directly to the target elements.

$("div span").on("click", ".dev, .inc", function () {
  _this.updateWidth(this);
});

In the code above you are delegating the event to the div elements. As long as the divs exist all the time, your events will trigger even if you alter their inner HTML.

Cleaner, as noriMonsta wrote:

this.overlay.on("click", ".dec, .inc", function () {
  _this.updateWidth(this);
});

Because, as you said, this.overlay is an element whose content doens't change never.

In the following snippet you can check how undelegated (or direct) events stop to work after the DOM manipulation:

$(".dec, .inc").on("click", function() {
  $("#results").append("not delegated<br>");
});
$(".column").on("click", ".dec, .inc", function() {
  $("#results").append("delegated<br>");
});
$("#alterDOM").on("click", function() {
  $(".column").html( $(".column").html() );
});

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

<div class="row">
  <div class="column">
    <span class="dec">dec</span>
    <span class="inc">inc</span>
  </div>
  <div class="column">
    <span class="dec">dec</span>
    <span class="inc">inc</span>
  </div>
</div>

<button id="alterDOM">Alter DOM</button>
<div id="results"></div>


问:
ListView opening a new activity
this is a more design centric question. But I was thinking of developing an app which will have a ListView containing arrays of for example, coffee names.

Now when the user clicks on a coffee name, I want to have a detailed info page on the coffee style and how to make it. Basically just imagine a new window with a lot of info.

My main question is, do you think that the best way to do this is to open a new activity on click in the ListView? I am new to Android so I am not sure if there is a simpler way to do this.

Thanks to anybody that can help!

答:
In my current app, I created my listview within a fragment. I would set a listener inside the fragment and this would pass all my data as so to a new activity.</p>

```<code> listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //goes to new activity passing the item name
            Intent intent = new Intent(view.getContext(), MapsActivity.class);
            Bundle b = new Bundle();

            //get text for current item
            String textGet = mylist1.get(position);

            //put text into a bundle and add to intent
            intent.putExtra("text", textGet);

            //get position to carry integer
            intent.putExtra("position", position);

            intent.putExtras(b);

            //begin other activity
            startActivity(intent);
        }
    });
</code>```

Title: ListView opening a new activity

Body:
In my current app, I created my listview within a fragment. I would set a listener inside the fragment and this would pass all my data as so to a new activity.

 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //goes to new activity passing the item name
            Intent intent = new Intent(view.getContext(), MapsActivity.class);
            Bundle b = new Bundle();

            //get text for current item
            String textGet = mylist1.get(position);

            //put text into a bundle and add to intent
            intent.putExtra("text", textGet);

            //get position to carry integer
            intent.putExtra("position", position);

            intent.putExtras(b);

            //begin other activity
            startActivity(intent);
        }
    });


问:
Three gray dots under variable names in Visual Studio

What do these three gray dots mean? I recently updated to Visual Studio 2017, and I haven't ever seen them in other versions of VS.

答:
They indicate suggestion from Visual Studio to refactor your code to be simpler, more readable and efficient.
See Quick Actions and Refactorings section of the Visual Studio 2017 (version 15.0) Release Notes.</p>


问:
A more pythonic way to define an enum with dynamic members
I needed to create an enum to represent the ISO country codes. The country code data comes from a json file which can be obtained from: https://github.com/lukes/ISO-3166-Countries-with-Regional-Codes

So what I've done is:

```<code>data = json.load(open('slim-2.json'))
codes_list = [(data[i]['alpha-2'], int(data[i]['country-code']))
              for i in range(len(data))]

CountryCode = enum.Enum('CountryCode', codes_list,)

names_dict = {int(data[i]['country-code']):data[i]['name']
              for i in range(len(data))}
setattr(CountryCode, '_names', names_dict)

CountryCode.choices = classmethod(lambda cls:((member.value, name)
                                  for name, member in cls.__members__.items()))
setattr(CountryCode, '__str__' ,lambda self: self.__class__._names[self.value])
</code>```

This code snippet is frankly ugly. I looked at alternative ways to define the enum class but couldn't piece together a solution. Is there a way to define the enum in the following form:

```<code>class CountryCode(enum.Enum):

    data = json.load(open('slim-2.json'))
    # Some code to define the enum members

    @classmethod
    def choices(cls):
    # etc...
</code>```

Any suggestions on how to do this?

答:
Yes, there is a way to define the enum using the alternate declaration syntax you want. It works by hiding the "ugly" code in a metaclass derived from enum.EnumMeta. If you wished, it would also be possible to define the choices() class method there, too.

```<code>import enum
import json

class CountryCodeMeta(enum.EnumMeta):
    def __new__(metacls, cls, bases, classdict):
        data = classdict['data']
        names = [(country['alpha-2'], int(country['country-code'])) for country in data]

        temp = type(classdict)()
        for name, value in names:
            temp[name] = value

        excluded = set(temp) | set(('data',))
        temp.update(item for item in classdict.items() if item[0] not in excluded)

        return super(CountryCodeMeta, metacls).__new__(metacls, cls, bases, temp)

class CountryCode(enum.Enum, metaclass=CountryCodeMeta):
    data = json.load(open('slim-2.json'))

    @classmethod
    def choices(cls):
        return ((member.value, name) for name, member in cls.__members__.items())
</code>```

Body:
I needed to create an enum to represent the ISO country codes. The country code data comes from a json file which can be obtained from: https://github.com/lukes/ISO-3166-Countries-with-Regional-Codes

So what I've done is:

data = json.load(open('slim-2.json'))
codes_list = [(data[i]['alpha-2'], int(data[i]['country-code']))
              for i in range(len(data))]

CountryCode = enum.Enum('CountryCode', codes_list,)

names_dict = {int(data[i]['country-code']):data[i]['name']
              for i in range(len(data))}
setattr(CountryCode, '_names', names_dict)

CountryCode.choices = classmethod(lambda cls:((member.value, name)
                                  for name, member in cls.__members__.items()))
setattr(CountryCode, '__str__' ,lambda self: self.__class__._names[self.value])

This code snippet is frankly ugly. I looked at alternative ways to define the enum class but couldn't piece together a solution. Is there a way to define the enum in the following form:

class CountryCode(enum.Enum):

    data = json.load(open('slim-2.json'))
    # Some code to define the enum members

    @classmethod
    def choices(cls):
    # etc...

Any suggestions on how to do this?

Body:
Yes, there is a way to define the enum using the alternate declaration syntax you want. It works by hiding the "ugly" code in a metaclass derived from enum.EnumMeta. If you wished, it would also be possible to define the choices() class method there, too.

import enum
import json

class CountryCodeMeta(enum.EnumMeta):
    def __new__(metacls, cls, bases, classdict):
        data = classdict['data']
        names = [(country['alpha-2'], int(country['country-code'])) for country in data]

        temp = type(classdict)()
        for name, value in names:
            temp[name] = value

        excluded = set(temp) | set(('data',))
        temp.update(item for item in classdict.items() if item[0] not in excluded)

        return super(CountryCodeMeta, metacls).__new__(metacls, cls, bases, temp)

class CountryCode(enum.Enum, metaclass=CountryCodeMeta):
    data = json.load(open('slim-2.json'))

    @classmethod
    def choices(cls):
        return ((member.value, name) for name, member in cls.__members__.items())


问:
Reading through null pointer in #define with condition
I have definition of macro printerr

```<code>#define CLR_R "\x1b[1;31m"
#define CLR_N "\x1b[0m"
#define printerr(caller,msg) (caller==NULL)?printf(CLR_R "%s" CLR_N "\n",msg) \
   : printf(CLR_R "%s:" CLR_N " %s\n",caller,msg)
</code>```

And get warning

warning: reading through null pointer (argument 2), when calling printerr(NULL,"error");.

How to suppress this warning?

```<code>#include <stdio.h>
#define printerr(caller,msg) (caller==NULL)?printf("%s\n",msg) : \
    printf("%s: %s\n",caller,msg)
void main() {
    printerr("Error","error occurred"); //will be ok
    printerr(NULL,"error"); //Warning: is caller even checked here?
}
</code>```

答:
This works (gcc, clang):

```<code>#include <stdio.h>
int main()
{
#define CLR_R "\x1b[1;31m"
#define CLR_N "\x1b[0m"

#define printerr(caller,msg)  \
    (caller==NULL)? printf(CLR_R "%s" CLR_N "\n",msg) : \
    printf(CLR_R "%s:" CLR_N " %s\n", ((caller)?(caller):""),msg)

    printerr(NULL,"msg");
    printerr("caller","msg");
}
</code>```

I'm using ((caller)?(caller):"")to suppress the warning. It will never evaluate to "".

You could also use an inline function to the same effect:

```<code>#define CLR_R "\x1b[1;31m"
#define CLR_N "\x1b[0m"
static inline int inl_printerr(char const *caller, char const *msg)
{
    if (caller)
        return printf(CLR_R "%s:" CLR_N " %s\n", caller,msg);
    else
        return printf(CLR_R "%s" CLR_N "\n",msg);
}
</code>```

(Recommended as it avoids the typesafety and double-evaluation issues that macros have).

Body:
I have definition of macro printerr

#define CLR_R "\x1b[1;31m"
#define CLR_N "\x1b[0m"
#define printerr(caller,msg) (caller==NULL)?printf(CLR_R "%s" CLR_N "\n",msg) \
   : printf(CLR_R "%s:" CLR_N " %s\n",caller,msg)

And get warning

warning: reading through null pointer (argument 2), when calling printerr(NULL,"error");.

How to suppress this warning?

#include <stdio.h>
#define printerr(caller,msg) (caller==NULL)?printf("%s\n",msg) : \
    printf("%s: %s\n",caller,msg)
void main() {
    printerr("Error","error occurred"); //will be ok
    printerr(NULL,"error"); //Warning: is caller even checked here?
}

Body:
This works (gcc, clang):

#include <stdio.h>
int main()
{
#define CLR_R "\x1b[1;31m"
#define CLR_N "\x1b[0m"

#define printerr(caller,msg)  \
    (caller==NULL)? printf(CLR_R "%s" CLR_N "\n",msg) : \
    printf(CLR_R "%s:" CLR_N " %s\n", ((caller)?(caller):""),msg)

    printerr(NULL,"msg");
    printerr("caller","msg");
}

I'm using ((caller)?(caller):"")to suppress the warning. It will never evaluate to "".

You could also use an inline function to the same effect:

#define CLR_R "\x1b[1;31m"
#define CLR_N "\x1b[0m"
static inline int inl_printerr(char const *caller, char const *msg)
{
    if (caller)
        return printf(CLR_R "%s:" CLR_N " %s\n", caller,msg);
    else
        return printf(CLR_R "%s" CLR_N "\n",msg);
}

(Recommended as it avoids the typesafety and double-evaluation issues that macros have).


问:
WCF service blocked by Windows Firewall
I've got a WCF service using a HttpBinding. The service is running in a self hosting process (A Windows Service) and this process is inside the Windows Firewall exceptions list.

If the Firewall is active and I'm trying to access the service using a C# client or Internet Explorer, the service does not respond. But if the Firewall is disabled the connection works like a charm.

Does anyone have expirence with WCF and the Windows Firewall? The problem came up on Windows 7 64bit. I didn't try another OS yet.

What am I supposed to do to get this working with an active Firewall?

Regards Michael

EDIT:
I found a clue, that the http.sys has to be added to the firewall exceptions list, as wcf self hosting uses http.sys. Any advices, how to solve this?

EDIT:
I tried opening all listening port manually, which works too, but is not an option, because I don't know them in advance.

答: Try the MSDN article Configuring HTTP and HTTPS.

Title: WCF service blocked by Windows Firewall


问:
Running ionic apps in an Android Emulator.
I am new in ionic framework,and want to run the app I made into an Android emulator. I type this command,

```<code>ionic emulate android
</code>```

and get this error.

```<code>Error: cmd: Command failed with exit code 1
</code>```

I have all the path variables set up correctly I think.

PATH

```<code>C:\Program Files\Git\usr\local;C:\Users\W\AppData\Roaming\npm\node_modules\bower\bin;C:\Users\Theodosios\AppData\Roaming\npm;C:\Program Files (x86)\Java\jre1.8.0_111\bin
</code>```

JAVA_OPTIONS

```<code>-Xmx512M
</code>```

Any ideas what is wrong and how can it be fixed?

Thanks,

Theo.

答:
1) Options
Remove android platfrom and install again.

Remove platform

$ cordova platform remove android

Add Platform

$ cordova platform add android

2) Options

Open SDK manager => Run as administrator

You will require:

1) SDK Platform

2) Android SDK Platform-tools

3) Andoid SDK tools

Body:
I am new in ionic framework,and want to run the app I made into an Android emulator. I type this command,

ionic emulate android

and get this error.

Error: cmd: Command failed with exit code 1

I have all the path variables set up correctly I think.

PATH

C:\Program Files\Git\usr\local;C:\Users\W\AppData\Roaming\npm\node_modules\bower\bin;C:\Users\Theodosios\AppData\Roaming\npm;C:\Program Files (x86)\Java\jre1.8.0_111\bin

JAVA_OPTIONS

-Xmx512M

Any ideas what is wrong and how can it be fixed?

Thanks,

Theo.


问:
How can I force reload InfoWindow on Android Maps v2 api's Marker?
Hi guys I'm a beginner with Android programming and I'm trying to make custom InfoWindow for my markers on my map application. My InfoWindows have to display a dynamical image (I download and set with Picasso library) different markers ad hoc and some text fields, like the name of the "POI", the address and the distance in minutes, walking and with a car. The problem is that InfoWindowAdapter are images and so I've seen that the only way is to force reload the showing of the marker's infowindow. But if I try (as I seen on some forums and also in others questions here on StackOverflow), my app crash. Below I post my code with comment that can help you and the screen of my app. Really thanks all of you.

Screenshot:

Code:

```<code>// ****** Custom InfoWindowAdapter ****** //
map.setInfoWindowAdapter(new InfoWindowAdapter() {

View v = getLayoutInflater().inflate(R.layout.custom_info_window, null);

@Override
public View getInfoWindow(Marker marker) {                //As I've seen on the web, if the marker is null and it is showing infowindow, I do a refresh,
    if (marker != null && marker.isInfoWindowShown()){    //but with the debug I've seen that it doesn't never enter in this IF statement and nothing happen when the image is loaded.
        marker.hideInfoWindow();
        marker.showInfoWindow();
    }
    return null;
}

@Override
public View getInfoContents(final Marker marker) {

BuildInfoMatrix req = new BuildInfoMatrix();

String nome = marker.getTitle();
String currentUrl = "";

int vuoto = -15;

try{
    currentUrl=req.findImageUrl(nome); //from another class (BuildInfoMatrix) I retrieve the right image marker URL to display
}catch(Exception e){
    currentUrl = "http://upload.wikimedia.org/wikipedia/commons/b/bb/XScreenSaver_simulating_Windows_9x_BSOD.png"; //If the currentURL is null (I haven't set any URL for the marker) it set an error image
}
if (currentUrl == null)
{
    currentUrl = "http://upload.wikimedia.org/wikipedia/commons/b/bb/XScreenSaver_simulating_Windows_9x_BSOD.png";
}
ImageView image;
image = (ImageView) v.findViewById(R.id.image_nuvoletta); //image_nuvoletta is where it will be placed on the InfoWindowAdapter

Picasso.with(v.getContext())         //Here with Picasso I download the image and I set into
    .load(currentUrl)                //R.id.image_nuvoletta
    .error(R.drawable.ic_launcher)
    .resize(150, 110)
    .into(image, new Callback(){
    @Override
    public void onSuccess(){
        //I should reload here (when the image have been downloaded) the infoWindowAdapter but
        //if I place here "marker.showInfoWindow()" the app crash; without, nothing happens.
    }

    @Override
    public void onError(){

    }
});

                        /***********************************/
</code>```

答:
I have the same problem, after going to anywhere and no answer found, i do try my self with new Handler().postDelayed() and it's really work for me.

```<code>@Override
public View getInfoWindow(Marker marker) {
    // Left it empty
    return null;
}

@Override
public View getInfoContents(final Marker marker) {
    ....

    Picasso.with(v.getContext())         //Here with Picasso I download the image and I set into
        .load(currentUrl)                //R.id.image_nuvoletta
        .error(R.drawable.ic_launcher)
        .resize(150, 110)
        .into(image, new Callback(){
        @Override
        public void onSuccess(){
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    marker.showInfoWindow();
                }
            }, 500);
        }

        @Override
        public void onError(){
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    marker.showInfoWindow();
                }
            }, 500);
        }
    });
}
</code>```

Don't forget to vote if this snippet work for you.

Body:
Hi guys I'm a beginner with Android programming and I'm trying to make custom InfoWindow for my markers on my map application. My InfoWindows have to display a dynamical image (I download and set with Picasso library) different markers ad hoc and some text fields, like the name of the "POI", the address and the distance in minutes, walking and with a car. The problem is that InfoWindowAdapter are images and so I've seen that the only way is to force reload the showing of the marker's infowindow. But if I try (as I seen on some forums and also in others questions here on StackOverflow), my app crash. Below I post my code with comment that can help you and the screen of my app. Really thanks all of you.

Screenshot:

Code:

// ****** Custom InfoWindowAdapter ****** //
map.setInfoWindowAdapter(new InfoWindowAdapter() {

View v = getLayoutInflater().inflate(R.layout.custom_info_window, null);

@Override
public View getInfoWindow(Marker marker) {                //As I've seen on the web, if the marker is null and it is showing infowindow, I do a refresh,
    if (marker != null && marker.isInfoWindowShown()){    //but with the debug I've seen that it doesn't never enter in this IF statement and nothing happen when the image is loaded.
        marker.hideInfoWindow();
        marker.showInfoWindow();
    }
    return null;
}

@Override
public View getInfoContents(final Marker marker) {

BuildInfoMatrix req = new BuildInfoMatrix();

String nome = marker.getTitle();
String currentUrl = "";

int vuoto = -15;

try{
    currentUrl=req.findImageUrl(nome); //from another class (BuildInfoMatrix) I retrieve the right image marker URL to display
}catch(Exception e){
    currentUrl = "http://upload.wikimedia.org/wikipedia/commons/b/bb/XScreenSaver_simulating_Windows_9x_BSOD.png"; //If the currentURL is null (I haven't set any URL for the marker) it set an error image
}
if (currentUrl == null)
{
    currentUrl = "http://upload.wikimedia.org/wikipedia/commons/b/bb/XScreenSaver_simulating_Windows_9x_BSOD.png";
}
ImageView image;
image = (ImageView) v.findViewById(R.id.image_nuvoletta); //image_nuvoletta is where it will be placed on the InfoWindowAdapter

Picasso.with(v.getContext())         //Here with Picasso I download the image and I set into
    .load(currentUrl)                //R.id.image_nuvoletta
    .error(R.drawable.ic_launcher)
    .resize(150, 110)
    .into(image, new Callback(){
    @Override
    public void onSuccess(){
        //I should reload here (when the image have been downloaded) the infoWindowAdapter but
        //if I place here "marker.showInfoWindow()" the app crash; without, nothing happens.
    }

    @Override
    public void onError(){

    }
});

                        /***********************************/

Body:
I have the same problem, after going to anywhere and no answer found, i do try my self with new Handler().postDelayed() and it's really work for me.

@Override
public View getInfoWindow(Marker marker) {
    // Left it empty
    return null;
}

@Override
public View getInfoContents(final Marker marker) {
    ....

    Picasso.with(v.getContext())         //Here with Picasso I download the image and I set into
        .load(currentUrl)                //R.id.image_nuvoletta
        .error(R.drawable.ic_launcher)
        .resize(150, 110)
        .into(image, new Callback(){
        @Override
        public void onSuccess(){
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    marker.showInfoWindow();
                }
            }, 500);
        }

        @Override
        public void onError(){
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    marker.showInfoWindow();
                }
            }, 500);
        }
    });
}

Don't forget to vote if this snippet work for you.


问:
Wordpress theme header
I have Esteem blog wordpress theme and the header title dont show in home page

In article page it is show the article title etc but in homepage nothing.

In the homepage I want in the header title the blog title: BlogTest

答:
There must be an option given there in Appearance>Customize tab. Check their documentation if are unable to find it.

https://docs.themegrill.com/esteem/

Also have you checked the header.php file in the editor? It will be a lot better if your share your site link.

Title: Wordpress theme header


问:
How can I control the font size of sequence logos?
I have many sequence logos, which I plot using ggplot2 and ggseqlogo. The vertical axis remains constant, but the horizontal axis is differing for each plot.

I am not aware how I can create sequence logos with identical width for each letter. I tried to manually adjust the letter width using stack_width for varying length of my sequence. Unfortunately, that leads to a gap between the individual letters.

How can I achieve identical letter sizes for plots with varying sequence length without introducing a gap between the letters?

Below an example of the issue I am facing:

```<code># "R version 3.3.1 (2016-06-21)"
# "x86_64-w64-mingw32"
# library(ggplot2)
# library(ggseqlogo)

AA_alphabet <- c('R','H','K','D','E','S','Y','T','N','Q','C','G','P','W','A','V','I','L','M','F')

AA1 = c('RHKDES', 'RHKDES', 'RHKDGP', 'RHKDGP', 'TNQCGP')
ggplot() + geom_logo(AA1, method='p', seq_type='other', namespace=AA_alphabet)+theme_logo()

AA2 = c('RH', 'RH', 'RH', 'TN', 'TN')
ggplot() + geom_logo(AA2, method='p', seq_type='other', namespace=AA_alphabet)+theme_logo()

# control for sequence length:
ggplot() + geom_logo(AA2, method='p',seq_type='other', namespace=AA_alphabet,stack_width = 0.2) + theme_logo()
</code>```

答:
Actually, how about something like this?

```<code>require(gridExtra)
AA_alphabet <- c('R','H','K','D','E','S','Y','T','N','Q','C','G','P','W','A','V','I','L','M','F')

AA1 = c('RHKDES', 'RHKDES', 'RHKDGP', 'RHKDGP', 'TNQCGP')
AA2 = c('RH', 'RH', 'RH', 'TN', 'TN')

p1 = ggplot() + geom_logo(AA1, method='p', seq_type='other', namespace=AA_alphabet)+theme_logo()
p2 = ggplot() + geom_logo(AA2, method='p', seq_type='other', namespace=AA_alphabet)+theme_logo()

p3 = grid.arrange(p1, p2, ncol=1)
print(p3)
</code>```

You can add as many plots as you want to grid.arrange, as well as adjust the layout of rows and columns using ncol and nrow parameters.

Body:
I have many sequence logos, which I plot using ggplot2 and ggseqlogo. The vertical axis remains constant, but the horizontal axis is differing for each plot.

I am not aware how I can create sequence logos with identical width for each letter. I tried to manually adjust the letter width using stack_width for varying length of my sequence. Unfortunately, that leads to a gap between the individual letters.

How can I achieve identical letter sizes for plots with varying sequence length without introducing a gap between the letters?

Below an example of the issue I am facing:

# "R version 3.3.1 (2016-06-21)"
# "x86_64-w64-mingw32"
# library(ggplot2)
# library(ggseqlogo)

AA_alphabet <- c('R','H','K','D','E','S','Y','T','N','Q','C','G','P','W','A','V','I','L','M','F')

AA1 = c('RHKDES', 'RHKDES', 'RHKDGP', 'RHKDGP', 'TNQCGP')
ggplot() + geom_logo(AA1, method='p', seq_type='other', namespace=AA_alphabet)+theme_logo()

AA2 = c('RH', 'RH', 'RH', 'TN', 'TN')
ggplot() + geom_logo(AA2, method='p', seq_type='other', namespace=AA_alphabet)+theme_logo()

# control for sequence length:
ggplot() + geom_logo(AA2, method='p',seq_type='other', namespace=AA_alphabet,stack_width = 0.2) + theme_logo()

Body:
Actually, how about something like this?

require(gridExtra)
AA_alphabet <- c('R','H','K','D','E','S','Y','T','N','Q','C','G','P','W','A','V','I','L','M','F')

AA1 = c('RHKDES', 'RHKDES', 'RHKDGP', 'RHKDGP', 'TNQCGP')
AA2 = c('RH', 'RH', 'RH', 'TN', 'TN')

p1 = ggplot() + geom_logo(AA1, method='p', seq_type='other', namespace=AA_alphabet)+theme_logo()
p2 = ggplot() + geom_logo(AA2, method='p', seq_type='other', namespace=AA_alphabet)+theme_logo()

p3 = grid.arrange(p1, p2, ncol=1)
print(p3)

You can add as many plots as you want to grid.arrange, as well as adjust the layout of rows and columns using ncol and nrow parameters.


问:
ng-click is not firing
adding the following 'hyperlink' to html like:

```<code><a style="color:white" ng-click="ClickMe()"><i class="fa fa-trash-o" style="color:white"></i>Click</a>
</code>```

and then use this code to trigger click event like

```<code> $scope.ClickMe = function () { alert("clicked"); }
</code>```

works fine, but this did not work when  'hyperlink' generated dynamically like

```<code> $('<a style="color:white" ng-click="ClickMe()"><i class="fa fa-trash-o" style="color:white"></i>Click</a>').insertAfter("#dashboard_link");
</code>```

Could anyone explain why did that happen?

答: use javascript:void(0)  within your hyperlink</p>

Title: ng-click is not firing

Body:
adding the following 'hyperlink' to html like:

Click

and then use this code to trigger click event like

 $scope.ClickMe = function () { alert("clicked"); }

works fine, but this did not work when  'hyperlink' generated dynamically like

 $('Click').insertAfter("#dashboard_link");

Could anyone explain why did that happen?


问:
How to implement exponential backoff/delay calculation with fixed timeout and number of attempts?
Most backoff/delay algorithms I've seen have fixed number of attempts OR fixed timeout, but not both.

I want to make exactly M attempts within T seconds, with exponential spacing between them, so that "T = delay(0) + delay(1) + ... + delay(M-1)", where "delay(N) = (e^N - 1) / e" (where N - retry number).

How to calculate "e" value in the description above, so that exactly M attempts will be made within overall timeout T (with M and T specified in advance)?

答:
Since "T" is a monotonous function of "e", you can perform a binary search to find the best value that fits.

Here's an example Python program to find such "e" given "T" and "M":

def total_time(e, M):
    current = 1
    total = 0
    for i in range(M):
        total += current-1
        current *= e
    return total

def find_best_e(T, M):
    a, b = 0, T
    while abs(a-b) > 1e-6:
        m = (a+b)/2.0
        if total_time(m, M) > T:
            b = m
        else:
            a = m
    return (a+b)/2

e = find_best_e(10, 3)
print([e**n-1 for n in range(3)])
```


问:
set height programmatically for mapfragment in xamarin android
I am using xamarin android.

I want to set the height for the below fragment tag programmatically.

```<code><fragment
                android:id="@+id/googlemap"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                class="com.google.android.gms.maps.MapFragment"/>
</code>```

Could anyone please advice me.

Thanks in Advance.

答:
Try this:</p>

```<code>var mapFragment = (MapFragment)FragmentManager.FindFragmentById(Resource.Id.googlemap);

mapFragment.View.LayoutParameters.Height = 500; //The size you decide
mapFragment.View.LayoutParameters.Width = 500; //The size you decide
</code>```

Body:
I am using xamarin android.

I want to set the height for the below fragment tag programmatically.

<fragment
                android:id="@+id/googlemap"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                class="com.google.android.gms.maps.MapFragment"/>

Could anyone please advice me.

Thanks in Advance.

Body:
Try this:

var mapFragment = (MapFragment)FragmentManager.FindFragmentById(Resource.Id.googlemap);

mapFragment.View.LayoutParameters.Height = 500; //The size you decide
mapFragment.View.LayoutParameters.Width = 500; //The size you decide


问:
Correct way to emit value with Marko.js
I want a Marko.js component to emit an event along with a value, I then want the containing component to listen for the event and access the value.

I have a simple button component which looks like this:

class {
    doSomething() {
        this.emit('buttonClicked', {someValue:'10'});
    }
}

<button.example-button on-click('doSomething')>Click me!</button>```
</div>
</div>
</p>

<p>The containing component then looks like this...</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class {
 onButtonClicked(data){
  console.log("I heard event:" + data.someValue);
 }
}

<div class="button-manager">
  <my-button on-buttonClicked('onButtonClicked') />
</div></code>```

This works and correctly logs the event with the value. However I am a little confused as I would expect the syntax in the container to reference the passed arguments in the event listener... like this...

  <my-button on-buttonClicked('onButtonClicked', data) />

```

However that then traces out an empty object. If I put a string as the argument that string is logged and overwrites the original data argument passed through from the emitter.

Is this the intended behaviour?

答:
Given the following and continuing with your example:

```<code>class {
    onButtonClicked(foo, bar, eventArg){
        console.log('foo:', foo);
        console.log('bar:', bar);
        console.log('eventArg:', eventArg);
    }
}

$ var foo = 'foo';
$ var bar = 'bar';

<div class="button-manager">
    <my-button on-buttonClicked('onButtonClicked', foo, bar) />
</div>
</code>```

The output will be the following on buttonClicked is emitted:

```<code>foo: foo
bar: bar
eventArg: { someValue: 10 }
</code>```

Additional arguments passed after the method name for an event handler will be passed to event handler method at the beginning of the arguments. See: http://markojs.com/docs/components/#codeon-eventmethodname-argscode

Side note: this was intended to mirror the behavior of Function.prototype.bind

Unless there was additional data that you wanted to pass to your event handler method (data that was not provided when this.emit() was called) then there is no need to bind any additional arguments.

Hope that answers your question.

Title: Correct way to emit value with Marko.js

Body:
I want a Marko.js component to emit an event along with a value, I then want the containing component to listen for the event and access the value.

I have a simple button component which looks like this:

class {
    doSomething() {
        this.emit('buttonClicked', {someValue:'10'});
    }
}

<button.example-button on-click('doSomething')>Click me!</button>

The containing component then looks like this...

class {
 onButtonClicked(data){
  console.log("I heard event:" + data.someValue);
 }
}

  <my-button on-buttonClicked('onButtonClicked') />

This works and correctly logs the event with the value. However I am a little confused as I would expect the syntax in the container to reference the passed arguments in the event listener... like this...

  <my-button on-buttonClicked('onButtonClicked', data) />

However that then traces out an empty object. If I put a string as the argument that string is logged and overwrites the original data argument passed through from the emitter.

Is this the intended behaviour?

Body:
Given the following and continuing with your example:

class {
    onButtonClicked(foo, bar, eventArg){
        console.log('foo:', foo);
        console.log('bar:', bar);
        console.log('eventArg:', eventArg);
    }
}

$ var foo = 'foo';
$ var bar = 'bar';

<div class="button-manager">
    <my-button on-buttonClicked('onButtonClicked', foo, bar) />
</div>

The output will be the following on buttonClicked is emitted:

foo: foo
bar: bar
eventArg: { someValue: 10 }

Additional arguments passed after the method name for an event handler will be passed to event handler method at the beginning of the arguments. See: http://markojs.com/docs/components/#codeon-eventmethodname-argscode

Side note: this was intended to mirror the behavior of Function.prototype.bind

Unless there was additional data that you wanted to pass to your event handler method (data that was not provided when this.emit() was called) then there is no need to bind any additional arguments.

Hope that answers your question.


问:
Passing window handle to view model in WPF with MVVM
I am using an external library which requires a window handle. My application architecture is MVVM, but the external library doesn't exactly fit into this architecture. I have decided that the view model is the most appropriate place to call an initialization function which requires a window handle. How can I get the window handle from my view to my view model?</p>

答:
Typically, your view model shouldn't know about the implementation details of your view (such as it's HWND). However, as your question indicates, the external library you are using requires you to initialize it, and you can only do that in one place. Assuming that your view model is the most appropriate place for it (it might even belong in the model), you can do something like the following.

This implementation provides the window handle to your view model as soon as all the pieces are available. Note that the view model implementation that you provided in your previous question requires the HWND in the view model's constructor. You're going to have to change your view model so that the initialization happens via an explicitly called method or property. In the code below, I assume that there is a method in your view model called OnWindowHandleAvailable. You could certainly call that method Initialize instead, or you could put a Handle property on your view model which you explicitly set.

```<code>public partial class View
{
    public View()
    {
        InitializeComponent();
        this.Loaded += View_Loaded;
        this.DataContextChanged += View_DataContextChanged;
    }

    private void View_Loaded(object sender, RoutedEventArgs e)
    {
        GiveWindowHandleToViewModel();
    }

    private void View_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        GiveWindowHandleToViewModel();
    }

    private void GiveWindowHandleToViewModel()
    {
        // get view model
        var viewModel = this.DataContext as ViewModel;
        if (viewModel == null)
            return;

        // get window handle
        var windowHandle = this.GetWindowHandle();
        if (windowHandle == IntPtr.Zero)
            return;

        // signal view model
        viewModel.OnWindowHandleAvailable(windowHandle);
    }

    private IntPtr GetWindowHandle()
    {
        // get window
        var window = Window.GetWindow(this);
        if (window == null)
            return IntPtr.Zero;

        // get window handle
        return new WindowInteropHelper(window).Handle;
    }
}
</code>```

Body:
Typically, your view model shouldn't know about the implementation details of your view (such as it's HWND). However, as your question indicates, the external library you are using requires you to initialize it, and you can only do that in one place. Assuming that your view model is the most appropriate place for it (it might even belong in the model), you can do something like the following.

This implementation provides the window handle to your view model as soon as all the pieces are available. Note that the view model implementation that you provided in your previous question requires the HWND in the view model's constructor. You're going to have to change your view model so that the initialization happens via an explicitly called method or property. In the code below, I assume that there is a method in your view model called OnWindowHandleAvailable. You could certainly call that method Initialize instead, or you could put a Handle property on your view model which you explicitly set.

public partial class View
{
    public View()
    {
        InitializeComponent();
        this.Loaded += View_Loaded;
        this.DataContextChanged += View_DataContextChanged;
    }

    private void View_Loaded(object sender, RoutedEventArgs e)
    {
        GiveWindowHandleToViewModel();
    }

    private void View_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        GiveWindowHandleToViewModel();
    }

    private void GiveWindowHandleToViewModel()
    {
        // get view model
        var viewModel = this.DataContext as ViewModel;
        if (viewModel == null)
            return;

        // get window handle
        var windowHandle = this.GetWindowHandle();
        if (windowHandle == IntPtr.Zero)
            return;

        // signal view model
        viewModel.OnWindowHandleAvailable(windowHandle);
    }

    private IntPtr GetWindowHandle()
    {
        // get window
        var window = Window.GetWindow(this);
        if (window == null)
            return IntPtr.Zero;

        // get window handle
        return new WindowInteropHelper(window).Handle;
    }
}


问:
How to kill all instance of uwsgi
I am trying to upload my project to the server. There is already a project in the server now. I have new project which I want to run and replace the old project with the new one, so I pull the new project to the server. Then I activate the virtual environment and do all the necessary work. Then when I try to run the command:

```<code>uwsgi --plugins=python --chdir=/var/www/prjt/src/ --socket=127.0.0.1:8889 --module=prjt.wsgi:application &
</code>```

it tell me that

```<code>probably another instance of uWSGI is running on the same address (127.0.0.1:8889).
bind(): Address already in use [core/socket.c line 761]
</code>```

I searched for similar problems and found some solutions about killing all instance of uwsgi as mentioned in this answer here but could not find how to do it.

答:
you can get the pid of the uwsgi process here lsof -t -i tcp:8000

and kill it then kill -9 pid

ContentLicense: CC BY-SA 4.0

Title: How to kill all instance of uwsgi

Body:
I am trying to upload my project to the server. There is already a project in the server now. I have new project which I want to run and replace the old project with the new one, so I pull the new project to the server. Then I activate the virtual environment and do all the necessary work. Then when I try to run the command:

uwsgi --plugins=python --chdir=/var/www/prjt/src/ --socket=127.0.0.1:8889 --module=prjt.wsgi:application &

it tell me that

probably another instance of uWSGI is running on the same address (127.0.0.1:8889).
bind(): Address already in use [core/socket.c line 761]

I searched for similar problems and found some solutions about killing all instance of uwsgi as mentioned in this answer here but could not find how to do it.


问:
Bootstrap datetimepicker without default initial value
I am using bootstrap datetimepicker I wanted to remove default selected date.

$("#datetimepicker1").datetimepicker({ format: 'MM/DD/YYYY', minDate:new Date() });

答:
if you print out new Date() you will understand it is a datetime, you should set as a date which you can use (new Date()).toDateString()

```<code>var datetimepicker1 = $('#datetimepicker1').datetimepicker({
  format: 'YYYY-MM-DD',
  minDate: (new Date()).toDateString()
})
</code>```

https://jsfiddle.net/dalinhuang/0Ltv25o8/4795/

or you can use moment js to set the minDate...
if you use useCurrent: false will exclude 'Today' so use moment or find the 'day' yourself.

```<code>var datetimepicker1 = $('#datetimepicker1').datetimepicker({
  format: 'YYYY-MM-DD',
  minDate: moment().startOf('day')
})
</code>```

https://jsfiddle.net/dalinhuang/0Ltv25o8/4793/

Body:
if you print out new Date() you will understand it is a datetime, you should set as a date which you can use (new Date()).toDateString()

var datetimepicker1 = $('#datetimepicker1').datetimepicker({
  format: 'YYYY-MM-DD',
  minDate: (new Date()).toDateString()
})

https://jsfiddle.net/dalinhuang/0Ltv25o8/4795/

or you can use moment js to set the minDate...
if you use useCurrent: false will exclude 'Today' so use moment or find the 'day' yourself.

var datetimepicker1 = $('#datetimepicker1').datetimepicker({
  format: 'YYYY-MM-DD',
  minDate: moment().startOf('day')
})

https://jsfiddle.net/dalinhuang/0Ltv25o8/4793/


问:
Using a timer in java Error
```<code> public void setTimerCount(View view){
        int value5;
        final double timerCountSeconds = 0;

        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                timerCountSeconds ++ 0.1;
                timerCount.setText("" + (timerCountSeconds));

            }
        };
</code>```

I think this is right but i get this error on the call of the variable in the run function "Not a Statement

答:
try this..</p>

```<code>public void setTimerCount(View view){
    int value5;
    final double timerCountSeconds = 0;

    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            //timerCountSeconds ++ 0.1; is not valid java syntax
            timerCountSeconds =timerCountSeconds+ 0.1;
            timerCount.setText("" + (timerCountSeconds));

        }
    };
</code>```

Title: Using a timer in java Error

Body:
 public void setTimerCount(View view){
        int value5;
        final double timerCountSeconds = 0;

        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                timerCountSeconds ++ 0.1;
                timerCount.setText("" + (timerCountSeconds));

            }
        };

I think this is right but i get this error on the call of the variable in the run function "Not a Statement

Body:
try this..

public void setTimerCount(View view){
    int value5;
    final double timerCountSeconds = 0;

    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            //timerCountSeconds ++ 0.1; is not valid java syntax
            timerCountSeconds =timerCountSeconds+ 0.1;
            timerCount.setText("" + (timerCountSeconds));

        }
    };


问:
How can I have the main repository stored on a local network?
I'm wondering how can I have the main Mercurial repository stored on the local network and every developer connected to it can do the usual things (just like with BitBucket online.)

Thanks.

答:
Check https://www.mercurial-scm.org/wiki/PublishingRepositories

If it's only on a local network, hg serve is the easiest/fastest with 0 auth support.
of course you can always use ssh without the need of setting up a server.
hg clone ssh://your-main-server/path/to/repo


问:
Cordova iOS: xcrun can't find "PackageApplication" after xcode update
This morning, xcode got updated to version 8.3 on my osx building device.

Since then, when I try to build my iOs app with Cordova, I get the following error at the end of the building process:

```<code> [exec]
 [exec] ** BUILD SUCCEEDED **
 [exec]
 [exec] xcrun: error: unable to find utility "PackageApplication", not a developer tool or in PATH
 [exec] Error: Error code 72 for command: xcrun with args: -sdk,iphoneos,PackageApplication,-v,[source.app]-o,[destination.ipa]
 [exec] Result 1
</code>```

I can't seem to get this fixed in my Cordova or Xcode setup. Wouldn't know where to start ;)

Did anyone experience the same issue? Do you have some advise for a solution.

Thank you!

(I'll be happy to buy a beer if you could help me out)

答:
This tool has been removed from Xcode 8.3.  It was marked as deprecated for a few versions, and now it's sadly gone.

You will need to use xcodebuild and it may be a bit of a pain with Cordova

Body:
This morning, xcode got updated to version 8.3 on my osx building device.

Since then, when I try to build my iOs app with Cordova, I get the following error at the end of the building process:

 [exec]
 [exec] ** BUILD SUCCEEDED **
 [exec]
 [exec] xcrun: error: unable to find utility "PackageApplication", not a developer tool or in PATH
 [exec] Error: Error code 72 for command: xcrun with args: -sdk,iphoneos,PackageApplication,-v,[source.app]-o,[destination.ipa]
 [exec] Result 1

I can't seem to get this fixed in my Cordova or Xcode setup. Wouldn't know where to start ;)

Did anyone experience the same issue? Do you have some advise for a solution.

Thank you!

(I'll be happy to buy a beer if you could help me out)


问:
Wicked PDF with password protection
Can anyone tell me that how to make password on wicked PDF before open?
Or

Is there any way to make wicked pdf password protective.

答:
I had already gone through that link, but nothing happened.
Yes, it's true that they will be implementing in future but client wants password functionality within 2 or 3 days.

So, therefore Now I'm trying to implement with Prawn gem which is a little difficult because  I'm not familiar with Prawn.
Pdf is too big therefore I am little worried because it can take time may be more than 1 week.

But if anyone will suggest with wicked pdf, will be appreciated.

Thanks

Title: Wicked PDF with password protection