问:
R sapply loop to replace for loop
I have successfully switched for loops to sapply loops before,
and I know for a fact (system.time()) that they are faster.

BUT my mind still works in a for loop way...

Please help me to convert this for loop case:

```<code>names.list <- c("Anna", "Ana", "Albert", "Albort", "Rob", "Robb", "Tommy", "Tommie")
misspell.list <- c("Anna", "Albort", "Robb", "Tommie")
fix.list <- c("Ana", "Albert", "Rob", "Tommy")

for(i in 1:length(fix.list)) {
        names.list[which(names.list == misspell.list[i])] <- fix.list[i]

}

names.list
</code>```

To a sapply()

So far, I got:

```<code>sapply(seq_along(fix.list), function(x)
        names.list[which(names.list == misspell.list[x])]  <- fix.list[x]
)
</code>```

But it only returns me the original vector.

Thanks!

EDIT 1:

the misspell.list and fix.list were created automatically by adist() bellow and the original names.list has 665 elements. My for() solution returns length(unique(names.list)) = 653 elements

```<code># will do another sapply() substitution here soon
for(i in 1:(length(names.list)-1)) {
        distancias[i] <- adist(names.list[i], names.list[i+1])
}

# fix list
misspell.list <- names.list[which(distancias < 2)]
fix.list <- names.list[which(distancias < 2) +1]
</code>```

EDIT 2: thanks to you, now I'm a sapply overlord and I'm here just to show my other for-sapply substitution used with adist()

```<code>nomes <- sort(unique(names.list))
distancias <- rep(10, length(nomes))

#adist() for finding misspelling
sapply(seq_along(nomes),
       function(x) {
                if(x<length(nomes)) {
                        distancias[x] <<- adist(nomes[x], nomes[x+1])
                        }
        }
       )
# fix list
misspell.list <- names.list[which(distancias < 2)]
fix.list <- names.list[which(distancias < 2) +1]
</code>```

The other part you already know, thanks again!

答:
If there is one-to-one correspondence between misspell.list and fix.list you can do away with loops by using match function

```<code>names.list[match(misspell.list,names.list)] <- fix.list

names.list
#[1] "Ana"    "Ana"    "Albert" "Albert" "Rob"    "Rob"    "Tommy"  "Tommy"
</code>```

Title: R sapply loop to replace for loop

Body:
I have successfully switched for loops to sapply loops before,
and I know for a fact (system.time()) that they are faster.

BUT my mind still works in a for loop way...

Please help me to convert this for loop case:

names.list <- c("Anna", "Ana", "Albert", "Albort", "Rob", "Robb", "Tommy", "Tommie")
misspell.list <- c("Anna", "Albort", "Robb", "Tommie")
fix.list <- c("Ana", "Albert", "Rob", "Tommy")

for(i in 1:length(fix.list)) {
        names.list[which(names.list == misspell.list[i])] <- fix.list[i]

}

names.list

To a sapply()

So far, I got:

sapply(seq_along(fix.list), function(x)
        names.list[which(names.list == misspell.list[x])]  <- fix.list[x]
)

But it only returns me the original vector.

Thanks!

EDIT 1:

the misspell.list and fix.list were created automatically by adist() bellow and the original names.list has 665 elements. My for() solution returns length(unique(names.list)) = 653 elements

# will do another sapply() substitution here soon
for(i in 1:(length(names.list)-1)) {
        distancias[i] <- adist(names.list[i], names.list[i+1])
}

# fix list
misspell.list <- names.list[which(distancias < 2)]
fix.list <- names.list[which(distancias < 2) +1]

EDIT 2: thanks to you, now I'm a sapply overlord and I'm here just to show my other for-sapply substitution used with adist()

nomes <- sort(unique(names.list))
distancias <- rep(10, length(nomes))

#adist() for finding misspelling
sapply(seq_along(nomes),
       function(x) {
                if(x<length(nomes)) {
                        distancias[x] <<- adist(nomes[x], nomes[x+1])
                        }
        }
       )
# fix list
misspell.list <- names.list[which(distancias < 2)]
fix.list <- names.list[which(distancias < 2) +1]

The other part you already know, thanks again!

Body:
If there is one-to-one correspondence between misspell.list and fix.list you can do away with loops by using match function

names.list[match(misspell.list,names.list)] <- fix.list

names.list
#[1] "Ana"    "Ana"    "Albert" "Albert" "Rob"    "Rob"    "Tommy"  "Tommy"


来源: stackexchange

答:
The solution using match is much better, but in terms of what you were trying to do, this will work.  Firstly, you don't need the which.  You also need to use the <<- operator to tell the internal function defined within the loop to use the global environment rather than its own local one - otherwise it does not change names.list, only its copy.

```<code>sapply(seq_along(fix.list), function(x)
  names.list[names.list == misspell.list[x]]  <<- fix.list[x]
)

names.list
[1] "Ana"    "Ana"    "Albert" "Albert" "Rob"    "Rob"    "Tommy"  "Tommy"
</code>```

ContentLicense: CC BY-SA 3.0

Title: R sapply loop to replace for loop

Body:
The solution using match is much better, but in terms of what you were trying to do, this will work.  Firstly, you don't need the which.  You also need to use the <<- operator to tell the internal function defined within the loop to use the global environment rather than its own local one - otherwise it does not change names.list, only its copy.

sapply(seq_along(fix.list), function(x)
  names.list[names.list == misspell.list[x]]  <<- fix.list[x]
)

names.list
[1] "Ana"    "Ana"    "Albert" "Albert" "Rob"    "Rob"    "Tommy"  "Tommy"


问:
div dynamically between footer and header
I want to add a div for my content between a fixed footer and header.

The height of the header and footer may change. So I don't want any paddings or margins that refer to the height of the footer or header.

In other words: I want to be able to change the size of the footer or header in a single place without usage of css preprocessors .

I have seen many examples but they all used hardcoded references to the height of the header or footer. I don't want these.

Is this possible at all? If so I would like to know.

Here a example of what I'm trying to do:

答: Use a flexbox grid for the header & footer, they will expand and contract as they need but you won't have to hardcode heights.</p>


问:
Mapbox popup ReferenceError: features is not defined
I'm trying to display 3 fields properties from a geojson data that is loaded from a file. The data is loaded an added to the map. And the markers/points are display on the HTML page. BUt then I click on a marker/point nothing happens. Around .setLngLat(features.geometry.coordinates) I get an ReferenceError: features is not defined I'm not sure what I've missed or needed to do for it to be available to the current scope.

I would very much appreciate any hints or tips to resolve this.

```<code>{% load static %}
<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'/>
    <title></title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no'/>
    <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.css' rel='stylesheet'/>
    <style>
        body {
            margin: 0;
            padding: 0;
        }

        #map {
            position: absolute;
            top: 0;
            bottom: 0;
            width: 100%;
        }
    </style>
</head>
<body>
<div id='map'></div>
<script>
mapboxgl.accessToken = 'pk.myaccesstoken';

var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v9',
    center: [10.600, 55.900],
    zoom: 6.0,
    hash: true
});

map.on('load', function () {

    // Add a layer showing the places.
    map.addSource('markers', {
        type: 'geojson',
        data: '{% static 'json/architecture_map.geojson'%}'
    });

    map.addLayer({
        "id": "places",
        "source": "markers",
        "type": "circle",
        "paint": {
            "circle-radius": 5,
            "circle-color": "#fb05ff"
        }
    });

    map.on('click', function (e) {
        var f = map.queryRenderedFeatures(e.point, {layers: ['places']});
        if (f.length) {
            var feature = f[0];

            new mapboxgl.Popup()
                .setLngLat(features.geometry.coordinates)
                .setHTML(ProjectPopup(feature))
                .addTo(map);
            }
    });

    function ProjectPopup(feature){
        var html = '';
        html += "<div>";
        html += "<h2>" + feature.properties.project + "</h2>";
        html += "<p>" + feature.properties.image + "</p>";
        html += "<a>" + feature.properties.slug + "</a>";
        html += "</div>";
        return html;
    }

    // Change the cursor to a pointer when the mouse is over the places layer.
    map.on('mouseenter', 'places', function () {
        map.getCanvas().style.cursor = 'pointer';
    });

    // Change it back to a pointer when it leaves.
    map.on('mouseleave', 'places', function () {
        map.getCanvas().style.cursor = '';
    });

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

Sample of the geojson file.

```<code>{
  "type": "FeatureCollection",
  "crs": {
    "type": "name",
    "properties": {
      "name": "EPSG:4326"
    }
  },
  "features": [
    {
      "type": "Feature",
      "properties": {
        "image": "project01.JPG",
        "project": "Project Title",
        "slug": "project-title"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          9.932241438432886,
          57.04649628721196
        ]
      }
    }
  ]
}
</code>```

答:
First of all your provided geojson is not a valid one. You can check your geojson here: http://geojsonlint.com/

Second your "not defined" error might just be a typo. You defined your variable like this:

var feature = f[0];

But using is like this:

new mapboxgl.Popup()
    .setLngLat(features.geometry.coordinates)
    .setHTML(ProjectPopup(feature))
    .addTo(map);
}```

You notice that features is not the same as your defined variable named feature thus resulting in undefined.

I corrected your mistake. See here:
https://jsfiddle.net/andi_lo/xzrzzzsc

Body:
I'm trying to display 3 fields properties from a geojson data that is loaded from a file. The data is loaded an added to the map. And the markers/points are display on the HTML page. BUt then I click on a marker/point nothing happens. Around .setLngLat(features.geometry.coordinates) I get an ReferenceError: features is not defined I'm not sure what I've missed or needed to do for it to be available to the current scope.

I would very much appreciate any hints or tips to resolve this.

{% load static %}
<!DOCTYPE html>

    <meta charset='utf-8'/>
    <title></title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no'/>

    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.css' rel='stylesheet'/>

Sample of the geojson file.

{
  "type": "FeatureCollection",
  "crs": {
    "type": "name",
    "properties": {
      "name": "EPSG:4326"
    }
  },
  "features": [
    {
      "type": "Feature",
      "properties": {
        "image": "project01.JPG",
        "project": "Project Title",
        "slug": "project-title"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          9.932241438432886,
          57.04649628721196
        ]
      }
    }
  ]
}

Body:
First of all your provided geojson is not a valid one. You can check your geojson here: http://geojsonlint.com/

Second your "not defined" error might just be a typo. You defined your variable like this:

var feature = f[0];

But using is like this:

new mapboxgl.Popup()
    .setLngLat(features.geometry.coordinates)
    .setHTML(ProjectPopup(feature))
    .addTo(map);
}

You notice that features is not the same as your defined variable named feature thus resulting in undefined.

I corrected your mistake. See here:
https://jsfiddle.net/andi_lo/xzrzzzsc


