问:
GridView PreRender not firing after RowDeleted
When deleting a GridView row in the UI (via a LinkButton whose CommandName="Delete"), the view does not automatically refresh and continues to display the deleted row until I take some other action (manually refresh page, navigate away and back again, etc).

In the debugger, I see the row is successfully deleted, and both the RowDeleting and RowDeleted events fire, but the GridView's PreRender event does not fire afterwards (in contrast, that PreRender event does fire when first loading the page, when adding a new row, etc).

I've used GridViews in similar configurations without having this problem, but I don't see obvious differences. It seems the process is aborting before the PreRender event, but no exceptions are being thrown, and stepping off the end of the RowDeleted event in the debugger brings me back to the UI as though the process were completing normally.

Any ideas where I should look for the trouble or a solution? Other possibly-relevant details: the GridView is bound to a SqlDataSource; the data source does not declare any DeleteCommand; I handle the deletion by calling a stored procedure in the RowCommand handler, after which I rebind the GridView with DataBind(), at which point I can see the GridView's Rows.Count has decreased by one as I'd expect. Everything seems fine through the RowDeleted event, then... nothing!

UPDATE: tried calling the SP to delete in the RowDeleting handler rather than RowCommand handler... made no difference. The row is still deleted but processing terminates without calling the GridView's PreRender, and the deleted row is left on display until some further UI interaction updates the view.

UPDATE2: I'm not even getting the Page's PreRender event, which precedes the control PreRender events. Will continue working backwards to see if I can find where things are halting, since stepping out of the RowDeleted event seems to be the end of the line...

UPDATE3: I've been poking around some more and, although it complicates my code, I was able to get things working by declaring a DeleteCommand in the GridView's SqlDataSource that just does the simple row (record) deletion, and then in the RowDeleted handler calling the additional stuff I had in my stored procedure that needs to happen along with the primary deletion. While it's less convenient having the primary deletion in one place and the related processing in another, at least it's working.

But I don't know what to conclude from this: that a DeleteCommand is needed for proper page life cycle? that one shouldn't do a deletion in a stored procedure in the RowCommand handler? something else? I wish I could identify what, specifically, is broken about my initial attempt...

答: just bind the gridview with the fresh data from database after deleting the row.</p>


来源: stackexchange

问:
How do I retrieve and return an instance from my Class-Based Detail view?
I have two linked models:

```<code>class MyUser(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=24, unique=True)
    profile_page = models.OneToOneField(Profile, null=True)

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)
</code>```

I am attempting to retrieve and return an instance of a single user's profile in this CBV:

```<code>class ProfileView(DetailView):
    queryset = Profile.objects.all()
    template_name = 'profile_detail.html'

    def get_object(self, *args, **kwargs):
        user_profile = self.kwargs.get('username')
        obj = get_object_or_404(Profile, user=user_profile)
        return obj
</code>```

The get_object_or_404 call causes the following exception: invalid literal for int() with base 10: 'adam'

"adam" because I am requesting the page url: http://127.0.0.1:8000/profile/adam

Here are my url patterns:

```<code>urlpatterns = [
    url(r'^edit/', profile_edit, name='profile_edit'),
    url(r'^(?P<username>[\w.@+-]+)$', ProfileView.as_view(), name='profile'),
]
</code>```

(Just in case: these also belong in the namespaced /profile/)

I'm trying to access the model fields within the Profile model.
Why is it that I receive the error when trying to return obj to my profile_detail.html template?

What I've tried:

If I change the URL regex to accept ID or PK instead of <username> and access the url of /profile/1, I receive: TypeError at /profile/1
__str__ returned non-string (type MyUser). If I then update my code to be:

```<code>def get_object(self, *args, **kwargs):
    user_profile = self.kwargs.get('id')
    obj = get_object_or_404(Profile, user=user_profile)
    objj = obj.user
    return objj
</code>```

then the errors clear and I can somewhat get things to appear on the profile_detail.html page. However, the {{object}} refers to the MyUser model, and not the Profile model as I desired.

What might be going on? Does it have something to do with

```<code>def __str__(self):
    return self.username
</code>```

in the models?

edit: string method for my Profile model:

```<code>def __str__(self):
    return self.user
</code>```

答:
You are including the username in the url, not the user id. Therefore you need to change the get_object_or_404 line as follows:

```<code>self.kwargs.get('username')
obj = get_object_or_404(Profile, user__username=user_profile)
</code>```

As the error message __str__ returned non-string (type MyUser) suggests, your Profile.__str__ method should be returning a string, for example:

```<code>def __str__(self):
    return self.user.username
</code>```

Finally, you appear to have two OneToOneFields, MyUser.profile_page and Profile.user. This is unnecessary. If you remove the MyUser.profile_page field, then you can follow the Profile.user relationship backwards from MyUser to Profile with user.profile.

ContentLicense: CC BY-SA 3.0

Body:
I have two linked models:

class MyUser(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=24, unique=True)
    profile_page = models.OneToOneField(Profile, null=True)

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)

I am attempting to retrieve and return an instance of a single user's profile in this CBV:

class ProfileView(DetailView):
    queryset = Profile.objects.all()
    template_name = 'profile_detail.html'

    def get_object(self, *args, **kwargs):
        user_profile = self.kwargs.get('username')
        obj = get_object_or_404(Profile, user=user_profile)
        return obj

The get_object_or_404 call causes the following exception: invalid literal for int() with base 10: 'adam'

"adam" because I am requesting the page url: http://127.0.0.1:8000/profile/adam

Here are my url patterns:

urlpatterns = [
    url(r'^edit/', profile_edit, name='profile_edit'),
    url(r'^(?P<username>[\w.@+-]+)$', ProfileView.as_view(), name='profile'),
]

(Just in case: these also belong in the namespaced /profile/)

I'm trying to access the model fields within the Profile model.
Why is it that I receive the error when trying to return obj to my profile_detail.html template?

What I've tried:

If I change the URL regex to accept ID or PK instead of <username> and access the url of /profile/1, I receive: TypeError at /profile/1
__str__ returned non-string (type MyUser). If I then update my code to be:

def get_object(self, *args, **kwargs):
    user_profile = self.kwargs.get('id')
    obj = get_object_or_404(Profile, user=user_profile)
    objj = obj.user
    return objj

then the errors clear and I can somewhat get things to appear on the profile_detail.html page. However, the {{object}} refers to the MyUser model, and not the Profile model as I desired.

What might be going on? Does it have something to do with

def __str__(self):
    return self.username

in the models?

edit: string method for my Profile model:

def __str__(self):
    return self.user

Body:
You are including the username in the url, not the user id. Therefore you need to change the get_object_or_404 line as follows:

self.kwargs.get('username')
obj = get_object_or_404(Profile, user__username=user_profile)

As the error message __str__ returned non-string (type MyUser) suggests, your Profile.__str__ method should be returning a string, for example:

def __str__(self):
    return self.user.username

Finally, you appear to have two OneToOneFields, MyUser.profile_page and Profile.user. This is unnecessary. If you remove the MyUser.profile_page field, then you can follow the Profile.user relationship backwards from MyUser to Profile with user.profile.


问:
Design pattern for searching object in class of objects without comparing all objects in java
I want to search particular object in collection of class objects in java without comparing all attributes and all objects. I have individual attributes value in search key.

