问:
eclipse : adding JSF 2 facet results in NullpointerException
I have a maven project, and then, i would like to enable JSF 2 facet into the project, because i realized that i cant do the auto completion with the jsf / primefaces tags and with the tag attributes with the ctrl space when editing my jsf page.

Enabling the JSF 2 facet in my Helios eclipse results in NullPointerException, with this complete exception trace :

```<code>!ENTRY org.eclipse.wst.common.project.facet.core 4 0 2011-01-18 22:45:17.073
!MESSAGE null
!STACK 0
java.lang.NullPointerException
        at org.eclipse.jst.jsf.core.internal.project.facet.JSFFacetInstallDataModelProvider.validateConfigLocation(JSFFacetInstallDataModelProvider.java:232)
        at org.eclipse.jst.jsf.core.internal.project.facet.JSFFacetInstallDataModelProvider.validate(JSFFacetInstallDataModelProvider.java:161)
        at org.eclipse.wst.common.frameworks.internal.datamodel.DataModelImpl.validate(DataModelImpl.java:377)
        at org.eclipse.wst.common.frameworks.internal.datamodel.DataModelImpl.validate(DataModelImpl.java:358)
        at org.eclipse.wst.common.componentcore.datamodel.FacetDataModelConfigAdapter.validate(FacetDataModelConfigAdapter.java:63)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsPropertyPage.updateFurtherConfigHyperlink(FacetsPropertyPage.java:422)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsPropertyPage.access$4(FacetsPropertyPage.java:337)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsPropertyPage$6.run(FacetsPropertyPage.java:330)
        at org.eclipse.wst.common.project.facet.ui.internal.util.SwtUtil.runOnDisplayThread(SwtUtil.java:34)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsPropertyPage.handleProjectModifiedEvent(FacetsPropertyPage.java:334)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsPropertyPage.access$2(FacetsPropertyPage.java:324)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsPropertyPage$3.handleEvent(FacetsPropertyPage.java:189)
        at org.eclipse.wst.common.project.facet.core.internal.FacetedProjectWorkingCopy.notifyListeners(FacetedProjectWorkingCopy.java:1752)
        at org.eclipse.wst.common.project.facet.core.internal.FacetedProjectWorkingCopy.resumeEventNotification(FacetedProjectWorkingCopy.java:1797)
        at org.eclipse.wst.common.project.facet.core.internal.FacetedProjectWorkingCopy.addProjectFacet(FacetedProjectWorkingCopy.java:822)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsSelectionPanel.handleCheckStateChanged(FacetsSelectionPanel.java:758)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsSelectionPanel.access$10(FacetsSelectionPanel.java:729)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsSelectionPanel$6.checkStateChanged(FacetsSelectionPanel.java:309)
        at org.eclipse.jface.viewers.CheckboxTreeViewer$1.run(CheckboxTreeViewer.java:166)
        at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
        at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:49)
        at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:175)
        at org.eclipse.jface.viewers.CheckboxTreeViewer.fireCheckStateChanged(CheckboxTreeViewer.java:164)
        at org.eclipse.jface.viewers.CheckboxTreeViewer.handleSelect(CheckboxTreeViewer.java:300)
        at org.eclipse.jface.viewers.StructuredViewer$4.widgetSelected(StructuredViewer.java:1220)
        at org.eclipse.jface.util.OpenStrategy.fireSelectionEvent(OpenStrategy.java:228)
        at org.eclipse.jface.util.OpenStrategy.access$4(OpenStrategy.java:222)
        at org.eclipse.jface.util.OpenStrategy$1.handleEvent(OpenStrategy.java:389)
        at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
        at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1258)
        at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3540)
        at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3161)
        at org.eclipse.jface.window.Window.runEventLoop(Window.java:825)
        at org.eclipse.jface.window.Window.open(Window.java:801)
        at org.eclipse.ui.dialogs.PropertyDialogAction.run(PropertyDialogAction.java:157)
        at org.eclipse.jface.action.Action.runWithEvent(Action.java:498)
        at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:584)
        at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:501)
        at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:411)
        at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
        at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1258)
        at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3540)
        at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3161)
        at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2640)
        at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2604)
        at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2438)
        at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:671)
        at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
        at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:664)
        at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
        at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:115)
        at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
        at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
        at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
        at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
        at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
        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 org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:619)
        at org.eclipse.equinox.launcher.Main.basicRun(Main.java:574)
        at org.eclipse.equinox.launcher.Main.run(Main.java:1407)

!ENTRY org.eclipse.wst.common.project.facet.core 4 0 2011-01-18 22:45:18.622
!MESSAGE Failed while installing JavaServer Faces 2.0.
!STACK 0
java.lang.NullPointerException
        at org.eclipse.jst.jsf.core.internal.project.facet.JSFFacetInstallDelegate.resolveConfigPath(JSFFacetInstallDelegate.java:296)
        at org.eclipse.jst.jsf.core.internal.project.facet.JSFFacetInstallDelegate.createConfigFile(JSFFacetInstallDelegate.java:313)
        at org.eclipse.jst.jsf.core.internal.project.facet.JSFFacetInstallDelegate.execute(JSFFacetInstallDelegate.java:124)
        at org.eclipse.wst.common.project.facet.core.internal.FacetedProject.callDelegate(FacetedProject.java:1478)
        at org.eclipse.wst.common.project.facet.core.internal.FacetedProject.modifyInternal(FacetedProject.java:442)
        at org.eclipse.wst.common.project.facet.core.internal.FacetedProject.mergeChangesInternal(FacetedProject.java:1182)
        at org.eclipse.wst.common.project.facet.core.internal.FacetedProject.access$2(FacetedProject.java:1118)
        at org.eclipse.wst.common.project.facet.core.internal.FacetedProject$5.run(FacetedProject.java:1100)
        at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1975)
        at org.eclipse.wst.common.project.facet.core.internal.FacetedProject.mergeChanges(FacetedProject.java:1110)
        at org.eclipse.wst.common.project.facet.core.internal.FacetedProjectWorkingCopy.commitChanges(FacetedProjectWorkingCopy.java:2020)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsPropertyPage$4.run(FacetsPropertyPage.java:232)
        at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1975)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsPropertyPage$5.run(FacetsPropertyPage.java:246)
        at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121)
</code>```

What could be wrong here .. or ..

Perhaps there is some other ways to enable the auto completion without adding the dynamic web module and jsf 2 facets in the Eclipse Helios ?

答:
I've found the solution/workaround myself. I just delete the project, re-import it as a maven project, added the facets and finally everything is fine now.

Thanks! Very happy now. Hopefully this could help others also.

Body:
I have a maven project, and then, i would like to enable JSF 2 facet into the project, because i realized that i cant do the auto completion with the jsf / primefaces tags and with the tag attributes with the ctrl space when editing my jsf page.

Enabling the JSF 2 facet in my Helios eclipse results in NullPointerException, with this complete exception trace :

!ENTRY org.eclipse.wst.common.project.facet.core 4 0 2011-01-18 22:45:17.073
!MESSAGE null
!STACK 0
java.lang.NullPointerException
        at org.eclipse.jst.jsf.core.internal.project.facet.JSFFacetInstallDataModelProvider.validateConfigLocation(JSFFacetInstallDataModelProvider.java:232)
        at org.eclipse.jst.jsf.core.internal.project.facet.JSFFacetInstallDataModelProvider.validate(JSFFacetInstallDataModelProvider.java:161)
        at org.eclipse.wst.common.frameworks.internal.datamodel.DataModelImpl.validate(DataModelImpl.java:377)
        at org.eclipse.wst.common.frameworks.internal.datamodel.DataModelImpl.validate(DataModelImpl.java:358)
        at org.eclipse.wst.common.componentcore.datamodel.FacetDataModelConfigAdapter.validate(FacetDataModelConfigAdapter.java:63)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsPropertyPage.updateFurtherConfigHyperlink(FacetsPropertyPage.java:422)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsPropertyPage.access$4(FacetsPropertyPage.java:337)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsPropertyPage$6.run(FacetsPropertyPage.java:330)
        at org.eclipse.wst.common.project.facet.ui.internal.util.SwtUtil.runOnDisplayThread(SwtUtil.java:34)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsPropertyPage.handleProjectModifiedEvent(FacetsPropertyPage.java:334)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsPropertyPage.access$2(FacetsPropertyPage.java:324)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsPropertyPage$3.handleEvent(FacetsPropertyPage.java:189)
        at org.eclipse.wst.common.project.facet.core.internal.FacetedProjectWorkingCopy.notifyListeners(FacetedProjectWorkingCopy.java:1752)
        at org.eclipse.wst.common.project.facet.core.internal.FacetedProjectWorkingCopy.resumeEventNotification(FacetedProjectWorkingCopy.java:1797)
        at org.eclipse.wst.common.project.facet.core.internal.FacetedProjectWorkingCopy.addProjectFacet(FacetedProjectWorkingCopy.java:822)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsSelectionPanel.handleCheckStateChanged(FacetsSelectionPanel.java:758)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsSelectionPanel.access$10(FacetsSelectionPanel.java:729)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsSelectionPanel$6.checkStateChanged(FacetsSelectionPanel.java:309)
        at org.eclipse.jface.viewers.CheckboxTreeViewer$1.run(CheckboxTreeViewer.java:166)
        at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
        at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:49)
        at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:175)
        at org.eclipse.jface.viewers.CheckboxTreeViewer.fireCheckStateChanged(CheckboxTreeViewer.java:164)
        at org.eclipse.jface.viewers.CheckboxTreeViewer.handleSelect(CheckboxTreeViewer.java:300)
        at org.eclipse.jface.viewers.StructuredViewer$4.widgetSelected(StructuredViewer.java:1220)
        at org.eclipse.jface.util.OpenStrategy.fireSelectionEvent(OpenStrategy.java:228)
        at org.eclipse.jface.util.OpenStrategy.access$4(OpenStrategy.java:222)
        at org.eclipse.jface.util.OpenStrategy$1.handleEvent(OpenStrategy.java:389)
        at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
        at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1258)
        at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3540)
        at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3161)
        at org.eclipse.jface.window.Window.runEventLoop(Window.java:825)
        at org.eclipse.jface.window.Window.open(Window.java:801)
        at org.eclipse.ui.dialogs.PropertyDialogAction.run(PropertyDialogAction.java:157)
        at org.eclipse.jface.action.Action.runWithEvent(Action.java:498)
        at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:584)
        at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:501)
        at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:411)
        at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
        at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1258)
        at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3540)
        at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3161)
        at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2640)
        at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2604)
        at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2438)
        at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:671)
        at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
        at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:664)
        at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
        at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:115)
        at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
        at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
        at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
        at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
        at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
        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 org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:619)
        at org.eclipse.equinox.launcher.Main.basicRun(Main.java:574)
        at org.eclipse.equinox.launcher.Main.run(Main.java:1407)