问:
How to upload file from a subfolder using Selenium in Python
Can somebody tell me what to modify here, so the file I'm uploading can be uploaded from a subfolder? At the moment the files are stored in the same folder as the python script.

This script helps me to automate the process of adding ads to a site. Here is the part which uploads image files from a json file (photofiles is an array in config.json). I want to store the photos in a subfolder.

```<code># Upload images
fileup = driver.find_element_by_xpath("//input[@type='file']")

for path in photofiles:
    uploaded_count = len(driver.find_elements_by_class_name("imagebox-thumbnail"))
    fileup.send_keys(os.path.abspath(path))
    total_upload_time = 0
    while uploaded_count == len(driver.find_elements_by_class_name("imagebox-thumbnail")) and \
                    total_upload_time < 30:
        time.sleep(0.5)
        total_upload_time += 0.5

    log.debug("Uploaded file in %s seconds." % total_upload_time)
</code>```

答:
Should be pretty simple by just modifying the photofiles list. Assuming your code creates a list of files and stores it as "photofiles" you just need to append to it all the needed paths from the folder you want.

There are multiple ways of traversing a folder and, for example, getting all the files with a certain extension (see Find all files in a directory with extension .txt in Python). You could build your "photofiles" list from all the files with certain extensions in your desired folder.

Body:
Can somebody tell me what to modify here, so the file I'm uploading can be uploaded from a subfolder? At the moment the files are stored in the same folder as the python script.

This script helps me to automate the process of adding ads to a site. Here is the part which uploads image files from a json file (photofiles is an array in config.json). I want to store the photos in a subfolder.

# Upload images
fileup = driver.find_element_by_xpath("//input[@type='file']")

for path in photofiles:
    uploaded_count = len(driver.find_elements_by_class_name("imagebox-thumbnail"))
    fileup.send_keys(os.path.abspath(path))
    total_upload_time = 0
    while uploaded_count == len(driver.find_elements_by_class_name("imagebox-thumbnail")) and \
                    total_upload_time < 30:
        time.sleep(0.5)
        total_upload_time += 0.5

    log.debug("Uploaded file in %s seconds." % total_upload_time)


问:
MYSQL Query - Some results don't return
I have a problem im my sql query:

```<code>SELECT table_2.id, SUM(table_2.time + table_4.time + table_6.time + table_8.time + table_10.time + table_12.time) AS total_time, SUM(table_2.connects + table_4.connects + table_6.connects + table_8.connects + table_10.connects + table_12.connects) AS total_connects FROM table_2
  INNER JOIN table_4 ON table_2.id = table_4.id
  INNER JOIN table_6 ON table_2.id = table_6.id
  INNER JOIN table_8 ON table_2.id = table_8.id
  INNER JOIN table_10 ON table_2.id = table_10.id
  INNER JOIN table_12 ON table_2.id = table_12.id
GROUP BY table_2.authid ORDER BY total_time DESC
</code>```

Ok, I have a script that grabs the user IDS and the time they spent and then puts it in mysql tables depending on which forum they have entered. The query above seems to be working fine but only for the users that have entered all forums, because the others that haven't entered in all forums don't return any result.

The ID is always the same, it is the users ID and connects is the number of times the user enters the specific forum.

If you understand my problem and know the answear please let me know, otherwise I'll try to explain better

Thanks

答:
Replace the JOIN with the LEFT JOIN:

```<code>SELECT  people.id, SUM(COALESCE(table_2.time, 0) + COALESCE(table_4.time, 0) + table_6.time, 0) + COALESCE(table_8.time, 0) + COALESCE(table_10.time, 0) + COALESCE(table_12.time, 0)) AS total_time,
        SUM(COALESCE(table_2.connects, 0) + COALESCE(table_4.connects, 0) + COALESCE(table_6.connects, 0) + COALESCE(table_8.connects, 0) + COALESCE(table_10.connects, 0) + COALESCE(table_12.connects, 0)) AS total_connects
FROM    people p
LEFT JOIN
        table_2
ON      table_2.id = people.id
LEFT JOIN
        table_4
ON      people.id = table_4.id
LEFT JOIN
        table_6
ON      people.id = table_6.id
LEFT JOIN
        table_8
ON      people.id = table_8.id
LEFT JOIN
        table_10
ON      people.id = table_10.id
LEFT JOIN
        table_12
ON      people.id = table_12.id
GROUP BY
        people.authid
ORDER BY
        total_time DESC
</code>```

ContentLicense: CC BY-SA 2.5

Title: MYSQL Query - Some results don't return

Body:
I have a problem im my sql query:

SELECT table_2.id, SUM(table_2.time + table_4.time + table_6.time + table_8.time + table_10.time + table_12.time) AS total_time, SUM(table_2.connects + table_4.connects + table_6.connects + table_8.connects + table_10.connects + table_12.connects) AS total_connects FROM table_2
  INNER JOIN table_4 ON table_2.id = table_4.id
  INNER JOIN table_6 ON table_2.id = table_6.id
  INNER JOIN table_8 ON table_2.id = table_8.id
  INNER JOIN table_10 ON table_2.id = table_10.id
  INNER JOIN table_12 ON table_2.id = table_12.id
GROUP BY table_2.authid ORDER BY total_time DESC

Ok, I have a script that grabs the user IDS and the time they spent and then puts it in mysql tables depending on which forum they have entered. The query above seems to be working fine but only for the users that have entered all forums, because the others that haven't entered in all forums don't return any result.

The ID is always the same, it is the users ID and connects is the number of times the user enters the specific forum.

If you understand my problem and know the answear please let me know, otherwise I'll try to explain better

Thanks

Body:
Replace the JOIN with the LEFT JOIN:

SELECT  people.id, SUM(COALESCE(table_2.time, 0) + COALESCE(table_4.time, 0) + table_6.time, 0) + COALESCE(table_8.time, 0) + COALESCE(table_10.time, 0) + COALESCE(table_12.time, 0)) AS total_time,
        SUM(COALESCE(table_2.connects, 0) + COALESCE(table_4.connects, 0) + COALESCE(table_6.connects, 0) + COALESCE(table_8.connects, 0) + COALESCE(table_10.connects, 0) + COALESCE(table_12.connects, 0)) AS total_connects
FROM    people p
LEFT JOIN
        table_2
ON      table_2.id = people.id
LEFT JOIN
        table_4
ON      people.id = table_4.id
LEFT JOIN
        table_6
ON      people.id = table_6.id
LEFT JOIN
        table_8
ON      people.id = table_8.id
LEFT JOIN
        table_10
ON      people.id = table_10.id
LEFT JOIN
        table_12
ON      people.id = table_12.id
GROUP BY
        people.authid
ORDER BY
        total_time DESC


问:
How to return 2 values and rounding them? Excel VBA
I am working on a code that should calculate simple foundations, and in order to do that I have to return 2 values with my function -preferably in two different columns.

```<code>Function FundacaoSimples(b, l, carga) As Variant

tensao = Sheets("Tabelas e Constantes").Range("tensao").Value

Dim area As Double
Dim Bs As Single
Dim Ls As Single
Dim Resultado(1 To 2) As String

If b = l Then
    area = (1.1 * carga) / tensao
    Bs = Sqr(area)
    Ls = Bs
ElseIf b <> l Then
    area = (1.1 * carga) / tensao
    Bs = Sqr((2 * area) / 3)
    Ls = (3 * Bs) / 2
End If

Resultado(1) = Round(Bs, 2)
Resultado(2) = Round(Ls, 2)

FundacaoSimples = (Resultado(1) & " / " & Resultado(2))

End Function
</code>```

This rounding I am using it just to get a value rounded with 2 decimals, e.g: 2,73 to 2,75; 0,89 to 0,90.
I tried working with ActiveCells.Offset(0,1), but the statement isn't valid.
Is it possible to to just jump one column to the right?

答:
In general, functions should not be writing values or accessing values from a spreadsheet. They should access their parameters and return result.
Try like this, an oversimplified version of what you need:

```<code>Option Explicit

Public Sub TestMe()

    ActiveCell = FundacaoSimples(0)
    ActiveCell.Offset(0, 1) = FundacaoSimples(1)

End Sub

Function FundacaoSimples() As Variant

    ReDim varResult(1)

    varResult(0) = 55
    varResult(1) = 100

    FundacaoSimples = varResult

End Function
</code>```

Then you can edit the function a bit with your own parameters and use it further.

Body:
I am working on a code that should calculate simple foundations, and in order to do that I have to return 2 values with my function -preferably in two different columns.

Function FundacaoSimples(b, l, carga) As Variant

tensao = Sheets("Tabelas e Constantes").Range("tensao").Value

Dim area As Double
Dim Bs As Single
Dim Ls As Single
Dim Resultado(1 To 2) As String

If b = l Then
    area = (1.1 * carga) / tensao
    Bs = Sqr(area)
    Ls = Bs
ElseIf b <> l Then
    area = (1.1 * carga) / tensao
    Bs = Sqr((2 * area) / 3)
    Ls = (3 * Bs) / 2
End If

Resultado(1) = Round(Bs, 2)
Resultado(2) = Round(Ls, 2)

FundacaoSimples = (Resultado(1) & " / " & Resultado(2))

End Function

This rounding I am using it just to get a value rounded with 2 decimals, e.g: 2,73 to 2,75; 0,89 to 0,90.
I tried working with ActiveCells.Offset(0,1), but the statement isn't valid.
Is it possible to to just jump one column to the right?

Body:
In general, functions should not be writing values or accessing values from a spreadsheet. They should access their parameters and return result.
Try like this, an oversimplified version of what you need:

Option Explicit

Public Sub TestMe()

    ActiveCell = FundacaoSimples(0)
    ActiveCell.Offset(0, 1) = FundacaoSimples(1)

End Sub

Function FundacaoSimples() As Variant

    ReDim varResult(1)

    varResult(0) = 55
    varResult(1) = 100

    FundacaoSimples = varResult

End Function

Then you can edit the function a bit with your own parameters and use it further.


问:
Java loading JAR dynamically: NoClassDefFoundError
Let's say I have a main class App that loads all jars in the sub-directory plugins using a URLClassLoader:

```<code>public class App(){
    public static void main(String[] args){
        for(File f : new File("plugins").listFiles()){
                URL[] urls = { new URL("jar:file:" + "plugins/" + f.getName() + ".jar" + "!/") };
                URLClassLoader cl = URLClassLoader.newInstance(urls);

                Class<?> clazz = cl.loadClass(f.getName().toLowerCase()+"."+f.getName());
                cl.close();
                Plugin p = ((Plugin) clazz.newInstance());
        }
    }
}
</code>```

All those jars contain a class that implements an interface Plugin.