One of the way could be to create HashMap of objects based on custom hashing function(key would be concatenated string of all attributes value like "attr1|attr2|attr3".

Is there any other better way of doing this in java?

答:
If you are using Java 8 then use streams:
This returns a collection with your search result

```<code>yourCollection.stream()
    .filter( it -> it.attr1.equals(keyAttr1) &&  it.attr2.equals(keyAttr2) && ...)
    .collect( Collectors.toList());
</code>```

or if you just want to do something with all matching

```<code>yourCollection.stream()
    .filter( it -> it.attr1.equals(keyAttr1) &&  it.attr2.equals(keyAttr2) && ...)
    .forEach( it -> do something with it );
</code>```

In lower versions you could implement a filter function yourself that takes a collection and a matcher function as an argument and loops through your collection and filters out the ones that return true from the matcher function.

Body:
If you are using Java 8 then use streams:
This returns a collection with your search result

yourCollection.stream()
    .filter( it -> it.attr1.equals(keyAttr1) &&  it.attr2.equals(keyAttr2) && ...)
    .collect( Collectors.toList());

or if you just want to do something with all matching

yourCollection.stream()
    .filter( it -> it.attr1.equals(keyAttr1) &&  it.attr2.equals(keyAttr2) && ...)
    .forEach( it -> do something with it );

In lower versions you could implement a filter function yourself that takes a collection and a matcher function as an argument and loops through your collection and filters out the ones that return true from the matcher function.


问:
Logstash when launched as service keeps restarting
So I had the exact same issue as described in https://discuss.elastic.co/t/consistent-restarts-of-logstash-with-high-cpu-recorded/86597:

I'm running Logstash as a service on Ubuntu. And I'm launching it by

```<code>sudo systemctl start logstash.service
</code>```

My task was simple: import data from jdbc (MySQL) into Elasticsearch in a one shot manner (so no scheduling option. no cron timer). So as in the link above, I'm using a JDBC input filter. And the elasticsearch output filter.

I managed to get it to work well when I launched logstash directly through command line (logstash -f conf_file): logstash starts, imports the data and shutdown. Just as expected.

Now, when I tried to do the same when I was launching logstash as a service, it would keep importing the data and restarting over and over again.

The link above provide a solution but it's actually wrong. It says that when no "schedule" option is specified, a default 1 minute timer is used. This is in direct contradiction with what the documentation says here:

There is no schedule by default. If no schedule is given, then the
  statement is run exactly once.

答:
Here is what I think is the explanation:
when logstash is launched as a service and the config file has no "schedule" option, once it has finished importing the data, logstash simply shutdowns by itself. The problem is that because it was started as a service, the service manager (systemctl) detects that the service is offline and "resurrect it" over and over again.

When a schedule option is used, the service says alive and therefore, there is no issue.

Body:
So I had the exact same issue as described in https://discuss.elastic.co/t/consistent-restarts-of-logstash-with-high-cpu-recorded/86597:

I'm running Logstash as a service on Ubuntu. And I'm launching it by

sudo systemctl start logstash.service

My task was simple: import data from jdbc (MySQL) into Elasticsearch in a one shot manner (so no scheduling option. no cron timer). So as in the link above, I'm using a JDBC input filter. And the elasticsearch output filter.

I managed to get it to work well when I launched logstash directly through command line (logstash -f conf_file): logstash starts, imports the data and shutdown. Just as expected.

Now, when I tried to do the same when I was launching logstash as a service, it would keep importing the data and restarting over and over again.

The link above provide a solution but it's actually wrong. It says that when no "schedule" option is specified, a default 1 minute timer is used. This is in direct contradiction with what the documentation says here:

There is no schedule by default. If no schedule is given, then the
  statement is run exactly once.


问:
How to read and show xslx file in javascript
I'm trying to read a xlsx file in html using javaScript but it seems my code is not so right as it should be.

I'm using this code:

```<code>    <script>
    function openRead(){
    var excel = activeXObject("Excel.Application");
            excel.visible = false;
            var file = exel.workbooks.open("C:\Users\Utilizador\Desktop\teste.xlsx").activeSheet.cell(1,1).value;

var div = document.getElementById("div1").text;
div = file;
}
</script>
</code>```

Getting the following error

activeXObject is not defined

I hope you guys can point me to the right direction!

答:
ActiveXObject is available only on IE browser. So every other useragent will throw an error

https://stackoverflow.com/a/11101655/1172872

You can try existing libraries... (or see how they implemented it)

http://sheetjs.com/  (https://github.com/SheetJS/js-xlsx)

http://oss.sheetjs.com/js-xls/

Body:
I'm trying to read a xlsx file in html using javaScript but it seems my code is not so right as it should be.

I'm using this code:

Getting the following error

activeXObject is not defined

I hope you guys can point me to the right direction!


问:
How to swap value in SQL Server?
I want to swap the value between the row but I don't have an idea how to make it as I create a script to do it but the answer still not correct. I get the data raw in from the pdf then convert it into excel 'xls'.

Please see the sample below.

```<code>DECLARE @MyTable TABLE(Id INT, RoomNo INT, Class VARCHAR(10), Price VARCHAR(255))

INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 1,    21,     'A',        '43,028,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 2,    NULL,   NULL,       '43,896,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 3,    20,     'A',        '42,681,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 4,    NULL,   NULL,       '43,549,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 5,    19,     'A',        '42,334,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 6,    NULL,   NULL,       '43,202,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 7,    18,     'A',        '41,987,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 8,    NULL,   NULL,       '42,855,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 9,    17,     'A',        '41,467,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 10,   NULL,   NULL,       '42,334,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 11,   16,     'A',        '41,120,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 12,   NULL,   NULL,       '41,987,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 13,   NULL,   'A',        '39,211,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 14,   9,      NULL,       '40,079,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 15,   NULL,   NULL,       '38,691,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 16,   6,      NULL,       '39,385,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 17,   NULL,   'A',        '44,756,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 18,   5,      NULL,       '45,591,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 19,   21,     'B',        '26,598,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 20,   20,     'B',        '26,393,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 21,   NULL,   NULL,       '26,905,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 22,   19,     'B',        '26,189,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 23,   NULL,   NULL,       '26,700,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 24,   18,     'B',        '25,984,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 25,   NULL,   NULL,       '26,496,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 26,   17,     'B',        '25,677,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 27,   NULL,   'B',        '24,041,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 28,   6,      NULL,       '24,552,000'
</code>```

what i tried

```<code>SELECT
        *,
        ISNULL(RoomNo, (SELECT TOP 1 RoomNo FROM @MyTable WHERE Id < MyTable.Id AND RoomNo IS NOT NULL ORDER BY ID DESC)),
        ISNULL(Class, (SELECT TOP 1 Class FROM @MyTable WHERE Id < MyTable.Id AND Class IS NOT NULL ORDER BY ID DESC)),
        Price
    FROM @MyTable as MyTable
</code>```

Result is wrong:

```<code>Id  RoomNo  Class   Price       NewRoomNo   NewClass    Price
1   21      A       43,028,000  21          A           43,028,000
2   NULL    NULL    43,896,000  21          A           43,896,000
3   20      A       42,681,000  20          A           42,681,000
4   NULL    NULL    43,549,000  20          A           43,549,000
5   19      A       42,334,000  19          A           42,334,000
6   NULL    NULL    43,202,000  19          A           43,202,000
7   18      A       41,987,000  18          A           41,987,000
8   NULL    NULL    42,855,000  18          A           42,855,000
9   17      A       41,467,000  17          A           41,467,000
10  NULL    NULL    42,334,000  17          A           42,334,000
11  16      A       41,120,000  16          A           41,120,000
12  NULL    NULL    41,987,000  16          A           41,987,000
13  NULL    A       39,211,000  16          A           39,211,000
14  9       NULL    40,079,000  9           A           40,079,000
15  NULL    NULL    38,691,000  9           A           38,691,000
16  6       NULL    39,385,000  6           A           39,385,000
17  NULL    A       44,756,000  6           A           44,756,000
18  5       NULL    45,591,000  5           A           45,591,000
19  21      B       26,598,000  21          B           26,598,000
20  20      B       26,393,000  20          B           26,393,000
21  NULL    NULL    26,905,000  20          B           26,905,000
22  19      B       26,189,000  19          B           26,189,000
23  NULL    NULL    26,700,000  19          B           26,700,000
24  18      B       25,984,000  18          B           25,984,000
25  NULL    NULL    26,496,000  18          B           26,496,000
26  17      B       25,677,000  17          B           25,677,000
27  NULL    B       24,041,000  17          B           24,041,000
28  6       NULL    24,552,000  6           B           24,552,000
</code>```

I want to achieve:

```<code>Id  RoomNo  Class   Price       NewRoomNo   NewClass    Price
1   21      A       43,028,000  NULL        NULL        43,028,000
2   NULL    NULL    43,896,000  21          A           43,896,000
3   20      A       42,681,000  NULL        NULL        42,681,000
4   NULL    NULL    43,549,000  20          A           43,549,000
5   19      A       42,334,000  NULL        NULL        42,334,000
6   NULL    NULL    43,202,000  19          A           43,202,000
7   18      A       41,987,000  NULL        NULL        41,987,000
8   NULL    NULL    42,855,000  18          A           42,855,000
9   17      A       41,467,000  NULL        NULL        41,467,000
10  NULL    NULL    42,334,000  17          A           42,334,000
11  16      A       41,120,000  NULL        NULL        41,120,000
12  NULL    NULL    41,987,000  16          A           41,987,000
13  NULL    A       39,211,000  NULL        NULL        39,211,000
14  9       NULL    40,079,000  9           A           40,079,000
15  NULL    NULL    38,691,000  NULL        NULL        38,691,000
16  6       NULL    39,385,000  6           A           39,385,000
17  NULL    A       44,756,000  NULL        NULL        44,756,000
18  5       NULL    45,591,000  5           A           45,591,000
19  21      B       26,598,000  21          B           26,598,000
20  20      B       26,393,000  NULL        NULL        26,393,000
21  NULL    NULL    26,905,000  20          B           26,905,000
22  19      B       26,189,000  NULL        NULL        26,189,000
23  NULL    NULL    26,700,000  19          B           26,700,000
24  18      B       25,984,000  NULL        NULL        25,984,000
25  NULL    NULL    26,496,000  18          B           26,496,000
26  17      B       25,677,000  17          B           25,677,000
27  NULL    B       24,041,000  NULL        NULL        24,041,000
28  6       NULL    24,552,000  6           B           24,552,000
</code>```

答:
```<code>SELECT

Id,

RoomNo,

Class,

Price,

CASE WHEN RoomNo IS NULL THEN lag(RoomNo) over(Order by Id)

ELSE NULL END as NewRoomNo,

CASE WHEN Class IS NULL THEN lag(Class) over(Order by Id)

ELSE NULL END as NewClass,

Price

FROM @MyTable
</code>```

Title: How to swap value in SQL Server?

Body:
I want to swap the value between the row but I don't have an idea how to make it as I create a script to do it but the answer still not correct. I get the data raw in from the pdf then convert it into excel 'xls'.

Please see the sample below.

DECLARE @MyTable TABLE(Id INT, RoomNo INT, Class VARCHAR(10), Price VARCHAR(255))

INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 1,    21,     'A',        '43,028,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 2,    NULL,   NULL,       '43,896,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 3,    20,     'A',        '42,681,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 4,    NULL,   NULL,       '43,549,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 5,    19,     'A',        '42,334,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 6,    NULL,   NULL,       '43,202,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 7,    18,     'A',        '41,987,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 8,    NULL,   NULL,       '42,855,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 9,    17,     'A',        '41,467,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 10,   NULL,   NULL,       '42,334,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 11,   16,     'A',        '41,120,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 12,   NULL,   NULL,       '41,987,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 13,   NULL,   'A',        '39,211,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 14,   9,      NULL,       '40,079,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 15,   NULL,   NULL,       '38,691,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 16,   6,      NULL,       '39,385,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 17,   NULL,   'A',        '44,756,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 18,   5,      NULL,       '45,591,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 19,   21,     'B',        '26,598,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 20,   20,     'B',        '26,393,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 21,   NULL,   NULL,       '26,905,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 22,   19,     'B',        '26,189,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 23,   NULL,   NULL,       '26,700,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 24,   18,     'B',        '25,984,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 25,   NULL,   NULL,       '26,496,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 26,   17,     'B',        '25,677,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 27,   NULL,   'B',        '24,041,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 28,   6,      NULL,       '24,552,000'

what i tried

SELECT
        *,
        ISNULL(RoomNo, (SELECT TOP 1 RoomNo FROM @MyTable WHERE Id < MyTable.Id AND RoomNo IS NOT NULL ORDER BY ID DESC)),
        ISNULL(Class, (SELECT TOP 1 Class FROM @MyTable WHERE Id < MyTable.Id AND Class IS NOT NULL ORDER BY ID DESC)),
        Price
    FROM @MyTable as MyTable

Result is wrong:

Id  RoomNo  Class   Price       NewRoomNo   NewClass    Price
1   21      A       43,028,000  21          A           43,028,000
2   NULL    NULL    43,896,000  21          A           43,896,000
3   20      A       42,681,000  20          A           42,681,000
4   NULL    NULL    43,549,000  20          A           43,549,000
5   19      A       42,334,000  19          A           42,334,000
6   NULL    NULL    43,202,000  19          A           43,202,000
7   18      A       41,987,000  18          A           41,987,000
8   NULL    NULL    42,855,000  18          A           42,855,000
9   17      A       41,467,000  17          A           41,467,000
10  NULL    NULL    42,334,000  17          A           42,334,000
11  16      A       41,120,000  16          A           41,120,000
12  NULL    NULL    41,987,000  16          A           41,987,000
13  NULL    A       39,211,000  16          A           39,211,000
14  9       NULL    40,079,000  9           A           40,079,000
15  NULL    NULL    38,691,000  9           A           38,691,000
16  6       NULL    39,385,000  6           A           39,385,000
17  NULL    A       44,756,000  6           A           44,756,000
18  5       NULL    45,591,000  5           A           45,591,000
19  21      B       26,598,000  21          B           26,598,000
20  20      B       26,393,000  20          B           26,393,000
21  NULL    NULL    26,905,000  20          B           26,905,000
22  19      B       26,189,000  19          B           26,189,000
23  NULL    NULL    26,700,000  19          B           26,700,000
24  18      B       25,984,000  18          B           25,984,000
25  NULL    NULL    26,496,000  18          B           26,496,000
26  17      B       25,677,000  17          B           25,677,000
27  NULL    B       24,041,000  17          B           24,041,000
28  6       NULL    24,552,000  6           B           24,552,000

I want to achieve:

Id  RoomNo  Class   Price       NewRoomNo   NewClass    Price
1   21      A       43,028,000  NULL        NULL        43,028,000
2   NULL    NULL    43,896,000  21          A           43,896,000
3   20      A       42,681,000  NULL        NULL        42,681,000
4   NULL    NULL    43,549,000  20          A           43,549,000
5   19      A       42,334,000  NULL        NULL        42,334,000
6   NULL    NULL    43,202,000  19          A           43,202,000
7   18      A       41,987,000  NULL        NULL        41,987,000
8   NULL    NULL    42,855,000  18          A           42,855,000
9   17      A       41,467,000  NULL        NULL        41,467,000
10  NULL    NULL    42,334,000  17          A           42,334,000
11  16      A       41,120,000  NULL        NULL        41,120,000
12  NULL    NULL    41,987,000  16          A           41,987,000
13  NULL    A       39,211,000  NULL        NULL        39,211,000
14  9       NULL    40,079,000  9           A           40,079,000
15  NULL    NULL    38,691,000  NULL        NULL        38,691,000
16  6       NULL    39,385,000  6           A           39,385,000
17  NULL    A       44,756,000  NULL        NULL        44,756,000
18  5       NULL    45,591,000  5           A           45,591,000
19  21      B       26,598,000  21          B           26,598,000
20  20      B       26,393,000  NULL        NULL        26,393,000
21  NULL    NULL    26,905,000  20          B           26,905,000
22  19      B       26,189,000  NULL        NULL        26,189,000
23  NULL    NULL    26,700,000  19          B           26,700,000
24  18      B       25,984,000  NULL        NULL        25,984,000
25  NULL    NULL    26,496,000  18          B           26,496,000
26  17      B       25,677,000  17          B           25,677,000
27  NULL    B       24,041,000  NULL        NULL        24,041,000
28  6       NULL    24,552,000  6           B           24,552,000


问:
How to open a html file?
I have been trying to open a htmlfile on clicking help button.   And i need to import the file to source package so after build it wont show errors. I am using netbeans.  When i copied the file to src and tried running the file it showed error in compiling.  I want to know how to add the file to src and how to open by asking the user with a list of browsers installed in the system. Here is the code i have searched and tried..Thanks in advance

```<code>  try
  {
      File htmlFile = new File(this.getClass().getResource("help.html").getFile());
      Desktop.getDesktop().browse(htmlFile.toURI());
  }
  catch (IOException ex)
  {
      System.out.println(ex);
  }
</code>```

答:
Try this one.

```<code>import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Desktop;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class FileOpenBrowser {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JFrame frame = new JFrame("FileOpenBrowser"); // set API Name
        JPanel topPanel = new JPanel(new FlowLayout()); // set Panel Layout

        Button btn = new Button("Help");
        btn.setBounds(50, 100, 60, 30);
        topPanel.add(btn);

        frame.add(topPanel, BorderLayout.PAGE_START);

        frame.setSize(300, 300);
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    System.out.println("Start..");
                    File file = new java.io.File("src/help.html").getAbsoluteFile();
                    Desktop.getDesktop().open(file);
                    System.out.println("End..");
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        });
    }
}
</code>```

Title: How to open a html file?

Body:
I have been trying to open a htmlfile on clicking help button.   And i need to import the file to source package so after build it wont show errors. I am using netbeans.  When i copied the file to src and tried running the file it showed error in compiling.  I want to know how to add the file to src and how to open by asking the user with a list of browsers installed in the system. Here is the code i have searched and tried..Thanks in advance

  try
  {
      File htmlFile = new File(this.getClass().getResource("help.html").getFile());
      Desktop.getDesktop().browse(htmlFile.toURI());
  }
  catch (IOException ex)
  {
      System.out.println(ex);
  }

Body:
Try this one.

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Desktop;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class FileOpenBrowser {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JFrame frame = new JFrame("FileOpenBrowser"); // set API Name
        JPanel topPanel = new JPanel(new FlowLayout()); // set Panel Layout

        Button btn = new Button("Help");
        btn.setBounds(50, 100, 60, 30);
        topPanel.add(btn);

        frame.add(topPanel, BorderLayout.PAGE_START);

        frame.setSize(300, 300);
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    System.out.println("Start..");
                    File file = new java.io.File("src/help.html").getAbsoluteFile();
                    Desktop.getDesktop().open(file);
                    System.out.println("End..");
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        });
    }
}


