问:
Lodash/JS - Convert _.find statement to _.forEach
I'm having trouble converting the following Lodash statement to something that works in an application that I inherited at work and am trying to fix bugs in. At the moment, we are having issues with only one device on our system returning when two devices have the same name and the following code seems to be the culprit as it would only return the first "true" value in an array:

```<code>var group = _.find(groupList, {id: id});
</code>```

How would I successfully convert this to a statement that iterates over all objects in an array and then returns those objects? I've tried the following options to no avail:

```<code> var group = _.filter(groupList, {id: id});
</code>```

and

```<code> var group = _.every(groupList, {id: id});
</code>```

and

```<code> var group = _.forEach(groupList, {id: id})
 return {id};
</code>```

I know I am probably missing something in my syntax. Any help would be much appreciated. Running Lodash v3.7.0

Here's the rest of the code in the directive in case anyone is interested or sees something else I might be missing:

```<code>define(['./../_module'], function (directives) {
'use strict';
directives.directive('dmGroupedList', ['$compile', '$state', 'APP_CONSTANTS', function ($compile, $state, APP_CONSTANTS) {
    return {
        restrict: 'A',
        scope: {
            items: '=',
            groupBy: '=',
            actions: '=',
            nonameGroupLabel: '='
        },
        templateUrl: function (elem, attrs) {
            return attrs.templateUrl || 'views/shared-templates/grouped-list.html';
        },
        link: function (scope, element, attrs) {
            scope.$watchGroup(['items', 'groupBy', 'nonameGroupLabel'], function () {
                scope.groupList = [];
                scope.groupedItems = {};

                var actions = scope.actions[scope.groupBy];

                _.forEach(scope.items, function (item) {
                    scope.handlers.getGroups(scope.groupList, item, scope.items, scope.groupBy, actions);
                });

                _.forEach(scope.groupList, function (group) {
                    var items = scope.groupedItems[group.id];
                    items = _.sortBy(items, function (item) {
                        return item.description;
                    });

                    scope.groupedItems[group.id] = items;
                });

                var groupsToSort = _.where(scope.groupList, {unassigned: false});
                var unassignedGroups = _.sortBy(_.where(scope.groupList, {unassigned: true}), 'name');
                scope.groupList = _.sortBy(groupsToSort, function (group) {
                    return group.name;
                });
                //adds unassigned groups to a new array via the javascript "push" method
                if (angular.isDefined(unassignedGroups)) {
                    for (var i = 0; i < unassignedGroups.length; i++) {
                        scope.groupList.push(unassignedGroups[i]);
                    }
                }
            });

            scope.handlers = {
                getGroups: function (groupList, item, items, groupBy, actions) {
                    var group = item[groupBy];

                    if (_.isEmpty(group)) {
                        scope.handlers.addGroupToList(groupList, APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE, items, groupBy, item, actions, scope);
                    }
                    else {
                        if (angular.isArray(group) || angular.isObject(group)) {
                            _.forEach(group, function (groupName) {
                                if (groupName == APP_CONSTANTS.ZERO) {
                                    scope.handlers.addGroupToList(groupList, APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE, items, groupBy, item, actions, scope);
                                    return;
                                }

                                scope.handlers.addGroupToList(groupList, groupName, items, groupBy, item, actions, scope);
                            })
                        } else {
                            scope.handlers.addGroupToList(groupList, group, items, groupBy, item, actions, scope);
                        }
                    }
                },
                addGroupToList: function (groupList, groupId, items, groupBy, item, handlers, scope) {
                    var id = _.camelCase(groupId);

                   var group = _.find(groupList, {id: id});
                    //var group = _.forEach(groupList, {id: id})
                    //return {id};

                    if (!group) {
                        var name = '';
                        var unassigned = false;
                        var link = null;

                        if (groupId == APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE || groupId == APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE_PARENT_ID) {
                            if (groupId == APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE_PARENT_ID) {
                                name = APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE;
                            } else {
                                name = APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.UNASSIGNED;
                            }

                            unassigned = true;
                        } else {
                            link = handlers.getGroupLink(groupId);
                            name = handlers.getGroupName(groupId, items);
                        }

                        group = {id: id, name: name, unassigned: unassigned, link: link};

                        groupList.push(group);
                    }

                    scope.groupedItems[group.id] = scope.groupedItems[group.id] || [];

                    if (angular.isDefined(handlers.processingGroup)) {
                        handlers.processingGroup(group, groupList, groupId, items, groupBy, item, handlers, scope);
                    } else {
                        scope.groupedItems[group.id].push({
                            description: handlers.getItemDescription(item),
                            link: handlers.getItemLink(item)
                        })
                    }
                }
            };
        }
    };
}]);
</code>```

});

答:
You can just use filter:

```<code>var group = groupList.filter((group) => group.id === id);
</code>```

EDIT: to return only the element, and not an array, when there is only one match, you can do the following:

```<code>var checkSingle = (groups) => groups.length === 1 ? groups[0] : groups;
var group = checkSingle(groupList.filter((group) => group.id === id));
</code>```

Body:
I'm having trouble converting the following Lodash statement to something that works in an application that I inherited at work and am trying to fix bugs in. At the moment, we are having issues with only one device on our system returning when two devices have the same name and the following code seems to be the culprit as it would only return the first "true" value in an array:

var group = _.find(groupList, {id: id});

How would I successfully convert this to a statement that iterates over all objects in an array and then returns those objects? I've tried the following options to no avail:

 var group = _.filter(groupList, {id: id});

and

 var group = _.every(groupList, {id: id});

and

 var group = _.forEach(groupList, {id: id})
 return {id};

I know I am probably missing something in my syntax. Any help would be much appreciated. Running Lodash v3.7.0

Here's the rest of the code in the directive in case anyone is interested or sees something else I might be missing:

define(['./../_module'], function (directives) {
'use strict';
directives.directive('dmGroupedList', ['$compile', '$state', 'APP_CONSTANTS', function ($compile, $state, APP_CONSTANTS) {
    return {
        restrict: 'A',
        scope: {
            items: '=',
            groupBy: '=',
            actions: '=',
            nonameGroupLabel: '='
        },
        templateUrl: function (elem, attrs) {
            return attrs.templateUrl || 'views/shared-templates/grouped-list.html';
        },
        link: function (scope, element, attrs) {
            scope.$watchGroup(['items', 'groupBy', 'nonameGroupLabel'], function () {
                scope.groupList = [];
                scope.groupedItems = {};

                var actions = scope.actions[scope.groupBy];

                _.forEach(scope.items, function (item) {
                    scope.handlers.getGroups(scope.groupList, item, scope.items, scope.groupBy, actions);
                });

                _.forEach(scope.groupList, function (group) {
                    var items = scope.groupedItems[group.id];
                    items = _.sortBy(items, function (item) {
                        return item.description;
                    });

                    scope.groupedItems[group.id] = items;
                });

                var groupsToSort = _.where(scope.groupList, {unassigned: false});
                var unassignedGroups = _.sortBy(_.where(scope.groupList, {unassigned: true}), 'name');
                scope.groupList = _.sortBy(groupsToSort, function (group) {
                    return group.name;
                });
                //adds unassigned groups to a new array via the javascript "push" method
                if (angular.isDefined(unassignedGroups)) {
                    for (var i = 0; i < unassignedGroups.length; i++) {
                        scope.groupList.push(unassignedGroups[i]);
                    }
                }
            });

            scope.handlers = {
                getGroups: function (groupList, item, items, groupBy, actions) {
                    var group = item[groupBy];

                    if (_.isEmpty(group)) {
                        scope.handlers.addGroupToList(groupList, APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE, items, groupBy, item, actions, scope);
                    }
                    else {
                        if (angular.isArray(group) || angular.isObject(group)) {
                            _.forEach(group, function (groupName) {
                                if (groupName == APP_CONSTANTS.ZERO) {
                                    scope.handlers.addGroupToList(groupList, APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE, items, groupBy, item, actions, scope);
                                    return;
                                }

                                scope.handlers.addGroupToList(groupList, groupName, items, groupBy, item, actions, scope);
                            })
                        } else {
                            scope.handlers.addGroupToList(groupList, group, items, groupBy, item, actions, scope);
                        }
                    }
                },
                addGroupToList: function (groupList, groupId, items, groupBy, item, handlers, scope) {
                    var id = _.camelCase(groupId);

                   var group = _.find(groupList, {id: id});
                    //var group = _.forEach(groupList, {id: id})
                    //return {id};

                    if (!group) {
                        var name = '';
                        var unassigned = false;
                        var link = null;

                        if (groupId == APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE || groupId == APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE_PARENT_ID) {
                            if (groupId == APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE_PARENT_ID) {
                                name = APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE;
                            } else {
                                name = APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.UNASSIGNED;
                            }

                            unassigned = true;
                        } else {
                            link = handlers.getGroupLink(groupId);
                            name = handlers.getGroupName(groupId, items);
                        }

                        group = {id: id, name: name, unassigned: unassigned, link: link};

                        groupList.push(group);
                    }

                    scope.groupedItems[group.id] = scope.groupedItems[group.id] || [];

                    if (angular.isDefined(handlers.processingGroup)) {
                        handlers.processingGroup(group, groupList, groupId, items, groupBy, item, handlers, scope);
                    } else {
                        scope.groupedItems[group.id].push({
                            description: handlers.getItemDescription(item),
                            link: handlers.getItemLink(item)
                        })
                    }
                }
            };
        }
    };
}]);

});

Body:
You can just use filter:

var group = groupList.filter((group) => group.id === id);

EDIT: to return only the element, and not an array, when there is only one match, you can do the following:

var checkSingle = (groups) => groups.length === 1 ? groups[0] : groups;
var group = checkSingle(groupList.filter((group) => group.id === id));


