问:
Can't access Tomcat 8 Manager App
I've just set up Tomcat 8 on an Ubuntu 14.04 VM and I'm not able to access the Manager App at http://[hostname]:8080/manager/html from my browser. I get a "403 Access Denied" error as soon as I click on it. I am running Tomcat as a service defined in a config file in /etc/init.d/tomcat8-dev. The error message indicates that Tomcat is set up to be accessible only from localhost initially, but as it is a hosted VM I'm not able to run a browser on it.

I have set up a user in the tomcat-users.xml file as several people have recommended. However, I am not prompted to provide the credentials for that user, and I can't find any kind of login button on the default page. That file currently looks like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<tomcat-users xmlns="http://tomcat.apache.org/xml"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
    version="1.0">

    <role rolename="manager-script"/>
    <role rolename="manager-jmx"/>
    <role rolename="manager-gui"/>
    <role rolename="manager-status"/>

    <user username="(redacted)" password="(redacted)"
        roles="manager-gui,manager-jmx,manager-status,manager-script"/>
</tomcat-users>
</code>```

After reading the Tomcat documentation page here, I have also tried adding <Valve /> tags into context.xml that look something like this:

```<code><Context privileged="true" antiResourceLocking="false"
    docBase="${catalina.home}/webapps/manager">

    <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="127\.0\.0\.1" />
    <!--Another valve for my local machine's IP-->

</Context>
</code>```

However, as soon as I set privileged="true", I get a blank white page when I connect to the server with my browser regardless of the valves I provide afterwards.

I restart my service with sudo service tomcat8-dev restart whenever I make changes.

Other things I have tried based on posts I read here and on other sites:

Various configurations of roles for my tomcat user

Adding address="0.0.0.0" to server.xml inside the <Connector /> tag

Using initctl instead of setting up a service based on the instructions here, which doesn't load the default page on my server for some reason

Trying different browsers, and disabling my popup blocker

Nothing I've tried works. Please let me know if you would like more details about my situation. Any suggestions?

Edit: The problem was that I was editing the wrong context.xml file. The correct file is in tomcat/webapps/manager/META-INF. I had incorrectly been making changes to tomcat/conf/context.xml.

答:
I think this might help for all of you because its work for me.

Here I'm using Apache tomcat 8:

```<code>root@akash-LIFEBOOK-A555:/opt/apache-tomcat-8.5.20/bin# ./version.sh
Using CATALINA_BASE:   /opt/apache-tomcat-8.5.20
Using CATALINA_HOME:   /opt/apache-tomcat-8.5.20
Using CATALINA_TMPDIR: /opt/apache-tomcat-8.5.20/temp
Using JRE_HOME:        /DATA/jre1.8.0_131/
Using CLASSPATH:       /opt/apache-tomcat-8.5.20/bin/bootstrap.jar:/opt/apache-tomcat-8.5.20/bin/tomcat-juli.jar
Server version: Apache Tomcat/8.5.20
Server built:   Aug 2 2017 21:35:49 UTC
Server number:  8.5.20.0
OS Name:        Linux
OS Version:     4.4.0-98-generic
Architecture:   amd64
JVM Version:    1.8.0_131-b11
JVM Vendor:     Oracle Corporation
</code>```

Edit tomcat-user.xml and added the roles and users

```<code><role rolename="manager-gui"/>
<role rolename="manager-status"/>
<role rolename="manager-script"/>
<role rolename="manager-jmx"/>
<role rolename="admin-gui"/>
<user username="admin" password="password" roles="manager-gui,manager-status,manager-script,manager-jmx,admin-gui"/>
</code>```

Title: Can't access Tomcat 8 Manager App

Body:
I've just set up Tomcat 8 on an Ubuntu 14.04 VM and I'm not able to access the Manager App at http://[hostname]:8080/manager/html from my browser. I get a "403 Access Denied" error as soon as I click on it. I am running Tomcat as a service defined in a config file in /etc/init.d/tomcat8-dev. The error message indicates that Tomcat is set up to be accessible only from localhost initially, but as it is a hosted VM I'm not able to run a browser on it.

I have set up a user in the tomcat-users.xml file as several people have recommended. However, I am not prompted to provide the credentials for that user, and I can't find any kind of login button on the default page. That file currently looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<tomcat-users xmlns="http://tomcat.apache.org/xml"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
    version="1.0">

    <role rolename="manager-script"/>
    <role rolename="manager-jmx"/>
    <role rolename="manager-gui"/>
    <role rolename="manager-status"/>

    <user username="(redacted)" password="(redacted)"
        roles="manager-gui,manager-jmx,manager-status,manager-script"/>
</tomcat-users>

After reading the Tomcat documentation page here, I have also tried adding <Valve /> tags into context.xml that look something like this:

<Context privileged="true" antiResourceLocking="false"
    docBase="${catalina.home}/webapps/manager">

    <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="127\.0\.0\.1" />

</Context>

However, as soon as I set privileged="true", I get a blank white page when I connect to the server with my browser regardless of the valves I provide afterwards.

I restart my service with sudo service tomcat8-dev restart whenever I make changes.

Other things I have tried based on posts I read here and on other sites:

Various configurations of roles for my tomcat user

Adding address="0.0.0.0" to server.xml inside the <Connector /> tag

Using initctl instead of setting up a service based on the instructions here, which doesn't load the default page on my server for some reason

Trying different browsers, and disabling my popup blocker

Nothing I've tried works. Please let me know if you would like more details about my situation. Any suggestions?

Edit: The problem was that I was editing the wrong context.xml file. The correct file is in tomcat/webapps/manager/META-INF. I had incorrectly been making changes to tomcat/conf/context.xml.

Body:
I think this might help for all of you because its work for me.

Here I'm using Apache tomcat 8:

root@akash-LIFEBOOK-A555:/opt/apache-tomcat-8.5.20/bin# ./version.sh
Using CATALINA_BASE:   /opt/apache-tomcat-8.5.20
Using CATALINA_HOME:   /opt/apache-tomcat-8.5.20
Using CATALINA_TMPDIR: /opt/apache-tomcat-8.5.20/temp
Using JRE_HOME:        /DATA/jre1.8.0_131/
Using CLASSPATH:       /opt/apache-tomcat-8.5.20/bin/bootstrap.jar:/opt/apache-tomcat-8.5.20/bin/tomcat-juli.jar
Server version: Apache Tomcat/8.5.20
Server built:   Aug 2 2017 21:35:49 UTC
Server number:  8.5.20.0
OS Name:        Linux
OS Version:     4.4.0-98-generic
Architecture:   amd64
JVM Version:    1.8.0_131-b11
JVM Vendor:     Oracle Corporation

Edit tomcat-user.xml and added the roles and users

<role rolename="manager-gui"/>
<role rolename="manager-status"/>
<role rolename="manager-script"/>
<role rolename="manager-jmx"/>
<role rolename="admin-gui"/>
<user username="admin" password="password" roles="manager-gui,manager-status,manager-script,manager-jmx,admin-gui"/>


来源: stackexchange

问:
(Python)How to use MQTT protocol to subscribe topics on Thingspeak.com and display it?
I have to write a python program using MQTT protocol to subscribe topics on thingspeak.com and display it on the screen of a Raspberry Pi.
I found official help/documentation about publishing messages and field feeds to thingspeak.com, but they don't provide any information about how to subscribe a topic, e.g. what is the form of a topic string, what are the inclusions of that topic string etc.
Does anyone have any clue about that?</p>

答:
just an update: ThingSpeak does support (at this moment) the possibility to subscribe to channels: https://nl.mathworks.com/help/thingspeak/use-desktop-mqtt-client-to-subscribe-to-channel-updates.html

just be aware that you need to get the topic exactly right to get te subscribe to work correctly

topic is like channels/[channel_id]/subscribe/json/[api readkey]

replace [channel_id] with you channel ID
and [api readkey] with the api read key of that channel

you have to login with your username and as a pass an mqtt key that you can set under account>my profile > mqttkey on the ThingSpeak site.

ContentLicense: CC BY-SA 3.0


问:
Can't decode session from elm port
Trying to get elm ports working to maintain the session.

In index.html, the script includes the following listener:

```<code>  window.addEventListener("load", function(event) {
    app.ports.onSessionChange.send(localStorage.session);
  }, false);
</code>```

localStorage.session looks like this (and it stays there until I've logged out):

```<code>{"email":"user@fake.com","token":"eyJhbG...","user_id":1,"handle":"me"}
</code>```

The definition in Ports.elm is:

port onSessionChange : (Value -> msg) -> Sub msg

This port is connected to Main.elm here (let me know if I've forgotten to include some of the definitions below):

```<code>subscriptions : Model -> Sub Msg
subscriptions model =
    Ports.onSessionChange sessionChange

sessionChange : Json.Decode.Value -> Msg
sessionChange value =
    let
        result =
            Json.Decode.decodeValue sessionDecoder value
    in
        case result of
            Ok sess ->
                SetSession (Just sess)

            Err err ->
                SetSession Nothing

    ...

type alias Session =
    { email : String
    , token : String
    , user_id : Int
    , handle : String
    }

    ...

import Json.Decode as Decode exposing (..)
import Json.Decode.Pipeline as Pipeline exposing (decode, required)

sessionDecoder : Decode.Decoder Session
sessionDecoder =
    Pipeline.decode Session
        |> Pipeline.required "email" Decode.string
        |> Pipeline.required "token" Decode.string
        |> Pipeline.required "user_id" Decode.int
        |> Pipeline.required "handle" Decode.string

    ...

type Msg
    = NoOp
    | SetSession (Maybe Session)

    ...