问:
What can cause .NET assembly registration to fail?
We've seen an issue where one of our installers (msi) returns the error code 2908, which is used to indicate that an assembly failed to register.  Later in the installation, we get the following (sanitized) error:

MyAssemblyName, version="1.0.1.1",
  culture="neutral",
  publicKeyToken="119EFC79848A50".
  Please refer to Help and Support for
  more information. HRESULT: 0x8002802F.

The assembly registers properly on most systems.  Has anyone else encountered this issue?  How did you solve it?

答: I found a pair of blog postings that appear to cover this topic.</p>

OwnerDisplayName: tsellon

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: moocha

OwnerDisplayName: Curt Hagenlocher


问:
How to create a copy of a file having length more than 260 characters
How to create a copy of a file having length more than 260 characters including file name using vb.net

When we are trying to create a copy using File.Copy method it throws exception as follows:

"The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters."

Is it possible, then please help...

答: Have a look at this library and this discussion.</p>

OwnerDisplayName: Sugam

LastEditorDisplayName: CodeSlave

OwnerDisplayName: schnaader


问:
Get text from anchor tag
I have the following anchor tag

```<code><a href="http://www.google.com/">Google</a>
</code>```

I know how to get the href from an anchor take:

```<code>alert($(this).attr("href"));
</code>```

But how do I get the text from the anchor tag, i.e. how do I get "Google"?

答:
On using the .text() as mentioned, I got the text of all the anchor tags combined in my code:

HTML:

```<code><div class="col-sm-2 jumbotron jumbotronUserRaces list-group list-group-
userRaces" id="listGroupUserRaces">
                <a href="" class="list-group-item active">First item</a>
                <a href="" class="list-group-item">Second item</a>
                <a href="" class="list-group-item">Third item</a>
            </div>
</code>```

JS:

```<code>$("#listGroupUserRaces").click(function () {
   alert($(this).text());
});
</code>```

OUTPUT:

First item

Second item

Third item

Title: Get text from anchor tag

Body:
I have the following anchor tag

Google

I know how to get the href from an anchor take:

alert($(this).attr("href"));

But how do I get the text from the anchor tag, i.e. how do I get "Google"?

Body:
On using the .text() as mentioned, I got the text of all the anchor tags combined in my code:

HTML:

<div class="col-sm-2 jumbotron jumbotronUserRaces list-group list-group-
userRaces" id="listGroupUserRaces">
                <a href="" class="list-group-item active">First item</a>
                <a href="" class="list-group-item">Second item</a>
                <a href="" class="list-group-item">Third item</a>
            </div>

JS:

$("#listGroupUserRaces").click(function () {
   alert($(this).text());
});

OUTPUT:

First item

Second item

Third item


问:
Getting all nodes connected to the given node in Neo4j browser causing neo4j crash
I have a graph with many hundread thousand nodes. In that, there is one particular node of interest. I want to get all nodes connected to that node with any relationship and any relationship depth (that is it might be connected to the original node through several other nodes). I queries node with its id property and expanded all its neighboring nodes. The graph looks like this with the node of interest highlighted/clicked:

I tried following query to get all those nodes:

```<code>MATCH (a {id :"8e5b90c5242f4382bd8e71ae901b0433"})
CALL apoc.path.expandConfig(a,
{
  uniqueness: 'NODE_PATH'
}) yield path
return path
</code>```

But this makes the neo4j take gigs of RAM and I have only 4GBs. The query hangs pc and never completes. Whats wrong with cypher?

答:
You might want to use apoc.path.subgraphNodes() instead, which "expands to nodes of a subgraph" which es exactly what you want.

See the APOC User Guide, this function was added in March.

Body:
I have a graph with many hundread thousand nodes. In that, there is one particular node of interest. I want to get all nodes connected to that node with any relationship and any relationship depth (that is it might be connected to the original node through several other nodes). I queries node with its id property and expanded all its neighboring nodes. The graph looks like this with the node of interest highlighted/clicked:

I tried following query to get all those nodes:

MATCH (a {id :"8e5b90c5242f4382bd8e71ae901b0433"})
CALL apoc.path.expandConfig(a,
{
  uniqueness: 'NODE_PATH'
}) yield path
return path

But this makes the neo4j take gigs of RAM and I have only 4GBs. The query hangs pc and never completes. Whats wrong with cypher?


问:
Java build: Executing manifest /build/null2120978844 is invalid
I've built this project several times in the past. Suddenly it started doing this:

```<code>init:
deps-clean:
Updating property file: /home/adam/code/HeimdallOneClick/build/built-clean.properties
Deleting directory /home/adam/code/HeimdallOneClick/build
clean:
init:
deps-jar:
Created dir: /home/adam/code/HeimdallOneClick/build
Updating property file: /home/adam/code/HeimdallOneClick/build/built-jar.properties
Created dir: /home/adam/code/HeimdallOneClick/build/classes
Created dir: /home/adam/code/HeimdallOneClick/build/empty
Compiling 14 source files to /home/adam/code/HeimdallOneClick/build/classes
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Copying 51 files to /home/adam/code/HeimdallOneClick/build/classes
compile:
Created dir: /home/adam/code/HeimdallOneClick/dist
Copying 1 file to /home/adam/code/HeimdallOneClick/build
/home/adam/code/HeimdallOneClick/nbproject/build-impl.xml:676: Existing manifest /home/adam/code/HeimdallOneClick/build/null2120978844 is invalid
BUILD FAILED (total time: 4 seconds)
</code>```