来源: stackexchange

问:
Redirecting stderr to multiple streams
I'm trying to understand how a part of a Bash script works. Relevant code is:

sqlprogram -f $filename.sql > $date.log 2>&1

It looks like if there's no error with the sqlprogram -f $filename.sql part, then the contents of stdout are written to $date.log but if there is an error, then stderr is written to $date.log. So basically, one of stderr and stdout is written to $date.log. Is that correct?

How do I redirect stderr to another file as well, say $errorlog.file? I've tried playing around with tee but struggled for a bit

答:
> redirect standard output, 2>&1 redirects standard error to standard output. All the output (regardless of whether there's an error or not) goes to the file specified, as well as anything normally printed to stderr - usually errors, but some programs also output warnings, diagnostic messages, or debugging information to stderr.

If you want to save stderr to a different file, use

```<code>program > $date.log 2> different-file
</code>```

To save stderr to both the file where stdout goes and a different one, use

```<code>program > log 2> >(tee different-file >&1)
</code>```

To save stdout to a file and output stderr to itself and a different file, use

```<code>program > log 2> >(tee different-file >&2)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Redirecting stderr to multiple streams

Body:
> redirect standard output, 2>&1 redirects standard error to standard output. All the output (regardless of whether there's an error or not) goes to the file specified, as well as anything normally printed to stderr - usually errors, but some programs also output warnings, diagnostic messages, or debugging information to stderr.

If you want to save stderr to a different file, use

program > $date.log 2> different-file

To save stderr to both the file where stdout goes and a different one, use

program > log 2> >(tee different-file >&1)

To save stdout to a file and output stderr to itself and a different file, use

program > log 2> >(tee different-file >&2)


问:
random numbers after a ? on an image is this for far expires headers?
I was pooking around a random site on the internet and noticed that on the images they have numbers prefixing it: icons-16.png?1292032550

I've heard of people optimising websites with far expires headers. If someone changes the content that doesn't change very often, the cache won't get refreshed. Ergo this new image won't get re-downloaded to someones cache. Because the filename has to change.

答: Yes. One way to get around caches is to append an otherwise inconsequential query parameter, such as a time stamp, to a URL.</p>

ContentLicense: CC BY-SA 2.5


问:
How to transfer blame from a deleted file to it's replacement?
I started with the file OldController.php and converted it to NewController.php. Here's my workflow:

Commit: Delete OldController.php and create NewController.php

Amend: Do some work on NewController.php

Amend: Do more work on NewController.php

(Pretty sure the amends hold no relevance, but figured I'd mention them anyways.)

So, how do I take the history of OldController.php and point it to NewController.php?

I know I can just go back and do this manually, but I'd like to know how to do this within mercurial.

答:
Update back to the last revision where OldController.php still existed. At that point, use hg mv to effectively rename it to NewController.php. Commit that rename. This creates a new head.

At that point you have a few options:

Merge the commit you just made with the other head which already had NewController.php

Rebase everything starting with the first commit to include NewController.php onto the new head you just created.

Either way would be effective, but it depends on whether you want to preserve the history of this change, or you're OK just to make it look like you had renamed it from the get-go.


问:
Removing duplicate values over multiple columns sql server
I created a small app at work for my personal use that displays information based city lookups. I am running into and issue where some data is duplicated because the same values can be in any of 3 columns.

Example Query

```<code>SqlCommand cmd6 = new SqlCommand("SELECT Distinct County1, County2, County3 from table where StateId=" + "'" + State + "'" + " AND City=" + "'" + City + "'", con);
using (SqlDataReader rdr = cmd6.ExecuteReader())
        {
            while (rdr.Read())
            {
                this.County.Text += rdr["County1"].ToString() + " ";
                this.County.Text += rdr["County2"].ToString()+ " ";
                this.County.Text += rdr["County3"].ToString() + " ";
            }
        }

        con.Close();
</code>```

Output: for Auburn, Alabama

```<code> CHAMBERS CHAMBERS CHAMBERS LEE CHAMBERS LEE LEE
</code>```

Chambers and Lee can be in either County1, County2 based on how they were entered into the DB. Instead of starting from scratch, I am wondering if it is possible to check for duplicates in the SQL statement prior to putting it into the string. Maybe display the unique values between the 3 columns when the columns are compared? Thanks everyone!

答:
Would putting the values in one column work?</p>

```<code>select Distinct v.county
from table t cross apply
     (values (t.county1), (t.county2), (t.county3)) v(county)
where v.county is not null and
      StateId=" + "'" + State + "'" + " AND City=" + "'" + City + "'",
</code>```

Body:
I created a small app at work for my personal use that displays information based city lookups. I am running into and issue where some data is duplicated because the same values can be in any of 3 columns.

Example Query

SqlCommand cmd6 = new SqlCommand("SELECT Distinct County1, County2, County3 from table where StateId=" + "'" + State + "'" + " AND City=" + "'" + City + "'", con);
using (SqlDataReader rdr = cmd6.ExecuteReader())
        {
            while (rdr.Read())
            {
                this.County.Text += rdr["County1"].ToString() + " ";
                this.County.Text += rdr["County2"].ToString()+ " ";
                this.County.Text += rdr["County3"].ToString() + " ";
            }
        }

        con.Close();

Output: for Auburn, Alabama

 CHAMBERS CHAMBERS CHAMBERS LEE CHAMBERS LEE LEE

Chambers and Lee can be in either County1, County2 based on how they were entered into the DB. Instead of starting from scratch, I am wondering if it is possible to check for duplicates in the SQL statement prior to putting it into the string. Maybe display the unique values between the 3 columns when the columns are compared? Thanks everyone!

Body:
Would putting the values in one column work?

select Distinct v.county
from table t cross apply
     (values (t.county1), (t.county2), (t.county3)) v(county)
where v.county is not null and
      StateId=" + "'" + State + "'" + " AND City=" + "'" + City + "'",


问:
Mocking ActionContext.getContext().getSession() returns null
I am trying to write jUnit test case for following method.

```<code>public class MyClass {

  public static Map<String, Object> getSession() {
    Map<String, Object> session = ActionContext.getContext().getSession();
    return session;
  }
}
</code>```

I followed this question and also this question and tried to  mock ActionContext. But still session is null.

```<code>    public class TestClass {

        private HttpServletRequest request;
        private HttpSession session;

        @Before
        public void setUp() {
            // mock the session
            session = mock(HttpSession.class);
            // mock the request
            request = mock(HttpServletRequest);
            when(request.getSession()).thenReturn(session);

            // set the context
            Map<String, Object> contextMap = new HashMap<String, Object>();
            contextMap.put(StrutsStatics.HTTP_REQUEST, request);
            ActionContext.setContext(new ActionContext(contextMap));
        }

        @After
        public void destroyTests() {
           ActionContext.setContext(null);
        }

@Test
    public void testGetSession() {
        Map<String, Object> session =MyClass.getSession();
        //session is null here

    }

}
</code>```

Is there something I am doing wrong here ?

答:
Add the following code to the context map, since it's empty context created you should set the session into action context.</p>

```<code>contextMap.put(ActionContext.SESSION, new SessionMap(request));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to write jUnit test case for following method.

public class MyClass {

  public static Map<String, Object> getSession() {
    Map<String, Object> session = ActionContext.getContext().getSession();
    return session;
  }
}

I followed this question and also this question and tried to  mock ActionContext. But still session is null.

    public class TestClass {

        private HttpServletRequest request;
        private HttpSession session;

        @Before
        public void setUp() {
            // mock the session
            session = mock(HttpSession.class);
            // mock the request
            request = mock(HttpServletRequest);
            when(request.getSession()).thenReturn(session);

            // set the context
            Map<String, Object> contextMap = new HashMap<String, Object>();
            contextMap.put(StrutsStatics.HTTP_REQUEST, request);
            ActionContext.setContext(new ActionContext(contextMap));
        }

        @After
        public void destroyTests() {
           ActionContext.setContext(null);
        }

@Test
    public void testGetSession() {
        Map<String, Object> session =MyClass.getSession();
        //session is null here

    }

}

Is there something I am doing wrong here ?

Body:
Add the following code to the context map, since it's empty context created you should set the session into action context.

contextMap.put(ActionContext.SESSION, new SessionMap(request));


问:
Angular Material 2 - Trigger change event in md-checkbox in a Unit Test
I am having problems triggering a 'change' event for a md-checkbox in an Angular Unit Test, using the test framework setup provided by the Angular CLI.

I have a simple component:

ts:

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  checkedValue = 'false';

  result = false;

  checkValueChange(event) {
    console.log('CheckBox clicked: ' + event.checked);
    this.result = true;
  }
}
</code>```

template:

```<code><md-checkbox [checked]="true" [(ngModel)]="checkedValue" (change)="checkValueChange($event)">Check Box</md-checkbox>
</code>```

And here is the unit test code I am trying to cause the change event to be emitted - via a simulated click:

test code:

```<code>import {TestBed, async, fakeAsync} from '@angular/core/testing';
import { AppComponent } from './app.component';
import {DebugElement} from '@angular/core';
import {By} from '@angular/platform-browser';
import {MaterialModule} from '@angular/material';
import {FormsModule} from '@angular/forms';
import {tick} from '@angular/core/testing';