```<code>+-- Main.jar
|    +-- App.class
|    +-- Plugin.class
|
+-- Plugins/
|    +-- PluginTest.jar
|         +-- plugintest
|              +-- PluginTest.class
|              +-- Two.class
</code>```

That's all working fine if I write my code just in the PluginTest class. But as soon as I try to access Two from PluginTest, I'm getting a big error:

```<code>Exception in thread "Thread-4" java.lang.NoClassDefFoundError: plugintest/Two
[...]
</code>```

How should I load the the class correctly? Need help! Thanks.

答:
Do not close your classloader.

Remove cl.close();statement.

Body:
Let's say I have a main class App that loads all jars in the sub-directory plugins using a URLClassLoader:

public class App(){
    public static void main(String[] args){
        for(File f : new File("plugins").listFiles()){
                URL[] urls = { new URL("jar:file:" + "plugins/" + f.getName() + ".jar" + "!/") };
                URLClassLoader cl = URLClassLoader.newInstance(urls);

                Class<?> clazz = cl.loadClass(f.getName().toLowerCase()+"."+f.getName());
                cl.close();
                Plugin p = ((Plugin) clazz.newInstance());
        }
    }
}

All those jars contain a class that implements an interface Plugin.

+-- Main.jar
|    +-- App.class
|    +-- Plugin.class
|
+-- Plugins/
|    +-- PluginTest.jar
|         +-- plugintest
|              +-- PluginTest.class
|              +-- Two.class

That's all working fine if I write my code just in the PluginTest class. But as soon as I try to access Two from PluginTest, I'm getting a big error:

Exception in thread "Thread-4" java.lang.NoClassDefFoundError: plugintest/Two
[...]

How should I load the the class correctly? Need help! Thanks.


问:
ReporteRs FlexTable taking ages on Windows Server 2012 R2
The University I work for has just switched to Windows Server 2012 R2 and I am finding that the FlexTable command on ReporteRs takes extremely long to run; where previously it would have taken less than a minute, it is now taking over 15 minutes.

Is there a known issue anyone is aware of?

答: Wait until the end of the operation, package gdtools is scanning your system fonts as it didn't find any available list when starting. It should only happen once</p>