I don't know how to fix this.  The manifest is quite long, but here's the section it's failing on.

```<code><target depends="init,-do-jar-with-libraries-create-manifest,-do-jar-with-libraries-copy-manifest" if="do.archive+main.class.available" name="-do-jar-with-libraries-set-main">
    <manifest file="${tmp.manifest.file}" mode="update">
        <attribute name="Main-Class" value="${main.class}"/>
    </manifest>
</target>
</code>```

What do I do for troubleshooting?  Is there some way to rebuild the manifest?

答:
Put your SplashScreen in the first line in manifest like:

```<code>SplashScreen-Image: "Here the path of your Image"
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build
</code>```

Body:
I've built this project several times in the past. Suddenly it started doing this:

init:
deps-clean:
Updating property file: /home/adam/code/HeimdallOneClick/build/built-clean.properties
Deleting directory /home/adam/code/HeimdallOneClick/build
clean:
init:
deps-jar:
Created dir: /home/adam/code/HeimdallOneClick/build
Updating property file: /home/adam/code/HeimdallOneClick/build/built-jar.properties
Created dir: /home/adam/code/HeimdallOneClick/build/classes
Created dir: /home/adam/code/HeimdallOneClick/build/empty
Compiling 14 source files to /home/adam/code/HeimdallOneClick/build/classes
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Copying 51 files to /home/adam/code/HeimdallOneClick/build/classes
compile:
Created dir: /home/adam/code/HeimdallOneClick/dist
Copying 1 file to /home/adam/code/HeimdallOneClick/build
/home/adam/code/HeimdallOneClick/nbproject/build-impl.xml:676: Existing manifest /home/adam/code/HeimdallOneClick/build/null2120978844 is invalid
BUILD FAILED (total time: 4 seconds)

I don't know how to fix this.  The manifest is quite long, but here's the section it's failing on.

<target depends="init,-do-jar-with-libraries-create-manifest,-do-jar-with-libraries-copy-manifest" if="do.archive+main.class.available" name="-do-jar-with-libraries-set-main">
    <manifest file="${tmp.manifest.file}" mode="update">
        <attribute name="Main-Class" value="${main.class}"/>
    </manifest>
</target>

What do I do for troubleshooting?  Is there some way to rebuild the manifest?

Body:
Put your SplashScreen in the first line in manifest like:

SplashScreen-Image: "Here the path of your Image"
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build


问:
batch doen't read text file till save it first
My code stops at line 3 in the .dat file ,but when i save the .dat file it reads all the lines and work properly why this happening and what to do??

this is code my data contain Latina characters and symbols.

```<code>@ECHO Off
SET "sourcedir=D:\yyyyy\Orgin_file_Ma\MA_SMS"
SET "destdir=D:\llllll\STG_file_Ma"
FOR %%f IN ("%sourcedir%\*.dat") DO > "%destdir%\%%~nf.txt" (
FOR /f "usebackqdelims=" %%a IN ("%%f") DO (
set Typ=SMS
  ECHO %%a^|!Typ!
 )
   )
</code>```

答: Thank you for your helpful answers i learned a lot,i solved my problem by using Powershell instead of batch.</p>

Body:
My code stops at line 3 in the .dat file ,but when i save the .dat file it reads all the lines and work properly why this happening and what to do??

this is code my data contain Latina characters and symbols.

@ECHO Off
SET "sourcedir=D:\yyyyy\Orgin_file_Ma\MA_SMS"
SET "destdir=D:\llllll\STG_file_Ma"
FOR %%f IN ("%sourcedir%\*.dat") DO > "%destdir%\%%~nf.txt" (
FOR /f "usebackqdelims=" %%a IN ("%%f") DO (
set Typ=SMS
  ECHO %%a^|!Typ!
 )
   )


问:
Automapper 6.1.1 Exception using MemberList.Source: Unmapped members were found
I'm getting the following error in Automapper:

```<code>Unmapped members were found. Review the types and members below.
Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
For no matching constructor, add a no-arg ctor, add optional arguments, or map all of the constructor parameters
</code>```

Configuration looks like this:

```<code>cfg.CreateMap<ArticleViewModel, Article>(MemberList.Source)
    .EqualityComparison((src, dst) => src.Id == dst.Id);
</code>```

Normally I would solve it like .ForMember(x => x.NoMapProp, opt => opt.Ignore()) but since I'm using MemberList.Source I can't reach the property with ForMember. How can I solve this?

答:
It was easy, solved like this:</p>

```<code>cfg.CreateMap<ArticleViewModel, Article>(MemberList.Source)
    .EqualityComparison((src, dst) => src.Id == dst.Id)
    .ForSourceMember(x => x.NoMapProp, opt => opt.Ignore());
</code>```

Body:
I'm getting the following error in Automapper:

Unmapped members were found. Review the types and members below.
Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
For no matching constructor, add a no-arg ctor, add optional arguments, or map all of the constructor parameters

Configuration looks like this:

cfg.CreateMap<ArticleViewModel, Article>(MemberList.Source)
    .EqualityComparison((src, dst) => src.Id == dst.Id);

Normally I would solve it like .ForMember(x => x.NoMapProp, opt => opt.Ignore()) but since I'm using MemberList.Source I can't reach the property with ForMember. How can I solve this?

Body:
It was easy, solved like this:

cfg.CreateMap<ArticleViewModel, Article>(MemberList.Source)
    .EqualityComparison((src, dst) => src.Id == dst.Id)
    .ForSourceMember(x => x.NoMapProp, opt => opt.Ignore());


问:
How to invoke another servlet in a servlet?
As title metioned, How to invoke another servlet in a servlet and get the invoked servlet response?</p>

答:
See here:

```<code>getServletContext().getNamedRequestDispatcher("servletName")
    .forward(request, response);
</code>```

However I'd assume there are better options. For example move the code you need to a helper class / utility method, and invoke it.

As I come to think of it, you may want another thing: call a servlet separately. For that you need:

```<code>InputStream is = new URL(urlOfTheServlet).openStream();
IOUtils.copy(is, response.getOutputStream());
</code>```

(this is using apache commons-io to copy the input stream to the output stream of the current request)

Body:
See here:

getServletContext().getNamedRequestDispatcher("servletName")
    .forward(request, response);

However I'd assume there are better options. For example move the code you need to a helper class / utility method, and invoke it.

As I come to think of it, you may want another thing: call a servlet separately. For that you need:

InputStream is = new URL(urlOfTheServlet).openStream();
IOUtils.copy(is, response.getOutputStream());

(this is using apache commons-io to copy the input stream to the output stream of the current request)


问:
Getting ID of detail-page instance that is currently open
How to handle PushNotifications in my Ionic3 / AngularJS mobile app are shown to my users while the app is open? I can identify page which the user is currently on and I can do that by:

```<code>if ( (this.navCtrl.getActive().component === Page1) ){
    // user is currently on Page1
    // handle push notification
}
</code>```

Unfortunately, this is not enough. Page1 is a detail page, which shows details of an item. Let's say there are 3 items: Banana (id: 1), Apple (id: 2) and Orange (id: 3).

I need to know, whether the user is currently looking at Page1 for item1, item2 or item3. I want to do something like this:

```<code>if ( (this.navCtrl.getActive().component === Page1 && data.itemID === "page1-itemId") ){
    // data.itemID is the ID i get from the push notification
    // "page1-itemId" is what I desire to get somehow
}
</code>```

How could I find out about page1-itemId?

答:
Yo can do something like from component which navigates to Detail component.

```<code>this.navCtrl.push(DetailPage, {
  id: "1",
});
</code>```

and then in Detail page read that id param like this. Don't forget to import and inject Navparams in constructor

```<code>import { NavParams } from 'ionic-angular';

constructor(private navParams: NavParams) {
  let id = navParams.get('id');
}
</code>```

source Ionic NavController docs

Body:
How to handle PushNotifications in my Ionic3 / AngularJS mobile app are shown to my users while the app is open? I can identify page which the user is currently on and I can do that by:

if ( (this.navCtrl.getActive().component === Page1) ){
    // user is currently on Page1
    // handle push notification
}

Unfortunately, this is not enough. Page1 is a detail page, which shows details of an item. Let's say there are 3 items: Banana (id: 1), Apple (id: 2) and Orange (id: 3).

I need to know, whether the user is currently looking at Page1 for item1, item2 or item3. I want to do something like this:

if ( (this.navCtrl.getActive().component === Page1 && data.itemID === "page1-itemId") ){
    // data.itemID is the ID i get from the push notification
    // "page1-itemId" is what I desire to get somehow
}

How could I find out about page1-itemId?

Body:
Yo can do something like from component which navigates to Detail component.

this.navCtrl.push(DetailPage, {
  id: "1",
});

and then in Detail page read that id param like this. Don't forget to import and inject Navparams in constructor

import { NavParams } from 'ionic-angular';

constructor(private navParams: NavParams) {
  let id = navParams.get('id');
}

source Ionic NavController docs


问:
easiest way to rotate a PNG file 90 degrees within R
what's the most painless way to programmatically open a PNG file on my computer, rotate it 90 degrees, then save it as another PNG file - with no loss of quality and no other changes?  it's a five-second task in microsoft paint but all of the plotting, raster, image, device answers to related SO questions have me confused about the simplest way to do this?  thanks

答:
Try package magick :

```<code>library(magick)
newlogo <- image_read("https://www.r-project.org/logo/Rlogo.png")
newlogo <- image_scale(newlogo, "400x400") # logo is too big

# rotate
image_rotate(newlogo, 90)

# save
image_rotate(newlogo, 45) %>% image_write("newlogoRotated.png")
</code>```

I think that's the easiest way !

Body:
Try package magick :

library(magick)
newlogo <- image_read("https://www.r-project.org/logo/Rlogo.png")
newlogo <- image_scale(newlogo, "400x400") # logo is too big

# rotate
image_rotate(newlogo, 90)

# save
image_rotate(newlogo, 45) %>% image_write("newlogoRotated.png")

I think that's the easiest way !


问:
write to new row every xth element java csv write
Using an answer I found here on SO I have found a way to write out my resultset to a csv file.  However it currently just writes every element of the array to a new column.  How would I alter the following code to change format to create new row, on every xth element like below?

```<code>int value = 2
Current format:  a, b, c, d, e, f

Desired format: a, b,
                c, d,
                e, f
</code>```

I know I can utilize the modulo of the int value, but am unsure how to write to a specific column or row.

