问:
Spring Responsebody, Naming List objects in json
I'm working on a REST service using the Spring Framework's spring-boot library.
I'm getting responses from my services as JSON, my problem is I am using a parent class to store all of the objects being sent as the result of a request and the response is sent without names on the JSON array.

This is the output for one of my tests:

```<code>success: true,
message: null,
data: [
{ },
{
vehicleBatteryId: 3,
modelTypeId: 3,
cycleCount: -9640,
currentCapacity: -9640,
manufactureDate: 414037682000,
manufacturerId: 10,
modeTypeCode: 461271880,
partStatus: 215692740,
lastMaintenanceDate: 428880743000
},
{
vehicleBmsId: 3,
bmsModelId: 5,
manufactureDate: 942436247000,
manufacturerId: 4,
lastMaintenanceDate: 437823118000,
partStatus: 477293493,
replaceDate: 179716409000,
replaceDistance: 4783810
}...
</code>```

And this is the Result I'm trying to get:

```<code>success: true,
message: null,
data: {
Property1:{ },
Property2:{
vehicleBatteryId: 3,
modelTypeId: 3,
cycleCount: -9640,
currentCapacity: -9640,
manufactureDate: 414037682000,
manufacturerId: 10,
modeTypeCode: 461271880,
partStatus: 215692740,
lastMaintenanceDate: 428880743000
},...
</code>```

This is the parent class. I want to be able to use it for every response my service creates regardless of the details of that response

```<code>public class MasterResponse extends RequestStatus{
    private List<Object> data;

    public MasterResponse() {
        init();
    }

    public MasterResponse(boolean _success, String _message){
        super(_success, _message);
        init();
    }
    private void init(){
        this.data = new ArrayList<Object>();
    }

    public void addModel(Object newModel){
        this.data.add(newModel);
    }

    public void clearData(){
        this.data=null;
    }

    public List<Object> getData() {
        return data;
    }

    public void setData(List<Object> data) {
        this.data = data;
    }
}
</code>```

Anyone have any ideas? As far as I can tell Spring uses Jackson to convert to json, I'm exploring what I can do with the json view functions they provide at the moment.

答:
You are using an ArrayList, which Jackson serialize as [{...},{...}, ...]
You could use a Map (i.e. HashMap<>) for data, but you might need to create a custom "push()" or add() function, in order to maintain the index propery. i.e. Property1.

the HashMap Object wil be serialised as: data: {"index-1":{...}, "index-2": { ... } ... }

simple example for your code:

```<code>    private Map<String, Object> data;
    int nextIndex = 1;

    private void init(){
        this.data = new HashMap<String, Object>();
    }

    public void addModel(Object newModel){
            this.data.add("Property" + this.nextIndex, newModel);
            this.nextIndex++;
    }
</code>```

Body:
I'm working on a REST service using the Spring Framework's spring-boot library.
I'm getting responses from my services as JSON, my problem is I am using a parent class to store all of the objects being sent as the result of a request and the response is sent without names on the JSON array.

This is the output for one of my tests:

success: true,
message: null,
data: [
{ },
{
vehicleBatteryId: 3,
modelTypeId: 3,
cycleCount: -9640,
currentCapacity: -9640,
manufactureDate: 414037682000,
manufacturerId: 10,
modeTypeCode: 461271880,
partStatus: 215692740,
lastMaintenanceDate: 428880743000
},
{
vehicleBmsId: 3,
bmsModelId: 5,
manufactureDate: 942436247000,
manufacturerId: 4,
lastMaintenanceDate: 437823118000,
partStatus: 477293493,
replaceDate: 179716409000,
replaceDistance: 4783810
}...

And this is the Result I'm trying to get:

success: true,
message: null,
data: {
Property1:{ },
Property2:{
vehicleBatteryId: 3,
modelTypeId: 3,
cycleCount: -9640,
currentCapacity: -9640,
manufactureDate: 414037682000,
manufacturerId: 10,
modeTypeCode: 461271880,
partStatus: 215692740,
lastMaintenanceDate: 428880743000
},...

This is the parent class. I want to be able to use it for every response my service creates regardless of the details of that response

public class MasterResponse extends RequestStatus{
    private List<Object> data;

    public MasterResponse() {
        init();
    }

    public MasterResponse(boolean _success, String _message){
        super(_success, _message);
        init();
    }
    private void init(){
        this.data = new ArrayList<Object>();
    }

    public void addModel(Object newModel){
        this.data.add(newModel);
    }

    public void clearData(){
        this.data=null;
    }

    public List<Object> getData() {
        return data;
    }

    public void setData(List<Object> data) {
        this.data = data;
    }
}

Anyone have any ideas? As far as I can tell Spring uses Jackson to convert to json, I'm exploring what I can do with the json view functions they provide at the moment.

Body:
You are using an ArrayList, which Jackson serialize as [{...},{...}, ...]
You could use a Map (i.e. HashMap<>) for data, but you might need to create a custom "push()" or add() function, in order to maintain the index propery. i.e. Property1.

the HashMap Object wil be serialised as: data: {"index-1":{...}, "index-2": { ... } ... }

simple example for your code:

    private Map<String, Object> data;
    int nextIndex = 1;

    private void init(){
        this.data = new HashMap<String, Object>();
    }

    public void addModel(Object newModel){
            this.data.add("Property" + this.nextIndex, newModel);
            this.nextIndex++;
    }


来源: stackexchange

问:
How to call a factory which reads a json file, inside a .run method in angular js?Is it possible or not?
I need to call a factory inside run method.Is it possible or not?
And the factory call returns a array of objects.
My code is :   </p>

```<code> myApp.run(function($rootScope, $location, $route, AuthService) {
    $rootScope.$on('$routeChangeStart',
        function(event, next, current) {
            $rootScope.menuPermission = next.access.restricted
            /***Need to call a factory here***/
            AuthService.getUserStatus()
                .then(function() {
                    if (next.access.restricted && !AuthService.isLoggedIn()) {
                        $location.path('/login');
                        $route.reload();
                    }
                });
           });
   });
</code>```

答:
Yes. You can call a factory inside your run method.

Factory :

```<code>myApp.factory('YourFactory', function(){
   var svc={};
   svc.getData = function(){
     //your processing logic
   }
   return svc;
 });
</code>```

Run method :

```<code>myApp.run(function($rootScope, $location, $route, AuthService, YourFactory) {
$rootScope.$on('$routeChangeStart',
function(event, next, current) {
    $rootScope.menuPermission = next.access.restricted
    YourFactory.getData().then(function(){
     // do what you want here
    });
    AuthService.getUserStatus()
        .then(function() {
            if (next.access.restricted && !AuthService.isLoggedIn())
         {
                $location.path('/login');
                $route.reload();
            }
        });
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to call a factory inside run method.Is it possible or not?
And the factory call returns a array of objects.
My code is :

 myApp.run(function($rootScope, $location, $route, AuthService) {
    $rootScope.$on('$routeChangeStart',
        function(event, next, current) {
            $rootScope.menuPermission = next.access.restricted
            /***Need to call a factory here***/
            AuthService.getUserStatus()
                .then(function() {
                    if (next.access.restricted && !AuthService.isLoggedIn()) {
                        $location.path('/login');
                        $route.reload();
                    }
                });
           });
   });

Body:
Yes. You can call a factory inside your run method.

Factory :

myApp.factory('YourFactory', function(){
   var svc={};
   svc.getData = function(){
     //your processing logic
   }
   return svc;
 });

Run method :

myApp.run(function($rootScope, $location, $route, AuthService, YourFactory) {
$rootScope.$on('$routeChangeStart',
function(event, next, current) {
    $rootScope.menuPermission = next.access.restricted
    YourFactory.getData().then(function(){
     // do what you want here
    });
    AuthService.getUserStatus()
        .then(function() {
            if (next.access.restricted && !AuthService.isLoggedIn())
         {
                $location.path('/login');
                $route.reload();
            }
        });
});

ContentLicense: CC BY-SA 3.0


问:
Android Application Lifecycle
I see a lot of answers concerning the Activity Lifecycle and that for most part is clear to me. What I'm looking for is the Application Lifecycle. I have the following case:

Application starts - Invalidate PIN

A PIN has to be entered if it is stale of invalid

Application is backgrounded (Android Home screen is visible) - Invalidate PIN

The applicatiion is foregrounded (App becomes visible again) - goto step 2

With the Activity Lifecycle it is hard if not impossible to achieve. Any suggestions?

答:
When your application is backgrounded (no longer visible), the method called is onStop(), and when the application is foregrounded, onStart() and then onResume() will be called (onCreate() could be called as well).

The thing is, what you should do is invalidate PIN in onStop(), and then ask for the PIN in onResume(). This will always make your application ask for the PIN: the first time the application starts and whenever it is backgrounded.

Title: Android Application Lifecycle


问:
Floor of very large floats in python
As Python has no limit over integers but has some limit over its floats.
How do I go about calculating floor of very large floats?

I am trying to calculate floor(A*B), where A is a small irrational number, possibly sqrt(2), e, sqrt(5) etc and B is a very large number in range 10^1000.

答:
You can use decimal module:

```<code>>>> from decimal import Decimal
>>> from math import floor, sqrt
>>>
>>> d1 = Decimal(sqrt(2))
>>> d2 = Decimal(10**1000)
>>>
>>> result = d1 * d2
>>> floor(result)
</code>```

You can also set the precision for the decimal using getcontext().prec in order to get more precise result.

```<code>>>> from decimal import *
>>> getcontext().prec = 100
>>> d1 = Decimal(2).sqrt()
>>> d1
Decimal('1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573')
</code>```

Title: Floor of very large floats in python

Body:
You can use decimal module:

>>> from decimal import Decimal
>>> from math import floor, sqrt
>>>
>>> d1 = Decimal(sqrt(2))
>>> d2 = Decimal(10**1000)
>>>
>>> result = d1 * d2
>>> floor(result)

You can also set the precision for the decimal using getcontext().prec in order to get more precise result.

>>> from decimal import *
>>> getcontext().prec = 100
>>> d1 = Decimal(2).sqrt()
>>> d1
Decimal('1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573')


问:
how to load a table after the data is fetched
I am currently developing a web application and I am fetching a huge amount of data through ajax request triggering it by onload event on body.My table requires jquery and other CSS files for UI once the data is retrieved when I try to append the data to the table the styling and other features(jquery) does not apply to new data and I can't refresh the whole page because it makes an another ajax call. So, is there a way to reload(refresh) that particular table after the data is received or blocking the table from loading until after the data is received.</p>

答:
There are multiple solutions and possibly not all are suitable for every setup. Specifically, if you use an MVVM framework such as Angular, Vue or similar, you should be able to leverage their components to do the job. Since you mention none such framework, I assume you want a vanilla JS solution.

One possibility is to create an empty table and build the missing HTML by hand inside the ajax call's callback:

```<code><table id="foo"></table>

<script>
    const callback = (results) => {
        const table = document.getElementById("foo");
        let innerHTML = "";
        results.forEach((result) => {
            innerHTML += `<tr><td>${result.column1}</td>` +
                         `<td>${result.column2}</td></tr>`;
        });
        table.innerHTML = innerHTML;
    };
</script>
</code>```

You could also consider using HTML templates. In your ajax call's callback, you could process the data to fill the template and then append as many rows as needed to your table:

```<code><table id="foo"></table>
<template id="bar">
    <tr>
        <td></td>
        <td></td>
    </tr>
</template>

<script>
    const callback = (results) => {
        const table = document.getElementById("foo");
        const rowTemplate = document.getElementById("bar");
        results.forEach(result => {
            const cells = rowTemplate.content.querySelectorAll("td");
            cells[0].textContent = result.column1;
            cells[1].textContent = result.column2;

            table.appendChild(document.importNode(rowTemplate.content, true));
        });
    };
</script>
</code>```

An even more interesting way of leveraging the templates would probably be using a templating engine. Here's an example using Nunjucks:

```<code><table id="foo"></table>
<template id="bar">
    {% for result in results %}
    <tr>
        <td>{{result.column1}}</td>
        <td>{{result.column2}}</td>
    </tr>
    {% endfor %}
</template>

<script>
    const callback = (results) => {
        const table = document.getElementById("foo");
        const templateHTML = document.getElementById("bar").innerHTML;
        const rowTemplate = nunjucks.compile(templateHTML);

        table.innerHTML = rowTemplate.render({results});
    };
</script>
</code>```

Finally, if you have control over the data returned by the ajax call, you could also go the old-fashioned way and just return HTML there instead of, say, a JSON array.

As for CSS styling, you need to make sure the CSS rules are written in a way that will be applied to the generated code. They will be used automatically without the need to reload the page.

Should you need to do further operations on the table rows, i.e. add event listeners, it would be best to just set them on the table element and then check the event target. This way you can manipulate the table contents without the need to remove and re-add any event listeners.

Body:
There are multiple solutions and possibly not all are suitable for every setup. Specifically, if you use an MVVM framework such as Angular, Vue or similar, you should be able to leverage their components to do the job. Since you mention none such framework, I assume you want a vanilla JS solution.

One possibility is to create an empty table and build the missing HTML by hand inside the ajax call's callback:

<table id="foo"></table>

<script>
    const callback = (results) => {
        const table = document.getElementById("foo");
        let innerHTML = "";
        results.forEach((result) => {
            innerHTML += `<tr><td>${result.column1}</td>` +
                         `<td>${result.column2}</td></tr>`;
        });
        table.innerHTML = innerHTML;
    };
</script>

You could also consider using HTML templates. In your ajax call's callback, you could process the data to fill the template and then append as many rows as needed to your table:

<table id="foo"></table>
<template id="bar">
    <tr>
        <td></td>
        <td></td>
    </tr>
</template>

<script>
    const callback = (results) => {
        const table = document.getElementById("foo");
        const rowTemplate = document.getElementById("bar");
        results.forEach(result => {
            const cells = rowTemplate.content.querySelectorAll("td");
            cells[0].textContent = result.column1;
            cells[1].textContent = result.column2;

            table.appendChild(document.importNode(rowTemplate.content, true));
        });
    };
</script>

An even more interesting way of leveraging the templates would probably be using a templating engine. Here's an example using Nunjucks:

<table id="foo"></table>
<template id="bar">
    {% for result in results %}
    <tr>
        <td>{{result.column1}}</td>
        <td>{{result.column2}}</td>
    </tr>
    {% endfor %}
</template>

<script>
    const callback = (results) => {
        const table = document.getElementById("foo");
        const templateHTML = document.getElementById("bar").innerHTML;
        const rowTemplate = nunjucks.compile(templateHTML);

        table.innerHTML = rowTemplate.render({results});
    };
</script>

Finally, if you have control over the data returned by the ajax call, you could also go the old-fashioned way and just return HTML there instead of, say, a JSON array.

As for CSS styling, you need to make sure the CSS rules are written in a way that will be applied to the generated code. They will be used automatically without the need to reload the page.

Should you need to do further operations on the table rows, i.e. add event listeners, it would be best to just set them on the table element and then check the event target. This way you can manipulate the table contents without the need to remove and re-add any event listeners.


问:
"ui-sref" does not refresh the "ui-view"(its controller does not rerun) when a link is clicked twice
When a state is clicked at first, the div that owns the "ui-view" attribute is replaced with the "template" of that state. However, when I click the same state again, its controller does not reloaded. How can I make this controller to load again?

For example, suppose I have the following navigation menu:

```<code><nav>
    <a ui-sref="state1">State 1</a>
    <a ui-sref="state2">State 2</a>
</nav>
</code>```

My "ui-view" content is as follows:

```<code><div ui-view></div>
</code>```

My states are described as below. When I click the "State1" on the navigation menu, I expect to observe the text "Ctrl 1 loaded" on the developer console. If it's first time, then I observe that text. However, when I re-click the same link, the controller is not loaded again that is I couldn't see the text "Ctrl 1 loaded" displayed on the console twice.

```<code>myApp.config(function ($stateProvider, $urlRouterProvider){
    $stateProvider.state("state1", {
        url: "#",
        template: "<p>State 1</p>",
        controller: "Ctrl1"
      }).state("state2", {
        url: "#",
        template: "<p>State 2</p>",
        controller: "Ctrl2"
      });
});
</code>```

Why? Do you have any idea?

Here is the JSFiddle of this question.

答:
just use below code</p>

```<code>$stateProvider.
  state('myPage', {
    url: '/',
    cache: false // add this line
</code>```

Body:
When a state is clicked at first, the div that owns the "ui-view" attribute is replaced with the "template" of that state. However, when I click the same state again, its controller does not reloaded. How can I make this controller to load again?

For example, suppose I have the following navigation menu:

    State 1
    State 2

My "ui-view" content is as follows:

My states are described as below. When I click the "State1" on the navigation menu, I expect to observe the text "Ctrl 1 loaded" on the developer console. If it's first time, then I observe that text. However, when I re-click the same link, the controller is not loaded again that is I couldn't see the text "Ctrl 1 loaded" displayed on the console twice.

myApp.config(function ($stateProvider, $urlRouterProvider){
    $stateProvider.state("state1", {
        url: "#",
        template: "
State 1
",
        controller: "Ctrl1"
      }).state("state2", {
        url: "#",
        template: "
State 2
",
        controller: "Ctrl2"
      });
});

Why? Do you have any idea?

Here is the JSFiddle of this question.

Body:
just use below code

$stateProvider.
  state('myPage', {
    url: '/',
    cache: false // add this line


问:
C# Asp.NET Get URL Parameters
How I can get the number 68 of the following link? http://localhost:54547/Home/Details/68

I had a DB whit table "Modules", in each module i had content(that is other table in DB) . So when i click in see Contents, it pass a Module ID (that i click) for associate to Content ( localhost:54547/Home/Details/68). When I click for "Create a New Content", i want that the Module ID pass for the next link.

Thanks for help

I am programing in Asp.NET using C#

答:
I assume it's MVC and then 68 is a part of your RouteConfig.cs and in most cases called id.

So you could fetch it like this:

```<code>public ActionResult Index(int id)
{
   //id is 68
}
</code>```

Title: C# Asp.NET Get URL Parameters

Body:
I assume it's MVC and then 68 is a part of your RouteConfig.cs and in most cases called id.

So you could fetch it like this:

public ActionResult Index(int id)
{
   //id is 68
}


问:
Undefined values in chart.js from json
i am working on showing data in a bar chart with chart.js . my json response is already ready there but chart says its undefined values.

here is jquery with json

```<code>    $(document).ready(function(){
    $.ajax({
        url: "<?php base_url();?>/charts/getsome",
        method: "GET",
        success: function(data) {
            console.log(data);
            var month = [];
            var customers = [];

            for(var i in data) {
                month.push("Customer in" + data[i].apply_month);
                customers.push(data[i].no_customers);
            }
            var chartdata = {
                labels: month,
                datasets : [
                    {
                        label: 'monthly customers',
                        backgroundColor: 'rgba(200, 200, 200, 0.75)',
                        borderColor: 'rgba(200, 200, 200, 0.75)',
                        hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
                        hoverBorderColor: 'rgba(200, 200, 200, 1)',
                        data: customers
                    }
                ]
            };

            // alert(chartdata);

            var ctx = $("#mycanvas");

            var barGraph = new Chart(ctx, {
                type: 'bar',
                data: chartdata
            });
        },
        error: function(data) {
            console.log(data);
        }
    });
});
</code>```

below is a snap for json response in console

And here is also a snap for chart with error

Please guide me where i am wrong. Thanks

答:
You are getting response as a string. you should parse using JSON.parse(data)

```<code>success: function(data) {
            console.log(data);
            data = JSON.parse(data)
            //the rest of your code
         }
</code>```

Title: Undefined values in chart.js from json

Body:
i am working on showing data in a bar chart with chart.js . my json response is already ready there but chart says its undefined values.

here is jquery with json

    $(document).ready(function(){
    $.ajax({
        url: "<?php base_url();?>/charts/getsome",
        method: "GET",
        success: function(data) {
            console.log(data);
            var month = [];
            var customers = [];

            for(var i in data) {
                month.push("Customer in" + data[i].apply_month);
                customers.push(data[i].no_customers);
            }
            var chartdata = {
                labels: month,
                datasets : [
                    {
                        label: 'monthly customers',
                        backgroundColor: 'rgba(200, 200, 200, 0.75)',
                        borderColor: 'rgba(200, 200, 200, 0.75)',
                        hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
                        hoverBorderColor: 'rgba(200, 200, 200, 1)',
                        data: customers
                    }
                ]
            };

            // alert(chartdata);

            var ctx = $("#mycanvas");

            var barGraph = new Chart(ctx, {
                type: 'bar',
                data: chartdata
            });
        },
        error: function(data) {
            console.log(data);
        }
    });
});

below is a snap for json response in console

And here is also a snap for chart with error

Please guide me where i am wrong. Thanks

Body:
You are getting response as a string. you should parse using JSON.parse(data)

success: function(data) {
            console.log(data);
            data = JSON.parse(data)
            //the rest of your code
         }


问:
My increment doesn't work (c)
So, I have this code, at end I have an increment for exit when it reaches 4 (4 times wrong value entered), but it doesn't work:

```<code>int main() {
  int nej;
  printf("1-Triangulo \n");
  printf("2-Division \n");
  printf("3-Menu \n");
  printf("4-Bosque \n");
  printf("0-Salir \n");
  scanf("%d", &nej);
  if (nej == 1) {
    // Ejercicio 1-Triangulo:

    triangulo();
  }

  if (nej == 2) {
    // Ejercicio 2-Division:

    division();
  }

  if (nej == 3) {
    menu();
  }

  if (nej == 4) {
    arboles();
  }

  if (nej == 0) {
    // Salida
    exit(1);
  }

  int nerr = 0;

  while (nej < 0 || nej > 4) {
    nerr++;
    // Contador de error
    if (nerr == 4) {
      exit(1);
    }
  }
}
</code>```

How to fix this?

答:
I believe you have a typo inside the while condition

```<code>while (nej < 0 || nej > 4) {
...
</code>```

should be:

```<code>while (nerr < 0 || nerr > 4) {
..
</code>```

Title: My increment doesn't work (c)

Body:
So, I have this code, at end I have an increment for exit when it reaches 4 (4 times wrong value entered), but it doesn't work:

int main() {
  int nej;
  printf("1-Triangulo \n");
  printf("2-Division \n");
  printf("3-Menu \n");
  printf("4-Bosque \n");
  printf("0-Salir \n");
  scanf("%d", &nej);
  if (nej == 1) {
    // Ejercicio 1-Triangulo:

    triangulo();
  }

  if (nej == 2) {
    // Ejercicio 2-Division:

    division();
  }

  if (nej == 3) {
    menu();
  }

  if (nej == 4) {
    arboles();
  }

  if (nej == 0) {
    // Salida
    exit(1);
  }

  int nerr = 0;

  while (nej < 0 || nej > 4) {
    nerr++;
    // Contador de error
    if (nerr == 4) {
      exit(1);
    }
  }
}

How to fix this?

Body:
I believe you have a typo inside the while condition

while (nej < 0 || nej > 4) {
...

should be:

while (nerr < 0 || nerr > 4) {
..


问:
Hit multiple url without getting response in php
I have multiple urls in my database and want to hit them without getting response using php.

is there any way to do this..

答:
```<code>public function multiUrlUsingCurl($urls)
{
        $sg = curl_multi_init();

        $results = array();
        foreach ($urls as $key => $url) {

            $results[$key] = curl_init();
            curl_setopt_array($results[$key], array(
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_FOLLOWLOCATION => true
            ));

            curl_multi_add_handle($sg, $results[$key]);
        }

        $flag = null;
        do {
            $status = curl_multi_exec($sg, $flag);
        }
        while ($flag);

        foreach ($results as $res) {
            echo curl_multi_getcontent($res);
            curl_multi_remove_handle($sg, $res);
            curl_close($res);
        }

        curl_multi_close($sg);
}
</code>```


问:
Android in service how to know when screen is locked?
I want to handle an Androids application work in the background. I've read that I have to use services for this.
In this application, I need to know when the screen gets locked and when it gets unlocked again. Every time this happens, I have to do some actions.

For activities, I've seen we have onPause and onRestart for this, but I need to know when the screen is turned off and when it is turned on in a service. How can this information be retrieved from inside a service.

答:
Turning screen on/off produces system events. You must listen to those broadcasts and capture them. Add this to your manifest: </p>

```<code><receiver android:name=".ScreenLockBroadcastReceiver">
  <intent-filter>
    <action android:name="android.intent.action.USER_PRESENT" />
    <action android:name="android.intent.action.ACTION_SHUTDOWN" />
 </intent-filter>
</receiver>
</code>```

<p>And then register a broadcast receiver to capture it inside your service. </p>

```<code>public class ScreenLockBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context arg0, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
            // do stuff
        }
    }
}
</code>```

Body:
Turning screen on/off produces system events. You must listen to those broadcasts and capture them. Add this to your manifest:

<receiver android:name=".ScreenLockBroadcastReceiver">
  <intent-filter>
    <action android:name="android.intent.action.USER_PRESENT" />
    <action android:name="android.intent.action.ACTION_SHUTDOWN" />
 </intent-filter>
</receiver>

And then register a broadcast receiver to capture it inside your service.

public class ScreenLockBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context arg0, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
            // do stuff
        }
    }
}


问:
Managing PHP Errors
I have been searching all over the net to try and find a way to catch all errors thrown by PHP (5.3)

I have been reading through the documentation and it looks like set_error_handler is what I need but it doesn't get fatal/parse errors. I'm not sure if this is possible...

Here is my source: https://github.com/tarnfeld/PHP-Error-Handler
Feel free to fork/commit if you know better solutions to all of this.

Thanks in advanced!

Updated!

Using the answers below I finished writing an error handler, it takes care of E_ERROR|E_PARSE|E_WARNING|E_NOTICE and will kill the script when it is fatal! :-)

答:
Quoting the manual:

The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

This means Fatals cannot be caught and handled. What you can do is setup an additional handler to be run when the script exits, e.g. register_shutdown_function.

In that handler, use error_get_last and check if it was a Fatal Error. This will not allow you to continue script execution though. The script will end, but you can do any cleanup or logging (usually fatals will be logged anyway to the error.log) or whatever.

There is a user-supplied example in the comments below set_error_handler

```<code>register_shutdown_function('shutdownFunction');
function shutDownFunction() {
    $error = error_get_last();
    if ($error['type'] == 1) {
        //do your stuff
    }
}
</code>```

But note that this still will only catch certain additional runtime errors.

ContentLicense: CC BY-SA 2.5

Title: Managing PHP Errors

Body:
Quoting the manual:

The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

This means Fatals cannot be caught and handled. What you can do is setup an additional handler to be run when the script exits, e.g. register_shutdown_function.

In that handler, use error_get_last and check if it was a Fatal Error. This will not allow you to continue script execution though. The script will end, but you can do any cleanup or logging (usually fatals will be logged anyway to the error.log) or whatever.

There is a user-supplied example in the comments below set_error_handler

register_shutdown_function('shutdownFunction');
function shutDownFunction() {
    $error = error_get_last();
    if ($error['type'] == 1) {
        //do your stuff
    }
}

But note that this still will only catch certain additional runtime errors.


答:
You can get this from the RouteData:

```<code>var url = Url.RequestContext.RouteData.Values["id"];
</code>```

Title: C# Asp.NET Get URL Parameters

Body:
How I can get the number 68 of the following link? http://localhost:54547/Home/Details/68

I had a DB whit table "Modules", in each module i had content(that is other table in DB) . So when i click in see Contents, it pass a Module ID (that i click) for associate to Content ( localhost:54547/Home/Details/68). When I click for "Create a New Content", i want that the Module ID pass for the next link.

Thanks for help

I am programing in Asp.NET using C#

Body:
You can get this from the RouteData:

var url = Url.RequestContext.RouteData.Values["id"];


问:
This version of Xcode cannot be used with OS X Server
I just download OSX Server (5.1.7) and I have this message which made me crazy!
I already tried to:

reboot

re-install (fully) xcode and server

accept Licence after re-install

execute : sudo /Applications/Xcode.app/Contents/MacOS/Xcode (same on Server).

reboot, reboot and re-reboot

still nothing works.

答:
Having experienced this on updating to Xcode 8.3.3 as of June 6 2017, the solution was to select "choose Xcode and reset", then reboot.

This approach did not seem to affect the configuration or Bots.

After rebooting, open Server and follow the dialogue to login as "Xcode Server".

Switching users back to the Server admin, everything should now be green. Viewing the Server in Xcode's Report Navigator, all Bots should be visible.


问:
PySpark - How to do split on multiple dictionary values
After some processing on raw data I got my result as bellow , its like a Key with multiple values and the values are dictionary values - I want to make as Key + each dictionary values

```<code>[('HOMICIDE', {'2017': 1}),
('DECEPTIVE PRACTICE', {'2015': 2, '2017': 2, '2016': 8}),
('ROBBERY', {'2016': 2}),
('OTHER OFFENSE', {'2016': 3}),
('MOTOR VEHICLE THEFT', {'2017': 2, '2016': 2})]
</code>```

How can I make the above to

```<code>('HOMICIDE', '2017': 1),
('DECEPTIVE PRACTICE', '2015': 2 ),
('DECEPTIVE PRACTICE', '2017': 2,),
('DECEPTIVE PRACTICE', '2016': 8),
('ROBBERY', '2016': 2),
('OTHER OFFENSE', '2016': 3),
('MOTOR VEHICLE THEFT', '2017': 2)
('MOTOR VEHICLE THEFT', '2016': 2)]
</code>```

Whether I need to move the dictionary to a List and from there I need to process ?

答:
Just flatMapValues:

```<code>In [1]: rdd = sc.parallelize([('HOMICIDE', {'2017': 1}),
   ...: ('DECEPTIVE PRACTICE', {'2015': 2, '2017': 2, '2016': 8}),
   ...: ('ROBBERY', {'2016': 2}),
   ...: ('OTHER OFFENSE', {'2016': 3}),
   ...: ('MOTOR VEHICLE THEFT', {'2017': 2, '2016': 2})])

In [4]: rdd.flatMapValues(dict.items)
Out[4]: PythonRDD[5] at RDD at PythonRDD.scala:48

In [5]: rdd.flatMapValues(dict.items).collect()
Out[5]:
[('HOMICIDE', ('2017', 1)),
 ('DECEPTIVE PRACTICE', ('2015', 2)),
 ('DECEPTIVE PRACTICE', ('2017', 2)),
 ('DECEPTIVE PRACTICE', ('2016', 8)),
 ('ROBBERY', ('2016', 2)),
 ('OTHER OFFENSE', ('2016', 3)),
 ('MOTOR VEHICLE THEFT', ('2017', 2)),
 ('MOTOR VEHICLE THEFT', ('2016', 2))]
</code>```

or in a long way

```<code>In [5]: rdd.flatMap(lambda x: [(x[0], k, v) for k, v in x[1].items()]).collect()
Out[5]:
[('HOMICIDE', '2017', 1),
 ('DECEPTIVE PRACTICE', '2015', 2),
 ('DECEPTIVE PRACTICE', '2017', 2),
 ('DECEPTIVE PRACTICE', '2016', 8),
 ('ROBBERY', '2016', 2),
 ('OTHER OFFENSE', '2016', 3),
 ('MOTOR VEHICLE THEFT', '2017', 2),
 ('MOTOR VEHICLE THEFT', '2016', 2)]
</code>```

Body:
After some processing on raw data I got my result as bellow , its like a Key with multiple values and the values are dictionary values - I want to make as Key + each dictionary values

[('HOMICIDE', {'2017': 1}),
('DECEPTIVE PRACTICE', {'2015': 2, '2017': 2, '2016': 8}),
('ROBBERY', {'2016': 2}),
('OTHER OFFENSE', {'2016': 3}),
('MOTOR VEHICLE THEFT', {'2017': 2, '2016': 2})]

How can I make the above to

('HOMICIDE', '2017': 1),
('DECEPTIVE PRACTICE', '2015': 2 ),
('DECEPTIVE PRACTICE', '2017': 2,),
('DECEPTIVE PRACTICE', '2016': 8),
('ROBBERY', '2016': 2),
('OTHER OFFENSE', '2016': 3),
('MOTOR VEHICLE THEFT', '2017': 2)
('MOTOR VEHICLE THEFT', '2016': 2)]

Whether I need to move the dictionary to a List and from there I need to process ?

Body:
Just flatMapValues:

In [1]: rdd = sc.parallelize([('HOMICIDE', {'2017': 1}),
   ...: ('DECEPTIVE PRACTICE', {'2015': 2, '2017': 2, '2016': 8}),
   ...: ('ROBBERY', {'2016': 2}),
   ...: ('OTHER OFFENSE', {'2016': 3}),
   ...: ('MOTOR VEHICLE THEFT', {'2017': 2, '2016': 2})])

In [4]: rdd.flatMapValues(dict.items)
Out[4]: PythonRDD[5] at RDD at PythonRDD.scala:48

In [5]: rdd.flatMapValues(dict.items).collect()
Out[5]:
[('HOMICIDE', ('2017', 1)),
 ('DECEPTIVE PRACTICE', ('2015', 2)),
 ('DECEPTIVE PRACTICE', ('2017', 2)),
 ('DECEPTIVE PRACTICE', ('2016', 8)),
 ('ROBBERY', ('2016', 2)),
 ('OTHER OFFENSE', ('2016', 3)),
 ('MOTOR VEHICLE THEFT', ('2017', 2)),
 ('MOTOR VEHICLE THEFT', ('2016', 2))]

or in a long way

In [5]: rdd.flatMap(lambda x: [(x[0], k, v) for k, v in x[1].items()]).collect()
Out[5]:
[('HOMICIDE', '2017', 1),
 ('DECEPTIVE PRACTICE', '2015', 2),
 ('DECEPTIVE PRACTICE', '2017', 2),
 ('DECEPTIVE PRACTICE', '2016', 8),
 ('ROBBERY', '2016', 2),
 ('OTHER OFFENSE', '2016', 3),
 ('MOTOR VEHICLE THEFT', '2017', 2),
 ('MOTOR VEHICLE THEFT', '2016', 2)]


问:
How to get Document-Coordinates from a Mouse Click in an OpenOffice BASIC Macro

Background:

I want to paste (like [CTRL+V]) anything (preferably image, shape) at the position I click or hover with the mouse (when using a key to activate). I don't know how to get the position on the document (X, Y) I clicked.

(Apache OpenOffice, SDraw-Document, OpenOffice BASIC Macro)

What I need:

Hint/Tip how to get the location from the mouse-click / mouse-position on the document. (Which class, listener, component I need)

Notes:
Something like a com.sun.star.awt.XMouseClickHandler would be perfect, if the given oEvent gave me the X+Y of the document, where I clicked.
(Maybe you know how to "activate" PopupTrigger? (com.sun.star.awt.MouseEvent))

My code so far:

I tried using the mentioned XMouseClickHandler to get X+Y.
Sadly, X+Y refer to the relative position of the window and not the actual position a shape or text would have on the document.

Execution: My Sub Main is executed via a Menu-Button at the top.
 Then clicking anywhere will output (via MsgBox) the coordinates of that click.

Only Problem: Coordinates are relative to the corner of the window, not the corner of the document.

```<code>Global gListener As Object

Sub Main
  gListener = CreateUnoListener("Listener_","com.sun.star.awt.XMouseClickHandler")
  ThisComponent.CurrentController.addMouseClickHandler(gListener)
End Sub

Sub Listener_mousePressed(oMouseEvent) As Boolean
   ThisComponent.CurrentController.removeMouseClickHandler(gListener)

   Msg = "Position: "
   Msg = Msg & oMouseEvent.X & "/" & oMouseEvent.Y
   MsgBox(Msg)

   REM :: I want something like:
   REM :: Msg = "Position: " & oMouseEvent.PositionOnDocument.X
   REM :: Msg = Msg & "/" & oMouseEvent.PositionOnDocument.Y
   REM :: MsgBox(Msg)
End Sub
</code>```

My references:

All my information come from the official references/docs so far, since all my searches did not find anything helpful.

Class-List: http://api.libreoffice.org/docs/idl/ref/annotated.html Here you can see docs for the used classes (com.sun.star.awt.XMouseClickHandler, com.sun.star.awt.MouseEvent)

Infos about listener: https://help.libreoffice.org/3.6/Basic/CreateUnoListener_Function_Runtime

Thanks in advance.

答:
It turns out that the DrawingDocumentDrawView service has a member called VisibleArea that helps.  Subtract (actually add because they have the opposite sign) those coordinates from the mouse position to get the location relative to the document.

Here is an example that creates a rectangle at the location of the mouse click.

Sub Listener_mousePressed(oMouseEvent) As Boolean
   ThisComponent.CurrentController.removeMouseClickHandler(gListener)

   xpos = (oMouseEvent.X + ThisComponent.VisibleArea.X / 25.4) / 100
   ypos = (oMouseEvent.Y + ThisComponent.VisibleArea.Y / 25.4) / 100
   Msg = "Position: " & xpos & "/" & ypos
   MsgBox(Msg)
   InsertProcessShape(xpos, ypos)
End Sub

Sub InsertProcessShape(xpos, ypos)
   Dim oDoc As Object
   Dim oDrawPage As Object
   Dim oShape As Object
   Dim shapeGeometry(0) as new com.sun.star.beans.PropertyValue
   Dim oSize As new com.sun.star.awt.Size

   oSize.width = 3000
   oSize.height = 1000

   oDoc = ThisComponent
   odrawPage = oDoc.DrawPages(0)
   oShape = oDoc.createInstance("com.sun.star.drawing.CustomShape")
   shapeGeometry(0).Name = "Type"
   shapeGeometry(0).Value = "flowchart-process"
   oDrawPage.add(oShape)
   oShape.CustomShapeGeometry = shapeGeometry
   oShape.Size = oSize

   ' Position the object
   IN_TO_CM = 2540  ' converts 1/1000 cm to inches
   Dim aPosition As New com.sun.star.awt.Point
   aPosition.X = xpos * IN_TO_CM
   aPosition.Y = ypos * IN_TO_CM
   oShape.setposition(aPosition)
End Sub
```

To figure this out, I used xray.  The formula may need to be fine-tuned.  But the left-top corner of the rectangles seemed to go roughly where the mouse was clicked when I tested it, as intended.

InsertProcessShape is from https://forum.openoffice.org/en/forum/viewtopic.php?f=45&t=46682, plus some code from Listing 5.84 of Andrew Pitonyak's Macro Document.

Body:
Background:

I want to paste (like [CTRL+V]) anything (preferably image, shape) at the position I click or hover with the mouse (when using a key to activate). I don't know how to get the position on the document (X, Y) I clicked.

(Apache OpenOffice, SDraw-Document, OpenOffice BASIC Macro)

What I need:

Hint/Tip how to get the location from the mouse-click / mouse-position on the document. (Which class, listener, component I need)

Notes:
Something like a com.sun.star.awt.XMouseClickHandler would be perfect, if the given oEvent gave me the X+Y of the document, where I clicked.
(Maybe you know how to "activate" PopupTrigger? (com.sun.star.awt.MouseEvent))

My code so far:

I tried using the mentioned XMouseClickHandler to get X+Y.
Sadly, X+Y refer to the relative position of the window and not the actual position a shape or text would have on the document.

Execution: My Sub Main is executed via a Menu-Button at the top.
 Then clicking anywhere will output (via MsgBox) the coordinates of that click.

Only Problem: Coordinates are relative to the corner of the window, not the corner of the document.

Global gListener As Object

Sub Main
  gListener = CreateUnoListener("Listener_","com.sun.star.awt.XMouseClickHandler")
  ThisComponent.CurrentController.addMouseClickHandler(gListener)
End Sub

Sub Listener_mousePressed(oMouseEvent) As Boolean
   ThisComponent.CurrentController.removeMouseClickHandler(gListener)

   Msg = "Position: "
   Msg = Msg & oMouseEvent.X & "/" & oMouseEvent.Y
   MsgBox(Msg)

   REM :: I want something like:
   REM :: Msg = "Position: " & oMouseEvent.PositionOnDocument.X
   REM :: Msg = Msg & "/" & oMouseEvent.PositionOnDocument.Y
   REM :: MsgBox(Msg)
End Sub

My references:

All my information come from the official references/docs so far, since all my searches did not find anything helpful.

Class-List: http://api.libreoffice.org/docs/idl/ref/annotated.html Here you can see docs for the used classes (com.sun.star.awt.XMouseClickHandler, com.sun.star.awt.MouseEvent)

Infos about listener: https://help.libreoffice.org/3.6/Basic/CreateUnoListener_Function_Runtime

Thanks in advance.

Body:
It turns out that the DrawingDocumentDrawView service has a member called VisibleArea that helps.  Subtract (actually add because they have the opposite sign) those coordinates from the mouse position to get the location relative to the document.

Here is an example that creates a rectangle at the location of the mouse click.

Sub Listener_mousePressed(oMouseEvent) As Boolean
   ThisComponent.CurrentController.removeMouseClickHandler(gListener)

   xpos = (oMouseEvent.X + ThisComponent.VisibleArea.X / 25.4) / 100
   ypos = (oMouseEvent.Y + ThisComponent.VisibleArea.Y / 25.4) / 100
   Msg = "Position: " & xpos & "/" & ypos
   MsgBox(Msg)
   InsertProcessShape(xpos, ypos)
End Sub

Sub InsertProcessShape(xpos, ypos)
   Dim oDoc As Object
   Dim oDrawPage As Object
   Dim oShape As Object
   Dim shapeGeometry(0) as new com.sun.star.beans.PropertyValue
   Dim oSize As new com.sun.star.awt.Size

   oSize.width = 3000
   oSize.height = 1000

   oDoc = ThisComponent
   odrawPage = oDoc.DrawPages(0)
   oShape = oDoc.createInstance("com.sun.star.drawing.CustomShape")
   shapeGeometry(0).Name = "Type"
   shapeGeometry(0).Value = "flowchart-process"
   oDrawPage.add(oShape)
   oShape.CustomShapeGeometry = shapeGeometry
   oShape.Size = oSize

   ' Position the object
   IN_TO_CM = 2540  ' converts 1/1000 cm to inches
   Dim aPosition As New com.sun.star.awt.Point
   aPosition.X = xpos * IN_TO_CM
   aPosition.Y = ypos * IN_TO_CM
   oShape.setposition(aPosition)
End Sub

To figure this out, I used xray.  The formula may need to be fine-tuned.  But the left-top corner of the rectangles seemed to go roughly where the mouse was clicked when I tested it, as intended.

InsertProcessShape is from https://forum.openoffice.org/en/forum/viewtopic.php?f=45&t=46682, plus some code from Listing 5.84 of Andrew Pitonyak's Macro Document.


问:
Group and count values in an array
I have an array with objects, like the following.

```<code>b = {
  "issues": [{
    "fields": {
      "status": {
        "id": "200",
        "name": "Backlog"
      }
    }
  }, {
    "fields": {
      "status": {
        "id": "202",
        "name": "close"
      }
    }
  }, {
    "fields": {
      "status": {
        "id": "201",
        "name": "close"
      }
    }
  }]
};
</code>```

I want to count how many issues have status close, and how many have backlog. I'd like to save the count in a new array as follows.

```<code>a = [
  {Name: 'Backlog', count: 1},
  {Name: 'close', count: 2}
];
</code>```

I have tried the following.

```<code>b.issues.forEach(function(i) {
  var statusName = i.fields.status.name;

  if (statusName in a.Name) {
    a.count = +1;
  } else {
    a.push({
      Name: statusName,
      count: 1
    });
  }
});
</code>```

That however doesn't seem to be working. How should I implement this?

答:
You can write like this. It is dynamic. </p>

```<code>var a = {};
for(var key in b["issues"]){
    if(!a.hasOwnProperty(b["issues"][key].fields.status.name)){
     a[b["issues"][key].fields.status.name] = 1;
    }else{
     a[b["issues"][key].fields.status.name] = a[b["issues"][key].fields.status.name]+1;
    }
}
var c = [];
for(var key1 in a){
   c.push({
   name  : key1,
   count : a[key1]
   });
}
</code>```

Title: Group and count values in an array

Body:
I have an array with objects, like the following.

b = {
  "issues": [{
    "fields": {
      "status": {
        "id": "200",
        "name": "Backlog"
      }
    }
  }, {
    "fields": {
      "status": {
        "id": "202",
        "name": "close"
      }
    }
  }, {
    "fields": {
      "status": {
        "id": "201",
        "name": "close"
      }
    }
  }]
};

I want to count how many issues have status close, and how many have backlog. I'd like to save the count in a new array as follows.

a = [
  {Name: 'Backlog', count: 1},
  {Name: 'close', count: 2}
];

I have tried the following.

b.issues.forEach(function(i) {
  var statusName = i.fields.status.name;

  if (statusName in a.Name) {
    a.count = +1;
  } else {
    a.push({
      Name: statusName,
      count: 1
    });
  }
});

That however doesn't seem to be working. How should I implement this?

Body:
You can write like this. It is dynamic.

var a = {};
for(var key in b["issues"]){
    if(!a.hasOwnProperty(b["issues"][key].fields.status.name)){
     a[b["issues"][key].fields.status.name] = 1;
    }else{
     a[b["issues"][key].fields.status.name] = a[b["issues"][key].fields.status.name]+1;
    }
}
var c = [];
for(var key1 in a){
   c.push({
   name  : key1,
   count : a[key1]
   });
}


答:
64 bit floats don't go above ~10^308. So your 10^1000 is definitely not going to fit, regardless of multiplication by any constant. (No 64-bit float can be small enough to make 10^1000 less than 10^308.) So your procedure isn't going to work for floats.

Consider using the decimal module. E.g.:

```<code>import decimal
import math
a = decimal.Decimal("10") ** 10000
b = decimal.Decimal("0.123")
math.floor(a*b)
</code>```

Title: Floor of very large floats in python

Body:
As Python has no limit over integers but has some limit over its floats.
How do I go about calculating floor of very large floats?

I am trying to calculate floor(A*B), where A is a small irrational number, possibly sqrt(2), e, sqrt(5) etc and B is a very large number in range 10^1000.

Body:
64 bit floats don't go above ~10^308. So your 10^1000 is definitely not going to fit, regardless of multiplication by any constant. (No 64-bit float can be small enough to make 10^1000 less than 10^308.) So your procedure isn't going to work for floats.

Consider using the decimal module. E.g.:

import decimal
import math
a = decimal.Decimal("10") ** 10000
b = decimal.Decimal("0.123")
math.floor(a*b)


答:
If you initialize the int nerr = 0;  every time when you read,the flow will never reach the exit condition

```<code> int main()
 {
int nej;

int nerr = 0; // Keep the counter outside the loop

while (true){//Start a infinite loop here

printf("1-Triangulo \n");
printf("2-Division \n");
printf("3-Menu \n");
printf("4-Bosque \n");
printf("0-Salir \n");
scanf("%d", &nej);

if (nej == 1) {
  // Ejercicio 1-Triangulo:

  triangulo();
}

if (nej == 2) {
  // Ejercicio 2-Division:

  division();
}

if (nej == 3) {
  menu();
}

if (nej == 4) {
  arboles();
}

if (nej == 0) {
  // Salida
  exit(1);
}

while (nej < 0 || nej > 4) {
  nerr++;
  // Contador de error
  if (nerr == 4) {
    exit(1);
  }
}
}
</code>```

Title: My increment doesn't work (c)

Body:
If you initialize the int nerr = 0;  every time when you read,the flow will never reach the exit condition

 int main()
 {
int nej;

int nerr = 0; // Keep the counter outside the loop

while (true){//Start a infinite loop here

printf("1-Triangulo \n");
printf("2-Division \n");
printf("3-Menu \n");
printf("4-Bosque \n");
printf("0-Salir \n");
scanf("%d", &nej);

if (nej == 1) {
  // Ejercicio 1-Triangulo:

  triangulo();
}

if (nej == 2) {
  // Ejercicio 2-Division:

  division();
}

if (nej == 3) {
  menu();
}

if (nej == 4) {
  arboles();
}

if (nej == 0) {
  // Salida
  exit(1);
}

while (nej < 0 || nej > 4) {
  nerr++;
  // Contador de error
  if (nerr == 4) {
    exit(1);
  }
}
}


问:
How to loop indices of .formula/.formulaR1C1
I am stuck with a problem i cannot get my head around currently.

I have a checklist that has to update automatically when adding lines to my excel worksheet so that the checklist is applied to all rows.
I tried to use a "for loop" to modify the formula but excel returns Error 1004, when starting the string with "=".

No error but no functionality as well:

```<code> ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").FormulaLocal = "Wenn(Oder(AB" & firstRow & "=""x"""
</code>```

Returns error 1004:

```<code> ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").FormulaLocal = "=Wenn(Oder(AB" & firstRow & "=""x"""
</code>```

My first solution
Loop FormulaR1C1, or Formula and use nothing but english Function names eg. sum() instead of Summe() and follow english syntax , instead of ;.

Problem
When testing the syntax without a loop and actual indices it works like a charm. As soon as I try to loop it, Excel does not recognize R[i]C as cell anymore but just returns plain text.

no issues:

```<code>ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").Formula = "IF(OR( R[1]C = ""x"""
</code>```

issues:

```<code>ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").Formula = "IF(OR( R[i]C = ""x"""
</code>```

Splitting it like this did not solve my problem either
    ..R[" & i & "]C =..

Any tips?

// For i=  ... to .. next i
// Excel 2007

答:
Try this:</p>

```<code>   With ActiveWorkbook.Sheets("Kalkulation Änderungen")
      'find last row of column AB
      LastRow = .Cells(.Rows.Count, "AB").End(xlUp).Row
      'apply the formula from AB9 to its last non-blank row
     .Range("AB9:AB" & LastRow).Formula = "IF(OR( R[1]C = ""x"""
   End With
</code>```

Body:
I am stuck with a problem i cannot get my head around currently.

I have a checklist that has to update automatically when adding lines to my excel worksheet so that the checklist is applied to all rows.
I tried to use a "for loop" to modify the formula but excel returns Error 1004, when starting the string with "=".

No error but no functionality as well:

 ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").FormulaLocal = "Wenn(Oder(AB" & firstRow & "=""x"""

Returns error 1004:

 ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").FormulaLocal = "=Wenn(Oder(AB" & firstRow & "=""x"""

My first solution
Loop FormulaR1C1, or Formula and use nothing but english Function names eg. sum() instead of Summe() and follow english syntax , instead of ;.

Problem
When testing the syntax without a loop and actual indices it works like a charm. As soon as I try to loop it, Excel does not recognize R[i]C as cell anymore but just returns plain text.

no issues:

ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").Formula = "IF(OR( R[1]C = ""x"""

issues:

ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").Formula = "IF(OR( R[i]C = ""x"""

Splitting it like this did not solve my problem either
    ..R[" & i & "]C =..

Any tips?

// For i=  ... to .. next i
// Excel 2007

Body:
Try this:

   With ActiveWorkbook.Sheets("Kalkulation Änderungen")
      'find last row of column AB
      LastRow = .Cells(.Rows.Count, "AB").End(xlUp).Row
      'apply the formula from AB9 to its last non-blank row
     .Range("AB9:AB" & LastRow).Formula = "IF(OR( R[1]C = ""x"""
   End With


问:
Genetic algorithms: How to do crossover in "subset" problems?
I have a problem which I am trying to solve with genetic algorithms. The problem is selecting some subset (say 4) of 100 integers (these integers are just ids that represent something else). Order does not matter, the solution to the problem is a SET of integers not an ordered list. I have a good fitness function but am having trouble with the crossover function.

I want to be able to mate the following two chromosomes:

[1 2 3 4] and
[3 4 5 6] into something useful. Clearly I cannot use the typical crossover function because I could end up with duplicates in my children which would represent invalid solutions. What is the best crossover method in this case.

答: In order to combine sets A and B, you could choose the resulting set S probabilistically so that the probability that x is in S is (number of sets out of A, B, which contain x) / 2.  This will be guaranteed to contain the intersection and be contained in the union, and will have expected cardinality 4.</p>


问:
mySQL 'where name NOT IN' not working?
I have this statement:

```<code>SELECT id, name
FROM players
WHERE this = 1
  AND name NOT IN (SELECT name
                   FROM players_online
                   WHERE this = 'that')
ORDER BY RAND()
LIMIT 3, 6
</code>```

All columns are correctly named. No SQL errors occur, it just returns no results.

From what I've read in documentation it should work, but doesn't.

Any idea?

答:
Don't use NOT IN with subqueries.  It has the wrong semantics if any value in the subquery is NULL.  In that case, the NOT IN never evaluates to TRUE, so no rows are returned at all.

Instead, use NOT EXISTS:

```<code>SELECT p.id, p.name
FROM players p
WHERE p.this = 1 AND
      NOT EXISTS (SELECT 1
                  FROM players_online po
                  WHERE po.name = p.name AND po.this = 'that'
                 )
ORDER BY RAND()
LIMIT 3, 6;
</code>```

Title: mySQL 'where name NOT IN' not working?

Body:
I have this statement:

SELECT id, name
FROM players
WHERE this = 1
  AND name NOT IN (SELECT name
                   FROM players_online
                   WHERE this = 'that')
ORDER BY RAND()
LIMIT 3, 6

All columns are correctly named. No SQL errors occur, it just returns no results.

From what I've read in documentation it should work, but doesn't.

Any idea?

Body:
Don't use NOT IN with subqueries.  It has the wrong semantics if any value in the subquery is NULL.  In that case, the NOT IN never evaluates to TRUE, so no rows are returned at all.

Instead, use NOT EXISTS:

SELECT p.id, p.name
FROM players p
WHERE p.this = 1 AND
      NOT EXISTS (SELECT 1
                  FROM players_online po
                  WHERE po.name = p.name AND po.this = 'that'
                 )
ORDER BY RAND()
LIMIT 3, 6;


问:
UILabel with text of two different colors
I want to display a string like this in a UILabel:

There are 5 results.

Where the number 5 is red in color and the rest of the string is black.

How can I do this in code?

答:
By using below code you can set multiple colors based on word.</p>

```<code>NSMutableArray * array = [[NSMutableArray alloc] initWithObjects:@"1 ball",@"2 ball",@"3 ball",@"4 ball", nil];
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] init];
for (NSString * str in array)
 {
    NSMutableAttributedString * textstr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ ,",str] attributes:@{NSForegroundColorAttributeName :[self getRandomColor]}];
     [attStr appendAttributedString:textstr];
  }
UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(10, 300, 300, 30)];
lab.attributedText = attStr;
[self.view addSubview:lab];

-(UIColor *) getRandomColor
{
   CGFloat redcolor = arc4random() % 255 / 255.0;
   CGFloat greencolor = arc4random() % 255 / 255.0;
   CGFloat bluencolor = arc4random() % 255 / 255.0;
   return  [UIColor colorWithRed:redcolor green:greencolor blue:bluencolor alpha:1.0];
}
</code>```

Body:
By using below code you can set multiple colors based on word.

NSMutableArray * array = [[NSMutableArray alloc] initWithObjects:@"1 ball",@"2 ball",@"3 ball",@"4 ball", nil];
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] init];
for (NSString * str in array)
 {
    NSMutableAttributedString * textstr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ ,",str] attributes:@{NSForegroundColorAttributeName :[self getRandomColor]}];
     [attStr appendAttributedString:textstr];
  }
UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(10, 300, 300, 30)];
lab.attributedText = attStr;
[self.view addSubview:lab];

-(UIColor *) getRandomColor
{
   CGFloat redcolor = arc4random() % 255 / 255.0;
   CGFloat greencolor = arc4random() % 255 / 255.0;
   CGFloat bluencolor = arc4random() % 255 / 255.0;
   return  [UIColor colorWithRed:redcolor green:greencolor blue:bluencolor alpha:1.0];
}


问:
iphone : How to capitalize the first character of my textfield?
In my iPhone app, I want to capitalize the first character in my UITextField's text.

How can it be done?

答:
Instead of tanking it separate and capitalizing, try this.
Simple 1 line code.    </p>

```<code>NSString *text = [textField text];
NSString *capText = [text capitalizedString]; // capitalizes only first alphabet.
</code>```

Body:
Instead of tanking it separate and capitalizing, try this.
Simple 1 line code.

NSString *text = [textField text];
NSString *capText = [text capitalizedString]; // capitalizes only first alphabet.


问:
search results only from post title, category and tags
If it is default WordPress search or custom search form, If only matched the search text in a post title, category and tags.</p>

答:
The search form should like this.

```<code><form class="search" action="<?php echo home_url( '/' ); ?>">
  <input type="search" name="s" placeholder="Search…">
  <input type="submit" value="Search">
  <input type="hidden" name="post_type" value="kb_article">
</form>
</code>```

We’ll name our custom search results templates using the WordPress filename conventions of {template}-{post_type}.php. In our case, that would result in search-kb_article.php. We could just check to see if that post_type=kb_article is set in the URL string and use get_template_part to load it if it is, but let’s go a step further. We’ll check to see if post_type is set in the URL string, and if it is, also check to see if custom search template exists for that post type using the {template}-{post_type}.php naming pattern. If it does, we’ll load it. If not, we’ll continue with the default search template.

```<code><?php
// store the post type from the URL string
$post_type = $_GET['post_type'];
// check to see if there was a post type in the
// URL string and if a results template for that
// post type actually exists
if ( isset( $post_type ) && locate_template( 'search-' . $post_type . '.php' ) ) {
  // if so, load that template
  get_template_part( 'search', $post_type );

  // and then exit out
  exit;
}
?>
</code>```

Body:
The search form should like this.

<form class="search" action="<?php echo home_url( '/' ); ?>">
  <input type="search" name="s" placeholder="Search&hellip;">
  <input type="submit" value="Search">
  <input type="hidden" name="post_type" value="kb_article">
</form>

We’ll name our custom search results templates using the WordPress filename conventions of {template}-{post_type}.php. In our case, that would result in search-kb_article.php. We could just check to see if that post_type=kb_article is set in the URL string and use get_template_part to load it if it is, but let’s go a step further. We’ll check to see if post_type is set in the URL string, and if it is, also check to see if custom search template exists for that post type using the {template}-{post_type}.php naming pattern. If it does, we’ll load it. If not, we’ll continue with the default search template.

<?php
// store the post type from the URL string
$post_type = $_GET['post_type'];
// check to see if there was a post type in the
// URL string and if a results template for that
// post type actually exists
if ( isset( $post_type ) && locate_template( 'search-' . $post_type . '.php' ) ) {
  // if so, load that template
  get_template_part( 'search', $post_type );

  // and then exit out
  exit;
}
?>


问:
ListView row highlight when data changes
I have a ListView in which data is streaming (changing). I want to just highlight the row for a fraction of seconds when the data is changing and then comes back to old state.

any solution?

答:
I don't think there is a way to automagically do it.

The easiest way out is setting a boolean variable inside the model class you use in your Adapter.

So you will end up doing something like this when something changed:

In your Activity:

```<code>/* setProgress will set the boolean variable */
model.setProgress(40);

/* This will make the ListView update */
adapter.notifyDataSetChanged();
</code>```

In your Adapter in the getView() method:

```<code>ModelClass model = getItem(position);
if ( model.isUpdated() ) {
  viewForTheRow.startAnimation(yourHighlightAnimation);
}
</code>```

Body:
I don't think there is a way to automagically do it.

The easiest way out is setting a boolean variable inside the model class you use in your Adapter.

So you will end up doing something like this when something changed:

In your Activity:

/* setProgress will set the boolean variable */
model.setProgress(40);

/* This will make the ListView update */
adapter.notifyDataSetChanged();

In your Adapter in the getView() method:

ModelClass model = getItem(position);
if ( model.isUpdated() ) {
  viewForTheRow.startAnimation(yourHighlightAnimation);
}


问:
Connecting to Postgres Database via Python
I am trying to connect to my database via Python 2.7 with this code:

```<code>import csv
import psycopg2

try:
    conn = psycopg2.connect("dbname='student', user='postgres',password='password', host='localhost'")
    cursor = conn_cursor()
    reader = csv.reader(open('last_file.csv', 'rb'))
    print "connected"
except:
    print "not Connected"
</code>```

It did work last week and we don't think we've changed anything, but now it won't connect.
We've tried using it with the database open and closed, nothing worked.
The database does exist in Postgres.

答:
Exception part add like this to see what is error</p>

```<code>except Exception as ex:

    print "not Connected"

    print "Error: "+ str(ex)
</code>```

Body:
I am trying to connect to my database via Python 2.7 with this code:

import csv
import psycopg2

try:
    conn = psycopg2.connect("dbname='student', user='postgres',password='password', host='localhost'")
    cursor = conn_cursor()
    reader = csv.reader(open('last_file.csv', 'rb'))
    print "connected"
except:
    print "not Connected"

It did work last week and we don't think we've changed anything, but now it won't connect.
We've tried using it with the database open and closed, nothing worked.
The database does exist in Postgres.

Body:
Exception part add like this to see what is error

except Exception as ex:

    print "not Connected"

    print "Error: "+ str(ex)


问:
Ruby redirect output to file
How can I redirect the output of this puts method to a file?

```<code>File.open('links.txt').readlines.each do |li|
  puts li if (li['PersonNight'])
end
</code>```

I tried some solutions, but none of them works.

答:
You can call IO#puts on the IO object for the file you want to write to:

```<code>File.open('outputfile.txt', 'at') do |out|
  File.open('links.txt').readlines.each do |li|
    out.puts li if (li['PersonNight'])
  end
end
</code>```

Alternatively, you can redirect the output of Kernel#puts by assigning an output file to $stdout:

```<code>old_stdout, $stdout = $stdout, File.open('outputfile.txt', 'at')

File.open('links.txt').readlines.each do |li|
  puts li if (li['PersonNight'])
end

f, $stdout = $stdout, old_stdout
f.close
</code>```

But this is a really bad idea. You redirect puts for all code in the system.

Title: Ruby redirect output to file

Body:
How can I redirect the output of this puts method to a file?

File.open('links.txt').readlines.each do |li|
  puts li if (li['PersonNight'])
end

I tried some solutions, but none of them works.

Body:
You can call IO#puts on the IO object for the file you want to write to:

File.open('outputfile.txt', 'at') do |out|
  File.open('links.txt').readlines.each do |li|
    out.puts li if (li['PersonNight'])
  end
end

Alternatively, you can redirect the output of Kernel#puts by assigning an output file to $stdout:

old_stdout, $stdout = $stdout, File.open('outputfile.txt', 'at')

File.open('links.txt').readlines.each do |li|
  puts li if (li['PersonNight'])
end

f, $stdout = $stdout, old_stdout
f.close

But this is a really bad idea. You redirect puts for all code in the system.


问:
File separators of Path name of ZipEntry?
ZIP entries store the full path name of the entry because (I'm sure of the next part) the ZIP archive is not organized as directories. The metadata contains the info about how files are supposed to be stored (inside directories).

If I create a ZIP file in Windows, when I unzip the data in another OS, e.g. Mac OS X, the file structure remains as it used to be in Windows. Is this because the unzipper is designed to handle this, or isit  because the file separators inside the ZIP are standard?

I'm asking this because I'm trying to find an entry inside a ZIP file using the name of the zipped file. But which file separator should I use to make it work in systems other than Windows?

I'm using Java, and the method: .getName() of the ZipEntry gives me the path using the Windows file separator \. Would it be enough if I use the java File.separator separator to make it work on another OS? Or will I have to try to find my file with each possible separator?

Honorary Correct Answer Mention

The answer given by @Eren Yilmaz is correct describing the functionality of many tools (or even the one you can code yourself). But given that the .zip standard clearly documents how it must be, the correct answer had to be updated

答:
The .zip file specification states:

4.4.17.1 The name of the file, with optional relative path.
         The path stored MUST not contain a drive or
         device letter, or a leading slash.  All slashes
         MUST be forward slashes '/' as opposed to
         backwards slashes '\' for compatibility with Amiga
         and UNIX file systems etc.  If input came from standard
         input, there is no file name field.


问:
View Controller shows black screen instead of fetching users from Firebase database Swift iOS
When I go to the HomeViewController the screen is to totally black. I actually want to fetch the users to put them into TableViewCells. I am using Firebase as a database and Swift as a language. Help me to accomplish this.

```<code>import UIKit
import Firebase

class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!

    var users = [User]()

    override func viewDidLoad() {
        super.viewDidLoad()
        fetchUser()
    }

    func fetchUser() {
        FIRDatabase.database().reference().child("users").observe(.childAdded, with: { (snapshot) in

            if let dictionary = snapshot.value as? [String: AnyObject] {
                let user = User(dictionary: dictionary)
                self.users.append(user)

                //this will crash because of background thread, so lets use dispatch_async to fix
                DispatchQueue.main.async(execute: {
                    self.tableView.reloadData()
                })
            }
        }, withCancel: nil)
    }

    func handleCancel() {
        dismiss(animated: true, completion: nil)
    }

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

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "resultCell", for: indexPath)
        let user = users[indexPath.row]
        cell.textLabel?.text = user.name
        cell.detailTextLabel?.text = user.email
        return cell
    }
}

class UserCell: UITableViewCell {
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
</code>```

Presenting Home View Controller through SWRevealViewController under LoginButton

```<code>let vc : SWRevealViewController = self.storyboard?.instantiateViewController(withIdentifier: "SWRevealViewController") as! SWRevealViewController
self.present(vc, animated: true, completion: nil)
</code>```

Architecture

答:
Problem

You may be not setting the RootViewController of You navigation controller.

Solution

Select the segue between SWRevealViewController and the NavigationController. In the attributes inspector, set the segue identifier to “sw_front”. This is the default identifier that indicates a transition of front view controller.

For the segue between SWRevealViewController and the sidebar view controller, set the segue identifier to “sw_rear”. This identifier tells SWRevealViewController that the controller represents the rear view

Body:
When I go to the HomeViewController the screen is to totally black. I actually want to fetch the users to put them into TableViewCells. I am using Firebase as a database and Swift as a language. Help me to accomplish this.

import UIKit
import Firebase

class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!

    var users = [User]()

    override func viewDidLoad() {
        super.viewDidLoad()
        fetchUser()
    }

    func fetchUser() {
        FIRDatabase.database().reference().child("users").observe(.childAdded, with: { (snapshot) in

            if let dictionary = snapshot.value as? [String: AnyObject] {
                let user = User(dictionary: dictionary)
                self.users.append(user)

                //this will crash because of background thread, so lets use dispatch_async to fix
                DispatchQueue.main.async(execute: {
                    self.tableView.reloadData()
                })
            }
        }, withCancel: nil)
    }

    func handleCancel() {
        dismiss(animated: true, completion: nil)
    }

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

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "resultCell", for: indexPath)
        let user = users[indexPath.row]
        cell.textLabel?.text = user.name
        cell.detailTextLabel?.text = user.email
        return cell
    }
}

class UserCell: UITableViewCell {
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Presenting Home View Controller through SWRevealViewController under LoginButton

let vc : SWRevealViewController = self.storyboard?.instantiateViewController(withIdentifier: "SWRevealViewController") as! SWRevealViewController
self.present(vc, animated: true, completion: nil)

Architecture


问:
R colour percentage bin histogram
how can I get an histogram in R such that the colour of each bin corresponds to the percentage of ok/valid/true cases of the total? I mean, the histogram shows the number of cases per bin, so I get the distribution over all the x-range. However, I would like also to fill each bin with a colour showing which was the percentage of any condition (satisfactory, true...) in each interval...

Any help is welcome! Thank you!!

答:
to use histogram use
hist(df$colname)
Also check these two links provided below

https://www.r-bloggers.com/how-to-make-a-histogram-with-ggplot2/

How to plot a histogram with different colors in R

Title: R colour percentage bin histogram


问:
Visual Studio 2017 locking files
Visual Studio Version 15.2 (26430.6) Release.

Having recently updated to the above version I am running into continuous issues with VS locking up files when trying to build.

Could not copy "obj\Debug\projHype.dll" to "bin\Debug\projHype.dll". Exceeded retry count of 10. Failed.

Also tried running VS2017 with and with out admin priveledges

I tried the suggestions for older versions of visual studio but to no avail.  Any ideas how to get around this?

答: For anyone encountering this. Updating to version 26430.12 will resolve this. Looks like the previous release contained a bug.</p>

Title: Visual Studio 2017 locking files


问:
Why apprend("

")is so strange
I got a problem with append in jquery

When i write the code like

```<code><script>
  $(document).ready(function(){
    for(var a=0;a<5;a++){
          var u=$("#nav").append("<li >a_"+a);
               u.append("<ul>");
                   for(var b=0;b<5;b++){
                       u.append("<li>b_"+b+"</li>");
                   }
                u.append("</ul>")

          $("#nav").append("</li>")
     }
    });

 </script>
  <div class="section-tree">
  <ul id="nav"></ul>         </div>
</code>```

It output like:

Is not what i want

What i want is:

```<code>  <ul>

   <li>
    a_0
      <ul>
         <li>b_1</li>
         <li>b_2</li>
         <li>b_3</li>
         <li>b_4</li>
         <li>b_5</li>
      </ul>
   </li>

   <li>
   a_1
      <ul>
        <li>b_1</li>
        <li>b_2</li>
        <li>b_3</li>
        <li>b_4</li>
        <li>b_5</li>
      </ul>
  </li>
        ...
</ul>
</code>```

why it's not right?

hellowworld
hellowworld
hellowworld
hellowworld

答:
```<code>$(document).ready(function(){
      var finalUiLi="";
      for(var a=0;a<5;a++){
          finalUiLi+="<li>a_"+a;
            finalUiLi+="<ul>";
                for(var b=0;b<5;b++){
                    finalUiLi+="<li>b_"+b +"</li>";
                }
            finalUiLi+="</ul>";
          finalUiLi+="</li>";
      }
     $("#nav").append(finalUiLi);
    });
</code>```

Please try this way it will work. Below is the screen shot for the output.

Title: Why apprend("<ul><li>")is so strange

Body:
I got a problem with append in jquery

When i write the code like

It output like:

Is not what i want

What i want is:

    a_0

b_1

b_2

b_3

b_4

b_5

   a_1

b_1

b_2

b_3

b_4

b_5

        ...

why it's not right?

hellowworld
hellowworld
hellowworld
hellowworld

Body:
$(document).ready(function(){
      var finalUiLi="";
      for(var a=0;a<5;a++){
          finalUiLi+="<li>a_"+a;
            finalUiLi+="<ul>";
                for(var b=0;b<5;b++){
                    finalUiLi+="<li>b_"+b +"</li>";
                }
            finalUiLi+="</ul>";
          finalUiLi+="</li>";
      }
     $("#nav").append(finalUiLi);
    });

Please try this way it will work. Below is the screen shot for the output.


问:
How to apply bootstrap v4 alpha's form input validation classes with ASP.NET Razor syntax?
So, bootstrap v4 alpha has changed form validation classes a bit. Now, to apply validation styles to a form input, you apply the CSS class to the parent div.form-group.

I'm writing a website using ASP.NET MVC4, and am trying to figure out how to apply this CSS class to a parent HTML element.

For example, here's my current HTML for a form input element ...

```<code><div class="form-group">
    @Html.LabelFor(m => m.Password)
    @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
    @Html.ValidationMessageFor(m => m.Password)
</div>
</code>```

If my view's model has a validation error for the Password field, it'll get a corresponding bit of text below the input field. That's what that ValidationMessageFor call does.

But, with bootstrap v4, I need to apply a has-danger class to the parent div.form-group. It'd need to look like so ...

```<code><div class="form-group has-danger">
    @Html.LabelFor(m => m.Password)
    @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
    @Html.ValidationMessageFor(m => m.Password)
</div>
</code>```

But, I only want to apply that if there is a validation message for the password field.

Any idea how to achieve this with Razor?

答:
You can create an HtmlHelper that checks ModelState and returns an error class:

```<code>public static class HtmlHelperExtensions
{
    public static string FieldHasError(this HtmlHelper helper, string propertyName, string errorClass = "has-danger")
    {
        if (helper.ViewData.ModelState != null && !helper.ViewData.ModelState.IsValidField(propertyName))
        {
            return errorClass;
        }
        return string.Empty;
    }

    public static string FieldHasError<TModel, TEnum>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TEnum>> expression, string errorClass = "has-danger")
    {
        var expressionString = ExpressionHelper.GetExpressionText(expression);
        var modelName = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expressionString);
        return FieldHasError(helper, modelName, errorClass);
    }
}
</code>```

Simple usage:

```<code><div class="form-group @Html.FieldHasError("Password")">
    @Html.LabelFor(m => m.Password)
    @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
    @Html.ValidationMessageFor(m => m.Password)
</div>
</code>```

or

```<code><div class="form-group @Html.FieldHasError(m => m.Password)">
    @Html.LabelFor(m => m.Password)
    @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
    @Html.ValidationMessageFor(m => m.Password)
</div>
</code>```

Body:
So, bootstrap v4 alpha has changed form validation classes a bit. Now, to apply validation styles to a form input, you apply the CSS class to the parent div.form-group.

I'm writing a website using ASP.NET MVC4, and am trying to figure out how to apply this CSS class to a parent HTML element.

For example, here's my current HTML for a form input element ...

    @Html.LabelFor(m => m.Password)
    @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
    @Html.ValidationMessageFor(m => m.Password)

If my view's model has a validation error for the Password field, it'll get a corresponding bit of text below the input field. That's what that ValidationMessageFor call does.

But, with bootstrap v4, I need to apply a has-danger class to the parent div.form-group. It'd need to look like so ...

    @Html.LabelFor(m => m.Password)
    @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
    @Html.ValidationMessageFor(m => m.Password)

But, I only want to apply that if there is a validation message for the password field.

Any idea how to achieve this with Razor?

Body:
You can create an HtmlHelper that checks ModelState and returns an error class:

public static class HtmlHelperExtensions
{
    public static string FieldHasError(this HtmlHelper helper, string propertyName, string errorClass = "has-danger")
    {
        if (helper.ViewData.ModelState != null && !helper.ViewData.ModelState.IsValidField(propertyName))
        {
            return errorClass;
        }
        return string.Empty;
    }

    public static string FieldHasError<TModel, TEnum>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TEnum>> expression, string errorClass = "has-danger")
    {
        var expressionString = ExpressionHelper.GetExpressionText(expression);
        var modelName = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expressionString);
        return FieldHasError(helper, modelName, errorClass);
    }
}

Simple usage:

<div class="form-group @Html.FieldHasError("Password")">
    @Html.LabelFor(m => m.Password)
    @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
    @Html.ValidationMessageFor(m => m.Password)
</div>

or

<div class="form-group @Html.FieldHasError(m => m.Password)">
    @Html.LabelFor(m => m.Password)
    @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
    @Html.ValidationMessageFor(m => m.Password)
</div>


问:
Android Application Lifecycle
I see a lot of answers concerning the Activity Lifecycle and that for most part is clear to me. What I'm looking for is the Application Lifecycle. I have the following case:

Application starts - Invalidate PIN

A PIN has to be entered if it is stale of invalid

Application is backgrounded (Android Home screen is visible) - Invalidate PIN

The applicatiion is foregrounded (App becomes visible again) - goto step 2

With the Activity Lifecycle it is hard if not impossible to achieve. Any suggestions?

答:
Application starts - onCreate()/ onStart()

Get the pin in onCreate or onStart or onResume() (check the state of the pin.

3.Application is backgrounded - onPause() - Invalidate your pin on onPause() method

4.The applicatiion is foregrounded - onResume() - perform step 2 in onResume()

Title: Android Application Lifecycle


问:
How to escape sed in shell script
I have the regex expression "myname"(?:(?:.*\n)+).*tree_ish = "(.*)",, that works fine for itself (tested in https://regex101.com/) with:

```<code>    name = "myname",
    dummy1 = 2345,
    dummy2 = "dummy",
    tree_ish = "bc59c4f7c7cf4d0b969a3f405a4a5b7fee22ae96",
</code>```

Now I want to use that regex expression in sed to replace the one captioning group but cannot figure out the proper escaping. I tried to escape all \().*+ but somehow neither permutation did work. And sadly using sed is not as easy as:

```<code>sed -i 's|"myname"(?:(?:.*\n)+).*tree_ish = "(.*)",|rEpLaCe|' myfile
</code>```

Does anyone know what the correct escaping would look like for replacing bc59c4f7c7cf4d0b969a3f405a4a5b7fee22ae96 with rEpLaCe?

Expected output:

```<code>    name = "myname",
    dummy1 = 2345,
    dummy2 = "dummy",
    tree_ish = "rEpLaCe",
</code>```

答:
awk is better suited here

```<code>$ awk '/"myname"/{f=1} /tree_ish/ && f{sub(/"[^"]+"/,"\"rEpLaCe\"");f=0} 1' ip.txt
    name = "myname",
    dummy1 = 2345,
    dummy2 = "dummy",
    tree_ish = "rEpLaCe",
</code>```

/"myname"/{f=1} set a flag if line contains "myname"

/tree_ish/ && f if line contains tree_ish and flag is set

sub(/"[^"]+"/,"\"rEpLaCe\"") change contents between double quotes to "rEpLaCe"

f=0 clear the flag

1 idiomatic way to print the input line, including any changes made

there are lot of assumptions made here like only one double quoted value, no anchors used, etc. Change them accordingly

If PCRE is more comfortable, then probably use

```<code>$ perl -0777 -pe 's/"myname".*?tree_ish\h*=\h*"\K[^"]+(?=")/rEpLaCe/sg' ip.txt
    name = "myname",
    dummy1 = 2345,
    dummy2 = "dummy",
    tree_ish = "rEpLaCe",
</code>```

See Reference - What does this regex mean? and http://perldoc.perl.org/perlrun.html#Command-Switches

Use perl -0777 -i -pe for inplace editing

Title: How to escape sed in shell script

Body:
I have the regex expression "myname"(?:(?:.*\n)+).*tree_ish = "(.*)",, that works fine for itself (tested in https://regex101.com/) with:

    name = "myname",
    dummy1 = 2345,
    dummy2 = "dummy",
    tree_ish = "bc59c4f7c7cf4d0b969a3f405a4a5b7fee22ae96",

Now I want to use that regex expression in sed to replace the one captioning group but cannot figure out the proper escaping. I tried to escape all \().*+ but somehow neither permutation did work. And sadly using sed is not as easy as:

sed -i 's|"myname"(?:(?:.*\n)+).*tree_ish = "(.*)",|rEpLaCe|' myfile

Does anyone know what the correct escaping would look like for replacing bc59c4f7c7cf4d0b969a3f405a4a5b7fee22ae96 with rEpLaCe?

Expected output:

    name = "myname",
    dummy1 = 2345,
    dummy2 = "dummy",
    tree_ish = "rEpLaCe",

Body:
awk is better suited here

$ awk '/"myname"/{f=1} /tree_ish/ && f{sub(/"[^"]+"/,"\"rEpLaCe\"");f=0} 1' ip.txt
    name = "myname",
    dummy1 = 2345,
    dummy2 = "dummy",
    tree_ish = "rEpLaCe",

/"myname"/{f=1} set a flag if line contains "myname"

/tree_ish/ && f if line contains tree_ish and flag is set

sub(/"[^"]+"/,"\"rEpLaCe\"") change contents between double quotes to "rEpLaCe"

f=0 clear the flag

1 idiomatic way to print the input line, including any changes made

there are lot of assumptions made here like only one double quoted value, no anchors used, etc. Change them accordingly

If PCRE is more comfortable, then probably use

$ perl -0777 -pe 's/"myname".*?tree_ish\h*=\h*"\K[^"]+(?=")/rEpLaCe/sg' ip.txt
    name = "myname",
    dummy1 = 2345,
    dummy2 = "dummy",
    tree_ish = "rEpLaCe",

See Reference - What does this regex mean? and http://perldoc.perl.org/perlrun.html#Command-Switches

Use perl -0777 -i -pe for inplace editing


问:
Powershell Email format and retrieving CN from Certificate subject
I'm trying to create a powershell script that will alert me when one or more of my certificates are about to expire.I combined some scripts i found on internet and it seems to work fine. The only problem is when sending the email im getting just one big row with all certificate one behind the other. I'd preffer to get more of a list like:
Certificate 1
Subject: CN =hello
Expiration:2/11/2017 1:00:00 AM

Certificate 2
Subject: CN =hello2
Expiration:2/11/2017 1:00:00 AM

If possible i would also like some help on how to just get the CN from the certificate subject rather the the complete subject with (OU, O, L, S,C)

Here is my current script:

```<code>import-module webadministration
$DaysToExpiration = 700 #just modify this date for more or less

$expirationDate = (Get-Date).AddDays($DaysToExpiration)

$body = Get-ChildItem CERT:LocalMachine/My |
Where {$_.NotAfter -lt  (Get-Date).AddDays($DaysToExpiration)}

$body | select  Subject, @{Name="Expiration"; Expression = {$_.NotAfter}} | fl | out-string

$emailSmtpServer = "172.17.1.236"
$emailSmtpServerPort = "25"
$emailSmtpUser = "test"
$emailSmtpPass = "test"

$emailMessage = New-Object System.Net.Mail.MailMessage

$PCName = $env:COMPUTERNAME
$emailMessage.From  = "$PCName@test.com"
$emailMessage.To.Add( "test@dev.test.de" )
$emailMessage.Body  = $body | select Subject, @{Name="Expiration"; Expression = {$_.NotAfter}} | fl | out-string
$emailMessage.Subject = "Certificates Expiring within $DaysToExpiration days"
$emailMessage.IsBodyHtml = $true

$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );

if ($emailMessage.Body.Length -gt 1)
{
  Write-host "Sending Email"
  $SMTPClient.Send( $emailMessage )
}
</code>```

答:
I was searching for the same and I found the following stack overflow
link

```<code>$s = Get-ChildItem -Path 'Cert:\localmachine\My'| select subject
$s -replace "(CN=)(.*?),.*",'$2'
$s = $s -replace "@{Subject="
</code>```

OR the non regex way ..

```<code>$sub = $_.Subject.split(",")[0].split("=")
$sub[1] = $sub[1] -replace "\*","star"
$sub[1]
</code>```

It is working for most domain certificates but and I can see some issues with self certificates and server certificates.

Body:
I'm trying to create a powershell script that will alert me when one or more of my certificates are about to expire.I combined some scripts i found on internet and it seems to work fine. The only problem is when sending the email im getting just one big row with all certificate one behind the other. I'd preffer to get more of a list like:
Certificate 1
Subject: CN =hello
Expiration:2/11/2017 1:00:00 AM

Certificate 2
Subject: CN =hello2
Expiration:2/11/2017 1:00:00 AM

If possible i would also like some help on how to just get the CN from the certificate subject rather the the complete subject with (OU, O, L, S,C)

Here is my current script:

import-module webadministration
$DaysToExpiration = 700 #just modify this date for more or less

$expirationDate = (Get-Date).AddDays($DaysToExpiration)

$body = Get-ChildItem CERT:LocalMachine/My |
Where {$_.NotAfter -lt  (Get-Date).AddDays($DaysToExpiration)}

$body | select  Subject, @{Name="Expiration"; Expression = {$_.NotAfter}} | fl | out-string

$emailSmtpServer = "172.17.1.236"
$emailSmtpServerPort = "25"
$emailSmtpUser = "test"
$emailSmtpPass = "test"

$emailMessage = New-Object System.Net.Mail.MailMessage

$PCName = $env:COMPUTERNAME
$emailMessage.From  = "$PCName@test.com"
$emailMessage.To.Add( "test@dev.test.de" )
$emailMessage.Body  = $body | select Subject, @{Name="Expiration"; Expression = {$_.NotAfter}} | fl | out-string
$emailMessage.Subject = "Certificates Expiring within $DaysToExpiration days"
$emailMessage.IsBodyHtml = $true

$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );

if ($emailMessage.Body.Length -gt 1)
{
  Write-host "Sending Email"
  $SMTPClient.Send( $emailMessage )
}

Body:
I was searching for the same and I found the following stack overflow
link

$s = Get-ChildItem -Path 'Cert:\localmachine\My'| select subject
$s -replace "(CN=)(.*?),.*",'$2'
$s = $s -replace "@{Subject="

OR the non regex way ..

$sub = $_.Subject.split(",")[0].split("=")
$sub[1] = $sub[1] -replace "\*","star"
$sub[1]

It is working for most domain certificates but and I can see some issues with self certificates and server certificates.


问:
Beyond Stack Sampling: C++ Profilers

A Hacker's Tale

The date is 12/02/10.  The days before Christmas are dripping away and I've pretty much hit a major road block as a windows programmer.  I've been using AQTime, I've tried sleepy, shiny, and very sleepy, and as we speak, VTune is installing.  I've tried to use the VS2008 profiler, and it's been positively punishing as well as often insensible.  I've used the random pause technique.  I've examined call-trees.  I've fired off function traces.  But the sad painful fact of the matter is that the app I'm working with is over a million lines of code, with probably another million lines worth of third-party apps.

I need better tools.  I've read the other topics.  I've tried out each profiler listed in each topic.  There simply has to be something better than these junky and expensive options, or ludicrous amounts of work for almost no gain.  To further complicate matters, our code is heavily threaded, and runs a number of Qt Event loops, some of which are so fragile that they crash under heavy instrumentation due to timing delays.  Don't ask me why we're running multiple event loops.  No one can tell me.

Are there any options more along the lines of Valgrind in a windows environment?

Is there anything better than the long swath of broken tools I've already tried?

Is there anything designed to integrate with Qt, perhaps with a useful display of events in queue?

A full list of the tools I tried, with the ones that were really useful in italics:

AQTime: Rather good!  Has some trouble with deep recursion, but the call graph is correct in these cases, and can be used to clear up any confusion you might have.  Not a perfect tool, but worth trying out.  It might suit your needs, and it certainly was good enough for me most of the time.

Random Pause attack in debug mode: Not enough information enough of the time.

A good tool but not a complete solution.

Parallel Studios:  The nuclear option.  Obtrusive, weird, and crazily powerful.  I think you should hit up the 30 day evaluation, and figure out if it's a good fit. It's just darn cool, too.

AMD Codeanalyst:  Wonderful, easy to use, very crash-prone, but I think that's an environment thing.  I'd recommend trying it, as it is free.

Luke Stackwalker: Works fine on small projects, it's a bit trying to get it working on ours.  Some good results though, and it definitely replaces Sleepy for my personal tasks.

PurifyPlus: No support for Win-x64 environments, most prominently Windows 7.  Otherwise excellent.  A number of my colleagues in other departments swear by it.

VS2008 Profiler: Produces output in the 100+gigs range in function trace mode at the required resolution.  On the plus side, produces solid results.

GProf: Requires GCC to be even moderately effective.

VTune: VTune's W7 support borders on criminal. Otherwise excellent

PIN: I'd need to hack up my own tool, so this is sort of a last resort.

Sleepy\VerySleepy: Useful for smaller apps, but failing me here.

EasyProfiler: Not bad if you don't mind a bit of manually injected code to indicate where to instrument.

Valgrind: *nix only, but very good when you're in that environment.

OProfile: Linux only.

Proffy: They shoot wild horses.

Suggested tools that I haven't tried:

XPerf:

Glowcode:

Devpartner:

Notes:
Intel environment at the moment.  VS2008, boost libraries.  Qt 4+.  And the wretched humdinger of them all: Qt/MFC integration via trolltech.

Now: Almost two weeks later, it looks like my issue is resolved.  Thanks to a variety of tools, including almost everything on the list and a couple of my personal tricks, we found the primary bottlenecks.  However, I'm going to keep testing, exploring, and trying out new profilers as well as new tech.  Why?  Because I owe it to you guys, because you guys rock.  It does slow the timeline down a little, but I'm still very excited to keep trying out new tools.

Synopsis

Among many other problems, a number of components had recently been switched to the incorrect threading model, causing serious hang-ups due to the fact that the code underneath us was suddenly no longer multithreaded.  I can't say more because it violates my NDA, but I can tell you that this would never have been found by casual inspection or even by normal code review.  Without profilers, callgraphs, and random pausing in conjunction, we'd still be screaming our fury at the beautiful blue arc of the sky.  Thankfully, I work with some of the best hackers I've ever met, and I have access to an amazing 'verse full of great tools and great people.

Gentlefolk, I appreciate this tremendously, and only regret that I don't have enough rep to reward each of you with a bounty.  I still think this is an important question to get a better answer to than the ones we've got so far on SO.

As a result, each week for the next three weeks, I'll be putting up the biggest bounty I can afford, and awarding it to the answer with the nicest tool that I think isn't common knowledge.  After three weeks, we'll hopefully have accumulated a definitive profile of the profilers, if you'll pardon my punning.

Take-away

Use a profiler.  They're good enough for Ritchie, Kernighan, Bentley, and Knuth. I don't care who you think you are.  Use a profiler.  If the one you've got doesn't work, find another.  If you can't find one, code one.  If you can't code one, or it's a small hang up, or you're just stuck, use random pausing.  If all else fails, hire some grad students to bang out a profiler.

A Longer View

So, I thought it might be nice to write up a bit of a retrospective.  I opted to work extensively with Parallel Studios, in part because it is actually built on top of the PIN Tool.  Having had academic dealings with some of the researchers involved, I felt that this was probably a mark of some quality.  Thankfully, I was right.  While the GUI is a bit dreadful, I found IPS to be incredibly useful, though I can't comfortably recommend it for everyone.  Critically, there's no obvious way to get line-level hit counts, something that AQT and a number of other profilers provide, and I've found very useful for examining rate of branch-selection among other things.  In net, I've enjoyed using AQTime as well, and I've found their support to be really responsive.  Again, I have to qualify my recommendation:  A lot of their features don't work that well, and some of them are downright crash-prone on Win7x64.  XPerf also performed admirably, but is agonizingly slow for the sampling detail required to get good reads on certain kinds of applications.

Right now, I'd have to say that I don't think there's a definitive option for profiling C++ code in a W7x64 environment, but there are certainly options that simply fail to perform any useful service.

答: I have successfully used PurifyPlus for Windows. Although it is not cheap, IBM provides a trial version that is slightly crippled. All you need for profiling with quantify are pdb files and linking with /FIXED:NO. Only drawback: No support for Win7/64.

Title: Beyond Stack Sampling: C++ Profilers