答: @afonso: I think you should populate all those time tables whenever a new user is created by inserting the user with a time of 0 (just so that they're in the table). Would this be an acceptable compromise for your application just to have those users in the tables so your initial query will work?</p>

Title: MYSQL Query - Some results don't return


问:
Error 500 Internal Server Error Whenever I Deploy BlogEngine.NET To Remote Server
Each time I deploy BlogEngine on a remote server on IIS, I get Error 500 - Internal Server Error, anytime I try creating a new post. I have followed procedures on deploying BlogEngine on IIS (here), i have created the NETWORK SERVICE property and given it permissions in the App_Data folder. I even gave permissions to the IIS_USR property on the remote server.

I try making a post on BlogEngine, I get an Error making post toastr message. Whereas this same project works without any hindrance on my local computer.

I narrowed the post action to postEditController.js, to the $scope.save() function but I'm not getting any stack trace whatsoever in Inspect Element.

答: Error 500 - Internal Server Error usually pops up when you are using incorrect version of .net framework. Check the application pool is 4.0 or 4.5 and app pool is running.</p>


问:
trouble making an "if" statment with time.now on ruby on rails
I'm trying to display a message depending on the time of the day and I currently have this piece of code:

```<code><% if Time.now >= "7:00" and Time.now <= "14:00" %>
Good Morning <%= current_user.nome %>! <br>
<% else %>
Good Afternoon <%= current_user.nome %>!
<% end %>
</code>```

It's currently 14:30 and the page still displays Good Morning (username), when it should display Good Evening (username)

Is my code wrong?

How do I fix this?

答:
I think this is worth it to be a helper method:

```<code># in app/helpers/application_helper.rb
def greeting(name)
  greeting = (7..13).cover?(Time.current.hour) ? 'Good Morning' : 'Good Afternoon'

  "#{greeting} #{name}".strip
end
</code>```

And in your view:

```<code><%= greeting(current_user.nome) %>!
</code>```

Another more detailed version that supports uneven times might look like this:

```<code>def greeting(name)
  greeting = case Time.current.to_s(:time)
             when ('05:00'..'11:59') then 'Good Morning'
             when ('12:00'..'17:59') then 'Good Afternoon'
             when ('18:00'..'21:59') then 'Good Evening'
             else 'Good Night'
             end
  "#{greeting} #{name}".strip
end
</code>```

Body:
I'm trying to display a message depending on the time of the day and I currently have this piece of code:

<% if Time.now >= "7:00" and Time.now <= "14:00" %>
Good Morning <%= current_user.nome %>!

<% else %>
Good Afternoon <%= current_user.nome %>!
<% end %>

It's currently 14:30 and the page still displays Good Morning (username), when it should display Good Evening (username)

Is my code wrong?

How do I fix this?

Body:
I think this is worth it to be a helper method:

# in app/helpers/application_helper.rb
def greeting(name)
  greeting = (7..13).cover?(Time.current.hour) ? 'Good Morning' : 'Good Afternoon'

  "#{greeting} #{name}".strip
end

And in your view:

<%= greeting(current_user.nome) %>!

Another more detailed version that supports uneven times might look like this:

def greeting(name)
  greeting = case Time.current.to_s(:time)
             when ('05:00'..'11:59') then 'Good Morning'
             when ('12:00'..'17:59') then 'Good Afternoon'
             when ('18:00'..'21:59') then 'Good Evening'
             else 'Good Night'
             end
  "#{greeting} #{name}".strip
end


问:
Offline Storage Vs Service Worker for a Progressive Web App
My app saves the data (product catalog) in the Offline storage IndexedDB and read it from there whenever necessary. Instead of using custom JavaScript to save and retrieve the data from the IndexedDB, can I use Service Worker to get the same results?</p>

答:
Service Workers are developed using "custom" JavaScript, so there would be no difference for your code.

But you could keep your current JavaScript, and cache it with a Service Worker for offline.


问:
python script in linux shell that checks if a command line writes into file
I'm writing a python script that print output into the screen (linux shell), and I'm printing it with colors.
Is there a way to know if the output goes into a file or not?

Example:

```<code>script.py parms
</code>```

this gives me good colored output in the shell

Now if I do this:

```<code>script.py parms > output.txt
</code>```

when I open the file I see weird ASCII characters (the colors values), I've tried to open it in a few text editors (kate, gedit).

I want to do something like:

```<code>if goesIntoFile:
  print in black
else:
  print in color
</code>```

How can I do it?

答:
You could use isatty() on your stdout to check if the standard output is a tty (terminal) device, or a file.

Check this script.py:

```<code>#!/usr/bin/env python
import sys
print sys.stdout.isatty()
</code>```

When run:

```<code>$ python script.py
True
$ python script.py | cat
False
</code>```

Also, you might want to check some of the color-output libraries which handle this for you, for example crayons uses the isatty approach above.

Body:
I'm writing a python script that print output into the screen (linux shell), and I'm printing it with colors.
Is there a way to know if the output goes into a file or not?

Example:

script.py parms

this gives me good colored output in the shell

Now if I do this:

script.py parms > output.txt

when I open the file I see weird ASCII characters (the colors values), I've tried to open it in a few text editors (kate, gedit).

I want to do something like:

if goesIntoFile:
  print in black
else:
  print in color

How can I do it?

Body:
You could use isatty() on your stdout to check if the standard output is a tty (terminal) device, or a file.

Check this script.py:

#!/usr/bin/env python
import sys
print sys.stdout.isatty()

When run:

$ python script.py
True
$ python script.py | cat
False

Also, you might want to check some of the color-output libraries which handle this for you, for example crayons uses the isatty approach above.


问:
Apache Drill crash immediately on lunch
I have an issue with my drill cluster, my drill cluster have 1 master node and 4 nodes.

I have stopped each one of drill nodes

```<code>sudo -i /home/hadoop/apache-drill-1.10.0/bin/drillbit.sh stop
</code>```

and started it

```<code>sudo -i /home/hadoop/apache-drill-1.10.0/bin/drillbit.sh start
</code>```

I have no clue what to do, have tried searching online but nothing seems related beside this link which didnt solve my issue

```<code>    2017-07-04 13:09:10,454 [main] INFO  o.apache.drill.exec.server.Drillbit - Construction completed (2928 ms).
    2017-07-04 13:09:10,864 [main] INFO  o.a.drill.exec.rpc.user.UserServer - User Error Occurred: Drillbit could not bind to port 31010. (Address already in use)
    org.apache.drill.common.exceptions.UserException: RESOURCE ERROR: Drillbit could not bind to port 31010.

    Server type UserServer

    [Error Id: a75dd2ec-a3b6-4fcb-b60b-0a1a63354943 ]

................
................
org.apache.drill.common.AutoCloseables.close(AutoCloseables.java:64) ~[drill-common-1.10.0.jar:1.10.0]
            at org.apache.drill.exec.server.Drillbit.close(Drillbit.java:159) [drill-java-exec-1.10.0.jar:1.10.0]
            at org.apache.drill.exec.server.Drillbit.start(Drillbit.java:294) [drill-java-exec-1.10.0.jar:1.10.0]
            at org.apache.drill.exec.server.Drillbit.start(Drillbit.java:271) [drill-java-exec-1.10.0.jar:1.10.0]
            at org.apache.drill.exec.server.Drillbit.main(Drillbit.java:267) [drill-java-exec-1.10.0.jar:1.10.0]
    2017-07-04 13:09:11,919 [main] INFO  o.apache.drill.exec.server.Drillbit - Shutdown completed (1053 ms).
</code>```

Would love to get input for how to solve it

how can i find the reason for this:
Drillbit could not bind to port 31010. (Address already in use

答:
It appeared that i had a zombie task on my ec2 instance locking port 31010

so i killed that pid task
by this:

```<code>netstat -tulp | grep LIST | grep 31010
</code>```

return

```<code>tcp        0      0 *:31010                     *:*                         LISTEN      16449/java
</code>```

and now for the finisher

```<code>kill -9 16449
</code>```

Title: Apache Drill crash immediately on lunch

Body:
I have an issue with my drill cluster, my drill cluster have 1 master node and 4 nodes.

I have stopped each one of drill nodes

sudo -i /home/hadoop/apache-drill-1.10.0/bin/drillbit.sh stop

and started it

sudo -i /home/hadoop/apache-drill-1.10.0/bin/drillbit.sh start

I have no clue what to do, have tried searching online but nothing seems related beside this link which didnt solve my issue

    2017-07-04 13:09:10,454 [main] INFO  o.apache.drill.exec.server.Drillbit - Construction completed (2928 ms).
    2017-07-04 13:09:10,864 [main] INFO  o.a.drill.exec.rpc.user.UserServer - User Error Occurred: Drillbit could not bind to port 31010. (Address already in use)
    org.apache.drill.common.exceptions.UserException: RESOURCE ERROR: Drillbit could not bind to port 31010.

    Server type UserServer

    [Error Id: a75dd2ec-a3b6-4fcb-b60b-0a1a63354943 ]

................
................
org.apache.drill.common.AutoCloseables.close(AutoCloseables.java:64) ~[drill-common-1.10.0.jar:1.10.0]
            at org.apache.drill.exec.server.Drillbit.close(Drillbit.java:159) [drill-java-exec-1.10.0.jar:1.10.0]
            at org.apache.drill.exec.server.Drillbit.start(Drillbit.java:294) [drill-java-exec-1.10.0.jar:1.10.0]
            at org.apache.drill.exec.server.Drillbit.start(Drillbit.java:271) [drill-java-exec-1.10.0.jar:1.10.0]
            at org.apache.drill.exec.server.Drillbit.main(Drillbit.java:267) [drill-java-exec-1.10.0.jar:1.10.0]
    2017-07-04 13:09:11,919 [main] INFO  o.apache.drill.exec.server.Drillbit - Shutdown completed (1053 ms).

Would love to get input for how to solve it

how can i find the reason for this:
Drillbit could not bind to port 31010. (Address already in use

Body:
It appeared that i had a zombie task on my ec2 instance locking port 31010

so i killed that pid task
by this:

netstat -tulp | grep LIST | grep 31010

return

tcp        0      0 *:31010                     *:*                         LISTEN      16449/java

and now for the finisher

kill -9 16449


答:
I think a good way to do this may be:

```<code>SELECT id, SUM(time), SUM(connects)
FROM (
    SELECT id, time, connects FROM table_2
UNION ALL
    SELECT id, time, connects FROM table_4
UNION ALL
    SELECT id, time, connects FROM table_6
UNION ALL
    SELECT id, time, connects FROM table_8
UNION ALL
    SELECT id, time, connects FROM table_10
UNION ALL
    SELECT id, time, connects FROM table_12
) uniontable
GROUP BY id
</code>```

Since they all have the same fields.

EDIT: And it sounds like it may not be such a strange idea to merge them into one table, especially if you want to count the total time like this ;)

EDIT 2: I'm sorry, that wasn't valid SQL at all. This should be better.

Title: MYSQL Query - Some results don't return

Body:
I think a good way to do this may be:

SELECT id, SUM(time), SUM(connects)
FROM (
    SELECT id, time, connects FROM table_2
UNION ALL
    SELECT id, time, connects FROM table_4
UNION ALL
    SELECT id, time, connects FROM table_6
UNION ALL
    SELECT id, time, connects FROM table_8
UNION ALL
    SELECT id, time, connects FROM table_10
UNION ALL
    SELECT id, time, connects FROM table_12
) uniontable
GROUP BY id

Since they all have the same fields.

EDIT: And it sounds like it may not be such a strange idea to merge them into one table, especially if you want to count the total time like this ;)

EDIT 2: I'm sorry, that wasn't valid SQL at all. This should be better.


问:
Select Input on Label Click
I want to search data
but i have multiple label like firstname,lastname and Username
and only one input
i want to place different placeholder based on the label clicked
how this possible with jquery and javascript

Thanks In Advance

答:
You can use jQuery.attr():

$('label').on('click', function () {
   $('input#text').attr('placeholder', $(this).text());
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>label, input {display: block;}</code>```

Firstname
Lastname
Username
<input id="text" type="text">```

Title: Select Input on Label Click

Body:
You can use jQuery.attr():

$('label').on('click', function () {
   $('input#text').attr('placeholder', $(this).text());
});

label, input {display: block;}

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

<label>Firstname</label>
<label>Lastname</label>
<label>Username</label>
<input id="text" type="text">


问:
how combine multiple arrays into a single associate array using the arrays as keys
I have 2 arrays that i would like to loop through and combine into an associative array. I would like to use the 2 arrays as the keys for the new associative array. I am new to php so any and all help would be appreciated.

```<code>$id = array( 2, 4);

$qty = array( 5, 7);

array('id' => , 'qty' => );
</code>```

Thanks in advance

I would like to output something like this

```<code>array(
'id' => 2,
'qty' => 5),
array(
'id'=> 4,
'qty' => 7
)
</code>```

答:
Also one-liner w/ lambda (PHP >= 5.3.0) and short array syntax [] (PHP >= 5.4)

```<code>$combined = array_map(function($id, $qty) {return ['id' => $id, 'qty' => $qty];}, $id, $qty);
</code>```

or callback and old array() for earlier versions

```<code>function comb($id, $qty)
{
    return array('id' => $id, 'qty' => $qty);
}
$combined = array_map('comb', $id, $qty);
</code>```

Body:
I have 2 arrays that i would like to loop through and combine into an associative array. I would like to use the 2 arrays as the keys for the new associative array. I am new to php so any and all help would be appreciated.

$id = array( 2, 4);

$qty = array( 5, 7);

array('id' => , 'qty' => );

Thanks in advance

I would like to output something like this

array(
'id' => 2,
'qty' => 5),
array(
'id'=> 4,
'qty' => 7
)

Body:
Also one-liner w/ lambda (PHP >= 5.3.0) and short array syntax [] (PHP >= 5.4)

$combined = array_map(function($id, $qty) {return ['id' => $id, 'qty' => $qty];}, $id, $qty);

or callback and old array() for earlier versions

function comb($id, $qty)
{
    return array('id' => $id, 'qty' => $qty);
}
$combined = array_map('comb', $id, $qty);


问:
When to use each type of loop?
I'm learning the basics of programming here (C#) but I think this question is generic in its nature.

What are some simple practical situations that lend themselves closer to a particular type of loop?

The while and for loops seem pretty similar and there are several SO questions addressing the differences between the two. How about foreach? From my basic understanding, its seems I ought to be able to do everything a foreach loop does within a for loop.

答:
when you know how many iterations there will be use for

when you don't know use while, when don't know and need to execute code at least once use do

when you iterate through collection and don't need index use foreach
(also you can not use collection[i] on everything that you can use foreach on)

Title: When to use each type of loop?


问:
OpenGL: How are base vectors laid out in memory
this topic has been discussed quite a few times. There are a lot of information on the memory layout of matrices in OpenGL on the internet. Sadly different sources often contradict each other.

My question boils down to:

When I have three base vectors of my matrix bx, by and bz. If I want to make a matrix out of them to plug them into a shader, how are they laid out in memory?

Lets clarify what I mean by base vector, because I suspect this can also mean different things:

When I have a 3D model, that is Z-up and I want to lay it down flat in my world space along the X-axis, then bz is [1 0 0]. I.e. a vertex [0 0 2] in model space will be transformed to [2 0 0] when that vertex is multiplied by my matrix that has bz as the base vector for the Z-axis.

Coming to OpenGL matrix memory layout:

According to the GLSL spec (GLSL Spec p.110) it says:

```<code>vec3 v, u;
mat3 m;
u = v * m;

is equivalent to

u.x = dot(v, m[0]); // m[0] is the left column of m
u.y = dot(v, m[1]); // dot(a,b) is the inner (dot) product of a and b
u.z = dot(v, m[2]);
</code>```

So, in order to have best performance, I should premultiply my vertices in the vertex shader (that way the GPU can use the dot product and so on):

```<code>attribute vec4 vertex;
uniform mat4 mvp;
void main()
{
    gl_Position = vertex * mvp;
}
</code>```

Now OpenGL is said to be column-major (GLSL Spec p 101). I.e. the columns are laid out contiguously in memory:

```<code>[ column 0 | column 1 | column 2  | column 3    ]
[ 0 1 2 3  | 4 5 6 7  | 8 9 10 11 | 12 13 14 15 ]
</code>```

or:

```<code>[
    0  4  8 12,
    1  5  9 13,
    2  6 10 14,
    3  7 11 15,
]
</code>```

This would mean that I have to store my base vectors in the rows like this:

```<code>bx.x bx.y bx.z 0
by.x by.y by.z 0
bz.x bz.y bz.z 0
0    0    0    1
</code>```

So for my example with the 3D model that I want to lay flat down, it has the base vectors:

```<code>bx = [0 0 -1]
by = [0 1  0]
bz = [1 0  0]
</code>```

The model vertex [0 0 2] from above would be transformed like dis in the vertex shader:

```<code>// m[0] is [ 0 0 1 0]
// m[1] is [ 0 1 0 0]
// m[2] is [-1 0 0 0]
// v    is [ 0 0 2 1]
u.x = dot([ 0 0 2 1], [ 0 0 1 0]);
u.y = dot([ 0 0 2 1], [ 0 1 0 0]);
u.z = dot([ 0 0 2 1], [-1 0 0 0]);
// u    is [ 2 0 0]
</code>```

Just as expected!

On the contrary:

This: Correct OpenGL matrix format?
SO question and consequently the OpenGL Faq states:

For programming purposes, OpenGL matrices are 16-value arrays with base vectors laid out contiguously in memory. The translation components occupy the 13th, 14th, and 15th elements of the 16-element matrix, where indices are numbered from 1 to 16 as described in section 2.11.2 of the OpenGL 2.1 Specification.

This says that my base vectors should be laid out in columns like this:

```<code>bx.x by.x bz.x 0
bx.y by.y bz.y 0
bx.z by.z bz.z 0
0    0    0    1
</code>```

To me these two sources which both are official documentation from Khronos seem to contradict each other.

Can somebody explain this to me? Have I made a mistake? Is there indeed some wrong information?

答:
The FAQ is correct, it should be:

```<code>bx.x by.x bz.x 0
bx.y by.y bz.y 0
bx.z by.z bz.z 0
0    0    0    1
</code>```

and it's your reasoning that is flawed.

Assuming that your base vectors bx, by, bz are the model basis given in world coordinates, then the transformation from the model-space vertex v to the world space vertex Bv is given by linear combination of the base vectors:

```<code>B*v = bx*v.x + by*v.y + bz*v.z
</code>```

It is not a dot product of b with v. Instead it's the matrix multiplication where B is of the above form.

Taking a dot product of a vertex u with bx would answer the inverse question: given a world-space u what would be its coordinates in the model space along the axis bx? Therefore multiplying by the transposed matrix transpose(B) would give you the transformation from world space to model space.

Body:
this topic has been discussed quite a few times. There are a lot of information on the memory layout of matrices in OpenGL on the internet. Sadly different sources often contradict each other.

My question boils down to:

When I have three base vectors of my matrix bx, by and bz. If I want to make a matrix out of them to plug them into a shader, how are they laid out in memory?

Lets clarify what I mean by base vector, because I suspect this can also mean different things:

When I have a 3D model, that is Z-up and I want to lay it down flat in my world space along the X-axis, then bz is [1 0 0]. I.e. a vertex [0 0 2] in model space will be transformed to [2 0 0] when that vertex is multiplied by my matrix that has bz as the base vector for the Z-axis.

Coming to OpenGL matrix memory layout:

According to the GLSL spec (GLSL Spec p.110) it says:

vec3 v, u;
mat3 m;
u = v * m;

is equivalent to

u.x = dot(v, m[0]); // m[0] is the left column of m
u.y = dot(v, m[1]); // dot(a,b) is the inner (dot) product of a and b
u.z = dot(v, m[2]);

So, in order to have best performance, I should premultiply my vertices in the vertex shader (that way the GPU can use the dot product and so on):

attribute vec4 vertex;
uniform mat4 mvp;
void main()
{
    gl_Position = vertex * mvp;
}

Now OpenGL is said to be column-major (GLSL Spec p 101). I.e. the columns are laid out contiguously in memory:

[ column 0 | column 1 | column 2  | column 3    ]
[ 0 1 2 3  | 4 5 6 7  | 8 9 10 11 | 12 13 14 15 ]

or:

[
    0  4  8 12,
    1  5  9 13,
    2  6 10 14,
    3  7 11 15,
]

This would mean that I have to store my base vectors in the rows like this:

bx.x bx.y bx.z 0
by.x by.y by.z 0
bz.x bz.y bz.z 0
0    0    0    1

So for my example with the 3D model that I want to lay flat down, it has the base vectors:

bx = [0 0 -1]
by = [0 1  0]
bz = [1 0  0]

The model vertex [0 0 2] from above would be transformed like dis in the vertex shader:

// m[0] is [ 0 0 1 0]
// m[1] is [ 0 1 0 0]
// m[2] is [-1 0 0 0]
// v    is [ 0 0 2 1]
u.x = dot([ 0 0 2 1], [ 0 0 1 0]);
u.y = dot([ 0 0 2 1], [ 0 1 0 0]);
u.z = dot([ 0 0 2 1], [-1 0 0 0]);
// u    is [ 2 0 0]

Just as expected!

On the contrary:

This: Correct OpenGL matrix format?
SO question and consequently the OpenGL Faq states:

For programming purposes, OpenGL matrices are 16-value arrays with base vectors laid out contiguously in memory. The translation components occupy the 13th, 14th, and 15th elements of the 16-element matrix, where indices are numbered from 1 to 16 as described in section 2.11.2 of the OpenGL 2.1 Specification.

This says that my base vectors should be laid out in columns like this:

bx.x by.x bz.x 0
bx.y by.y bz.y 0
bx.z by.z bz.z 0
0    0    0    1

To me these two sources which both are official documentation from Khronos seem to contradict each other.

Can somebody explain this to me? Have I made a mistake? Is there indeed some wrong information?

Body:
The FAQ is correct, it should be:

bx.x by.x bz.x 0
bx.y by.y bz.y 0
bx.z by.z bz.z 0
0    0    0    1

and it's your reasoning that is flawed.

Assuming that your base vectors bx, by, bz are the model basis given in world coordinates, then the transformation from the model-space vertex v to the world space vertex Bv is given by linear combination of the base vectors:

B*v = bx*v.x + by*v.y + bz*v.z

It is not a dot product of b with v. Instead it's the matrix multiplication where B is of the above form.

Taking a dot product of a vertex u with bx would answer the inverse question: given a world-space u what would be its coordinates in the model space along the axis bx? Therefore multiplying by the transposed matrix transpose(B) would give you the transformation from world space to model space.


问:
Solr - limit the number of results from a certain type
I wonder if I can limit the number of results from a certain type.

For example, I make a search for 40 results, I want to get maximum 4 docs marked as 'promoted'. Assume that I have a boolean field, which indicates if the document should be promoted or not (promoted: true\false).

Is there a way to do so?

答:
the best way would be by using the DiversifiedTopDocsCollector, but it has not been exposed at Solr level yet.

The other alternative is to use grouping or collapsing and try to achieve what you need with the params.


问:
Jquery Check if Array contains empty entry
I have an array : var list = ["",""];that will be filled with strings.

Before I let the user do something, I would like to make sure the array doesn't contain anymore empty entry.

I made a special function that I would like to work like that:

```<code>function checkEmptryEntry(array_name)
{
   if(arrayContainsEmptyEntry(array_name))
   {
      return "bad";
   }

   else
   {
      return "good";
   }
}
</code>```

How could I do that ?

答:
Assuming you have used jquery, you can use inArray:

```<code>return (!jQuery.inArray("", array_name) ? "good" : "bad");
</code>```

Using native javascript, You can use indexOf to find first position of empty string. if it return -1, then array have no empty string:

```<code>return (array_name.indexOf("") == -1 ? "good" : "bad" ) ;
</code>```

Body:
I have an array : var list = ["",""];that will be filled with strings.

Before I let the user do something, I would like to make sure the array doesn't contain anymore empty entry.

I made a special function that I would like to work like that:

function checkEmptryEntry(array_name)
{
   if(arrayContainsEmptyEntry(array_name))
   {
      return "bad";
   }

   else
   {
      return "good";
   }
}

How could I do that ?

Body:
Assuming you have used jquery, you can use inArray:

return (!jQuery.inArray("", array_name) ? "good" : "bad");

Using native javascript, You can use indexOf to find first position of empty string. if it return -1, then array have no empty string:

return (array_name.indexOf("") == -1 ? "good" : "bad" ) ;


问:
How to get the current day and last day of the current month
I'm just a beginner !! I need a html number input, with today's day of the month as the minimum value and number of day's of the current month as the maximum value.

In PHP I declare $today = date ('Y-m-d,time()); to read the date today  and i don't know how to declare the value of the day of the month in <Input type="number" min="" max="" /> as a minimum number?

答:
If I read your question correctly, you need a html input that represents a day of the month. And you want the minimum value to be today.

If so:

You can format your date and use that as value.

```<code>$today = new DateTime();
// Day of the month, 2 digits with leading zeros
$day_today; = $today->format('d');
// OR
//  Day of the month without leading zeros
$day_today; = $today->format('J');

//  Last day of the given month in datetime
$last_day; = $today->format('t');

Choose day:<input type="number" min="<?php echo $day_today; ?>" max="<?php echo $last_day; ?>" />
</code>```

Body:
If I read your question correctly, you need a html input that represents a day of the month. And you want the minimum value to be today.

If so:

You can format your date and use that as value.

$today = new DateTime();
// Day of the month, 2 digits with leading zeros
$day_today; = $today->format('d');
// OR
//  Day of the month without leading zeros
$day_today; = $today->format('J');

//  Last day of the given month in datetime
$last_day; = $today->format('t');

Choose day:<input type="number" min="<?php echo $day_today; ?>" max="<?php echo $last_day; ?>" />


问:
Parsing strings representing lists of integers and integer spans
I am looking for a function that parses integer lists in Emacs Lisp, along the lines of Perl's Set::IntSpan.  I.e., I would like to be able to do something like this:

```<code>(parse-integer-list "1-3, 4, 8, 18-21")
⇒ (1 2 3 4 8 18 19 20 21)
</code>```

Is there an elisp library somewhere for this?

答:
The following does what you want:

```<code>(defun parse-integer-list (str)
  "Parse string representing a range of integers into a list of integers."
  (let (start ranges)
    (while (string-match "\\([0-9]+\\)\\(?:-\\([0-9]+\\)\\)?" str start)
      (push
       (apply 'number-sequence
              (seq-map 'string-to-int
                       (seq-filter
                        'identity
                        (list (match-string 1 str) (match-string 2 str)))))
            ranges)
        (setq start (match-end 0)))
    (nreverse (seq-mapcat 'nreverse ranges))))
</code>```

The code loops over the incoming string searching for plain numbers or ranges of numbers. On each match it calls number-sequence with either just a number for a plain match or two numbers for a range match and pushes each resulting number sequence into a list. To account for push building the result backwards, at the end it reverses all ranges in the list, concatenates them, then reverses the result and returns it.

Calling parse-integer-list with your example input:

```<code>(parse-integer-list "1-3, 4, 8, 18-21")
</code>```

produces:

```<code>(1 2 3 4 8 18 19 20 21)
</code>```

Body:
I am looking for a function that parses integer lists in Emacs Lisp, along the lines of Perl's Set::IntSpan.  I.e., I would like to be able to do something like this:

(parse-integer-list "1-3, 4, 8, 18-21")
⇒ (1 2 3 4 8 18 19 20 21)

Is there an elisp library somewhere for this?

Body:
The following does what you want:

(defun parse-integer-list (str)
  "Parse string representing a range of integers into a list of integers."
  (let (start ranges)
    (while (string-match "\\([0-9]+\\)\\(?:-\\([0-9]+\\)\\)?" str start)
      (push
       (apply 'number-sequence
              (seq-map 'string-to-int
                       (seq-filter
                        'identity
                        (list (match-string 1 str) (match-string 2 str)))))
            ranges)
        (setq start (match-end 0)))
    (nreverse (seq-mapcat 'nreverse ranges))))

The code loops over the incoming string searching for plain numbers or ranges of numbers. On each match it calls number-sequence with either just a number for a plain match or two numbers for a range match and pushes each resulting number sequence into a list. To account for push building the result backwards, at the end it reverses all ranges in the list, concatenates them, then reverses the result and returns it.

Calling parse-integer-list with your example input:

(parse-integer-list "1-3, 4, 8, 18-21")

produces:

(1 2 3 4 8 18 19 20 21)


问:
Defining template and style together within the button
I have WPF button below:

```<code><Button Name="btnAdd" Click="btnAdd_Click">
    <Button.Template>
        <ControlTemplate>
            <StackPanel Orientation="Vertical">
                <Image Height="20" Width="20" Stretch="UniformToFill" Source="./Resources/Add.png"/>
                <Label HorizontalAlignment="Center">Add</Label>
            </StackPanel>
        </ControlTemplate>
    </Button.Template>
</Button>
</code>```

Now within the wpf button I am trying to add the following style, I mean, combining style with template in the button:

```<code><Button>
    <Button.Style>
        <Style TargetType="Button" BasedOn="{StaticResource MyStyle}">
            <Style.Triggers>
                <Trigger Property="IsPressed" Value="True">
                    <Setter Property="Foreground" Value="Green" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>
</code>```

How can I do this?

答:
One way could be adding a Setter to your Style for Template property. Like this:

```<code><Button.Style>
    <Style TargetType="Button" BasedOn="{StaticResource MyStyle}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <StackPanel Orientation="Vertical">
                        <Image Height="20" Width="20" Stretch="UniformToFill" Source="./Resources/Add.png"/>
                        <Label HorizontalAlignment="Center">Add</Label>
                    </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsPressed" Value="True">
                <Setter Property="Foreground" Value="Green" />
            </Trigger>
        </Style.Triggers>
    </Style>
</Button.Style>
</code>```

Body:
I have WPF button below:

<Button Name="btnAdd" Click="btnAdd_Click">
    <Button.Template>
        <ControlTemplate>
            <StackPanel Orientation="Vertical">
                <Image Height="20" Width="20" Stretch="UniformToFill" Source="./Resources/Add.png"/>
                Add
            </StackPanel>
        </ControlTemplate>
    </Button.Template>
</Button>

Now within the wpf button I am trying to add the following style, I mean, combining style with template in the button:

<Button>
    <Button.Style>

        </Style>
    </Button.Style>
</Button>

How can I do this?

Body:
One way could be adding a Setter to your Style for Template property. Like this:

<Button.Style>
    <Style TargetType="Button" BasedOn="{StaticResource MyStyle}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <StackPanel Orientation="Vertical">
                        <Image Height="20" Width="20" Stretch="UniformToFill" Source="./Resources/Add.png"/>
                        <Label HorizontalAlignment="Center">Add</Label>
                    </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsPressed" Value="True">
                <Setter Property="Foreground" Value="Green" />
            </Trigger>
        </Style.Triggers>
    </Style>
</Button.Style>


问:
How to try-except an illegal matrix operation due to singularity in NumPy
In NumPy, I'm trying to use linalg to compute matrix inverses at each step of a Newton-Raphson scheme (the problem size is small intentionally so that we can invert analytically computed Hessian matrices). However, after I get far along towards convergence, the Hessian gets close to singular.

Is there any method within NumPy that lets me test whether a matrix is considered singular (computing determinant is not robust enough)? Ideally, it would be nice if there's a way to use a try except block to catch NumPy's singular array error.

How would I do this? The NumPy error given at the terminal is:

```<code>raise LinAlgError, 'Singular matrix'
numpy.linalg.linalg.LinAlgError: Singular matrix
</code>```

答:
wim's answer no longer works for current versions of NumPy (I'm using 1.13 at the time of writing). Instead do:</p>

```<code>import numpy as np

try:
    # your code that will (maybe) throw
except np.linalg.LinAlgError as e:
    if 'Singular matrix' in str(e):
        # your error handling block
    else:
        raise
</code>```

Body:
In NumPy, I'm trying to use linalg to compute matrix inverses at each step of a Newton-Raphson scheme (the problem size is small intentionally so that we can invert analytically computed Hessian matrices). However, after I get far along towards convergence, the Hessian gets close to singular.

Is there any method within NumPy that lets me test whether a matrix is considered singular (computing determinant is not robust enough)? Ideally, it would be nice if there's a way to use a try except block to catch NumPy's singular array error.

How would I do this? The NumPy error given at the terminal is:

raise LinAlgError, 'Singular matrix'
numpy.linalg.linalg.LinAlgError: Singular matrix

Body:
wim's answer no longer works for current versions of NumPy (I'm using 1.13 at the time of writing). Instead do:

import numpy as np

try:
    # your code that will (maybe) throw
except np.linalg.LinAlgError as e:
    if 'Singular matrix' in str(e):
        # your error handling block
    else:
        raise


问:
How to create drop down list of all user in MVC5
I have a few users with  roles created in my MVC 5 application. I have a ticket Model which contains basic ticket info. But now I want to add a property called "Assigned To" to this ticket Model and I want to assign this property value to the users available.

In my view I want to have a drop down list of all available Users so I can select a user to assign the ticket to. How can I create this property in my Model and how to make it a drop down list in my view? Thanks

Update 1:
in my Index() method I already have an existing actionresult model to return to view and its like this:

```<code>Models.Application model = db.Applications
            .Include("Source")
            .Include(.....)
            .SingleOrDefault(m => m.Id == id);

        if (model == null)
        {
            return new HttpNotFoundResult();
        }

        return View(model);
</code>```

How can I incorporate the code you suggest in the Index() method with what I already have?

答:
Query your database to get the list of users, then transpose this into your view model.  Make sure you DONT pass the User class directly from the DB as you will send the password, salt etc to the browser.   You should transpose it from a DB shape to a VM shape, containing only the fields required in the view.

ViewModel:

```<code>class MyViewModel
{
     public IEnumerable<User> Users { get; set; }
     public string User { get; set;}
}

[HttpGet]
public ActionResult Index()
{
    var viewModel = new MyViewModel()
    {
         Users = <map users from db>
    };

    return this.View(viewModel);
}
</code>```

View:

```<code> <div class="form-group">
    @Html.LabelFor(m => m.User)
    <div class="col-md-10">
        @Html.DropDownListFor(x => x.User, new SelectList(Model.Users, "Id", "Name"), new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.OriginStation, "", new { @class = "text-danger" })
    </div>
 </div>
</code>```

Then your form postback handler:

```<code>[HttpPost]
public ActionResult Index(MyViewModel viewModel)
{
    viewModel.User now contains the id of the user
}
</code>```

Body:
I have a few users with  roles created in my MVC 5 application. I have a ticket Model which contains basic ticket info. But now I want to add a property called "Assigned To" to this ticket Model and I want to assign this property value to the users available.

In my view I want to have a drop down list of all available Users so I can select a user to assign the ticket to. How can I create this property in my Model and how to make it a drop down list in my view? Thanks

Update 1:
in my Index() method I already have an existing actionresult model to return to view and its like this:

Models.Application model = db.Applications
            .Include("Source")
            .Include(.....)
            .SingleOrDefault(m => m.Id == id);

        if (model == null)
        {
            return new HttpNotFoundResult();
        }

        return View(model);

How can I incorporate the code you suggest in the Index() method with what I already have?

Body:
Query your database to get the list of users, then transpose this into your view model.  Make sure you DONT pass the User class directly from the DB as you will send the password, salt etc to the browser.   You should transpose it from a DB shape to a VM shape, containing only the fields required in the view.

ViewModel:

class MyViewModel
{
     public IEnumerable<User> Users { get; set; }
     public string User { get; set;}
}

[HttpGet]
public ActionResult Index()
{
    var viewModel = new MyViewModel()
    {
         Users = <map users from db>
    };

    return this.View(viewModel);
}

View:

 <div class="form-group">
    @Html.LabelFor(m => m.User)
    <div class="col-md-10">
        @Html.DropDownListFor(x => x.User, new SelectList(Model.Users, "Id", "Name"), new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.OriginStation, "", new { @class = "text-danger" })
    </div>
 </div>

Then your form postback handler:

[HttpPost]
public ActionResult Index(MyViewModel viewModel)
{
    viewModel.User now contains the id of the user
}


问:
Error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
https://github.com/affinelayer/pix2pix-tensorflow/tree/master/tools

An error occurred when compiling "process.py" on the above site.

python tools/process.py --input_dir data --operation resize --output_dir data2/resize
data/0.jpg -> data2/resize/0.png

Traceback (most recent call last):
  File "tools/process.py", line 235, in <module>
    main()
  File "tools/process.py", line 167, in main
    src = load(src_path)
  File "tools/process.py", line 113, in load
    contents = open(path).read()
  File"/home/user/anaconda3/envs/tensorflow_2/lib/python3.5/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
```

What is the cause of the error?
Python's version is 3.5.2.

答:
Check the path of the file to be read. My code kept on giving me errors until I changed the path name to present working directory. The error was:</p>

```<code>newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
</code>```

ContentLicense: CC BY-SA 4.0

Body:
https://github.com/affinelayer/pix2pix-tensorflow/tree/master/tools

An error occurred when compiling "process.py" on the above site.

python tools/process.py --input_dir data --operation resize --output_dir data2/resize
data/0.jpg -> data2/resize/0.png

Traceback (most recent call last):
  File "tools/process.py", line 235, in <module>
    main()
  File "tools/process.py", line 167, in main
    src = load(src_path)
  File "tools/process.py", line 113, in load
    contents = open(path).read()
  File"/home/user/anaconda3/envs/tensorflow_2/lib/python3.5/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

What is the cause of the error?
Python's version is 3.5.2.

Body:
Check the path of the file to be read. My code kept on giving me errors until I changed the path name to present working directory. The error was:

newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte


问:
scatter chart formula
I am trying to create a scatter chart on my web page with CSS and few dots images. I have created the design successfully, but now I can't figure out how a scatter chart  actually works.  Can anyone provide me any idea how I can arrange them?  My chart width is 968 and height 432.
like this chart

http://chart.apis.google.com/chart?cht=s&chd=t:12,16,16,24,26,28,41,51,66,68,13,45,81|16,14,22,34,22,31,31,48,71,64,15,38,84&chs=250x100&chl=Hello|World

i cannot use this but i want to know how it works

Thanks for any help.

```<code><?php
$w = 968; $h = 432;
$xmin = 0; $xmax = 968;
$ymin = 10; $ymax = 100;
$x = 10; $y = 10;
$xc = 20;
$yc = 20;
$r = (20)/ 2;
 $xc = $w * (($x - $xmin)/($xmax - $xmin)) - $r . "<br>";
$yc = $h * (($ymax - $y)/($ymax - $ymin)) -$r;
$tr ='';
$data = array("120|90","345|456","45|66","45|45");
foreach($data as $value){
    $new =  explode("|",$value);
    $tr .='<a href="#" style="top:'.$new[0].'px; left:'.$new[1].'px;" class="dot"></a>';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

    <style type="text/css">
#most_engaged_graph{
width:968px;
height:432px;
background-color:#CCCCCC;
}
a.dot {
 height:20px;
 width:20px;
 position:absolute;
 background-color:#0033FF;
}
</style>
</head>
<body>
<div id="most_engaged_graph">
<?=$tr?>
</div>
</body>
</html>
</code>```

答:
Well, there are two parts really. First you have to establish a scale. I typically do slightly more than the extremes. So if you take the top, right, left, and bottom-most value, add/subtract a little or to make it fit a power of ten. Then you have a scale. From here, you can use math to decide where each dot goes. It doesn't simply go at the value location, you have to scale it to fit the chart.

So, let's say you have a scale of 1000 by 1000. But your chart is only 100 by 100. In this case, each pixel will count for 10. So the value 40,40 will be located at 4,4 on your plot.

You also need to bear in mind the existence of negative numbers. If the plot was -500 to 500 and not 0 to 1000, you would need to move 4,4 to 54,54 to place them in the correct location.

Hopefully this helps you figure the rest out.

Title: scatter chart formula

Body:
I am trying to create a scatter chart on my web page with CSS and few dots images. I have created the design successfully, but now I can't figure out how a scatter chart  actually works.  Can anyone provide me any idea how I can arrange them?  My chart width is 968 and height 432.
like this chart

http://chart.apis.google.com/chart?cht=s&chd=t:12,16,16,24,26,28,41,51,66,68,13,45,81|16,14,22,34,22,31,31,48,71,64,15,38,84&chs=250x100&chl=Hello|World

i cannot use this but i want to know how it works

Thanks for any help.

<?php
$w = 968; $h = 432;
$xmin = 0; $xmax = 968;
$ymin = 10; $ymax = 100;
$x = 10; $y = 10;
$xc = 20;
$yc = 20;
$r = (20)/ 2;
 $xc = $w * (($x - $xmin)/($xmax - $xmin)) - $r . "
";
$yc = $h * (($ymax - $y)/($ymax - $ymin)) -$r;
$tr ='';
$data = array("120|90","345|456","45|66","45|45");
foreach($data as $value){
    $new =  explode("|",$value);
    $tr .='';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<?=$tr?>


问:
ReactJS: Get multiple checkboxes value with material-ui
How to get multiple checkboxes value ? Ref not working in material ui checkbox, no idea why.

```<code><Checkbox key={i} label={catagory.name} ref="categories" value={catagory_name} name="category"  />
</code>```

for example : example

Without material-ui you can get the value by ref, but with material-ui it require another method to get checkbox value.

I get the data from API, so it will add more from time to time. How to get the value? What function I should write? Anyone know ?

答:
You can use build-in Material UI checkbox function - onChange. It will return the specified category and it's value.

app.js

```<code>class App extends Component {

  result = new Set();

  handleCheckbox(event, isChecked, value) {
    console.log(isChecked, value);
    this.res.add(value);
    if (this.res.size === 3) console.log(this.res);
  }

  labelList = [{id: 1, category: 'a'}, {id: 2, category: 'b'}, {id: 3, category: 'c'}]; // your data

  render() {
    return (
      <div className="App">
        {this.labelList.map(element => (
          <CheckboxField
            key={element.id}
            label={element.category}
            category={element.category}
            onChange={this.handleCheckbox}
          />
        ))}
      </div>
    )
  }
}
</code>```

Checkbox.js

```<code>export class CheckboxField extends React.PureComponent {

  handleCheck = (event, isInputChecked) => {
    this.props.onChange(event, isInputChecked, this.props.category);
  };

  render() {
    return (
          <Checkbox
            label={this.props.category}
            iconStyle={{fill: '#000'}}
            value={this.props.category}
            onCheck={this.handleCheck}
          />
    )}
}
</code>```

Body:
How to get multiple checkboxes value ? Ref not working in material ui checkbox, no idea why.

<Checkbox key={i} label={catagory.name} ref="categories" value={catagory_name} name="category"  />

for example : example

Without material-ui you can get the value by ref, but with material-ui it require another method to get checkbox value.

I get the data from API, so it will add more from time to time. How to get the value? What function I should write? Anyone know ?

Body:
You can use build-in Material UI checkbox function - onChange. It will return the specified category and it's value.

app.js

class App extends Component {

  result = new Set();

  handleCheckbox(event, isChecked, value) {
    console.log(isChecked, value);
    this.res.add(value);
    if (this.res.size === 3) console.log(this.res);
  }

  labelList = [{id: 1, category: 'a'}, {id: 2, category: 'b'}, {id: 3, category: 'c'}]; // your data

  render() {
    return (
      <div className="App">
        {this.labelList.map(element => (
          <CheckboxField
            key={element.id}
            label={element.category}
            category={element.category}
            onChange={this.handleCheckbox}
          />
        ))}
      </div>
    )
  }
}

Checkbox.js

export class CheckboxField extends React.PureComponent {

  handleCheck = (event, isInputChecked) => {
    this.props.onChange(event, isInputChecked, this.props.category);
  };

  render() {
    return (
          <Checkbox
            label={this.props.category}
            iconStyle={{fill: '#000'}}
            value={this.props.category}
            onCheck={this.handleCheck}
          />
    )}
}


问:
what is the difference between No Upfront Reserved Instances and on demand instances aws?
When trying to purchase a AWS reserved instance, I have found for no upfront,  What is the difference between it and on demand instances ?  </p>

答:
when you purchase a AWS reserved instance you reserve the capacity from AWS. You know you're needing a certain capacity for 1 or 3 years so you want to reserve it and to make sure a specific instance of this type will be available for you.

The upfront fee is just a payment method. You can choose between three payment options: All Upfront, Partial Upfront, and No Upfront. If you choose the Partial or No Upfront payment option, the remaining balance will be due in monthly increments over the term

When you purchase a reserved instance with No Upfront free, you will pay on a monthly basis the price (this price depends on your region and instance type) wether you're using the capacity or not. This price is a discount price (from 40% up to 75%) compared to the OnDemand price for the same instance in the same region.


问:
How to define an array with conditional elements?
How can I define conditional array elements?
I want to do something like this:

```<code>const cond = true;
const myArr = ["foo", cond && "bar"];
</code>```

This works as expected and results in ["foo", "bar"] but if I set cond to false, I get the following result: ["foo", false]

How can I define an array with a conditional element?

答:
There's a few different ways, but the way you're doing it won't really work for Javascript.

The easiest solution would be to just have an if statement.

```<code>if (myCond) arr.push(element);
</code>```

There's also filter, but I don't think that's what you want here at all, since you seem to be going for "Add this one thing, if this one condition is true" rather than checking everything against some condition. Although, if you want to get really freaky, you can do this (would not recommend, but it's cool that you can).

```<code>var arr = ["a", cond && "bar"];
arr.filter( e => e)
</code>```

Basically it will just filter out all the non true values.

Body:
How can I define conditional array elements?
I want to do something like this:

const cond = true;
const myArr = ["foo", cond && "bar"];

This works as expected and results in ["foo", "bar"] but if I set cond to false, I get the following result: ["foo", false]

How can I define an array with a conditional element?

Body:
There's a few different ways, but the way you're doing it won't really work for Javascript.

The easiest solution would be to just have an if statement.

if (myCond) arr.push(element);

There's also filter, but I don't think that's what you want here at all, since you seem to be going for "Add this one thing, if this one condition is true" rather than checking everything against some condition. Although, if you want to get really freaky, you can do this (would not recommend, but it's cool that you can).

var arr = ["a", cond && "bar"];
arr.filter( e => e)

Basically it will just filter out all the non true values.


问:
Android: How to call functions in a Android service repetitively?
I have created a Android service where I am finding out the process which are in Error state and the usage stats of app from UsageStatManager. When I run this service then it executes the methods in it once and I want to do a periodic check of the process in error state and the usage stats of apps.

One way I thought of was to implement a while loop with a Thread.sleep() for the time I would like to check my statistics but wondering if there is any other way of doing this in a much better way as placing a while loop may use CPU consumption. Any ideas would be helpfull.

My code:

```<code>public class Senddata_1 extends Service {

private String ip = "85.228.204.209";
private int port = 5000;
String message;
String file;
String TAG = "Senddata_1";

private static final SimpleDateFormat dateFormat = new SimpleDateFormat("M-d-yyyy HH:mm:ss");

public void find_out_process_in_error_state(){

    /*Some code to find out process in error state*/
    return;
}

private UsageStatsManager getUsageStatsManager(Context context){
    UsageStatsManager usm = (UsageStatsManager) context.getSystemService("usagestats");
    return usm;
}

public List<UsageStats> getUsageStatsList(Context context){

    List<UsageStats> usageStatsList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,startTime,endTime);
    return usageStatsList;
}

public void printUsageStats(List<UsageStats> usageStatsList){

}

@Override
public void onCreate() {
    super.onCreate();
    Log.e(TAG, "Inside service Senddata_1");

    find_out_process_in_error_state();
    printUsageStats(getUsageStatsList(Senddata_1.this));

    new Thread(new Senddata_1.ClientSend()).start();

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
//        return;
}

public class ClientSend implements Runnable {

}
</code>```

}

答:
you can use Timer and in there set time to start service and run function

```<code>Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {

            //start service here

        }
    }, 0, mTimeRate);
</code>```

mTimeRate will be in milliseconds

Body:
I have created a Android service where I am finding out the process which are in Error state and the usage stats of app from UsageStatManager. When I run this service then it executes the methods in it once and I want to do a periodic check of the process in error state and the usage stats of apps.

One way I thought of was to implement a while loop with a Thread.sleep() for the time I would like to check my statistics but wondering if there is any other way of doing this in a much better way as placing a while loop may use CPU consumption. Any ideas would be helpfull.

My code:

public class Senddata_1 extends Service {

private String ip = "85.228.204.209";
private int port = 5000;
String message;
String file;
String TAG = "Senddata_1";

private static final SimpleDateFormat dateFormat = new SimpleDateFormat("M-d-yyyy HH:mm:ss");

public void find_out_process_in_error_state(){

    /*Some code to find out process in error state*/
    return;
}

private UsageStatsManager getUsageStatsManager(Context context){
    UsageStatsManager usm = (UsageStatsManager) context.getSystemService("usagestats");
    return usm;
}

public List<UsageStats> getUsageStatsList(Context context){

    List<UsageStats> usageStatsList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,startTime,endTime);
    return usageStatsList;
}

public void printUsageStats(List<UsageStats> usageStatsList){

}

@Override
public void onCreate() {
    super.onCreate();
    Log.e(TAG, "Inside service Senddata_1");

    find_out_process_in_error_state();
    printUsageStats(getUsageStatsList(Senddata_1.this));

    new Thread(new Senddata_1.ClientSend()).start();

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
//        return;
}

public class ClientSend implements Runnable {

}

}

Body:
you can use Timer and in there set time to start service and run function

Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {

            //start service here

        }
    }, 0, mTimeRate);

mTimeRate will be in milliseconds


问:
show content based on angular drop down array of objects
I haven't been able to find and example of using angular drop downs using an array of objects in the drop down menu, can someone please help me debug this? I eventually want the "Show me" to be a radio button list from the angular library.  </p>

```<code>    <div ng-app="myApp" ng-controller="myCtrl">
        Method:
        <select ng-model="selectedName" ng-options="x.name for x in names">
        </select>
    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function($scope) {
            $scope.names = [{name: 'Experiment'}, {name: 'Clinical Trial'}, {name: 'Case Report'}];
              $scope.changeme = function() {
                alert('here');
              }
        });
    </script>
    <div ng-if = "x.name == 'Experiment'">
        <span>Show Me</span>
    </div>
</code>```

答:
Working version

```<code>    <div ng-app="myApp" ng-controller="myCtrl">
    Method:
    <select ng-model="selectedName" ng-options="name.name as
        name.name for name in names">
    </select>

<div ng-if = "selectedName === 'Experiment'">
    <span>Show Me</span>
</div>
      </div>
<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
    $scope.selectedName = null;
        $scope.names = [{name: 'Experiment'}, {name: 'Clinical Trial'}, {name: 'Case Report'}];

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

Plunker

Your problem is that you put your "Show me" block outside ng-app

Body:
I haven't been able to find and example of using angular drop downs using an array of objects in the drop down menu, can someone please help me debug this? I eventually want the "Show me" to be a radio button list from the angular library.

        Method:
        <select ng-model="selectedName" ng-options="x.name for x in names">
        </select>

        Show Me

Body:
Working version

    <div ng-app="myApp" ng-controller="myCtrl">
    Method:
    <select ng-model="selectedName" ng-options="name.name as
        name.name for name in names">
    </select>

<div ng-if = "selectedName === 'Experiment'">
    <span>Show Me</span>
</div>
      </div>
<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
    $scope.selectedName = null;
        $scope.names = [{name: 'Experiment'}, {name: 'Clinical Trial'}, {name: 'Case Report'}];

    });
</script>

Plunker

Your problem is that you put your "Show me" block outside ng-app


问:
How to get location and its updates in Google Maps Android API V2
I want to enable location in Google Maps Android API v2. What I want is:

load the map centered on a fix latitude/longitude,.

Start listening to location changes, and once a provider (network/GPS) gets the location, center the map on this location and animate it (animation shall only run once). Meanwhile, location listener updates user's location after specified amount of time,

Store this location data and use it to fetch nearby places of interest via my API.

I'm kind of confused with how to get periodic updates, the amount of time interval to choose. Right now, I have set up the project to show a map and used

```<code>googleMap.setMyLocationEnabled(true);
googleMap.setOnMyLocationChangeListener(myLocationChangeListener);

private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
    @Override
    public void onMyLocationChange(Location location) {
        LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
        if(googleMap != null){
            if(!firstTime){
                CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(loc).zoom(zoom).build();
                googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                firstTime = true;
            }

            lat = location.getLatitude();
            lng = location.getLongitude();
            Toast.makeText(context, "Location is: " + String.valueOf(lat) + ", "
                    + String.valueOf(lng), Toast.LENGTH_LONG).show();
        }
    }
};
</code>```

to set lat/lng in variables.
My questions are:

Is this a correct approach? Or can it be made better?

The location change listener updates itself quite often. I'm seeing toasts being made in a few seconds interval. How to regulate that?

How to stop the listener from fetching location when the activity's gone (paused/stopped)?
Thank you!

答:
I already answered to the similar question here.How to get the current location in Google Maps Android API v2?

The point is to use GoogleApiClient due to deprecation of OnMyLocationChangeListener.

```<code>private LocationRequest  mLocationRequest;
private GoogleApiClient  mGoogleApiClient;
private LocationListener mLocationListener;

private void initGoogleApiClient(Context context)
{
    mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks()
    {
        @Override
        public void onConnected(Bundle bundle)
        {
            mLocationRequest = LocationRequest.create();
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            mLocationRequest.setInterval(1000);

            setLocationListener();
        }

        @Override
        public void onConnectionSuspended(int i)
        {
            Log.i("LOG_TAG", "onConnectionSuspended");
        }
    }).build();

    if (mGoogleApiClient != null)
        mGoogleApiClient.connect();

}

private void setLocationListener()
{
    mLocationListener = new LocationListener()
    {
        @Override
        public void onLocationChanged(Location location)
        {
            String lat = String.valueOf(location.getLatitude());
            String lon = String.valueOf(location.getLongitude());
            Log.i("LOG_TAG", "Latitude = " + lat + " Longitude = " + lon);
        }
    };

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationListener);
}

private void removeLocationListener()
{
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationListener);
}
</code>```

Don't forget to call  mGoogleApiClient.connect(); and removeLocationListener(); methods when you finish working with Google Maps.

Body:
I want to enable location in Google Maps Android API v2. What I want is:

load the map centered on a fix latitude/longitude,.

Start listening to location changes, and once a provider (network/GPS) gets the location, center the map on this location and animate it (animation shall only run once). Meanwhile, location listener updates user's location after specified amount of time,

Store this location data and use it to fetch nearby places of interest via my API.

I'm kind of confused with how to get periodic updates, the amount of time interval to choose. Right now, I have set up the project to show a map and used

googleMap.setMyLocationEnabled(true);
googleMap.setOnMyLocationChangeListener(myLocationChangeListener);

private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
    @Override
    public void onMyLocationChange(Location location) {
        LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
        if(googleMap != null){
            if(!firstTime){
                CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(loc).zoom(zoom).build();
                googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                firstTime = true;
            }

            lat = location.getLatitude();
            lng = location.getLongitude();
            Toast.makeText(context, "Location is: " + String.valueOf(lat) + ", "
                    + String.valueOf(lng), Toast.LENGTH_LONG).show();
        }
    }
};