let de:      DebugElement;
let el:      HTMLElement;

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      imports: [MaterialModule, FormsModule]
    }).compileComponents();
  }));

  it('should create the app', fakeAsync(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;

    de = fixture.debugElement.query(By.css('md-checkbox'));
    el = de.nativeElement;

    // Neither click appears to trigger the change event to occur, or update the model
    de.triggerEventHandler('click', {});
    el.click();

    tick(100);
    expect(app.result).toBe(true);
  }));
});
</code>```

So maybe trying to get the change event to trigger via a click is incorrect? Anyone got any ideas?

Thanks.

答:
The handle is not in the md-checkbox but in its label element

```<code>de = fixture.debugElement.query(By.css('md-checkbox label'));
el = de.nativeElement;
el.click();
</code>```

should do the trick

You can also import only MdCheckboxModule instead of MaterialModule.

Body:
I am having problems triggering a 'change' event for a md-checkbox in an Angular Unit Test, using the test framework setup provided by the Angular CLI.

I have a simple component:

ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  checkedValue = 'false';

  result = false;

  checkValueChange(event) {
    console.log('CheckBox clicked: ' + event.checked);
    this.result = true;
  }
}

template:

<md-checkbox [checked]="true" [(ngModel)]="checkedValue" (change)="checkValueChange($event)">Check Box</md-checkbox>

And here is the unit test code I am trying to cause the change event to be emitted - via a simulated click:

test code:

import {TestBed, async, fakeAsync} from '@angular/core/testing';
import { AppComponent } from './app.component';
import {DebugElement} from '@angular/core';
import {By} from '@angular/platform-browser';
import {MaterialModule} from '@angular/material';
import {FormsModule} from '@angular/forms';
import {tick} from '@angular/core/testing';

let de:      DebugElement;
let el:      HTMLElement;

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      imports: [MaterialModule, FormsModule]
    }).compileComponents();
  }));

  it('should create the app', fakeAsync(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;

    de = fixture.debugElement.query(By.css('md-checkbox'));
    el = de.nativeElement;

    // Neither click appears to trigger the change event to occur, or update the model
    de.triggerEventHandler('click', {});
    el.click();

    tick(100);
    expect(app.result).toBe(true);
  }));
});

So maybe trying to get the change event to trigger via a click is incorrect? Anyone got any ideas?

Thanks.

Body:
The handle is not in the md-checkbox but in its label element

de = fixture.debugElement.query(By.css('md-checkbox label'));
el = de.nativeElement;
el.click();

should do the trick

You can also import only MdCheckboxModule instead of MaterialModule.


问:
Rails, collection_select - remembering values with :selected after form submitted
(Using Rails 2.3.5 on an internal work server with no choice of versions, and I'm pretty new)

I'm building a search form where I need to provide a list of directories to a user so they can select which one(s) to search against.   I'm trying to figure out how to get the selected values of a collection_select to remain after the form is submitted.

Say the user selected 3 directories from the collection_select, the id's of those directories would look like this in the params:

```<code>directory: !map:HashWithIndifferentAccess
  id:
  - "2"
  - "4"
  - "6"
</code>```

I know that you can manually specify multiple selected items:

```<code><%= collection_select :directory, :id, @directories, :id, :name,
                 {:selected => [2,4,6]}, {:size => 5, :multiple => true} %>
</code>```

I've also played around a bit and was able to us "to_i" against a single value in the params hash:

```<code><%= collection_select :directory, :id, @directories, :id, :name,
                 {:selected => params[:directory][:id][0].to_i}, {:size => 5, :multiple => true} %>
</code>```

What I can't figure out is how to use all of the values of the :directory params at the same time so what the user selected remains after the form is submitted.   Thanks for any help.

答:
I'm not precisely sure what you're asking, but if you're trying to get the array of strings in params[:directory][:id] as an array of integers, all you need is

```<code>params[:directory][:id].map{|id|id.to_i}
</code>```

Body:
(Using Rails 2.3.5 on an internal work server with no choice of versions, and I'm pretty new)

I'm building a search form where I need to provide a list of directories to a user so they can select which one(s) to search against.   I'm trying to figure out how to get the selected values of a collection_select to remain after the form is submitted.

Say the user selected 3 directories from the collection_select, the id's of those directories would look like this in the params:

directory: !map:HashWithIndifferentAccess
  id:
  - "2"
  - "4"
  - "6"

I know that you can manually specify multiple selected items:

<%= collection_select :directory, :id, @directories, :id, :name,
                 {:selected => [2,4,6]}, {:size => 5, :multiple => true} %>

I've also played around a bit and was able to us "to_i" against a single value in the params hash:

<%= collection_select :directory, :id, @directories, :id, :name,
                 {:selected => params[:directory][:id][0].to_i}, {:size => 5, :multiple => true} %>

What I can't figure out is how to use all of the values of the :directory params at the same time so what the user selected remains after the form is submitted.   Thanks for any help.

Body:
I'm not precisely sure what you're asking, but if you're trying to get the array of strings in params[:directory][:id] as an array of integers, all you need is

params[:directory][:id].map{|id|id.to_i}


问:
To Filter json data
In the below code i have two jsons which i have to filter json based on json data/value.

Master Json:

```<code>    var set1 =[{"LevelID":"1","levelname":"Level1",,"levelType":"TypeA"},
    {"LevelID":"2","levelname":"Level2",,"levelType":"TypeB"},
    {"LevelID":"3","levelname":"Level3",,"levelType":"TypeC"},
    {"LevelID":"4","levelname":"Level4",,"levelType":"TypeD"}
    ];
</code>```

Data Json:

```<code>    var set2 =[{"LevelID":"1"},{"LevelID":"2"}];

    var Commaseparated="TypeA","TypeD";
</code>```

Here i want to pass Data json and commaseparated to Master json and filter and get the filtered data that should match with levelID and Commaseparated.

Expected result:

```<code>    var set3 =[{"LevelID":"1","levelname":"Level1","levelType":"TypeA"}];
</code>```

答:
Probably not the best way, but here's one way you could start going that direction.

var master = [{"LevelID":"1","levelname":"Level1","levelType":"TypeA"},
    {"LevelID":"2","levelname":"Level2","levelType":"TypeB"},
    {"LevelID":"3","levelname":"Level3","levelType":"TypeC"},
    {"LevelID":"4","levelname":"Level4","levelType":"TypeD"}
    ];

var set2 = [{
  "LevelID": "1"
}, {
  "LevelID": "2"
}];

var Commaseparated = ["TypeA", "TypeD"];

const set3 = master.filter(item => {
  return set2.find(item2 => item.LevelID === item2.LevelID)
}).filter(exclude => Commaseparated.indexOf(exclude.levelType) > -1);

/*
const set3 = set2.map(item => {
  item.levelname = Commaseparated[item.LevelID - 1];
  return item;
});
*/

console.log(set3);```

Title: To Filter json data

Body:
In the below code i have two jsons which i have to filter json based on json data/value.

Master Json:

    var set1 =[{"LevelID":"1","levelname":"Level1",,"levelType":"TypeA"},
    {"LevelID":"2","levelname":"Level2",,"levelType":"TypeB"},
    {"LevelID":"3","levelname":"Level3",,"levelType":"TypeC"},
    {"LevelID":"4","levelname":"Level4",,"levelType":"TypeD"}
    ];

Data Json:

    var set2 =[{"LevelID":"1"},{"LevelID":"2"}];

    var Commaseparated="TypeA","TypeD";

Here i want to pass Data json and commaseparated to Master json and filter and get the filtered data that should match with levelID and Commaseparated.

Expected result:

    var set3 =[{"LevelID":"1","levelname":"Level1","levelType":"TypeA"}];


问:
Netbeans 8.1 on Debian 9 no plugins available
I've just installed Debian 9 and NetBeans 8.1. I use to work with this setup so I'm familiarized with it. But now, my NetBeans is not detecting any 'available plugins' (it just come with the basics, but I need PHP support, in addition to typescript and more stuff).

I have a working Internet connection

In 'settings' -> 'proxy settings', 'use system proxy settings' is checked, furthermore when I click on 'Test connection' it shows the green check.

At '~/.netbeans/8.1/var/log/.log' it looks like there is no error showing.

I have ran NetBeans with root privileges and same happens.

Something strange is that, when I click 'Check for newest', it "checks" so quick (double quote because I doubt it does anything).

Any ideas?

答:
Netbeans 7 hides most plugins by default.

From Tools (Menu) -> Plugins (Menu) -> Settings (Tab)
Certified Plugins - http://updates.netbeans.org/netbeans/updates/7.0.1/uc/final/certified/catalog.xml.gz

Plugin Portal - http://plugins.netbeans.org/nbpluginportal/updates/7.0/catalog.xml.gz
and NetBeans Distribution

and make sure each of them is checked. If these are not present or not checked, you will not see anything in the list of Available Plugins (tab). Make sure you Reload Catalog on the Available Plugins tab after adding these.


问:
Google App Engine, define a Preprocessing class

I am trying to define a base request handling class so that the webapp pages may inherit some basic methods and variable which otherwise would be required to be repeatedly be defined for each page of the application. A sort of similar functionality like django preprocessors.  This is my base class from which other pages inherit:

```<code>class BasePage(webapp.RequestHandler):
    def __init__(self):
        self.user = users.get_current_user()
        self.template_values = {
                'user': self.user,
                'environ': self,   #I don't like the idea of passing the whole environ object to a template

                ##The below three functions cannot be executed during _init_ because of absence of self.request
                #'openid_providers': self.openid_providers(),
                #'logout_url': self.get_logout_url(),
                #'request': self.get_request(),
            }

    ##A sort of similar functionality like render_to_response in django
    def render_template(self, template_name, values = None, *args, **kwargs):
        #PATH is the directory containing the templates
        if values:
            for value in values:  self.template_values[value] = values[value]
        self.response.out.write(template.render(PATH+template_name, self.template_values, *args, **kwargs))

    ##Returns request as the name suggests
    def logout_url(self):
        return users.create_logout_url(self.request.url)

    ##Returns request as the name suggests
    def request(self):
        return request

    ##Returns openid login urls
    def openid_providers(self):
        #OPENID_POVIDERS  is a list of dictionary
        for p in OPENID_PROVIDERS:
             p['login_url'] = users.create_login_url(self.request.get('next', '/') , p['name'], p['url'])
        return OPENID_PROVIDERS
</code>```

