问:
Placing the cursor at the beginning of a MaskedTextBox vb.net from a separate class
I have a class that creates the controls:

```<code>Overrides Sub createControls()
    _GlobalCounter = 0
    Dim lblName As New Label
    lblName.Text = "Store Name"
    Dim txtName As New MaskedTextBox
    txtName.Mask = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    txtName.Text = name
    addControl(lblName, txtName)
    '  txtName.SelectionStart = txtName.Text.Length()
    '  txtName.SelectionLength = 0
    '  txtName.SelectionStart = 0
    '  txtName.SelectionLength = 0

        addEntityControls()
End Sub
</code>```

I have a dynamic form that calls those controls using the following method:

```<code> Public Function returnEditorControls() As Control()
        createControls()
        Return _Controls
    End Function
</code>```

In the form itself:

```<code>Public Sub loadEditor()
    Dim controlCount As Integer = 0
    createControls()
    tlpMain.Controls.Clear()
    tlpMain.ColumnStyles.Clear()
    tlpMain.RowStyles.Clear()
    tlpMain.ColumnCount = _ColumnCount
    Dim intControls As Integer = myControls.Length()
    Dim intTotalRows As Integer = intControls / _ColumnCount
    If (intControls Mod _ColumnCount) > 0 Then
        intTotalRows += 1
    End If
    tlpMain.RowCount = intTotalRows
    For row = 0 To intTotalRows - 1
        tlpMain.RowStyles.Add(New RowStyle(SizeType.Percent, 100 / tlpMain.RowCount()))
        For column = 0 To _ColumnCount - 1
            If controlCount < intControls Then
                tlpMain.Controls.Add(myControls(controlCount), column, row)
                controlCount += 1
            End If
        Next
    Next
End Sub
</code>```

My problem is that the dynamically created controls will not place the cursor at the beginning of the MaskedTextBox. I attempted the ways commented out, and they did not work. Alternatively, if the textbox is full, I want the cursor at the end of the text. I cannot make the cursor do anything but stay where it is clicked.

答:
With some help, here was the final answer.</p>

```<code>  Public Function returnEditorControls() As Control()
        createControls()
        For Each mtb As MaskedTextBox In _Controls.OfType(Of MaskedTextBox)
            AddHandler mtb.Click, AddressOf fixMTBCursor
        Next
        Return _Controls
    End Function

Public Sub fixMTBCursor(sender As Object, e As EventArgs)
    If TypeOf sender Is MaskedTextBox Then
        Dim txt As MaskedTextBox = DirectCast(sender, MaskedTextBox)
        If txt.SelectionStart > txt.Text.Length Then
            txt.Select(txt.Text.Length, 0)
        End If
    End If
End Sub
</code>```

Body:
I have a class that creates the controls:

Overrides Sub createControls()
    _GlobalCounter = 0
    Dim lblName As New Label
    lblName.Text = "Store Name"
    Dim txtName As New MaskedTextBox
    txtName.Mask = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    txtName.Text = name
    addControl(lblName, txtName)
    '  txtName.SelectionStart = txtName.Text.Length()
    '  txtName.SelectionLength = 0
    '  txtName.SelectionStart = 0
    '  txtName.SelectionLength = 0

        addEntityControls()
End Sub

I have a dynamic form that calls those controls using the following method:

 Public Function returnEditorControls() As Control()
        createControls()
        Return _Controls
    End Function

In the form itself:

Public Sub loadEditor()
    Dim controlCount As Integer = 0
    createControls()
    tlpMain.Controls.Clear()
    tlpMain.ColumnStyles.Clear()
    tlpMain.RowStyles.Clear()
    tlpMain.ColumnCount = _ColumnCount
    Dim intControls As Integer = myControls.Length()
    Dim intTotalRows As Integer = intControls / _ColumnCount
    If (intControls Mod _ColumnCount) > 0 Then
        intTotalRows += 1
    End If
    tlpMain.RowCount = intTotalRows
    For row = 0 To intTotalRows - 1
        tlpMain.RowStyles.Add(New RowStyle(SizeType.Percent, 100 / tlpMain.RowCount()))
        For column = 0 To _ColumnCount - 1
            If controlCount < intControls Then
                tlpMain.Controls.Add(myControls(controlCount), column, row)
                controlCount += 1
            End If
        Next
    Next
End Sub

My problem is that the dynamically created controls will not place the cursor at the beginning of the MaskedTextBox. I attempted the ways commented out, and they did not work. Alternatively, if the textbox is full, I want the cursor at the end of the text. I cannot make the cursor do anything but stay where it is clicked.

Body:
With some help, here was the final answer.

  Public Function returnEditorControls() As Control()
        createControls()
        For Each mtb As MaskedTextBox In _Controls.OfType(Of MaskedTextBox)
            AddHandler mtb.Click, AddressOf fixMTBCursor
        Next
        Return _Controls
    End Function

Public Sub fixMTBCursor(sender As Object, e As EventArgs)
    If TypeOf sender Is MaskedTextBox Then
        Dim txt As MaskedTextBox = DirectCast(sender, MaskedTextBox)
        If txt.SelectionStart > txt.Text.Length Then
            txt.Select(txt.Text.Length, 0)
        End If
    End If
End Sub


来源: stackexchange

问:
Python/Pandas: For loop to sum moving range and append to new column
I am fairly new to Python and Pandas so please forgive the uninformed question I'm posing here.

I have a dataframe (QReport) that looks like so:

```<code>DATE            STATE       SALES
2010-12-01       AL          10
2010-12-02       AL          13
2010-12-03       AL          16
2010-12-04       AL          10
2010-12-05       AL          10
2010-12-06       AL          2
2010-12-07       AL          5
2010-12-08       AL          5
</code>```

I'd like to create a seven day sales total column that sums seven day slices of sales and adds that total to a new '7DTotal' column. I've been trying to get at this through a for loop, setting x and y variables as 0 (zero) and 6 indexes which I try to increment each run through the loop:

```<code>x = 0
y = 6
for i in QReport:
    QReport['7DTotal'] = sum(QReport['SALES'][x:y])
    x = x + 1
    y = y + 1
</code>```

This approach, however, is not working and is returning the same value for every row in the newly-added 7DTotal column.

Expected output would be:

```<code>DATE            STATE       SALES   7DTotal
2010-12-01       AL          10        0
2010-12-02       AL          13        0
2010-12-03       AL          16        0
2010-12-04       AL          10        0
2010-12-05       AL          10        0
2010-12-06       AL          2         0
2010-12-07       AL          5         66
2010-12-08       AL          5         61
</code>```

Thanks in advance for any help!

答:
an easy solution would be

```<code>7_day_list = []

for index in QReport.

    avg = np.mean(QReport.loc[index:index+7, 'SALES'])

    7_day_list.append(avg)
</code>```

hope that helps

ContentLicense: CC BY-SA 3.0

Body:
I am fairly new to Python and Pandas so please forgive the uninformed question I'm posing here.

I have a dataframe (QReport) that looks like so:

DATE            STATE       SALES
2010-12-01       AL          10
2010-12-02       AL          13
2010-12-03       AL          16
2010-12-04       AL          10
2010-12-05       AL          10
2010-12-06       AL          2
2010-12-07       AL          5
2010-12-08       AL          5

I'd like to create a seven day sales total column that sums seven day slices of sales and adds that total to a new '7DTotal' column. I've been trying to get at this through a for loop, setting x and y variables as 0 (zero) and 6 indexes which I try to increment each run through the loop:

x = 0
y = 6
for i in QReport:
    QReport['7DTotal'] = sum(QReport['SALES'][x:y])
    x = x + 1
    y = y + 1

This approach, however, is not working and is returning the same value for every row in the newly-added 7DTotal column.

Expected output would be:

DATE            STATE       SALES   7DTotal
2010-12-01       AL          10        0
2010-12-02       AL          13        0
2010-12-03       AL          16        0
2010-12-04       AL          10        0
2010-12-05       AL          10        0
2010-12-06       AL          2         0
2010-12-07       AL          5         66
2010-12-08       AL          5         61

Thanks in advance for any help!

Body:
an easy solution would be

7_day_list = []

for index in QReport.

    avg = np.mean(QReport.loc[index:index+7, 'SALES'])

    7_day_list.append(avg)

hope that helps


问:
Navigating from Platform Specific (UWP) PageRenderer and back to PCL Page

I have a MainPage in PCL which then navigates to a Platform Specific
Login Page on LoginButton Click Event

The LoginPage is inherited from
platform specific PageRenderer as it needs platform specific
Authentication to Social Providers (Facebook, Google, Twitter,
Microsoft, etc.)

I am using Xamarin.Auth to do the authentication.

Inside the OnElementChanged event of the LoginPage, it instantiates
the OAuth2Authenticator object.

Upon successful instantiation (based
on provider and app details), it needs to call the UI of the specific
provider.

To do that, I call the auth.GetUI where auth is
Xamarin.Auth.OAuth2Authenticator object.

I have two questions:

In UWP, how do I navigate to the provider login UI? More specifically, what is the equivalent in UWP of the following code snippets in iOS and Android? In iOS, the following code is used:
PresentViewController(auth.GetUI(), true, null);
where auth is Xamarin.Auth.OAuth2Authenticator object.
In Android the following is used:
activity.StartActivity(auth.GetUI(activity));

I am looking for the equivalent code in UWP. Please bear in mind that these calls are made from the LoginPage which is derived from Platform specific PageRenderer

How do I navigate back to my MainPage (which is in PCL) upon successful authentication?

The code is based off of a sample from the following source:
http://www.c-sharpcorner.com/article/oauth-login-authenticating-with-identity-provider-in-xamarin-forms/