to set lat/lng in variables.
My questions are:

Is this a correct approach? Or can it be made better?

The location change listener updates itself quite often. I'm seeing toasts being made in a few seconds interval. How to regulate that?

How to stop the listener from fetching location when the activity's gone (paused/stopped)?
Thank you!

Body:
I already answered to the similar question here.How to get the current location in Google Maps Android API v2?

The point is to use GoogleApiClient due to deprecation of OnMyLocationChangeListener.

private LocationRequest  mLocationRequest;
private GoogleApiClient  mGoogleApiClient;
private LocationListener mLocationListener;

private void initGoogleApiClient(Context context)
{
    mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks()
    {
        @Override
        public void onConnected(Bundle bundle)
        {
            mLocationRequest = LocationRequest.create();
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            mLocationRequest.setInterval(1000);

            setLocationListener();
        }

        @Override
        public void onConnectionSuspended(int i)
        {
            Log.i("LOG_TAG", "onConnectionSuspended");
        }
    }).build();

    if (mGoogleApiClient != null)
        mGoogleApiClient.connect();

}

private void setLocationListener()
{
    mLocationListener = new LocationListener()
    {
        @Override
        public void onLocationChanged(Location location)
        {
            String lat = String.valueOf(location.getLatitude());
            String lon = String.valueOf(location.getLongitude());
            Log.i("LOG_TAG", "Latitude = " + lat + " Longitude = " + lon);
        }
    };

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationListener);
}