Everything is working fine except that I cannot pass some variables during initialization as self.request is not available. So for a workaround what I did is pass on whole self variable as a template variable.

Is there some other way to provide the template variables (request, logout_url etc) to the templates?

答:
A much simpler solution than bgporter's is to do the common setup in the initialize method of webapp.RequestHandler.  Here's an example from work, where we wanted to add a Django-like is_ajax method to the request object:

```<code>class BaseHandler(webapp.RequestHandler):
    def initialize(self, request, response):
        super(BaseHandler, self).initialize(request, response)
        # Add a Django-like is_ajax() method to the request object
        request.is_ajax = lambda: \
            request.environ.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
</code>```

This method is called to, uh, initialize each request handler with the current request and response objects, before the appropriate get or post (or whatever) methods are called.

Body:
I am trying to define a base request handling class so that the webapp pages may inherit some basic methods and variable which otherwise would be required to be repeatedly be defined for each page of the application. A sort of similar functionality like django preprocessors.  This is my base class from which other pages inherit:

class BasePage(webapp.RequestHandler):
    def __init__(self):
        self.user = users.get_current_user()
        self.template_values = {
                'user': self.user,
                'environ': self,   #I don't like the idea of passing the whole environ object to a template

                ##The below three functions cannot be executed during _init_ because of absence of self.request
                #'openid_providers': self.openid_providers(),
                #'logout_url': self.get_logout_url(),
                #'request': self.get_request(),
            }

    ##A sort of similar functionality like render_to_response in django
    def render_template(self, template_name, values = None, *args, **kwargs):
        #PATH is the directory containing the templates
        if values:
            for value in values:  self.template_values[value] = values[value]
        self.response.out.write(template.render(PATH+template_name, self.template_values, *args, **kwargs))

    ##Returns request as the name suggests
    def logout_url(self):
        return users.create_logout_url(self.request.url)

    ##Returns request as the name suggests
    def request(self):
        return request

    ##Returns openid login urls
    def openid_providers(self):
        #OPENID_POVIDERS  is a list of dictionary
        for p in OPENID_PROVIDERS:
             p['login_url'] = users.create_login_url(self.request.get('next', '/') , p['name'], p['url'])
        return OPENID_PROVIDERS

Everything is working fine except that I cannot pass some variables during initialization as self.request is not available. So for a workaround what I did is pass on whole self variable as a template variable.

Is there some other way to provide the template variables (request, logout_url etc) to the templates?

Body:
A much simpler solution than bgporter's is to do the common setup in the initialize method of webapp.RequestHandler.  Here's an example from work, where we wanted to add a Django-like is_ajax method to the request object:

class BaseHandler(webapp.RequestHandler):
    def initialize(self, request, response):
        super(BaseHandler, self).initialize(request, response)
        # Add a Django-like is_ajax() method to the request object
        request.is_ajax = lambda: \
            request.environ.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'

This method is called to, uh, initialize each request handler with the current request and response objects, before the appropriate get or post (or whatever) methods are called.


问:
How to hash a single char to a relatively small prime in C++?
I am interested in hashing the alphabet letters to different prime numbers which are relatively small. For example,  a->2,b->3, c->5, d->7, .... Since I will be multiplying/dividing hashes of several characters.

I tried std::hash, however, it hashes characters to very large integers and it causes overflows if I multiply/divide, is there an easier way to do this?

One possible way I though of is to use the Sieve of Eratosthenes to generate the first bunch of primes then use a std::unordered_map to store char,int pairs. However, is there any ready made hashing function in the standard library that would suit my needs?

答: I would just store the first 26 primes in a std::vector called primes, and then if you have character c, simply access the correct prime using primes[c-'a'].


问:
Nightwatch - button click using button text name
Is there any way to click the button using button text?

Button 1
Button 2
Button 3
Button 4

I currently use :nth-of-type to locate them but I'm looking for something more readable. (Xpath also not very readable).

The other option I'm thinking about, to use page objects and move not readable selector there.

答:
You can configure them as buttons. Then style them as text using CSS.</p>

```<code><html>
<head>
<style>
.astext {
    background:none;
    border:none;
    margin:0;
    padding:0;
}
</style>
</head>
<body>
<button class="astext"><span>Button 1</span></button>
<button class="astext"><span>Button 2</span></button>
<button class="astext"><span>Button 3</span></button>
<button class="astext"><span>Button 4</span></button>
</body>
</html>
</code>```

Body:
You can configure them as buttons. Then style them as text using CSS.

<html>
<head>
<style>
.astext {
    background:none;
    border:none;
    margin:0;
    padding:0;
}
</style>
</head>
<body>
<button class="astext"><span>Button 1</span></button>
<button class="astext"><span>Button 2</span></button>
<button class="astext"><span>Button 3</span></button>
<button class="astext"><span>Button 4</span></button>
</body>
</html>


问:
Extract string between nth and ith instance of delimiter
I have a vector of strings, similar to this one, but with many more elements:

```<code>s <- c("CGA-DV-558_T_90.67.0_DV_1541_07", "TC-V-576_T_90.0_DV_151_0", "TCA-DV-X_T_6.0_D_A2_07", "T-V-Z_T_2_D_A_0", "CGA-DV-AW0_T.1_24.4.0_V_A6_7", "ACGA-DV-A4W0_T_274.46.0_DV_A266_07")
</code>```

And I would like to use a function that extracts the string between the nth and ith instances of the delimiter "_". For example, the string between the 2nd (n = 2) and 3rd (i = 3) instances, to get this:

```<code>[1] "90.67.0"  "90.0"     "6.0"      "2"        "24.4.0"   "274.46.0"
</code>```

Or if n = 4 and i = 5"

```<code>[1] "1541" "151"  "A2"   "A"    "A"    "A266"
</code>```

Any suggestions?

答:
A third method, that uses substring for the extraction and gregexpr to find the positions is

```<code># extract postions of "_" from each vector element, returns a list
spots <- gregexpr("_", s, fixed=TRUE)

# extract text in between third and fifth underscores
substring(s, sapply(spots, "[", 3) + 1, sapply(spots, "[", 5) - 1)
"DV_1541" "DV_151"  "D_A2"    "D_A"     "V_A6"    "DV_A266"
</code>```

Body:
I have a vector of strings, similar to this one, but with many more elements:

s <- c("CGA-DV-558_T_90.67.0_DV_1541_07", "TC-V-576_T_90.0_DV_151_0", "TCA-DV-X_T_6.0_D_A2_07", "T-V-Z_T_2_D_A_0", "CGA-DV-AW0_T.1_24.4.0_V_A6_7", "ACGA-DV-A4W0_T_274.46.0_DV_A266_07")

And I would like to use a function that extracts the string between the nth and ith instances of the delimiter "_". For example, the string between the 2nd (n = 2) and 3rd (i = 3) instances, to get this:

[1] "90.67.0"  "90.0"     "6.0"      "2"        "24.4.0"   "274.46.0"

Or if n = 4 and i = 5"

[1] "1541" "151"  "A2"   "A"    "A"    "A266"

Any suggestions?

Body:
A third method, that uses substring for the extraction and gregexpr to find the positions is

# extract postions of "_" from each vector element, returns a list
spots <- gregexpr("_", s, fixed=TRUE)

# extract text in between third and fifth underscores
substring(s, sapply(spots, "[", 3) + 1, sapply(spots, "[", 5) - 1)
"DV_1541" "DV_151"  "D_A2"    "D_A"     "V_A6"    "DV_A266"


问:
Bash process substitution and syncing
(Possibly related to Do some programs not accept process substitution for input files?)

In some Bash unit test scripts I'm using the following trick to log and display stdout and stderr of a command:

```<code>command > >(tee "${stdoutF}") 2> >(tee "${stderrF}" >&2)
</code>```

This process produces some output to stdout, so the $stdoutF file gets some data. Then I run another command which does not output any data:

```<code>diff -r "$source" "$target" > >(tee "${stdoutF}") 2> >(tee "${stderrF}" >&2)
</code>```

However, it doesn't look like this process always finishes successfully before the test for emptiness is run (using shunit-ng):

```<code>assertNull 'Unexpected output to stdout' "$(<"$stdoutF")"
</code>```

In a 100 run test this failed 25 times.

Should it be sufficient to call sync before testing the file for emptiness:

```<code>sync
assertNull 'Unexpected output to stdout' "$(<"$stdoutF")"
</code>```

... and/or should it work by forcing the sequence of the commands:

```<code>diff -r "$source" "$target" \
> >(tee "${stdoutF}"; assertNull 'Unexpected output to stdout' "$(<"$stdoutF")")
2> >(tee "${stderrF}" >&2)
</code>```

... and/or is it possible to tee it somehow to assertNull directly instead of a file?

Update: sync is not the answer - See Gilles' response below.

Update 2: Discussion taken further to Save stdout, stderr and stdout+stderr synchronously. Thanks for the answers!

答:
In bash, a process substitution substitution command foo > >(bar) finishes as soon as foo finishes. (This is not discussed in the documentation.) You can check this with

```<code>: > >(sleep 1; echo a)
</code>```

This command returns immediately, then prints a asynchronously one second later.

In your case, the tee command takes just one little bit of time to finish after command completes. Adding sync gave tee enough time to complete, but this doesn't remove the race condition, any more than adding a sleep would, it just makes the race more unlikely to manifest.

More generally, sync does not have any internally observable effect: it only makes a difference if you want to access device where your filesystems are stored under a different operating system instance. In clearer terms, if your system loses power, only data written before the last sync is guaranteed to be available after you reboot.

As for removing the race condition, here are a few of possible approaches:

Explicitly synchronize all substituted processes.

