问:
Linear/Order Preserving Clustering in Python
I want to group numbers in a list, based on how 'large' the numbers are in comparison of their neighbors, but I want to do it continuously and via clustering if possible. To clarify, let me give you an example:

Suppose you have the list

```<code>lst = [10, 11.1, 30.4, 30.0, 32.9, 4.5, 7.2]
</code>```

then, if we have 3 groups, it's obvious how to cluster. Running the k-means algorithm from sklearn (see code) confirms this. But, when the numbers in the list aren't that 'convenient',  I run into trouble. Suppose you have the list:

```<code>lst = [10, 11.1, 30.4, 30.0, 32.9, 6.2, 31.2, 29.8, 12.3, 10.5]
</code>```

My problem now is two-fold:

I want some sort of 'order-preserving, linear' clustering, which takes the order of the data into account. For the list above, the clustering algorithm should give me a desired output of the form

```<code>lst = [0,0,1,1,1,1,1,1,2,2]
</code>```

If you look at this output above, you also see that I want the value 6.2 to be clustered in the second cluster, i.e. I want the cluster algorithm to see it as an outlier, not as an entirely new cluster.

EDIT For clarification, I want to be able to specify the amount of clusters in the linear clustering process, i.e. the 'end total' of clusters.

Code:

```<code>import numpy as np
from sklearn.cluster import KMeans

lst = [10, 11.1, 30.4, 30.0, 32.9, 4.5, 7.2]

km = KMeans(3,).fit(np.array(lst).reshape(-1,1))
print(km.labels_)
# [0 0 1 1 1 2 2]: OK output

lst = [10, 11.1, 30.4, 30.0, 32.9, 6.2, 31.2, 29.8, 12.3, 10.5]
km = KMeans(3,).fit(np.array(lst).reshape(-1,1))
print(km.labels_)
# [0 0 1 1 1 2 1 1 0 0]. Desired output: [0 0 1 1 1 1 1 1 2 2]
</code>```

答:
I had a similar problem and solved it as follows:

Given a distances matrix between all the elements,

I either do a bottom-up clustering (merging the two "most similar" elements/sub-clusters) or a top-down clustering (splitting a group of elements into the "most different" sub-clusters);

To compute the distance between sub-clusters I aggregate the distances of all the elements in them (the default method is taking the average, using the minimal or maximal distance is also possible).

Either way this results in a hierarchical clustering which you can then cut to produce any desired number of clusters.

It seems the bottom-up method gave better results, but YMMV.

Here's the code for the bottom-up method (in R). It builds:

A merge matrix where every row includes two columns with the indices of the next two things to merge - negative index for elements and positive index for previously created sub-clusters (R uses 1-based indices)

A height array containing the distance between the two merged elements/sub-clusters. This is added to the maximal height of the merged things (0 height for leaf elements) so heights are always increasing (for display of the tree, or as R calls it, the "dendogram").

This can be used to create R hclust objects which can be displayed and manipulated in various ways.

This isn't the most efficient possible implementation, but it gets the work done in a reasonable amount of time. A more efficient approach would be to reduce the size of the distances matrix (this would require more book keeping keeping track of the indices mapping between the smaller matrix and the original elements):

```<code>bottom_up <- function(distances, aggregation) {
    aggregate <- switch(aggregation, mean=mean, min=min, max=max)

    rows_count <- dim(distances)[1]
    diag(distances) <- Inf

    merge <- matrix(0, nrow=rows_count - 1, ncol=2)
    height <- rep(0, rows_count - 1)
    merged_height <- rep(0, rows_count)
    groups <- -(1:rows_count)

    for (merge_index in 1:(rows_count - 1)) {
        adjacent_distances <- pracma::Diag(distances, 1)

        low_index <- which.min(adjacent_distances)
        high_index <- low_index + 1

        grouped_indices <- sort(groups[c(low_index, high_index)])

        merged_indices <- which(groups %in% grouped_indices)
        groups[merged_indices] <- merge_index
        merge[merge_index,] <- grouped_indices

        height[merge_index] <- max(merged_height[merged_indices]) + adjacent_distances[low_index]
        merged_height[merged_indices] <- height[merge_index]

        merged_distances <- apply(distances[,merged_indices], 1, aggregate)
        distances[,merged_indices] <- merged_distances
        distances[merged_indices,] <- rep(merged_distances, each=length(merged_indices))

        distances[merged_indices, merged_indices] <- Inf
    }

    return (list(merge=merge, height=height))
}
</code>```

The pracma::Diag(distances, 1) fetches the offset-by-1 diagonal (above the main diagonal).

Body:
I want to group numbers in a list, based on how 'large' the numbers are in comparison of their neighbors, but I want to do it continuously and via clustering if possible. To clarify, let me give you an example:

Suppose you have the list

lst = [10, 11.1, 30.4, 30.0, 32.9, 4.5, 7.2]

then, if we have 3 groups, it's obvious how to cluster. Running the k-means algorithm from sklearn (see code) confirms this. But, when the numbers in the list aren't that 'convenient',  I run into trouble. Suppose you have the list:

lst = [10, 11.1, 30.4, 30.0, 32.9, 6.2, 31.2, 29.8, 12.3, 10.5]

My problem now is two-fold:

I want some sort of 'order-preserving, linear' clustering, which takes the order of the data into account. For the list above, the clustering algorithm should give me a desired output of the form

lst = [0,0,1,1,1,1,1,1,2,2]

If you look at this output above, you also see that I want the value 6.2 to be clustered in the second cluster, i.e. I want the cluster algorithm to see it as an outlier, not as an entirely new cluster.

EDIT For clarification, I want to be able to specify the amount of clusters in the linear clustering process, i.e. the 'end total' of clusters.

Code:

import numpy as np
from sklearn.cluster import KMeans

lst = [10, 11.1, 30.4, 30.0, 32.9, 4.5, 7.2]

km = KMeans(3,).fit(np.array(lst).reshape(-1,1))
print(km.labels_)
# [0 0 1 1 1 2 2]: OK output

lst = [10, 11.1, 30.4, 30.0, 32.9, 6.2, 31.2, 29.8, 12.3, 10.5]
km = KMeans(3,).fit(np.array(lst).reshape(-1,1))
print(km.labels_)
# [0 0 1 1 1 2 1 1 0 0]. Desired output: [0 0 1 1 1 1 1 1 2 2]

Body:
I had a similar problem and solved it as follows:

Given a distances matrix between all the elements,

I either do a bottom-up clustering (merging the two "most similar" elements/sub-clusters) or a top-down clustering (splitting a group of elements into the "most different" sub-clusters);

To compute the distance between sub-clusters I aggregate the distances of all the elements in them (the default method is taking the average, using the minimal or maximal distance is also possible).

Either way this results in a hierarchical clustering which you can then cut to produce any desired number of clusters.

It seems the bottom-up method gave better results, but YMMV.

Here's the code for the bottom-up method (in R). It builds:

A merge matrix where every row includes two columns with the indices of the next two things to merge - negative index for elements and positive index for previously created sub-clusters (R uses 1-based indices)

A height array containing the distance between the two merged elements/sub-clusters. This is added to the maximal height of the merged things (0 height for leaf elements) so heights are always increasing (for display of the tree, or as R calls it, the "dendogram").

This can be used to create R hclust objects which can be displayed and manipulated in various ways.

This isn't the most efficient possible implementation, but it gets the work done in a reasonable amount of time. A more efficient approach would be to reduce the size of the distances matrix (this would require more book keeping keeping track of the indices mapping between the smaller matrix and the original elements):

bottom_up <- function(distances, aggregation) {
    aggregate <- switch(aggregation, mean=mean, min=min, max=max)

    rows_count <- dim(distances)[1]
    diag(distances) <- Inf

    merge <- matrix(0, nrow=rows_count - 1, ncol=2)
    height <- rep(0, rows_count - 1)
    merged_height <- rep(0, rows_count)
    groups <- -(1:rows_count)

    for (merge_index in 1:(rows_count - 1)) {
        adjacent_distances <- pracma::Diag(distances, 1)

        low_index <- which.min(adjacent_distances)
        high_index <- low_index + 1

        grouped_indices <- sort(groups[c(low_index, high_index)])

        merged_indices <- which(groups %in% grouped_indices)
        groups[merged_indices] <- merge_index
        merge[merge_index,] <- grouped_indices

        height[merge_index] <- max(merged_height[merged_indices]) + adjacent_distances[low_index]
        merged_height[merged_indices] <- height[merge_index]

        merged_distances <- apply(distances[,merged_indices], 1, aggregate)
        distances[,merged_indices] <- merged_distances
        distances[merged_indices,] <- rep(merged_distances, each=length(merged_indices))

        distances[merged_indices, merged_indices] <- Inf
    }

    return (list(merge=merge, height=height))
}

The pracma::Diag(distances, 1) fetches the offset-by-1 diagonal (above the main diagonal).


来源: stackexchange

问:
Shredding XML column data into rows in SQL
I have an xml value

```<code><ITEMS>
<ITEM><ID>1</ID><NAME>John</NAME></ITEM>
<ITEM><ID>5</ID><NAME>James</NAME></ITEM>
</ITEMS>
</code>```

I am able to shred the above xml into tables of ID and Name column using the below query

```<code>Declare @X xml
select x.r.value('(ID)[1]','int') as [ID],
       x.r.value('(DATA)[1]','VARCHAR(100)') AS [DATA]
FROM @X.nodes ('/ITEMS/ITEM') AS x(r)
</code>```

But how will i able to do this when the above xml is present in a row.

```<code>S.No   COMPANY        DATA
 1      ABC      </ITEMS><ITEM><ID>1</ID><NAME>John</Name>....
</code>```

I need to populate like below

```<code>S.No   COMPANY    ID     NAME
 1      ABC        1    John
 2      ABC        5    James
</code>```

Note : The Data column in the table is of varchar data type and not xml data type.

答:
First, you can use a CTE to convert it to XML data type. Second way is via a derived table.

SQL