Here is my code for the LoginPage:

```<code>using System;
using Valufy;
using Xamarin.Forms.Platform.UWP;
using System.ComponentModel;
using Valufy.UWP;
using Valufy.AuthConfiguration;
using Xamarin.Forms;
[assembly: ExportRenderer(typeof(ProviderLoginPage), typeof(LoginRenderer))]

namespace Valufy.UWP
{
class LoginRenderer: PageRenderer
{
protected override void OnElementChanged (ElementChangedEventArgs<Xamarin.Forms.Page> e)
{
    base.OnElementChanged(e);

    //Get and Assign ProviderName from ProviderLoginPage
    ProviderLoginPage loginPage = (ProviderLoginPage)Element;
    string providername = loginPage.ProviderName;

        //Create OauthProviderSetting class with Oauth Implementation .Refer Step 6
        OAuthProviderSetting oauth = new OAuthProviderSetting();

            Xamarin.Auth.OAuth2Authenticator auth = oauth.LoginWithProvider(providername);

            // After facebook,google and all identity provider login completed
            auth.Completed += Auth_Completed;

            Type page_type = auth.GetUI();
//////THIS IS WHERE I AM STUCK...HOW DO I GO TO THE PROVIDER AUTH UI ////////////

//this.Frame.Navigate(page_type, auth);
//parentPage.Navigation.PushModalAsync(auth.GetUI());

            }

    }

    private void Auth_Completed(object sender, Xamarin.Auth.AuthenticatorCompletedEventArgs e)
    {
        if (e.IsAuthenticated)
        {
            OAuthConfig.User = new UserDetails();
            // Get and Save User Details
            OAuthConfig.User.Token = e.Account.Properties["oauth_token"];
            OAuthConfig.User.TokenSecret = e.Account.Properties["oauth_token_secret"];
            OAuthConfig.User.TwitterId = e.Account.Properties["user_id"];
        OAuthConfig.User.ScreenName = e.Account.Properties["screen_name"];

/////NOW, HOW GO I GO BACK TO THE CALLING PAGE IN PCL ///////////////////

    }
    else
    {
        // The user cancelled
/////NOW, HOW GO I GO BACK TO THE CALLING PAGE IN PCL ///////////////////
}
}
}
}
</code>```

答:
Here is the code to navigate to the provider login for UWP:
                        WindowsPage windowsPage = new WindowsPage();

```<code>                _frame = windowsPage.Frame;
                if (_frame == null)
                {
                    _frame = new Windows.UI.Xaml.Controls.Frame
                    {
                        Language = global::Windows.Globalization.ApplicationLanguages.Languages[0]
                    };
                    windowsPage.Content = _frame;
                    SetNativeControl(windowsPage);
                }

                Type pageType = auth.GetUI();
                _frame.Navigate(pageType, auth);
</code>```

To navigate back to my page upon successful authentication, here is the code:

```<code>private async void Auth_Completed(object sender, Xamarin.Auth.AuthenticatorCompletedEventArgs e)
    {
        if (e.IsAuthenticated)
        {

            var request = new OAuth2Request("GET", new Uri("https://login.microsoftonline.com/common/oauth2/V2.0/token?oauth2_access_token=" + e.Account.Properties["access_token"]), null, e.Account);
            try
            {
                string response = await MSGetUserInfo(e.Account);

            }
            catch (System.OperationCanceledException)
            {
                                }
            catch (Exception ex)
            {
                                }
            this.Element.Navigation.PushModalAsync(new MainPage());

        }
        else
        {
            // The user cancelled
        }
    }
</code>```

Body:
I have a MainPage in PCL which then navigates to a Platform Specific
Login Page on LoginButton Click Event

The LoginPage is inherited from
platform specific PageRenderer as it needs platform specific
Authentication to Social Providers (Facebook, Google, Twitter,
Microsoft, etc.)

I am using Xamarin.Auth to do the authentication.

Inside the OnElementChanged event of the LoginPage, it instantiates
the OAuth2Authenticator object.

Upon successful instantiation (based
on provider and app details), it needs to call the UI of the specific
provider.

To do that, I call the auth.GetUI where auth is
Xamarin.Auth.OAuth2Authenticator object.

I have two questions:

In UWP, how do I navigate to the provider login UI? More specifically, what is the equivalent in UWP of the following code snippets in iOS and Android? In iOS, the following code is used:
PresentViewController(auth.GetUI(), true, null);
where auth is Xamarin.Auth.OAuth2Authenticator object.
In Android the following is used:
activity.StartActivity(auth.GetUI(activity));

I am looking for the equivalent code in UWP. Please bear in mind that these calls are made from the LoginPage which is derived from Platform specific PageRenderer

How do I navigate back to my MainPage (which is in PCL) upon successful authentication?

The code is based off of a sample from the following source:
http://www.c-sharpcorner.com/article/oauth-login-authenticating-with-identity-provider-in-xamarin-forms/

Here is my code for the LoginPage:

using System;
using Valufy;
using Xamarin.Forms.Platform.UWP;
using System.ComponentModel;
using Valufy.UWP;
using Valufy.AuthConfiguration;
using Xamarin.Forms;
[assembly: ExportRenderer(typeof(ProviderLoginPage), typeof(LoginRenderer))]

namespace Valufy.UWP
{
class LoginRenderer: PageRenderer
{
protected override void OnElementChanged (ElementChangedEventArgs<Xamarin.Forms.Page> e)
{
    base.OnElementChanged(e);

    //Get and Assign ProviderName from ProviderLoginPage
    ProviderLoginPage loginPage = (ProviderLoginPage)Element;
    string providername = loginPage.ProviderName;

        //Create OauthProviderSetting class with Oauth Implementation .Refer Step 6
        OAuthProviderSetting oauth = new OAuthProviderSetting();

            Xamarin.Auth.OAuth2Authenticator auth = oauth.LoginWithProvider(providername);

            // After facebook,google and all identity provider login completed
            auth.Completed += Auth_Completed;

            Type page_type = auth.GetUI();
//////THIS IS WHERE I AM STUCK...HOW DO I GO TO THE PROVIDER AUTH UI ////////////

//this.Frame.Navigate(page_type, auth);
//parentPage.Navigation.PushModalAsync(auth.GetUI());

            }

    }

    private void Auth_Completed(object sender, Xamarin.Auth.AuthenticatorCompletedEventArgs e)
    {
        if (e.IsAuthenticated)
        {
            OAuthConfig.User = new UserDetails();
            // Get and Save User Details
            OAuthConfig.User.Token = e.Account.Properties["oauth_token"];
            OAuthConfig.User.TokenSecret = e.Account.Properties["oauth_token_secret"];
            OAuthConfig.User.TwitterId = e.Account.Properties["user_id"];
        OAuthConfig.User.ScreenName = e.Account.Properties["screen_name"];

/////NOW, HOW GO I GO BACK TO THE CALLING PAGE IN PCL ///////////////////

    }
    else
    {
        // The user cancelled
/////NOW, HOW GO I GO BACK TO THE CALLING PAGE IN PCL ///////////////////
}
}
}
}

Body:
Here is the code to navigate to the provider login for UWP:
                        WindowsPage windowsPage = new WindowsPage();

                _frame = windowsPage.Frame;
                if (_frame == null)
                {
                    _frame = new Windows.UI.Xaml.Controls.Frame
                    {
                        Language = global::Windows.Globalization.ApplicationLanguages.Languages[0]
                    };
                    windowsPage.Content = _frame;
                    SetNativeControl(windowsPage);
                }

                Type pageType = auth.GetUI();
                _frame.Navigate(pageType, auth);

To navigate back to my page upon successful authentication, here is the code:

private async void Auth_Completed(object sender, Xamarin.Auth.AuthenticatorCompletedEventArgs e)
    {
        if (e.IsAuthenticated)
        {

            var request = new OAuth2Request("GET", new Uri("https://login.microsoftonline.com/common/oauth2/V2.0/token?oauth2_access_token=" + e.Account.Properties["access_token"]), null, e.Account);
            try
            {
                string response = await MSGetUserInfo(e.Account);

            }
            catch (System.OperationCanceledException)
            {
                                }
            catch (Exception ex)
            {
                                }
            this.Element.Navigation.PushModalAsync(new MainPage());

        }
        else
        {
            // The user cancelled
        }
    }


问:
how do i print values in nested json array using node.js?
i have this json array.

```<code>[ { '0': { msg: 'helloworld1' } }, { '0': { msg: 'helloworld2' } } ]
</code>```

and here I'm trying to console log the value of every msg by doing this.

```<code>jsonArray.forEach(function(element) {
    console.log(element);
    console.log(element['0']);
});
</code>```

output

```<code>{ '0': { msg: 'helloworld1' } }
{ '0': { msg: 'helloworld2' } }

undefined
undefined
</code>```

the question is, how do i print out the values of msg keys and why is it returning undefined?

答:
Try to parse the data again as following:

```<code>var jsonArray = [ { '0': { msg: 'helloworld1' } }, { '0': { msg: 'helloworld2' } } ]
jsonArray = JSON.parse(JSON.stringify(jsonArray));
jsonArray.forEach(function(element) {
  console.log(element['0'].msg);
});
</code>```

This JSON.stringify should convert the data to string then JSON.parse will convert it to JS Object.

Body:
i have this json array.

[ { '0': { msg: 'helloworld1' } }, { '0': { msg: 'helloworld2' } } ]

and here I'm trying to console log the value of every msg by doing this.

jsonArray.forEach(function(element) {
    console.log(element);
    console.log(element['0']);
});

output