```<code>mkfifo sync.pipe
command > >(tee -- "$stdoutF"; echo >sync.pipe)
       2> >(tee -- "$stderrF"; echo >sync.pipe)
read line < sync.pipe; read line < sync.pipe
</code>```

Use a different temporary file name for each command instead of reusing $stdoutF and $stderrF, and enforce that the temporary file is always newly created.

Give up on process substitution and use pipes instead.

```<code>{ { command | tee -- "$stdoutF" 1>&3; } 2>&1 \
            | tee -- "$stderrF" 1>&2; } 3>&1
</code>```

If you need the command's return status, bash puts it in ${PIPESTATUS[0]}.

```<code>{ { command | tee -- "$stdoutF" 1>&3; exit ${PIPESTATUS[0]}; } 2>&1 \
            | tee -- "$stderrF" 1>&2; } 3>&1
if [ ${PIPESTATUS[0]} -ne 0 ]; then echo command failed; fi
</code>```

Title: Bash process substitution and syncing

Body:
(Possibly related to Do some programs not accept process substitution for input files?)

In some Bash unit test scripts I'm using the following trick to log and display stdout and stderr of a command:

command > >(tee "${stdoutF}") 2> >(tee "${stderrF}" >&2)

This process produces some output to stdout, so the $stdoutF file gets some data. Then I run another command which does not output any data:

diff -r "$source" "$target" > >(tee "${stdoutF}") 2> >(tee "${stderrF}" >&2)

However, it doesn't look like this process always finishes successfully before the test for emptiness is run (using shunit-ng):

assertNull 'Unexpected output to stdout' "$(<"$stdoutF")"

In a 100 run test this failed 25 times.

Should it be sufficient to call sync before testing the file for emptiness:

sync
assertNull 'Unexpected output to stdout' "$(<"$stdoutF")"

... and/or should it work by forcing the sequence of the commands:

diff -r "$source" "$target" \
> >(tee "${stdoutF}"; assertNull 'Unexpected output to stdout' "$(<"$stdoutF")")
2> >(tee "${stderrF}" >&2)

... and/or is it possible to tee it somehow to assertNull directly instead of a file?

Update: sync is not the answer - See Gilles' response below.

Update 2: Discussion taken further to Save stdout, stderr and stdout+stderr synchronously. Thanks for the answers!

Body:
In bash, a process substitution substitution command foo > >(bar) finishes as soon as foo finishes. (This is not discussed in the documentation.) You can check this with

: > >(sleep 1; echo a)

This command returns immediately, then prints a asynchronously one second later.

In your case, the tee command takes just one little bit of time to finish after command completes. Adding sync gave tee enough time to complete, but this doesn't remove the race condition, any more than adding a sleep would, it just makes the race more unlikely to manifest.

More generally, sync does not have any internally observable effect: it only makes a difference if you want to access device where your filesystems are stored under a different operating system instance. In clearer terms, if your system loses power, only data written before the last sync is guaranteed to be available after you reboot.

As for removing the race condition, here are a few of possible approaches:

Explicitly synchronize all substituted processes.

mkfifo sync.pipe
command > >(tee -- "$stdoutF"; echo >sync.pipe)
       2> >(tee -- "$stderrF"; echo >sync.pipe)
read line < sync.pipe; read line < sync.pipe

Use a different temporary file name for each command instead of reusing $stdoutF and $stderrF, and enforce that the temporary file is always newly created.

Give up on process substitution and use pipes instead.

{ { command | tee -- "$stdoutF" 1>&3; } 2>&1 \
            | tee -- "$stderrF" 1>&2; } 3>&1

If you need the command's return status, bash puts it in ${PIPESTATUS[0]}.

{ { command | tee -- "$stdoutF" 1>&3; exit ${PIPESTATUS[0]}; } 2>&1 \
            | tee -- "$stderrF" 1>&2; } 3>&1
if [ ${PIPESTATUS[0]} -ne 0 ]; then echo command failed; fi


问:
Unable to add ! (opposite operator) to Source item in a QT binding
When I am adding text to a binding in the source item column, the tutorial I am following requires me to put a ! in front of the source item. However I am simply not able to type it in as the QT ide does not allow me. Was the Qt IDE recently changed to not allow this/is there a different way to indicate the ! opposite operator in front of a source item?</p>

答: You have to edit it in the forms actual code (kind of unorthodox)</p>


问:
Copy paste column range using OpenPyxl
Hi so I am trying to copy and paste W7:W46 column into another worksheet. The code I have so far,

```<code>col_j = New_Burden['W']
for idx, cell in enumerate(col_j,1):
    ws1.cell(row = idx, column = 10).value = cell.value
</code>```

is able to copy over the entire column, but unfortunately transfers the various headers as well. One solution I have tried is:

```<code>for row in New_Burden['W7:W46']:
    for cell in row:
        ws1.cell(row = 2, column = 10).value = cell.value
</code>```

But that only copies the first value of W7

答:
Copy a Range(['W7:W46']) from one Worksheet to another Worksheet:

If the Ranges are not overlapping, it's also possible in the same Worksheet.

```<code>from openpyxl import Workbook
# Create a new Workbook
wb = Workbook()
ws = wb.worksheets[0]

from openpyxl.utils import range_boundaries
# Define start Range(['J2']) in the new Worksheet
min_col, min_row, max_col, max_row = range_boundaries('J2')

# Iterate Range you want to copy
for row, row_cells in enumerate(New_Burden['W7:W46'], min_row):
    for column, cell in enumerate(row_cells, min_col):
        # Copy Value from Copy.Cell to given Worksheet.Cell
        ws.cell(row=row, column=column).value = cell.value
</code>```

If you want to do the above with multiple different Columns,
use the above in a function:

```<code>def copy_range(source_range, target_start):
    # Define start Range(target_start) in the new Worksheet
    min_col, min_row, max_col, max_row = range_boundaries(target_start)

    # Iterate Range you want to copy
    for row, row_cells in enumerate(New_Burden[source_range], min_row):
        for column, cell in enumerate(row_cells, min_col):
            # Copy Value from Copy.Cell to given Worksheet.Cell
            ws.cell(row=row, column=column).value = cell.value

for source_range, target_start in [('W7:W46','J2'), ('Y7:Y46','A2')]:
    copy_range(source_range, target_start)
</code>```

Tested with Python: 3.4.2 - openpyxl: 2.4.1 - LibreOffice: 4.3.3.2

Title: Copy paste column range using OpenPyxl

Body:
Hi so I am trying to copy and paste W7:W46 column into another worksheet. The code I have so far,

col_j = New_Burden['W']
for idx, cell in enumerate(col_j,1):
    ws1.cell(row = idx, column = 10).value = cell.value

is able to copy over the entire column, but unfortunately transfers the various headers as well. One solution I have tried is:

for row in New_Burden['W7:W46']:
    for cell in row:
        ws1.cell(row = 2, column = 10).value = cell.value

But that only copies the first value of W7

Body:
Copy a Range(['W7:W46']) from one Worksheet to another Worksheet:

If the Ranges are not overlapping, it's also possible in the same Worksheet.

from openpyxl import Workbook
# Create a new Workbook
wb = Workbook()
ws = wb.worksheets[0]

from openpyxl.utils import range_boundaries
# Define start Range(['J2']) in the new Worksheet
min_col, min_row, max_col, max_row = range_boundaries('J2')

# Iterate Range you want to copy
for row, row_cells in enumerate(New_Burden['W7:W46'], min_row):
    for column, cell in enumerate(row_cells, min_col):
        # Copy Value from Copy.Cell to given Worksheet.Cell
        ws.cell(row=row, column=column).value = cell.value

If you want to do the above with multiple different Columns,
use the above in a function:

def copy_range(source_range, target_start):
    # Define start Range(target_start) in the new Worksheet
    min_col, min_row, max_col, max_row = range_boundaries(target_start)

    # Iterate Range you want to copy
    for row, row_cells in enumerate(New_Burden[source_range], min_row):
        for column, cell in enumerate(row_cells, min_col):
            # Copy Value from Copy.Cell to given Worksheet.Cell
            ws.cell(row=row, column=column).value = cell.value

for source_range, target_start in [('W7:W46','J2'), ('Y7:Y46','A2')]:
    copy_range(source_range, target_start)

Tested with Python: 3.4.2 - openpyxl: 2.4.1 - LibreOffice: 4.3.3.2


问:
how can i connect two forms once i clicked button another form will show something
Hi everyone now I have three forms in my Qt,I want to click first page button and show numbers in other form. so What i can do for it ?
what i tried is :</p>

```<code>void MainWindow::on_pushButton_clicked()
{
    loginpage.show();

 loginpage.ui->label->setText();

}
</code>```

答:
You will have to set up a public function in your "loginpage" class that uses a string argument to set the text.

Ex.
In LoginPageClass.h

```<code>public slots:
    void setLabel(QString label);
</code>```

In LoginPageClass.cpp

```<code>void LoginPageClass::setLabel(QString label)
{
    ui.label.setText(label);
    return;
}
</code>```

In mainwindow.cpp

```<code>void MainWindow::on_pushButton_clicked()
{
    loginpage.show();
    loginpage.setLabel(label);
}
</code>```

Body:
Hi everyone now I have three forms in my Qt,I want to click first page button and show numbers in other form. so What i can do for it ?
what i tried is :

void MainWindow::on_pushButton_clicked()
{
    loginpage.show();

 loginpage.ui->label->setText();

}

Body:
You will have to set up a public function in your "loginpage" class that uses a string argument to set the text.

Ex.
In LoginPageClass.h

public slots:
    void setLabel(QString label);

In LoginPageClass.cpp

void LoginPageClass::setLabel(QString label)
{
    ui.label.setText(label);
    return;
}

In mainwindow.cpp