```<code>private static final String DEFAULT_SEPARATOR = " ";

 public static void writeLine(Writer w, List<String> values, String separators, String customQuote) throws IOException {

    boolean first = true;

    //default customQuote is empty

    if (separators == " ") {
        separators = DEFAULT_SEPARATOR;
    }

    StringBuilder sb = new StringBuilder();
    for (String value : values) {
        if (!first) {
            sb.append(separators);
        }
        if (customQuote == " ") {
            sb.append(followCVSformat(value));
        } else {
            sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
        }

        first = false;
    }
    sb.append("\n");
    w.append(sb.toString());

}

private static String followCVSformat(String value) {

        String result = value;
        if (result.contains("\"")) {
            result = result.replace("\"", "\"\"");
        }
        return result;

    }
</code>```

答:
```<code>public static void writeLine(
        Writer w, List<String> values, String separators, String customQuote, int elementsPerRow)
        throws IOException {
    ...
    int counter = 0;
    for (String value : values) {
        if (!first) {
            sb.append(separators);
        }
        if (counter != 0 && counter % elementsPerRow == 0)
            sb.append("\n");
        if (customQuote == " ") {
            sb.append(followCVSformat(value));
        } else {
            sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
        }
        first = false;
        counter++;
    }
    ...
</code>```

Body:
Using an answer I found here on SO I have found a way to write out my resultset to a csv file.  However it currently just writes every element of the array to a new column.  How would I alter the following code to change format to create new row, on every xth element like below?

int value = 2
Current format:  a, b, c, d, e, f

Desired format: a, b,
                c, d,
                e, f

I know I can utilize the modulo of the int value, but am unsure how to write to a specific column or row.

private static final String DEFAULT_SEPARATOR = " ";

 public static void writeLine(Writer w, List<String> values, String separators, String customQuote) throws IOException {

    boolean first = true;

    //default customQuote is empty

    if (separators == " ") {
        separators = DEFAULT_SEPARATOR;
    }

    StringBuilder sb = new StringBuilder();
    for (String value : values) {
        if (!first) {
            sb.append(separators);
        }
        if (customQuote == " ") {
            sb.append(followCVSformat(value));
        } else {
            sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
        }

        first = false;
    }
    sb.append("\n");
    w.append(sb.toString());

}

private static String followCVSformat(String value) {

        String result = value;
        if (result.contains("\"")) {
            result = result.replace("\"", "\"\"");
        }
        return result;

    }


问:
How set the android:gravity to TextView from Java side in Android
I can use android:gravity="bottom|center_horizontal" in xml on a textview to get my desired results, but I need to do this programmatically. My textview is inside a tablerow if that matters in a relativelayout.

I have tried:

```<code>LayoutParams layoutParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
labelTV.setLayoutParams(layoutParams);
</code>```

But if I understand correctly, that would apply it to the tablerow, not the textview?

答:
```<code>textView.setGravity(Gravity.CENTER | Gravity.BOTTOM);
</code>```

This will set gravity of your textview.

ContentLicense: CC BY-SA 4.0

Body:
I can use android:gravity="bottom|center_horizontal" in xml on a textview to get my desired results, but I need to do this programmatically. My textview is inside a tablerow if that matters in a relativelayout.

I have tried:

LayoutParams layoutParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
labelTV.setLayoutParams(layoutParams);

But if I understand correctly, that would apply it to the tablerow, not the textview?

Body:
textView.setGravity(Gravity.CENTER | Gravity.BOTTOM);

This will set gravity of your textview.


问:
paypal express checkout problem
Hi I am integrating paypal with my website. I want that user enter their all information on my site (creditcard information and personal information).

I have down loded paypalfunctions.php from paypal developer website.

My code is :-

```<code>if(isset($_POST['submitCard']))
{
 $firstName  =trim($_POST['firstName']);
 $lastName  =trim($_POST['lastName']);
 $street   =trim($_POST['street']);
 $city   =trim($_POST['city']);
 $state   =trim($_POST['state']);
 $zip   =trim($_POST['zip']);
 $countryCode =$_POST['country'];
 $currencyCode ='USD';
 $paymentType ='Sale';
 $paymentAmount =$_POST['productPrice'];
 $creditCardType =$_POST['cardType'];
 $creditCardNumber=$_POST['cardNo'];
 $expDate  ='122015';
 $cvv2   =$_POST['cvv'];
 $returnResult=DirectPayment( $paymentType, $paymentAmount, $creditCardType, $creditCardNumber,
        $expDate, $cvv2, $firstName, $lastName, $street, $city, $state, $zip,
        $countryCode, $currencyCode );
 echo '```';
     print_r($returnResult);
```

<p>DirectPayment method is in paypalFunctions.php and this is </p>

```function DirectPayment( $paymentType, $paymentAmount, $creditCardType, $creditCardNumber,
       $expDate, $cvv2, $firstName, $lastName, $street, $city, $state, $zip,
       $countryCode, $currencyCode )
 {
  //Construct the parameter string that describes DoDirectPayment
  $nvpstr = "&AMT=" . $paymentAmount;
  $nvpstr = $nvpstr . "&CURRENCYCODE=" . $currencyCode;
  $nvpstr = $nvpstr . "&PAYMENTACTION=" . $paymentType;
  $nvpstr = $nvpstr . "&CREDITCARDTYPE=" . $creditCardType;
  $nvpstr = $nvpstr . "&ACCT=" . $creditCardNumber;
  $nvpstr = $nvpstr . "&EXPDATE=" . $expDate;
  $nvpstr = $nvpstr . "&CVV2=" . $cvv2;
  $nvpstr = $nvpstr . "&FIRSTNAME=" . $firstName;
  $nvpstr = $nvpstr . "&LASTNAME=" . $lastName;
  $nvpstr = $nvpstr . "&STREET=" . $street;
  $nvpstr = $nvpstr . "&CITY=" . $city;
  $nvpstr = $nvpstr . "&STATE=" . $state;
  $nvpstr = $nvpstr . "&COUNTRYCODE=" . $countryCode;
  $nvpstr = $nvpstr . "&IPADDRESS=" . $_SERVER['REMOTE_ADDR'];

  $resArray=hash_call("DoDirectPayment", $nvpstr);

  return $resArray;
 }

 /**
   '-------------------------------------------------------------------------------------------------------------------------------------------
   * hash_call: Function to perform the API call to PayPal using API signature
   * @methodName is name of API  method.
   * @nvpStr is nvp string.
   * returns an associtive array containing the response from the server.
   '-------------------------------------------------------------------------------------------------------------------------------------------
 */
 function hash_call($methodName,$nvpStr)
 {
  //declaring of global variables
  global $API_Endpoint, $version, $API_UserName, $API_Password, $API_Signature;
  global $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
  global $gv_ApiErrorURL;
  global $sBNCode;

  //setting the curl parameters.
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL,$API_Endpoint);
  curl_setopt($ch, CURLOPT_VERBOSE, 1);

  //turning off the server and peer verification(TrustManager Concept).
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch, CURLOPT_POST, 1);

     //if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
    //Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php
  if($USE_PROXY)
   curl_setopt ($ch, CURLOPT_PROXY, $PROXY_HOST. ":" . $PROXY_PORT);

  //NVPRequest for submitting to server
  $nvpreq="METHOD=" . urlencode($methodName) . "&VERSION=" . urlencode($version) . "&PWD=" . urlencode($API_Password) . "&USER=" . urlencode($API_UserName) . "&SIGNATURE=" . urlencode($API_Signature) . $nvpStr . "&BUTTONSOURCE=" . urlencode($sBNCode);

  //setting the nvpreq as POST FIELD to curl
  curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);

  //getting response from server
  $response = curl_exec($ch);

  //convrting NVPResponse to an Associative Array
  $nvpResArray=deformatNVP($response);
  $nvpReqArray=deformatNVP($nvpreq);
  $_SESSION['nvpReqArray']=$nvpReqArray;

  if (curl_errno($ch))
  {
   // moving to display page to display curl errors
     $_SESSION['curl_error_no']=curl_errno($ch) ;
     $_SESSION['curl_error_msg']=curl_error($ch);

     //Execute the Error handling module to display errors.
  }
  else
  {
    //closing the curl
     curl_close($ch);
  }

  return $nvpResArray;
 }

    }
    ?>