private void removeLocationListener()
{
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationListener);
}

Don't forget to call  mGoogleApiClient.connect(); and removeLocationListener(); methods when you finish working with Google Maps.


问:
router.navigate doesn't work if error occurs during ng lifecycle hooks
I have an ErrorHandler that I use to log all exceptions & then redirect user to generic error page. The problem is that this does work only if the exception that is handled occured outside of any lifecycle hooks (or constructor). method. Consider the following example with ngOnInit:

```<code>class MyErrorHandler implements ErrorHandler {
  constructor(private injector: Injector) { }

  handleError(error) {
    // log error

    var router = this.injector.get(Router);

     router.navigate['/error'];
  }
}
</code>```

The error handler is called correctly. However, the router.navigate works only when exception occured after initialization of component.

Doesn't work:

```<code>import { Component, OnInit} from '@angular/core';
@Component({
  template: ''
})
export class SampleComponent implements OnInit{
    ngOnInit() {
    throw Error(`Boom!`);
  }
}
</code>```

Works as expected:

```<code>import { Component, OnInit} from '@angular/core';
@Component({
  template: `<button (click)="handleClick()">click me</button>`
})
export class SampleComponent{
      private handleClick(): void{
        throw Error(`Boom!`);
    }
}
</code>```

Am I missing something or how can I make this work? I suppose I can use windows.location.href, but that will reload the page which is something I would rather avoid.