```<code>-- DDL and sample data population, start
DECLARE @tbl TABLE (SequentialNo INT PRIMARY KEY, Company VARCHAR(20), [DATA] VARCHAR(MAX));
INSERT INTO @tbl (SequentialNo, Company, [DATA])
VALUES
(1, 'ABC', '<ITEMS>
    <ITEM>
        <ID>1</ID>
        <NAME>John</NAME>
    </ITEM>
    <ITEM>
        <ID>5</ID>
        <NAME>James</NAME>
    </ITEM>
</ITEMS>');
-- DDL and sample data population, end

-- Method #1
-- CTE
;WITH rs AS
(
   SELECT *, TRY_CAST([DATA] AS XML) AS [xmldata]
   FROM @tbl
)
SELECT SequentialNo
    , Company
    , col.value('(ID/text())[1]','INT') AS ID
    , col.value('(NAME/text())[1]','VARCHAR(40)') AS [Name]
FROM rs AS tbl
    CROSS APPLY tbl.[xmldata].nodes('/ITEMS/ITEM') AS tab(col);

-- Method #2
-- Derived table
SELECT SequentialNo
    , Company
    , col.value('(ID/text())[1]','INT') AS ID
    , col.value('(NAME/text())[1]','VARCHAR(40)') AS [Name]
FROM (SELECT *, TRY_CAST([DATA] AS XML) AS [xmldata]
   FROM @tbl) AS tbl
    CROSS APPLY tbl.[xmldata].nodes('/ITEMS/ITEM') AS tab(col);
</code>```

Output

```<code>+--------------+---------+----+-------+
| SequentialNo | Company | ID | Name  |
+--------------+---------+----+-------+
|            1 | ABC     |  1 | John  |
|            1 | ABC     |  5 | James |
+--------------+---------+----+-------+
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an xml value

<ITEMS>
<ITEM><ID>1</ID><NAME>John</NAME></ITEM>
<ITEM><ID>5</ID><NAME>James</NAME></ITEM>
</ITEMS>

I am able to shred the above xml into tables of ID and Name column using the below query

Declare @X xml
select x.r.value('(ID)[1]','int') as [ID],
       x.r.value('(DATA)[1]','VARCHAR(100)') AS [DATA]
FROM @X.nodes ('/ITEMS/ITEM') AS x(r)

But how will i able to do this when the above xml is present in a row.

S.No   COMPANY        DATA
 1      ABC      </ITEMS><ITEM><ID>1</ID><NAME>John</Name>....

I need to populate like below

S.No   COMPANY    ID     NAME
 1      ABC        1    John
 2      ABC        5    James

Note : The Data column in the table is of varchar data type and not xml data type.

Body:
First, you can use a CTE to convert it to XML data type. Second way is via a derived table.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (SequentialNo INT PRIMARY KEY, Company VARCHAR(20), [DATA] VARCHAR(MAX));
INSERT INTO @tbl (SequentialNo, Company, [DATA])
VALUES
(1, 'ABC', '<ITEMS>
    <ITEM>
        <ID>1</ID>
        <NAME>John</NAME>
    </ITEM>
    <ITEM>
        <ID>5</ID>
        <NAME>James</NAME>
    </ITEM>
</ITEMS>');
-- DDL and sample data population, end

-- Method #1
-- CTE
;WITH rs AS
(
   SELECT *, TRY_CAST([DATA] AS XML) AS [xmldata]
   FROM @tbl
)
SELECT SequentialNo
    , Company
    , col.value('(ID/text())[1]','INT') AS ID
    , col.value('(NAME/text())[1]','VARCHAR(40)') AS [Name]
FROM rs AS tbl
    CROSS APPLY tbl.[xmldata].nodes('/ITEMS/ITEM') AS tab(col);

-- Method #2
-- Derived table
SELECT SequentialNo
    , Company
    , col.value('(ID/text())[1]','INT') AS ID
    , col.value('(NAME/text())[1]','VARCHAR(40)') AS [Name]
FROM (SELECT *, TRY_CAST([DATA] AS XML) AS [xmldata]
   FROM @tbl) AS tbl
    CROSS APPLY tbl.[xmldata].nodes('/ITEMS/ITEM') AS tab(col);

Output

+--------------+---------+----+-------+
| SequentialNo | Company | ID | Name  |
+--------------+---------+----+-------+
|            1 | ABC     |  1 | John  |
|            1 | ABC     |  5 | James |
+--------------+---------+----+-------+


问:
ARMV4i (Windows Mobile 6) Native Code disassembler
Does anyone know of a disassembler for ARMV4i executables and DLLs?

I've got a plug-in DLL I'm writing with a very rare data abort (<5% of the time) that I have narrowed down to a specific function (via dumpbin and the address output by the data abort).  However, it is a fairly large function and I would like to narrow it down a little.  I know it's happening in a memset() call, but that particular function has about 35 of them, so I was hoping that by looking at the disassembly I could figure out where about the problem actually is.

答:
ChARMeD is a Windows Mobile / Pocket PC /  Win CE (for ARM CPUs) Disassembler and Assembler

You might also look at BDASM, a shareware disassembler - later versions have ARM plugins.  The website seems to be down, but if you search for it you'll find the shareware distribution.

The source code for the simple ARM disassembler, DISARM, is available as well.

The binutils (linux compiler tools) objdump can be used to produce disassembly, "objdump -b binary -m arm7tdmi -D file_name"

-Adam

OwnerDisplayName: Adam Haile

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Adam Davis

ContentLicense: CC BY-SA 2.5


问:
Template or abstract base class?
If I want to make a class adaptable, and make it possible to select different algorithms from the outside -- what is the best implementation in C++?

I see mainly two possibilities:

Use an abstract base class and pass concrete object in

Use a template

Here is a little example, implemented in the various versions:

Version 1: Abstract base class

```<code>class Brake {
public: virtual void stopCar() = 0;
};

class BrakeWithABS : public Brake {
public: void stopCar() { ... }
};

class Car {
  Brake* _brake;
public:
  Car(Brake* brake) : _brake(brake) { brake->stopCar(); }
};
</code>```

Version 2a: Template

```<code>template<class Brake>
class Car {
  Brake brake;
public:
  Car(){ brake.stopCar(); }
};
</code>```

Version 2b: Template and private inheritance

```<code>template<class Brake>
class Car : private Brake {
  using Brake::stopCar;
public:
  Car(){ stopCar(); }
};
</code>```

Coming from Java, I am naturally inclined to always use version 1, but the templates versions seem to be preferred often, e.g. in STL code? If that's true, is it just because of memory efficiency etc (no inheritance, no virtual function calls)?

I realize there is not a big difference between version 2a and 2b, see C++ FAQ.

Can you comment on these possibilities?

答:
Use interface if you suppose to support different Break classes and its hierarchy at once.

```<code>Car( new Brake() )
Car( new BrakeABC() )
Car( new CoolBrake() )
</code>```

And you don't know this information at compile time.

If you know which Break you are going to use 2b is right choice for you to specify different Car classes. Brake in this case will be your car "Strategy" and you can set default one.

I wouldn't use 2a. Instead you can add static methods to Break and call them without instance.

Title: Template or abstract base class?

Body:
If I want to make a class adaptable, and make it possible to select different algorithms from the outside -- what is the best implementation in C++?

I see mainly two possibilities:

Use an abstract base class and pass concrete object in

Use a template

Here is a little example, implemented in the various versions:

Version 1: Abstract base class

class Brake {
public: virtual void stopCar() = 0;
};

class BrakeWithABS : public Brake {
public: void stopCar() { ... }
};

class Car {
  Brake* _brake;
public:
  Car(Brake* brake) : _brake(brake) { brake->stopCar(); }
};

Version 2a: Template

template<class Brake>
class Car {
  Brake brake;
public:
  Car(){ brake.stopCar(); }
};

Version 2b: Template and private inheritance

template<class Brake>
class Car : private Brake {
  using Brake::stopCar;
public:
  Car(){ stopCar(); }
};

Coming from Java, I am naturally inclined to always use version 1, but the templates versions seem to be preferred often, e.g. in STL code? If that's true, is it just because of memory efficiency etc (no inheritance, no virtual function calls)?

I realize there is not a big difference between version 2a and 2b, see C++ FAQ.

Can you comment on these possibilities?

Body:
Use interface if you suppose to support different Break classes and its hierarchy at once.

Car( new Brake() )
Car( new BrakeABC() )
Car( new CoolBrake() )

And you don't know this information at compile time.

If you know which Break you are going to use 2b is right choice for you to specify different Car classes. Brake in this case will be your car "Strategy" and you can set default one.

I wouldn't use 2a. Instead you can add static methods to Break and call them without instance.

OwnerDisplayName: Mykola Golubyev


问:
How to detect Pivot View using MVVM in WP7?
basically I have a pivot control in my WP7 app that contains 3 views. On each view I'm calling 1 of my 3 different web services that I run. What I'm trying to do is call the service only when they navigate to that particular view.

It's pretty simple using the code behind because all you do is use selected index with a switch statement and you can fire certain methods accordingly. Any idea on how to accomplish this from a view model?

NOTE: I'm using MVVM Light.

UPDATE: Here's my code that I would normally use:

```<code>private void PivotItem_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        int currentPivot = ResultsPivot.SelectedIndex;
        switch (currentPivot)
        {
            case 0:
                //Fire Method 1
                break;
            case 1:
                //Fire Method 2
                break;
            case 2:
                //Fire Method 3
                break;
            default:
                //Fire default method
                break;
        }
    }
</code>```

答:
I like to keep things simple in situations like these where the View needs to notify the ViewModel that something that is so trivial changed (for example: A trivial combobox selection change that really has nothing to do with the view state (i.e ViewModel)).

For your specific case, in your switch statement, just call a public method in your ViewModel.
How to get the viewmodel reference? You can obtain that by the view's DataContext. So now your views can call public methods (and properties) within your viewModel.

For significant things stick with DataBinding. otherwise, just call directly. Saves so much time and hassle.

Body:
basically I have a pivot control in my WP7 app that contains 3 views. On each view I'm calling 1 of my 3 different web services that I run. What I'm trying to do is call the service only when they navigate to that particular view.

It's pretty simple using the code behind because all you do is use selected index with a switch statement and you can fire certain methods accordingly. Any idea on how to accomplish this from a view model?

NOTE: I'm using MVVM Light.

UPDATE: Here's my code that I would normally use:

private void PivotItem_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        int currentPivot = ResultsPivot.SelectedIndex;
        switch (currentPivot)
        {
            case 0:
                //Fire Method 1
                break;
            case 1:
                //Fire Method 2
                break;
            case 2:
                //Fire Method 3
                break;
            default:
                //Fire default method
                break;
        }
    }


问:
How to resolve one day offset problem for a date in Java Spring
I am very tired. I cannot resolve the problem with one day lost in Java Spring. There are many similar questions in stackoverflow, but none of them helped me.

My Spring App uses java.time.LocalDate package and accepts birthday from date field on frontend (react-datetime component). In yyyy-mm-dd format. Spring uses jdbc to save data to table in mysql database.

The birthday saved into DB as one day lost. For example user entered  - 1998-04-12  then it will be saved as 1998-04-11. This happens only for some months, the months from november till march saved correctly to DB, but other months with one day lost. This is both on creating and on editing of the user.

Here is the code:

```<code>...
import java.time.LocalDate;