{ '0': { msg: 'helloworld1' } }
{ '0': { msg: 'helloworld2' } }

undefined
undefined

the question is, how do i print out the values of msg keys and why is it returning undefined?

Body:
Try to parse the data again as following:

var jsonArray = [ { '0': { msg: 'helloworld1' } }, { '0': { msg: 'helloworld2' } } ]
jsonArray = JSON.parse(JSON.stringify(jsonArray));
jsonArray.forEach(function(element) {
  console.log(element['0'].msg);
});

This JSON.stringify should convert the data to string then JSON.parse will convert it to JS Object.


问:
SQL Server 2008: How to find trailing spaces
How can I find all column values in a column which have trailing spaces? For leading spaces it would simply be </p>

```<code>select col from table where substring(col,1,1) = ' ';
</code>```

答:
There's a few different ways to do this...

My favorite option, assuming your intention is to remove any leading and / or trailing spaces, is to execute the following, which will dynamically create the T-SQL to UPDATE all columns with an unwanted space to their trimmed value:

```<code>SELECT
'UPDATE [<DatabaseName>].[dbo].['+TABLE_NAME+']
SET ['+COLUMN_NAME+']=LTRIM(RTRIM(['+COLUMN_NAME+']))
WHERE ['+COLUMN_NAME+']=LTRIM(RTRIM(['+COLUMN_NAME+']));'+CHAR(13)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE '<TableName>%'
    AND DATA_TYPE!='date'
ORDER BY TABLE_NAME,COLUMN_NAME
</code>```

If you really need to identify them though, try one of these queries:

```<code>SELECT *
FROM [database].[schema].[table]
WHERE [col1]!=LTRIM(RTRIM([col1]))
</code>```

More dynamic SQL:

```<code>SELECT 'SELECT ''['+TABLE_NAME+'].['+COLUMN_NAME+']'',*
FROM [<your database name>].[dbo].['+TABLE_NAME+']
WHERE ['+COLUMN_NAME+'] LIKE ''% ''
    OR ['+COLUMN_NAME+'] LIKE '' %'';
GO
'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE '<filter table name as desired>%'
    AND DATA_TYPE!='date'
</code>```

ContentLicense: CC BY-SA 2.5

Body:
How can I find all column values in a column which have trailing spaces? For leading spaces it would simply be

select col from table where substring(col,1,1) = ' ';

Body:
There's a few different ways to do this...

My favorite option, assuming your intention is to remove any leading and / or trailing spaces, is to execute the following, which will dynamically create the T-SQL to UPDATE all columns with an unwanted space to their trimmed value:

SELECT
'UPDATE [<DatabaseName>].[dbo].['+TABLE_NAME+']
SET ['+COLUMN_NAME+']=LTRIM(RTRIM(['+COLUMN_NAME+']))
WHERE ['+COLUMN_NAME+']=LTRIM(RTRIM(['+COLUMN_NAME+']));'+CHAR(13)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE '<TableName>%'
    AND DATA_TYPE!='date'
ORDER BY TABLE_NAME,COLUMN_NAME

If you really need to identify them though, try one of these queries:

SELECT *
FROM [database].[schema].[table]
WHERE [col1]!=LTRIM(RTRIM([col1]))

More dynamic SQL:

SELECT 'SELECT ''['+TABLE_NAME+'].['+COLUMN_NAME+']'',*
FROM [<your database name>].[dbo].['+TABLE_NAME+']
WHERE ['+COLUMN_NAME+'] LIKE ''% ''
    OR ['+COLUMN_NAME+'] LIKE '' %'';
GO
'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE '<filter table name as desired>%'
    AND DATA_TYPE!='date'


问:
org.apache.camel.CamelExecutionException: Exception occurred during execution on the exchange
I am New to Apache Camel integration with the alfresco activiti, I am getting below error while running below program.

Exception

```<code>Exception in thread "main" org.apache.camel.CamelExecutionException: Exception occurred during execution on the exchange: Exchange[ID-Ravi-59907-1467728441130-0-2]
        at org.apache.camel.util.ObjectHelper.wrapCamelExecutionException(ObjectHelper.java:1706)
        at org.apache.camel.util.ExchangeHelper.extractResultBody(ExchangeHelper.java:660)
        at org.apache.camel.impl.DefaultProducerTemplate.extractResultBody(DefaultProducerTemplate.java:471)
        at org.apache.camel.impl.DefaultProducerTemplate.sendBody(DefaultProducerTemplate.java:133)
        at org.apache.camel.impl.DefaultProducerTemplate.sendBody(DefaultProducerTemplate.java:149)
        at org.apache.camel.impl.DefaultProducerTemplate.requestBody(DefaultProducerTemplate.java:301)
        at org.quick.AppMain.main(AppMain.java:32)
    Caused by: org.activiti.engine.ActivitiException: Couldn't serialize value '[DefaultMessageHistory[routeId=route1, node=setProperty1], DefaultMessageHistory[routeId=route1, node=setBody1]]' in variable 'CamelMessageHistory'
        at org.activiti.engine.impl.variable.SerializableType.serialize(SerializableType.java:95)
        at org.activiti.engine.impl.variable.SerializableType.setValue(SerializableType.java:69)
        at org.activiti.engine.impl.persistence.entity.VariableInstanceEntity.setValue(VariableInstanceEntity.java:178)
        at org.activiti.engine.impl.persistence.entity.VariableInstanceEntity.create(VariableInstanceEntity.java:74)
        at org.activiti.engine.impl.persistence.entity.VariableInstanceEntity.createAndInsert(VariableInstanceEntity.java:60)
        at org.activiti.engine.impl.persistence.entity.VariableScopeImpl.createVariableInstance(VariableScopeImpl.java:839)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.createVariableInstance(ExecutionEntity.java:1175)
        at org.activiti.engine.impl.persistence.entity.VariableScopeImpl.createVariableLocal(VariableScopeImpl.java:752)
        at org.activiti.engine.impl.persistence.entity.VariableScopeImpl.createVariableLocal(VariableScopeImpl.java:739)
        at org.activiti.engine.impl.persistence.entity.VariableScopeImpl.setVariable(VariableScopeImpl.java:633)
        at org.activiti.engine.impl.persistence.entity.VariableScopeImpl.setVariable(VariableScopeImpl.java:590)
        at org.activiti.engine.impl.persistence.entity.VariableScopeImpl.setVariables(VariableScopeImpl.java:534)
        at org.activiti.camel.CamelBehaviour.execute(CamelBehaviour.java:45)
        at org.activiti.engine.impl.delegate.ActivityBehaviorInvocation.invoke(ActivityBehaviorInvocation.java:34)
        at org.activiti.engine.impl.delegate.DelegateInvocation.proceed(DelegateInvocation.java:37)
        at org.activiti.engine.impl.delegate.DefaultDelegateInterceptor.handleInvocation(DefaultDelegateInterceptor.java:25)
        at org.activiti.engine.impl.bpmn.behavior.ServiceTaskDelegateExpressionActivityBehavior.execute(ServiceTaskDelegateExpressionActivityBehavior.java:98)
        at org.activiti.engine.impl.pvm.runtime.AtomicOperationActivityExecute.execute(AtomicOperationActivityExecute.java:60)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerStart.eventNotificationsCompleted(AtomicOperationTransitionNotifyListenerStart.java:52)
        at org.activiti.engine.impl.pvm.runtime.AbstractEventAtomicOperation.execute(AbstractEventAtomicOperation.java:56)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.pvm.runtime.AbstractEventAtomicOperation.execute(AbstractEventAtomicOperation.java:49)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionCreateScope.execute(AtomicOperationTransitionCreateScope.java:49)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerTake.execute(AtomicOperationTransitionNotifyListenerTake.java:80)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionDestroyScope.execute(AtomicOperationTransitionDestroyScope.java:116)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerEnd.eventNotificationsCompleted(AtomicOperationTransitionNotifyListenerEnd.java:35)
        at org.activiti.engine.impl.pvm.runtime.AbstractEventAtomicOperation.execute(AbstractEventAtomicOperation.java:56)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.pvm.runtime.AbstractEventAtomicOperation.execute(AbstractEventAtomicOperation.java:49)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.take(ExecutionEntity.java:453)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.take(ExecutionEntity.java:431)
        at org.activiti.engine.impl.bpmn.behavior.BpmnActivityBehavior.performOutgoingBehavior(BpmnActivityBehavior.java:140)
        at org.activiti.engine.impl.bpmn.behavior.BpmnActivityBehavior.performDefaultOutgoingBehavior(BpmnActivityBehavior.java:66)
        at org.activiti.engine.impl.bpmn.behavior.FlowNodeActivityBehavior.leave(FlowNodeActivityBehavior.java:44)
        at org.activiti.engine.impl.bpmn.behavior.FlowNodeActivityBehavior.execute(FlowNodeActivityBehavior.java:36)
        at org.activiti.engine.impl.pvm.runtime.AtomicOperationActivityExecute.execute(AtomicOperationActivityExecute.java:60)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.pvm.runtime.AtomicOperationProcessStartInitial.eventNotificationsCompleted(AtomicOperationProcessStartInitial.java:45)
        at org.activiti.engine.impl.pvm.runtime.AbstractEventAtomicOperation.execute(AbstractEventAtomicOperation.java:56)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.pvm.runtime.AtomicOperationProcessStart.eventNotificationsCompleted(AtomicOperationProcessStart.java:64)
        at org.activiti.engine.impl.pvm.runtime.AbstractEventAtomicOperation.execute(AbstractEventAtomicOperation.java:56)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.start(ExecutionEntity.java:381)
        at org.activiti.engine.impl.cmd.StartProcessInstanceCmd.execute(StartProcessInstanceCmd.java:110)
        at org.activiti.engine.impl.cmd.StartProcessInstanceCmd.execute(StartProcessInstanceCmd.java:37)
        at org.activiti.engine.impl.interceptor.CommandInvoker.execute(CommandInvoker.java:24)
        at org.activiti.engine.impl.interceptor.CommandContextInterceptor.execute(CommandContextInterceptor.java:57)
        at org.activiti.spring.SpringTransactionInterceptor$1.doInTransaction(SpringTransactionInterceptor.java:47)
        at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133)
        at org.activiti.spring.SpringTransactionInterceptor.execute(SpringTransactionInterceptor.java:45)
        at org.activiti.engine.impl.interceptor.LogInterceptor.execute(LogInterceptor.java:37)
        at org.activiti.engine.impl.cfg.CommandExecutorImpl.execute(CommandExecutorImpl.java:40)
        at org.activiti.engine.impl.cfg.CommandExecutorImpl.execute(CommandExecutorImpl.java:35)
        at org.activiti.engine.impl.RuntimeServiceImpl.startProcessInstanceByKey(RuntimeServiceImpl.java:80)
        at org.activiti.camel.ActivitiProducer.startProcess(ActivitiProducer.java:168)
        at org.activiti.camel.ActivitiProducer.process(ActivitiProducer.java:65)
        at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
        at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:145)
        at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
        at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:468)
        at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:190)
        at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:190)
        at org.apache.camel.component.direct.DirectProducer.process(DirectProducer.java:62)
        at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:190)
        at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:109)
        at org.apache.camel.processor.UnitOfWorkProducer.process(UnitOfWorkProducer.java:68)
        at org.apache.camel.impl.ProducerCache$2.doInProducer(ProducerCache.java:412)
        at org.apache.camel.impl.ProducerCache$2.doInProducer(ProducerCache.java:380)
        at org.apache.camel.impl.ProducerCache.doInProducer(ProducerCache.java:270)
        at org.apache.camel.impl.ProducerCache.sendExchange(ProducerCache.java:380)
        at org.apache.camel.impl.ProducerCache.send(ProducerCache.java:238)
        at org.apache.camel.impl.DefaultProducerTemplate.send(DefaultProducerTemplate.java:128)
        at org.apache.camel.impl.DefaultProducerTemplate.sendBody(DefaultProducerTemplate.java:132)
        ... 3 more
    Caused by: java.io.NotSerializableException: org.apache.camel.impl.DefaultMessageHistory
        at java.io.ObjectOutputStream.writeObject0(Unknown Source)
        at java.io.ObjectOutputStream.writeObject(Unknown Source)
        at java.util.ArrayList.writeObject(Unknown Source)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
        at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
        at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
        at java.io.ObjectOutputStream.writeObject0(Unknown Source)
        at java.io.ObjectOutputStream.writeObject(Unknown Source)
        at org.activiti.engine.impl.variable.SerializableType.serialize(SerializableType.java:93)
        ... 104 more
</code>```