update msg model =
    case msg of
        SetSession session ->
            case Debug.log "session = " session of
                Just sess ->
                    ({ model | session = sess } , Cmd.none)

                Nothing ->
                    (model, Cmd.none)
</code>```

Debug.log "session" displays Nothing in the console when the page loads, so JS is talking to elm, but the decoder seems to be failing.  Any ideas?

答: I've plugged your code into a minimal working example and everything works fine. You might want to log the value of localStorage.session from inside the javascript portion to make sure it's a valid JSON value.

Title: Can't decode session from elm port

Body:
Trying to get elm ports working to maintain the session.

In index.html, the script includes the following listener:

  window.addEventListener("load", function(event) {
    app.ports.onSessionChange.send(localStorage.session);
  }, false);

localStorage.session looks like this (and it stays there until I've logged out):

{"email":"user@fake.com","token":"eyJhbG...","user_id":1,"handle":"me"}

The definition in Ports.elm is:

port onSessionChange : (Value -> msg) -> Sub msg

This port is connected to Main.elm here (let me know if I've forgotten to include some of the definitions below):

subscriptions : Model -> Sub Msg
subscriptions model =
    Ports.onSessionChange sessionChange

sessionChange : Json.Decode.Value -> Msg
sessionChange value =
    let
        result =
            Json.Decode.decodeValue sessionDecoder value
    in
        case result of
            Ok sess ->
                SetSession (Just sess)

            Err err ->
                SetSession Nothing

    ...

type alias Session =
    { email : String
    , token : String
    , user_id : Int
    , handle : String
    }

    ...

import Json.Decode as Decode exposing (..)
import Json.Decode.Pipeline as Pipeline exposing (decode, required)

sessionDecoder : Decode.Decoder Session
sessionDecoder =
    Pipeline.decode Session
        |> Pipeline.required "email" Decode.string
        |> Pipeline.required "token" Decode.string
        |> Pipeline.required "user_id" Decode.int
        |> Pipeline.required "handle" Decode.string

    ...

type Msg
    = NoOp
    | SetSession (Maybe Session)

    ...

update msg model =
    case msg of
        SetSession session ->
            case Debug.log "session = " session of
                Just sess ->
                    ({ model | session = sess } , Cmd.none)

                Nothing ->
                    (model, Cmd.none)

Debug.log "session" displays Nothing in the console when the page loads, so JS is talking to elm, but the decoder seems to be failing.  Any ideas?


问:
divide values of column based on some other column
I have a pandas data frame as can be seen below: </p>

```<code>index     ID           Val

 1    BBID_2041         1
 2    BBID_2041         1
 3    BBID_2041         3
 4    BBID_2041         1
 5    BBID_2041         2
 6    BBID_2041         1
 7    BBID_2041         1
 8    BBID_20410        1
 9    BBID_20410        1
 10   BBID_20410        5
 11   BBID_20410        1
</code>```

<p>Now I want to divide every value present in column Val by the total number of IDs present in that group. For e.g i want to divide the values from index 1 to 7 by 7 as there are total 7 rows for ID BBID_2041 and so on. I can use a loop for that but what could be a fast way to do that.    </p>

Body:
I have a pandas data frame as can be seen below:

index     ID           Val

 1    BBID_2041         1
 2    BBID_2041         1
 3    BBID_2041         3
 4    BBID_2041         1
 5    BBID_2041         2
 6    BBID_2041         1
 7    BBID_2041         1
 8    BBID_20410        1
 9    BBID_20410        1
 10   BBID_20410        5
 11   BBID_20410        1

Now I want to divide every value present in column Val by the total number of IDs present in that group. For e.g i want to divide the values from index 1 to 7 by 7 as there are total 7 rows for ID BBID_2041 and so on. I can use a loop for that but what could be a fast way to do that.

Body:
By using transform

df['New']=df.groupby('ID').Val.transform(lambda x : x/len(x))
df
Out[814]:
    index          ID  Val       New
0       1   BBID_2041    1  0.142857
1       2   BBID_2041    1  0.142857
2       3   BBID_2041    3  0.428571
3       4   BBID_2041    1  0.142857
4       5   BBID_2041    2  0.285714
5       6   BBID_2041    1  0.142857
6       7   BBID_2041    1  0.142857
7       8  BBID_20410    1  0.250000
8       9  BBID_20410    1  0.250000
9      10  BBID_20410    5  1.250000
10     11  BBID_20410    1  0.250000


问:
How to check a SQL CASE with multiple conditions?
I have two tables. Accounts ACC and FinancialTrans FT

The FinancialTrans table is as follows:

```<code>AcctID  TransTypeCode   DateOfTrans
123     TOLL            2016-06-06 00:00:00.000
123     TOLL            2016-06-02 00:00:00.000
123     TOLL            2016-04-28 00:00:00.000
123     PYMT            2016-03-11 00:00:00.000
123     TOLL            2015-12-22 00:00:00.000
123     TOLL            2015-12-22 00:00:00.000
</code>```

The requirement is:

When any Accounts have NO 'TOLL' or 'PYMT' in the last 2 years print 'Flag'

```<code>SELECT ACC.Field1
      ,ACC.Field2
      ,ACC.Field3
      ,ACC.Field4
      ,CASE WHEN
        (SELECT Max(DateOfTrans) FROM FinanceTrans FT
         WHERE ACC.AccountID = FT.AcctID
               AND (TransTypeCode = 'TOLL' AND DateOfTrans >= DATEADD(year, -2, GETDATE()))
               AND (TransTypeCode = 'PYMT' AND DateOfTrans >= DATEADD(year, -2, GETDATE()))
             GROUP BY AcctID, TransTypeCode) IS NULL
        THEN 'Flag'
        ELSE ''
       AND AS NoNo_Flag

FROM Accounts ACC

WHERE Condition 1, Condition 2...
</code>```

答:
I could be misunderstanding the question, in which case I can refine my answer. It seems like you just need to check for the existence, or not, of records in the the sub-query. So to that extent do you really need to do an aggregate? And, try using EXISTS:</p>

```<code>SELECT ACC.Field1, ACC.Field2, ACC.Field3, ACC.Field4,
       CASE WHEN NOT EXISTS
           (SELECT DateOfTrans
            FROM FinanceTrans FT
            WHERE ACC.AccountID = FT.AcctID
                  AND (TransTypeCode = 'TOLL' AND DateOfTrans >= DATEADD(year, -2, GETDATE()))
                  AND (TransTypeCode = 'PYMT' AND DateOfTrans >= DATEADD(year, -2, GETDATE())))
       THEN 'Flag'
       ELSE ''
       END AS NoNo_Flag
FROM Accounts ACC
WHERE [*condition*]
</code>```

Body:
I have two tables. Accounts ACC and FinancialTrans FT

The FinancialTrans table is as follows:

AcctID  TransTypeCode   DateOfTrans
123     TOLL            2016-06-06 00:00:00.000
123     TOLL            2016-06-02 00:00:00.000
123     TOLL            2016-04-28 00:00:00.000
123     PYMT            2016-03-11 00:00:00.000
123     TOLL            2015-12-22 00:00:00.000
123     TOLL            2015-12-22 00:00:00.000

The requirement is:

When any Accounts have NO 'TOLL' or 'PYMT' in the last 2 years print 'Flag'

SELECT ACC.Field1
      ,ACC.Field2
      ,ACC.Field3
      ,ACC.Field4
      ,CASE WHEN
        (SELECT Max(DateOfTrans) FROM FinanceTrans FT
         WHERE ACC.AccountID = FT.AcctID
               AND (TransTypeCode = 'TOLL' AND DateOfTrans >= DATEADD(year, -2, GETDATE()))
               AND (TransTypeCode = 'PYMT' AND DateOfTrans >= DATEADD(year, -2, GETDATE()))
             GROUP BY AcctID, TransTypeCode) IS NULL
        THEN 'Flag'
        ELSE ''
       AND AS NoNo_Flag

FROM Accounts ACC

WHERE Condition 1, Condition 2...

Body:
I could be misunderstanding the question, in which case I can refine my answer. It seems like you just need to check for the existence, or not, of records in the the sub-query. So to that extent do you really need to do an aggregate? And, try using EXISTS:

SELECT ACC.Field1, ACC.Field2, ACC.Field3, ACC.Field4,
       CASE WHEN NOT EXISTS
           (SELECT DateOfTrans
            FROM FinanceTrans FT
            WHERE ACC.AccountID = FT.AcctID
                  AND (TransTypeCode = 'TOLL' AND DateOfTrans >= DATEADD(year, -2, GETDATE()))
                  AND (TransTypeCode = 'PYMT' AND DateOfTrans >= DATEADD(year, -2, GETDATE())))
       THEN 'Flag'
       ELSE ''
       END AS NoNo_Flag
FROM Accounts ACC
WHERE [*condition*]


问:
vim configuration to turn on syntax for .conf files
I have a config file under my python project, called "logging.conf", the file looks like:

```<code>[formatters]
keys: console, logging

[formatter_console]
format: %(asctime)s | %(message)s

[formatter_logging]
format: %(message)s

etc etc etc
</code>```

Tried :syntax on, nothing happened, the .conf files look very plain. Is there anyway I can turn on some syntax to make the .conf file more colorful and readable?

答:
I almost have that kind of text style but mine was the ansible hosts file, I found a lot of options here filetype.vim. I used povini or texmf for my ansible hosts file text highlights

To configure it in your .vimrc.

Grab the string before setf, so in case of provini, it is au BufNewFile,BufRead .povrayrc

Replace the last string(.povrayrc) with *.conf

The final config is au BufNewFile,BufRead *.conf for your .vimrc

Body:
I have a config file under my python project, called "logging.conf", the file looks like:

[formatters]
keys: console, logging

[formatter_console]
format: %(asctime)s | %(message)s

[formatter_logging]
format: %(message)s

etc etc etc

Tried :syntax on, nothing happened, the .conf files look very plain. Is there anyway I can turn on some syntax to make the .conf file more colorful and readable?


问:
JavaScript - How to get current date, and store previous dates, for use in a list?
I would like to make a UL with previous dates, the current date, and have
these listed items nested within it. An example is this:

```<code>•   Monday November 13, 2017
   o    List item
   o    List item
   o    List item