void MainWindow::on_pushButton_clicked()
{
    loginpage.show();
    loginpage.setLabel(label);
}


问:
NullPointerException while trying to set click listener on button which is on bottomsheet
i have recyclerview in my App and when list item is pressed bottomsheet dialog expends where i have two buttons but i can't set click listeners to it.
This is onClick method in adapter

```<code>BottomSheetDialog offer_info_dialog;
RelativeLayout rel;
Button Yes,No;
View parentView;
@Override
public void onClick(View view) {
    rel = (RelativeLayout) activity.findViewById(R.id.bottomsheet);
    Yes = (Button) offer_info_dialog.findViewById(R.id.confirm_btn_on_info);
    No = (Button) offer_info_dialog.findViewById(R.id.cancel_btn_on_info);
        offer_info_dialog = new BottomSheetDialog(context);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        parentView = inflater.inflate(R.layout.offer_info_layout, null);
        offer_info_dialog.setContentView(parentView);
        ((View) parentView.getParent()).setBackgroundColor(context.getResources().getColor(android.R.color.transparent));
        offer_info_dialog.show();
        rel.setVisibility(View.INVISIBLE);

    Yes.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MainActivity.removeCheatOfferMarkers(2);
        }
    });

    No.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from((View) parentView.getParent());
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        }
    });
    offer_info_dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialog) {
            rel.setVisibility(View.VISIBLE);
        }
    });

}
</code>```

and this is an error:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.support.design.widget.BottomSheetDialog.findViewById(int)' on a null object reference
</code>```

答:
Multiple problems here.

You are calling findViewById before you have inflated your view. This will cause nullpointer exceptions. findViewById should only be called AFTER inflater.inflate has been called, except in the case of your activity which I assume has already been inflated.

Take a look at your code. offer_info_dialog has not been initialized to anything before you try to start calling methods on it, which is why you are getting a nullpointer.

Body:
i have recyclerview in my App and when list item is pressed bottomsheet dialog expends where i have two buttons but i can't set click listeners to it.
This is onClick method in adapter

BottomSheetDialog offer_info_dialog;
RelativeLayout rel;
Button Yes,No;
View parentView;
@Override
public void onClick(View view) {
    rel = (RelativeLayout) activity.findViewById(R.id.bottomsheet);
    Yes = (Button) offer_info_dialog.findViewById(R.id.confirm_btn_on_info);
    No = (Button) offer_info_dialog.findViewById(R.id.cancel_btn_on_info);
        offer_info_dialog = new BottomSheetDialog(context);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        parentView = inflater.inflate(R.layout.offer_info_layout, null);
        offer_info_dialog.setContentView(parentView);
        ((View) parentView.getParent()).setBackgroundColor(context.getResources().getColor(android.R.color.transparent));
        offer_info_dialog.show();
        rel.setVisibility(View.INVISIBLE);

    Yes.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MainActivity.removeCheatOfferMarkers(2);
        }
    });

    No.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from((View) parentView.getParent());
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        }
    });
    offer_info_dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialog) {
            rel.setVisibility(View.VISIBLE);
        }
    });

}

and this is an error:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.support.design.widget.BottomSheetDialog.findViewById(int)' on a null object reference


问:
JaxbRepresentation gives error "doesnt contain ObjectFactory.class or jaxb.index"
I am trying to create a sample test application which converts an object to JaxbRepresentation. But when I try to run this, it gives me an error.

Main.java file

```<code>package test_jaxb;

import org.restlet.Server;
import org.restlet.data.Protocol;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
      Server helloServer = new Server(Protocol.HTTP, 8111,
      TestResource.class);
      helloServer.start();
    }

}
</code>```

TestResource.java file

```<code>package test_jaxb;

import org.restlet.ext.jaxb.JaxbRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;

public class TestResource extends ServerResource{

   @Override
   protected Representation get() throws ResourceException {
      SampleResponse res = new SampleResponse();
      res.setMsg("Success");
      res.setStatusCode(0);
      JaxbRepresentation<SampleResponse> representation = new JaxbRepresentation<SampleResponse>(res);
      return representation;
   }
}
</code>```

SampleResponse.java file

```<code>package test_jaxb;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="Response")
public class SampleResponse {
   private int statusCode;
   private String msg;

   @XmlElement(name="Msg")
   public String getMsg() {
      return msg;
   }

   public void setMsg(String msg) {
      this.msg = msg;
   }

   @XmlElement(name="StatusCode")
   public int getStatusCode() {
      return statusCode;
   }

   public void setStatusCode(int statusCode) {
      this.statusCode = statusCode;
   }
}
</code>```

When I run this on the server, it throws the following error:

```<code>WARNING: Problem creating Marshaller
javax.xml.bind.JAXBException: "test_jaxb" doesnt contain ObjectFactory.class or jaxb.index
    at com.sun.xml.internal.bind.v2.ContextFactory.createContext(ContextFactory.java:119)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:132)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:299)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:372)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:337)
    at org.restlet.ext.jaxb.JaxbRepresentation.getContext(JaxbRepresentation.java:83)
    at org.restlet.ext.jaxb.internal.Marshaller$1.initialValue(Marshaller.java:68)
    at org.restlet.ext.jaxb.internal.Marshaller$1.initialValue(Marshaller.java:64)
    at java.lang.ThreadLocal.setInitialValue(ThreadLocal.java:141)
    at java.lang.ThreadLocal.get(ThreadLocal.java:131)
    at org.restlet.ext.jaxb.internal.Marshaller.getMarshaller(Marshaller.java:163)
    at org.restlet.ext.jaxb.internal.Marshaller.marshal(Marshaller.java:216)
    at org.restlet.ext.jaxb.JaxbRepresentation.write(JaxbRepresentation.java:527)
    at org.restlet.representation.WriterRepresentation.write(WriterRepresentation.java:104)
    at org.restlet.engine.http.connector.Connection.writeMessageBody(Connection.java:873)
    at org.restlet.engine.http.connector.Connection.writeMessage(Connection.java:818)
    at org.restlet.engine.http.connector.ServerConnection.writeMessage(ServerConnection.java:334)
    at org.restlet.engine.http.connector.Connection.writeMessages(Connection.java:954)
    at org.restlet.engine.http.connector.BaseServerHelper.handleOutbound(BaseServerHelper.java:201)
    at org.restlet.engine.http.connector.BaseHelper.handleNextOutbound(BaseHelper.java:425)
    at org.restlet.engine.http.connector.BaseServerHelper.handleInbound(BaseServerHelper.java:174)
    at org.restlet.engine.http.connector.BaseHelper.handleNextInbound(BaseHelper.java:418)
    at org.restlet.engine.http.connector.Connection.readMessages(Connection.java:695)
    at org.restlet.engine.http.connector.Controller$2.run(Controller.java:95)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:619)
May 16, 2011 7:05:12 AM org.restlet.ext.jaxb.internal.Marshaller getMarshaller
WARNING: Unable to locate marshaller.
May 16, 2011 7:05:12 AM org.restlet.ext.jaxb.JaxbRepresentation write
WARNING: JAXB marshalling error caught.
javax.xml.bind.JAXBException: Unable to locate marshaller.
    at org.restlet.ext.jaxb.internal.Marshaller.getMarshaller(Marshaller.java:166)
    at org.restlet.ext.jaxb.internal.Marshaller.marshal(Marshaller.java:216)
    at org.restlet.ext.jaxb.JaxbRepresentation.write(JaxbRepresentation.java:527)
    at org.restlet.representation.WriterRepresentation.write(WriterRepresentation.java:104)
    at org.restlet.engine.http.connector.Connection.writeMessageBody(Connection.java:873)
    at org.restlet.engine.http.connector.Connection.writeMessage(Connection.java:818)
    at org.restlet.engine.http.connector.ServerConnection.writeMessage(ServerConnection.java:334)
    at org.restlet.engine.http.connector.Connection.writeMessages(Connection.java:954)
    at org.restlet.engine.http.connector.BaseServerHelper.handleOutbound(BaseServerHelper.java:201)
    at org.restlet.engine.http.connector.BaseHelper.handleNextOutbound(BaseHelper.java:425)
    at org.restlet.engine.http.connector.BaseServerHelper.handleInbound(BaseServerHelper.java:174)
    at org.restlet.engine.http.connector.BaseHelper.handleNextInbound(BaseHelper.java:418)
    at org.restlet.engine.http.connector.Connection.readMessages(Connection.java:695)
    at org.restlet.engine.http.connector.Controller$2.run(Controller.java:95)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:619)
May 16, 2011 7:05:12 AM org.restlet.ext.jaxb.internal.Marshaller$1 initialValue
WARNING: Problem creating Marshaller
javax.xml.bind.JAXBException: "failure" doesnt contain ObjectFactory.class or jaxb.index
    at com.sun.xml.internal.bind.v2.ContextFactory.createContext(ContextFactory.java:119)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:132)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:299)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:372)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:337)
    at org.restlet.ext.jaxb.JaxbRepresentation.getContext(JaxbRepresentation.java:83)
    at org.restlet.ext.jaxb.internal.Marshaller$1.initialValue(Marshaller.java:68)
    at org.restlet.ext.jaxb.internal.Marshaller$1.initialValue(Marshaller.java:64)
    at java.lang.ThreadLocal.setInitialValue(ThreadLocal.java:141)
    at java.lang.ThreadLocal.get(ThreadLocal.java:131)
    at org.restlet.ext.jaxb.internal.Marshaller.getMarshaller(Marshaller.java:163)
    at org.restlet.ext.jaxb.internal.Marshaller.marshal(Marshaller.java:216)
    at org.restlet.ext.jaxb.JaxbRepresentation.write(JaxbRepresentation.java:535)
    at org.restlet.representation.WriterRepresentation.write(WriterRepresentation.java:104)
    at org.restlet.engine.http.connector.Connection.writeMessageBody(Connection.java:873)
    at org.restlet.engine.http.connector.Connection.writeMessage(Connection.java:818)
    at org.restlet.engine.http.connector.ServerConnection.writeMessage(ServerConnection.java:334)
    at org.restlet.engine.http.connector.Connection.writeMessages(Connection.java:954)
    at org.restlet.engine.http.connector.BaseServerHelper.handleOutbound(BaseServerHelper.java:201)
    at org.restlet.engine.http.connector.BaseHelper.handleNextOutbound(BaseHelper.java:425)
    at org.restlet.engine.http.connector.BaseServerHelper.handleInbound(BaseServerHelper.java:174)
    at org.restlet.engine.http.connector.BaseHelper.handleNextInbound(BaseHelper.java:418)
    at org.restlet.engine.http.connector.Connection.readMessages(Connection.java:695)
    at org.restlet.engine.http.connector.Controller$2.run(Controller.java:95)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:619)