!ENTRY org.eclipse.wst.common.project.facet.core 4 0 2011-01-18 22:45:18.622
!MESSAGE Failed while installing JavaServer Faces 2.0.
!STACK 0
java.lang.NullPointerException
        at org.eclipse.jst.jsf.core.internal.project.facet.JSFFacetInstallDelegate.resolveConfigPath(JSFFacetInstallDelegate.java:296)
        at org.eclipse.jst.jsf.core.internal.project.facet.JSFFacetInstallDelegate.createConfigFile(JSFFacetInstallDelegate.java:313)
        at org.eclipse.jst.jsf.core.internal.project.facet.JSFFacetInstallDelegate.execute(JSFFacetInstallDelegate.java:124)
        at org.eclipse.wst.common.project.facet.core.internal.FacetedProject.callDelegate(FacetedProject.java:1478)
        at org.eclipse.wst.common.project.facet.core.internal.FacetedProject.modifyInternal(FacetedProject.java:442)
        at org.eclipse.wst.common.project.facet.core.internal.FacetedProject.mergeChangesInternal(FacetedProject.java:1182)
        at org.eclipse.wst.common.project.facet.core.internal.FacetedProject.access$2(FacetedProject.java:1118)
        at org.eclipse.wst.common.project.facet.core.internal.FacetedProject$5.run(FacetedProject.java:1100)
        at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1975)
        at org.eclipse.wst.common.project.facet.core.internal.FacetedProject.mergeChanges(FacetedProject.java:1110)
        at org.eclipse.wst.common.project.facet.core.internal.FacetedProjectWorkingCopy.commitChanges(FacetedProjectWorkingCopy.java:2020)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsPropertyPage$4.run(FacetsPropertyPage.java:232)
        at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1975)
        at org.eclipse.wst.common.project.facet.ui.internal.FacetsPropertyPage$5.run(FacetsPropertyPage.java:246)
        at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121)

What could be wrong here .. or ..

Perhaps there is some other ways to enable the auto completion without adding the dynamic web module and jsf 2 facets in the Eclipse Helios ?


来源: stackexchange

问:
struct pointer with pointers
If I try to use my struct i got the following errors:

invalid conversion from 'int' to 'Arp::Bit*' [-fpermissive]:

```<code>input->p2_motorVerticalUp= 1;
</code>```

or 'bool Arp::Bit::value' is private within this context:

```<code>input->p2_motorVerticalUp->value = 1;
</code>```

Programm:

```<code>//.hpp

    struct inputPorts
{
public:
    bit *p1_endSwitchHorizontal;
    bit *p2_motorVerticalUp;
    bit *p3_motorVerticalDown;
};

class MyProgram : public ProgramBase, private Loggable<MyProgram>
{
public:
    inputPorts *input;
    bit endSwitchHorizontal;
    bit motorVerticalUp;
    bit motorVerticalDown;

////////////////////////////////////////////////////////////////
//.cpp

void MyProgram::Execute()
{
    input->p1_endSwitchHorizontal = &endSwitchHorizontal;
    input->p2_motorVerticalUp = &motorVerticalUp;
    input->p3_motorVerticalDown = &motorVerticalDown;

    input->p2_motorVerticalUp= 1;
}
</code>```

How can I allocate a value to endSwitchHorizontal with the struct?

答:
You're trying to set a pointer to a bit (bit*) with an integer of 1.

If you want to set the value of the bit to 1 you have dereference the pointer like this:
*input->p2_motorVerticalUp = 1;

ContentLicense: CC BY-SA 3.0

Title: struct pointer with pointers

Body:
If I try to use my struct i got the following errors:

invalid conversion from 'int' to 'Arp::Bit*' [-fpermissive]:

input->p2_motorVerticalUp= 1;

or 'bool Arp::Bit::value' is private within this context:

input->p2_motorVerticalUp->value = 1;

Programm:

//.hpp

    struct inputPorts
{
public:
    bit *p1_endSwitchHorizontal;
    bit *p2_motorVerticalUp;
    bit *p3_motorVerticalDown;
};