•   Tuesday November 14, 2017
   o    List item
   o    List item
   o    List item
•   Wednesday November 15, 2017
   o    List item
   o    List item
   o    List item
</code>```

I would be getting the current date via JavaScript.

How would I be able to do the following?

Get the current date via JavaScript?

Store the previous dates (i.e. yesterday's date, the day before's date, etc.)?;

note: every time a new list item is added (like a to do app), the current date will be saved. If i were to come back to my app the next day, yesterday's date is saved, and the current date is added. Hope that makes sense!

Thanks in advance!

答:
Have a look at this example:

var ul = document.getElementById('mylist');

var daysAmount = 3;
var items = [
  {v: 'v1'},
  {v: 'v2'},
  {v: 'v3'},
];

var ts = new Date() / 1;

for(var i = daysAmount; i >= 0; i--){ // 3 previous + today = 4 days on list
  var shift = i * (1000 * 60 * 60 * 24);

  var previousDay = new Date(ts - shift);

  var li = document.createElement('li');
  var nestedUl = document.createElement('ul');
  items.forEach(function(el){
    var nestedLi = document.createElement('li');
    nestedLi.innerText = el.v;
    nestedUl.appendChild(nestedLi);
  });

  li.innerText = previousDay;
  li.appendChild(nestedUl);
  ul.appendChild(li)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="mylist">
</ul></code>```

Body:
I would like to make a UL with previous dates, the current date, and have
these listed items nested within it. An example is this:

•   Monday November 13, 2017
   o    List item
   o    List item
   o    List item
•   Tuesday November 14, 2017
   o    List item
   o    List item
   o    List item
•   Wednesday November 15, 2017
   o    List item
   o    List item
   o    List item

I would be getting the current date via JavaScript.

How would I be able to do the following?

Get the current date via JavaScript?

Store the previous dates (i.e. yesterday's date, the day before's date, etc.)?;

note: every time a new list item is added (like a to do app), the current date will be saved. If i were to come back to my app the next day, yesterday's date is saved, and the current date is added. Hope that makes sense!

Thanks in advance!

Body:
Have a look at this example:

var ul = document.getElementById('mylist');

var daysAmount = 3;
var items = [
  {v: 'v1'},
  {v: 'v2'},
  {v: 'v3'},
];

var ts = new Date() / 1;

for(var i = daysAmount; i >= 0; i--){ // 3 previous + today = 4 days on list
  var shift = i * (1000 * 60 * 60 * 24);

  var previousDay = new Date(ts - shift);

  var li = document.createElement('li');
  var nestedUl = document.createElement('ul');
  items.forEach(function(el){
    var nestedLi = document.createElement('li');
    nestedLi.innerText = el.v;
    nestedUl.appendChild(nestedLi);
  });

  li.innerText = previousDay;
  li.appendChild(nestedUl);
  ul.appendChild(li)
}

<ul id="mylist">
</ul>


问:
How to filter for attributes from database
I am using visual studio 2017 and have created a standard ASP.NET/MVC Project with the Entity Framework, finally a local database is included.
I have the Class "Courses" and "Categories". One Course can have one categorie, and one categorie can be in many courses. (n:1 relationship)

My Model is for my course.cs:

```<code>namespace project.Models
{
    public class Course
    {
        public int ID { get; set; }
        public int CategoryID { get; set; }
        public string Name { get; set; }
        public string  Description { get; set; }

        public virtual CourseCategory CourseCategory { get; set; }

    }
</code>```

Model for the courseCategory.cs is:

```<code>    namespace project.Models
{
    public class CourseCategory
    {
        public int ID { get; set; }
        public string Name { get; set; }

        public virtual ICollection<Course> Course { get; set; }
    }
}
</code>```

The view is:

```<code>@model IEnumerable<Models.Courses>

@{
    ViewData["Title"] = "Index";
}

<h2>Index</h2>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
                <th>
                    @Html.DisplayNameFor(model => model.ID)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.CategoryID)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Description)
                </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.ID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CategoryID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Description)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.ID">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.ID">Details</a>
                <a asp-action="Delete" asp-route-id="@item.ID">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>
</code>```

Derived from these two classes i created the controller and the views automatically. I do "add-migration -xx" and "update-database" and my application is runnable.
I open "http://localhost/courses" and i have list of my courses (inluded the given category of the course) and can add, move delete, etc...
If i have a look into my database/tables i can see the right primary- and foreign keys. It works....

But now, i want to add a possibility to filter my courses. I need an extra part in this side, where my categories are listed and if i click on one of these categories, i want a new resultlist of all course with the clicked categorie.

How can i realize it and where i have to modify the code?
I tried to modify the CourseController.cs

```<code>  // GET: Course
    public async Task<IActionResult> Index()
    {
        return View(await _context.Course.ToListAsync());
    }
</code>```

I guess i need here somethink like a comparison of the primary keys in the tables?

答:
This is what you need

A dropdown in your view where user can select a category

Changes to your action method where it will accept the selected category and get the courses under that category.

There are multiple ways to do this. This is how i will do it.

I like to not mix the entity classes created by ORM in my UI layer. So i create a view model specific to the view

```<code>public class CourseListVm
{
   public int? CategoryId { set;get;}
   public List<SelectListItem> Categories { set;get;}
   public IEnumerable<CourseVm> Courses { set;get;}
   public CourseListVm()
   {
       this.Courses = new List<CourseVm>();
   }
}
public class CourseVm
{
   public int Id { set;get;}
   public string Name { set;get;}
}
</code>```

Now in your action method, create an object of this, load available categories from your database to the Categories property. We will add a parameter to the action method and check if there is a value for selected catetory (from the ui) and if yes ,we will do the filtering when populating the Courses property

```<code>public async Task<IActionResult> Index(int? categoryId)
{
    var vm=new CourseListVm();
    //Populate the catetory list so that we can use that in UI to build the dropdown
    vm.Categories = _context.Categories
                            .Select(a => new SelectListItem() {Value = a.Id.ToString(),
                                                               Text = a.Name})
                            .ToList();
    List<Course> courseList = new List<Course>();
    if(categoryId==null)
    {
      courseList = await _context.Course.ToListAsync()
    }
    else
    {
      courseList = await _context.Course
                     .Where(a=>a.CategoryId==categoryId.Value)
                     .ToListAsync()
    }
    vm.Courses = GetCourseVms(courseList);
    return View(vm);
}
private IEnumerable<CourseVm> GetCourseVms(IEnumerable<Course> courses)
{
    return courses.Select(a=>new CourseVm { Id=a.Id, Name =a.Name});
}
</code>```

I am using the GetCourseVms method to map the Course entity to the CourseVm view model object. You can use a library like Auto mapper to do so if you prefer that.

Now in your view, which is strongly typed to the CourseListVm, we will render a dropdown for the categories using the DropDownListFor helper method. If you are doing asp.net core app, you can use the Select tag helper to render the dropdown

```<code>@model CourseListVm
@using (Html.BeginForm("Index", "Courses",FormMethod.Get))
{
    @Html.DropDownListFor(a=>a.CategoryId,Model.Categories,"All")
    <button type="submit">Filter</button>
}
@foreach (var p in Model.Courses)
{
    <p>@p.Id</p>
    <p>@p.Name</p>
}
</code>```

When user selects a category and click the submit button, the form will be submitted to the Index action with the id of selected category in the url and the action method code will use that to create the filtered set of the courses to render in the view.

Body:
I am using visual studio 2017 and have created a standard ASP.NET/MVC Project with the Entity Framework, finally a local database is included.
I have the Class "Courses" and "Categories". One Course can have one categorie, and one categorie can be in many courses. (n:1 relationship)

My Model is for my course.cs:

namespace project.Models
{
    public class Course
    {
        public int ID { get; set; }
        public int CategoryID { get; set; }
        public string Name { get; set; }
        public string  Description { get; set; }

        public virtual CourseCategory CourseCategory { get; set; }

    }

Model for the courseCategory.cs is:

    namespace project.Models
{
    public class CourseCategory
    {
        public int ID { get; set; }
        public string Name { get; set; }

        public virtual ICollection<Course> Course { get; set; }
    }
}

The view is:

@model IEnumerable<Models.Courses>

@{
    ViewData["Title"] = "Index";
}

Index

    Create New

                    @Html.DisplayNameFor(model => model.ID)

                    @Html.DisplayNameFor(model => model.CategoryID)

                    @Html.DisplayNameFor(model => model.Name)

                    @Html.DisplayNameFor(model => model.Description)

@foreach (var item in Model) {

                @Html.DisplayFor(modelItem => item.ID)

                @Html.DisplayFor(modelItem => item.CategoryID)

                @Html.DisplayFor(modelItem => item.Name)

                @Html.DisplayFor(modelItem => item.Description)

                Edit |
                Details
                Delete

}

Derived from these two classes i created the controller and the views automatically. I do "add-migration -xx" and "update-database" and my application is runnable.
I open "http://localhost/courses" and i have list of my courses (inluded the given category of the course) and can add, move delete, etc...
If i have a look into my database/tables i can see the right primary- and foreign keys. It works....

But now, i want to add a possibility to filter my courses. I need an extra part in this side, where my categories are listed and if i click on one of these categories, i want a new resultlist of all course with the clicked categorie.

How can i realize it and where i have to modify the code?
I tried to modify the CourseController.cs