Java Class

```<code>package org.quick;

import java.util.Collections;
import java.util.List;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppMain {

    public static void main(String[] args) throws Exception {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "application-context.xml");
        RepositoryService repositoryService =
                  (RepositoryService) applicationContext.getBean("repositoryService");
                String deploymentId = repositoryService
                  .createDeployment()
                  .addClasspathResource("helloworld.bpmn")
                  .deploy()
                  .getId();
                System.out.print( "process id is :" +deploymentId);
                CamelContext cxt = (CamelContext) applicationContext.getBean("camelProcess");
                RuntimeService runService= (RuntimeService) applicationContext.getBean("runtimeService");
                ProducerTemplate tpl = cxt.createProducerTemplate();
                String instanceId = (String) tpl.requestBody("direct:start", Collections.singletonMap("var1", "hello"));
                String str =  (String) runService.getVariable(instanceId, "var2");
                System.out.print(str);
                System.out.print(str);

                TaskService taskService = (TaskService) applicationContext.getBean("taskService");
                //Retrieving the tasks assigned for the candidate group Register
                List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup("Register").list();
                for (Task task : tasks) {
                    System.out.println("Following task is available for register group: " + task.getName());

                    // claim it
                    taskService.claim(task.getId(), "rupa");
                }

                // Verify Fozzie can now retrieve the task
                tasks = taskService.createTaskQuery().taskAssignee("rupa").list();
                for (Task task : tasks) {
                    System.out.println("Task for roopa: " + task.getName());

                    // Complete the task
                    //taskService.complete(task.getId());
                }

                System.out
                        .println("Number of tasks for roopa: " + taskService.createTaskQuery().taskAssignee("rupa").list().size());
    }

}
</code>```

XMLs  --  application context

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

    <import resource="classpath:activiti-application-context.xml" />
    <import resource="classpath:camel-application-context.xml" />

</beans>

camel-application-context.xml

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

    <camelContext id="camelProcess" xmlns="http://camel.apache.org/schema/spring">
    <routeBuilder ref="myBuilder" />
    </camelContext>
    <bean id="myBuilder" class="org.quick.CamelRouteBuilder"/>

    <bean id="camel" class="org.activiti.camel.CamelBehaviour">
        <constructor-arg index="0">
            <list>
                <bean class="org.activiti.camel.SimpleContextProvider">
                    <constructor-arg index="0" value="helloCamelProcess" />
                    <constructor-arg index="1" ref="camelProcess" />
                </bean>
            </list>
        </constructor-arg>
    </bean>