```

<p>it gives error</p>

```         Array
(
    [TIMESTAMP] => 2010-12-21T06:06:54Z
    [CORRELATIONID] => 1cafc53222e76
    [ACK] => Failure
    [VERSION] => 64
    [BUILD] => 1620725
    [L_ERRORCODE0] => 10002
    [L_SHORTMESSAGE0] => Security error
    [L_LONGMESSAGE0] => Security header is not valid
    [L_SEVERITYCODE0] => Error
)
```

i cant understand what is problem is going on.Please help.

答:
Have configure your API credentials correctly?
you can dump the hash_call out if needed.

If you are doing sandbox testing,
Make sure the endpoint of the call is: https://api-3t.sandbox.paypal.com/nvp
-- pointed to the 'SANDBOX'

Title: paypal express checkout problem

Body:
Hi I am integrating paypal with my website. I want that user enter their all information on my site (creditcard information and personal information).

I have down loded paypalfunctions.php from paypal developer website.

My code is :-

if(isset($_POST['submitCard']))
{
 $firstName  =trim($_POST['firstName']);
 $lastName  =trim($_POST['lastName']);
 $street   =trim($_POST['street']);
 $city   =trim($_POST['city']);
 $state   =trim($_POST['state']);
 $zip   =trim($_POST['zip']);
 $countryCode =$_POST['country'];
 $currencyCode ='USD';
 $paymentType ='Sale';
 $paymentAmount =$_POST['productPrice'];
 $creditCardType =$_POST['cardType'];
 $creditCardNumber=$_POST['cardNo'];
 $expDate  ='122015';
 $cvv2   =$_POST['cvv'];
 $returnResult=DirectPayment( $paymentType, $paymentAmount, $creditCardType, $creditCardNumber,
        $expDate, $cvv2, $firstName, $lastName, $street, $city, $state, $zip,
        $countryCode, $currencyCode );
 echo '
';
     print_r($returnResult);

DirectPayment method is in paypalFunctions.php and this is

function DirectPayment( $paymentType, $paymentAmount, $creditCardType, $creditCardNumber,
       $expDate, $cvv2, $firstName, $lastName, $street, $city, $state, $zip,
       $countryCode, $currencyCode )
 {
  //Construct the parameter string that describes DoDirectPayment
  $nvpstr = "&AMT=" . $paymentAmount;
  $nvpstr = $nvpstr . "&CURRENCYCODE=" . $currencyCode;
  $nvpstr = $nvpstr . "&PAYMENTACTION=" . $paymentType;
  $nvpstr = $nvpstr . "&CREDITCARDTYPE=" . $creditCardType;
  $nvpstr = $nvpstr . "&ACCT=" . $creditCardNumber;
  $nvpstr = $nvpstr . "&EXPDATE=" . $expDate;
  $nvpstr = $nvpstr . "&CVV2=" . $cvv2;
  $nvpstr = $nvpstr . "&FIRSTNAME=" . $firstName;
  $nvpstr = $nvpstr . "&LASTNAME=" . $lastName;
  $nvpstr = $nvpstr . "&STREET=" . $street;
  $nvpstr = $nvpstr . "&CITY=" . $city;
  $nvpstr = $nvpstr . "&STATE=" . $state;
  $nvpstr = $nvpstr . "&COUNTRYCODE=" . $countryCode;
  $nvpstr = $nvpstr . "&IPADDRESS=" . $_SERVER['REMOTE_ADDR'];

  $resArray=hash_call("DoDirectPayment", $nvpstr);

  return $resArray;
 }

 /**
   '-------------------------------------------------------------------------------------------------------------------------------------------
   * hash_call: Function to perform the API call to PayPal using API signature
   * @methodName is name of API  method.
   * @nvpStr is nvp string.
   * returns an associtive array containing the response from the server.
   '-------------------------------------------------------------------------------------------------------------------------------------------
 */
 function hash_call($methodName,$nvpStr)
 {
  //declaring of global variables
  global $API_Endpoint, $version, $API_UserName, $API_Password, $API_Signature;
  global $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
  global $gv_ApiErrorURL;
  global $sBNCode;

  //setting the curl parameters.
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL,$API_Endpoint);
  curl_setopt($ch, CURLOPT_VERBOSE, 1);

  //turning off the server and peer verification(TrustManager Concept).
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch, CURLOPT_POST, 1);

     //if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
    //Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php
  if($USE_PROXY)
   curl_setopt ($ch, CURLOPT_PROXY, $PROXY_HOST. ":" . $PROXY_PORT);

  //NVPRequest for submitting to server
  $nvpreq="METHOD=" . urlencode($methodName) . "&VERSION=" . urlencode($version) . "&PWD=" . urlencode($API_Password) . "&USER=" . urlencode($API_UserName) . "&SIGNATURE=" . urlencode($API_Signature) . $nvpStr . "&BUTTONSOURCE=" . urlencode($sBNCode);

  //setting the nvpreq as POST FIELD to curl
  curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);

  //getting response from server
  $response = curl_exec($ch);

  //convrting NVPResponse to an Associative Array
  $nvpResArray=deformatNVP($response);
  $nvpReqArray=deformatNVP($nvpreq);
  $_SESSION['nvpReqArray']=$nvpReqArray;

  if (curl_errno($ch))
  {
   // moving to display page to display curl errors
     $_SESSION['curl_error_no']=curl_errno($ch) ;
     $_SESSION['curl_error_msg']=curl_error($ch);

     //Execute the Error handling module to display errors.
  }
  else
  {
    //closing the curl
     curl_close($ch);
  }

  return $nvpResArray;
 }

    }
    ?>

it gives error

         Array
(
    [TIMESTAMP] => 2010-12-21T06:06:54Z
    [CORRELATIONID] => 1cafc53222e76
    [ACK] => Failure
    [VERSION] => 64
    [BUILD] => 1620725
    [L_ERRORCODE0] => 10002
    [L_SHORTMESSAGE0] => Security error
    [L_LONGMESSAGE0] => Security header is not valid
    [L_SEVERITYCODE0] => Error
)

i cant understand what is problem is going on.Please help.


问:
Subtle curve on bottom of div
I am trying to achieve a subtle curve at the bottom of my

Here is an example image of what i am trying to achieve

I tried to achieve it by doing this :

```<code>section.box{
    border-bottom-left-radius: 40%;
    border-bottom-right-radius: 40%;
}
</code>```

This is what I'm getting.

What can i do to change this?

UPDATE

What I have tried :

.box{
  height: 300px;
  background-color: white;
}

.round-bottom{
  background-color: pink;
  height: 200px;

  border-bottom-left-radius: 50%;
  border-bottom-right-radius: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <section class="round-bottom">

  </section>
</div></code>```

答:
You could achive that by adjustion border-radius in your CSS rules like :

```<code>  border-radius: 0 0 100% 100%  /100%;
</code>```

And by adding shadows like :

```<code>  box-shadow: 1px -3px 22px 0px;
</code>```

Hope this helps.

body{
  margin: 0px;
}
div#box{
  height: 50px;
  width: 100%;
  background-color: #ea3e5e;
  border-radius: 0 0 100% 100%  /100%;
  box-shadow: 1px -3px 22px 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="box"></div></code>```

Title: Subtle curve on bottom of div

Body:
I am trying to achieve a subtle curve at the bottom of my

Here is an example image of what i am trying to achieve

I tried to achieve it by doing this :

section.box{
    border-bottom-left-radius: 40%;
    border-bottom-right-radius: 40%;
}

This is what I'm getting.

What can i do to change this?

UPDATE

What I have tried :

.box{
  height: 300px;
  background-color: white;
}

.round-bottom{
  background-color: pink;
  height: 200px;

  border-bottom-left-radius: 50%;
  border-bottom-right-radius: 50%;
}

Body:
You could achive that by adjustion border-radius in your CSS rules like :

  border-radius: 0 0 100% 100%  /100%;

And by adding shadows like :

  box-shadow: 1px -3px 22px 0px;

Hope this helps.

body{
  margin: 0px;
}
div#box{
  height: 50px;
  width: 100%;
  background-color: #ea3e5e;
  border-radius: 0 0 100% 100%  /100%;
  box-shadow: 1px -3px 22px 0px;
}

<div id="box"></div>


问:
How can I properly include a css file in my index.html file in React?
I've looked everywhere and can't seem to find an answer. I am building a website with React, and I want to include a stylesheet. My React app has the index.html file and I created a line in the file that says:

<link rel="stylesheet" type="text/css" href="homePage.css">

but React won't load the css. How do I do this properly?

Sidenote: React also doesn't load images. When I put a line of code in my JSX like this:

React won't load the image. Please help, I've been banging my head against my desk about this for a while now.

Thanks in advance.

答:
in your html file all you need to do is a normal link statement

```<code><link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/journal/bootstrap.min.css" rel="stylesheet" integrity="sha384-1L94saFXWAvEw88RkpRz8r28eQMvt7kG9ux3DdCqya/P3CfLNtgqzMnyaUa49Pl2" crossorigin="anonymous" />
</code>```

Like so that one is from a website but you can do the same thing with a local one like

```<code><link src="/styles/maincss.css" rel="stylesheet" />
</code>```

that will work

Body:
in your html file all you need to do is a normal link statement

<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/journal/bootstrap.min.css" rel="stylesheet" integrity="sha384-1L94saFXWAvEw88RkpRz8r28eQMvt7kG9ux3DdCqya/P3CfLNtgqzMnyaUa49Pl2" crossorigin="anonymous" />

Like so that one is from a website but you can do the same thing with a local one like

<link src="/styles/maincss.css" rel="stylesheet" />

that will work


问:
How can I blur the background of my layout?
I have tried most of the solutions from stack overflow, but I don't seem to get a correct implementation of the blurred effect.

Help me out please

答:
alpha attribute is there for view  in android who represent Opacity

In XML

```<code>android:alpha="0.5"
</code>```

Programatically

```<code>yourView.setAlpha(0.5f);
</code>```

also you can set backgroud color as you want for view

```<code>v.setBackgroundColor(0xFF00FF00);
</code>```

Body:
alpha attribute is there for view  in android who represent Opacity

In XML

android:alpha="0.5"

Programatically

yourView.setAlpha(0.5f);

also you can set backgroud color as you want for view

v.setBackgroundColor(0xFF00FF00);


问:
How to invoke controller methods in Spring MVC
I want to hit the readTasks method of my controller when navigating to the root of my web app. I have set a breakpoint in the method but I am not hitting it when debugging on the server. I am using Eclipse.

I nagivate to: http://localhost:8080/ToDoList/ and I see my index page but the controller method is not invoked.

My Controller:

```<code>import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TaskController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<TaskEntity> readTasks()
    {
        TaskEntityDao tasks = new TaskEntityDaoImpl();
        return tasks.getAllTasks();
    }
}
</code>```

My web.xml:

```<code><web-app version="2.4"
     xmlns="http://java.sun.com/xml/ns/j2ee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>Dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>
</code>```

I believe I am missing some configuration to initialise the controller, but I am not sure how to go about it. Do I need a configuration file that contains initialisation of every single controller in my application?

答:
You need to made a Spring MVC configuration, in your web.xml:

```<code><servlet>
    <servlet-name>Dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    <init-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>/WEB-INF/spring/mvc-dispatcher-servlet.xml</param-value>
    </init-param>
</servlet>
</code>```

Then make mvc-dispatcher-servlet.xml under WEB-INF folder.

```<code><beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd ">

    <!-- enable to scan spring annotations, specify on web package -->
    <context:component-scan base-package="id.swhp.spring.web"/>
    <!-- Enable Spring MVC Anotations -->
    <mvc:annotation-driven/>

</beans>
</code>```

Body:
I want to hit the readTasks method of my controller when navigating to the root of my web app. I have set a breakpoint in the method but I am not hitting it when debugging on the server. I am using Eclipse.

I nagivate to: http://localhost:8080/ToDoList/ and I see my index page but the controller method is not invoked.

My Controller:

import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TaskController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<TaskEntity> readTasks()
    {
        TaskEntityDao tasks = new TaskEntityDaoImpl();
        return tasks.getAllTasks();
    }
}

My web.xml:

<web-app version="2.4"
     xmlns="http://java.sun.com/xml/ns/j2ee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>Dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

I believe I am missing some configuration to initialise the controller, but I am not sure how to go about it. Do I need a configuration file that contains initialisation of every single controller in my application?

Body:
You need to made a Spring MVC configuration, in your web.xml:

<servlet>
    <servlet-name>Dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    <init-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>/WEB-INF/spring/mvc-dispatcher-servlet.xml</param-value>
    </init-param>
</servlet>

Then make mvc-dispatcher-servlet.xml under WEB-INF folder.

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd ">

    <!-- enable to scan spring annotations, specify on web package -->
    <context:component-scan base-package="id.swhp.spring.web"/>
    <!-- Enable Spring MVC Anotations -->
    <mvc:annotation-driven/>

</beans>


答:
Use RequestDispatcher instance which is available through the HttpServletRequest instance.

However, if you're looking at getting hold of the single instance held by the servlet container [like using the getServlet method in the ServletContext instance], it's an entirely different story. The servlet specs have purposefully deprecated the operation which might allow such an option. But, if you really want to invoke one servlet while executing the other one, use the include method of the RequestDispatcher instead of the forward method.

Title: How to invoke another servlet in a servlet?

Body: As title metioned, How to invoke another servlet in a servlet and get the invoked servlet response?


问:
Multiple level by aggregation data.table (R)
it might be that this is trivial, but I'm probably confused.

I have something like this:

```<code>set.seed(1234)