  // GET: Course
    public async Task<IActionResult> Index()
    {
        return View(await _context.Course.ToListAsync());
    }

I guess i need here somethink like a comparison of the primary keys in the tables?

Body:
This is what you need

A dropdown in your view where user can select a category

Changes to your action method where it will accept the selected category and get the courses under that category.

There are multiple ways to do this. This is how i will do it.

I like to not mix the entity classes created by ORM in my UI layer. So i create a view model specific to the view

public class CourseListVm
{
   public int? CategoryId { set;get;}
   public List<SelectListItem> Categories { set;get;}
   public IEnumerable<CourseVm> Courses { set;get;}
   public CourseListVm()
   {
       this.Courses = new List<CourseVm>();
   }
}
public class CourseVm
{
   public int Id { set;get;}
   public string Name { set;get;}
}

Now in your action method, create an object of this, load available categories from your database to the Categories property. We will add a parameter to the action method and check if there is a value for selected catetory (from the ui) and if yes ,we will do the filtering when populating the Courses property

public async Task<IActionResult> Index(int? categoryId)
{
    var vm=new CourseListVm();
    //Populate the catetory list so that we can use that in UI to build the dropdown
    vm.Categories = _context.Categories
                            .Select(a => new SelectListItem() {Value = a.Id.ToString(),
                                                               Text = a.Name})
                            .ToList();
    List<Course> courseList = new List<Course>();
    if(categoryId==null)
    {
      courseList = await _context.Course.ToListAsync()
    }
    else
    {
      courseList = await _context.Course
                     .Where(a=>a.CategoryId==categoryId.Value)
                     .ToListAsync()
    }
    vm.Courses = GetCourseVms(courseList);
    return View(vm);
}
private IEnumerable<CourseVm> GetCourseVms(IEnumerable<Course> courses)
{
    return courses.Select(a=>new CourseVm { Id=a.Id, Name =a.Name});
}

I am using the GetCourseVms method to map the Course entity to the CourseVm view model object. You can use a library like Auto mapper to do so if you prefer that.

Now in your view, which is strongly typed to the CourseListVm, we will render a dropdown for the categories using the DropDownListFor helper method. If you are doing asp.net core app, you can use the Select tag helper to render the dropdown

@model CourseListVm
@using (Html.BeginForm("Index", "Courses",FormMethod.Get))
{
    @Html.DropDownListFor(a=>a.CategoryId,Model.Categories,"All")
    <button type="submit">Filter</button>
}
@foreach (var p in Model.Courses)
{
    <p>@p.Id</p>
    <p>@p.Name</p>
}

When user selects a category and click the submit button, the form will be submitted to the Index action with the id of selected category in the url and the action method code will use that to create the filtered set of the courses to render in the view.


问:
When validating data in Laravel 5.5, Update returns "unknown column in field list" error where Create does not
Laravel 5.5 introduces a new streamlined request validation. The idea being that:

```<code>$validData = $request->validate($rules)
</code>```

will return only those fields that are present in the $rules. This is beneficial so that one can then simply User::create($validData) or User::update($validData).

However, I noticed that when I have additional data, which I do validate, but that doesn't exist in the model's (this case User) table, the create method inserts the record, but that the update method returns this error:

```<code>Column not found: 1054 Unknown column 'column_name' in 'field list'
</code>```

I can of course write the relevant field lists out, or use other workaround, but I wonder why are the two methods are behaving differently?

e.g. passing

```<code>array:4 [▼
  "first_name" => "Pedro"
  "last_name" => "Taco"
  "email" => "taco@example.org"
  "operators" => array:1 [▼
    0 => "1"
  ]
]
</code>```

to User::create() inserts the record. Passing the same to User::update() returns an error.
User has $fillable = 'first_name', 'last_name', 'email'

答:
If you are trying to use validations, you can decouple the code even further using Request validations.

Here you have a full example of applying Request validations and extracting just the necessary data to store (or update) objects:

1. Generation the request:

php artisan make:request CreateUserRequest
```

<h3>2. Custom the validation rules:</h3>

<pre class="lang-php prettyprint-override"><code>namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CreateUserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        // you specify here a previous condition before access to the method
        // can be Auth::check() for example
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            // put here your validation rules like:
        'first_name' => 'required|string|max:100',
        ];
    }
</code>```

3. Modify the method in your controller:

public function store(CreateUserRequest $request)
{
    // getting all the attributes
    $data = $request->only('first_name', 'last_name', 'other_attribute..');

    // creating the object
    $user = new User;
    // adding data
    $user->fill($data);
    // saving in database
    $user->save();

    return response()->json([
        "message" => "The user has been created.",
        "data" => $user,
    ], 201);
}
```

* Notice that the $request used as an argument is of type CreateUserRequest, so this indicates to Laravel wath rules to apply.

We have also only pull the data that we want to store (check the $request->only part), that seemed to be the root of your problem.

Body:
Laravel 5.5 introduces a new streamlined request validation. The idea being that:

$validData = $request->validate($rules)

will return only those fields that are present in the $rules. This is beneficial so that one can then simply User::create($validData) or User::update($validData).

However, I noticed that when I have additional data, which I do validate, but that doesn't exist in the model's (this case User) table, the create method inserts the record, but that the update method returns this error:

Column not found: 1054 Unknown column 'column_name' in 'field list'

I can of course write the relevant field lists out, or use other workaround, but I wonder why are the two methods are behaving differently?

e.g. passing

array:4 [▼
  "first_name" => "Pedro"
  "last_name" => "Taco"
  "email" => "taco@example.org"
  "operators" => array:1 [▼
    0 => "1"
  ]
]

to User::create() inserts the record. Passing the same to User::update() returns an error.
User has $fillable = 'first_name', 'last_name', 'email'

Body:
If you are trying to use validations, you can decouple the code even further using Request validations.

Here you have a full example of applying Request validations and extracting just the necessary data to store (or update) objects:

1. Generation the request:

php artisan make:request CreateUserRequest

2. Custom the validation rules:

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CreateUserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        // you specify here a previous condition before access to the method
        // can be Auth::check() for example
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            // put here your validation rules like:
        'first_name' => 'required|string|max:100',
        ];
    }

3. Modify the method in your controller:

public function store(CreateUserRequest $request)
{
    // getting all the attributes
    $data = $request->only('first_name', 'last_name', 'other_attribute..');

    // creating the object
    $user = new User;
    // adding data
    $user->fill($data);
    // saving in database
    $user->save();

    return response()->json([
        "message" => "The user has been created.",
        "data" => $user,
    ], 201);
}

* Notice that the $request used as an argument is of type CreateUserRequest, so this indicates to Laravel wath rules to apply.

We have also only pull the data that we want to store (check the $request->only part), that seemed to be the root of your problem.


问:
Java: what is the overhead of using ConcurrentSkipList* when no concurrency is needed?
I need a sorted list in a scenario dominated by iteration (compared to insert/remove, not random get at all). For this reason I thought about using a skip list compared to a tree (the iterator should be faster).

The problem is that java6 only has a concurrent implementation of a skip list, so I was guessing whether it makes sense to use it in a non-concurrent scenario or if the overhead makes it a wrong decision.

For what I know ConcurrentSkipList* are basically lock-free implementations based on CAS, so they should not carry (much) overhead, but I wanted to hear somebody else's opinion.

EDIT:

After some micro-benchmarking (running iteration multiple times on different-sized TreeSet, LinkedList, ConcurrentSkipList and ArrayList) shows that there's quite an overhead. ConcurrentSkipList does store the elements in a linked list inside, so the only reason why it would be slower on iteration than a LinkedList would be due to the aforementioned overhead.

答:
As noted SkipList has a lot of overhead compared to TreeMap and the TreeMap iterator isn't well suited to your use case because it just repeatedly calls the method successor() which turns out to be very slow.

So one alternative that will be significantly faster than the previous two is to write your own TreeMap iterator.  Actually, I would dump TreeMap altogether since 3000 lines of code is a bit bulkier than you probably need and just write a clean AVL tree implementation with the methods you need.  The basic AVL logic is just a few hundred lines of code in any language then add the iterator that works best in your case.


问:
How to refresh listView date on CalenderView date changed
I want to sync my listView with my CalenderView so that when a new date is selected on the calendar is changed only appointments that have a date that equals the date on the calendar view are displayed. I am using Firebase real-time database and the only way I thought of getting this to work is update the database each time a selection is made but I don't think this is the optimal/correct way to do it. I have attached the class below if any other classes are needed I can add them too. I have attached an image of the screen too for some clarity. Thanks in advance

```<code>package com.example.steph.fyp;

import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

public class BookAppointment extends AppCompatActivity {

ListView listViewAppointments;
DatabaseReference databaseAppointment;

List<Appointment> appointmentList;
DateHelper dateHelper = new DateHelper();
CalendarView calendarView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_book_appointment);

    listViewAppointments = (ListView) findViewById(R.id.listview_appointments);
    calendarView = (CalendarView) findViewById(R.id.calendar_view);

    //getting the reference of appointments node
    databaseAppointment = FirebaseDatabase.getInstance().getReference("appointments");
    appointmentList = new ArrayList<>();

    calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {

        @Override
        public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {

        }
    });
    listViewAppointments.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            //getting the selected appointment
            Appointment appointment = appointmentList.get(i);
            showUpdateDialog(appointment.getId(), appointment.getDate());
        }
    });

}