class MyProgram : public ProgramBase, private Loggable<MyProgram>
{
public:
    inputPorts *input;
    bit endSwitchHorizontal;
    bit motorVerticalUp;
    bit motorVerticalDown;

////////////////////////////////////////////////////////////////
//.cpp

void MyProgram::Execute()
{
    input->p1_endSwitchHorizontal = &endSwitchHorizontal;
    input->p2_motorVerticalUp = &motorVerticalUp;
    input->p3_motorVerticalDown = &motorVerticalDown;

    input->p2_motorVerticalUp= 1;
}

How can I allocate a value to endSwitchHorizontal with the struct?


问:
How to post JSON data and a request token(in the header) in cURL php
I want to send the login credentials and a pin number as a JSON data and the request token as my http header.

initially it's like this,

```<code>{
    "Username":"admin",
    "Password":"root123",
   "PinCode” : "hello321"
}
</code>```

and I need to post my Request Header token as well.

and if the request is ok, I should get JSON response as follow,

```<code>{
            "Title": "Mr.",
            "Name": "Pushkov",
            "Age": "18"

}
</code>```

I'm trying to do it in cURL PHP. Below is my controller code.

I tried to save my request token to a variable and pass it in header and post username, password and pinnumber as JSON data. if the login success than user info should be displayed. but I'm struggling to move ahead from here. How can I achieve that?

```<code>public function send_data() {

$url='http://samplesite.azurewebsites.net/api/member/loginmember';

$ch = curl_init('http://localhost/main');

$data = array("Username" =>$this->input->post('un'), "Password"  =>$this->input->post('pw'), "PinCode" =>$this->input->post('PinCode'));
$data_string = json_encode($data);

//echo $data_string;

// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);

//var_dump(json_decode($result, true));
$data2=json_decode($result, true);
$ref_id = ( ( is_array( $data2["UserCode"] ) ? implode(", ", $data2["PinCode"]) : $data2["RequestToken"] ) ); // array to string
$acc_t = $data2["RequestToken"];
$uun = $data2["UserCode"];

//echo $acc_t;

// Closing
curl_close($ch);
//print  $result ;
}
</code>```

答:
In your code above, you set a URL to curl_init() and you also passed another one in CURLOPT_URL option. You can't do that in one cURL request.

If you are using OAuth 2.0 you can set the access token to CURLOPT_XOAUTH2_BEARER option.

More information, please refer to PHP manual on cURL Functions.

Body:
I want to send the login credentials and a pin number as a JSON data and the request token as my http header.

initially it's like this,

{
    "Username":"admin",
    "Password":"root123",
   "PinCode” : "hello321"
}

and I need to post my Request Header token as well.

and if the request is ok, I should get JSON response as follow,

{
            "Title": "Mr.",
            "Name": "Pushkov",
            "Age": "18"

}

I'm trying to do it in cURL PHP. Below is my controller code.

I tried to save my request token to a variable and pass it in header and post username, password and pinnumber as JSON data. if the login success than user info should be displayed. but I'm struggling to move ahead from here. How can I achieve that?

public function send_data() {

$url='http://samplesite.azurewebsites.net/api/member/loginmember';

$ch = curl_init('http://localhost/main');

$data = array("Username" =>$this->input->post('un'), "Password"  =>$this->input->post('pw'), "PinCode" =>$this->input->post('PinCode'));
$data_string = json_encode($data);

//echo $data_string;

// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);

//var_dump(json_decode($result, true));
$data2=json_decode($result, true);
$ref_id = ( ( is_array( $data2["UserCode"] ) ? implode(", ", $data2["PinCode"]) : $data2["RequestToken"] ) ); // array to string
$acc_t = $data2["RequestToken"];
$uun = $data2["UserCode"];

//echo $acc_t;

// Closing
curl_close($ch);
//print  $result ;
}


问:
Resource consumption inside a Docker container
```<code>CONTAINER      CPU %    MEM USAGE / LIMIT     MEM %    NET I/O             BLOCK I/O           PIDS
48c16e180af6   0.20%    91.48MiB / 31.31GiB   0.29%    3.86kB / 0B         85.3MB / 0B         33
f734efe5a249        0.00%    472KiB / 31.31GiB     0.00%    3.97kB / 0B         12.3kB / 0B         1
165a7b031093        0.00%    480KiB / 31.31GiB     0.00%    9.49kB / 0B         3.66MB / 0B         1
</code>```

Does anyone know how to get resource consumption of a specific Docker container within its running environment?

Outside of a container, we can get it easily  by typing a command "docker stats". Besides, if I try to get resource consumption inside a container, it will get the consumption (RAM, CPU) of the physical computer which the container runs on.
Another option is using 'htop' command, but it does not show the result exactly compared to 'docker stats' command.

答:
If you want the processes consumption inside the container, you can go into the container and monitor the processes.

```<code>docker exec -it <container-name> watch ps -aux
</code>```

Notice that after running the above command, the container doesn't know about any docker processes running.

Body:
CONTAINER      CPU %    MEM USAGE / LIMIT     MEM %    NET I/O             BLOCK I/O           PIDS
48c16e180af6   0.20%    91.48MiB / 31.31GiB   0.29%    3.86kB / 0B         85.3MB / 0B         33
f734efe5a249        0.00%    472KiB / 31.31GiB     0.00%    3.97kB / 0B         12.3kB / 0B         1
165a7b031093        0.00%    480KiB / 31.31GiB     0.00%    9.49kB / 0B         3.66MB / 0B         1

Does anyone know how to get resource consumption of a specific Docker container within its running environment?

Outside of a container, we can get it easily  by typing a command "docker stats". Besides, if I try to get resource consumption inside a container, it will get the consumption (RAM, CPU) of the physical computer which the container runs on.
Another option is using 'htop' command, but it does not show the result exactly compared to 'docker stats' command.

Body:
If you want the processes consumption inside the container, you can go into the container and monitor the processes.

docker exec -it <container-name> watch ps -aux

Notice that after running the above command, the container doesn't know about any docker processes running.


问:
how to send user to a specific area of the page by passing url values to that specific section
Sorry for the long title, I have no clue how to properly explain this in a efficient way as I dont know the terms for it. An example of what I want to do is done by stackoverflow itself. Take the most voted question in here, if I want to share a answer with you guys I can just use the url with the following https://stackoverflow.com/a/16184827/8782879 that would take the user to the specific area of the page.

I want to do something like this with my page, not necessary an answer but I would like to take them back to a certain point of the page once they re-visit that page. But as you all can see I dont know where to start looking for it as I dont even know the terms for this type of functions. Any help and tutorial on this would be very helpful to get me started.

I include the tags that I will possibly be using for this.

答:
What are you looking for is called anchors and it is a HTML feature, not PHP.
Just set id to a element like this

```<code><div id="my-anchor">Your content here</div>
</code>```

then use it like this http://localhost#my-anchor

Here you can see working example: http://www.tagindex.net/html/link/anchor_example1s.html#a001

Body:
What are you looking for is called anchors and it is a HTML feature, not PHP.
Just set id to a element like this

<div id="my-anchor">Your content here</div>

then use it like this http://localhost#my-anchor

Here you can see working example: http://www.tagindex.net/html/link/anchor_example1s.html#a001


问:
styling for all elements except for a div and all divs inside it

$('#main div').not('#2 > #3').each(function() {
  $(this).css('background-color', 'blue');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">

  <div id="1">
    <div>Some text in paragraph 1</div>
    <div>Some text in paragraph 1</div>
  </div><br>
  <div id="2">
    <div id="3">Some text in paragraph 2</div>
    <div>Some text in paragraph 1</div>
  </div><br>
  <div id="3">
    <div>Some text in paragraph 3</div>
    <div>Some text in paragraph 1</div>
  </div><br>

</div></code>```

I want the css not to be applied for the nested divs of div with id=2. Any suggestions?

答:
You have to exclude div#2 in this way:

```<code>$('#main > div').not('#2').each(function() {
    $(this).css('background-color', 'blue');
});
</code>```

Or more simply:

```<code>$('#main > div').not('#2').css('background-color', 'blue');
</code>```

Pure CSS:

```<code>#main > div:not(#2) {
    background-color: blue;
}
</code>```

Body:
$('#main div').not('#2 > #3').each(function() {
  $(this).css('background-color', 'blue');
});

Some text in paragraph 1

Some text in paragraph 1

Some text in paragraph 2

Some text in paragraph 1

Some text in paragraph 3

Some text in paragraph 1

I want the css not to be applied for the nested divs of div with id=2. Any suggestions?

Body:
You have to exclude div#2 in this way:

$('#main > div').not('#2').each(function() {
    $(this).css('background-color', 'blue');
});

Or more simply:

$('#main > div').not('#2').css('background-color', 'blue');

Pure CSS:

#main > div:not(#2) {
    background-color: blue;
}


问:
Check if value exists in the list
Let’s say I have 123-0-1 and I want to check if this value exists inside the list. Below is the list that I have:

```<code> df = [
       {'mpls': '123-0-1', 'source': '192.168.10.10', 'destination' : '12.168.100.10'},
       {'mpls': '123-0-1', 'source': '192.168.10.15', 'destination': '10.12.129.200'}
      ]
</code>```

In SQL I would use:

```<code>select mpls, source from df where source = 192.168.10.10
</code>```

From the list, I would like extract mpls 123-0-1 from the source 192.168.10.10 such that I can get the correct destination 12.168.100.10.

答:
We can also use filter function to get filtered data from the list.

filtered_list = filter((lambda x: x['source'] == '192.168.10.10'), df)

Title: Check if value exists in the list

Body:
Let’s say I have 123-0-1 and I want to check if this value exists inside the list. Below is the list that I have:

 df = [
       {'mpls': '123-0-1', 'source': '192.168.10.10', 'destination' : '12.168.100.10'},
       {'mpls': '123-0-1', 'source': '192.168.10.15', 'destination': '10.12.129.200'}
      ]

In SQL I would use:

select mpls, source from df where source = 192.168.10.10

From the list, I would like extract mpls 123-0-1 from the source 192.168.10.10 such that I can get the correct destination 12.168.100.10.


问:
Do I need to delete an static std::map?
In some classes I have an static std::map with pointers inside. My question is if I need to delete at the end of the program or this memory is automatically freed. My concern is if the pointers stored inside are correctly deleted through our destructors when std::map is deleted.

Thanks.

答:
If the map contains pointers that were allocated with new (or new[], or malloc), then each pointer needs a corresponding delete (or delete[], or free).

The map's destructor wont know what to do with a bald pointer.  Consider using a smart pointer that has appropriate move semantics like a boost smart pointer or if you've got a very new compiler, one of the C++0x smart pointers.  However, do not use the current standard's std::auto_ptr, inside of STL containers.  See this thread for why.

Edit:

As Billy ONeal pointed out, boost::ptr_map is also designed exactly for this purpose.

ContentLicense: CC BY-SA 2.5

Title: Do I need to delete an static std::map?


问:
ios CocoaPods Could not automatically select an Xcode project. Specify one in your Podfile like so
I try to run pod install command in my project directory. But it throws an error like below:

```<code>[!] Could not automatically select an Xcode project. Specify one in your Podfile like so:

    project 'path/to/Project.xcodeproj'
</code>```

My project directory:

```<code> - MyApp
 - MyApp.xcodeproj
 - MyApp.xcworkspace
 - Podfile
 - Podfile.lock
 - Pods
</code>```

podFile

```<code>source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
use_frameworks!
project '/Users/dev4/Developer/iOS/MyApp/MyApp.xcodeproj'

target 'MyApp' do
  pod 'Gifu'
  pod 'Alamofire'
  pod 'SwiftyJSON'
  pod 'Fabric'
  pod 'Crashlytics'
  pod 'IQKeyboardManagerSwift'
  pod 'NVActivityIndicatorView'
  pod 'M13Checkbox'
  pod 'Kingfisher'
  pod 'KMPlaceholderTextView'
  pod 'WDImagePicker', :git => 'https://github.com/justwudi/WDImagePicker', :tag => 'master'
  pod 'RSBarcodes_Swift', '~> 0.1.9'
  pod 'CCMPopup'
  pod 'Cosmos', '~> 1.0'
  pod 'FLAnimatedImage', '~> 1.0'
  pod 'Google/Analytics'
  pod 'Reveal-iOS-SDK', :configurations => ['Debug']
end
</code>```

I added code part "project 'myprojectpath/to/Project.xcodeproj'". But it didn't work. How can I solve this?

答: I had copied my previous project with changing the App package name.When i came through this issue i go through my project structure and get to know that i have two .xcodeproj file .After deleting the old one i get rid of this issue.</p>

Body:
I try to run pod install command in my project directory. But it throws an error like below:

[!] Could not automatically select an Xcode project. Specify one in your Podfile like so:

    project 'path/to/Project.xcodeproj'

My project directory:

 - MyApp
 - MyApp.xcodeproj
 - MyApp.xcworkspace
 - Podfile
 - Podfile.lock
 - Pods

podFile

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
use_frameworks!
project '/Users/dev4/Developer/iOS/MyApp/MyApp.xcodeproj'

target 'MyApp' do
  pod 'Gifu'
  pod 'Alamofire'
  pod 'SwiftyJSON'
  pod 'Fabric'
  pod 'Crashlytics'
  pod 'IQKeyboardManagerSwift'
  pod 'NVActivityIndicatorView'
  pod 'M13Checkbox'
  pod 'Kingfisher'
  pod 'KMPlaceholderTextView'
  pod 'WDImagePicker', :git => 'https://github.com/justwudi/WDImagePicker', :tag => 'master'
  pod 'RSBarcodes_Swift', '~> 0.1.9'
  pod 'CCMPopup'
  pod 'Cosmos', '~> 1.0'
  pod 'FLAnimatedImage', '~> 1.0'
  pod 'Google/Analytics'
  pod 'Reveal-iOS-SDK', :configurations => ['Debug']
end

I added code part "project 'myprojectpath/to/Project.xcodeproj'". But it didn't work. How can I solve this?


问:
WebStorm TypeScript inspection errors - isn't shown at realtime?
I'm using WebStorm 2017.2.4 with Angular 4.3 - TypeScript doesn't show errors :

Question

How can I see real time inspections ? immediately ?

(I've already tried invalidating and clear cache).

configuration :

ts.config.json file :

```<code>{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "noEmitHelpers": true,
        "noEmitOnError": true,
        "lib": [
            "dom",
            "es6",
            "es2015.iterable"
        ],
        "baseUrl": ".",
        "paths": {
            "*": [
                "./node_modules/tns-core-modules/*",
                "./node_modules/*"
            ]
        }
    },
    "exclude": [
        "node_modules",
        "platforms",
        "**/*.aot.ts"
    ]
}
</code>```

答:
WebStorm 2017.2.4 doesn't support TypeScript 2.6 (API was broken). This problem was fixed in WebStorm 2017.2.5.

See also: https://blog.jetbrains.com/webstorm/2017/10/webstorm-2017-2-5/

Body:
I'm using WebStorm 2017.2.4 with Angular 4.3 - TypeScript doesn't show errors :

Question

How can I see real time inspections ? immediately ?

(I've already tried invalidating and clear cache).

configuration :

ts.config.json file :

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "noEmitHelpers": true,
        "noEmitOnError": true,
        "lib": [
            "dom",
            "es6",
            "es2015.iterable"
        ],
        "baseUrl": ".",
        "paths": {
            "*": [
                "./node_modules/tns-core-modules/*",
                "./node_modules/*"
            ]
        }
    },
    "exclude": [
        "node_modules",
        "platforms",
        "**/*.aot.ts"
    ]
}


问:
How do I explain to the user of my class the expected type of one of its attributes?
I'm developing a class in Python, in which one of its attributes is supposed to represent a neural network. I would like this attribute to actually be an instance of another class, let's call it NN, with several methods (like train() for training, predict() for prediction, etc.). Furthermore, I thought a reasonable way to initialize this attribute was by using my class' constructor, which would expect an instance of the NN class as one of its arguments.

My first thought on how to solve this was to implement an interface, and then type check whatever it is that the user supplies to my class constructor, in order to make sure it is from the expected NN class. However, it seems like neither interfaces (1) nor typechecking (2, 3, 4, 5) are good practices in Python.

Instead, we're supposed to use Duck typing, and simply try using the objects methods until we can't (i.e. defer type checking to runtime). However, in my case the NN class might be quite complicated, with several methods and attributes. If I do discard the interface idea, and simply expect the user of my class to provide an object with all the necessary methods and attributes, how will he/she know what is expected of this object? Should I write all this information in my class docstring, in my constructor docstring, or somewhere else? Or is there a better way to solve this scenario?

答: As of Python 3.5 you can use type hints. This documents the expected type to the user and enables optional off-line type checking.</p>


问:
Node.js and Request.js: Finding the file extension for a download?
I'm trying to download a couple of files using request, but I don't know how to find what their extensions are. Some of them are images, some are sounds, some are videos, but all of them come from a URL with no extension at the end.

```<code>const request = require("request");

request.get({
    url: "http://example.com/unknownextension",
})
.on("error", function(error) {
    console.log(error);
})
.pipe(fs.createWriteStream("files/what.extension"));
</code>```

When you go on this website, it downloads just fine. Think of something like Google Drive links.

I can't open any of these files unless they have a valid extension, so I'd appreciate some help.

答:
File Type npm will solve your purpose.

npm install file-type

```<code>const fileType = require('file-type');
http.get(url, res => {
res.once('data', chunk => {
    res.destroy();
    console.log(fileType(chunk));
    //=> {ext: 'One of the supported file types', mime: 'The MIME type'}
});});
</code>```

Body:
I'm trying to download a couple of files using request, but I don't know how to find what their extensions are. Some of them are images, some are sounds, some are videos, but all of them come from a URL with no extension at the end.

const request = require("request");

request.get({
    url: "http://example.com/unknownextension",
})
.on("error", function(error) {
    console.log(error);
})
.pipe(fs.createWriteStream("files/what.extension"));

When you go on this website, it downloads just fine. Think of something like Google Drive links.

I can't open any of these files unless they have a valid extension, so I'd appreciate some help.

Body:
File Type npm will solve your purpose.

npm install file-type

const fileType = require('file-type');
http.get(url, res => {
res.once('data', chunk => {
    res.destroy();
    console.log(fileType(chunk));
    //=> {ext: 'One of the supported file types', mime: 'The MIME type'}
});});


问:
Start service on Android O irrespective of app is running or not
I am building an app which will be connected to a bean device (which gives accelerometer reading) via Bluetooth. I have to read the accelerometer readings every 20 secs irrespective of the app is running or not. Also based on those readings, I need to send the notification to the user. I think I have following options for this:

JobScheduler with startForegroundService method: Does it take care of Doze mode also?

Alarm Manager

Which options should I use to read the readings every 20 secs? Is there any better option?

BeanAPI doc: http://punchthrough.github.io/bean-sdk-android/

答: I think your best bet is AlarmManager. Use a background Service as a foreground Service seems like an overkill for your situation. Implement an AlarmManager that checks on your Service periodically if it's running or has been killed and restarts it if latter is the case.


问:
How to restrict buffering in video steaming in android
I want to restrict buffering after pausing a video in android. When I pause the video player, the video stops but buffering does not. It continues to consume data. I want to stop data to be consumed.
Thanks in advance.</p>

答: You can't skip buffering it depends on the network</p>


问:
SAS: What's the optimal way to find the sum of a column by another column?
I want to find out the best way to perform a group-by in SAS so I can perform some benchmarks. The simplest two ways I can think of is Proc SQL and Proc means. Here is the example in proc sql

    proc sql noprint; /* took 6 mins */
    create table summ as select
            id,
            sum(val)
        from
            randint
        group by
            id
        ;
    quit;

I think there are ways to make this run fast

use sasfile command to load the data into memory first

create an index on id

Are there any other options I can use? Any SAS options I should turn on to make this run as fast as possible? I am not tied to proc sql nor proc means, so if there are faster ways then I would love to know about it!!!

My set up code is as below

```<code>options macrogen;
options obs=max sortsize=max source2 FULLSTIMER;
options minoperator SASTRACE=',,,d' SASTRACELOC=SASLOG;
options compress = binary NOSTSUFFIX;
options noxwait noxsync;
options LRECL=32767;

proc fcmp outlib=work.myfunc.sample;
    function RandBetween(min, max);
        return (min + floor((1 + max - min) * rand("uniform")));
    endsub;
run;

options cmplib=work.myfunc;

data RandInt;
    do i = 1 to 250000000;
        id = RandBetween(1, 2500000);
        val = rand("uniform");
        output;
    end;
    drop i;
run;
</code>```

My SAS comparison macros are as below

```<code>%macro sasbench(dosql = N); %macro _; %mend;
    %if &dosql. = Y %then %do;
        proc sql noprint; /* took 6 mins */
            create table summ as select
                id,
                sum(val)
            from
                randint
            group by
                id
            ;
        quit;
    %end;