May 16, 2011 7:05:12 AM org.restlet.ext.jaxb.internal.Marshaller getMarshaller
WARNING: Unable to locate marshaller.
May 16, 2011 7:05:12 AM org.restlet.engine.http.connector.Connection writeMessage
WARNING: Exception while writing the message body.
java.io.IOException: Unable to locate marshaller.
    at org.restlet.ext.jaxb.JaxbRepresentation.write(JaxbRepresentation.java:539)
    at org.restlet.representation.WriterRepresentation.write(WriterRepresentation.java:104)
    at org.restlet.engine.http.connector.Connection.writeMessageBody(Connection.java:873)
    at org.restlet.engine.http.connector.Connection.writeMessage(Connection.java:818)
    at org.restlet.engine.http.connector.ServerConnection.writeMessage(ServerConnection.java:334)
    at org.restlet.engine.http.connector.Connection.writeMessages(Connection.java:954)
    at org.restlet.engine.http.connector.BaseServerHelper.handleOutbound(BaseServerHelper.java:201)
    at org.restlet.engine.http.connector.BaseHelper.handleNextOutbound(BaseHelper.java:425)
    at org.restlet.engine.http.connector.BaseServerHelper.handleInbound(BaseServerHelper.java:174)
    at org.restlet.engine.http.connector.BaseHelper.handleNextInbound(BaseHelper.java:418)
    at org.restlet.engine.http.connector.Connection.readMessages(Connection.java:695)
    at org.restlet.engine.http.connector.Controller$2.run(Controller.java:95)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:619)
May 16, 2011 7:05:12 AM org.restlet.engine.http.connector.ServerConnection writeMessage
INFO: An exception occured while writing the response
java.io.IOException: Unable to locate marshaller.
    at org.restlet.ext.jaxb.JaxbRepresentation.write(JaxbRepresentation.java:539)
    at org.restlet.representation.WriterRepresentation.write(WriterRepresentation.java:104)
    at org.restlet.engine.http.connector.Connection.writeMessageBody(Connection.java:873)
    at org.restlet.engine.http.connector.Connection.writeMessage(Connection.java:818)
    at org.restlet.engine.http.connector.ServerConnection.writeMessage(ServerConnection.java:334)
    at org.restlet.engine.http.connector.Connection.writeMessages(Connection.java:954)
    at org.restlet.engine.http.connector.BaseServerHelper.handleOutbound(BaseServerHelper.java:201)
    at org.restlet.engine.http.connector.BaseHelper.handleNextOutbound(BaseHelper.java:425)
    at org.restlet.engine.http.connector.BaseServerHelper.handleInbound(BaseServerHelper.java:174)
    at org.restlet.engine.http.connector.BaseHelper.handleNextInbound(BaseHelper.java:418)
    at org.restlet.engine.http.connector.Connection.readMessages(Connection.java:695)
    at org.restlet.engine.http.connector.Controller$2.run(Controller.java:95)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:619)