答:
Injection in MyErrorHandler isn't correct.

Change { provide: ErrorHandler, useClass: MyErrorHandler } in app.module.ts on

```<code>{
  provide: ExceptionHandler,
    useFactory: (router) => {
      return new MyErrorHandler(router);
    },
  deps: [Router]
}
</code>```

So now you have properly injected router.

Body:
I have an ErrorHandler that I use to log all exceptions & then redirect user to generic error page. The problem is that this does work only if the exception that is handled occured outside of any lifecycle hooks (or constructor). method. Consider the following example with ngOnInit:

class MyErrorHandler implements ErrorHandler {
  constructor(private injector: Injector) { }

  handleError(error) {
    // log error

    var router = this.injector.get(Router);

     router.navigate['/error'];
  }
}

The error handler is called correctly. However, the router.navigate works only when exception occured after initialization of component.

Doesn't work:

import { Component, OnInit} from '@angular/core';
@Component({
  template: ''
})
export class SampleComponent implements OnInit{
    ngOnInit() {
    throw Error(`Boom!`);
  }
}

Works as expected:

import { Component, OnInit} from '@angular/core';
@Component({
  template: `<button (click)="handleClick()">click me</button>`
})
export class SampleComponent{
      private handleClick(): void{
        throw Error(`Boom!`);
    }
}