    proc means data=randint  sum noprint;
        var val ;
        class id;
        output out = summmeans(drop=_type_ _freq_) sum = /autoname;
    run;
%mend;

%sasbench();
/**/
/*sasfile randint load;*/
/*%sasbench();*/
/*sasfile randint close;*/

proc datasets lib=work;
    modify randint;
    INDEX CREATE id / nomiss;
run;

%sasbench();
</code>```

答:
sasfile is only a benefit if the entire data set can fit into session ram limits and if the data set is going to be used more than once.  I suppose this would make sense if your benchmark includes multiple runs / different techniques on the same sasfile.

An index on id would help if the data was unsorted by id.  When the data set is presorted by id the id column metadata will have sortedby flag set which a procedure can use for its own internal optimization, however there is no guarantee.  As for indexes, use option msglevel=i to get informational messages in the log about index selection during processing.

The fastest way is direct addressing, but requires enough ram to handle the largest id value as an array index:

array ids(250000000) _temporary_

ids(id) + value

The next fastest way is probably hand coded array based hashing:

search SAS conference proceedings for papers by Paul Dorfman

The next fastest hash way is probably the hash component object with key suminc.

DATA Step was edited to align with the comments

```<code>data demo_data;
  do rownum = 1 to 1000;
    id = ceil(100*ranuni(123));     * NOTE: 100 different groups, disordered;
    value = ceil(1000*ranuni(123)); * NOTE: want to sum value over group, for demonstration individual values integers from 1..1000;
    output;
  end;
run;

data _null_;
  if 0 then set demo_data(keep=id value);                         %* prep pdv ;
  length total 8;                                                 %* prep keysum variable ;
  call missing (total);                                           %* prevent warnings ;
  declare hash ids (ordered:'a', suminc:'value', keysum:'total'); %* ordered ensures keys will be sorted ascending upon output ;
  ids.defineKey('id');
 *ids.defineData('id');                                           % * not having a defineData is an implicit way of adding only the keys as data, only data + keysum variables are .output;
  ids.defineDone();

  * read all records and touch each hash key in order to perform tacit total+value summation;
  do until (end);
    set demo_data end=end;
    if ids.find() ne 0 then ids.add();
  end;