</code>```

Please someone help!!!

答: Use the complete package name of the where the ObjectFactory class is present to declare and instantiate the Object.

Body:
I am trying to create a sample test application which converts an object to JaxbRepresentation. But when I try to run this, it gives me an error.

Main.java file

package test_jaxb;

import org.restlet.Server;
import org.restlet.data.Protocol;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
      Server helloServer = new Server(Protocol.HTTP, 8111,
      TestResource.class);
      helloServer.start();
    }

}

TestResource.java file

package test_jaxb;

import org.restlet.ext.jaxb.JaxbRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;

public class TestResource extends ServerResource{

   @Override
   protected Representation get() throws ResourceException {
      SampleResponse res = new SampleResponse();
      res.setMsg("Success");
      res.setStatusCode(0);
      JaxbRepresentation<SampleResponse> representation = new JaxbRepresentation<SampleResponse>(res);
      return representation;
   }
}

SampleResponse.java file

package test_jaxb;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="Response")
public class SampleResponse {
   private int statusCode;
   private String msg;

   @XmlElement(name="Msg")
   public String getMsg() {
      return msg;
   }

   public void setMsg(String msg) {
      this.msg = msg;
   }

   @XmlElement(name="StatusCode")
   public int getStatusCode() {
      return statusCode;
   }

   public void setStatusCode(int statusCode) {
      this.statusCode = statusCode;
   }
}

When I run this on the server, it throws the following error:

WARNING: Problem creating Marshaller
javax.xml.bind.JAXBException: "test_jaxb" doesnt contain ObjectFactory.class or jaxb.index
    at com.sun.xml.internal.bind.v2.ContextFactory.createContext(ContextFactory.java:119)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:132)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:299)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:372)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:337)
    at org.restlet.ext.jaxb.JaxbRepresentation.getContext(JaxbRepresentation.java:83)
    at org.restlet.ext.jaxb.internal.Marshaller$1.initialValue(Marshaller.java:68)
    at org.restlet.ext.jaxb.internal.Marshaller$1.initialValue(Marshaller.java:64)
    at java.lang.ThreadLocal.setInitialValue(ThreadLocal.java:141)
    at java.lang.ThreadLocal.get(ThreadLocal.java:131)
    at org.restlet.ext.jaxb.internal.Marshaller.getMarshaller(Marshaller.java:163)
    at org.restlet.ext.jaxb.internal.Marshaller.marshal(Marshaller.java:216)
    at org.restlet.ext.jaxb.JaxbRepresentation.write(JaxbRepresentation.java:527)
    at org.restlet.representation.WriterRepresentation.write(WriterRepresentation.java:104)
    at org.restlet.engine.http.connector.Connection.writeMessageBody(Connection.java:873)
    at org.restlet.engine.http.connector.Connection.writeMessage(Connection.java:818)
    at org.restlet.engine.http.connector.ServerConnection.writeMessage(ServerConnection.java:334)
    at org.restlet.engine.http.connector.Connection.writeMessages(Connection.java:954)
    at org.restlet.engine.http.connector.BaseServerHelper.handleOutbound(BaseServerHelper.java:201)
    at org.restlet.engine.http.connector.BaseHelper.handleNextOutbound(BaseHelper.java:425)
    at org.restlet.engine.http.connector.BaseServerHelper.handleInbound(BaseServerHelper.java:174)
    at org.restlet.engine.http.connector.BaseHelper.handleNextInbound(BaseHelper.java:418)
    at org.restlet.engine.http.connector.Connection.readMessages(Connection.java:695)
    at org.restlet.engine.http.connector.Controller$2.run(Controller.java:95)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:619)
May 16, 2011 7:05:12 AM org.restlet.ext.jaxb.internal.Marshaller getMarshaller
WARNING: Unable to locate marshaller.
May 16, 2011 7:05:12 AM org.restlet.ext.jaxb.JaxbRepresentation write
WARNING: JAXB marshalling error caught.
javax.xml.bind.JAXBException: Unable to locate marshaller.
    at org.restlet.ext.jaxb.internal.Marshaller.getMarshaller(Marshaller.java:166)
    at org.restlet.ext.jaxb.internal.Marshaller.marshal(Marshaller.java:216)
    at org.restlet.ext.jaxb.JaxbRepresentation.write(JaxbRepresentation.java:527)
    at org.restlet.representation.WriterRepresentation.write(WriterRepresentation.java:104)
    at org.restlet.engine.http.connector.Connection.writeMessageBody(Connection.java:873)
    at org.restlet.engine.http.connector.Connection.writeMessage(Connection.java:818)
    at org.restlet.engine.http.connector.ServerConnection.writeMessage(ServerConnection.java:334)
    at org.restlet.engine.http.connector.Connection.writeMessages(Connection.java:954)
    at org.restlet.engine.http.connector.BaseServerHelper.handleOutbound(BaseServerHelper.java:201)
    at org.restlet.engine.http.connector.BaseHelper.handleNextOutbound(BaseHelper.java:425)
    at org.restlet.engine.http.connector.BaseServerHelper.handleInbound(BaseServerHelper.java:174)
    at org.restlet.engine.http.connector.BaseHelper.handleNextInbound(BaseHelper.java:418)
    at org.restlet.engine.http.connector.Connection.readMessages(Connection.java:695)
    at org.restlet.engine.http.connector.Controller$2.run(Controller.java:95)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:619)
May 16, 2011 7:05:12 AM org.restlet.ext.jaxb.internal.Marshaller$1 initialValue
WARNING: Problem creating Marshaller
javax.xml.bind.JAXBException: "failure" doesnt contain ObjectFactory.class or jaxb.index
    at com.sun.xml.internal.bind.v2.ContextFactory.createContext(ContextFactory.java:119)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:132)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:299)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:372)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:337)
    at org.restlet.ext.jaxb.JaxbRepresentation.getContext(JaxbRepresentation.java:83)
    at org.restlet.ext.jaxb.internal.Marshaller$1.initialValue(Marshaller.java:68)
    at org.restlet.ext.jaxb.internal.Marshaller$1.initialValue(Marshaller.java:64)
    at java.lang.ThreadLocal.setInitialValue(ThreadLocal.java:141)
    at java.lang.ThreadLocal.get(ThreadLocal.java:131)
    at org.restlet.ext.jaxb.internal.Marshaller.getMarshaller(Marshaller.java:163)
    at org.restlet.ext.jaxb.internal.Marshaller.marshal(Marshaller.java:216)
    at org.restlet.ext.jaxb.JaxbRepresentation.write(JaxbRepresentation.java:535)
    at org.restlet.representation.WriterRepresentation.write(WriterRepresentation.java:104)
    at org.restlet.engine.http.connector.Connection.writeMessageBody(Connection.java:873)
    at org.restlet.engine.http.connector.Connection.writeMessage(Connection.java:818)
    at org.restlet.engine.http.connector.ServerConnection.writeMessage(ServerConnection.java:334)
    at org.restlet.engine.http.connector.Connection.writeMessages(Connection.java:954)
    at org.restlet.engine.http.connector.BaseServerHelper.handleOutbound(BaseServerHelper.java:201)
    at org.restlet.engine.http.connector.BaseHelper.handleNextOutbound(BaseHelper.java:425)
    at org.restlet.engine.http.connector.BaseServerHelper.handleInbound(BaseServerHelper.java:174)
    at org.restlet.engine.http.connector.BaseHelper.handleNextInbound(BaseHelper.java:418)
    at org.restlet.engine.http.connector.Connection.readMessages(Connection.java:695)
    at org.restlet.engine.http.connector.Controller$2.run(Controller.java:95)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:619)
May 16, 2011 7:05:12 AM org.restlet.ext.jaxb.internal.Marshaller getMarshaller
WARNING: Unable to locate marshaller.
May 16, 2011 7:05:12 AM org.restlet.engine.http.connector.Connection writeMessage
WARNING: Exception while writing the message body.
java.io.IOException: Unable to locate marshaller.
    at org.restlet.ext.jaxb.JaxbRepresentation.write(JaxbRepresentation.java:539)
    at org.restlet.representation.WriterRepresentation.write(WriterRepresentation.java:104)
    at org.restlet.engine.http.connector.Connection.writeMessageBody(Connection.java:873)
    at org.restlet.engine.http.connector.Connection.writeMessage(Connection.java:818)
    at org.restlet.engine.http.connector.ServerConnection.writeMessage(ServerConnection.java:334)
    at org.restlet.engine.http.connector.Connection.writeMessages(Connection.java:954)
    at org.restlet.engine.http.connector.BaseServerHelper.handleOutbound(BaseServerHelper.java:201)
    at org.restlet.engine.http.connector.BaseHelper.handleNextOutbound(BaseHelper.java:425)
    at org.restlet.engine.http.connector.BaseServerHelper.handleInbound(BaseServerHelper.java:174)
    at org.restlet.engine.http.connector.BaseHelper.handleNextInbound(BaseHelper.java:418)
    at org.restlet.engine.http.connector.Connection.readMessages(Connection.java:695)
    at org.restlet.engine.http.connector.Controller$2.run(Controller.java:95)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:619)
May 16, 2011 7:05:12 AM org.restlet.engine.http.connector.ServerConnection writeMessage
INFO: An exception occured while writing the response
java.io.IOException: Unable to locate marshaller.
    at org.restlet.ext.jaxb.JaxbRepresentation.write(JaxbRepresentation.java:539)
    at org.restlet.representation.WriterRepresentation.write(WriterRepresentation.java:104)
    at org.restlet.engine.http.connector.Connection.writeMessageBody(Connection.java:873)
    at org.restlet.engine.http.connector.Connection.writeMessage(Connection.java:818)
    at org.restlet.engine.http.connector.ServerConnection.writeMessage(ServerConnection.java:334)
    at org.restlet.engine.http.connector.Connection.writeMessages(Connection.java:954)
    at org.restlet.engine.http.connector.BaseServerHelper.handleOutbound(BaseServerHelper.java:201)
    at org.restlet.engine.http.connector.BaseHelper.handleNextOutbound(BaseHelper.java:425)
    at org.restlet.engine.http.connector.BaseServerHelper.handleInbound(BaseServerHelper.java:174)
    at org.restlet.engine.http.connector.BaseHelper.handleNextInbound(BaseHelper.java:418)
    at org.restlet.engine.http.connector.Connection.readMessages(Connection.java:695)
    at org.restlet.engine.http.connector.Controller$2.run(Controller.java:95)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:619)

Please someone help!!!


问:
Multidimensional array in php SESSION
I am having problem with updating an array element with in $_SESSION variable of PHP. This is the basic structure:

```<code>$product = array();
$product['id'] = $id;
$product['type'] = $type;
$product['quantity'] = $quantity;
</code>```

And then by using array_push() function I insert that product in SESSION variable.

```<code>array_push($_SESSION['cart'], $product);
</code>```

Now this is the main part where i m facing problem:

```<code>foreach($_SESSION['cart'] as $product){

    if($id == $product['id']){
        $quantity = $product['quantity'];
        $quantity += 1;
        $product['quantity'] = $quantity;
    }

}
</code>```

I want to increment product quantity within $_SESSION['cart'] variable. How can I do that?

答:
this not best answers for u...but hope can help u guys
im not expert coders, and just learn coding in this forum ^,^ .You must always trying to solved.
for more example hope can help to update value quantity:</p>

```<code><?php
if(isset($_POST['test'])) {
    $id =$_POST['id'];

    $newitem = array(
    'idproduk' => $id,
    'nm_produk' => 'hoodie',
    'img_produk' => 'images/produk/hodie.jpg',
    'harga_produk' => '20',
    'qty' => '2'
    );
    //if not empty
    if(!empty($_SESSION['cart']))
    {
        //and if session cart same
        if(isset($_SESSION['cart'][$id]) == $id) {
            $_SESSION['cart'][$id]['qty']++;
        } else {
            //if not same put new storing
            $_SESSION['cart'][$id] = $newitem;
        }
    } else  {
        $_SESSION['cart'] = array();
        $_SESSION['cart'][$id] = $newitem;
    }
}
?>
<form method="post">
<input type="text" name="id" value="1">
<input type="submit" name="test" value="test">
<input type="submit" name="unset" value="unset">
</form>
</code>```

Title: Multidimensional array in php SESSION

Body:
I am having problem with updating an array element with in $_SESSION variable of PHP. This is the basic structure:

$product = array();
$product['id'] = $id;
$product['type'] = $type;
$product['quantity'] = $quantity;

And then by using array_push() function I insert that product in SESSION variable.

array_push($_SESSION['cart'], $product);

Now this is the main part where i m facing problem:

foreach($_SESSION['cart'] as $product){

    if($id == $product['id']){
        $quantity = $product['quantity'];
        $quantity += 1;
        $product['quantity'] = $quantity;
    }

}

I want to increment product quantity within $_SESSION['cart'] variable. How can I do that?

Body:
this not best answers for u...but hope can help u guys
im not expert coders, and just learn coding in this forum ^,^ .You must always trying to solved.
for more example hope can help to update value quantity:

<?php
if(isset($_POST['test'])) {
    $id =$_POST['id'];

    $newitem = array(
    'idproduk' => $id,
    'nm_produk' => 'hoodie',
    'img_produk' => 'images/produk/hodie.jpg',
    'harga_produk' => '20',
    'qty' => '2'
    );
    //if not empty
    if(!empty($_SESSION['cart']))
    {
        //and if session cart same
        if(isset($_SESSION['cart'][$id]) == $id) {
            $_SESSION['cart'][$id]['qty']++;
        } else {
            //if not same put new storing
            $_SESSION['cart'][$id] = $newitem;
        }
    } else  {
        $_SESSION['cart'] = array();
        $_SESSION['cart'][$id] = $newitem;
    }
}
?>
<form method="post">
<input type="text" name="id" value="1">
<input type="submit" name="test" value="test">
<input type="submit" name="unset" value="unset">
</form>


问:
.Htaccess rewrite to username
I'm a beginner in php and primarily with htaccess part. It's pretty darn confusing.

So I have this file :-

```<code>www.domain.com/profile.php?username=my_username
</code>```

How can I make the above accessible using only :-

```<code>wwww.domain.com/my_username
</code>```

Any kind of directions would be helpful

Something that I tried :-

```<code>RewriteEngine on
RewriteRule ^/([0-9]+)$ /profile.php?username=$1
</code>```

答:
You can use these set of rule in your site root .htaccess:</p>

```<code>Options +FollowSymLinks
RewriteEngine On
RewriteBase /foldername/

RewriteCond %{THE_REQUEST} /profile\.php\?username=([^\s&]+) [NC]
RewriteRule ^ %1? [R=301,L,NE]

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^([\w-]+)/?$ profile.php?username=$1 [L,QSA]
</code>```

Title: .Htaccess rewrite to username

Body:
I'm a beginner in php and primarily with htaccess part. It's pretty darn confusing.

So I have this file :-

www.domain.com/profile.php?username=my_username

How can I make the above accessible using only :-

wwww.domain.com/my_username

Any kind of directions would be helpful

Something that I tried :-

RewriteEngine on
RewriteRule ^/([0-9]+)$ /profile.php?username=$1

Body:
You can use these set of rule in your site root .htaccess:

Options +FollowSymLinks
RewriteEngine On
RewriteBase /foldername/

RewriteCond %{THE_REQUEST} /profile\.php\?username=([^\s&]+) [NC]
RewriteRule ^ %1? [R=301,L,NE]

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^([\w-]+)/?$ profile.php?username=$1 [L,QSA]