</beans>
</code>```

答:
I've fixed this by adding interceptor to camel context:

    <camelContext id="camelContext" xmlns="http://camel.apache.org/schema/spring">
        <intercept>
            <removeProperty propertyName="CamelMessageHistory" />
        </intercept>
    </camelContext>

Body:
I am New to Apache Camel integration with the alfresco activiti, I am getting below error while running below program.

Exception

Exception in thread "main" org.apache.camel.CamelExecutionException: Exception occurred during execution on the exchange: Exchange[ID-Ravi-59907-1467728441130-0-2]
        at org.apache.camel.util.ObjectHelper.wrapCamelExecutionException(ObjectHelper.java:1706)
        at org.apache.camel.util.ExchangeHelper.extractResultBody(ExchangeHelper.java:660)
        at org.apache.camel.impl.DefaultProducerTemplate.extractResultBody(DefaultProducerTemplate.java:471)
        at org.apache.camel.impl.DefaultProducerTemplate.sendBody(DefaultProducerTemplate.java:133)
        at org.apache.camel.impl.DefaultProducerTemplate.sendBody(DefaultProducerTemplate.java:149)
        at org.apache.camel.impl.DefaultProducerTemplate.requestBody(DefaultProducerTemplate.java:301)
        at org.quick.AppMain.main(AppMain.java:32)
    Caused by: org.activiti.engine.ActivitiException: Couldn't serialize value '[DefaultMessageHistory[routeId=route1, node=setProperty1], DefaultMessageHistory[routeId=route1, node=setBody1]]' in variable 'CamelMessageHistory'
        at org.activiti.engine.impl.variable.SerializableType.serialize(SerializableType.java:95)
        at org.activiti.engine.impl.variable.SerializableType.setValue(SerializableType.java:69)
        at org.activiti.engine.impl.persistence.entity.VariableInstanceEntity.setValue(VariableInstanceEntity.java:178)
        at org.activiti.engine.impl.persistence.entity.VariableInstanceEntity.create(VariableInstanceEntity.java:74)
        at org.activiti.engine.impl.persistence.entity.VariableInstanceEntity.createAndInsert(VariableInstanceEntity.java:60)
        at org.activiti.engine.impl.persistence.entity.VariableScopeImpl.createVariableInstance(VariableScopeImpl.java:839)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.createVariableInstance(ExecutionEntity.java:1175)
        at org.activiti.engine.impl.persistence.entity.VariableScopeImpl.createVariableLocal(VariableScopeImpl.java:752)
        at org.activiti.engine.impl.persistence.entity.VariableScopeImpl.createVariableLocal(VariableScopeImpl.java:739)
        at org.activiti.engine.impl.persistence.entity.VariableScopeImpl.setVariable(VariableScopeImpl.java:633)
        at org.activiti.engine.impl.persistence.entity.VariableScopeImpl.setVariable(VariableScopeImpl.java:590)
        at org.activiti.engine.impl.persistence.entity.VariableScopeImpl.setVariables(VariableScopeImpl.java:534)
        at org.activiti.camel.CamelBehaviour.execute(CamelBehaviour.java:45)
        at org.activiti.engine.impl.delegate.ActivityBehaviorInvocation.invoke(ActivityBehaviorInvocation.java:34)
        at org.activiti.engine.impl.delegate.DelegateInvocation.proceed(DelegateInvocation.java:37)
        at org.activiti.engine.impl.delegate.DefaultDelegateInterceptor.handleInvocation(DefaultDelegateInterceptor.java:25)
        at org.activiti.engine.impl.bpmn.behavior.ServiceTaskDelegateExpressionActivityBehavior.execute(ServiceTaskDelegateExpressionActivityBehavior.java:98)
        at org.activiti.engine.impl.pvm.runtime.AtomicOperationActivityExecute.execute(AtomicOperationActivityExecute.java:60)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerStart.eventNotificationsCompleted(AtomicOperationTransitionNotifyListenerStart.java:52)
        at org.activiti.engine.impl.pvm.runtime.AbstractEventAtomicOperation.execute(AbstractEventAtomicOperation.java:56)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.pvm.runtime.AbstractEventAtomicOperation.execute(AbstractEventAtomicOperation.java:49)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionCreateScope.execute(AtomicOperationTransitionCreateScope.java:49)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerTake.execute(AtomicOperationTransitionNotifyListenerTake.java:80)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionDestroyScope.execute(AtomicOperationTransitionDestroyScope.java:116)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerEnd.eventNotificationsCompleted(AtomicOperationTransitionNotifyListenerEnd.java:35)
        at org.activiti.engine.impl.pvm.runtime.AbstractEventAtomicOperation.execute(AbstractEventAtomicOperation.java:56)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.pvm.runtime.AbstractEventAtomicOperation.execute(AbstractEventAtomicOperation.java:49)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.take(ExecutionEntity.java:453)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.take(ExecutionEntity.java:431)
        at org.activiti.engine.impl.bpmn.behavior.BpmnActivityBehavior.performOutgoingBehavior(BpmnActivityBehavior.java:140)
        at org.activiti.engine.impl.bpmn.behavior.BpmnActivityBehavior.performDefaultOutgoingBehavior(BpmnActivityBehavior.java:66)
        at org.activiti.engine.impl.bpmn.behavior.FlowNodeActivityBehavior.leave(FlowNodeActivityBehavior.java:44)
        at org.activiti.engine.impl.bpmn.behavior.FlowNodeActivityBehavior.execute(FlowNodeActivityBehavior.java:36)
        at org.activiti.engine.impl.pvm.runtime.AtomicOperationActivityExecute.execute(AtomicOperationActivityExecute.java:60)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.pvm.runtime.AtomicOperationProcessStartInitial.eventNotificationsCompleted(AtomicOperationProcessStartInitial.java:45)
        at org.activiti.engine.impl.pvm.runtime.AbstractEventAtomicOperation.execute(AbstractEventAtomicOperation.java:56)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.pvm.runtime.AtomicOperationProcessStart.eventNotificationsCompleted(AtomicOperationProcessStart.java:64)
        at org.activiti.engine.impl.pvm.runtime.AbstractEventAtomicOperation.execute(AbstractEventAtomicOperation.java:56)
        at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:97)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:636)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:629)
        at org.activiti.engine.impl.persistence.entity.ExecutionEntity.start(ExecutionEntity.java:381)
        at org.activiti.engine.impl.cmd.StartProcessInstanceCmd.execute(StartProcessInstanceCmd.java:110)
        at org.activiti.engine.impl.cmd.StartProcessInstanceCmd.execute(StartProcessInstanceCmd.java:37)
        at org.activiti.engine.impl.interceptor.CommandInvoker.execute(CommandInvoker.java:24)
        at org.activiti.engine.impl.interceptor.CommandContextInterceptor.execute(CommandContextInterceptor.java:57)
        at org.activiti.spring.SpringTransactionInterceptor$1.doInTransaction(SpringTransactionInterceptor.java:47)
        at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133)
        at org.activiti.spring.SpringTransactionInterceptor.execute(SpringTransactionInterceptor.java:45)
        at org.activiti.engine.impl.interceptor.LogInterceptor.execute(LogInterceptor.java:37)
        at org.activiti.engine.impl.cfg.CommandExecutorImpl.execute(CommandExecutorImpl.java:40)
        at org.activiti.engine.impl.cfg.CommandExecutorImpl.execute(CommandExecutorImpl.java:35)
        at org.activiti.engine.impl.RuntimeServiceImpl.startProcessInstanceByKey(RuntimeServiceImpl.java:80)
        at org.activiti.camel.ActivitiProducer.startProcess(ActivitiProducer.java:168)
        at org.activiti.camel.ActivitiProducer.process(ActivitiProducer.java:65)
        at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
        at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:145)
        at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
        at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:468)
        at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:190)
        at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:190)
        at org.apache.camel.component.direct.DirectProducer.process(DirectProducer.java:62)
        at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:190)
        at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:109)
        at org.apache.camel.processor.UnitOfWorkProducer.process(UnitOfWorkProducer.java:68)
        at org.apache.camel.impl.ProducerCache$2.doInProducer(ProducerCache.java:412)
        at org.apache.camel.impl.ProducerCache$2.doInProducer(ProducerCache.java:380)
        at org.apache.camel.impl.ProducerCache.doInProducer(ProducerCache.java:270)
        at org.apache.camel.impl.ProducerCache.sendExchange(ProducerCache.java:380)
        at org.apache.camel.impl.ProducerCache.send(ProducerCache.java:238)
        at org.apache.camel.impl.DefaultProducerTemplate.send(DefaultProducerTemplate.java:128)
        at org.apache.camel.impl.DefaultProducerTemplate.sendBody(DefaultProducerTemplate.java:132)
        ... 3 more
    Caused by: java.io.NotSerializableException: org.apache.camel.impl.DefaultMessageHistory
        at java.io.ObjectOutputStream.writeObject0(Unknown Source)
        at java.io.ObjectOutputStream.writeObject(Unknown Source)
        at java.util.ArrayList.writeObject(Unknown Source)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
        at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
        at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
        at java.io.ObjectOutputStream.writeObject0(Unknown Source)
        at java.io.ObjectOutputStream.writeObject(Unknown Source)
        at org.activiti.engine.impl.variable.SerializableType.serialize(SerializableType.java:93)
        ... 104 more

Java Class

package org.quick;

import java.util.Collections;
import java.util.List;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppMain {

    public static void main(String[] args) throws Exception {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "application-context.xml");
        RepositoryService repositoryService =
                  (RepositoryService) applicationContext.getBean("repositoryService");
                String deploymentId = repositoryService
                  .createDeployment()
                  .addClasspathResource("helloworld.bpmn")
                  .deploy()
                  .getId();
                System.out.print( "process id is :" +deploymentId);
                CamelContext cxt = (CamelContext) applicationContext.getBean("camelProcess");
                RuntimeService runService= (RuntimeService) applicationContext.getBean("runtimeService");
                ProducerTemplate tpl = cxt.createProducerTemplate();
                String instanceId = (String) tpl.requestBody("direct:start", Collections.singletonMap("var1", "hello"));
                String str =  (String) runService.getVariable(instanceId, "var2");
                System.out.print(str);
                System.out.print(str);

                TaskService taskService = (TaskService) applicationContext.getBean("taskService");
                //Retrieving the tasks assigned for the candidate group Register
                List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup("Register").list();
                for (Task task : tasks) {
                    System.out.println("Following task is available for register group: " + task.getName());

                    // claim it
                    taskService.claim(task.getId(), "rupa");
                }

                // Verify Fozzie can now retrieve the task
                tasks = taskService.createTaskQuery().taskAssignee("rupa").list();
                for (Task task : tasks) {
                    System.out.println("Task for roopa: " + task.getName());

                    // Complete the task
                    //taskService.complete(task.getId());
                }

                System.out
                        .println("Number of tasks for roopa: " + taskService.createTaskQuery().taskAssignee("rupa").list().size());
    }

}

XMLs  --  application context

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

    <import resource="classpath:activiti-application-context.xml" />
    <import resource="classpath:camel-application-context.xml" />

</beans>

camel-application-context.xml

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

    <camelContext id="camelProcess" xmlns="http://camel.apache.org/schema/spring">
    <routeBuilder ref="myBuilder" />
    </camelContext>
    <bean id="myBuilder" class="org.quick.CamelRouteBuilder"/>

    <bean id="camel" class="org.activiti.camel.CamelBehaviour">
        <constructor-arg index="0">
            <list>
                <bean class="org.activiti.camel.SimpleContextProvider">
                    <constructor-arg index="0" value="helloCamelProcess" />
                    <constructor-arg index="1" ref="camelProcess" />
                </bean>
            </list>
        </constructor-arg>
    </bean>

</beans>


问:
Mesos Marathon deploy was failed when added parameters in Json file
I was trying to deploy ngnix docker container by mesos Marathon, I would like to set some environment variables in the container, so I added parameter section in the Json file, but after I added the parameter section, it was failed. My Json file as following:

```<code>{
  "container":{
    "type":"DOCKER",
    "docker":{
      "image":"nginx",
      "network":"BRIDGE",
      "portMappings":[{"containerPort":80,"hostPort":0,"servicePort":80,"protocol":"tcp"}],
      "parameters": [
                { "key": "myhostname", "value": "a.corp.org" }
            ]
    }
  },
  "id":"nginx7",
  "instances":1,
  "cpus":0.25,
  "mem":256,
  "uris":[]
}
</code>```

my launch script was: curl -X POST -H "Content-Type: application/json" 10.3.11.11:8080/v2/apps -d@"$@"

The command I ran was: ./launch.sh nginx.json

答:
You used the wrong parameter key myhostname, if you want to setup hostname for you container, it should be:

```<code>"parameters": [
            { "key": "hostname", "value": "a.corp.org" }
        ]
</code>```

if you want to pass environment variable, it should be:

```<code>"parameters": [
            { "key": "env", "value": "myhostname=a.corp.org" }
        ]