private boolean updateAppointmentBooked(String id, long date) {
    //getting the specified appointments reference
    DatabaseReference dR = FirebaseDatabase.getInstance().getReference("appointments").child(id);

    //updating appointment
    Appointment appointment = new Appointment(id, date, true);
    dR.setValue(appointment);
    Toast.makeText(getApplicationContext(), "Booking Successful", Toast.LENGTH_LONG).show();
    return true;
}
private void showUpdateDialog(final String appointmentId, final long appointmentDate){
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

    LayoutInflater inflater = getLayoutInflater();

    final View dialogView = inflater.inflate(R.layout.book_appointment_dialog, null);

    dialogBuilder.setView(dialogView);

    final TextView textViewDate = (TextView) dialogView.findViewById(R.id.textview_date);
    final TextView textViewTime = (TextView) dialogView.findViewById(R.id.textview_time);
    final TextView textViewCancel = (TextView) dialogView.findViewById(R.id.textview_cancel);
    final Button bookAppointmentButton = (Button) dialogView.findViewById(R.id.book_appointment_button);

    textViewDate.setText(dateHelper.toAppointmentDate(appointmentDate));
    textViewTime.setText(dateHelper.toAppointmentTime(appointmentDate));
    dialogBuilder.setTitle("Confirm Booking");

    final AlertDialog alertDialog = dialogBuilder.create();
    alertDialog.show();

    bookAppointmentButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            updateAppointmentBooked(appointmentId,appointmentDate);
            alertDialog.dismiss();
        }

    });
    textViewCancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            alertDialog.dismiss();
        }

    });
    //alertDialog.dismiss();

}

@Override
protected void onStart() {
    super.onStart();
    //attaching value event listener
    databaseAppointment.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            //clearing the previous artist list
            appointmentList.clear();

            //iterating through all the nodes
            for (DataSnapshot appointmentSnapshot : dataSnapshot.getChildren()) {
                //getting artist
                Appointment appointment = appointmentSnapshot.getValue(Appointment.class);
                if(!appointment.isBooked() && dateHelper.isDateSameDay(calendarView.getDate(), appointment.getDate())){
                    //adding appointment to the list
                    appointmentList.add(appointment);
                }

            }

            //creating adapter
            AppointmentList appointmentAdapter = new AppointmentList(BookAppointment.this, appointmentList);

            //attaching adapter to the listview
            //expandableListViewAppointments.setAdapter(expandableListViewAdapter);
            listViewAppointments.setAdapter(appointmentAdapter);

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

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

答:
You can create two lists. One list for adapter another for backup. When calendar listener fired you can make a method like this

```<code>addList(){
list1.clear(); // main list clear
list1.addAll(list2) // backup list added
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to sync my listView with my CalenderView so that when a new date is selected on the calendar is changed only appointments that have a date that equals the date on the calendar view are displayed. I am using Firebase real-time database and the only way I thought of getting this to work is update the database each time a selection is made but I don't think this is the optimal/correct way to do it. I have attached the class below if any other classes are needed I can add them too. I have attached an image of the screen too for some clarity. Thanks in advance

package com.example.steph.fyp;

import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

public class BookAppointment extends AppCompatActivity {

ListView listViewAppointments;
DatabaseReference databaseAppointment;

List<Appointment> appointmentList;
DateHelper dateHelper = new DateHelper();
CalendarView calendarView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_book_appointment);

    listViewAppointments = (ListView) findViewById(R.id.listview_appointments);
    calendarView = (CalendarView) findViewById(R.id.calendar_view);

    //getting the reference of appointments node
    databaseAppointment = FirebaseDatabase.getInstance().getReference("appointments");
    appointmentList = new ArrayList<>();

    calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {

        @Override
        public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {

        }
    });
    listViewAppointments.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            //getting the selected appointment
            Appointment appointment = appointmentList.get(i);
            showUpdateDialog(appointment.getId(), appointment.getDate());
        }
    });

}

private boolean updateAppointmentBooked(String id, long date) {
    //getting the specified appointments reference
    DatabaseReference dR = FirebaseDatabase.getInstance().getReference("appointments").child(id);

    //updating appointment
    Appointment appointment = new Appointment(id, date, true);
    dR.setValue(appointment);
    Toast.makeText(getApplicationContext(), "Booking Successful", Toast.LENGTH_LONG).show();
    return true;
}
private void showUpdateDialog(final String appointmentId, final long appointmentDate){
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

    LayoutInflater inflater = getLayoutInflater();

    final View dialogView = inflater.inflate(R.layout.book_appointment_dialog, null);

    dialogBuilder.setView(dialogView);

    final TextView textViewDate = (TextView) dialogView.findViewById(R.id.textview_date);
    final TextView textViewTime = (TextView) dialogView.findViewById(R.id.textview_time);
    final TextView textViewCancel = (TextView) dialogView.findViewById(R.id.textview_cancel);
    final Button bookAppointmentButton = (Button) dialogView.findViewById(R.id.book_appointment_button);

    textViewDate.setText(dateHelper.toAppointmentDate(appointmentDate));
    textViewTime.setText(dateHelper.toAppointmentTime(appointmentDate));
    dialogBuilder.setTitle("Confirm Booking");

    final AlertDialog alertDialog = dialogBuilder.create();
    alertDialog.show();

    bookAppointmentButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            updateAppointmentBooked(appointmentId,appointmentDate);
            alertDialog.dismiss();
        }

    });
    textViewCancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            alertDialog.dismiss();
        }

    });
    //alertDialog.dismiss();

}

@Override
protected void onStart() {
    super.onStart();
    //attaching value event listener
    databaseAppointment.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            //clearing the previous artist list
            appointmentList.clear();

            //iterating through all the nodes
            for (DataSnapshot appointmentSnapshot : dataSnapshot.getChildren()) {
                //getting artist
                Appointment appointment = appointmentSnapshot.getValue(Appointment.class);
                if(!appointment.isBooked() && dateHelper.isDateSameDay(calendarView.getDate(), appointment.getDate())){
                    //adding appointment to the list
                    appointmentList.add(appointment);
                }

            }

            //creating adapter
            AppointmentList appointmentAdapter = new AppointmentList(BookAppointment.this, appointmentList);

            //attaching adapter to the listview
            //expandableListViewAppointments.setAdapter(expandableListViewAdapter);
            listViewAppointments.setAdapter(appointmentAdapter);

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

    });
    };

Body:
You can create two lists. One list for adapter another for backup. When calendar listener fired you can make a method like this

addList(){
list1.clear(); // main list clear
list1.addAll(list2) // backup list added
}


问:
Android - clickable items from JSON
I know there are many similar questions and answers here, but nothing worked for my case.

I created a simple JSON list using fragment - according to this tutorial http://androidbeginnerstutorial.blogspot.sk/2015/06/json-parsing-using-fragment-with.html

It is working fine, but I want to have all items from the list clickable, so after click another page appears with some more info from the same JSON.

I tried to implement to ActorAdapter.java inside

```<code>public View getView(int position, View convertView, ViewGroup parent) {
</code>```

I created something like

```<code> itemView.setOnClickListener(new OnClickListener() {
Intent intent = new Intent(context, SingleitemView.class);
})
</code>```

but not sure what else to put there to get it work.

I have already created the SingleitemView class.

Can you please help me? Thank you.

Here is my code from ActorAdapter.java:

```<code>import java.io.InputStream;
import java.util.ArrayList;

import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ListView;

public class ActorAdapter extends ArrayAdapter<Actors> {
    ArrayList<Actors> actorList;
    LayoutInflater vi;
    int Resource;
    ViewHolder holder;

    public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
        super(context, resource, objects);
        vi = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Resource = resource;
        actorList = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // convert view = design
        View v = convertView;
        if (v == null) {
            holder = new ViewHolder();
            v = vi.inflate(Resource, null);
            holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
            holder.tvName = (TextView) v.findViewById(R.id.tvName);
            holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
            holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
            holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
            holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
            holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
            holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }
        holder.imageview.setImageResource(R.drawable.ic_launcher);
        new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
        holder.tvName.setText(actorList.get(position).getName());
        holder.tvDescription.setText(actorList.get(position).getDescription());
        holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
        holder.tvCountry.setText(actorList.get(position).getCountry());
        holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
        holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
        holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());

   v.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        Intent intent = new Intent(view.getContext(), SingleitemView.class);
        intent.putExtra("name", "XXXXXX");
        view.getContext().startActivity(intent);
    }
});

        return v;

    }

    static class ViewHolder {
        public ImageView imageview;
        public TextView tvName;
        public TextView tvDescription;
        public TextView tvDOB;
        public TextView tvCountry;
        public TextView tvHeight;
        public TextView tvSpouse;
        public TextView tvChildren;

    }

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {

            bmImage.setImageBitmap(result);
        }

    }
}
</code>```

and the SingleitemView.java - that is supposed to be the new activity after click

```<code>    import android.app.Activity;
        import android.content.Intent;
        import android.os.Bundle;
        import android.widget.TextView;

public class SingleitemView extends Activity {
// Declare Variables
String name;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from singleitemview.xml
    setContentView(R.layout.singleitemview);

    Intent i = getIntent();
    // Get the result of rank
    name = i.getStringExtra("name");

    // Locate the TextViews in singleitemview.xml
    TextView txtname = (TextView) findViewById(R.id.name);