  ids.output(dataset:'sum_value_over_id'); * save the summation of each key combination;
  stop;
run;
</code>```

Note: There can be only one keysum variable.

If the suminc variable was set to be always 1 instead of value, then the keysum would be the count instead of the total.

Obtaining both sum and count over group via hash would require an explicit defineData for a count and sum variable and slightly different statements, such as:

```<code>declare hash ids (ordered:'a');
...
ids.defineData('id', 'count', 'total');
...
    if ids.find() ne 0 then do; count=0; total=0; end;
    count+1;
    total+value;
    ids.replace();
...
</code>```

However, if value is known to be always a natural number, and group size is known to be < 10group size limit you could numerically encode the count by using a suminc of value + 10-group size limit and numerically decode count by processing the output data with count = (total - int(total)) * 10group size limit.

For sorted data the fastest way is most likely a DOW loop with accumulation.

```<code>proc sort data=foo;
  by id;
data sum_value_over_id_v2(keep=id total);
  do until (last.id);
    set foo;
    by id;
    total = sum(total, value);
  end;
run;
</code>```

You will likely find that I/O is largest component of performance.

Body:
I want to find out the best way to perform a group-by in SAS so I can perform some benchmarks. The simplest two ways I can think of is Proc SQL and Proc means. Here is the example in proc sql

    proc sql noprint; /* took 6 mins */
    create table summ as select
            id,
            sum(val)
        from
            randint
        group by
            id
        ;
    quit;

I think there are ways to make this run fast

use sasfile command to load the data into memory first

create an index on id

Are there any other options I can use? Any SAS options I should turn on to make this run as fast as possible? I am not tied to proc sql nor proc means, so if there are faster ways then I would love to know about it!!!

My set up code is as below

options macrogen;
options obs=max sortsize=max source2 FULLSTIMER;
options minoperator SASTRACE=',,,d' SASTRACELOC=SASLOG;
options compress = binary NOSTSUFFIX;
options noxwait noxsync;
options LRECL=32767;

proc fcmp outlib=work.myfunc.sample;
    function RandBetween(min, max);
        return (min + floor((1 + max - min) * rand("uniform")));
    endsub;
run;

options cmplib=work.myfunc;

data RandInt;
    do i = 1 to 250000000;
        id = RandBetween(1, 2500000);
        val = rand("uniform");
        output;
    end;
    drop i;
run;

My SAS comparison macros are as below

%macro sasbench(dosql = N); %macro _; %mend;
    %if &dosql. = Y %then %do;
        proc sql noprint; /* took 6 mins */
            create table summ as select
                id,
                sum(val)
            from
                randint
            group by
                id
            ;
        quit;
    %end;

    proc means data=randint  sum noprint;
        var val ;
        class id;
        output out = summmeans(drop=_type_ _freq_) sum = /autoname;
    run;
%mend;

%sasbench();
/**/
/*sasfile randint load;*/
/*%sasbench();*/
/*sasfile randint close;*/

proc datasets lib=work;
    modify randint;
    INDEX CREATE id / nomiss;
run;

%sasbench();

Body:
sasfile is only a benefit if the entire data set can fit into session ram limits and if the data set is going to be used more than once.  I suppose this would make sense if your benchmark includes multiple runs / different techniques on the same sasfile.

An index on id would help if the data was unsorted by id.  When the data set is presorted by id the id column metadata will have sortedby flag set which a procedure can use for its own internal optimization, however there is no guarantee.  As for indexes, use option msglevel=i to get informational messages in the log about index selection during processing.

The fastest way is direct addressing, but requires enough ram to handle the largest id value as an array index:

array ids(250000000) _temporary_

ids(id) + value

The next fastest way is probably hand coded array based hashing:

search SAS conference proceedings for papers by Paul Dorfman

The next fastest hash way is probably the hash component object with key suminc.

DATA Step was edited to align with the comments

data demo_data;
  do rownum = 1 to 1000;
    id = ceil(100*ranuni(123));     * NOTE: 100 different groups, disordered;
    value = ceil(1000*ranuni(123)); * NOTE: want to sum value over group, for demonstration individual values integers from 1..1000;
    output;
  end;
run;

data _null_;
  if 0 then set demo_data(keep=id value);                         %* prep pdv ;
  length total 8;                                                 %* prep keysum variable ;
  call missing (total);                                           %* prevent warnings ;
  declare hash ids (ordered:'a', suminc:'value', keysum:'total'); %* ordered ensures keys will be sorted ascending upon output ;
  ids.defineKey('id');
 *ids.defineData('id');                                           % * not having a defineData is an implicit way of adding only the keys as data, only data + keysum variables are .output;
  ids.defineDone();

  * read all records and touch each hash key in order to perform tacit total+value summation;
  do until (end);
    set demo_data end=end;
    if ids.find() ne 0 then ids.add();
  end;

  ids.output(dataset:'sum_value_over_id'); * save the summation of each key combination;
  stop;
run;

Note: There can be only one keysum variable.

If the suminc variable was set to be always 1 instead of value, then the keysum would be the count instead of the total.

Obtaining both sum and count over group via hash would require an explicit defineData for a count and sum variable and slightly different statements, such as:

declare hash ids (ordered:'a');
...
ids.defineData('id', 'count', 'total');
...
    if ids.find() ne 0 then do; count=0; total=0; end;
    count+1;
    total+value;
    ids.replace();
...

However, if value is known to be always a natural number, and group size is known to be < 10group size limit you could numerically encode the count by using a suminc of value + 10-group size limit and numerically decode count by processing the output data with count = (total - int(total)) * 10group size limit.

For sorted data the fastest way is most likely a DOW loop with accumulation.

proc sort data=foo;
  by id;
data sum_value_over_id_v2(keep=id total);
  do until (last.id);
    set foo;
    by id;
    total = sum(total, value);
  end;
run;

You will likely find that I/O is largest component of performance.


问:
using both onTouch and onClick on a button in android
I have a Button that whenever the user clicks it, it increases the number in my EditText, but i want to have an onTouch method that when the user keeps their finger on the button the number increases with more speed(continuously), something like the backspace, that when you click it, it deleted just one letter and when you keep it down, it deletes the words faster, so i have both ontouch and onclick in my code, but whenever i click the button only onTouch triggers, what should i do? can anybody help, please? I have searched a lot but couldn't find anything that helps me

Here is part of my code

```<code>     btnFineUp.setOnTouchListener (this);
            btnFineUp.setOnClickListener (this);