Am I missing something or how can I make this work? I suppose I can use windows.location.href, but that will reload the page which is something I would rather avoid.

Body:
Injection in MyErrorHandler isn't correct.

Change { provide: ErrorHandler, useClass: MyErrorHandler } in app.module.ts on

{
  provide: ExceptionHandler,
    useFactory: (router) => {
      return new MyErrorHandler(router);
    },
  deps: [Router]
}

So now you have properly injected router.


问:
Include additional files in .bashrc
I have some stuff I want to perform in .bashrc which I would prefer to exist in another file on the system. How can I include this file into .bashrc?</p>

答:
I prefer to check version first and assign variable for path config:</p>

```<code>if [ -n "${BASH_VERSION}" ]; then
  filepath="${HOME}/ls_colors/monokai.sh"
  if [ -f "$filepath" ]; then
    source "$filepath"
  fi
fi
</code>```

Title: Include additional files in .bashrc

Body:
I prefer to check version first and assign variable for path config:

if [ -n "${BASH_VERSION}" ]; then
  filepath="${HOME}/ls_colors/monokai.sh"
  if [ -f "$filepath" ]; then
    source "$filepath"
  fi
fi


问:
Get the BIOS time in LINGO
Can someone tell me how to get the BIOS time in Lingo?</p>

答:
_system.time() will give you the system time.
You can also use the good old Lingo syntaxed "the systemDate" wich is an object with properties such as ".seconds" for example.

To access the BIOS probably need a custom built xtra. You can build one in Delphi or C/C++ but to make it auto-downloadable you need to sign if i remember correctly (Long time since I made one). :-)

OwnerDisplayName: Elie

Title: Get the BIOS time in LINGO