    // Set results to the TextViews
    txtname.setText(name);

}
</code>```

}

答:
this fixed my issue finally</p>

```<code>intent.putExtra("name", actorList.get(position).getName());
</code>```

Title: Android - clickable items from JSON

Body:
I know there are many similar questions and answers here, but nothing worked for my case.

I created a simple JSON list using fragment - according to this tutorial http://androidbeginnerstutorial.blogspot.sk/2015/06/json-parsing-using-fragment-with.html

It is working fine, but I want to have all items from the list clickable, so after click another page appears with some more info from the same JSON.

I tried to implement to ActorAdapter.java inside

public View getView(int position, View convertView, ViewGroup parent) {

I created something like

 itemView.setOnClickListener(new OnClickListener() {
Intent intent = new Intent(context, SingleitemView.class);
})

but not sure what else to put there to get it work.

I have already created the SingleitemView class.

Can you please help me? Thank you.

Here is my code from ActorAdapter.java:

import java.io.InputStream;
import java.util.ArrayList;

import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ListView;

public class ActorAdapter extends ArrayAdapter<Actors> {
    ArrayList<Actors> actorList;
    LayoutInflater vi;
    int Resource;
    ViewHolder holder;

    public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
        super(context, resource, objects);
        vi = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Resource = resource;
        actorList = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // convert view = design
        View v = convertView;
        if (v == null) {
            holder = new ViewHolder();
            v = vi.inflate(Resource, null);
            holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
            holder.tvName = (TextView) v.findViewById(R.id.tvName);
            holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
            holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
            holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
            holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
            holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
            holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }
        holder.imageview.setImageResource(R.drawable.ic_launcher);
        new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
        holder.tvName.setText(actorList.get(position).getName());
        holder.tvDescription.setText(actorList.get(position).getDescription());
        holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
        holder.tvCountry.setText(actorList.get(position).getCountry());
        holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
        holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
        holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());

   v.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        Intent intent = new Intent(view.getContext(), SingleitemView.class);
        intent.putExtra("name", "XXXXXX");
        view.getContext().startActivity(intent);
    }
});

        return v;

    }

    static class ViewHolder {
        public ImageView imageview;
        public TextView tvName;
        public TextView tvDescription;
        public TextView tvDOB;
        public TextView tvCountry;
        public TextView tvHeight;
        public TextView tvSpouse;
        public TextView tvChildren;

    }

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {

            bmImage.setImageBitmap(result);
        }

    }
}

and the SingleitemView.java - that is supposed to be the new activity after click

    import android.app.Activity;
        import android.content.Intent;
        import android.os.Bundle;
        import android.widget.TextView;

public class SingleitemView extends Activity {
// Declare Variables
String name;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from singleitemview.xml
    setContentView(R.layout.singleitemview);

    Intent i = getIntent();
    // Get the result of rank
    name = i.getStringExtra("name");

    // Locate the TextViews in singleitemview.xml
    TextView txtname = (TextView) findViewById(R.id.name);

    // Set results to the TextViews
    txtname.setText(name);

}

}

Body:
this fixed my issue finally

intent.putExtra("name", actorList.get(position).getName());


问:
PHP SimpleXML: Remove items with for
I just can remove an item from a simpleXML element with:

```<code>unset($this->simpleXML->channel->item[0]);
</code>```

but I can't with the a for:

```<code>    $items = $this->simpleXML->xpath('/rss/channel/item');
    for($i = count($items); $i > $itemsNumber; $i--) {
        unset($items[$i - 1]);
    }
</code>```

some items are removed from $items (Netbeans Debug can confirm that) but when I get the path again (/rss/channel/item) nothing was deleted.

What's wrong?

答:
SimpleXML does not handle node deletion, you need to use DOMNode for this.
Happily, when you import your nodes into DOMNode, the instances point to the same tree.

So, you can do that :

```<code><?php