dt<-data.table(day=sample(c("day1","day2","day3"),20,replace = T),
store=sample(c("store1","store2","store3"),20,replace=T),
x=rnorm(20,33,6),y=rnorm(20,12,10))
</code>```

I am interested in aggregating by day and store:

```<code>dt[,.(sumx=sum(x),sumy=sum(y)),by=c("day","store")]

    day  store      sumx     sumy
1: day1 store2  56.33890 44.52312
2: day2 store1 164.72854 61.37866
3: day3 store3 144.52483 53.74347
4: day1 store3  56.25504 34.00066
5: day3 store1  70.61311 30.85589
6: day2 store3 123.34534 74.67024
7: day2 store2  35.72952 21.19009
</code>```

But also, more globally, by day only:

```<code>dt[,.(sumx=sum(x),sumy=sum(y)),by=day]

    day     sumx      sumy
1: day1 112.5939  78.52378
2: day2 323.8034 157.23899
3: day3 215.1379  84.59936
</code>```

In practice, I would like to end up with a dataset that has aggregation per day and store, and an additional column with day only aggregation:

```<code>    day  store      sumx     sumy sumx_daylevel sumy_daylevel
1: day1 store2  56.33890 44.52312    112.5939    78.52378
2: day2 store1 164.72854 61.37866    323.8034    157.23899
3: day3 store3 144.52483 53.74347    215.1379    84.59936
4: day1 store3  56.25504 34.00066    112.5939    78.52378
5: day3 store1  70.61311 30.85589    215.1379    84.59936
6: day2 store3 123.34534 74.67024    323.8034    157.23899
7: day2 store2  35.72952 21.19009    323.8034    157.23899
</code>```

I'd like to achieve that wrapping everything in a function, no merging.
Any help will be appreciated. Thank you

答:
We can use := to create new columns

```<code>dt[,.(sumx=sum(x),sumy=sum(y)),by=c("day","store")
     ][, c("sumx_daylevel", "sumy_daylevel") := .(sum(sumx), sum(sumy)), day][]
</code>```

Body:
it might be that this is trivial, but I'm probably confused.

I have something like this:

set.seed(1234)

dt<-data.table(day=sample(c("day1","day2","day3"),20,replace = T),
store=sample(c("store1","store2","store3"),20,replace=T),
x=rnorm(20,33,6),y=rnorm(20,12,10))

I am interested in aggregating by day and store:

dt[,.(sumx=sum(x),sumy=sum(y)),by=c("day","store")]

    day  store      sumx     sumy
1: day1 store2  56.33890 44.52312
2: day2 store1 164.72854 61.37866
3: day3 store3 144.52483 53.74347
4: day1 store3  56.25504 34.00066
5: day3 store1  70.61311 30.85589
6: day2 store3 123.34534 74.67024
7: day2 store2  35.72952 21.19009

But also, more globally, by day only:

dt[,.(sumx=sum(x),sumy=sum(y)),by=day]

    day     sumx      sumy
1: day1 112.5939  78.52378
2: day2 323.8034 157.23899
3: day3 215.1379  84.59936

In practice, I would like to end up with a dataset that has aggregation per day and store, and an additional column with day only aggregation:

    day  store      sumx     sumy sumx_daylevel sumy_daylevel
1: day1 store2  56.33890 44.52312    112.5939    78.52378
2: day2 store1 164.72854 61.37866    323.8034    157.23899
3: day3 store3 144.52483 53.74347    215.1379    84.59936
4: day1 store3  56.25504 34.00066    112.5939    78.52378
5: day3 store1  70.61311 30.85589    215.1379    84.59936
6: day2 store3 123.34534 74.67024    323.8034    157.23899
7: day2 store2  35.72952 21.19009    323.8034    157.23899

I'd like to achieve that wrapping everything in a function, no merging.
Any help will be appreciated. Thank you

Body:
We can use := to create new columns

dt[,.(sumx=sum(x),sumy=sum(y)),by=c("day","store")
     ][, c("sumx_daylevel", "sumy_daylevel") := .(sum(sumx), sum(sumy)), day][]


问:
What is the difference between an attribute and a column?
The two terms "attribute" and "column" seems to be used interchangeably...but my guess is that a column is the box and an attribute is what goes into the box.</p>

答:
ActiveModel provides an attributes API for convenience which maps instance variables to a hash for ease of use. https://blog.metova.com/rails-5-attributes-api

ActiveRecord expands on ActiveModel to map columns onto attributes automatically, and you can still define custom attributes that do not have columns such as this good example.  http://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html

So in a standard Rails application, ActiveRecord models turn columns into attributes automatically and you can still add your own. You can also have additional ActiveModels that have their own mechanisms for persistence (or not) that use the same attributes API so standard Rails components can pretend it's like an ActiveRecord.


问:
Working example with ReliableSqlConnection and Azure
I have done everything i read on the internet, tutorials, but nothing seem to work!

https://www.google.com/search?q=reliablesqlconnection+azure

http://geekswithblogs.net/ScottKlein/archive/2012/01/27/understanding-sql-azure-throttling-and-implementing-retry-logic.aspx

i already install all the hand on lab:

http://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=6932

The NuGets

```<code>PM> Install-Package EnterpriseLibrary.WindowsAzure.TransientFaultHandling
PM> Install-Package CommonServiceLocator
</code>```

All the config I found to solve specific problems (just to mention one).

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <configSections>
  <section name="RetryPolicyConfiguration" type="Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling.Configuration.RetryPolicyConfigurationSettings, ... />
  <section name="typeRegistrationProvidersConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.TypeRegistrationProvidersConfigurationSection, Microsoft.Practices.EnterpriseLibrary.Common... />
 </configSections>
 <RetryPolicyConfiguration defaultRetryStrategy="Fixed Interval Retry Strategy">
  <incremental name="Incremental Retry Strategy" />
  <fixedInterval name="Fixed Interval Retry Strategy" />
  <exponentialBackoff name="Exponential Backoff Retry Strategy" />
 </RetryPolicyConfiguration>
 <typeRegistrationProvidersConfiguration>
  <add sectionName="RetryPolicyConfiguration" name="RetryPolicyConfiguration" />
 </typeRegistrationProvidersConfiguration>
</configuration>
</code>```

I cant get it work! I keep getting errors like

```<code>Could not load file or assembly 'Microsoft.Practices.ServiceLocation,
</code>```

OR

```<code>The type RetryManager cannot be constructed. You must configure the container to supply this value
</code>```

OR

```<code>Activation error occured while trying to get instance of type RetryManager, key "
</code>```

OR it keep looking for *.cs files when debugging!

And more and more!!

Is someone there! with a simple azure ReliableSqlConnection sample! that i can download and run?
Please! Preferable using the latest dlls?

Thanks.

This is one of my simple testing code in a new WinForm solution

I have tried many combinations! like

```<code>ReliableSqlconnection with ExecuteReader or
SqlConnection with ExecuteReaderWithRetry or
ReliableSqlconnection with ExecuteReaderWithRetry
</code>```

I just cant get it work! using SqlConnection with ExecuteReader, works perfect.! but is not reliable connection! so i will keep getting connection errors.

```<code>        using (var cnn = new ReliableSqlConnection(connString))
        {
            cnn.Open();
            using (var cmd = cnn.CreateCommand())
            {
                cmd.CommandText = "SELECT * FROM MyTable";
                using (var rdr = cmd.ExecuteReaderWithRetry())
                {
                    if (rdr.Read())
                    {
                        Console.Write(rdr.GetString(1));
                    }
                }
            }
        }
</code>```

答:
As of .NET 4.6.1 the SqlConnection class now has retrying built in.

Troubleshoot, diagnose, and prevent SQL connection errors and transient errors for SQL Database

.NET SqlConnection parameters for connection retry

If your client program connects to to Azure SQL Database by using the .NET Framework class System.Data.SqlClient.SqlConnection, you should use .NET 4.6.1 or later (or .NET Core) so you can leverage its connection retry feature. Details of the feature are here.

When you build the connection string for your SqlConnection object, you should coordinate the values among the following parameters:

  ConnectRetryCount   (Default is 1. Range is 0 through 255.)

  ConnectRetryInterval   (Default is 1 second. Range is 1 through 60.)

  Connection Timeout   (Default is 15 seconds. Range is 0 through 2147483647)

Specifically, your chosen values should make the following equality true:

  Connection Timeout = ConnectRetryCount * ConnectionRetryInterval

For example, if the count = 3, and interval = 10 seconds, a timeout of only 29 seconds would not quite give the system enough time for its 3rd and final retry at connecting: 29 < 3 * 10.

Body:
I have done everything i read on the internet, tutorials, but nothing seem to work!

https://www.google.com/search?q=reliablesqlconnection+azure

http://geekswithblogs.net/ScottKlein/archive/2012/01/27/understanding-sql-azure-throttling-and-implementing-retry-logic.aspx

i already install all the hand on lab:

http://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=6932

The NuGets

PM> Install-Package EnterpriseLibrary.WindowsAzure.TransientFaultHandling
PM> Install-Package CommonServiceLocator

All the config I found to solve specific problems (just to mention one).

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <configSections>

 </configSections>
 <RetryPolicyConfiguration defaultRetryStrategy="Fixed Interval Retry Strategy">
  <incremental name="Incremental Retry Strategy" />
  <fixedInterval name="Fixed Interval Retry Strategy" />
  <exponentialBackoff name="Exponential Backoff Retry Strategy" />
 </RetryPolicyConfiguration>
 <typeRegistrationProvidersConfiguration>
  <add sectionName="RetryPolicyConfiguration" name="RetryPolicyConfiguration" />
 </typeRegistrationProvidersConfiguration>
</configuration>

I cant get it work! I keep getting errors like

Could not load file or assembly 'Microsoft.Practices.ServiceLocation,

OR

The type RetryManager cannot be constructed. You must configure the container to supply this value