</code>```

Body:
I was trying to deploy ngnix docker container by mesos Marathon, I would like to set some environment variables in the container, so I added parameter section in the Json file, but after I added the parameter section, it was failed. My Json file as following:

{
  "container":{
    "type":"DOCKER",
    "docker":{
      "image":"nginx",
      "network":"BRIDGE",
      "portMappings":[{"containerPort":80,"hostPort":0,"servicePort":80,"protocol":"tcp"}],
      "parameters": [
                { "key": "myhostname", "value": "a.corp.org" }
            ]
    }
  },
  "id":"nginx7",
  "instances":1,
  "cpus":0.25,
  "mem":256,
  "uris":[]
}

my launch script was: curl -X POST -H "Content-Type: application/json" 10.3.11.11:8080/v2/apps -d@"$@"

The command I ran was: ./launch.sh nginx.json

Body:
You used the wrong parameter key myhostname, if you want to setup hostname for you container, it should be:

"parameters": [
            { "key": "hostname", "value": "a.corp.org" }
        ]

if you want to pass environment variable, it should be:

"parameters": [
            { "key": "env", "value": "myhostname=a.corp.org" }
        ]


问:
How to properly change the Chef::Config[:file_cache_path] in .kitchen.yml?
I'm stumped.  I want to change the cache location.  The default is in the user profile temp folder; it makes for a VERY long path on Windows.  I have looked over all the docs; and I can't seem to figure this out.

Here I see that I can specify client.rb settings on the chef-solo provisioner.
and here I see that the cache path is a setting in the client.rb specified by cache_path.
This leads me to believe that I should be able to:

provisioner:
  name: chef_solo
  client_rb:
    cache_path: c:/chef/cache
```