$items = $this->simpleXML->xpath('/rss/channel/item');
foreach ($items as $item) {
    $node = dom_import_simplexml($item);
    $node->parentNode->removeChild($node);
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: PHP SimpleXML: Remove items with for

Body:
I just can remove an item from a simpleXML element with:

unset($this->simpleXML->channel->item[0]);

but I can't with the a for:

    $items = $this->simpleXML->xpath('/rss/channel/item');
    for($i = count($items); $i > $itemsNumber; $i--) {
        unset($items[$i - 1]);
    }

some items are removed from $items (Netbeans Debug can confirm that) but when I get the path again (/rss/channel/item) nothing was deleted.

What's wrong?

Body:
SimpleXML does not handle node deletion, you need to use DOMNode for this.
Happily, when you import your nodes into DOMNode, the instances point to the same tree.

So, you can do that :

<?php

$items = $this->simpleXML->xpath('/rss/channel/item');
foreach ($items as $item) {
    $node = dom_import_simplexml($item);
    $node->parentNode->removeChild($node);
}


答:
Now that I can look more closely at the sample data and output, I can see better what you want (and it's nothing close to the existing code).

Since you're doing an INSERT, based on the sample, it looks like you get by with just this:

```<code>INSERT INTO TableA
SELECT MIN([time]) as ConfigTime, term_id, config1, config2, 1
FROM TableB
GROUP BY term_id, config1, config2
</code>```

Since that is added to what you already have, it should produce the expected results in the table (ie: SELECT * FROM TableA will produce what you want after this runs.

But if you're worried about accidentally producing duplicate records in TableA, you can do this:

```<code>INSERT INTO TableA
SELECT B.*, 1
FROM (
    SELECT MIN([time]) as ConfigTime, term_id, config1, config2
    FROM TableB
    GROUP BY term_id, config1, config2
) B
LEFT JOIN TableA A ON a.term_id = B.term_id
     AND A.config1 = B.config1 AND A.config2 = B.config2
WHERE A.[time] iS NULL
</code>```

This takes the results from TableB and does an exclusion join to remove rows that are already in TableA. You could also write this to use EXCEPT or NOT EXISTS(), I'm just more comfortable writing the exclusion join.

Title: Insert Only One/the Very First Record Using an Left Join in T-Sql

Body:
I have two tables TableA and TableB. I am trying to join using a leftjoin and insert some records into TableA.

My TableA,

Time                             term_id   config1   config2    final
2017-04-19 23:59:00                 8        147       0        NULL
2017-04-19 23:59:00                 9        87        0        NULL
2017-04-19 23:59:00                10        284       0        NULL

My TableB

Time                             term_id   config1   config2       Claims     Rejects
2017-04-20 00:00:00                8         148       0            568.2        62
2017-04-20 01:00:00                8         148       0            569          62
2017-04-20 02:00:00                8         148       0            572          62
2017-04-20 00:00:00                9         88        0            458          12
2017-04-20 01:00:00                9         88        0            459          12
2017-04-20 02:00:00                9         88        0            462          12
2017-04-20 00:00:00               10         285       0            125          13
2017-04-20 01:00:00               10         285       0            123          13
2017-04-20 02:00:00               10         285       0            117          13
2017-04-20 03:00:00               10         286       1            119          13

My desired output is,

Time                           term_id         config1     config2     final
2017-04-19 23:59:00                 8            147           0        NULL
2017-04-19 23:59:00                 9            87            0        NULL
2017-04-19 23:59:00                 10           284           0        NULL
2017-04-20 00:00:00                 8            148           0         1
2017-04-20 00:00:00                 9            88            0         1
2017-04-20 00:00:00                 10           285           0         1
2017-04-20 03:00:00                 10           286           1         1

I want to insert only the changes in the config1, config2 from TableB into the TableA. So, I did a left join like this, (I don't need Claims and Rejects from TableB)

insert into TableA
select B.[time], B.term_id, B.Config1, B.config2,
        (CASE
        WHEN B.config1 <> A.config1 OR
             B.config2 <> A.config2
        THEN 1
        ELSE 0 END)
from
    TableB B
left join
    (select max([time]) as maxtime, term_id, config1, config2
     from TableA
     group by [time], term_id, config1, config2
    ) as A
on A.term_id = B.term_id

I do not get what I want. How can I change my code to get only the very first changing value inserted into TableA?

Body:
Now that I can look more closely at the sample data and output, I can see better what you want (and it's nothing close to the existing code).

Since you're doing an INSERT, based on the sample, it looks like you get by with just this:

INSERT INTO TableA
SELECT MIN([time]) as ConfigTime, term_id, config1, config2, 1
FROM TableB
GROUP BY term_id, config1, config2

Since that is added to what you already have, it should produce the expected results in the table (ie: SELECT * FROM TableA will produce what you want after this runs.

But if you're worried about accidentally producing duplicate records in TableA, you can do this:

INSERT INTO TableA
SELECT B.*, 1
FROM (
    SELECT MIN([time]) as ConfigTime, term_id, config1, config2
    FROM TableB
    GROUP BY term_id, config1, config2
) B
LEFT JOIN TableA A ON a.term_id = B.term_id
     AND A.config1 = B.config1 AND A.config2 = B.config2
WHERE A.[time] iS NULL

This takes the results from TableB and does an exclusion join to remove rows that are already in TableA. You could also write this to use EXCEPT or NOT EXISTS(), I'm just more comfortable writing the exclusion join.


问:
Netbeans - Customize brace matching line color
Is there any option to change the color of this, very useful, line, on Netbeans 8. I tried in Formatting tab, but I didn't find the way.

Thanks a lot.

Screenshot of my current colorset

答:
The setting you need to change is "Indent Guide Lines" on the Highlighting tab of the Fonts & Colors Options.

Tools->Options

Select Fonts & Colors

Select Highlighting tab

Select Indent Guide Lines in the Category list

Edit the Foreground color as desired.

Click OK


问:
Why the value of output variable not change inside loop - Windows Batch
I am using the following code, and if I call the array.bat outside loop, you can the the value in output that is different, varying with the index that I used during call.

```<code>    @echo off

set empresas[0]=EPB
set empresas[1]=ENF
set empresas[2]=ESE
set empresas[3]=ESS
set empresas[4]=EBO
set empresas[5]=EMG
set empresas[6]=EMT
set empresas[7]=ETO

call array.bat len empresas length
call array.bat getitem empresas 0 empresa1
echo %empresa1%
call array.bat getitem empresas 1 empresa1
echo %empresa1%
echo %length%

for /l %%x in (0, 1, %length% ) do (

   call array.bat getitem empresas %x% empresa3

   echo %empresa3%
   echo %%x
)
</code>```

That code generate the output:

```<code>   EPB
ENF
7
ETO
0
ETO
1
ETO
2
ETO
3
ETO
4
ETO
5
ETO
6
ETO
7
</code>```

Only tha last value is being printted.

答:
delayedexpansion trap again. Please search for delayed expansion on SO.

Try

```<code>call array.bat getitem empresas %%x empresa3

CALL echo %%empresa3%%
</code>```

Note that %%x is the value of the metavariable %%x. %x% is the content of the environment variable x (which, according to your code, is undefined)

Reading about delayedexpansion will explain why the extra CALL and doubling of the % are required (one of many possible solutions)

Body:
I am using the following code, and if I call the array.bat outside loop, you can the the value in output that is different, varying with the index that I used during call.

    @echo off

set empresas[0]=EPB
set empresas[1]=ENF
set empresas[2]=ESE
set empresas[3]=ESS
set empresas[4]=EBO
set empresas[5]=EMG
set empresas[6]=EMT
set empresas[7]=ETO

call array.bat len empresas length
call array.bat getitem empresas 0 empresa1
echo %empresa1%
call array.bat getitem empresas 1 empresa1
echo %empresa1%
echo %length%

for /l %%x in (0, 1, %length% ) do (

   call array.bat getitem empresas %x% empresa3

   echo %empresa3%
   echo %%x
)

That code generate the output:

   EPB
ENF
7
ETO
0
ETO
1
ETO
2
ETO
3
ETO
4
ETO
5
ETO
6
ETO
7

Only tha last value is being printted.

Body:
delayedexpansion trap again. Please search for delayed expansion on SO.

Try

call array.bat getitem empresas %%x empresa3

CALL echo %%empresa3%%

Note that %%x is the value of the metavariable %%x. %x% is the content of the environment variable x (which, according to your code, is undefined)

Reading about delayedexpansion will explain why the extra CALL and doubling of the % are required (one of many possible solutions)


问:
JSON Encoding custom class not calling overriden default
I have a class definition which I have based on json.JSONEncoder, within which I have overriden the default method.  Now when I call json.dumps on an instance of that class the default method is not being called?  Is there something I have missed?

In my example code I do not expect this to magically produce the serialized object but I would expect the print("here") to be executed.

```<code>import json

class MyClass(json.JSONEncoder):
    id = "myId"
    data = "myData"

    def default(self, o):
        print("here")

print ("Create instance")
obj = MyClass()
print("Serialize")
print(json.dumps(obj))
print ("and done")
</code>```

I am quite new to Python, so apologies if this is something horribly obvious.

答:
After some further digging and tracing I think I have found the cause.  Part of the issue I think it my own misunderstanding of how this is intended to be used.

When calling json.dumps if you wish to use a custom encoder you need to specify the class of that encoder, otherwise dumps defaults to using the standard implementation of JSONEncoder.

```<code>json.dumps(obj, cls=MyEncoder)
</code>```

My misconception was that by basing my class on json.JSONEncoder that dumps would simply recognise the instance as inheriting from JSONEncoder and call the override default method.  However this is not the case.

I have now created the logic in it's own class to encode my own class/types and when I call json.dumps I pass in that class name.

So I now have

```<code>class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, MyClass):
            return {"id": obj.id, "data": obj.data}
        return json.JSONEncoder.default(self, obj)
</code>```

And when I wish to serialize I use

```<code>json.dumps(object_to_serialize, cls=MyEncoder)
</code>```

Which recognises my class and handles it, or passes on the encoding to the default encoder.

Body:
I have a class definition which I have based on json.JSONEncoder, within which I have overriden the default method.  Now when I call json.dumps on an instance of that class the default method is not being called?  Is there something I have missed?

In my example code I do not expect this to magically produce the serialized object but I would expect the print("here") to be executed.

import json

class MyClass(json.JSONEncoder):
    id = "myId"
    data = "myData"

    def default(self, o):
        print("here")

print ("Create instance")
obj = MyClass()
print("Serialize")
print(json.dumps(obj))
print ("and done")

I am quite new to Python, so apologies if this is something horribly obvious.

Body:
After some further digging and tracing I think I have found the cause.  Part of the issue I think it my own misunderstanding of how this is intended to be used.

When calling json.dumps if you wish to use a custom encoder you need to specify the class of that encoder, otherwise dumps defaults to using the standard implementation of JSONEncoder.

json.dumps(obj, cls=MyEncoder)

My misconception was that by basing my class on json.JSONEncoder that dumps would simply recognise the instance as inheriting from JSONEncoder and call the override default method.  However this is not the case.

I have now created the logic in it's own class to encode my own class/types and when I call json.dumps I pass in that class name.

So I now have

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, MyClass):
            return {"id": obj.id, "data": obj.data}
        return json.JSONEncoder.default(self, obj)

And when I wish to serialize I use

json.dumps(object_to_serialize, cls=MyEncoder)

Which recognises my class and handles it, or passes on the encoding to the default encoder.


问:
how to get point set (x,y) in a desired area in r

The figure is the plot of x,y set in a excel file, total 8760 pair of x and y. I want to remove the noise data pair in red circle area and output a new excel file with remain data pair. How could I do it in R?

答:
Both R and EXCEL read and write .csv files, so you can use those to transfer the data back and forth.

You do not provide any data so I made some junk data to produce a similar problem.

DATA

```<code>set.seed(2017)
x = runif(8760, 0,16)
y = c(abs(rnorm(8000, 0, 1)), runif(760,0,8))
XY = data.frame(x,y)
</code>```

One way to identify noise points is by looking at the distance to the nearest neighbors.  In dense areas, nearest neighbors will be closer. In non-dense areas, they will be further apart.  The package dbscan provides a nice function to get the distance to the k nearest neighbors. For this problem, I used k=6, but you may need to tune for your data. Looking at the distribution of distances to the 6th nearest neighbor we see that most points have 6 neighbors within a distance of 0.2

```<code>XY6 = kNNdist(XY, 6)
plot(density(XY6[,6]))
</code>```

So I will assume that point whose 6th nearest neighbor is further away are noise points. Just changing the color to see which points are affected, we get

```<code>TYPE = rep(1,8760)
TYPE[XY6[,6] > 0.2] = 2
plot(XY, col=TYPE)
</code>```

Of course, if you wish to restrict to the non-noise points, you can use

```<code>NonNoise = XY[XY6[,6] > 0.2,]
</code>```

Body:
Both R and EXCEL read and write .csv files, so you can use those to transfer the data back and forth.

You do not provide any data so I made some junk data to produce a similar problem.

DATA

set.seed(2017)
x = runif(8760, 0,16)
y = c(abs(rnorm(8000, 0, 1)), runif(760,0,8))
XY = data.frame(x,y)

One way to identify noise points is by looking at the distance to the nearest neighbors.  In dense areas, nearest neighbors will be closer. In non-dense areas, they will be further apart.  The package dbscan provides a nice function to get the distance to the k nearest neighbors. For this problem, I used k=6, but you may need to tune for your data. Looking at the distribution of distances to the 6th nearest neighbor we see that most points have 6 neighbors within a distance of 0.2

XY6 = kNNdist(XY, 6)
plot(density(XY6[,6]))

So I will assume that point whose 6th nearest neighbor is further away are noise points. Just changing the color to see which points are affected, we get

TYPE = rep(1,8760)
TYPE[XY6[,6] > 0.2] = 2
plot(XY, col=TYPE)

Of course, if you wish to restrict to the non-noise points, you can use

NonNoise = XY[XY6[,6] > 0.2,]


问:
iphone UISearchBar Done button always enabled
I have a UIViewController with a UISearchBar. I have replaced the Search Button by a Done button.

However, when one taps on the searchbar, the Done button is initially disabled. This occurs until one enters any character.

What I want to do is to have this Done button always enabled, such that if i tap on it i can inmediately dismiss the keyboard.

Any help? it would be highly appreciated.

I have on my UIViewController

```<code>-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    return YES;
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchBar.text.length == 0)
    {
        //[self fixOrientation];
        [searchBar resignFirstResponder];
    }
    else
    {
        NSLog(@"typed");
    }
}

-(void)searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar
{
    NSLog(@"began");  // this executes as soon as i tap on the searchbar, so I'm guessing this is the place to put whatever solution is available
}
</code>```

答:
Based on the Maps app, for example, it seems the pattern should be to have a cancel button near the textfield to get rid of the keyboard. With that said, one suggestion might be to have a custom UIButton placed right in that corner that looks just like the Done button.

Kind of a hacky solution...

Hope this helps!

Body:
I have a UIViewController with a UISearchBar. I have replaced the Search Button by a Done button.

However, when one taps on the searchbar, the Done button is initially disabled. This occurs until one enters any character.

What I want to do is to have this Done button always enabled, such that if i tap on it i can inmediately dismiss the keyboard.

Any help? it would be highly appreciated.

I have on my UIViewController

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    return YES;
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchBar.text.length == 0)
    {
        //[self fixOrientation];
        [searchBar resignFirstResponder];
    }
    else
    {
        NSLog(@"typed");
    }
}

-(void)searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar
{
    NSLog(@"began");  // this executes as soon as i tap on the searchbar, so I'm guessing this is the place to put whatever solution is available
}


问:
how to stop appium server through command line?
The command I'm using to start the Appium server:

```<code>node appium --address 127.0.0.1 --port 4723 --session-override --no-reset --platform-name Android --platform-version 23 --automation-name Appium
</code>```

How would I stop the server through command line?

答:
Ctrl+c

or

Run pkill -9 -f appium in the Terminal.

If you're looking to do this programmatically, see http://discuss.appium.io/t/launching-and-stopping-appium-server-programmtically/700.

Body:
The command I'm using to start the Appium server:

node appium --address 127.0.0.1 --port 4723 --session-override --no-reset --platform-name Android --platform-version 23 --automation-name Appium

How would I stop the server through command line?


问:
Simple type specifier is template parameter
According to ISO 14882:2011 § 14.6.2.1:

A type is dependent if it is — a template parameter,

And according to § ISO 14882:2011 14.6:

A name used in a template declaration or definition and that is
  dependent on a template-parameter is assumed not to name a type unless
  the applicable name lookup finds a type name or the name is qualified
  by the keyword typename.

But

```<code>template <typename T> class U
{
    typename T t; // ill-formed, i have an compilier error
};
</code>```

Are "dependent name" and "name used in a template declaration or definition and that is dependent on a template-parameter" the same concept?
I try to resolve my missunderstanding, since it looks as collision between  assertions in standard(ISO 14882:2011 § 14.6.2.1) and example from standard T t;.

答:
Your example code is ill-formed, because of ISO section 17.7.3 (http://eel.is/c++draft/temp.res#3): T is not a nested name-specifier.

Hence, there's no way T can be anything else but the typename T used as the template parameter. I.e. the compiler can't be mistaken, so you don't need to qualify it with the typename-specifier.

An example of a dependent type where the typename-specifier is required would be T::value_type, because the actual type/value of value_type depends on what T is. In that case you have to help the compiler out:

```<code>template <typename T> class U {
  using t = T;                      // OK
  using u = T::value_type;          // ill-formed: needs typename-specifier
  using v = typename t::value_type; // OK: qualified with typename keyword
};
</code>```

Let's say you have the following:

```<code>class foo {
  constexpr static int value_type = 7;
}

class bar {
  using value_type = int;
}
</code>```

This is the reason the 2nd typedef line above is ill-formed: if T is foo then value_type is not actually a type, but a constant with a very confusing name. If T is bar then all is well. But the compiler can't know this, so you have to help him out and assure him value_type is in fact a type. That also means you will be greeted with a compile error if you ever try to compile U<foo>.

Note: I used C++11 syntax for the typedefs, because I find it much more readable. The explanation above still holds if you use typedef instead of using.

Body:
According to ISO 14882:2011 § 14.6.2.1:

A type is dependent if it is — a template parameter,

And according to § ISO 14882:2011 14.6:

A name used in a template declaration or definition and that is
  dependent on a template-parameter is assumed not to name a type unless
  the applicable name lookup finds a type name or the name is qualified
  by the keyword typename.

But

template <typename T> class U
{
    typename T t; // ill-formed, i have an compilier error
};

Are "dependent name" and "name used in a template declaration or definition and that is dependent on a template-parameter" the same concept?
I try to resolve my missunderstanding, since it looks as collision between  assertions in standard(ISO 14882:2011 § 14.6.2.1) and example from standard T t;.

Body:
Your example code is ill-formed, because of ISO section 17.7.3 (http://eel.is/c++draft/temp.res#3): T is not a nested name-specifier.

Hence, there's no way T can be anything else but the typename T used as the template parameter. I.e. the compiler can't be mistaken, so you don't need to qualify it with the typename-specifier.

An example of a dependent type where the typename-specifier is required would be T::value_type, because the actual type/value of value_type depends on what T is. In that case you have to help the compiler out:

template <typename T> class U {
  using t = T;                      // OK
  using u = T::value_type;          // ill-formed: needs typename-specifier
  using v = typename t::value_type; // OK: qualified with typename keyword
};

Let's say you have the following:

class foo {
  constexpr static int value_type = 7;
}

class bar {
  using value_type = int;
}

This is the reason the 2nd typedef line above is ill-formed: if T is foo then value_type is not actually a type, but a constant with a very confusing name. If T is bar then all is well. But the compiler can't know this, so you have to help him out and assure him value_type is in fact a type. That also means you will be greeted with a compile error if you ever try to compile U<foo>.

Note: I used C++11 syntax for the typedefs, because I find it much more readable. The explanation above still holds if you use typedef instead of using.


问:
docker exec bash behaves weirdly
When I do:

docker exec -ti myContainer /bin/bash

I have a new bash terminal on running container myContainer.

Now when I write

docker exec -ti lescompanions /bin/bash -c "echo youpi"

docker only outputs youpi and returns with no interactive terminal created. I was actually expecting docker to create the terminal and run echo youpi within the newly created terminal.

Where am I wrong?

---- EDIT ----

Now how shall I run echo youpi in the new terminal on the existing container and not have the terminal return to the host after the execution of echo youpi?

答: echo youpi is a command that is run inside the container. The echo command prints the arguments given to it, which is youpi in this case, and that is also what you see.

Title: docker exec bash behaves weirdly


问:
Python 3: How to exit loop without stopping function
I am a complete newbie and have tried solving this problem (with my own head and with online research) for the last 5 hours.

Below is a snippet of a function we have written to simulate a game. We want to offer the ooportunity to start a new round - meaning if a player hits "b", the game should start again at the beginning of the range (0, players). But right now it just goes onto the next player in the range (if player 1 enters "b", the program calls player 2)

```<code>players = input(4)
if players in range(3, 9):
    for player in range(0, players):
        sum_points = 0
        throw_per_player_counter = 0
        print("\nIt is player no.", player+1, "'s turn!\n")
        print("\nPress 'return' to roll the dice.\n"
              "To start a new round press 'b'.\n"
              "Player", player+1)
        roll_dice = input(">>> ")
        if roll_dice == "b":
            player = 0
            throw_per_player_counter = 0
            sum_points = 0
            print("\n * A new round was started. * \n")
</code>```

I have tried return and break, also tried to put it all in another while-loop... failed. Break and return just ended the function.
Any hints highly appreciated!

答:
you could change the for loop to a while loop.  instead of using a range, make player a counter

```<code>players = 4
if 3 <= players < 9:
    player = 0  # here's where you make your counter
    while player < players:
        sum_points = 0
        throw_per_player_counter = 0
        print("\nIt is player no.", player+1, "'s turn!\n")
        print("\nPress 'return' to roll the dice.\n"
              "To start a new round press 'b'.\n"
              "Player", player+1)
        roll_dice = input(">>> ")
        player += 1  # increment it
        if roll_dice == "b":
            player = 0  # now your reset should work
            throw_per_player_counter = 0
            sum_points = 0
            print("\n * A new round was started. * \n")
</code>```

Body:
I am a complete newbie and have tried solving this problem (with my own head and with online research) for the last 5 hours.

Below is a snippet of a function we have written to simulate a game. We want to offer the ooportunity to start a new round - meaning if a player hits "b", the game should start again at the beginning of the range (0, players). But right now it just goes onto the next player in the range (if player 1 enters "b", the program calls player 2)

players = input(4)
if players in range(3, 9):
    for player in range(0, players):
        sum_points = 0
        throw_per_player_counter = 0
        print("\nIt is player no.", player+1, "'s turn!\n")
        print("\nPress 'return' to roll the dice.\n"
              "To start a new round press 'b'.\n"
              "Player", player+1)
        roll_dice = input(">>> ")
        if roll_dice == "b":
            player = 0
            throw_per_player_counter = 0
            sum_points = 0
            print("\n * A new round was started. * \n")

I have tried return and break, also tried to put it all in another while-loop... failed. Break and return just ended the function.
Any hints highly appreciated!

Body:
you could change the for loop to a while loop.  instead of using a range, make player a counter

players = 4
if 3 <= players < 9:
    player = 0  # here's where you make your counter
    while player < players:
        sum_points = 0
        throw_per_player_counter = 0
        print("\nIt is player no.", player+1, "'s turn!\n")
        print("\nPress 'return' to roll the dice.\n"
              "To start a new round press 'b'.\n"
              "Player", player+1)
        roll_dice = input(">>> ")
        player += 1  # increment it
        if roll_dice == "b":
            player = 0  # now your reset should work
            throw_per_player_counter = 0
            sum_points = 0
            print("\n * A new round was started. * \n")


问:
How can I port a Flash application to the BlackBerry PlayBook
I have a Flash application written in ActionScript 2 that I would like to port to the BlackBerry Playbook. The application is composed of an .swf file and a directory containing a large number of vector images. The path to these images (e.g. imagefolder/icons/icon1.swf) is hard-coded into an application and requires the image directory and the .swf file to be in the same directory.

I've installed the PlayBook SDK and have tried packaging the application with FlashBuilder 4, but I have no experience with this programme and have so far been unsuccessful. I tried placing the application in an SWFLoader component, but I then realised after reading this pdf document that MXML components are not supported. Since the app is written in AS2, I believe it cannot be compiled by Flash Builder. I don't need any any of the AIR features so I was wondering how could I embed the .swf and image directory in a Flash Builder ActionScript project so that it would run on the BlackBerry PlayBook.

答: The playbook uses AIR to play, so you need to be able to run it in AIR, which means that you need to have it working in as3. You could try "tricking it" by loading the AVM1 into AVM2.</p>


问:
Android material design - How do I place a breadcrumb (navigation) in the toolbar?
I am trying to figure out how to create a breadcrumb in my android app's (material design) toolbar.

This can be seen in the latest Dropbox android application, in which the breadcrumb is used to display the navigation of the files.

I have also found an image (which I took from another similar question), which can be seen here:

Can you guide me on how I can do this?

答: I know that this is fairly old but this seems just as good as any place to post this. There is a BreadcrumbsView via Github out there that seems to fit the need for purpose. Hope it helps anyone else looking for a similar solution.</p>