public class UserInfo {
...
public LocalDate birthday;

}
</code>```

...

```<code>@PreAuthorize("hasAnyAuthority('ADMIN_GROUP_EDIT, SPEC_USERS_EDIT, USERS_EDIT, REGISTRATION_DATA_EDIT')")
@RequestMapping(value = "/update/{id}", method = PUT)
public void update(HttpServletResponse response, HttpServletRequest request, @PathVariable Long id) {
    User curUser = getUser();
    log.info("Got update user request by user " + curUser);
    log.info("For user id " + id);
    String reqBody = Utils.toString(request);
    if (reqBody == null) {
        returnError(response, RestErrorCode.EMPTY_REQUEST);
        return;
    }
    JsonElement body = new JsonParser().parse(reqBody);
    JsonObject jsonObject = body.getAsJsonObject();
    if (jsonObject == null) {
        log.error(BAD_REQUEST_BODY_MESS);
        return;
    }

    UserInfo info = null;

    if (jsonObject.has("info")) {
        String infoStr = jsonObject.get("info").toString();
        info = GsonHelper.fromJson(infoStr, UserInfo.class);
    }

 userService.updateUserInfo(info);
</code>```

...

```<code>@Transactional
    public int updateUserInfo(UserInfo info) {
        info.editorUserId = AuthProvider.getCurUserId();
        return transactionTemplate.execute(status -> {
            String update = "" +
                "UPDATE USER_INFO " +
                "   SET first_name = COALESCE(:firstName, first_name), " +
                "   middle_name = COALESCE(:middleName, middle_name), " +
                "   last_name = COALESCE(:lastName, last_name), " +
                "   birthday = COALESCE(:birthday, birthday), " +
                "   address = COALESCE(:address, address)," +
                "   email = COALESCE(:email, email)," +
               "WHERE id =:id";
            return npDb.update(update, new FieldSqlParameterSource(info));
        });
    }
</code>```

I debugged my code, backend correctly accepts user's birthday and uses simple jdbc but where is the rat I didn't find.  How to overcome this problem?

答: This looks like a timezone issue, specifically one regarding the daylight savings time (last sunday in march to last sunday in october in European countries). Check that the timezone settings of the machine, your Java environment and the database server match. Dates like birthdays should be of type DATE (not TIMESTAMP).</p>

Body:
I am very tired. I cannot resolve the problem with one day lost in Java Spring. There are many similar questions in stackoverflow, but none of them helped me.

My Spring App uses java.time.LocalDate package and accepts birthday from date field on frontend (react-datetime component). In yyyy-mm-dd format. Spring uses jdbc to save data to table in mysql database.

The birthday saved into DB as one day lost. For example user entered  - 1998-04-12  then it will be saved as 1998-04-11. This happens only for some months, the months from november till march saved correctly to DB, but other months with one day lost. This is both on creating and on editing of the user.

Here is the code:

...
import java.time.LocalDate;

public class UserInfo {
...
public LocalDate birthday;

}

...

@PreAuthorize("hasAnyAuthority('ADMIN_GROUP_EDIT, SPEC_USERS_EDIT, USERS_EDIT, REGISTRATION_DATA_EDIT')")
@RequestMapping(value = "/update/{id}", method = PUT)
public void update(HttpServletResponse response, HttpServletRequest request, @PathVariable Long id) {
    User curUser = getUser();
    log.info("Got update user request by user " + curUser);
    log.info("For user id " + id);
    String reqBody = Utils.toString(request);
    if (reqBody == null) {
        returnError(response, RestErrorCode.EMPTY_REQUEST);
        return;
    }
    JsonElement body = new JsonParser().parse(reqBody);
    JsonObject jsonObject = body.getAsJsonObject();
    if (jsonObject == null) {
        log.error(BAD_REQUEST_BODY_MESS);
        return;
    }

    UserInfo info = null;

    if (jsonObject.has("info")) {
        String infoStr = jsonObject.get("info").toString();
        info = GsonHelper.fromJson(infoStr, UserInfo.class);
    }

 userService.updateUserInfo(info);

...

@Transactional
    public int updateUserInfo(UserInfo info) {
        info.editorUserId = AuthProvider.getCurUserId();
        return transactionTemplate.execute(status -> {
            String update = "" +
                "UPDATE USER_INFO " +
                "   SET first_name = COALESCE(:firstName, first_name), " +
                "   middle_name = COALESCE(:middleName, middle_name), " +
                "   last_name = COALESCE(:lastName, last_name), " +
                "   birthday = COALESCE(:birthday, birthday), " +
                "   address = COALESCE(:address, address)," +
                "   email = COALESCE(:email, email)," +
               "WHERE id =:id";
            return npDb.update(update, new FieldSqlParameterSource(info));
        });
    }

I debugged my code, backend correctly accepts user's birthday and uses simple jdbc but where is the rat I didn't find.  How to overcome this problem?


问:
How to fetch data for chart js Pie Chart from State in React js?
As I am new to react i have been struggling to pass data from my state to the chartjs dynamically...what I need is when ever user updates the Textbox and asks for the Output, the Pie chart should update itself automatically according to the output...i have stored the output values in the state but Pie chart is not allowing me to Pass state as data...

Here's a Link to the Code Sandbox
https://codesandbox.io/s/autumn-mountain-sv1qk?fontsize=14&hidenavigation=1&theme=dark

```<code> class Buyer extends Component {

        constructor(props) {
            super(props);
            this.state = {
                income: 100000,
                percent: 13,
                totalTax: '',
                grossPrice: '',
                otherValues: '',
            }
        }

PieChart = (Gross,totalTax) => {
    let GrossPrice = Gross  ;
    let TotalTax = totalTax ;
    let data = [GrossPrice,TotalTax]
    let Pie = {
            labels: ['Total Tax', 'Gross Price'],
            datasets: [{
                data: data,
                backgroundColor: [
                    '#1ca5b6',
                    '#89ba2b',
                ],

            }]

        }

    }

handleIncome = (event) => {
    let income = event.target.value
    this.handleData(income, this.state.percent)
    console.log(this.state)

}

handlePercent = (event) => {
    let Percent = event.target.value
    this.handleSliderData(this.state.income, Percent)

}

// From Slider
sliderIncome = (event) => {
    this.setState({ income: event })
    this.handleSliderData(event, this.state.percent)
    // console.log(this.state)

}

sliderPercent = (event) => {
    this.setState({ percent: event })
    this.handleSliderData(this.state.income, event)

}

handleData = (income, Percent) => {
    this.setState({
        income: income,
        percent: Percent,
        totalTax: //some Calculations
        grossPrice: //some Calculations
        otherValues: //some Calculations

    })

    console.log(this.state)
}

handleSliderData = (income, Percent) => {
    this.setState({
        income: income,
        percent: Percent,
        totalTax: //some Calculations
        grossPrice://some Calculations
        otherValues://some Calculations
    })
    this.PieChart(this.state.grossPrice,this.state.totalTax)
    // console.log(this.state)

}

render() {
            return (
              <div>
                    <div >
                        <Card s>
                            <PieChart data={this.PieChart} width={600} height={300} />
                        </Card>
                    </div>
                </Col>

              )
     }
</code>```

I have tried creating a function for the pie chart but was not able to get through...any help would be appreciated..thanks!!

答:
I think i found the solution for the particular problem...i order to update the data in the piechart dynamically using state we have create a state in the constructor(props) like so...

```<code>constructor(props) {
        super(props);
        this.state = {
            income: '',
            percent: '',
            totalTax: '',
            grossPrice: '',
            otherValues: '',
            Data: {}
        }

    }
</code>```

Then i have used componentDidMount() to mount the initial state of the PieChart like So....

```<code>componentDidMount() {

        let runscore = [100,200];

        this.setState(
            {
                Data: {
                    labels: [
                        'Purple',
                        'Yellow',

                    ],
                    datasets: [
                        {

                            data: runscore,
                            backgroundColor: [
                                '#1ca5b6',
                                '#89ba2b',

                            ]
                        }
                    ]
                }
            });

    }
</code>```

then i created a function PieChart = (Gross,totalTax) that fetches data from another functions and used that to set state in Data like so...

```<code>PieChart = (Gross,totalTax) => {
        let runscore = [Gross,totalTax];
        this.setState({
            Data: {
                labels: [
                    'Gross Price',
                    'Total Tax',

                ],
                datasets: [
                    {
                        data: runscore,
                        backgroundColor: [
                            '#1ca5b6',
                            '#89ba2b',
                        ]
                    }
                ]
            }
        });

        }
</code>```

For now this is not updating the state in sync with the current state but i gets the work done...i hope this helps others...

Body:
As I am new to react i have been struggling to pass data from my state to the chartjs dynamically...what I need is when ever user updates the Textbox and asks for the Output, the Pie chart should update itself automatically according to the output...i have stored the output values in the state but Pie chart is not allowing me to Pass state as data...

Here's a Link to the Code Sandbox
https://codesandbox.io/s/autumn-mountain-sv1qk?fontsize=14&hidenavigation=1&theme=dark

 class Buyer extends Component {

        constructor(props) {
            super(props);
            this.state = {
                income: 100000,
                percent: 13,
                totalTax: '',
                grossPrice: '',
                otherValues: '',
            }
        }

PieChart = (Gross,totalTax) => {
    let GrossPrice = Gross  ;
    let TotalTax = totalTax ;
    let data = [GrossPrice,TotalTax]
    let Pie = {
            labels: ['Total Tax', 'Gross Price'],
            datasets: [{
                data: data,
                backgroundColor: [
                    '#1ca5b6',
                    '#89ba2b',
                ],

            }]

        }

    }

handleIncome = (event) => {
    let income = event.target.value
    this.handleData(income, this.state.percent)
    console.log(this.state)

}

handlePercent = (event) => {
    let Percent = event.target.value
    this.handleSliderData(this.state.income, Percent)

}

// From Slider
sliderIncome = (event) => {
    this.setState({ income: event })
    this.handleSliderData(event, this.state.percent)
    // console.log(this.state)

}

sliderPercent = (event) => {
    this.setState({ percent: event })
    this.handleSliderData(this.state.income, event)

}

handleData = (income, Percent) => {
    this.setState({
        income: income,
        percent: Percent,
        totalTax: //some Calculations
        grossPrice: //some Calculations
        otherValues: //some Calculations

    })

    console.log(this.state)
}

handleSliderData = (income, Percent) => {
    this.setState({
        income: income,
        percent: Percent,
        totalTax: //some Calculations
        grossPrice://some Calculations
        otherValues://some Calculations
    })
    this.PieChart(this.state.grossPrice,this.state.totalTax)
    // console.log(this.state)

}

render() {
            return (

                        <Card s>
                            <PieChart data={this.PieChart} width={600} height={300} />
                        </Card>

                </Col>

              )
     }

I have tried creating a function for the pie chart but was not able to get through...any help would be appreciated..thanks!!

Body:
I think i found the solution for the particular problem...i order to update the data in the piechart dynamically using state we have create a state in the constructor(props) like so...

constructor(props) {
        super(props);
        this.state = {
            income: '',
            percent: '',
            totalTax: '',
            grossPrice: '',
            otherValues: '',
            Data: {}
        }

    }

Then i have used componentDidMount() to mount the initial state of the PieChart like So....

componentDidMount() {

        let runscore = [100,200];

        this.setState(
            {
                Data: {
                    labels: [
                        'Purple',
                        'Yellow',

                    ],
                    datasets: [
                        {

                            data: runscore,
                            backgroundColor: [
                                '#1ca5b6',
                                '#89ba2b',

                            ]
                        }
                    ]
                }
            });

    }

then i created a function PieChart = (Gross,totalTax) that fetches data from another functions and used that to set state in Data like so...

PieChart = (Gross,totalTax) => {
        let runscore = [Gross,totalTax];
        this.setState({
            Data: {
                labels: [
                    'Gross Price',
                    'Total Tax',

                ],
                datasets: [
                    {
                        data: runscore,
                        backgroundColor: [
                            '#1ca5b6',
                            '#89ba2b',
                        ]
                    }
                ]
            }
        });

        }

For now this is not updating the state in sync with the current state but i gets the work done...i hope this helps others...


问:
Waitforstatus service powershell
I have written a script to stop the services on any server!
But I get error:

```<code>      YMethod invocation failed because[System.ServiceProcess.ServiceControllerStatus] does not contain a method   named 'WaitForStatus'.
    At C:\Admin\Scripts\JBoss_StartStopp\stoppa_alla_IX2 och IX3.ps1:18 char:7
    +       $getservicestatus.WaitForStatus("Stopped")
    +       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound
</code>```

When you quit a service on a server, I want to wait until the service is stopped and then go to the next service on the next server!

```<code>   $serverlist = Get-Content “.\server.txt”
   $servicename = "JBoss_cambio"

   $serverlistIX3 = Get-Content “.\ix3.txt”
   $servicenameIX3 = "Laskopia_Cosmic"

  foreach ($server in $serverlist) {

$getservicestatus = (Get-Service -Name $servicename -ComputerName $server).status
if ($getservicestatus -eq "Running") {
  Set-Service -Name $servicename -ComputerName $server -Status Stopped

  $getservicestatusIX3.WaitForStatus("Stopped")

  Write-Host "$server $servicename Stoppad!" -ForegroundColor Green
  }
else
  {
  Write-Host "$server $servicename var redan Stopped!" -ForegroundColor Yellow
  }
}

   foreach ($server in $serverlistIX3) {

$getservicestatusIX3 = (Get-Service -Name $servicenameIX3 -ComputerName $server).status
if ($getservicestatusIX3 -eq "Running") {
  Set-Service -Name $servicenameIX3 -ComputerName $server -Status Stopped
  $getservicestatusIX3.WaitForStatus("Stopped")
  Write-Host "$server $servicenameIX3 Sttopad!" -ForegroundColor Green
  }
else
  {
  Write-Host "$server $servicenameIX3 var redan Stoppad!" -ForegroundColor Yellow
  }
}

    Write-Host "." -ForegroundColor DarkBlue
     Read-Host "Tryck ENTER för att avsluta"
</code>```

答: Unless you use a time-span parameter, wait will continually test every 1/4 second or so and may inadvertently wait forever. </p>

Title: Waitforstatus service powershell

Body:
I have written a script to stop the services on any server!
But I get error:

      YMethod invocation failed because[System.ServiceProcess.ServiceControllerStatus] does not contain a method   named 'WaitForStatus'.
    At C:\Admin\Scripts\JBoss_StartStopp\stoppa_alla_IX2 och IX3.ps1:18 char:7
    +       $getservicestatus.WaitForStatus("Stopped")
    +       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

When you quit a service on a server, I want to wait until the service is stopped and then go to the next service on the next server!

   $serverlist = Get-Content “.\server.txt”
   $servicename = "JBoss_cambio"

   $serverlistIX3 = Get-Content “.\ix3.txt”
   $servicenameIX3 = "Laskopia_Cosmic"

  foreach ($server in $serverlist) {

$getservicestatus = (Get-Service -Name $servicename -ComputerName $server).status
if ($getservicestatus -eq "Running") {
  Set-Service -Name $servicename -ComputerName $server -Status Stopped

  $getservicestatusIX3.WaitForStatus("Stopped")

  Write-Host "$server $servicename Stoppad!" -ForegroundColor Green
  }
else
  {
  Write-Host "$server $servicename var redan Stopped!" -ForegroundColor Yellow
  }
}

   foreach ($server in $serverlistIX3) {

$getservicestatusIX3 = (Get-Service -Name $servicenameIX3 -ComputerName $server).status
if ($getservicestatusIX3 -eq "Running") {
  Set-Service -Name $servicenameIX3 -ComputerName $server -Status Stopped
  $getservicestatusIX3.WaitForStatus("Stopped")
  Write-Host "$server $servicenameIX3 Sttopad!" -ForegroundColor Green
  }
else
  {
  Write-Host "$server $servicenameIX3 var redan Stoppad!" -ForegroundColor Yellow
  }
}

    Write-Host "." -ForegroundColor DarkBlue
     Read-Host "Tryck ENTER för att avsluta"


问:
Unable to load a pandas dataframe having a JSON column into mysql database
I have a pandas dataframe that looks like this when I print it out in the terminal in pycharm. This is inside a django project

```<code>`     exception              recommendation    time_dimension_id
0  {'exception': []}               0                217
1  {'exception': []}               0                218
2  {'exception': []}               0                219
3  {'exception': []}             546                220
4  {'exception': []}            2876                221
5  {'exception': []}            7855                222
6  {'exception': [{'error...  , 5041                223
7  {'exception': []}              57                224
8  {'exception': []}               0                225
9  {'exception': []}               0                226
10 {'exception': []}               0                227
11 {'exception': []}             108                228
12 {'exception': []}               0                229
13 {'exception': []}              12                230
14 {'exception': []}               0                231
15 {'exception': []}               0                232
16 {'exception': []}               0                233
17 {'exception': []}               0                234
18 {'exception': []}               0                235
19 {'exception': []}               0                236
20 {'exception': []}               0                237
21 {'exception': []}               0                238
22 {'exception': []}               0                239
23 {'exception': []}               0                240
`
</code>```

I tried to insert this dataframe into a table using the below code.

```<code>connection = engine.connect()
    df.to_sql('table_name', con=connection, if_exists='append', index=False)
</code>```

Then, I got the below error

graphql.error.located_error.GraphQLLocatedError: (MySQLdb._exceptions.OperationalError) (3140, 'Invalid JSON text: "Missing a name for object member." at position 1 in value for column \'fact_exception.exception\'.') [SQL: 'INSERT INTO fact_exception (exception, recommendation, time_dimension_id) VALUES (%s, %s, %s)'] [parameters: (({'exception': []}, 0, 217), ({'exception': []}, 0, 218), ({'exception': []}, 0, 219), ({'exception': []}, 546, 220), ({'exception': []}, 2876, 221), ({'exception': []}, 7855, 222), ({'exception': [{'error': '', 'fatal': 'com.materiall.recommender.cache.MetaLU:58 - Cannot Load metaLU for express_com-u1456154309768com.materiall.conn ... (6923 characters truncated) ... "resource.type":"index_or_alias","resource.id":"null","index_uuid":"na","index":"null"},"status":404}\n', 'time_stamp': '2020-02-11T06:26:23,694'}]}, 5041, 223), ({'exception': []}, 57, 224)  ... displaying 10 of 24 total bound parameter sets ...  ({'exception': []}, 0, 239), ({'exception': []}, 0, 240))] (Background on this error at: http://sqlalche.me/e/e3q8)

Below the relevant code used to create the dataframe column-wise

```<code>        fact_excep["exception"] = excep_df_column #this is a list of dictionaries
        fact_excep["recommendation"] = recommendation_col #this is a list integers
        fact_excep["time_dimension_id"] = time_dimension_id_col #this is a list integers
        # print(fact_excep)
    connection = engine.connect()
    fact_excep.to_sql("fact_exception", con=connection, if_exists="append", index=False)
    response = "fact_exception data created"
    return response
</code>```

Below is the model

```<code>class FactException (models.Model):    #this is the model
fact_exception_id = models.AutoField(primary_key=True)
time_dimension_id = models.ForeignKey(
    TimeDimension, null=False, blank=True, db_column="time_dimension_id", on_delete=models.CASCADE)
recommendation = models.IntegerField()
exception = JSONField(null=True, blank=True)

objects = models.Manager()

class Meta:
    db_table = 'fact_exception'

def __int__(self):
    return self.fact_exception_id
</code>```

Any help will be appreciated.

答:
Your column does not contain valid JSON:

```<code>{'exception': [{'error': '', 'fatal': 'com.materiall.recommender.cache.MetaLU:58 - Cannot Load metaLU for express_com-u1456154309768com.materiall.conn...'}]}
# and
{'exception': []}
</code>```

is not valid because the keys and strings have single quotes, which isn't valid in JSON. You should use double quotes and the whole column should be strings:

```<code>'{"exception": [{"error": "", "fatal": "com.materiall.recommender.cache.MetaLU:58 - Cannot Load metaLU for express_com-u1456154309768com.materiall.conn..."}]}'
# and
'{"exception": []}'
</code>```

You're setting the column using a list of python dicts, but since you use df.to_sql() to save, this requires your data frame to have the exact data required by the SQL query. If you were using your model, you could just assign my_factexception.exception = some_dict and it would save as JSON. But you're essentially bypassing the Django ORM that knows your model and knows how to map a dictionary to a jsonb field so you have to do it yourself.

So when you set the values for your exception column, use json.dumps(some_dict) to create json strings.

Body:
I have a pandas dataframe that looks like this when I print it out in the terminal in pycharm. This is inside a django project

`     exception              recommendation    time_dimension_id
0  {'exception': []}               0                217
1  {'exception': []}               0                218
2  {'exception': []}               0                219
3  {'exception': []}             546                220
4  {'exception': []}            2876                221
5  {'exception': []}            7855                222
6  {'exception': [{'error...  , 5041                223
7  {'exception': []}              57                224
8  {'exception': []}               0                225
9  {'exception': []}               0                226
10 {'exception': []}               0                227
11 {'exception': []}             108                228
12 {'exception': []}               0                229
13 {'exception': []}              12                230
14 {'exception': []}               0                231
15 {'exception': []}               0                232
16 {'exception': []}               0                233
17 {'exception': []}               0                234
18 {'exception': []}               0                235
19 {'exception': []}               0                236
20 {'exception': []}               0                237
21 {'exception': []}               0                238
22 {'exception': []}               0                239
23 {'exception': []}               0                240
`

I tried to insert this dataframe into a table using the below code.

connection = engine.connect()
    df.to_sql('table_name', con=connection, if_exists='append', index=False)

Then, I got the below error

graphql.error.located_error.GraphQLLocatedError: (MySQLdb._exceptions.OperationalError) (3140, 'Invalid JSON text: "Missing a name for object member." at position 1 in value for column \'fact_exception.exception\'.') [SQL: 'INSERT INTO fact_exception (exception, recommendation, time_dimension_id) VALUES (%s, %s, %s)'] [parameters: (({'exception': []}, 0, 217), ({'exception': []}, 0, 218), ({'exception': []}, 0, 219), ({'exception': []}, 546, 220), ({'exception': []}, 2876, 221), ({'exception': []}, 7855, 222), ({'exception': [{'error': '', 'fatal': 'com.materiall.recommender.cache.MetaLU:58 - Cannot Load metaLU for express_com-u1456154309768com.materiall.conn ... (6923 characters truncated) ... "resource.type":"index_or_alias","resource.id":"null","index_uuid":"na","index":"null"},"status":404}\n', 'time_stamp': '2020-02-11T06:26:23,694'}]}, 5041, 223), ({'exception': []}, 57, 224)  ... displaying 10 of 24 total bound parameter sets ...  ({'exception': []}, 0, 239), ({'exception': []}, 0, 240))] (Background on this error at: http://sqlalche.me/e/e3q8)

Below the relevant code used to create the dataframe column-wise

        fact_excep["exception"] = excep_df_column #this is a list of dictionaries
        fact_excep["recommendation"] = recommendation_col #this is a list integers
        fact_excep["time_dimension_id"] = time_dimension_id_col #this is a list integers
        # print(fact_excep)
    connection = engine.connect()
    fact_excep.to_sql("fact_exception", con=connection, if_exists="append", index=False)
    response = "fact_exception data created"
    return response

Below is the model

class FactException (models.Model):    #this is the model
fact_exception_id = models.AutoField(primary_key=True)
time_dimension_id = models.ForeignKey(
    TimeDimension, null=False, blank=True, db_column="time_dimension_id", on_delete=models.CASCADE)
recommendation = models.IntegerField()
exception = JSONField(null=True, blank=True)

objects = models.Manager()

class Meta:
    db_table = 'fact_exception'

def __int__(self):
    return self.fact_exception_id

Any help will be appreciated.

Body:
Your column does not contain valid JSON:

{'exception': [{'error': '', 'fatal': 'com.materiall.recommender.cache.MetaLU:58 - Cannot Load metaLU for express_com-u1456154309768com.materiall.conn...'}]}
# and
{'exception': []}

is not valid because the keys and strings have single quotes, which isn't valid in JSON. You should use double quotes and the whole column should be strings:

'{"exception": [{"error": "", "fatal": "com.materiall.recommender.cache.MetaLU:58 - Cannot Load metaLU for express_com-u1456154309768com.materiall.conn..."}]}'
# and
'{"exception": []}'

You're setting the column using a list of python dicts, but since you use df.to_sql() to save, this requires your data frame to have the exact data required by the SQL query. If you were using your model, you could just assign my_factexception.exception = some_dict and it would save as JSON. But you're essentially bypassing the Django ORM that knows your model and knows how to map a dictionary to a jsonb field so you have to do it yourself.

So when you set the values for your exception column, use json.dumps(some_dict) to create json strings.


问:
javascript not well-formed
I have an hmtl file which includes another javascript as

```<code><script type="text/javascript" src="hello.js"></script>
<div>
something
</div>
</code>```

This html file is loaded via de .load()
and it loads it in a div from the main page

This tells me that the first line is not well-formed

```<code>$(".flip").live("click", function() {

         $(this).find("div.panel").slideToggle("slow")
     });
     $(".flip").live("mouseover", function() {
         $(this).css('cursor', 'pointer');
     });
</code>```

If i remove this, it will tell me the next element is not well-formed and so on. If I include this javascript in a page which is not called via .load, it doesn't say any error. Is this because i'm calling this java script inside a div? and not in the head?

答:
try to write the javascript code inde this function</p>

```<code>$(document).ready(function(){
//Here insert your javascript code
});
</code>```

Title: javascript not well-formed

Body:
I have an hmtl file which includes another javascript as

something

This html file is loaded via de .load()
and it loads it in a div from the main page

This tells me that the first line is not well-formed

$(".flip").live("click", function() {

         $(this).find("div.panel").slideToggle("slow")
     });
     $(".flip").live("mouseover", function() {
         $(this).css('cursor', 'pointer');
     });

If i remove this, it will tell me the next element is not well-formed and so on. If I include this javascript in a page which is not called via .load, it doesn't say any error. Is this because i'm calling this java script inside a div? and not in the head?

Body:
try to write the javascript code inde this function

$(document).ready(function(){
//Here insert your javascript code
});


问:
How to make this jsp page work on Tomcat with eclipse?
JSP page:

```<code><%@ page language="java" contentType="text/html; utf-8"
    pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html lang="sv" dir="ltr">
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>

<c:forEach begin="1" end="5" var="current">
    <c:out value="${current}"/>
    <p>${current}</p>
</c:forEach>

</body>
</html>
</code>```

Maven POM file:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>GroupName</groupId>
  <artifactId>AppName</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.19</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.14</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>Whatever</finalName>
  </build>
</project>
</code>```

Instead of the output 1 2 3 4 5 I get ${current} ${current} ${current} ${current} ${current}

I code in eclipse, and I use maven for dependencies. I run code in local Tomcat Server.
Might be to little background info, but its hard since Eclipse + Tomcat + Maven = 100000 ways of doing stuff, weird quirks, configurations etc. Hoping it might be something obvious.

答:
try these dependencies:

```<code>   <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.1</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
</code>```

If that doesn't work, right click on the project and go into properties -> project facets.

And make sure Dynamic Web Module is 3.1

Body:
JSP page:

<%@ page language="java" contentType="text/html; utf-8"
    pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>

<meta charset="utf-8">
<title>Insert title here</title>

<c:forEach begin="1" end="5" var="current">
    <c:out value="${current}"/>

${current}

</c:forEach>

Maven POM file:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>GroupName</groupId>
  <artifactId>AppName</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.19</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.14</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>Whatever</finalName>
  </build>
</project>

Instead of the output 1 2 3 4 5 I get ${current} ${current} ${current} ${current} ${current}

I code in eclipse, and I use maven for dependencies. I run code in local Tomcat Server.
Might be to little background info, but its hard since Eclipse + Tomcat + Maven = 100000 ways of doing stuff, weird quirks, configurations etc. Hoping it might be something obvious.

Body:
try these dependencies:

   <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.1</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

If that doesn't work, right click on the project and go into properties -> project facets.

And make sure Dynamic Web Module is 3.1


问:
How to create a line-based observable from InputStream?
Sorry for the basic question...
I have a function that takes an InputStream with the content of a file, and returns a list of objects, let's say Person.

Every line of the input file contains a person, so I want to parse it by line.
Nothing difficult but... this time I want to use reactive programming.

Something like:

```<code>public List<Person> parse(final InputStream is) throws IOException {
    return
    //create an observable which will split the input in many lines, "\n"
            .map(Person::new)
            .collect(toList());
}
</code>```

I miss the commented step, that is: creating an observable that is not byte based, but line-based.

答:
According to your code, you don't need to implement an Observable of lines, since you want afterwards to use Java's Streams. You can't move back from Rx to java streams.

But if you want to base completely to Observables, you can start with this:

```<code>        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
            Observable<String> linesObs = Observable.from(reader.lines()::iterator);
            // In rxjava v2:
            // Observable<String> linesObs = Observable.fromIterable(reader.lines()::iterator);
            ...
        }
</code>```

Body:
Sorry for the basic question...
I have a function that takes an InputStream with the content of a file, and returns a list of objects, let's say Person.

Every line of the input file contains a person, so I want to parse it by line.
Nothing difficult but... this time I want to use reactive programming.

Something like:

public List<Person> parse(final InputStream is) throws IOException {
    return
    //create an observable which will split the input in many lines, "\n"
            .map(Person::new)
            .collect(toList());
}

I miss the commented step, that is: creating an observable that is not byte based, but line-based.

Body:
According to your code, you don't need to implement an Observable of lines, since you want afterwards to use Java's Streams. You can't move back from Rx to java streams.

But if you want to base completely to Observables, you can start with this:

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
            Observable<String> linesObs = Observable.from(reader.lines()::iterator);
            // In rxjava v2:
            // Observable<String> linesObs = Observable.fromIterable(reader.lines()::iterator);
            ...
        }


问:
python mechanize to access Sharepoint website
I'm trying to access Sharepoint using mechanize but i got a 401 error. Here's the code i'm using:

```<code>import mechanize

url = "http://sharepoint:8080/foo/bar/foobar.aspx"

br.addheaders = [('User-agent', 'Mozilla/4.0(compatible; MSIE 7.0b; Windows NT 6.0)')]
br.add_password(url, 'domain\\user', 'myPassword')
r = br.open(url)
html = r.read()
</code>```

Did i miss anything?

答:
Looking at the usage in the mechanize docs you only need to specify the username (eg 'john_doe', try this

```<code>...
br.add_password(url, 'username_string', 'myPassword')
r = br.open(url)
html = r.get_data() # r.get_data() can be called many times without calling seek
</code>```

Body:
I'm trying to access Sharepoint using mechanize but i got a 401 error. Here's the code i'm using:

import mechanize

url = "http://sharepoint:8080/foo/bar/foobar.aspx"

br.addheaders = [('User-agent', 'Mozilla/4.0(compatible; MSIE 7.0b; Windows NT 6.0)')]
br.add_password(url, 'domain\\user', 'myPassword')
r = br.open(url)
html = r.read()

Did i miss anything?

Body:
Looking at the usage in the mechanize docs you only need to specify the username (eg 'john_doe', try this

...
br.add_password(url, 'username_string', 'myPassword')
r = br.open(url)
html = r.get_data() # r.get_data() can be called many times without calling seek


问:
Install An ODBC connection from cmd line
Install An ODBC connection from cmd line

Hi, i want to install an odbc connection threw the cmd line, in this cmd below i can open

only a name and driver of the database i want to use. i need to add also a ip,user,password,description.

odbcconf configsysdsn "MySQL ODBC 5.2w Driver" "DSN=test1|SERVER=(local)"

答:
According to this article on Microsoft.com:

ODBCCONF.exe will be removed in a future version of Windows Data Access Components. Avoid using this feature, and plan to modify applications that currently use this feature. You can use PowerShell commands to manage drivers and data sources. For more information about these PowerShell commands, see Windows Data Access Components cmdlets.

The Power Shell equivalent to your command would be:

```<code>Add-OdbcDsn -Name "test" -DriverName "MySQL ODBC 5.2w Driver" -Platform "32-bit" -DsnType "System" -SetPropertyValue @("SERVER=127.0.0.1", "PORT=3306", "DATABASE=mdb")
</code>```

Body:
According to this article on Microsoft.com:

ODBCCONF.exe will be removed in a future version of Windows Data Access Components. Avoid using this feature, and plan to modify applications that currently use this feature. You can use PowerShell commands to manage drivers and data sources. For more information about these PowerShell commands, see Windows Data Access Components cmdlets.

The Power Shell equivalent to your command would be:

Add-OdbcDsn -Name "test" -DriverName "MySQL ODBC 5.2w Driver" -Platform "32-bit" -DsnType "System" -SetPropertyValue @("SERVER=127.0.0.1", "PORT=3306", "DATABASE=mdb")


问:
Problem with custom browser opened from powershell
In my GUI I have a button which opens a custom-created browser of AD (something like the left panel of dsa.msc). I created a button to open it and I want to display the selected path in a textbox next to the button. I have two problems, one small, one major. The small problem is, that the browser opens automatically before the GUI itself (but that's just a nuisance, nothing serious and I can even pretend that it was meant to work like that :-) ). The bigger, major problem is, that when I click on the button from the GUI and select another path than that already in the textbox from the initial opening, the path doesn't change. The OK button in the browser works more like Cancel. This is how the textbox is defined:

```<code>$Location_val                    = New-Object system.Windows.Forms.TextBox
$Location_val.multiline          = $false
$Location_val.text               = Browse-AD
$Location_val.width              = 250
$Location_val.height             = 20
$Location_val.location           = New-Object System.Drawing.Point(200,160)
</code>```

This is the definition of the function creating the browser:

```<code>function Browse-AD()
{
    # original inspiration: https://itmicah.wordpress.com/2013/10/29/active-directory-ou-picker-in-powershell/
    # author: Rene Horn the.rhorn@gmail.com

<#
    Copyright (c) 2015, Rene Horn
    All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#>

    $dc_hash = @{}
    $selected_ou = $null

    Import-Module ActiveDirectory
    $forest = Get-ADForest

    [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") | Out-Null
    [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null

    function Get-NodeInfo($sender, $dn_textbox)
    {
        $selected_node = $sender.Node
        $dn_textbox.Text = $selected_node.Name
    }

    function Add-ChildNodes($sender)
    {
        $expanded_node = $sender.Node

        if ($expanded_node.Name -eq "root") {
            return
        }

        $expanded_node.Nodes.Clear() | Out-Null

        $dc_hostname = $dc_hash[$($expanded_node.Name -replace '(OU=[^,]+,)*((DC=\w+,?)+)','$2')]

        $child_OUs = Get-ADObject -Server $dc_hostname -Filter 'ObjectClass -eq "organizationalUnit" -or ObjectClass -eq "container"' -SearchScope OneLevel -SearchBase $expanded_node.Name

        if($child_OUs -eq $null) {
            $sender.Cancel = $true
        } else {
            foreach($ou in $child_OUs) {
                $ou_node = New-Object Windows.Forms.TreeNode
                $ou_node.Text = $ou.Name
                $ou_node.Name = $ou.DistinguishedName
                $ou_node.Nodes.Add('') | Out-Null
                $expanded_node.Nodes.Add($ou_node) | Out-Null
            }
        }
    }

    function Add-ForestNodes($forest, [ref]$dc_hash)
    {
        $ad_root_node = New-Object Windows.Forms.TreeNode
        $ad_root_node.Text = $forest.RootDomain
        $ad_root_node.Name = "root"
        $ad_root_node.Expand()

        $i = 1
        foreach ($ad_domain in $forest.Domains) {
            Write-Progress -Activity "Querying AD forest for domains and hostnames..." -Status $ad_domain -PercentComplete ($i++ / $forest.Domains.Count * 100)

            $dc = Get-ADDomainController -Server $ad_domain
            $dn = $dc.DefaultPartition
            $dc_hash.Value.Add($dn, $dc.Hostname)
            $dc_node = New-Object Windows.Forms.TreeNode
            $dc_node.Name = $dn
            $dc_node.Text = $dc.Domain
            $dc_node.Nodes.Add("") | Out-Null
            $ad_root_node.Nodes.Add($dc_node) | Out-Null
        }

        return $ad_root_node
    }

    $main_dlg_box = New-Object System.Windows.Forms.Form
    $main_dlg_box.ClientSize = New-Object System.Drawing.Size(400,600)
    $main_dlg_box.MaximizeBox = $false
    $main_dlg_box.MinimizeBox = $false
    $main_dlg_box.FormBorderStyle = 'FixedSingle'

    # widget size and location variables
    $ctrl_width_col = $main_dlg_box.ClientSize.Width/20
    $ctrl_height_row = $main_dlg_box.ClientSize.Height/15
    $max_ctrl_width = $main_dlg_box.ClientSize.Width - $ctrl_width_col*2
    $max_ctrl_height = $main_dlg_box.ClientSize.Height - $ctrl_height_row
    $right_edge_x = $max_ctrl_width
    $left_edge_x = $ctrl_width_col
    $bottom_edge_y = $max_ctrl_height
    $top_edge_y = $ctrl_height_row

    # setup text box showing the distinguished name of the currently selected node
    $dn_text_box = New-Object System.Windows.Forms.TextBox
    # can not set the height for a single line text box, that's controlled by the font being used
    $dn_text_box.Width = (14 * $ctrl_width_col)
    $dn_text_box.Location = New-Object System.Drawing.Point($left_edge_x, ($bottom_edge_y - $dn_text_box.Height))
    $main_dlg_box.Controls.Add($dn_text_box)
    # /text box for dN

    # setup Ok button
    $ok_button = New-Object System.Windows.Forms.Button
    $ok_button.Size = New-Object System.Drawing.Size(($ctrl_width_col * 2), $dn_text_box.Height)
    $ok_button.Location = New-Object System.Drawing.Point(($right_edge_x - $ok_button.Width), ($bottom_edge_y - $ok_button.Height))
    $ok_button.Text = "Ok"
    $ok_button.DialogResult = 'OK'
    $main_dlg_box.Controls.Add($ok_button)
    # /Ok button

    # setup tree selector showing the domains
    $ad_tree_view = New-Object System.Windows.Forms.TreeView
    $ad_tree_view.Size = New-Object System.Drawing.Size($max_ctrl_width, ($max_ctrl_height - $dn_text_box.Height - $ctrl_height_row*1.5))
    $ad_tree_view.Location = New-Object System.Drawing.Point($left_edge_x, $top_edge_y)
    $ad_tree_view.Nodes.Add($(Add-ForestNodes $forest ([ref]$dc_hash))) | Out-Null
    $ad_tree_view.Add_BeforeExpand({Add-ChildNodes $_})
    $ad_tree_view.Add_AfterSelect({Get-NodeInfo $_ $dn_text_box})
    $main_dlg_box.Controls.Add($ad_tree_view)
    # /tree selector

    $main_dlg_box.ShowDialog() | Out-Null

    return  $dn_text_box.Text
}
</code>```

And this is the definition of the button that opens the browser:

```<code>$Select_AD_path                  = New-Object System.Windows.Forms.Button
$Select_AD_path.Text             = "Browse..."
$Select_AD_path.Width            = 100
$Select_AD_path.Height           = 30
$Select_AD_path.Location         = New-Object System.Drawing.Point(90,155)
$Select_AD_path.Font             = 'Microsoft Sans Serif,10'
$Select_AD_path.add_Click(${function:Browse-AD})
</code>```

How can I better achieve what I want? At best I'd like to open the GUI with some predefined value in the textbox, which I could change if needed by using the browser.

答:
Some changes are required, to solve both issues:

Change the initial value of the $Location_val:

```<code>$Location_val.text = ""
</code>```

Change the click event handler:

```<code>$Select_AD_path.add_Click({
    $dn = Browse-AD
    if ($dn)
    {
        $Location_val.Text = $dn
    }
})
</code>```

Change the last lines of the Browse-AD function:

```<code>...
    if ($main_dlg_box.ShowDialog() -eq [System.Windows.Forms.DialogResult]::Ok)
    {
        return $dn_text_box.Text
    }

    return $null
}
</code>```

Body:
In my GUI I have a button which opens a custom-created browser of AD (something like the left panel of dsa.msc). I created a button to open it and I want to display the selected path in a textbox next to the button. I have two problems, one small, one major. The small problem is, that the browser opens automatically before the GUI itself (but that's just a nuisance, nothing serious and I can even pretend that it was meant to work like that :-) ). The bigger, major problem is, that when I click on the button from the GUI and select another path than that already in the textbox from the initial opening, the path doesn't change. The OK button in the browser works more like Cancel. This is how the textbox is defined:

$Location_val                    = New-Object system.Windows.Forms.TextBox
$Location_val.multiline          = $false
$Location_val.text               = Browse-AD
$Location_val.width              = 250
$Location_val.height             = 20
$Location_val.location           = New-Object System.Drawing.Point(200,160)

This is the definition of the function creating the browser:

function Browse-AD()
{
    # original inspiration: https://itmicah.wordpress.com/2013/10/29/active-directory-ou-picker-in-powershell/
    # author: Rene Horn the.rhorn@gmail.com

<#
    Copyright (c) 2015, Rene Horn
    All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#>

    $dc_hash = @{}
    $selected_ou = $null

    Import-Module ActiveDirectory
    $forest = Get-ADForest

    [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") | Out-Null
    [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null

    function Get-NodeInfo($sender, $dn_textbox)
    {
        $selected_node = $sender.Node
        $dn_textbox.Text = $selected_node.Name
    }

    function Add-ChildNodes($sender)
    {
        $expanded_node = $sender.Node

        if ($expanded_node.Name -eq "root") {
            return
        }

        $expanded_node.Nodes.Clear() | Out-Null

        $dc_hostname = $dc_hash[$($expanded_node.Name -replace '(OU=[^,]+,)*((DC=\w+,?)+)','$2')]

        $child_OUs = Get-ADObject -Server $dc_hostname -Filter 'ObjectClass -eq "organizationalUnit" -or ObjectClass -eq "container"' -SearchScope OneLevel -SearchBase $expanded_node.Name

        if($child_OUs -eq $null) {
            $sender.Cancel = $true
        } else {
            foreach($ou in $child_OUs) {
                $ou_node = New-Object Windows.Forms.TreeNode
                $ou_node.Text = $ou.Name
                $ou_node.Name = $ou.DistinguishedName
                $ou_node.Nodes.Add('') | Out-Null
                $expanded_node.Nodes.Add($ou_node) | Out-Null
            }
        }
    }

    function Add-ForestNodes($forest, [ref]$dc_hash)
    {
        $ad_root_node = New-Object Windows.Forms.TreeNode
        $ad_root_node.Text = $forest.RootDomain
        $ad_root_node.Name = "root"
        $ad_root_node.Expand()

        $i = 1
        foreach ($ad_domain in $forest.Domains) {
            Write-Progress -Activity "Querying AD forest for domains and hostnames..." -Status $ad_domain -PercentComplete ($i++ / $forest.Domains.Count * 100)

            $dc = Get-ADDomainController -Server $ad_domain
            $dn = $dc.DefaultPartition
            $dc_hash.Value.Add($dn, $dc.Hostname)
            $dc_node = New-Object Windows.Forms.TreeNode
            $dc_node.Name = $dn
            $dc_node.Text = $dc.Domain
            $dc_node.Nodes.Add("") | Out-Null
            $ad_root_node.Nodes.Add($dc_node) | Out-Null
        }

        return $ad_root_node
    }

    $main_dlg_box = New-Object System.Windows.Forms.Form
    $main_dlg_box.ClientSize = New-Object System.Drawing.Size(400,600)
    $main_dlg_box.MaximizeBox = $false
    $main_dlg_box.MinimizeBox = $false
    $main_dlg_box.FormBorderStyle = 'FixedSingle'

    # widget size and location variables
    $ctrl_width_col = $main_dlg_box.ClientSize.Width/20
    $ctrl_height_row = $main_dlg_box.ClientSize.Height/15
    $max_ctrl_width = $main_dlg_box.ClientSize.Width - $ctrl_width_col*2
    $max_ctrl_height = $main_dlg_box.ClientSize.Height - $ctrl_height_row
    $right_edge_x = $max_ctrl_width
    $left_edge_x = $ctrl_width_col
    $bottom_edge_y = $max_ctrl_height
    $top_edge_y = $ctrl_height_row

    # setup text box showing the distinguished name of the currently selected node
    $dn_text_box = New-Object System.Windows.Forms.TextBox
    # can not set the height for a single line text box, that's controlled by the font being used
    $dn_text_box.Width = (14 * $ctrl_width_col)
    $dn_text_box.Location = New-Object System.Drawing.Point($left_edge_x, ($bottom_edge_y - $dn_text_box.Height))
    $main_dlg_box.Controls.Add($dn_text_box)
    # /text box for dN

    # setup Ok button
    $ok_button = New-Object System.Windows.Forms.Button
    $ok_button.Size = New-Object System.Drawing.Size(($ctrl_width_col * 2), $dn_text_box.Height)
    $ok_button.Location = New-Object System.Drawing.Point(($right_edge_x - $ok_button.Width), ($bottom_edge_y - $ok_button.Height))
    $ok_button.Text = "Ok"
    $ok_button.DialogResult = 'OK'
    $main_dlg_box.Controls.Add($ok_button)
    # /Ok button

    # setup tree selector showing the domains
    $ad_tree_view = New-Object System.Windows.Forms.TreeView
    $ad_tree_view.Size = New-Object System.Drawing.Size($max_ctrl_width, ($max_ctrl_height - $dn_text_box.Height - $ctrl_height_row*1.5))
    $ad_tree_view.Location = New-Object System.Drawing.Point($left_edge_x, $top_edge_y)
    $ad_tree_view.Nodes.Add($(Add-ForestNodes $forest ([ref]$dc_hash))) | Out-Null
    $ad_tree_view.Add_BeforeExpand({Add-ChildNodes $_})
    $ad_tree_view.Add_AfterSelect({Get-NodeInfo $_ $dn_text_box})
    $main_dlg_box.Controls.Add($ad_tree_view)
    # /tree selector

    $main_dlg_box.ShowDialog() | Out-Null

    return  $dn_text_box.Text
}

And this is the definition of the button that opens the browser:

$Select_AD_path                  = New-Object System.Windows.Forms.Button
$Select_AD_path.Text             = "Browse..."
$Select_AD_path.Width            = 100
$Select_AD_path.Height           = 30
$Select_AD_path.Location         = New-Object System.Drawing.Point(90,155)
$Select_AD_path.Font             = 'Microsoft Sans Serif,10'
$Select_AD_path.add_Click(${function:Browse-AD})

How can I better achieve what I want? At best I'd like to open the GUI with some predefined value in the textbox, which I could change if needed by using the browser.

Body:
Some changes are required, to solve both issues:

Change the initial value of the $Location_val:

$Location_val.text = ""

Change the click event handler:

$Select_AD_path.add_Click({
    $dn = Browse-AD
    if ($dn)
    {
        $Location_val.Text = $dn
    }
})

Change the last lines of the Browse-AD function:

...
    if ($main_dlg_box.ShowDialog() -eq [System.Windows.Forms.DialogResult]::Ok)
    {
        return $dn_text_box.Text
    }

    return $null
}


问:
How do i prevent the player from dragging an image outside the specified area?
I am trying to drag an Image in a certain area. For that I am using IDragHandler. To prevent the image to go outside the area, i put four box colliders in a square shape. The box was still moving out. So, I put the fixed timestep to 0.0001. Now, when the image goes out of boundry, it pushes back the image in the specified area which is fine but I want the image to stop moving out the boundary the moment it touch the edge of the image.
Here's my code:</p>

```<code>public class Draggable : MonoBehaviour, IDragHandler
{
    public GameObject box;

    private void OnCollisionEnter2D(Collision2D collision)
    {
        Debug.Log("Triggered");

    }

    public void OnDrag(PointerEventData eventData)
    {
        box.transform.position = eventData.position;
    }
}
</code>```

答:
Try to achieve your bounderies as simple numbers. Maybe create a rectangle and take its corners. Then you get the best user experience by using min and max functions, effectively "clamping" the allowed coordinates before they are actually set.
It makes sense to clamp x and y separately. That way the user can still drag along the Y axis if there is room despite the mouse being outside the boundary on the X axis.</p>

Body:
I am trying to drag an Image in a certain area. For that I am using IDragHandler. To prevent the image to go outside the area, i put four box colliders in a square shape. The box was still moving out. So, I put the fixed timestep to 0.0001. Now, when the image goes out of boundry, it pushes back the image in the specified area which is fine but I want the image to stop moving out the boundary the moment it touch the edge of the image.
Here's my code:

public class Draggable : MonoBehaviour, IDragHandler
{
    public GameObject box;

    private void OnCollisionEnter2D(Collision2D collision)
    {
        Debug.Log("Triggered");

    }

    public void OnDrag(PointerEventData eventData)
    {
        box.transform.position = eventData.position;
    }
}


问:
How can I merge these many csv files (around 130,000) using PySpark into one large dataset efficiently?
I posted this question earlier and got some advice to use PySpark instead.

How can I merge this large dataset into one large dataframe efficiently?

The following zip file (https://fred.stlouisfed.org/categories/32263/downloaddata/INTRNTL_csv_2.zip) contains a folder called data with around 130,000 of csv files. I want to merge all of them into one single dataframe. I have 16gb of RAM and I keep running out of RAM when I hit the first few hundred files. The files' total size is only about 300-400 mb of data.

If you open up any of the csv files, you can see that they all have the same format, the first column is for dates, and the second column is for the data series.

So now instead I am using PySpark, however I have no idea what is the most efficient way to connect all the files, with pandas dataframes I would just concat the list of individual frames like this because I want them to merge on the dates:

```<code>bigframe = pd.concat(listofframes,join='outer', axis=0)
</code>```

But like I mentioned, this method doesn't work as I run out of RAM really fast.

What would be the best way to do something similar using PySpark?

So far I have this, (by the way the filelist below is just a list of the files which I want to pull out, you can ignore that)

```<code>
import os

from pyspark.sql import SparkSession
spark = SparkSession.builder.appName('spark-dataframe-demo').getOrCreate()
from pyspark.sql import *
from pyspark.sql.functions import col

from functools import reduce
from pyspark.sql import DataFrame

listdf = []

for subdir, dirs, files in os.walk("/kaggle/input/filelist/"):
    for file in files:
        path = os.path.join(subdir,file)
        print(file)
        filelist = pd.read_excel("/kaggle/input/filelist/" + file)

        for row in filelist.File.items():
            df = spark.read.csv(f"/kaggle/input/master/{file[:-5]}/{file[:-5]}/data/" + row[1], inferSchema = True, header = True)
            df = df.select(col("DATE").alias("DATE"),col("VALUE").alias(row[1][:-4]))
            df.show(3)
            listdf.append(df)

</code>```

I stop the code after it appends like 10 frames,
But when I try the code below, it just has one column of data, it doesn't merge properly.

```<code>bigframe = reduce(DataFrame.join(listdf, ['DATE'], how='full'))
</code>```

But I am only left with 2 columns of data, the date and the first item in the list of spark frames.

How do I merge everything into one frame properly? I want the Dates to be the thing index that the other columns merge on. Meaning if one frame has:

```<code>Date        TimeSeries1
1 Jan 2012  12345
2 Jan 2012  23456
</code>```

and the other has

```<code>Date        TimeSeries2
1 Jan 2012  5678
3 Jan 2012  8910
</code>```

I want the final product to be

```<code>Date        TimeSeries1 TimeSeries2
1 Jan 2012  12345       5678
2 Jan 2012  23456
3 Jan 2012              8910
</code>```

Also, to identify the columns, the names have to be changed to the name of the file.

答:
spark can read data from multiple files by default if they contain the same schema.

To process each timeseries separately, you can group by the dataframe by filename and use a pandas udf to process each group.

```<code>import glob as g
import pyspark.sql.functions as F

@F.pandas_udf("date Date, value DECIMAL(38,4)", F.PandasUDFType.GROUPED_MAP)
def transform(pdf):
  # pdf will be a pandas datafrmme for each timeseries
  # apply timeseries computations here and return a new dataframe
  # with aggregated values
  return pdf

paths = g.glob("./INTRNTL_csv_2/data/**/*.csv", recursive=True)

df = spark.read.csv(paths, header=False, schema="date DATE, value DECIMAL(38,4)")

res = df.withColumn('name', F.input_file_name())
res = res.groupBy('name').apply(transform)
res.show()

</code>```

Body:
I posted this question earlier and got some advice to use PySpark instead.

How can I merge this large dataset into one large dataframe efficiently?

The following zip file (https://fred.stlouisfed.org/categories/32263/downloaddata/INTRNTL_csv_2.zip) contains a folder called data with around 130,000 of csv files. I want to merge all of them into one single dataframe. I have 16gb of RAM and I keep running out of RAM when I hit the first few hundred files. The files' total size is only about 300-400 mb of data.

If you open up any of the csv files, you can see that they all have the same format, the first column is for dates, and the second column is for the data series.

So now instead I am using PySpark, however I have no idea what is the most efficient way to connect all the files, with pandas dataframes I would just concat the list of individual frames like this because I want them to merge on the dates:

bigframe = pd.concat(listofframes,join='outer', axis=0)

But like I mentioned, this method doesn't work as I run out of RAM really fast.

What would be the best way to do something similar using PySpark?

So far I have this, (by the way the filelist below is just a list of the files which I want to pull out, you can ignore that)

import os

from pyspark.sql import SparkSession
spark = SparkSession.builder.appName('spark-dataframe-demo').getOrCreate()
from pyspark.sql import *
from pyspark.sql.functions import col

from functools import reduce
from pyspark.sql import DataFrame

listdf = []

for subdir, dirs, files in os.walk("/kaggle/input/filelist/"):
    for file in files:
        path = os.path.join(subdir,file)
        print(file)
        filelist = pd.read_excel("/kaggle/input/filelist/" + file)

        for row in filelist.File.items():
            df = spark.read.csv(f"/kaggle/input/master/{file[:-5]}/{file[:-5]}/data/" + row[1], inferSchema = True, header = True)
            df = df.select(col("DATE").alias("DATE"),col("VALUE").alias(row[1][:-4]))
            df.show(3)
            listdf.append(df)

I stop the code after it appends like 10 frames,
But when I try the code below, it just has one column of data, it doesn't merge properly.

bigframe = reduce(DataFrame.join(listdf, ['DATE'], how='full'))

But I am only left with 2 columns of data, the date and the first item in the list of spark frames.

How do I merge everything into one frame properly? I want the Dates to be the thing index that the other columns merge on. Meaning if one frame has:

Date        TimeSeries1
1 Jan 2012  12345
2 Jan 2012  23456

and the other has

Date        TimeSeries2
1 Jan 2012  5678
3 Jan 2012  8910

I want the final product to be

Date        TimeSeries1 TimeSeries2
1 Jan 2012  12345       5678
2 Jan 2012  23456
3 Jan 2012              8910

Also, to identify the columns, the names have to be changed to the name of the file.

Body:
spark can read data from multiple files by default if they contain the same schema.

To process each timeseries separately, you can group by the dataframe by filename and use a pandas udf to process each group.

import glob as g
import pyspark.sql.functions as F

@F.pandas_udf("date Date, value DECIMAL(38,4)", F.PandasUDFType.GROUPED_MAP)
def transform(pdf):
  # pdf will be a pandas datafrmme for each timeseries
  # apply timeseries computations here and return a new dataframe
  # with aggregated values
  return pdf

paths = g.glob("./INTRNTL_csv_2/data/**/*.csv", recursive=True)

df = spark.read.csv(paths, header=False, schema="date DATE, value DECIMAL(38,4)")

res = df.withColumn('name', F.input_file_name())
res = res.groupBy('name').apply(transform)
res.show()


问:
In Rails, what's the nicest way to create a specific time (not now) in a particular time zone?
Here's one way, but can you think of a more idiomatic way?</p>
```<code>>> Time.use_zone('Sydney'){ Time.zone.parse('2011-04-12 2pm') }
=> Tue, 12 Apr 2011 14:00:00 EST +10:00
</code>```

答:
How about using the *in_time_zone* helper..</p>

```<code>Time.now.in_time_zone('Sydney')
</code>```

Body:
Here's one way, but can you think of a more idiomatic way?

>> Time.use_zone('Sydney'){ Time.zone.parse('2011-04-12 2pm') }
=> Tue, 12 Apr 2011 14:00:00 EST +10:00

Body:
How about using the *in_time_zone* helper..

Time.now.in_time_zone('Sydney')


问:
Microsip softphone build problem (cannot open file 'hid.lib')
I am going to build microsip softphone from www.microsip.org, which is based on pjsip project.
The pjsip project files are downloaded and built successfully.
but when I build microsip source I get the following error :

cannot open file 'hid.lib'

I use VS2017 and this file is specified in linker dependencies.
I don't know what is this lib and how can I get the file or compile any other source to get it.

if anybody has experience working with microsip and it's dependencied please help.

答:
1) Install "Microsoft Windows Driver Kit"

2) Project -> Linker -> General -> Additional Library Directories. Set location of hid.lib (for me it's at C:\WinDDK\7600.16385.1\lib\win7\i386)


问:
Multiple variables definition in a bash sourced file behave differently
I have a .env file with the following:

FST_TEST=1
SCD_TEST=2
```

I run source .env and then:

If I run echo "$FST_TEST$FST_TEST" it prints 1.

If I run echo "$SCD_TEST$SCD_TEST" it prints 22.

I would have expected echo "$FST_TEST$FST_TEST" to also prints 11 but I can't manage to do it... I think there is something with the Return character.

答:
Most likely, it's because .env file is in Windows/DOS format.
Can you do :

```<code>dos2unix .env
</code>```

With DOS end of line, FST_TEST=1, is actually FST_TEST=1\r.
\r makes the cursor go to beginning of the line, so the 1
you saw is two 1s, one on top the other.
On the second line, you didn't put end of line, so there was no problem.

Body:
I have a .env file with the following:

FST_TEST=1
SCD_TEST=2

I run source .env and then:

If I run echo "$FST_TEST$FST_TEST" it prints 1.

If I run echo "$SCD_TEST$SCD_TEST" it prints 22.

I would have expected echo "$FST_TEST$FST_TEST" to also prints 11 but I can't manage to do it... I think there is something with the Return character.

Body:
Most likely, it's because .env file is in Windows/DOS format.
Can you do :

dos2unix .env

With DOS end of line, FST_TEST=1, is actually FST_TEST=1\r.
\r makes the cursor go to beginning of the line, so the 1
you saw is two 1s, one on top the other.
On the second line, you didn't put end of line, so there was no problem.


问:
ImportError: No module named pytesseract on Jupiter lab and VSCode but not my local
I have tried running a ProcessImage.py file in which I import the package pytesseract in Jupiter Lab and VSCode.
This is the error that pops out :

```<code>import pytesseract
ImportError: No module named pytesseract
</code>```

I already know that pytesseract is installed in my environment because with conda list:

```<code>pytesseract               0.3.2                      py_0    conda-forge
pytest                    5.3.5                    py38_0    coda-forge
</code>```

However, if I run my ProcessImage.py file on my local no error is prompted.

I know the error is related to paths in Jupiter Lab and VsCode but I can't seem to find a solution.

答:
Have you tried to launch your python file using Ctrl+F5 command for run?

I had this same ImportError when trying to launch my python program using the .run extension. It persistently started python 2.7 while my environment was using Python3. I first thought that it was a VS code error but it wasn't.

Body:
I have tried running a ProcessImage.py file in which I import the package pytesseract in Jupiter Lab and VSCode.
This is the error that pops out :

import pytesseract
ImportError: No module named pytesseract

I already know that pytesseract is installed in my environment because with conda list:

pytesseract               0.3.2                      py_0    conda-forge
pytest                    5.3.5                    py38_0    coda-forge

However, if I run my ProcessImage.py file on my local no error is prompted.

I know the error is related to paths in Jupiter Lab and VsCode but I can't seem to find a solution.


问:
elevate without prompt - verb runas start-process
This may not be possible, but I'm looking to run a .ps1 powershell script from a command line, it needs to be run with Elevated privileges, without or bypassing any UAC prompts.

This is from a scripting perspective, with no user interaction. So "Run as administrator" for CMD or Powershell is not an option. There cannot be any UAC prompts to click on as these will most likely be hidden from view.

My command started off like this -

powershell.exe -executionpolicy bypass -file .\remove-default-apps.ps1

This would launch the .ps1 fine, but the script would ultimately fail, as the commands in the script require elevation (Get-AppxPackage | Remove-AppxPackage)

My next attempt was using Powershell to run the script using -

Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File MyScript.ps1' -Verb RunAs

But still this prompts for elevation.
I can replicate the errors running the script from a non-elevated cmd window manually, but running elevated it works fine.

Anyone know if this is at all possible? Or have any tips to point me in the right direction, Ive tried a lot of other methods (psexec, scheduled task..) but am unable to achieve this.

答:
Disabling UAC is not a wise decision. However, it is possible to bypass it using Powershell:

if((([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544")) {
    Remove-Item "HKCU:\software\classes\ms-settings" -Force -Recurse
    #Script that will run at high integrity
} else {
    $reg_path = "HKCU:\software\classes\ms-settings\shell\open\command"
    New-Item $reg_path -Force
    New-ItemProperty $reg_path -Name "DelegateExecute" -Value $null -Force
    Set-ItemProperty $reg_path -Name "(default)" -Value "powershell.exe -NoProfile -ExecutionPolicy Bypass -File $PSCommandPath" -Force
    Start-Process "ComputerDefaults.exe"
}
```

*This script only for Windows 10 users who are already admin. See here for my full answer.

Body:
Disabling UAC is not a wise decision. However, it is possible to bypass it using Powershell:

if((([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544")) {
    Remove-Item "HKCU:\software\classes\ms-settings" -Force -Recurse
    #Script that will run at high integrity
} else {
    $reg_path = "HKCU:\software\classes\ms-settings\shell\open\command"
    New-Item $reg_path -Force
    New-ItemProperty $reg_path -Name "DelegateExecute" -Value $null -Force
    Set-ItemProperty $reg_path -Name "(default)" -Value "powershell.exe -NoProfile -ExecutionPolicy Bypass -File $PSCommandPath" -Force
    Start-Process "ComputerDefaults.exe"
}

*This script only for Windows 10 users who are already admin. See here for my full answer.