OR

Activation error occured while trying to get instance of type RetryManager, key "

OR it keep looking for *.cs files when debugging!

And more and more!!

Is someone there! with a simple azure ReliableSqlConnection sample! that i can download and run?
Please! Preferable using the latest dlls?

Thanks.

This is one of my simple testing code in a new WinForm solution

I have tried many combinations! like

ReliableSqlconnection with ExecuteReader or
SqlConnection with ExecuteReaderWithRetry or
ReliableSqlconnection with ExecuteReaderWithRetry

I just cant get it work! using SqlConnection with ExecuteReader, works perfect.! but is not reliable connection! so i will keep getting connection errors.

        using (var cnn = new ReliableSqlConnection(connString))
        {
            cnn.Open();
            using (var cmd = cnn.CreateCommand())
            {
                cmd.CommandText = "SELECT * FROM MyTable";
                using (var rdr = cmd.ExecuteReaderWithRetry())
                {
                    if (rdr.Read())
                    {
                        Console.Write(rdr.GetString(1));
                    }
                }
            }
        }


问:
How to change the parameters of getElementById in a loop
I am working on a form, and I would like to reset the lines individually without using reset.
How to vary the values of the attribute passed as parameter of the method getElementById in JavaScript using a loop?
 Here is an example of my source code below:</p>

```<code><script>
         var element = document.getElementById('#re');
    element.addEventListener('click', function() {
        document.getElementById("#id1").value = "";
        document.getElementById("#id2").value = "";
        document.getElementById("#id3").value = "";
    });
</script>
</code>```

答:
Assuming your IDs have the format shown in your example:

```<code>for (var i = 1; i <= 3; i++) {
  document.getElementById("id" + i).value = "";
}
</code>```

If that's not the case but you know the ID of every element you can put all IDs in an array and use that:

```<code>var elementIds = ["id1", "id2", "id3"];
elementIds.forEach(function(id) {
  document.getElementById(id).value = "";
});
</code>```

Another solution is to give all the elements you want to reset a specific class and target that:

```<code>var elements = document.getElementsByClassName("resetable-element");
[].slice.call(elements).forEach(function(element) {
  element.value = "";
});
</code>```

Body:
Assuming your IDs have the format shown in your example:

for (var i = 1; i <= 3; i++) {
  document.getElementById("id" + i).value = "";
}

If that's not the case but you know the ID of every element you can put all IDs in an array and use that:

var elementIds = ["id1", "id2", "id3"];
elementIds.forEach(function(id) {
  document.getElementById(id).value = "";
});

Another solution is to give all the elements you want to reset a specific class and target that:

var elements = document.getElementsByClassName("resetable-element");
[].slice.call(elements).forEach(function(element) {
  element.value = "";
});


问:
Vue JS router & updating route content dynamically
I am currently creating a client-side Vue JS app using Vue Router. To give you a bit of history, the app loads a json file stored on the server to display data. Periodically this file gets updated and I want to re-load the file and update the view.

Ignoring the fetching of the data file (this bit is fine), when I set up a new data fetch and update the data using a base Vue example, it works as expected.

However, when I introduce Vue Router, the visible updated data does not display. Doing a console.log with the results (and even the router/vue instance) reveals the new data changes, but the HTML does not update to reflect the change.

I'm using Vue 2 (which is fairly new) and all the documentation/examples point to updating the data on a page navigation & using Node (which I am not doing).

I've mocked up a simple JS bin with the basic process of what i'm doing. You can see in the newData array, the name and percentage of the first item changes.

http://jsbin.com/jeseden/edit?js,output

Any help is much appreciated.

答:
The correct way of doing this is actually with props.

This is all detailed in the blog post I wrote on the topic:

https://www.liquidlight.co.uk/blog/article/building-a-vue-v2-js-app-using-vue-router/

With an example being found on jsbin


答:
Try this one it works fine.

```<code>public Bitmap captureScreenShot(View view) {
/*
 * Creating a Bitmap of view with ARGB_4444.
 * */
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_4444);
    Canvas canvas = new Canvas(bitmap);
    Drawable backgroundDrawable = view.getBackground();
    if (backgroundDrawable != null) {
        backgroundDrawable.draw(canvas);
    } else {
        canvas.drawColor(Color.parseColor("#80000000"));
    }
    view.draw(canvas);
    return bitmap;
}
</code>```

You can pass any View to this function like RelativeLayout, LinearLayout, FrameLayout etc.

Now, Set up a Blur function.

```<code>    public static Bitmap blur(Context context, Bitmap image) {
    float BITMAP_SCALE = 0.4f;
    float BLUR_RADIUS = 7.5f;

    int width = Math.round(image.getWidth() * BITMAP_SCALE);
    int height = Math.round(image.getHeight() * BITMAP_SCALE);

    Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
    Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
    RenderScript rs = RenderScript.create(context);
    ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
    Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
    Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
    theIntrinsic.setRadius(BLUR_RADIUS);
    theIntrinsic.setInput(tmpIn);
    theIntrinsic.forEach(tmpOut);
    tmpOut.copyTo(outputBitmap);

    return outputBitmap;
}
</code>```

Thanks to Norman Peitek for this blur function.You can follow this link for more information regarding this blur function.

How to use this Function?

```<code>// relCustomDialog is the Parent object of RelativeLayout.
// relFullScreen is the Main Parent object of RelativeLayout.
relCustomDialog.setBackgroundDrawable(new BitmapDrawable(getResources(), blur
(MainActivity.this, captureScreenShot(relFullScreen))));
</code>```

You follow this link for full sourcecode .

Title: How can I blur the background of my layout?

Body:
I have tried most of the solutions from stack overflow, but I don't seem to get a correct implementation of the blurred effect.

Help me out please

Body:
Try this one it works fine.

public Bitmap captureScreenShot(View view) {
/*
 * Creating a Bitmap of view with ARGB_4444.
 * */
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_4444);
    Canvas canvas = new Canvas(bitmap);
    Drawable backgroundDrawable = view.getBackground();
    if (backgroundDrawable != null) {
        backgroundDrawable.draw(canvas);
    } else {
        canvas.drawColor(Color.parseColor("#80000000"));
    }
    view.draw(canvas);
    return bitmap;
}

You can pass any View to this function like RelativeLayout, LinearLayout, FrameLayout etc.

Now, Set up a Blur function.

    public static Bitmap blur(Context context, Bitmap image) {
    float BITMAP_SCALE = 0.4f;
    float BLUR_RADIUS = 7.5f;

    int width = Math.round(image.getWidth() * BITMAP_SCALE);
    int height = Math.round(image.getHeight() * BITMAP_SCALE);

    Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
    Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
    RenderScript rs = RenderScript.create(context);
    ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
    Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
    Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
    theIntrinsic.setRadius(BLUR_RADIUS);
    theIntrinsic.setInput(tmpIn);
    theIntrinsic.forEach(tmpOut);
    tmpOut.copyTo(outputBitmap);

    return outputBitmap;
}

Thanks to Norman Peitek for this blur function.You can follow this link for more information regarding this blur function.

How to use this Function?

// relCustomDialog is the Parent object of RelativeLayout.
// relFullScreen is the Main Parent object of RelativeLayout.
relCustomDialog.setBackgroundDrawable(new BitmapDrawable(getResources(), blur
(MainActivity.this, captureScreenShot(relFullScreen))));

You follow this link for full sourcecode .


问:
Limit iOS App even after the user re-installs it
I created an app that gives the user 3 coins at the first launch.

Once the user finished the 3 coins he should buy unlimited coins by an In-App purchase.

The problem is that if the user doesn't want to buy unlimited coins he can delete the app, install the app again and he will have again the 3 coins again.
And he can do this forever without ever buying the In-App purchase.

Is there a simple way to prevent this? How can I know if a user finished the coins inside the app even after deleting it?

答: One solution is to use Keychain storage of your device. But if user login to some other device then this problem will still exist. You can use iCloud keychain storage for this or store the necessary parameters on the server. Using iCloud keychain is very easy and reliable</p>


问:
how do i filter an javascript object and get the desired output as array?
```<code>[
  {imgUrl: "A"},
  {imgUrl: "B"},
  {imgUrl: "C", file: {fileName: "D"} }
]
</code>```

Desired output = ["A", "B", "D"];

答:
```<code>var obj=[
         {imgUrl: "A"},
         {imgUrl: "B"},
         {imgUrl: "C", file: {fileName: "D"} }
       ];
    var y=obj.map(function(z)
     {

      if(typeof(z.file) !== 'undefined')
       {
         return z.file.fileName;

       }
       else
       {
          return z.imgUrl;
       }
     });

 y is your desired array.
</code>```

Body:
[
  {imgUrl: "A"},
  {imgUrl: "B"},
  {imgUrl: "C", file: {fileName: "D"} }
]

Desired output = ["A", "B", "D"];


问:
Appending text while providing a stream and encoding, not a path
So I'm using a streamwriter which I feed a stream, not a path. I'm not able to use a path directly, because it must take into account a mocked filesystem.

The problem with this, is that the append bool is only an option if you provide a path, not a stream.

If I do this:

```<code>using (var writer = new StreamWriter(stream, encoding))
</code>```

then I can't set it to append instead of overwrite.

I've also tried to set it to the .AppendText() stream of the file, like this:

```<code>using (var writer = FileInfo.FromFileName(path).AppendText())
</code>```

This works, but the problem here is that I can't set the encoding, which I need to do. I've not found a way to set the encoding after it's been constructed.

So in essence, I need a way to be able to use a streamwriter to append text, while also taking into account that I have to feed it a stream, as well as an encoding. Anyone have an idea about what I can do?

答:
Just set the position of stream to the end before you create the StreamWriter.</p>

```<code>stream.Position = stream.Length;
</code>```

Body:
So I'm using a streamwriter which I feed a stream, not a path. I'm not able to use a path directly, because it must take into account a mocked filesystem.

The problem with this, is that the append bool is only an option if you provide a path, not a stream.

If I do this:

using (var writer = new StreamWriter(stream, encoding))

then I can't set it to append instead of overwrite.

I've also tried to set it to the .AppendText() stream of the file, like this:

using (var writer = FileInfo.FromFileName(path).AppendText())

This works, but the problem here is that I can't set the encoding, which I need to do. I've not found a way to set the encoding after it's been constructed.

So in essence, I need a way to be able to use a streamwriter to append text, while also taking into account that I have to feed it a stream, as well as an encoding. Anyone have an idea about what I can do?

Body:
Just set the position of stream to the end before you create the StreamWriter.

stream.Position = stream.Length;