But this does not seem to work :(  Can anyone tell me the correct way to accomplish this?

答: You can't, this is deeply controlled by Test Kitchen. Why do you think you need to change this?</p>

Body:
I'm stumped.  I want to change the cache location.  The default is in the user profile temp folder; it makes for a VERY long path on Windows.  I have looked over all the docs; and I can't seem to figure this out.

Here I see that I can specify client.rb settings on the chef-solo provisioner.
and here I see that the cache path is a setting in the client.rb specified by cache_path.
This leads me to believe that I should be able to:

provisioner:
  name: chef_solo
  client_rb:
    cache_path: c:/chef/cache

But this does not seem to work :(  Can anyone tell me the correct way to accomplish this?


问:
ERROR ITMS-90512: Invalid sdk value... 8.2 is higher than maximum allowed value of 10.3?
Trying to upload a binary, which includes a watch app.  The error I'm getting (which I wasn't getting a couple days ago) is the value provided for LC_VERSION_MIN_IPHONEOS for the watchkit extension is 8.2 which is greater than the maximum allowed value of 10.3... apparently 8.2 > 10.3?

I'm updated to the latest XCode, 8.3, that didn't fix the problem.  Tried changing the iOS deployment target for the watch app and extension, no apparent effect on the message.

答:
EDIT: This is problem on Apple side and nothing to do with Xcode. This is only effecting apps with WatchKit.

I just uploaded one my apps today that has a watchkit extension. Try this, it may or may not help.

Xcode -> Product Clean

Xcode -> Quit

In a console terminal do > rm -rf  /Users/your_mac_user/library/Developer/Xcode/DerivedData/*

Relaunch Xcode and project

Go to your Xcode -> Build Settings for your iPhone app and make sure its set to 8.0 for debug and release

Now go to both your watch and watch extensions and make sure the Build setting is set to 8.2

Archive and upload again.


问:
The Canvas Background and the HTML  Element
According to the spec:

It is recommended that authors of HTML documents specify the canvas background for the BODY element rather than the HTML element.

But it doesn't say what advantages it has. Why does the spec recommend this?

P.S. It crossed my mind when I saw Extra scrollbar when body height is 100vh: isn't it better to simply give the background to the html element instead?

答:
It is a matter of preference actually, this is why it is recommended rather than being forced as a strict rule.

The body tag being a descendant of the html tag overrides the html properties - being background otherwise.

However, since all browsers give a margin to body by default, creating a border between the body and the browser window (although we are used to resetting this margin to 0), I guess this ...border was meant to be visible, so using a background on the HTML would make this border invisible to users. Given this fact and since all content is contained inside the body tag, the recommendation was provided by spec.

However, nowadays the body tag is usually reset to 0 by almost everyone so using it on either html or body tag makes no difference and each case provides no advantages compared to the other.

Title: The Canvas Background and the HTML <body> Element


问:
HTML & CSS - put <link> tag outside of the
Is it ok to put the <link> to a css file out of the  tag, for example in the footer side?

Which are bad and good results of this?

I ask this, cause actually i have a css file which doesn't styles anything but brings just some css3 animations to my website, so i would like to put it to the end of the html just for performance reason...

thanks

答: This is an old discussion, but I think it's worth noting in here that Google Pagespeed Insights actually now (2017) recommends deferring the loading of large CSS files until below the fold to ensure they don't block loading of html.</p>

Title: HTML & CSS - put <link> tag outside of the <head>


问:
Apply a glow effect onto a THREE.TextGeometry object in Three.js
I have done quite a few hours of google search to see if this can be done
within the three.js environment.

I want to create a glow effect based on a TextGeometry and not a simple primitive like a sphere or cube object similar to the one in Lee StemKoski - shadow glow example below.

I have been reading and experimenting with Lee StemKoski examples

In particular with his Shader Glow example which as stated works well with simple objects but not with complex geometric shapes. Therefore I was wondering if there are any work arounds to this or other suggestions to how one could create a glow effect around text.

regards

w9914420

UPDATE: I decided to go with the mapping concept by attaching an image to the text I can create a glow effect. In this example I used a circle, but should not be too difficult to do a map for the text that I need.

UPDATE: 20/3/17 - So I had an attempt at using the theeX.atmosphere material to create that elusive text glow effect. Here are some of the results.

As you can see not quite there yet - the issue that I have is I am not able to smooth the vertices of the outer glow text more. I am not sure if it is possible any advice appreciated.

Native code used to create effect.

```<code>//normal text created

var geometry2  = threeLab.asset.simpleText('hello','my_font');
var materialme  = new THREE.MeshNormalMaterial();
var mesh    = new THREE.Mesh( geometry2, materialme );
this.scene.add( mesh );

// we create a secondary text object to use as glow
var geometry  = threeLab.asset.simpleText('hello','my_font');

// clone for manipulation
var geoclone = geometry.clone();

//Thes functions are need to make it work in this case
geoclone.mergeVertices();
//geoclone.computeCentroids();
geoclone.computeVertexNormals();
geoclone.computeFaceNormals();

// part of threex library to make the glow scale and expand
THREEx.dilateGeometry(geoclone, 0.5);
var materialz   = THREEx.createAtmosphereMaterial();
var meshHalo    = new THREE.Mesh(geoclone, materialz );

//we have now our glow
this.scene.add( meshHalo );
</code>```

答:
So In the end I increased the bevelsegments of my secondary TextGeometry object which helped to smooth it. I was then able to encase my first text into the second like so:

With further tweaking I will be able to get the glow effect more subtle, but for now the effect works.

Thank you all for the input :)

Body:
I have done quite a few hours of google search to see if this can be done
within the three.js environment.

I want to create a glow effect based on a TextGeometry and not a simple primitive like a sphere or cube object similar to the one in Lee StemKoski - shadow glow example below.

I have been reading and experimenting with Lee StemKoski examples

In particular with his Shader Glow example which as stated works well with simple objects but not with complex geometric shapes. Therefore I was wondering if there are any work arounds to this or other suggestions to how one could create a glow effect around text.

regards

w9914420

UPDATE: I decided to go with the mapping concept by attaching an image to the text I can create a glow effect. In this example I used a circle, but should not be too difficult to do a map for the text that I need.

UPDATE: 20/3/17 - So I had an attempt at using the theeX.atmosphere material to create that elusive text glow effect. Here are some of the results.

As you can see not quite there yet - the issue that I have is I am not able to smooth the vertices of the outer glow text more. I am not sure if it is possible any advice appreciated.

Native code used to create effect.

//normal text created

var geometry2  = threeLab.asset.simpleText('hello','my_font');
var materialme  = new THREE.MeshNormalMaterial();
var mesh    = new THREE.Mesh( geometry2, materialme );
this.scene.add( mesh );

// we create a secondary text object to use as glow
var geometry  = threeLab.asset.simpleText('hello','my_font');

// clone for manipulation
var geoclone = geometry.clone();

//Thes functions are need to make it work in this case
geoclone.mergeVertices();
//geoclone.computeCentroids();
geoclone.computeVertexNormals();
geoclone.computeFaceNormals();

// part of threex library to make the glow scale and expand
THREEx.dilateGeometry(geoclone, 0.5);
var materialz   = THREEx.createAtmosphereMaterial();
var meshHalo    = new THREE.Mesh(geoclone, materialz );

//we have now our glow
this.scene.add( meshHalo );

ContentLicense: CC BY-SA 4.0


问:
javafx - how to create a loop of graphic components
In my javafx application I want to create a scene where I can show the usernames of all the users in my database.

Precisely, I want to show a list of labels where every label get a username.
(the number of labels depend on the number of users).

Note: I can do this in java with a list and a foreach loop, but this is the first time that I work with javafx and I want to know how to create a loop of graphic component.

Thanks.

答:
Here are a couple of alternatives, one sample is just looping and adding new labels to the children of a layout pane, the other is using the in-built ListView component.  There are other alternatives of course.  Which you choose to use will depend upon the functionality you need to achieve.

```<code>import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class UserDisplay extends Application {
    @Override public void start(Stage stage) {
        String[] users = { "Huey", "Dewey", "Louie" };

        VBox layout = new VBox(10);

        // ALTERNATIVE 1: add labels in a loop.
        for (String user: users) {
            Label userLabel = new Label(user);
            layout.getChildren().add(userLabel);
        }

        // ALTERNATIVE 2: use the built-in ListView component.
        ListView<String> listView = new ListView<>(
                FXCollections.observableArrayList(users)
        );
        layout.getChildren().add(listView);

        layout.setPadding(new Insets(10));
        layout.setPrefSize(100,200);

        stage.setScene(new Scene(layout));
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

Body:
Here are a couple of alternatives, one sample is just looping and adding new labels to the children of a layout pane, the other is using the in-built ListView component.  There are other alternatives of course.  Which you choose to use will depend upon the functionality you need to achieve.

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class UserDisplay extends Application {
    @Override public void start(Stage stage) {
        String[] users = { "Huey", "Dewey", "Louie" };

        VBox layout = new VBox(10);

        // ALTERNATIVE 1: add labels in a loop.
        for (String user: users) {
            Label userLabel = new Label(user);
            layout.getChildren().add(userLabel);
        }

        // ALTERNATIVE 2: use the built-in ListView component.
        ListView<String> listView = new ListView<>(
                FXCollections.observableArrayList(users)
        );
        layout.getChildren().add(listView);

        layout.setPadding(new Insets(10));
        layout.setPrefSize(100,200);

        stage.setScene(new Scene(layout));
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


问:
Google Search API - Number of Results
Whenever you perform a Google search, it spits out this little snippet of info

"About 8,110,000 results (0.10 seconds)"

I'm using the number of results certain terms return to rank them against each other, so if I could get this integer - 8,110,000 - via the API it would be very helpful. Some Google API's have recently been deprecated, so if you could point me to the right one that isn't deprecated, it would be very helpful.

Any other workarounds would also be much appreciated. I've seen one or two old posts on similar topics, but none seemed to be resolved successfully.

答:
Completed using Bing instead of Google and with the following code:

```<code>string baseURL = "http://api.search.live.net/xml.aspx?Appid=<MyAppID>&query=%22" + name + "%22&sources=web";
WebClient c = new WebClient();
c.DownloadStringAsync(new Uri(baseURL));
c.DownloadStringCompleted += new DownloadStringCompletedEventHandler(findTotalResults);
</code>```

and this calls findTotalResults:

```<code>void findTotalResults(object sender, DownloadStringCompletedEventArgs e)
{
    lock (this)
    {
        string s = e.Result;
        XmlReader reader = XmlReader.Create(new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(s)));
        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Element)
            {
                if (reader.Name.Equals("web:Total"))
                {
                    gResults = reader.ReadInnerXml();
                }

            }
        }
    }
}
</code>```

Title: Google Search API - Number of Results

Body:
Completed using Bing instead of Google and with the following code:

string baseURL = "http://api.search.live.net/xml.aspx?Appid=<MyAppID>&query=%22" + name + "%22&sources=web";
WebClient c = new WebClient();
c.DownloadStringAsync(new Uri(baseURL));
c.DownloadStringCompleted += new DownloadStringCompletedEventHandler(findTotalResults);

and this calls findTotalResults:

void findTotalResults(object sender, DownloadStringCompletedEventArgs e)
{
    lock (this)
    {
        string s = e.Result;
        XmlReader reader = XmlReader.Create(new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(s)));
        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Element)
            {
                if (reader.Name.Equals("web:Total"))
                {
                    gResults = reader.ReadInnerXml();
                }

            }
        }
    }
}


问:
how to read from file and add to object data?
```<code>17  5
12  8
15  22
17  11
33  21
43  15
15  4
44  35
23  19
10  23
55  39
8   6
21  9
20  28
20  13
45  29
18  16
21  19
68  55
10  16
33  54
3   1
5   9
</code>```

I am trying to read in input.txt file that looks like input above but the problem is that the program only reads in the last line from the text file.

Here is my code:

```<code>import java.io.FileNotFoundException;
import java.io.*;
import java.io.IOException;
import java.util.*;
import java.util.Scanner;

/**
 *
 */
public class ReadIn {

public static void main(String[] args) throws IOException {

    //List<Integer> value = new ArrayList<Integer>();
    //List<Integer> weight = new ArrayList<Integer>();
    FileReader readFile = new FileReader ("C:\\Users\\owner\\IdeaProjects\\knapsack\\src\\input");
    BufferedReader br = new BufferedReader(readFile);
    Scanner input = new Scanner(br);
    Scanner keyboard = new Scanner(System.in);
    //List<Items> items = new ArrayList<Items>();

    Items[] items= new Items[23];//this only creates references that are set to their default value null which throws a null exception
    for(int i =0 ; i <items.length; i++) {//fixes null exception

        items[i] = new Items();//fully creates the objects

        while (input.hasNext()) {//read in file input to object data
            items[i].setValue(input.nextInt());
            items[i].setWeight(input.nextInt());
            items[i].setId(i);
        }
    }
    input.close();
    input.reset();
    System.out.println("What is the max capacity for the knapsack? ");
    Integer maxCapacity = keyboard.nextInt();
    System.out.println(maxCapacity);
    int[] maxWeight = new int[maxCapacity];//creates int array so we can use the index as the maxWeight as the number of fields
    printArray(items);

}
    public static void printArray(Items[] x) {

        for (int i = 0; i < x.length; i++) {
            x[i] = new Items();
            System.out.println(x[i].getValue() + " " + x[i].getWeight() + " " + x[i].getId() + " ");
        }
    }

}
</code>```

Thanks for the help I am stuck!!
I have also attached the Items class that i am trying to use

```<code>    public class Items {
        private Integer value ;
        private Integer weight;
        private Integer Id;

        public Items(){
            this.value = 0;
            this.weight = 0;
            this.Id =0;
        }

        public Items(Integer v, Integer w, Integer ID){
            this.value = v;
            this.weight = w;
            this.Id = ID;
        }

        public Integer getValue() {
            return value;
        }

        public void setValue(Integer value) {
            this.value = value;
        }

        public Integer getWeight() {
            return weight;
        }

        public void setWeight(Integer weight) {
            this.weight = weight;
        }

        public Integer getId() {
            return Id;
        }

        public void setId(Integer id) {//sets id
            Id = id;
        }
    }
</code>```

This is the end of the code

答:
Your problem lies in the for-loop below. You do a while-loop without actually changing the destination, so everything gets overwritten and only the last input prevails. There are two possibilities to fix this. Both of those only work optimally under the assumption that the input file is correctly formatted. Other changes would need to be adjusted to make it fail proof.

```<code>//---------Option 1: Remove the While-loop----
for(int i =0 ; i <items.length; i++) {//fixes null exception

    items[i] = new Items();//fully creates the objects
    items[i].setValue(input.nextInt());
    items[i].setWeight(input.nextInt());
    items[i].setId(i);
}

//---------Option 2: Let the for-loop finish before the while-loop ------
for(int i =0 ; i <items.length; i++) { //fixes null exception
    items[i] = new Items(); //fully creates the objects
}

int k=0; //Need a variable for count
while (input.hasNext()) {
    items[k].setValue(input.nextInt());
    items[k].setWeight(input.nextInt());
    items[k].setId(k);
    k++;
}
</code>```

Body:
17  5
12  8
15  22
17  11
33  21
43  15
15  4
44  35
23  19
10  23
55  39
8   6
21  9
20  28
20  13
45  29
18  16
21  19
68  55
10  16
33  54
3   1
5   9

I am trying to read in input.txt file that looks like input above but the problem is that the program only reads in the last line from the text file.

Here is my code:

import java.io.FileNotFoundException;
import java.io.*;
import java.io.IOException;
import java.util.*;
import java.util.Scanner;

/**
 *
 */
public class ReadIn {

public static void main(String[] args) throws IOException {

    //List<Integer> value = new ArrayList<Integer>();
    //List<Integer> weight = new ArrayList<Integer>();
    FileReader readFile = new FileReader ("C:\\Users\\owner\\IdeaProjects\\knapsack\\src\\input");
    BufferedReader br = new BufferedReader(readFile);
    Scanner input = new Scanner(br);
    Scanner keyboard = new Scanner(System.in);
    //List<Items> items = new ArrayList<Items>();

    Items[] items= new Items[23];//this only creates references that are set to their default value null which throws a null exception
    for(int i =0 ; i <items.length; i++) {//fixes null exception

        items[i] = new Items();//fully creates the objects

        while (input.hasNext()) {//read in file input to object data
            items[i].setValue(input.nextInt());
            items[i].setWeight(input.nextInt());
            items[i].setId(i);
        }
    }
    input.close();
    input.reset();
    System.out.println("What is the max capacity for the knapsack? ");
    Integer maxCapacity = keyboard.nextInt();
    System.out.println(maxCapacity);
    int[] maxWeight = new int[maxCapacity];//creates int array so we can use the index as the maxWeight as the number of fields
    printArray(items);

}
    public static void printArray(Items[] x) {

        for (int i = 0; i < x.length; i++) {
            x[i] = new Items();
            System.out.println(x[i].getValue() + " " + x[i].getWeight() + " " + x[i].getId() + " ");
        }
    }

}

Thanks for the help I am stuck!!
I have also attached the Items class that i am trying to use

    public class Items {
        private Integer value ;
        private Integer weight;
        private Integer Id;

        public Items(){
            this.value = 0;
            this.weight = 0;
            this.Id =0;
        }

        public Items(Integer v, Integer w, Integer ID){
            this.value = v;
            this.weight = w;
            this.Id = ID;
        }

        public Integer getValue() {
            return value;
        }

        public void setValue(Integer value) {
            this.value = value;
        }

        public Integer getWeight() {
            return weight;
        }

        public void setWeight(Integer weight) {
            this.weight = weight;
        }

        public Integer getId() {
            return Id;
        }

        public void setId(Integer id) {//sets id
            Id = id;
        }
    }

This is the end of the code

Body:
Your problem lies in the for-loop below. You do a while-loop without actually changing the destination, so everything gets overwritten and only the last input prevails. There are two possibilities to fix this. Both of those only work optimally under the assumption that the input file is correctly formatted. Other changes would need to be adjusted to make it fail proof.

//---------Option 1: Remove the While-loop----
for(int i =0 ; i <items.length; i++) {//fixes null exception

    items[i] = new Items();//fully creates the objects
    items[i].setValue(input.nextInt());
    items[i].setWeight(input.nextInt());
    items[i].setId(i);
}

//---------Option 2: Let the for-loop finish before the while-loop ------
for(int i =0 ; i <items.length; i++) { //fixes null exception
    items[i] = new Items(); //fully creates the objects
}

int k=0; //Need a variable for count
while (input.hasNext()) {
    items[k].setValue(input.nextInt());
    items[k].setWeight(input.nextInt());
    items[k].setId(k);
    k++;
}


问:
How to create a single Calendar object with a Date object and a string that holds the time. - JAVA
I am currently trying to make a Calendar object. One function returns a Date object which holds the Month, Day and year. And another function returns a string object holding the time.

How do I use both of this information to create a single Calendar object?

I am using Java

Thank you.

答:
Do not use old troublesome date-time classes, now legacy. Use java.time classes.

```<code>LocalDate ld = LocalDate.of( 2017 , Month.MAY , 23 );
LocalTime lt = LocalTime.of( 12 , 23 , 45 );
</code>```

To generate a String representing either value in standard ISO 8601 format, call toString. For other formats use, DateTimeFormatter.

Please search Stack Overflow before posting. This has been handled hundreds of times already.

Body:
Do not use old troublesome date-time classes, now legacy. Use java.time classes.

LocalDate ld = LocalDate.of( 2017 , Month.MAY , 23 );
LocalTime lt = LocalTime.of( 12 , 23 , 45 );

To generate a String representing either value in standard ISO 8601 format, call toString. For other formats use, DateTimeFormatter.

Please search Stack Overflow before posting. This has been handled hundreds of times already.


问:
pdfbox.util.ImageIOUtil.writeImage issue

There is an issue with PDFbox going on here.

```<code>java.lang.NullPointerException
    at org.apache.pdfbox.util.ImageIOUtil.writeImage(ImageIOUtil.java:197)
    at org.apache.pdfbox.pdmodel.graphics.xobject.PDJpeg.createImageStream(PDJpeg.java:190)
    at org.apache.pdfbox.pdmodel.graphics.xobject.PDJpeg.<init>(PDJpeg.java:150)
</code>```

Our current setup is 2 servers with 2 JVMs for each server running over Websphere 8.5 and Java 6.

When we restart the JVMs the issue seems to be resolved, but after few hours we get the same exception.

The application is using PDFBox v1.8.8

Here is a piece of the code:

```<code>ImageIO.setUseCache(false);
PDDocument document = new PDDocument();
PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
document.addPage(page);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedImage convertedFile = tiffToBufferedImageJAI(file);
PDXObjectImage img = new PDJpeg(document, convertedFile);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawXObject(img, 0, 0, 550, 800);
contentStream.close();

document.save(baos);
document.close();
baos.flush();

return baos.toByteArray();
</code>```

答:
Reading through the PDFBox code it would appear that the problem is caused because there are no writers for JPG images available at that time (see line ImageIOUtil line 197 and trace back to line 184).

I would suggest that something in your app server is calling ImageIO.scanForPlugins() with a constrained classpath of some kind and mutating the available writers, or something else is getting in and fiddling.

Body:
There is an issue with PDFbox going on here.

java.lang.NullPointerException
    at org.apache.pdfbox.util.ImageIOUtil.writeImage(ImageIOUtil.java:197)
    at org.apache.pdfbox.pdmodel.graphics.xobject.PDJpeg.createImageStream(PDJpeg.java:190)
    at org.apache.pdfbox.pdmodel.graphics.xobject.PDJpeg.<init>(PDJpeg.java:150)

Our current setup is 2 servers with 2 JVMs for each server running over Websphere 8.5 and Java 6.

When we restart the JVMs the issue seems to be resolved, but after few hours we get the same exception.

The application is using PDFBox v1.8.8

Here is a piece of the code:

ImageIO.setUseCache(false);
PDDocument document = new PDDocument();
PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
document.addPage(page);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedImage convertedFile = tiffToBufferedImageJAI(file);
PDXObjectImage img = new PDJpeg(document, convertedFile);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawXObject(img, 0, 0, 550, 800);
contentStream.close();

document.save(baos);
document.close();
baos.flush();

return baos.toByteArray();


问:
Angular JS table creation issue
I have just started learning Angular JS and I am trying to create an 8X8 table using ng-repeat. I am not able to get 8 table header. All the table header is coming in one column. Here is my code.

```<code><table border="1px solid black">
      <tr ng-repeat="k in [0,1,2,3,4,5,6,7,8]">
        <th>
          column
        </th>
      </tr>
      <tr ng-repeat="i in [0,1,2,3,4,5,6,7,8]">
        <td ng-repeat="j in [0,1,2,3,4,5,6,7,8]">
          [{{i}},{{j}}]
        </td>
      </tr>
    </table>
</code>```

This is the output of my code. I am not sure why is that happening.

Title: Angular JS table creation issue

Body:
I have just started learning Angular JS and I am trying to create an 8X8 table using ng-repeat. I am not able to get 8 table header. All the table header is coming in one column. Here is my code.

          column

          [{{i}},{{j}}]

This is the output of my code. I am not sure why is that happening.

Body:
    <table>
        <tr>Rows of 8
            <tr ng-repeat="i in [0, 1, 2, 3, 4, 5, 6, 7]">
                <td ng-repeat="a in [0, 1, 2, 3, 4, 5, 6, 7]">{{i+1}}</td>
                    <td>{{a}}</td>
            </tr>
        </tr>
    </table>


问:
Can't access data inside array that looks like JSON. JavaScript
Below, I have an array that looks like JSON data. I get this result by querying something and pushing it to var test = [];. The way I append the strings and numbers into my test array is by running test.push({item_name: name, number_of_items: number});. Just to be clear, it is not JSON:

```<code>[{"item_name":"Peri Peri Chicken","number_of_items":6},{"item_name":"Deep fried beef","number_of_items":22},{"item_name":"Roast chicken","number_of_items":7},{"item_name":"Chow Mein","number_of_items":3},{"item_name":"Sweet and sour noodles","number_of_items":5},{"item_name":"Steak","number_of_items":32}]
</code>```

Now, I want to sort the array so that it shows the array from the largest number_of_items to the smallest number_of_items.

I have tried to sort it like you would do with a JSON array, but it doesn't work as I have realised that I cannot access the elements in that array by using test.number_of_items. I tried THIS method to sort the array, but it doesn't work for me as my data is not in JSON.

It would also really helpful if someone can tell me if there's a better way to append multiple data into the same index of an array, and also to be able to access the elements easier in the future? so for example, on index 1 I would have something like (elem1: string1, elem2: number1) and then index 2 (elem1: string2, elem2: number2) and ...

答:
You can parse it as JSON, order it, and turn it back in to a string, like this:

var array = [
    { "item_name": "Peri Peri Chicken", "number_of_items": 6 },
    { "item_name": "Deep fried beef", "number_of_items": 22 },
    { "item_name": "Roast chicken", "number_of_items": 7 },
    { "item_name": "Chow Mein", "number_of_items": 3 },
    { "item_name": "Sweet and sour noodles", "number_of_items": 5 },
    { "item_name": "Steak", "number_of_items": 32 }
];

var compare = (a,b) => {
  if (a.number_of_items  b.number_of_items)
    return -1;
  return 0;
};

var test = JSON.parse(array);
test.sort(compare);
array = JSON.stringify(test);```

Body:
Below, I have an array that looks like JSON data. I get this result by querying something and pushing it to var test = [];. The way I append the strings and numbers into my test array is by running test.push({item_name: name, number_of_items: number});. Just to be clear, it is not JSON:

[{"item_name":"Peri Peri Chicken","number_of_items":6},{"item_name":"Deep fried beef","number_of_items":22},{"item_name":"Roast chicken","number_of_items":7},{"item_name":"Chow Mein","number_of_items":3},{"item_name":"Sweet and sour noodles","number_of_items":5},{"item_name":"Steak","number_of_items":32}]

Now, I want to sort the array so that it shows the array from the largest number_of_items to the smallest number_of_items.

I have tried to sort it like you would do with a JSON array, but it doesn't work as I have realised that I cannot access the elements in that array by using test.number_of_items. I tried THIS method to sort the array, but it doesn't work for me as my data is not in JSON.

It would also really helpful if someone can tell me if there's a better way to append multiple data into the same index of an array, and also to be able to access the elements easier in the future? so for example, on index 1 I would have something like (elem1: string1, elem2: number1) and then index 2 (elem1: string2, elem2: number2) and ...

Body:
You can parse it as JSON, order it, and turn it back in to a string, like this:

var array = [
    { "item_name": "Peri Peri Chicken", "number_of_items": 6 },
    { "item_name": "Deep fried beef", "number_of_items": 22 },
    { "item_name": "Roast chicken", "number_of_items": 7 },
    { "item_name": "Chow Mein", "number_of_items": 3 },
    { "item_name": "Sweet and sour noodles", "number_of_items": 5 },
    { "item_name": "Steak", "number_of_items": 32 }
];

var compare = (a,b) => {
  if (a.number_of_items < b.number_of_items)
    return 1;
  if (a.number_of_items > b.number_of_items)
    return -1;
  return 0;
};

var test = JSON.parse(array);
test.sort(compare);
array = JSON.stringify(test);