    @override
            public void onClick (View view)
        {
            switch (view.getId ())
            {
                case R.id.btn_fine_up:

                {
                    View     v = findViewById (getCurrentFocus ().getId ());
                    EditText editText;

                    if (v instanceof EditText)
                    {
                        editText = (EditText) v;
                    }
                    else
                    {
                        return;
                    }
                    int calcStateAmp   = +1;

                     if (view.getId () == R.id.btn_fine_up)
                    {
                        calcState_2 = upAndDown.getFineUpAmp () * calcStateAmp;

                        calcStateAmp = calcState_2;

                    }
                    double currentValue;
                    if (StringUtils.isNullOrEmpty (editText.getText ().toString ()))
                    {
                        currentValue = 0;
                    }
                    else
                    {
                        currentValue = Double.parseDouble (editText.getText ().toString ());
                    }
                    switch (getCurrentFocus ().getId ())
                    {
                        case R.id.txt_va1_a:
                        case R.id.txt_va2_a:
                        case R.id.txt_va3_a:
                        case R.id.txt_vb1_a:

                            editText.setText (String.format (Locale.ENGLISH, "%.2f", currentValue + (0.01 * calcStateAmp)));
                            break;
    }

        @Override
        public boolean onTouch (View view, MotionEvent motionEvent)
        {
                switch (view.getId ())
                {
                    case ir.vebko.R.id.btn_fine_up:

                    {
                        View     v = findViewById (getCurrentFocus ().getId ());
                        EditText editText;

                        if (v instanceof EditText)
                        {
                            editText = (EditText) v;
                        }
                        else
                        {
                            return false;
                        }
                        int calcStateAmp   = +1;

             if (view.getId () == R.id.btn_fine_up)
                        {
                            calcStateAmp = calcState_2;

                        }
                        double currentValue;
                        if (StringUtils.isNullOrEmpty (editText.getText ().toString ()))
                        {
                            currentValue = 0;
                        }
                        else
                        {
                            currentValue = Double.parseDouble (editText.getText ().toString ());
                        }

                        switch (getCurrentFocus ().getId ())
                        {
                            case ir.vebko.R.id.txt_va1_a:
                            case ir.vebko.R.id.txt_va2_a:
                            case ir.vebko.R.id.txt_va3_a:
                            case ir.vebko.R.id.txt_vb1_a:

                                editText.setText (String.format (Locale.ENGLISH, "%.2f", currentValue + (0.01 * calcStateAmp)));
                                break;
    }
return true;
}
</code>```

答:
OnTouch itself handles the click user action for OnClick as well. Thus, a click user action raises an OnTouch event first; only when there is no listener listening to OnTouch does it invoke the OnClick event. Since you have an OnTouchListener associated with the OnTouch event, there is no way your OnClickListener will be invoked.  For more details, look at this question.

From your question, it seems that you can skip View.OnTouchListener altogether and instead implement both View.OnLongClickListener and View.OnClickListener.

Hope that helps.

Body:
I have a Button that whenever the user clicks it, it increases the number in my EditText, but i want to have an onTouch method that when the user keeps their finger on the button the number increases with more speed(continuously), something like the backspace, that when you click it, it deleted just one letter and when you keep it down, it deletes the words faster, so i have both ontouch and onclick in my code, but whenever i click the button only onTouch triggers, what should i do? can anybody help, please? I have searched a lot but couldn't find anything that helps me

Here is part of my code

     btnFineUp.setOnTouchListener (this);
            btnFineUp.setOnClickListener (this);

    @override
            public void onClick (View view)
        {
            switch (view.getId ())
            {
                case R.id.btn_fine_up:

                {
                    View     v = findViewById (getCurrentFocus ().getId ());
                    EditText editText;

                    if (v instanceof EditText)
                    {
                        editText = (EditText) v;
                    }
                    else
                    {
                        return;
                    }
                    int calcStateAmp   = +1;

                     if (view.getId () == R.id.btn_fine_up)
                    {
                        calcState_2 = upAndDown.getFineUpAmp () * calcStateAmp;

                        calcStateAmp = calcState_2;

                    }
                    double currentValue;
                    if (StringUtils.isNullOrEmpty (editText.getText ().toString ()))
                    {
                        currentValue = 0;
                    }
                    else
                    {
                        currentValue = Double.parseDouble (editText.getText ().toString ());
                    }
                    switch (getCurrentFocus ().getId ())
                    {
                        case R.id.txt_va1_a:
                        case R.id.txt_va2_a:
                        case R.id.txt_va3_a:
                        case R.id.txt_vb1_a:

                            editText.setText (String.format (Locale.ENGLISH, "%.2f", currentValue + (0.01 * calcStateAmp)));
                            break;
    }

        @Override
        public boolean onTouch (View view, MotionEvent motionEvent)
        {
                switch (view.getId ())
                {
                    case ir.vebko.R.id.btn_fine_up:

                    {
                        View     v = findViewById (getCurrentFocus ().getId ());
                        EditText editText;

                        if (v instanceof EditText)
                        {
                            editText = (EditText) v;
                        }
                        else
                        {
                            return false;
                        }
                        int calcStateAmp   = +1;

             if (view.getId () == R.id.btn_fine_up)
                        {
                            calcStateAmp = calcState_2;

                        }
                        double currentValue;
                        if (StringUtils.isNullOrEmpty (editText.getText ().toString ()))
                        {
                            currentValue = 0;
                        }
                        else
                        {
                            currentValue = Double.parseDouble (editText.getText ().toString ());
                        }

                        switch (getCurrentFocus ().getId ())
                        {
                            case ir.vebko.R.id.txt_va1_a:
                            case ir.vebko.R.id.txt_va2_a:
                            case ir.vebko.R.id.txt_va3_a:
                            case ir.vebko.R.id.txt_vb1_a:

                                editText.setText (String.format (Locale.ENGLISH, "%.2f", currentValue + (0.01 * calcStateAmp)));
                                break;
    }
return true;
}


问:
Dynamically Sorting with LINQ
I have a collection of CLR objects. The class definition for the object has three properties: FirstName, LastName, BirthDate.

I have a string that reflects the name of the property the collection should be sorted by. In addition, I have a sorting direction. How do I dynamically apply this sorting information to my collection? Please note that sorting could be multi-layer, so for instance I could sort by LastName, and then by FirstName.

Currently, I'm trying the following without any luck:

```<code>var results = myCollection.OrderBy(sortProperty);
</code>```

However, I'm getting a message that says:

... does not contain a defintion for 'OrderBy'  and the best extension method overload ... has some invalid arguments.

答:
You will need to use reflection to get the PropertyInfo, and then use that to build an expression tree. Something like this:</p>

```<code>var entityType = typeof(TEntity);
var prop = entityType.GetProperty(sortProperty);
var param = Expression.Parameter(entityType, "x");
var access = Expression.Lambda(Expression.MakeMemberAccess(param, prop), param);

var ordered = (IOrderedQueryable<TEntity>) Queryable.OrderBy(
    myCollection,
    (dynamic) access);
</code>```

Title: Dynamically Sorting with LINQ

Body:
I have a collection of CLR objects. The class definition for the object has three properties: FirstName, LastName, BirthDate.

I have a string that reflects the name of the property the collection should be sorted by. In addition, I have a sorting direction. How do I dynamically apply this sorting information to my collection? Please note that sorting could be multi-layer, so for instance I could sort by LastName, and then by FirstName.

Currently, I'm trying the following without any luck:

var results = myCollection.OrderBy(sortProperty);

However, I'm getting a message that says:

... does not contain a defintion for 'OrderBy'  and the best extension method overload ... has some invalid arguments.

Body:
You will need to use reflection to get the PropertyInfo, and then use that to build an expression tree. Something like this:

var entityType = typeof(TEntity);
var prop = entityType.GetProperty(sortProperty);
var param = Expression.Parameter(entityType, "x");
var access = Expression.Lambda(Expression.MakeMemberAccess(param, prop), param);

var ordered = (IOrderedQueryable<TEntity>) Queryable.OrderBy(
    myCollection,
    (dynamic) access);


问:
Redefine protocol functions using constraints without having to expose method

Ugly 1

```<code>protocol Persisting {
    func persist()
}

extension Persisting {
    func persist() { print("persisting") }
}

protocol Service {
    func get()
    func persistIfAble() // If I remove this, "Not able to persist" gets printed twice
}

extension Service {
    func get() {
        persistIfAble()
    }
}

extension Service {
    func persistIfAble() {
        print("Not able to persist")
    }
}

extension Service where Self: Persisting {
    func persistIfAble() {
        persist()
    }
}

struct OnlyService: Service {}
struct Both: Service, Persisting {}

let both = Both()
both.get()

let onlyService = OnlyService()
onlyService.get()
print("Can now directly call `persistIfAble` which is not wanted")
onlyService.persistIfAble() // DONT WANT THIS TO BE POSSIBLE
</code>```

This solution would be elegant if I could remove func persistIfAble() from protocol declaration. Because I do not want it to be exposed. However, what is really interesting is that if I remove it, then the behavior changes, then the implementation inside extension Service where Self: Persisting never gets called.

Ugly 2

```<code>protocol Persisting {
    func persist()
}

extension Persisting {
    func persist() { print("persisting") }
}

protocol Service {
    func get()
}

extension Service {
    func get() {
        // Ugly solution, I do not want to cast, `Service` should not have to know about `Persisting`
        if let persisting = self as? Persisting {
            persisting.persist()
        } else {
            print("not able to persist")
        }
    }
}

extension Service where Self: Persisting {
    func persistIfAble() {
        persist()
    }
}

struct OnlyService: Service {}
struct Both: Service, Persisting {}

let both = Both()
both.get()

let onlyService = OnlyService()
onlyService.get()
</code>```

The code in both ugly solutions is of course an extremely simplified version of my actual scenario, where I really do not want to perform casts, because it makes the code so much more difficult to read. Even if I would change if let to guard let.

Ugly 3 (ugliest?)

```<code>protocol Persisting {
    func persist()
}

extension Persisting {
    func persist() { print("persisting") }
}

protocol Service {
    func get()
    func persistIfAble(allowed: Bool)
}

extension Service {
    func get() {
        persistIfAble(allowed: true)
    }
}

extension Service {
    func persistIfAble(allowed: Bool = false) {
        guard allowed else { print("KILL APP"); return }
        print("Not able to persist")
    }
}

extension Service where Self: Persisting {
    func persistIfAble(allowed: Bool = false) {
        guard allowed else { print("BREAKING RULES"); return }
        persist()
    }
}

struct OnlyService: Service {}
struct Both: Service, Persisting {}

let both = Both()
both.get()

let onlyService = OnlyService()
onlyService.get()
print("Can now directly call `persistIfAble` which is not wanted")
// DONT WANT THIS TO BE POSSIBLE
onlyService.persistIfAble() // prints: "KILL APP"
</code>```

What am I missing?

Where is the beautiful solution?

答:
How about removing one level of indirection (i.e. 'persistIfAble')?</p>

```<code>protocol Persisting {
    func persist()
}

extension Persisting {
    func persist() {
        print("persisting")
    }
}

protocol Service {
    func get()
}

extension Service where Self: Persisting {
    func get() {
        persist()
    }
}

extension Service {
    func get() {
        print("Not able to persist")
    }
}
</code>```

Body:
Ugly 1

protocol Persisting {
    func persist()
}

extension Persisting {
    func persist() { print("persisting") }
}

protocol Service {
    func get()
    func persistIfAble() // If I remove this, "Not able to persist" gets printed twice
}

extension Service {
    func get() {
        persistIfAble()
    }
}

extension Service {
    func persistIfAble() {
        print("Not able to persist")
    }
}

extension Service where Self: Persisting {
    func persistIfAble() {
        persist()
    }
}

struct OnlyService: Service {}
struct Both: Service, Persisting {}

let both = Both()
both.get()

let onlyService = OnlyService()
onlyService.get()
print("Can now directly call `persistIfAble` which is not wanted")
onlyService.persistIfAble() // DONT WANT THIS TO BE POSSIBLE

This solution would be elegant if I could remove func persistIfAble() from protocol declaration. Because I do not want it to be exposed. However, what is really interesting is that if I remove it, then the behavior changes, then the implementation inside extension Service where Self: Persisting never gets called.

Ugly 2

protocol Persisting {
    func persist()
}

extension Persisting {
    func persist() { print("persisting") }
}

protocol Service {
    func get()
}

extension Service {
    func get() {
        // Ugly solution, I do not want to cast, `Service` should not have to know about `Persisting`
        if let persisting = self as? Persisting {
            persisting.persist()
        } else {
            print("not able to persist")
        }
    }
}

extension Service where Self: Persisting {
    func persistIfAble() {
        persist()
    }
}

struct OnlyService: Service {}
struct Both: Service, Persisting {}

let both = Both()
both.get()

let onlyService = OnlyService()
onlyService.get()

The code in both ugly solutions is of course an extremely simplified version of my actual scenario, where I really do not want to perform casts, because it makes the code so much more difficult to read. Even if I would change if let to guard let.

Ugly 3 (ugliest?)

protocol Persisting {
    func persist()
}

extension Persisting {
    func persist() { print("persisting") }
}

protocol Service {
    func get()
    func persistIfAble(allowed: Bool)
}

extension Service {
    func get() {
        persistIfAble(allowed: true)
    }
}

extension Service {
    func persistIfAble(allowed: Bool = false) {
        guard allowed else { print("KILL APP"); return }
        print("Not able to persist")
    }
}

extension Service where Self: Persisting {
    func persistIfAble(allowed: Bool = false) {
        guard allowed else { print("BREAKING RULES"); return }
        persist()
    }
}

struct OnlyService: Service {}
struct Both: Service, Persisting {}

let both = Both()
both.get()

let onlyService = OnlyService()
onlyService.get()
print("Can now directly call `persistIfAble` which is not wanted")
// DONT WANT THIS TO BE POSSIBLE
onlyService.persistIfAble() // prints: "KILL APP"

What am I missing?

Where is the beautiful solution?

Body:
How about removing one level of indirection (i.e. 'persistIfAble')?

protocol Persisting {
    func persist()
}

extension Persisting {
    func persist() {
        print("persisting")
    }
}

protocol Service {
    func get()
}

extension Service where Self: Persisting {
    func get() {
        persist()
    }
}

extension Service {
    func get() {
        print("Not able to persist")
    }
}


问:
Angular 2: how to implement image map area
I am trying to implement image map area in Angular 2, as the example (in Angular JS)
http://plnkr.co/edit/5bfNEQxqPfzZxuBJOSWm?p=preview

What I have done:

product.component.html

```<code><div class="row“>
  <div id="image_map">
    <map name="map_example">
      <area shape="poly" coords="0.847,0.885, 1.133,0.669, 1.451,1.085, 1.176,1.225" ng-click="selectPart(546)">
      <area shape="poly" coords="1.171,0.604, 1.548,0.416, 1.813,0.988, 1.511,1.052" ng-click="selectPart(547)">
    </map>
    <img src="../../../assets/images/map_product_1_part.png" alt="image map example" width=557 height=441 usemap="#map_example">
  </div>
</div>
</code>```

product.component.ts

```<code>…
selectPart(part: number)
{
     console.log("click on" + part);
}
</code>```

Result: image areas are not detected or clickable.

I know code and logic should be different in Angular 2, but I am quite new with this, any suggestion is very appreciated.

答:
There is no ng-click attribute in angular2.

use (click) or on-click instead

Plunker Example

Body:
I am trying to implement image map area in Angular 2, as the example (in Angular JS)
http://plnkr.co/edit/5bfNEQxqPfzZxuBJOSWm?p=preview

What I have done:

product.component.html

    <map name="map_example">
      <area shape="poly" coords="0.847,0.885, 1.133,0.669, 1.451,1.085, 1.176,1.225" ng-click="selectPart(546)">
      <area shape="poly" coords="1.171,0.604, 1.548,0.416, 1.813,0.988, 1.511,1.052" ng-click="selectPart(547)">
    </map>

product.component.ts

…
selectPart(part: number)
{
     console.log("click on" + part);
}

Result: image areas are not detected or clickable.

I know code and logic should be different in Angular 2, but I am quite new with this, any suggestion is very appreciated.


问:
Enzyme - Test if a nested component is correctly rendered
I'm trying to test if within my parent component its child component is correctly rendered when the state is updated through a simple boolean value. Below the parent component :

```<code>class Parent extends Component {
  ...
  render() {
    const { ..., isReady } = this.state;
    const props = { ... };

    return(
      <div className="container page-content">

        { isReady ?
          <Child {...props} />
          :
          <div id="loader-wrapper">
            <div id="loader"></div>
          </div>
        }

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

My test is :

```<code>beforeEach(() => {
      wrapper = mount(<Parent isReady={true}/>);
    });

it('Should render Child component', () => {
      expect(wrapper.prop('isReady')).to.equal(true); // Working !!
      expect(wrapper.find(Child).length).to.equal(1); // Not Working -> equal 0
    });
</code>```

So far I double checked if the state is correctly changed, and it seems to be true when I check the wrapper's state of isReady. I'm pretty sure this part is working fine.

Also I tried wrapper.html() and even if isReady is true, I can see only the div part with my loader. The Child component which should be a <form>..</form> is never rendered. So If I try something like : expect(wrapper.find('form').length).to.equal(1); it's not working neither. I don't get why.

What should be the best practice here to test my parent behaviour and see if my child component inside is correctly rendered ?

update:

1/ I've been through console.log(wrapper), I can see the isReady is definitely true, but the only part rendered is the div with the loader. The nested component Child is never rendered. I have no idea why.. as I'm using mount and the prop/state is correctly set.

2/ From what I can see it's the { isReady ? ... } which is the problem because I'm doing a similar test in another component where I test if a parent component contains a nested component but this time there is no condition and it's working fine.

答:
You should import the component in your test file and pass that instance to the find function rather than a string

```<code>import Child from 'path/to/child';
expect(wrapper.find(Child).length).to.equal(1);
</code>```

Check this article on how to write the selectors:

Also the result in this condition will still could be false since when you create a mounted instance of your parent you are not setting the isReady state if its already not initialised to true

In order to set the state of the test component use setState

```<code>wrapper.setState({ isReady: true });
</code>```

Body:
I'm trying to test if within my parent component its child component is correctly rendered when the state is updated through a simple boolean value. Below the parent component :

class Parent extends Component {
  ...
  render() {
    const { ..., isReady } = this.state;
    const props = { ... };

    return(

        { isReady ?
          <Child {...props} />
          :

        }

    );
  }
}

My test is :

beforeEach(() => {
      wrapper = mount(<Parent isReady={true}/>);
    });

it('Should render Child component', () => {
      expect(wrapper.prop('isReady')).to.equal(true); // Working !!
      expect(wrapper.find(Child).length).to.equal(1); // Not Working -> equal 0
    });

So far I double checked if the state is correctly changed, and it seems to be true when I check the wrapper's state of isReady. I'm pretty sure this part is working fine.

Also I tried wrapper.html() and even if isReady is true, I can see only the div part with my loader. The Child component which should be a <form>..</form> is never rendered. So If I try something like : expect(wrapper.find('form').length).to.equal(1); it's not working neither. I don't get why.

What should be the best practice here to test my parent behaviour and see if my child component inside is correctly rendered ?

update:

1/ I've been through console.log(wrapper), I can see the isReady is definitely true, but the only part rendered is the div with the loader. The nested component Child is never rendered. I have no idea why.. as I'm using mount and the prop/state is correctly set.

2/ From what I can see it's the { isReady ? ... } which is the problem because I'm doing a similar test in another component where I test if a parent component contains a nested component but this time there is no condition and it's working fine.

Body:
You should import the component in your test file and pass that instance to the find function rather than a string

import Child from 'path/to/child';
expect(wrapper.find(Child).length).to.equal(1);

Check this article on how to write the selectors:

Also the result in this condition will still could be false since when you create a mounted instance of your parent you are not setting the isReady state if its already not initialised to true

In order to set the state of the test component use setState

wrapper.setState({ isReady: true });


问:
Return Zip File from ZipOutputStream in Java
I have a function which creates a Zip file from a list of files. Is it possible to return the Zip file without it being saved on the disk? I need the file as I have to use the zip file as a parameter for another function. I am not sure of the ByteStream would be an option for me.

```<code>public File compressFileList(List<File> fileList,String fileName) {
    FileOutputStream fileOutputStream=null;
    ZipOutputStream zipOutputStream=null;
    FileInputStream fileInputStream=null;
    String compressedFileName=fileName +".zip";
    if(fileList.isEmpty())
        return null;
    try
    {
        fileOutputStream =  new FileOutputStream(compressedFileName);
        zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputStream));
        for (File file: fileList) {
            fileInputStream = new FileInputStream(file);
            ZipEntry zipEntry =  new ZipEntry(file.getName());
            zipOutputStream.putNextEntry(zipEntry);
            byte[] tmp = new byte[4*1024];
            int size = 0;
            while((size = fileInputStream.read(tmp)) != -1){
                zipOutputStream.write(tmp, 0, size);
            }
            zipOutputStream.flush();
            fileInputStream.close();
        }
        zipOutputStream.close();
        return compressedFile; //This is what I am missing

    }
    catch (FileNotFoundException e)
    {

    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
</code>```

EDIT : adding the use case

The idea is to create a zip file and use the CreateClassifierOptions method of VisualRecognition Service of Watson.

```<code>classifierOptions = new CreateClassifierOptions.Builder()
            .classifierName("Santa")
            .addClass("Santa", new File("C:\\app\\GitRepo\\images\\beagle.zip"))
            .negativeExamples(new File("C:\\app\\GitRepo\\images\\nosport.zip"))
            .build();
</code>```

The builder accepts the zip file as the parameter.

Understanding

Based on the explanation from Alexandre Dupriez, I think it is better to store the file at some place on the hard disk.

答:
You should be able to use a ByteArrayOutputStream instead of a FileOutputStream:

```<code>zipOutputStream = new ZipOutputStream(new ByteArrayOutputStream());
</code>```

The difficulty here is to provide a File to the method consuming the zip file. The java.io.File does not provide an abstraction which allows you to manipulate in-memory files.

The java.io.File abstraction and java.io.FileInputStream implementation

To simplify, if we had to boil down what the File abstraction is, we would see it as a URI. And therefore, to be able to build an in-memory File, or at least mimic it, we would need to provide an URI which would then be used by the consumer of the File to read its content.

If we look at the FileInputStream which the consumer is likely to use, we can see that it always ends up with a native call which gives us to possibility whatsoever to abstract a FileSystem for in-memory files:

```<code>// class java.io.FileInputStream
/**
 * Opens the specified file for reading.
 * @param name the name of the file
 */
private native void open0(String name) throws FileNotFoundException;
</code>```

It would be easier if there was a possibility to adapt the consumer to accept an InputStream, but from your problem statement I guess this is not possible.

API call

Your requirement is to provide a File to the Watson Visual API.
Could you please provide the API method you need to call?

Body:
I have a function which creates a Zip file from a list of files. Is it possible to return the Zip file without it being saved on the disk? I need the file as I have to use the zip file as a parameter for another function. I am not sure of the ByteStream would be an option for me.

public File compressFileList(List<File> fileList,String fileName) {
    FileOutputStream fileOutputStream=null;
    ZipOutputStream zipOutputStream=null;
    FileInputStream fileInputStream=null;
    String compressedFileName=fileName +".zip";
    if(fileList.isEmpty())
        return null;
    try
    {
        fileOutputStream =  new FileOutputStream(compressedFileName);
        zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputStream));
        for (File file: fileList) {
            fileInputStream = new FileInputStream(file);
            ZipEntry zipEntry =  new ZipEntry(file.getName());
            zipOutputStream.putNextEntry(zipEntry);
            byte[] tmp = new byte[4*1024];
            int size = 0;
            while((size = fileInputStream.read(tmp)) != -1){
                zipOutputStream.write(tmp, 0, size);
            }
            zipOutputStream.flush();
            fileInputStream.close();
        }
        zipOutputStream.close();
        return compressedFile; //This is what I am missing

    }
    catch (FileNotFoundException e)
    {

    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

EDIT : adding the use case

The idea is to create a zip file and use the CreateClassifierOptions method of VisualRecognition Service of Watson.

classifierOptions = new CreateClassifierOptions.Builder()
            .classifierName("Santa")
            .addClass("Santa", new File("C:\\app\\GitRepo\\images\\beagle.zip"))
            .negativeExamples(new File("C:\\app\\GitRepo\\images\\nosport.zip"))
            .build();

The builder accepts the zip file as the parameter.

Understanding

Based on the explanation from Alexandre Dupriez, I think it is better to store the file at some place on the hard disk.

Body:
You should be able to use a ByteArrayOutputStream instead of a FileOutputStream:

zipOutputStream = new ZipOutputStream(new ByteArrayOutputStream());

The difficulty here is to provide a File to the method consuming the zip file. The java.io.File does not provide an abstraction which allows you to manipulate in-memory files.

The java.io.File abstraction and java.io.FileInputStream implementation

To simplify, if we had to boil down what the File abstraction is, we would see it as a URI. And therefore, to be able to build an in-memory File, or at least mimic it, we would need to provide an URI which would then be used by the consumer of the File to read its content.

If we look at the FileInputStream which the consumer is likely to use, we can see that it always ends up with a native call which gives us to possibility whatsoever to abstract a FileSystem for in-memory files:

// class java.io.FileInputStream
/**
 * Opens the specified file for reading.
 * @param name the name of the file
 */
private native void open0(String name) throws FileNotFoundException;

It would be easier if there was a possibility to adapt the consumer to accept an InputStream, but from your problem statement I guess this is not possible.

API call

Your requirement is to provide a File to the Watson Visual API.
Could you please provide the API method you need to call?


问:
Angular 1 - Compile ng-if condition into string
I have this string :

```<code>this.badge = `<span class="badge">{{ notification}}</span>`
</code>```

to interpret the {{ notification}} expression I do :

```<code>this.badge = this.$interpolate(this.badge)(this)
</code>```

What i would like to do now is to add an ng-if in the span element :

```<code>this.badge = `<span ng-if="notification > 0"class="badge">{{ notification}}</span>`
</code>```

But the $interpolate service does not support this, how can I "compile" the condition of ng-if ?

答:
you can to use local scope:

```<code>this.badge = '<span ng-if="'+(scope.notification > 0)+'" class="badge">'+scope.notification+'</span>';
</code>```

Body:
I have this string :

this.badge = `<span class="badge">{{ notification}}</span>`

to interpret the {{ notification}} expression I do :

this.badge = this.$interpolate(this.badge)(this)

What i would like to do now is to add an ng-if in the span element :

this.badge = `<span ng-if="notification > 0"class="badge">{{ notification}}</span>`

But the $interpolate service does not support this, how can I "compile" the condition of ng-if ?

Body:
you can to use local scope:

this.badge = '<span ng-if="'+(scope.notification > 0)+'" class="badge">'+scope.notification+'</span>';


问:
cURL returning XML or JSON
I've got a form say here - http://example.com/palreg.php

Once people register I'll be sending them an email with the link that will allow them to edit their details (I know it's a crazy way of doing things, but I am working on someone else's code so don't mind) for instance the url as such http://example.com/palreg.php?paliD=1234, and when they go to that page the form will be populated with their information so that they can make changes.

Now the problem is that the DB is in a different site and the information has to be passed to that site to perform a select action, to do so I use cURL to send the information like so

```<code>$url = "http://example2.com/processXML.php";
$xmlStr will be like this

<table>tab_name</table>
<action>select</action>
<palid>1234</palid>

$ch=curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, 'xmlstr='.$xmlStr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$data = curl_exec($ch);
</code>```

On the other end (http://example2.com/processXML.php) I convert the xml to an array and perform the query to select pal information based on the id sent.

The real question now is how do I send the retrieved pal information (as xml or json or array) back so that i can populate the form with the returned data.

Also can I do a return $dataArray; in processXML.php and be able to grab it?

OK to make things a bit clearer, what I do in processXML.php is
retrieve the result set and do this

```<code>print json_encode($resultArray);
</code>```

not should I print or return

Thank you, and do let me know if things aren't clear.

答: When you pull the information from the database and process it in processXML.php, add the results to an array, use json_encode() to convert the array to JSON, and then echo the results to the page.</p>

Title: cURL returning XML or JSON

Body:
I've got a form say here - http://example.com/palreg.php

Once people register I'll be sending them an email with the link that will allow them to edit their details (I know it's a crazy way of doing things, but I am working on someone else's code so don't mind) for instance the url as such http://example.com/palreg.php?paliD=1234, and when they go to that page the form will be populated with their information so that they can make changes.

Now the problem is that the DB is in a different site and the information has to be passed to that site to perform a select action, to do so I use cURL to send the information like so

$url = "http://example2.com/processXML.php";
$xmlStr will be like this

tab_name

<action>select</action>
<palid>1234</palid>

$ch=curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, 'xmlstr='.$xmlStr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$data = curl_exec($ch);

On the other end (http://example2.com/processXML.php) I convert the xml to an array and perform the query to select pal information based on the id sent.

The real question now is how do I send the retrieved pal information (as xml or json or array) back so that i can populate the form with the returned data.

Also can I do a return $dataArray; in processXML.php and be able to grab it?

OK to make things a bit clearer, what I do in processXML.php is
retrieve the result set and do this

print json_encode($resultArray);

not should I print or return

Thank you, and do let me know if things aren't clear.


问:
Symfony2 doctrine update schema from specific entity
If I run

```<code>php app/console doctrine:schema:update --force
</code>```

It will update my database from all entities.

I need to update database only for the User entity, what is the solution?

One solution is to define a custom entity manager and then pass that entity manager to

```<code>php app/console doctrine:schema:update --force --em="custom"
</code>```

But maybe it exists something faster without defining a custom entity manager?

答:
You can manually use the Doctrine SchemaTool class to generate an SQL diff based only on a single entity. You’ll need access to Doctrine’s EntityManager – the example below assumes access to Symfony’s container.

```<code>use Doctrine\ORM\Tools\SchemaTool;

$em = $this->container->get('doctrine')->getManager();
$schemaTool = new SchemaTool($em);
$metadata = $em->getClassMetadata(YourEntity::class);
$sqlDiff = $schemaTool->getUpdateSchemaSql([$metadata], true);
</code>```

The variable $sqlDiff will now contain an array of SQL statements that are needed to bring the database schema up to date with your entity mapping.

The second argument passed to SchemaTool::getUpdateSchemaSql() is important – without it, the default behaviour would be to generate DROP TABLE statements for every other table that appears in your database.

ContentLicense: CC BY-SA 4.0

Body:
If I run

php app/console doctrine:schema:update --force

It will update my database from all entities.

I need to update database only for the User entity, what is the solution?

One solution is to define a custom entity manager and then pass that entity manager to

php app/console doctrine:schema:update --force --em="custom"

But maybe it exists something faster without defining a custom entity manager?

Body:
You can manually use the Doctrine SchemaTool class to generate an SQL diff based only on a single entity. You’ll need access to Doctrine’s EntityManager – the example below assumes access to Symfony’s container.

use Doctrine\ORM\Tools\SchemaTool;

$em = $this->container->get('doctrine')->getManager();
$schemaTool = new SchemaTool($em);
$metadata = $em->getClassMetadata(YourEntity::class);
$sqlDiff = $schemaTool->getUpdateSchemaSql([$metadata], true);

The variable $sqlDiff will now contain an array of SQL statements that are needed to bring the database schema up to date with your entity mapping.

The second argument passed to SchemaTool::getUpdateSchemaSql() is important – without it, the default behaviour would be to generate DROP TABLE statements for every other table that appears in your database.


问:
How can I get the Face ID system icon programatically?
Is there a way to get this icon programatically?

In some way like this:

```<code>[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(someAction)];
</code>```

I've checked the Icons and Images section in iOS Human Interface Guidelines, but I don't see it anywhere.

答:
Apple does not encourage the usage of system icons to identify system authentication features.

From iOS Human Interface Guidelines:

Don't use icons to identify system authentication features. When people see icons that look like the system's Touch ID (thumbprint) and Face ID icons, they think they're supposed to authenticate. Using icons to identify authentication features creates inconsistency and causes confusion, especially when the icons are colorized, displayed at a large size, and presented out of context.

This basically means that there is no way to access the icon with a public API.

Body:
Is there a way to get this icon programatically?

In some way like this:

[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(someAction)];

I've checked the Icons and Images section in iOS Human Interface Guidelines, but I don't see it anywhere.


问:
Select nested sublist of a list based on condition in R
I do have the following simple example of a nested list:

```<code>list(list(structure(list(group = "a", def = "control"), .Names =  c("group",
"def"))), list(structure(list(group = "b", def = "disease1"), .Names = c("group",
"def"))))
</code>```

The structure is as follows:

```<code>str(t1)
List of 2
$ :List of 1
..$ :List of 2
.. ..$ group: chr "a"
.. ..$ def  : chr "control"
$ :List of 1
..$ :List of 2
.. ..$ group: chr "b"
.. ..$ def  : chr "disease1"
</code>```

Is there an easy way of getting only the nested list that satisfies a specific condition. As an example, if I knew only the name of the group, e.g., "a", how would I get the according sublist; in the example, this would be the first nested list:

```<code>[[1]]
[[1]]$group
[1] "a"

[[1]]$def
[1] "control"
</code>```

So essentially I am looking for a way to apply group == "a" in this nested list structure.

答:
We can convert to tibble and then with map create a logical vector to subset the 'lst'

```<code>library(purrr)
library(magrittr)
library(tibble)
lst %>%
      map_lgl(., ~map_lgl(., ~as.tibble(.) %>%
      .$group=='a')) %>%
       extract(lst, .) %>%
       .[[1]]
#[[1]]
#[[1]]$group
#[1] "a"

#[[1]]$def
#[1] "control"
</code>```

Or use the modify_depth

```<code>lst %>%
     modify_depth(., 2, ~as.tibble(.)[['group']]=='a') %>%
     unlist %>%
     extract(lst, .)
</code>```

Here, we assume that the position of 'group' can change in the list.

Body:
I do have the following simple example of a nested list:

list(list(structure(list(group = "a", def = "control"), .Names =  c("group",
"def"))), list(structure(list(group = "b", def = "disease1"), .Names = c("group",
"def"))))

The structure is as follows:

str(t1)
List of 2
$ :List of 1
..$ :List of 2
.. ..$ group: chr "a"
.. ..$ def  : chr "control"
$ :List of 1
..$ :List of 2
.. ..$ group: chr "b"
.. ..$ def  : chr "disease1"

Is there an easy way of getting only the nested list that satisfies a specific condition. As an example, if I knew only the name of the group, e.g., "a", how would I get the according sublist; in the example, this would be the first nested list:

[[1]]
[[1]]$group
[1] "a"

[[1]]$def
[1] "control"

So essentially I am looking for a way to apply group == "a" in this nested list structure.

Body:
We can convert to tibble and then with map create a logical vector to subset the 'lst'

library(purrr)
library(magrittr)
library(tibble)
lst %>%
      map_lgl(., ~map_lgl(., ~as.tibble(.) %>%
      .$group=='a')) %>%
       extract(lst, .) %>%
       .[[1]]
#[[1]]
#[[1]]$group
#[1] "a"

#[[1]]$def
#[1] "control"

Or use the modify_depth

lst %>%
     modify_depth(., 2, ~as.tibble(.)[['group']]=='a') %>%
     unlist %>%
     extract(lst, .)

Here, we assume that the position of 'group' can change in the list.


问:
How to add an action to a UIAlertView button using Swift iOS
I want to add another button other than the "OK" button which should just dismiss the alert.
I want the other button to call a certain function.

```<code>var logInErrorAlert: UIAlertView = UIAlertView()
logInErrorAlert.title = "Ooops"
logInErrorAlert.message = "Unable to log in."
logInErrorAlert.addButtonWithTitle("Ok")
</code>```

How do I add another button to this alert, and then allow it to call a function once clicks so lets say we want the new button to call:

```<code> retry()
</code>```

答:
Swift 4 Update

```<code>        // Create the alert controller
        let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)

        // Create the actions
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
            UIAlertAction in
            NSLog("OK Pressed")
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
            UIAlertAction in
            NSLog("Cancel Pressed")
        }

        // Add the actions
        alertController.addAction(okAction)
        alertController.addAction(cancelAction)

        // Present the controller
        self.present(alertController, animated: true, completion: nil)
</code>```

Body:
I want to add another button other than the "OK" button which should just dismiss the alert.
I want the other button to call a certain function.

var logInErrorAlert: UIAlertView = UIAlertView()
logInErrorAlert.title = "Ooops"
logInErrorAlert.message = "Unable to log in."
logInErrorAlert.addButtonWithTitle("Ok")

How do I add another button to this alert, and then allow it to call a function once clicks so lets say we want the new button to call:

 retry()

Body:
Swift 4 Update

        // Create the alert controller
        let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)

        // Create the actions
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
            UIAlertAction in
            NSLog("OK Pressed")
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
            UIAlertAction in
            NSLog("Cancel Pressed")
        }

        // Add the actions
        alertController.addAction(okAction)
        alertController.addAction(cancelAction)

        // Present the controller
        self.present(alertController, animated: true, completion: nil)