问:
Available suitable solutions for web app importing DWG || DXF files?
I need directions to what are possible solutions for web app handling autoCAD files(importing).

The app will have to render 2D architectural plans from imported autoCAD files with possibility to move walls, furniture etc.

I was thinking about using Unity with webGL build, as I already know it, but it's not a perfect tool for simple 2d application and there will be a problem(as always) with external .NET DWG/DXF handling libraries(old mono won't compile most(if not every) of libraries out there).

As an alternative I found this nice little engine - http://www.babylonjs.com/ - which also builds webGL apps, but much smaller and many times faster loading. But I have no idea if it's possible to use external libraries for it to handle autoCAD files. Any suggestions? Thanks for your time.

答:
You can use Forge translator and viewer on your website. The rest service, Model Derivative, translate a .DWG into a json stream that can viewed on browsers with uses WebGL and Three.js. </p>

<p>There are many examples at this github org, but this sample implements something similar to what you described for Revit models. </p>

Body:
You can use Forge translator and viewer on your website. The rest service, Model Derivative, translate a .DWG into a json stream that can viewed on browsers with uses WebGL and Three.js.

There are many examples at this github org, but this sample implements something similar to what you described for Revit models.


来源: stackexchange

问:
JavaScript window.location.assign() is not working
I am working on an HTML based text-adventure game, where one choice leads to the next, based on which links the user clicks. I am using localStorage to store the HP value of the player, when the HP value hits 0, the game is supposed to end, and the website is supposed to change to a 'Game Over' page. I have two functions that both navigate to a different page, depending on if the HP is above or below a certain number

```<code>function alterHP(value) {
    if (typeof (Storage) !== "undefined") {
        var currentHP = parseInt(localStorage.HP);
        localStorage.HP = currentHP + value;
        hp=parseInt(localStorage.HP);
        if (hp<=0) {
            alert(hp); //For debugging, is showing a negative number, like it should be
            /*If the error is syntactical, it is the next line*/
            window.location.replace('youLose.html');
            /*I used breakpoints and this line IS getting hit*/
            /*It's just not going to the 'youLose' page*/
        }
    }
}

function getResult() {
    var currentHP = parseInt(localStorage.HP);
    if (currentHP > 4) {
        window.location.assign('endAbove4.html');//These both work fine
    } else {
        window.location.assign('endBelow4.html');//These both work fine
    }
}
</code>```

```<code><li><a
    href="../S9/S9.html" onclick="alterHP(-6);"
    class="ghost-button">Go on to the next scene</a></li>
</code>```

I have tried every variation of the path name for youLose.html that i can think of, including ../youLose.html, ../../youLose.html, ..\youLose.html, and even putting the full http://gw.mvctc.com/Class2018/smcintosh/Projects/StMarys (I physically opened the page and copied directly from the URL bar to my code, so I know it was the right address.) I also tried using window.location.href="../youLose.html" "youLose.html" '../youLose.html' and 'youLose.html' and window.location.replace()

The most frustrating part is that if you get to the point where getResult(); is called, and you have -26hp, it acts correctly and redirects to the endBelow4.html page. I just need it to redirect to the youLose page as soon as HP hits 0

I cannot for the life of me figure out why it wont redirect to the youLose page.

ContentLicense: CC BY-SA 3.0

Body:
I am working on an HTML based text-adventure game, where one choice leads to the next, based on which links the user clicks. I am using localStorage to store the HP value of the player, when the HP value hits 0, the game is supposed to end, and the website is supposed to change to a 'Game Over' page. I have two functions that both navigate to a different page, depending on if the HP is above or below a certain number

function alterHP(value) {
    if (typeof (Storage) !== "undefined") {
        var currentHP = parseInt(localStorage.HP);
        localStorage.HP = currentHP + value;
        hp=parseInt(localStorage.HP);
        if (hp<=0) {
            alert(hp); //For debugging, is showing a negative number, like it should be
            /*If the error is syntactical, it is the next line*/
            window.location.replace('youLose.html');
            /*I used breakpoints and this line IS getting hit*/
            /*It's just not going to the 'youLose' page*/
        }
    }
}

function getResult() {
    var currentHP = parseInt(localStorage.HP);
    if (currentHP > 4) {
        window.location.assign('endAbove4.html');//These both work fine
    } else {
        window.location.assign('endBelow4.html');//These both work fine
    }
}

Go on to the next scene

I have tried every variation of the path name for youLose.html that i can think of, including ../youLose.html, ../../youLose.html, ..\youLose.html, and even putting the full http://gw.mvctc.com/Class2018/smcintosh/Projects/StMarys (I physically opened the page and copied directly from the URL bar to my code, so I know it was the right address.) I also tried using window.location.href="../youLose.html" "youLose.html" '../youLose.html' and 'youLose.html' and window.location.replace()

The most frustrating part is that if you get to the point where getResult(); is called, and you have -26hp, it acts correctly and redirects to the endBelow4.html page. I just need it to redirect to the youLose page as soon as HP hits 0

I cannot for the life of me figure out why it wont redirect to the youLose page.

Body: use window.open('youLose.html','_self')


问:
Convert string[] to Int[] without losing leading zeros
Input:

```<code>string param = "1100,1110,0110,0001";
</code>```

Output:

```<code>int[] matrix = new[]
    {
              1,1,0,0,
              1,1,1,0,
              0,1,1,0,
              0,0,0,1
    };
</code>```

What I did?

First of all I splited string to string[].

```<code>string[] resultantArray = param.Split(',');
</code>```

Created one method, where I passed my string[].

```<code>var intArray = toIntArray(resultantArray);

static private int[] toIntArray(string[] strArray)
{
    int[] intArray = new int[strArray.Length];
    for (int i = 0; i < strArray.Length; i++)
    {
        intArray[i] = int.Parse(strArray[i]);
    }

    return intArray;
}
</code>```

Issue?

I tried many solutions of SO, but none of them helped me.

Ended up with array without leading zeroes.

答:
determine all digits: .Where(char.IsDigit)

convert the selected char-digits into integer: .Select(x => x-'0') (this is not as pretty as int.Parse or Convert.ToInt32 but it's super fast)

Code:

```<code>string param = "1100,1110,0110,0001";
int[] result = param.Where(char.IsDigit).Select(x => x-'0').ToArray();
</code>```

As CodesInChaos commented, this could lead to an error if there are other type of Digits within your input like e.g. Thai digit characters: '๐' '๑' '๒' '๓' '๔' '๕' '๖' '๗' '๘' '๙'  where char.IsDigit == true - if you need to handle such special cases you can allow only 0 and 1 in your result .Where("01".Contains)

Body:
Input:

string param = "1100,1110,0110,0001";

Output:

int[] matrix = new[]
    {
              1,1,0,0,
              1,1,1,0,
              0,1,1,0,
              0,0,0,1
    };

What I did?

First of all I splited string to string[].

string[] resultantArray = param.Split(',');

Created one method, where I passed my string[].

var intArray = toIntArray(resultantArray);

static private int[] toIntArray(string[] strArray)
{
    int[] intArray = new int[strArray.Length];
    for (int i = 0; i < strArray.Length; i++)
    {
        intArray[i] = int.Parse(strArray[i]);
    }

    return intArray;
}

Issue?

I tried many solutions of SO, but none of them helped me.

Ended up with array without leading zeroes.

Body:
determine all digits: .Where(char.IsDigit)

convert the selected char-digits into integer: .Select(x => x-'0') (this is not as pretty as int.Parse or Convert.ToInt32 but it's super fast)

Code:

string param = "1100,1110,0110,0001";
int[] result = param.Where(char.IsDigit).Select(x => x-'0').ToArray();

As CodesInChaos commented, this could lead to an error if there are other type of Digits within your input like e.g. Thai digit characters: '๐' '๑' '๒' '๓' '๔' '๕' '๖' '๗' '๘' '๙'  where char.IsDigit == true - if you need to handle such special cases you can allow only 0 and 1 in your result .Where("01".Contains)


问:
How to close all activities and exit from an app
My app is intended to allow only logged in user to access the activities. If a user logs out, the Shared preference boolean isLogged in is set to false and the user should not access the rest of activities except the LoginActivity.

However, I am able to access all the previously opened activities by pressing the back button.

I would use finish(); while opening each activity but then I would like users to still use the back button while they're logged in.

I have tried solutions from other similar questions like

```<code>Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
</code>```

and on the onCreate() of my LoginActivity I have added

```<code>if (getIntent().getBooleanExtra("EXIT", false)) {
         finish();
    }
</code>```

When I press the logout option, the previous activity opens instead.

Any suggestions please help me?

答:
I faced to a similar situation. As I figured out, even if I call the finish() function in the beginning, the whole onCreate() function get executed. Then it will finish. In my scenario, in the onCreate() function, I call to another Activity. So even if the main activity finishes after onCreate(), the second activity still exists. So my solution was,

private boolean finish = false;

in onCreate() of the main function,

```<code>if(intent.getBooleanExtra("EXIT", false)) {
        finish();
        finish = true;
    }
</code>```

and I put a check in all navigations

```<code>if(!finish) {
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }
</code>```

My exit function was,

```<code>Intent intent = new Intent(getApplicationContext(), MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("EXIT", true);
    startActivity(intent);
</code>```

Body:
My app is intended to allow only logged in user to access the activities. If a user logs out, the Shared preference boolean isLogged in is set to false and the user should not access the rest of activities except the LoginActivity.

However, I am able to access all the previously opened activities by pressing the back button.

I would use finish(); while opening each activity but then I would like users to still use the back button while they're logged in.

I have tried solutions from other similar questions like

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

and on the onCreate() of my LoginActivity I have added

if (getIntent().getBooleanExtra("EXIT", false)) {
         finish();
    }

When I press the logout option, the previous activity opens instead.

Any suggestions please help me?

Body:
I faced to a similar situation. As I figured out, even if I call the finish() function in the beginning, the whole onCreate() function get executed. Then it will finish. In my scenario, in the onCreate() function, I call to another Activity. So even if the main activity finishes after onCreate(), the second activity still exists. So my solution was,

private boolean finish = false;

in onCreate() of the main function,

if(intent.getBooleanExtra("EXIT", false)) {
        finish();
        finish = true;
    }

and I put a check in all navigations

if(!finish) {
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

My exit function was,

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("EXIT", true);
    startActivity(intent);


问:
Call angular service in another js file
I have some javascript and html files: User.js, index.html, Door.js

I want use any function in User.js file.

My user.js file

My door.js file

I call getUserInfo in user.Js from Door.js file in function
doorApplicationLoginPage.service

Error: [$injector:unpr] Unknown provider: UserServiceProvider <- UserService <- PerioMainController

```<code>var doorApplicationLoginPage = angular.module("PerioLoginPage", []);

doorApplicationLoginPage.service('UserService', function () {

    this.getUserInfo = function () {
        alert("getUserInfo");
    }

    this.reLoginUser = function () {
        alert("reLoginUser");
    }

});

var doorApplication = angular.module("PerioDoorApplication", []);

doorApplication.controller("PerioMainController", function ($scope, $http, $sce, UserService) {

    UserService.getUserInfo();

});
</code>```

Thank you.

答:
As I said in my comments you have two things to do at least:

You need to return the functions you want to use from the service (UserService):

```<code>return{
    getUserInfo: getUserInfo,
    reLoginUser: reLoginUser
};
</code>```

Your module needs to reference the one the service is defined on:

```<code>angular.module('PerioDoorApplication', ['PerioLoginPage']);
</code>```

And in your 'PerioMainController', a better way to write it would be:

```<code>doorApplication.controller('PerioMainController', ['$scope', '$http', '$sce', 'UserService',
    function($scope, $http, $sce, UserService){
        [...]
    }
]);
</code>```

Title: Call angular service in another js file

Body:
I have some javascript and html files: User.js, index.html, Door.js

I want use any function in User.js file.

My user.js file

My door.js file

I call getUserInfo in user.Js from Door.js file in function
doorApplicationLoginPage.service

Error: [$injector:unpr] Unknown provider: UserServiceProvider <- UserService <- PerioMainController

var doorApplicationLoginPage = angular.module("PerioLoginPage", []);

doorApplicationLoginPage.service('UserService', function () {

    this.getUserInfo = function () {
        alert("getUserInfo");
    }

    this.reLoginUser = function () {
        alert("reLoginUser");
    }

});

var doorApplication = angular.module("PerioDoorApplication", []);

doorApplication.controller("PerioMainController", function ($scope, $http, $sce, UserService) {

    UserService.getUserInfo();

});

Thank you.

Body:
As I said in my comments you have two things to do at least:

You need to return the functions you want to use from the service (UserService):

return{
    getUserInfo: getUserInfo,
    reLoginUser: reLoginUser
};

Your module needs to reference the one the service is defined on:

angular.module('PerioDoorApplication', ['PerioLoginPage']);

And in your 'PerioMainController', a better way to write it would be:

doorApplication.controller('PerioMainController', ['$scope', '$http', '$sce', 'UserService',
    function($scope, $http, $sce, UserService){
        [...]
    }
]);


问:
Android cursor in RTL languages
I have problem with android input cursor in RTL languages. When I am in RTL support layout, I have two input cursor and it's really funny.
Does it have real solution, for get rid of this?

I use this code to make my android UI RTL:

```<code>getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
</code>```

And this my xml for text view:

```<code><android.support.design.widget.TextInputLayout
        android:id="@+id/input_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="numberDecimal"
            android:id="@+id/myID"
            android:maxLines="1"
            android:focusableInTouchMode="true"
            android:layout_weight="0.25"
            android:layout_gravity="center_horizontal"
            android:hint="phone Number"
            android:maxLength="20"
            android:gravity="center" />
    </android.support.design.widget.TextInputLayout>
</code>```

答:
I resolved it using below..

In your xml layout, for edit text field add this-->

```<code>android:textDirection="anyRtl"
</code>```

Here, "editText" is your view of edit text field. i.e,

```<code>EditText editText = (EditText) findViewById(R.id.edit_text);
</code>```

Then programatically add text watcher for that edit text.

```<code>editText.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    editText.setSelection(s.length()); // this line is very important for setting cursor position
                }

                @Override
                public void afterTextChanged(Editable s) {

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

This worked for me!

Title: Android cursor in RTL languages

Body:
I have problem with android input cursor in RTL languages. When I am in RTL support layout, I have two input cursor and it's really funny.
Does it have real solution, for get rid of this?

I use this code to make my android UI RTL:

getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);

And this my xml for text view:

<android.support.design.widget.TextInputLayout
        android:id="@+id/input_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="numberDecimal"
            android:id="@+id/myID"
            android:maxLines="1"
            android:focusableInTouchMode="true"
            android:layout_weight="0.25"
            android:layout_gravity="center_horizontal"
            android:hint="phone Number"
            android:maxLength="20"
            android:gravity="center" />
    </android.support.design.widget.TextInputLayout>

Body:
I resolved it using below..

In your xml layout, for edit text field add this-->

android:textDirection="anyRtl"

Here, "editText" is your view of edit text field. i.e,

EditText editText = (EditText) findViewById(R.id.edit_text);

Then programatically add text watcher for that edit text.

editText.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    editText.setSelection(s.length()); // this line is very important for setting cursor position
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
        }

This worked for me!


问:
RadGridView Dynamic adding Columns and ColumnGroups thread issue
I'm trying to create grid with static and dynamic columns.
Dynamic columns should be under ColumnGroups.
When I'm not using ColumnGroups everything works ok. But when I try to assign dynamic column to one of groups I get

The calling thread cannot access this object because a different thread owns it.

I create new window in separate thread

```<code>Thread newWindowThread=new Thread(new ThreadStart(() =>
        {
            var instrumentWindow=new InstrumentWindow();
            ((InstrumentWindowViewModel)instrumentWindow.DataContext).Initialize(instrument.ToString(),DateTime.Today);
            instrumentWindow.Show();
            System.Windows.Threading.Dispatcher.Run();
        }));

        newWindowThread.SetApartmentState(ApartmentState.STA);
        newWindowThread.IsBackground = true;

        newWindowThread.Start();
</code>```

After I create static columns

```<code>this.EventGrid.Columns.Add(new GridViewDataColumn()
        {
            Header = "Time",
            DataMemberBinding = new Binding("Time"),
            DataType = typeof(DateTime)
        });
</code>```

And actually function which is responsible for creating dynamic columns

Basically the idea is to create ColumnGroup for each term and under that group display term properties.

```<code>    private void InitDynamicColumns()
    {
        var maxTermCount = ((InstrumentWindowViewModel)this.DataContext).Events.Max(x => x.Terms.Length);
        var termHeaders = new List<string>();

        for (int i = 0; i < maxTermCount; i++)
        {
            var currentTerm = ((InstrumentWindowViewModel)this.DataContext).Events.First().Terms[i];
            var analyzerAmountType = currentTerm.Type == AnalyzerAmountType.Seconds ? "sec" : "ticks";
            this.EventGrid.ColumnGroups.Add(new GridViewColumnGroup
            {
                Header = currentTerm.Size + " " + analyzerAmountType + " term",
                Name = currentTerm.Size + analyzerAmountType + "term"
            });

            termHeaders.Add(currentTerm.Size + analyzerAmountType + "term");
        }

        for (int i = 0; i < maxTermCount; i++)
        {
            this.EventGrid.Columns.Add(new GridViewDataColumn()
            {
                Header = "Property1",
                DataMemberBinding = new Binding("Terms[" + i + "].Property1"),
                 ColumnGroupName = termHeaders[i]
            });
            this.EventGrid.Columns.Add(new GridViewDataColumn()
            {
                Header = "Property2",
                DataMemberBinding = new Binding("Terms[" + i + "].Property2"),
                  ColumnGroupName = termHeaders[i]
            });
            this.EventGrid.Columns.Add(new GridViewDataColumn()
            {
                Header = "Property3",
                DataMemberBinding = new Binding("Terms[" + i + "].Property3"),
                 ColumnGroupName = termHeaders[i]
            });
        }

    }
</code>```

When I don't use ColumnGroups everything works as expected.But when I try to assig ColumnGroup to Column I get this Thread exception.

Thanks for any help.

答:
You can't create the window on one thread and the columns on another one if you indend to display the columns in a control within that window.

Just forget about this because it doesn't work because of the thread affinity:

Why do UI Controls in WPF have Thread Affinity?

You must create the window on the same thread as the one on which you create the columns and this is typically the main (UI) thread.

A WPF control may only be accessed on the thread on which it was originally created.

Body:
I'm trying to create grid with static and dynamic columns.
Dynamic columns should be under ColumnGroups.
When I'm not using ColumnGroups everything works ok. But when I try to assign dynamic column to one of groups I get

The calling thread cannot access this object because a different thread owns it.

I create new window in separate thread

Thread newWindowThread=new Thread(new ThreadStart(() =>
        {
            var instrumentWindow=new InstrumentWindow();
            ((InstrumentWindowViewModel)instrumentWindow.DataContext).Initialize(instrument.ToString(),DateTime.Today);
            instrumentWindow.Show();
            System.Windows.Threading.Dispatcher.Run();
        }));

        newWindowThread.SetApartmentState(ApartmentState.STA);
        newWindowThread.IsBackground = true;

        newWindowThread.Start();

After I create static columns

this.EventGrid.Columns.Add(new GridViewDataColumn()
        {
            Header = "Time",
            DataMemberBinding = new Binding("Time"),
            DataType = typeof(DateTime)
        });

And actually function which is responsible for creating dynamic columns

Basically the idea is to create ColumnGroup for each term and under that group display term properties.

    private void InitDynamicColumns()
    {
        var maxTermCount = ((InstrumentWindowViewModel)this.DataContext).Events.Max(x => x.Terms.Length);
        var termHeaders = new List<string>();

        for (int i = 0; i < maxTermCount; i++)
        {
            var currentTerm = ((InstrumentWindowViewModel)this.DataContext).Events.First().Terms[i];
            var analyzerAmountType = currentTerm.Type == AnalyzerAmountType.Seconds ? "sec" : "ticks";
            this.EventGrid.ColumnGroups.Add(new GridViewColumnGroup
            {
                Header = currentTerm.Size + " " + analyzerAmountType + " term",
                Name = currentTerm.Size + analyzerAmountType + "term"
            });

            termHeaders.Add(currentTerm.Size + analyzerAmountType + "term");
        }

        for (int i = 0; i < maxTermCount; i++)
        {
            this.EventGrid.Columns.Add(new GridViewDataColumn()
            {
                Header = "Property1",
                DataMemberBinding = new Binding("Terms[" + i + "].Property1"),
                 ColumnGroupName = termHeaders[i]
            });
            this.EventGrid.Columns.Add(new GridViewDataColumn()
            {
                Header = "Property2",
                DataMemberBinding = new Binding("Terms[" + i + "].Property2"),
                  ColumnGroupName = termHeaders[i]
            });
            this.EventGrid.Columns.Add(new GridViewDataColumn()
            {
                Header = "Property3",
                DataMemberBinding = new Binding("Terms[" + i + "].Property3"),
                 ColumnGroupName = termHeaders[i]
            });
        }

    }

When I don't use ColumnGroups everything works as expected.But when I try to assig ColumnGroup to Column I get this Thread exception.

Thanks for any help.


问:
How to Render HTML entities string in Vash File with NodeJs
I am not able to get Hello world in vash file in below code:-</p>

```<code>var result = {"description" : "<H1>Hello world</H1>"};
res.render('home',{data:result});

In home.vash
@modal.data.description
The out put is
<H1>Hello world</H1>
but I want only Hello world with html entity properties
</code>```

答:
When you passed data from node js to any html compiled file like .vash or .ejs, data will be passed as string. Data will not render as html tag.

```

    var result = {"description" : "Hello world"};
    res.render('home',{data:result});

```

In home.vash

write your .vash code @modal.data.description inside the html tag

Body:
I am not able to get Hello world in vash file in below code:-

var result = {"description" : "
Hello world
"};
res.render('home',{data:result});

In home.vash
@modal.data.description
The out put is

Hello world

but I want only Hello world with html entity properties

Body:
When you passed data from node js to any html compiled file like .vash or .ejs, data will be passed as string. Data will not render as html tag.

    var result = {"description" : "Hello world"};
    res.render('home',{data:result});

In home.vash

write your .vash code @modal.data.description inside the html tag


问:
Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done
I am running following code

```<code>/*Fetchinch Last CustID from custMaster*/
int ID = 0;
try
{
     con.Open();
     da = new OleDbDataAdapter("select max(Id) from custMaster",con);
     DataSet ds = new DataSet();
     da.Fill(ds);
     for(int i=0;i<ds.Tables[0].Rows.Count;i++)
        ID=int.Parse(ds.Tables[0].Rows[i][0].ToString());
     con.Close();
}
catch (Exception ex) {}
finally
{
     con.Close();
}
</code>```

I am putting debugger from the first statement of try block and finding that error is coming when I am trying to open the connection.
Error Text:

Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.

Connection String is:

"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=E:\NewSoft\Database\TestApp.accdb;Integrated
  Security=SSPI"

I am using oledb connections.

答:
I was having same problem but found out to be special characters used in the password.

So, I changed the Access file password and replaced Jet OLEDB:Database Password= with the updated one and it solved the issue.

ContentLicense: CC BY-SA 4.0

Body:
I am running following code

/*Fetchinch Last CustID from custMaster*/
int ID = 0;
try
{
     con.Open();
     da = new OleDbDataAdapter("select max(Id) from custMaster",con);
     DataSet ds = new DataSet();
     da.Fill(ds);
     for(int i=0;i<ds.Tables[0].Rows.Count;i++)
        ID=int.Parse(ds.Tables[0].Rows[i][0].ToString());
     con.Close();
}
catch (Exception ex) {}
finally
{
     con.Close();
}

I am putting debugger from the first statement of try block and finding that error is coming when I am trying to open the connection.
Error Text:

Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.

Connection String is:

"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=E:\NewSoft\Database\TestApp.accdb;Integrated
  Security=SSPI"

I am using oledb connections.


问:
How do I fix this null pointer exception?
I'm a newbie to Android, and I'm using a ListView. No problem when scrolling the ListView slowly. But when I scroll it quickly, app crash occurs.

Can anyone help me?

Stack trace:

```<code> FATAL EXCEPTION: main
  Process: com.beco.ibeco, PID: 1764
  java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
      at com.beco.ibeco.app.account.ProfileFragmentNew$HelpListAdapter.getView(ProfileFragmentNew.java:417)
      at android.widget.HeaderViewListAdapter.getView(HeaderViewListAdapter.java:220)
      at android.widget.AbsListView.obtainView(AbsListView.java:2346)
      at android.widget.ListView.makeAndAddView(ListView.java:1876)
      at android.widget.ListView.fillDown(ListView.java:702)
      at android.widget.ListView.fillGap(ListView.java:666)
      at android.widget.AbsListView.trackMotionScroll(AbsListView.java:5106)
      at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:3463)
      at android.widget.AbsListView.onTouchMove(AbsListView.java:3878)
      at android.widget.AbsListView.onTouchEvent(AbsListView.java:3691)
      at android.view.View.dispatchTouchEvent(View.java:9306)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2548)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2241)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2405)
      at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1737)
      at android.app.Activity.dispatchTouchEvent(Activity.java:2820)
      at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:63)
      at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:63)
      at com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2366)
      at android.view.View.dispatchPointerEvent(View.java:9526)
      at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4262)
      at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4128)
      at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3669)
      at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3722)
      at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3688)
      at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3814)
      at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3696)
      at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3871)
      at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3669)
      at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3722)
      at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3688)
    at android.view.ViewRootI
</code>```

Code:

```<code>private class HelpListAdapter extends ArrayAdapter {

    private Holder holder;
    private Context context;

    public HelpListAdapter(Context context, int resource) {
        super(context, resource);
        this.context = context;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {

        if (view == null) {
            holder = new Holder();
            if (position == 3) {
                view = View.inflate(getContext(), R.layout.list_item_with_expandable_new, null);
                holder.expandableListView = (ExpandableListView) view.findViewById(R.id.expand_list);
                holder.containerList = (LinearLayout) view.findViewById(R.id.container_expandable_list);
            } else {
                view = View.inflate(getContext(), R.layout.list_item_text, null);
                holder.textView = (TextView) view.findViewById(R.id.text);
            }
            view.setTag(holder);
        } else {
            holder = (Holder) view.getTag();
        }

        if (position != 3) {
            holder.textView.setText(mHelpLabels.get(position));
            Drawable[] iconLeft = {Util.getCustomDrawableColor(getActivity(),R.drawable.ic_favorite_18dp,R.color.beco_logout_red, PorterDuff.Mode.SRC_ATOP),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_checkin_18dp, R.color.beco_logout_red, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_faq, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_feedback, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_feedback, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_share_app, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_privacy, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_terms, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_faq, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_beco_settings, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_beco_settings, R.color.beco_white, PorterDuff.Mode.DST_IN),

            };
            holder.textView.setCompoundDrawablesWithIntrinsicBounds(iconLeft[position], null, null, null);

        } else {
            holder.expandableListView.setAdapter(new ExpandableListAdapter(context, mHelpLabels.get(position), view));
            holder.expandableListView.setOnGroupClickListener((parentExpand, v, groupPosition, id) -> {
                setListViewHeight(parentExpand, groupPosition);
                return false;
            });
        }

        return view;
    }

    class Holder {
        TextView textView;
        ExpandableListView expandableListView;
        LinearLayout containerList;
    }

    private void setListViewHeight(ExpandableListView listView, int group) {

        ExpandableListAdapter listAdapter = (ExpandableListAdapter) listView.getExpandableListAdapter();
        int height = 0;
        int groupCount = 0;
        int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.EXACTLY);
        View groupItem = listAdapter.getGroupView(groupCount, false, null, listView);
        groupItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
        height += groupItem.getMeasuredHeight();

        if (((listView.isGroupExpanded(groupCount)) && (groupCount != group))
                || ((!listView.isGroupExpanded(groupCount)) && (groupCount == group))) {
            for (int j = 0; j < listAdapter.getChildrenCount(groupCount); j++) {
                View listItem = listAdapter.getChildView(groupCount, j, false, null, listView);
                listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
                height += listItem.getMeasuredHeight();
            }
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();

        if (height < 10)
            height = 200;
        params.height = height;
        listView.setLayoutParams(params);
        listView.requestLayout();
    }

    class ExpandableListAdapter extends BaseExpandableListAdapter {

        Context context;
        String title;
        View viewParent;

        ExpandableListAdapter(Context context, String title, View view) {
            this.context = context;
            this.title = title;
            this.viewParent = view;
        }

        @Override
        public String getChild(int groupPosition, int childPosititon) {
            return mContactLabels.get(childPosititon);
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View view, ViewGroup parent) {

            if (view == null) {
                LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = infalInflater.inflate(R.layout.list_item_text, null);
            }
            Drawable[] iconLeft = {Util.getCustomDrawableColor(getActivity(), R.drawable.ic_email, R.color.beco_icon_tint_color, PorterDuff.Mode.SRC_ATOP),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_phone_black, R.color.beco_icon_tint_color, PorterDuff.Mode.DST_IN)};

            TextView textView = (TextView) view.findViewById(R.id.text);
            textView.setText(mContactLabels.get(childPosition));
            textView.setCompoundDrawablesWithIntrinsicBounds(iconLeft[childPosition], null, null, null);
            textView.setOnClickListener(v -> {
                switch (childPosition) {
                    case 0:
                        Intent intentEmail = new Intent(Intent.ACTION_SENDTO);
                        intentEmail.setData(Uri.fromParts("mailto", mContactLabels.get(childPosition), null));
                        intentEmail.putExtra(Intent.EXTRA_SUBJECT, "Contact beCo");
                        startActivity(intentEmail);
                        break;
                    case 1:
                        Intent intentCall = new Intent(Intent.ACTION_DIAL);
                        intentCall.setData(Uri.parse("tel:" + mContactLabels.get(childPosition)));
                        startActivity(intentCall);
                        break;
                }
            });

            return view;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return mContactLabels.size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return mContactLabels.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return 1;
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View view, ViewGroup parent) {

            if (view == null) {
                LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = infalInflater.inflate(R.layout.list_item_text, null);
            }
            TextView contact = (TextView) view.findViewById(R.id.text);
            contact.setText(title);
            Drawable iconLeft = Util.getCustomDrawableColor(getActivity(), R.drawable.ic_contact_blue, R.color.beco_white, PorterDuff.Mode.DST_IN);
            contact.setCompoundDrawablesWithIntrinsicBounds(null,null,iconLeft,null);

            LinearLayout border = (LinearLayout) viewParent.findViewById(R.id.container_expandable_list);

            Drawable iconRight = Util.getCustomDrawableColor(getActivity(), R.drawable.ic_keyboard_arrow_down_black, R.color.beco_black, PorterDuff.Mode.DST_IN);

            if (isExpanded) {
                border.setBackgroundResource(R.drawable.border);
                iconRight = Util.getCustomDrawableColor(getActivity(), R.drawable.ic_keyboard_arrow_up_black, R.color.beco_black, PorterDuff.Mode.DST_IN);
                contact.setTextColor(ContextCompat.getColor(getActivity(), R.color.beco_primary));
                contact.setCompoundDrawablesWithIntrinsicBounds(null, null, iconRight, null);

            } else {
                border.setBackgroundResource(0);
                contact.setTextColor(ContextCompat.getColor(getActivity(), R.color.beco_label_color));
                contact.setCompoundDrawablesWithIntrinsicBounds(null, null, iconRight, null);
            }

            return view;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }
}
</code>```

答:
Replace this code in getView : </p>

```<code>public View getView(int position, View view, ViewGroup parent) {

    if (view == null) {
        holder = new Holder();
        if (position == 3) {
            view = View.inflate(getContext(), R.layout.list_item_with_expandable_new, null);
        } else {
            view = View.inflate(getContext(), R.layout.list_item_text, null);
        }
        view.setTag(holder);
    } else {
        holder = (Holder) view.getTag();
    }

    if (position != 3) {
        holder.textView = (TextView) view.findViewById(R.id.text);
        holder.textView.setText(mHelpLabels.get(position));
        Drawable[] iconLeft = {Util.getCustomDrawableColor(getActivity(),R.drawable.ic_favorite_18dp,R.color.beco_logout_red, PorterDuff.Mode.SRC_ATOP),
                Util.getCustomDrawableColor(getActivity(), R.drawable.ic_checkin_18dp, R.color.beco_logout_red, PorterDuff.Mode.DST_IN),
                Util.getCustomDrawableColor(getActivity(), R.drawable.ic_faq, R.color.beco_white, PorterDuff.Mode.DST_IN),
                Util.getCustomDrawableColor(getActivity(), R.drawable.ic_feedback, R.color.beco_white, PorterDuff.Mode.DST_IN),
                Util.getCustomDrawableColor(getActivity(), R.drawable.ic_feedback, R.color.beco_white, PorterDuff.Mode.DST_IN),
                Util.getCustomDrawableColor(getActivity(), R.drawable.ic_share_app, R.color.beco_white, PorterDuff.Mode.DST_IN),
                Util.getCustomDrawableColor(getActivity(), R.drawable.ic_privacy, R.color.beco_white, PorterDuff.Mode.DST_IN),
                Util.getCustomDrawableColor(getActivity(), R.drawable.ic_terms, R.color.beco_white, PorterDuff.Mode.DST_IN),
                Util.getCustomDrawableColor(getActivity(), R.drawable.ic_faq, R.color.beco_white, PorterDuff.Mode.DST_IN),
                Util.getCustomDrawableColor(getActivity(), R.drawable.ic_beco_settings, R.color.beco_white, PorterDuff.Mode.DST_IN),
                Util.getCustomDrawableColor(getActivity(), R.drawable.ic_beco_settings, R.color.beco_white, PorterDuff.Mode.DST_IN),

        };
        holder.textView.setCompoundDrawablesWithIntrinsicBounds(iconLeft[position], null, null, null);

    } else {
        holder.expandableListView = (ExpandableListView) view.findViewById(R.id.expand_list);
        holder.containerList = (LinearLayout) view.findViewById(R.id.container_expandable_list);
        holder.expandableListView.setAdapter(new ExpandableListAdapter(context, mHelpLabels.get(position), view));
        holder.expandableListView.setOnGroupClickListener((parentExpand, v, groupPosition, id) -> {
            setListViewHeight(parentExpand, groupPosition);
            return false;
        });
    }

    return view;
}
</code>```

Body:
I'm a newbie to Android, and I'm using a ListView. No problem when scrolling the ListView slowly. But when I scroll it quickly, app crash occurs.

Can anyone help me?

Stack trace:

 FATAL EXCEPTION: main
  Process: com.beco.ibeco, PID: 1764
  java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
      at com.beco.ibeco.app.account.ProfileFragmentNew$HelpListAdapter.getView(ProfileFragmentNew.java:417)
      at android.widget.HeaderViewListAdapter.getView(HeaderViewListAdapter.java:220)
      at android.widget.AbsListView.obtainView(AbsListView.java:2346)
      at android.widget.ListView.makeAndAddView(ListView.java:1876)
      at android.widget.ListView.fillDown(ListView.java:702)
      at android.widget.ListView.fillGap(ListView.java:666)
      at android.widget.AbsListView.trackMotionScroll(AbsListView.java:5106)
      at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:3463)
      at android.widget.AbsListView.onTouchMove(AbsListView.java:3878)
      at android.widget.AbsListView.onTouchEvent(AbsListView.java:3691)
      at android.view.View.dispatchTouchEvent(View.java:9306)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2548)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2241)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2255)
      at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2405)
      at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1737)
      at android.app.Activity.dispatchTouchEvent(Activity.java:2820)
      at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:63)
      at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:63)
      at com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2366)
      at android.view.View.dispatchPointerEvent(View.java:9526)
      at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4262)
      at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4128)
      at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3669)
      at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3722)
      at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3688)
      at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3814)
      at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3696)
      at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3871)
      at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3669)
      at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3722)
      at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3688)
    at android.view.ViewRootI

Code:

private class HelpListAdapter extends ArrayAdapter {

    private Holder holder;
    private Context context;

    public HelpListAdapter(Context context, int resource) {
        super(context, resource);
        this.context = context;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {

        if (view == null) {
            holder = new Holder();
            if (position == 3) {
                view = View.inflate(getContext(), R.layout.list_item_with_expandable_new, null);
                holder.expandableListView = (ExpandableListView) view.findViewById(R.id.expand_list);
                holder.containerList = (LinearLayout) view.findViewById(R.id.container_expandable_list);
            } else {
                view = View.inflate(getContext(), R.layout.list_item_text, null);
                holder.textView = (TextView) view.findViewById(R.id.text);
            }
            view.setTag(holder);
        } else {
            holder = (Holder) view.getTag();
        }

        if (position != 3) {
            holder.textView.setText(mHelpLabels.get(position));
            Drawable[] iconLeft = {Util.getCustomDrawableColor(getActivity(),R.drawable.ic_favorite_18dp,R.color.beco_logout_red, PorterDuff.Mode.SRC_ATOP),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_checkin_18dp, R.color.beco_logout_red, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_faq, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_feedback, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_feedback, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_share_app, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_privacy, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_terms, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_faq, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_beco_settings, R.color.beco_white, PorterDuff.Mode.DST_IN),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_beco_settings, R.color.beco_white, PorterDuff.Mode.DST_IN),

            };
            holder.textView.setCompoundDrawablesWithIntrinsicBounds(iconLeft[position], null, null, null);

        } else {
            holder.expandableListView.setAdapter(new ExpandableListAdapter(context, mHelpLabels.get(position), view));
            holder.expandableListView.setOnGroupClickListener((parentExpand, v, groupPosition, id) -> {
                setListViewHeight(parentExpand, groupPosition);
                return false;
            });
        }

        return view;
    }

    class Holder {
        TextView textView;
        ExpandableListView expandableListView;
        LinearLayout containerList;
    }

    private void setListViewHeight(ExpandableListView listView, int group) {

        ExpandableListAdapter listAdapter = (ExpandableListAdapter) listView.getExpandableListAdapter();
        int height = 0;
        int groupCount = 0;
        int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.EXACTLY);
        View groupItem = listAdapter.getGroupView(groupCount, false, null, listView);
        groupItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
        height += groupItem.getMeasuredHeight();

        if (((listView.isGroupExpanded(groupCount)) && (groupCount != group))
                || ((!listView.isGroupExpanded(groupCount)) && (groupCount == group))) {
            for (int j = 0; j < listAdapter.getChildrenCount(groupCount); j++) {
                View listItem = listAdapter.getChildView(groupCount, j, false, null, listView);
                listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
                height += listItem.getMeasuredHeight();
            }
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();

        if (height < 10)
            height = 200;
        params.height = height;
        listView.setLayoutParams(params);
        listView.requestLayout();
    }

    class ExpandableListAdapter extends BaseExpandableListAdapter {

        Context context;
        String title;
        View viewParent;

        ExpandableListAdapter(Context context, String title, View view) {
            this.context = context;
            this.title = title;
            this.viewParent = view;
        }

        @Override
        public String getChild(int groupPosition, int childPosititon) {
            return mContactLabels.get(childPosititon);
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View view, ViewGroup parent) {

            if (view == null) {
                LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = infalInflater.inflate(R.layout.list_item_text, null);
            }
            Drawable[] iconLeft = {Util.getCustomDrawableColor(getActivity(), R.drawable.ic_email, R.color.beco_icon_tint_color, PorterDuff.Mode.SRC_ATOP),
                    Util.getCustomDrawableColor(getActivity(), R.drawable.ic_phone_black, R.color.beco_icon_tint_color, PorterDuff.Mode.DST_IN)};

            TextView textView = (TextView) view.findViewById(R.id.text);
            textView.setText(mContactLabels.get(childPosition));
            textView.setCompoundDrawablesWithIntrinsicBounds(iconLeft[childPosition], null, null, null);
            textView.setOnClickListener(v -> {
                switch (childPosition) {
                    case 0:
                        Intent intentEmail = new Intent(Intent.ACTION_SENDTO);
                        intentEmail.setData(Uri.fromParts("mailto", mContactLabels.get(childPosition), null));
                        intentEmail.putExtra(Intent.EXTRA_SUBJECT, "Contact beCo");
                        startActivity(intentEmail);
                        break;
                    case 1:
                        Intent intentCall = new Intent(Intent.ACTION_DIAL);
                        intentCall.setData(Uri.parse("tel:" + mContactLabels.get(childPosition)));
                        startActivity(intentCall);
                        break;
                }
            });

            return view;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return mContactLabels.size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return mContactLabels.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return 1;
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View view, ViewGroup parent) {

            if (view == null) {
                LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = infalInflater.inflate(R.layout.list_item_text, null);
            }
            TextView contact = (TextView) view.findViewById(R.id.text);
            contact.setText(title);
            Drawable iconLeft = Util.getCustomDrawableColor(getActivity(), R.drawable.ic_contact_blue, R.color.beco_white, PorterDuff.Mode.DST_IN);
            contact.setCompoundDrawablesWithIntrinsicBounds(null,null,iconLeft,null);

            LinearLayout border = (LinearLayout) viewParent.findViewById(R.id.container_expandable_list);

            Drawable iconRight = Util.getCustomDrawableColor(getActivity(), R.drawable.ic_keyboard_arrow_down_black, R.color.beco_black, PorterDuff.Mode.DST_IN);

            if (isExpanded) {
                border.setBackgroundResource(R.drawable.border);
                iconRight = Util.getCustomDrawableColor(getActivity(), R.drawable.ic_keyboard_arrow_up_black, R.color.beco_black, PorterDuff.Mode.DST_IN);
                contact.setTextColor(ContextCompat.getColor(getActivity(), R.color.beco_primary));
                contact.setCompoundDrawablesWithIntrinsicBounds(null, null, iconRight, null);

            } else {
                border.setBackgroundResource(0);
                contact.setTextColor(ContextCompat.getColor(getActivity(), R.color.beco_label_color));
                contact.setCompoundDrawablesWithIntrinsicBounds(null, null, iconRight, null);
            }

            return view;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }
}

Body:
Replace this code in getView :

public View getView(int position, View view, ViewGroup parent) {

    if (view == null) {
        holder = new Holder();
        if (position == 3) {
            view = View.inflate(getContext(), R.layout.list_item_with_expandable_new, null);
        } else {
            view = View.inflate(getContext(), R.layout.list_item_text, null);
        }
        view.setTag(holder);
    } else {
        holder = (Holder) view.getTag();
    }

    if (position != 3) {
        holder.textView = (TextView) view.findViewById(R.id.text);
        holder.textView.setText(mHelpLabels.get(position));
        Drawable[] iconLeft = {Util.getCustomDrawableColor(getActivity(),R.drawable.ic_favorite_18dp,R.color.beco_logout_red, PorterDuff.Mode.SRC_ATOP),
                Util.getCustomDrawableColor(getActivity(), R.drawable.ic_checkin_18dp, R.color.beco_logout_red, PorterDuff.Mode.DST_IN),
                Util.getCustomDrawableColor(getActivity(), R.drawable.ic_faq, R.color.beco_white, PorterDuff.Mode.DST_IN),
                Util.getCustomDrawableColor(getActivity(), R.drawable.ic_feedback, R.color.beco_white, PorterDuff.Mode.DST_IN),
                Util.getCustomDrawableColor(getActivity(), R.drawable.ic_feedback, R.color.beco_white, PorterDuff.Mode.DST_IN),
                Util.getCustomDrawableColor(getActivity(), R.drawable.ic_share_app, R.color.beco_white, PorterDuff.Mode.DST_IN),
                Util.getCustomDrawableColor(getActivity(), R.drawable.ic_privacy, R.color.beco_white, PorterDuff.Mode.DST_IN),
                Util.getCustomDrawableColor(getActivity(), R.drawable.ic_terms, R.color.beco_white, PorterDuff.Mode.DST_IN),
                Util.getCustomDrawableColor(getActivity(), R.drawable.ic_faq, R.color.beco_white, PorterDuff.Mode.DST_IN),
                Util.getCustomDrawableColor(getActivity(), R.drawable.ic_beco_settings, R.color.beco_white, PorterDuff.Mode.DST_IN),
                Util.getCustomDrawableColor(getActivity(), R.drawable.ic_beco_settings, R.color.beco_white, PorterDuff.Mode.DST_IN),

        };
        holder.textView.setCompoundDrawablesWithIntrinsicBounds(iconLeft[position], null, null, null);

    } else {
        holder.expandableListView = (ExpandableListView) view.findViewById(R.id.expand_list);
        holder.containerList = (LinearLayout) view.findViewById(R.id.container_expandable_list);
        holder.expandableListView.setAdapter(new ExpandableListAdapter(context, mHelpLabels.get(position), view));
        holder.expandableListView.setOnGroupClickListener((parentExpand, v, groupPosition, id) -> {
            setListViewHeight(parentExpand, groupPosition);
            return false;
        });
    }

    return view;
}


问:
Returning a random even number
I have the following methods. The method rnd, returns a single random integer between two bounds:

```<code>  /* Create next batch of 55 random numbers */
  void advance_random (){
int j1;
double new_random;
for(j1=0; j1<24; j1++){
  new_random = oldrand[j1]-oldrand[j1+31];
  if(new_random<0.0){
    new_random = new_random+1.0;
  }
  oldrand[j1] = new_random;
}
for(j1=24; j1<55; j1++){
  new_random = oldrand[j1]-oldrand[j1-24];
  if(new_random<0.0){
    new_random = new_random+1.0;
  }
  oldrand[j1] = new_random;
}
 } //advance_ramdom

  /* Fetch a single random number between 0.0 and 1.0 */
  double randomperc(){
jrand++;
if(jrand>=55){
  jrand = 1;
  advance_random();
}
return((double)oldrand[jrand]);
  } //randomPerc

  /* Fetch a single random integer between low and high including the bounds */
  synchronized int rnd (int low, int high){
int res;
if (low >= high){
  res = low;
} else {
  res = low + (int)(randomperc()*(high-low+1));
  if (res > high){
    res = high;
  }
}
return (res);
  } // rnd
</code>```

How do I modify this so that the number returned mod2 =0?

Thanks

答:
In Java 1.7 or later, I would use ThreadLocalRandom:

```<code>import java.util.concurrent.ThreadLocalRandom;

// Get even random number within range [min, max]
// Start with an even minimum and add random even number from the remaining range
public static int randEvenInt(int min, int max) {
    if (min % 2 != 0) ++min;
    return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
}

// Get odd random number within range [min, max]
// Start with an odd minimum and add random even number from the remaining range
public static int randOddInt(int min, int max) {
    if (min % 2 == 0) ++min;
    return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
}
</code>```

The reason to use ThreadLocalRandom is explained here. Also note, that the reason we +1 to the input to ThreadLocalRandom.nextInt() is to make sure the max is included in the range.

Title: Returning a random even number

Body:
I have the following methods. The method rnd, returns a single random integer between two bounds:

  /* Create next batch of 55 random numbers */
  void advance_random (){
int j1;
double new_random;
for(j1=0; j1<24; j1++){
  new_random = oldrand[j1]-oldrand[j1+31];
  if(new_random<0.0){
    new_random = new_random+1.0;
  }
  oldrand[j1] = new_random;
}
for(j1=24; j1<55; j1++){
  new_random = oldrand[j1]-oldrand[j1-24];
  if(new_random<0.0){
    new_random = new_random+1.0;
  }
  oldrand[j1] = new_random;
}
 } //advance_ramdom

  /* Fetch a single random number between 0.0 and 1.0 */
  double randomperc(){
jrand++;
if(jrand>=55){
  jrand = 1;
  advance_random();
}
return((double)oldrand[jrand]);
  } //randomPerc

  /* Fetch a single random integer between low and high including the bounds */
  synchronized int rnd (int low, int high){
int res;
if (low >= high){
  res = low;
} else {
  res = low + (int)(randomperc()*(high-low+1));
  if (res > high){
    res = high;
  }
}
return (res);
  } // rnd

How do I modify this so that the number returned mod2 =0?

Thanks

Body:
In Java 1.7 or later, I would use ThreadLocalRandom:

import java.util.concurrent.ThreadLocalRandom;

// Get even random number within range [min, max]
// Start with an even minimum and add random even number from the remaining range
public static int randEvenInt(int min, int max) {
    if (min % 2 != 0) ++min;
    return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
}

// Get odd random number within range [min, max]
// Start with an odd minimum and add random even number from the remaining range
public static int randOddInt(int min, int max) {
    if (min % 2 == 0) ++min;
    return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
}

The reason to use ThreadLocalRandom is explained here. Also note, that the reason we +1 to the input to ThreadLocalRandom.nextInt() is to make sure the max is included in the range.


问:
spring-security block websocket (sockjs)
In one of my projects I configured both rest services and websockets, both go through spring security filter that check for JWT. For websockets on the client side, application uses sockjs & stomp (on Angular2) and Spring websockets on the server side (Tomcat 8). When I open connection with Spring security enabled then I get below error two seconds after it gets opened. However when I open connection without spring security enabled connection does not get dropped.

angular2 connect()/subscribe()/send() - all go with JWT token

public connect() : void {
        let sockjs = new SockJS('/rest/add?jwt=' + this.authService.getToken());
        let headers : any = this.authService.getAuthHeader();
        this.stompClient = Stomp.over(sockjs);
        this.stompClient.connect(this.token, (frame) => {
            this.log.d("frame", "My Frame: " + frame);
            this.log.d("connected()", "connected to /add");
            this.stompClient.subscribe('/topic/addMessage', this.authService.getAuthHeader(), (stompResponse) => {
                // this.stompSubject.next(JSON.parse(stompResponse.body));
                this.log.d("result of WS call: ", JSON.parse(stompResponse.body).message);
            }, (error) => {
                this.log.d(error);
            });
        });
    }

    public send(payload: string) {
        this.stompClient.send("/app/add", this.token, JSON.stringify({'message': payload}));
    }```
</div>
</div>
</p>

<p><strong>JwtAuthenticationFilter.java</strong> </p>

```public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public JwtAuthenticationFilter() {
        super("/rest/**");
    }

    @Override
    protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
        return true;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String token = null;

        String param = request.getParameter("jwt");
        if(param == null) {
            String header = request.getHeader("Authorization");
            if (header == null || !header.startsWith("Bearer ")) {
                throw new JwtAuthenticationException("No JWT token found in request headers");
            }
            token = header.substring(7);
        } else {
            token = param;
        }
        JwtAuthenticationToken authRequest = new JwtAuthenticationToken(token);

        return getAuthenticationManager().authenticate(authRequest);
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        super.successfulAuthentication(request, response, chain, authResult);

        // As this authentication is in HTTP header, after success we need to continue the request normally
        // and return the response as if the resource was not secured at all
        chain.doFilter(request, response);
    }
}
```

<p><strong>JwtAuthenticationProvider.java</strong></p>

```@Service
public class JwtAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

    @Autowired
    private SecurityService securityService;

    @Override
    public boolean supports(Class<?> authentication) {
        return (JwtAuthenticationToken.class.isAssignableFrom(authentication));
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    }

    @Override
    @Transactional(readOnly=true)
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        JwtAuthenticationToken jwtAuthenticationToken = (JwtAuthenticationToken) authentication;
        String token = jwtAuthenticationToken.getToken();

        User user = securityService.parseToken(token);

        if (user == null) {
            throw new JwtAuthenticationException("JWT token is not valid");
        }

        return new AuthenticatedUser(user);
    }
}
```

<p><strong>JwtAuthenticationSuccessHandler.java</strong></p>

```@Service
public class JwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        // We do not need to do anything extra on REST authentication success, because there is no page to redirect to
    }

}
```

<p><strong>RestAuthenticationEntryPoint.java</strong></p>

```@Service
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        // This is invoked when user tries to access a secured REST resource without supplying any credentials
        // We should just send a 401 Unauthorized response because there is no 'login page' to redirect to
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }
}
```

<p><strong>Weboscket configuration:</strong></p>

```<websocket:message-broker
    application-destination-prefix="/app">
    <websocket:stomp-endpoint path="/add">
        <websocket:sockjs />
    </websocket:stomp-endpoint>
    <websocket:simple-broker prefix="/topic, /queue" />
</websocket:message-broker>
```

<p>and my spring security</p>

```<context:component-scan base-package="com.myapp.ws.security"/>

<sec:global-method-security pre-post-annotations="enabled" />

<sec:http pattern="/rest/login/" security="none" />

<sec:http pattern="/rest/**" entry-point-ref="restAuthenticationEntryPoint" create-session="stateless">

    <sec:csrf disabled="true" />

    <sec:custom-filter before="FORM_LOGIN_FILTER" ref="jwtAuthenticationFilter" />
</sec:http>

<bean id="jwtAuthenticationFilter" class="com.myapp.ws.security.JwtAuthenticationFilter">
    <property name="authenticationManager" ref="authenticationManager" />
    <property name="authenticationSuccessHandler" ref="jwtAuthenticationSuccessHandler" />
</bean>

<sec:authentication-manager alias="authenticationManager">
    <sec:authentication-provider ref="jwtAuthenticationProvider" />
</sec:authentication-manager>
```

答:
@user1516873 finally I got it working:

passing correct parameters to STOMP fixed one problem

adding {transports: ["websocket"]} was not necessary (it works without it)

Problem was that I was using angular-cli server on port 4200 with proxy file like this:

{
  "/rest": {
    "target": "http://localhost:8080",
    "secure": false
  }
}

but should have been like this:

{
  "/rest": {
    "target": "http://localhost:8080",
    "secure": false,
    "ws": true,
    "logLevel": "debug"
  }
}

so through all the combinations of configuration I was always checking through 4200 proxy server and very rarely through native 8080 directly. I just didn't know that angular-cli proxy does not support when spring security is applied. I will accept your answer as you helped a lot!

Body:
In one of my projects I configured both rest services and websockets, both go through spring security filter that check for JWT. For websockets on the client side, application uses sockjs & stomp (on Angular2) and Spring websockets on the server side (Tomcat 8). When I open connection with Spring security enabled then I get below error two seconds after it gets opened. However when I open connection without spring security enabled connection does not get dropped.

angular2 connect()/subscribe()/send() - all go with JWT token

public connect() : void {
        let sockjs = new SockJS('/rest/add?jwt=' + this.authService.getToken());
        let headers : any = this.authService.getAuthHeader();
        this.stompClient = Stomp.over(sockjs);
        this.stompClient.connect(this.token, (frame) => {
            this.log.d("frame", "My Frame: " + frame);
            this.log.d("connected()", "connected to /add");
            this.stompClient.subscribe('/topic/addMessage', this.authService.getAuthHeader(), (stompResponse) => {
                // this.stompSubject.next(JSON.parse(stompResponse.body));
                this.log.d("result of WS call: ", JSON.parse(stompResponse.body).message);
            }, (error) => {
                this.log.d(error);
            });
        });
    }

    public send(payload: string) {
        this.stompClient.send("/app/add", this.token, JSON.stringify({'message': payload}));
    }

JwtAuthenticationFilter.java

public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public JwtAuthenticationFilter() {
        super("/rest/**");
    }

    @Override
    protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
        return true;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String token = null;

        String param = request.getParameter("jwt");
        if(param == null) {
            String header = request.getHeader("Authorization");
            if (header == null || !header.startsWith("Bearer ")) {
                throw new JwtAuthenticationException("No JWT token found in request headers");
            }
            token = header.substring(7);
        } else {
            token = param;
        }
        JwtAuthenticationToken authRequest = new JwtAuthenticationToken(token);

        return getAuthenticationManager().authenticate(authRequest);
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        super.successfulAuthentication(request, response, chain, authResult);

        // As this authentication is in HTTP header, after success we need to continue the request normally
        // and return the response as if the resource was not secured at all
        chain.doFilter(request, response);
    }
}

JwtAuthenticationProvider.java

@Service
public class JwtAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

    @Autowired
    private SecurityService securityService;

    @Override
    public boolean supports(Class<?> authentication) {
        return (JwtAuthenticationToken.class.isAssignableFrom(authentication));
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    }

    @Override
    @Transactional(readOnly=true)
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        JwtAuthenticationToken jwtAuthenticationToken = (JwtAuthenticationToken) authentication;
        String token = jwtAuthenticationToken.getToken();

        User user = securityService.parseToken(token);

        if (user == null) {
            throw new JwtAuthenticationException("JWT token is not valid");
        }

        return new AuthenticatedUser(user);
    }
}

JwtAuthenticationSuccessHandler.java

@Service
public class JwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        // We do not need to do anything extra on REST authentication success, because there is no page to redirect to
    }

}

RestAuthenticationEntryPoint.java

@Service
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        // This is invoked when user tries to access a secured REST resource without supplying any credentials
        // We should just send a 401 Unauthorized response because there is no 'login page' to redirect to
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }
}

Weboscket configuration:

<websocket:message-broker
    application-destination-prefix="/app">
    <websocket:stomp-endpoint path="/add">
        <websocket:sockjs />
    </websocket:stomp-endpoint>
    <websocket:simple-broker prefix="/topic, /queue" />
</websocket:message-broker>

and my spring security

<context:component-scan base-package="com.myapp.ws.security"/>

<sec:global-method-security pre-post-annotations="enabled" />

<sec:http pattern="/rest/login/" security="none" />

<sec:http pattern="/rest/**" entry-point-ref="restAuthenticationEntryPoint" create-session="stateless">

    <sec:csrf disabled="true" />

    <sec:custom-filter before="FORM_LOGIN_FILTER" ref="jwtAuthenticationFilter" />
</sec:http>

<bean id="jwtAuthenticationFilter" class="com.myapp.ws.security.JwtAuthenticationFilter">
    <property name="authenticationManager" ref="authenticationManager" />
    <property name="authenticationSuccessHandler" ref="jwtAuthenticationSuccessHandler" />
</bean>

<sec:authentication-manager alias="authenticationManager">
    <sec:authentication-provider ref="jwtAuthenticationProvider" />
</sec:authentication-manager>


问:
Serving static files Go seems inefficient..or maybe its just me :-)
Over months I've read tons of articles about Go and best practices.  Among those articles are numerous google searches and SOF searches regarding how to and the best way to serve static files.

This is what I currently have

```<code>fs := http.FileServer(http.Dir("static/"))
myRouter.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))

myRouter.PathPrefix("/admin/static/").Handler(http.StripPrefix("/admin/static/", fs))
myRouter.PathPrefix("/admin/accounts/static/").Handler(http.StripPrefix("/admin/accounts/static/", fs))
myRouter.PathPrefix("/admin/admin_tools/static/").Handler(http.StripPrefix("/admin/admin_tools/static/", fs))
myRouter.PathPrefix("/admin/audit_tools/static/").Handler(http.StripPrefix("/admin/audit_tools/static/", fs))
myRouter.PathPrefix("/admin/demand/static/").Handler(http.StripPrefix("/admin/demand/static/", fs))
myRouter.PathPrefix("/admin/optimization/static/").Handler(http.StripPrefix("/admin/optimization/static/", fs))
myRouter.PathPrefix("/admin/reports/static/").Handler(http.StripPrefix("/admin/reports/static/", fs))
myRouter.PathPrefix("/admin/setups/static/").Handler(http.StripPrefix("/admin/setups/static/", fs))
myRouter.PathPrefix("/admin/queue/static/").Handler(http.StripPrefix("/admin/queue/static/", fs))
myRouter.PathPrefix("/admin/tagservers/static/").Handler(http.StripPrefix("/admin/tagservers/static/", fs))
myRouter.PathPrefix("/admin/client/static/").Handler(http.StripPrefix("/admin/client/static/", fs))
myRouter.PathPrefix("/client/static/").Handler(http.StripPrefix("/client/static/", fs))
</code>```

My issue with this is that for every path I have to add a new line to cover where the static files come from.  Most examples show how it's done when you have a single landing page with no real navigations built into it. Coming from a Python background I suppose I was bit spoiled with some of the lightweight frameworks, such as Flask and Tornado, where one just points to the static folder once.

Another issue with this current setup is it doesn't play nice with NGINX.  Again with frameworks like Flask and Tornado, all you have to do in NGINX is set the static location once.  With Go I have to set the static location just like the code above (by defining each path).

Has anyone found a better way to serve static files?  I know in theory a function could probably be written to automate it, but it wouldn't really change the fact that each path has to be accounted for on the app level and NGINX level.

UPDATE: In reply to @mkopriva I've attached two screenshots.  The first is of the browser running the app with dev tools open to show the 404s on the static files. The Second is of the server code, to produce those errors all I did was comment out one line.  The line that handles the audit_tools path. If I uncomment it everything routes no problem.

Edit, both @mkopriva and @sberry did a great job. I wish I could pick two correct answers.

答:
All those PathPrefix and StripPrefix calls seem to me to be functionally pointless. If your static directory is inside your Go project and its structure looks something like this:

```<code>.
├── main.go
└── static
    ├── admin
    │   ├── accounts
    │   │   └── file.txt
    │   ├── file.txt
    │   └── reports
    │       └── file.txt
    └── file.txt
</code>```

then to serve files from that static directory with Go, all you should really need is this.

```<code>package main

import (
    "log"
    "net/http"
)

func main() {
    fs := http.FileServer(http.Dir("static/"))
    http.Handle("/", fs)

    log.Fatal(http.ListenAndServe(":8080", nil))
}
</code>```

Body:
Over months I've read tons of articles about Go and best practices.  Among those articles are numerous google searches and SOF searches regarding how to and the best way to serve static files.

This is what I currently have

fs := http.FileServer(http.Dir("static/"))
myRouter.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))

myRouter.PathPrefix("/admin/static/").Handler(http.StripPrefix("/admin/static/", fs))
myRouter.PathPrefix("/admin/accounts/static/").Handler(http.StripPrefix("/admin/accounts/static/", fs))
myRouter.PathPrefix("/admin/admin_tools/static/").Handler(http.StripPrefix("/admin/admin_tools/static/", fs))
myRouter.PathPrefix("/admin/audit_tools/static/").Handler(http.StripPrefix("/admin/audit_tools/static/", fs))
myRouter.PathPrefix("/admin/demand/static/").Handler(http.StripPrefix("/admin/demand/static/", fs))
myRouter.PathPrefix("/admin/optimization/static/").Handler(http.StripPrefix("/admin/optimization/static/", fs))
myRouter.PathPrefix("/admin/reports/static/").Handler(http.StripPrefix("/admin/reports/static/", fs))
myRouter.PathPrefix("/admin/setups/static/").Handler(http.StripPrefix("/admin/setups/static/", fs))
myRouter.PathPrefix("/admin/queue/static/").Handler(http.StripPrefix("/admin/queue/static/", fs))
myRouter.PathPrefix("/admin/tagservers/static/").Handler(http.StripPrefix("/admin/tagservers/static/", fs))
myRouter.PathPrefix("/admin/client/static/").Handler(http.StripPrefix("/admin/client/static/", fs))
myRouter.PathPrefix("/client/static/").Handler(http.StripPrefix("/client/static/", fs))

My issue with this is that for every path I have to add a new line to cover where the static files come from.  Most examples show how it's done when you have a single landing page with no real navigations built into it. Coming from a Python background I suppose I was bit spoiled with some of the lightweight frameworks, such as Flask and Tornado, where one just points to the static folder once.

Another issue with this current setup is it doesn't play nice with NGINX.  Again with frameworks like Flask and Tornado, all you have to do in NGINX is set the static location once.  With Go I have to set the static location just like the code above (by defining each path).

Has anyone found a better way to serve static files?  I know in theory a function could probably be written to automate it, but it wouldn't really change the fact that each path has to be accounted for on the app level and NGINX level.

UPDATE: In reply to @mkopriva I've attached two screenshots.  The first is of the browser running the app with dev tools open to show the 404s on the static files. The Second is of the server code, to produce those errors all I did was comment out one line.  The line that handles the audit_tools path. If I uncomment it everything routes no problem.

Edit, both @mkopriva and @sberry did a great job. I wish I could pick two correct answers.

Body:
All those PathPrefix and StripPrefix calls seem to me to be functionally pointless. If your static directory is inside your Go project and its structure looks something like this:

.
├── main.go
└── static
    ├── admin
    │   ├── accounts
    │   │   └── file.txt
    │   ├── file.txt
    │   └── reports
    │       └── file.txt
    └── file.txt

then to serve files from that static directory with Go, all you should really need is this.

package main

import (
    "log"
    "net/http"
)

func main() {
    fs := http.FileServer(http.Dir("static/"))
    http.Handle("/", fs)

    log.Fatal(http.ListenAndServe(":8080", nil))
}


问:
Move game object in direction its facing without rigidbody
I want an object (bullet) in 2d space move towards the direction its rotated in. Im using

```<code>   transform.position += Vector3.up * Time.deltaTime * Speed;
</code>```

which makes it just move upwards no matter what rotation the z axis has. What am i missing?

The bullet has no ned for a rigidbody2d component so i want to do it without.

答:
Multiply transform by any desired numbers

```<code>transform.position += Vector3.forward * Time.deltaTime * movementSpeed;
</code>```

ref

Body:
I want an object (bullet) in 2d space move towards the direction its rotated in. Im using

   transform.position += Vector3.up * Time.deltaTime * Speed;

which makes it just move upwards no matter what rotation the z axis has. What am i missing?

The bullet has no ned for a rigidbody2d component so i want to do it without.

Body:
Multiply transform by any desired numbers

transform.position += Vector3.forward * Time.deltaTime * movementSpeed;

ref


问:
How can I invoke a Model's method from view in a Xamarin PCL project
I'd like to call a method that is located in a class LoginViewModel but it is inacessible. How can I render it accessible from the Login.xaml.cs code behind so that i can call the Connexion() method ?

Login.xaml

```<code><Button
            StyleId="btn_connexion"
            Text="Connexion"
                Clicked="Connexion_click" />
</code>```

Login.xaml.cs

```<code>private void Connexion_click(object sender, EventArgs e)
        {
           //here is where i'd like to call the connexion method
        }
</code>```

LoginViewModel.cs

```<code>public async Task Connexion()
        {

            List<Visiteur> listeTest = CreerListeVisiteurDur();
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                foreach (Visiteur unVisiteur in listeTest)
                {
                    string login = unVisiteur.login;
                    string pass = unVisiteur.mdp;

                    if (login == username && pass == password)
                    {
                        App.Current.MainPage = new CreerVisite();
                    }

                }
            }
</code>```

答:
I agree with Alessandro Caliaro on your chosen design pattern; however, you can use the code below to achieve what you're asking for.

BtnClicker.xaml.cs

```<code> namespace BountyApp.Pages
{

    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class BtnClicker : ContentPage
    {
        BtnClickerViewModel model = new BtnClickerViewModel();
        public BtnClicker()
        {
            InitializeComponent();
            BindingContext = model;

        }

        private void Button_Clicked(object sender, EventArgs e)
        {
            Device.BeginInvokeOnMainThread(async () =>
            {
                await model.Connexion();
            });

        }
    }

    class BtnClickerViewModel : INotifyPropertyChanged
    {
        public async Task Connexion()
        {
            List<Visiteur> listeTest = CreerListeVisiteurDur();
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                foreach (Visiteur unVisiteur in listeTest)
                {
                    string login = unVisiteur.login;
                    string pass = unVisiteur.mdp;

                    if (login == username && pass == password)
                    {
                        App.Current.MainPage = new CreerVisite();
                    }

                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        void OnPropertyChanged([CallerMemberName]string propertyName = "") =>
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

    }
}
</code>```

BtnClicker.xaml

This button will be huge, so you'll want to adjust it appropriately.

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="BountyApp.Pages.BtnClicker"
             Title="BtnClicker">
    <Button StyleId="btn_connexion" Text="Connexion" Clicked="Button_Clicked"></Button>
</ContentPage>
</code>```

Body:
I'd like to call a method that is located in a class LoginViewModel but it is inacessible. How can I render it accessible from the Login.xaml.cs code behind so that i can call the Connexion() method ?

Login.xaml

<Button
            StyleId="btn_connexion"
            Text="Connexion"
                Clicked="Connexion_click" />

Login.xaml.cs

private void Connexion_click(object sender, EventArgs e)
        {
           //here is where i'd like to call the connexion method
        }

LoginViewModel.cs

public async Task Connexion()
        {

            List<Visiteur> listeTest = CreerListeVisiteurDur();
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                foreach (Visiteur unVisiteur in listeTest)
                {
                    string login = unVisiteur.login;
                    string pass = unVisiteur.mdp;

                    if (login == username && pass == password)
                    {
                        App.Current.MainPage = new CreerVisite();
                    }

                }
            }

Body:
I agree with Alessandro Caliaro on your chosen design pattern; however, you can use the code below to achieve what you're asking for.

BtnClicker.xaml.cs

 namespace BountyApp.Pages
{

    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class BtnClicker : ContentPage
    {
        BtnClickerViewModel model = new BtnClickerViewModel();
        public BtnClicker()
        {
            InitializeComponent();
            BindingContext = model;

        }

        private void Button_Clicked(object sender, EventArgs e)
        {
            Device.BeginInvokeOnMainThread(async () =>
            {
                await model.Connexion();
            });

        }
    }

    class BtnClickerViewModel : INotifyPropertyChanged
    {
        public async Task Connexion()
        {
            List<Visiteur> listeTest = CreerListeVisiteurDur();
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                foreach (Visiteur unVisiteur in listeTest)
                {
                    string login = unVisiteur.login;
                    string pass = unVisiteur.mdp;

                    if (login == username && pass == password)
                    {
                        App.Current.MainPage = new CreerVisite();
                    }

                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        void OnPropertyChanged([CallerMemberName]string propertyName = "") =>
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

    }
}

BtnClicker.xaml

This button will be huge, so you'll want to adjust it appropriately.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="BountyApp.Pages.BtnClicker"
             Title="BtnClicker">
    <Button StyleId="btn_connexion" Text="Connexion" Clicked="Button_Clicked"></Button>
</ContentPage>


问:
Manipulations with bits
I have binary file that is represented in hexa e.g

```<code> 4d42 b666 000a 0000 0000 0036 0000 0028
</code>```

The first 4 bytes represent value which i want to extract.

I know i can extract it right

```<code>std::ifstream is("img.bmp", std::ifstream::binary);
uint64_t data = 0;
is.read((char*)&data,4)
</code>```

which would result in 3060157762

However using

```<code>  unsigned char * test   = new unsigned char [ 4  ];
  is.read((char*)test , 4 );
  uint64_t t = 0;
  for( int i = 0; i < 4;i++){
    t <<= 8; // 2 hexa symbols = 1 byte = 1 char = 8 bits
    t|= test[i];
  }
  cout << t << endl;
</code>```

this results in 1112368822 which obviously differ.

I wonder how could we achieve same result with second method? What are some bitwise tricks for this? I cannot think of anything besides the method i have shown.

Thanks for help.

答:
First of all, use 4 byte type to store 4 bytes. You dont need 64 bit type. The thing is that you're reversing your number in the loop.
Your second method reads 4 bytes into test like that: test[0] = 0x4, test[1] = 0xd, test[2] = 0x4, test[3] = 0x2. What you do then is filling bytes of t in the reverse order, from right to the left. First, you fill the rightmost byte with 0x4, then moving to the left with 0xd, 0x4 and 0x2 accordingly. So you get t == 0x24d4.

Code that does the thing:

```<code>unsigned char * test = new unsigned char [4];
is.read((char*)test, 4);
uint32_t t = 0;
for(int i = 3; i >= 0; --i) {
    t <<= 8;
    t |= test[i];
}
cout << t << endl;
</code>```

Title: Manipulations with bits

Body:
I have binary file that is represented in hexa e.g

 4d42 b666 000a 0000 0000 0036 0000 0028

The first 4 bytes represent value which i want to extract.

I know i can extract it right

std::ifstream is("img.bmp", std::ifstream::binary);
uint64_t data = 0;
is.read((char*)&data,4)

which would result in 3060157762

However using

  unsigned char * test   = new unsigned char [ 4  ];
  is.read((char*)test , 4 );
  uint64_t t = 0;
  for( int i = 0; i < 4;i++){
    t <<= 8; // 2 hexa symbols = 1 byte = 1 char = 8 bits
    t|= test[i];
  }
  cout << t << endl;

this results in 1112368822 which obviously differ.

I wonder how could we achieve same result with second method? What are some bitwise tricks for this? I cannot think of anything besides the method i have shown.

Thanks for help.

Body:
First of all, use 4 byte type to store 4 bytes. You dont need 64 bit type. The thing is that you're reversing your number in the loop.
Your second method reads 4 bytes into test like that: test[0] = 0x4, test[1] = 0xd, test[2] = 0x4, test[3] = 0x2. What you do then is filling bytes of t in the reverse order, from right to the left. First, you fill the rightmost byte with 0x4, then moving to the left with 0xd, 0x4 and 0x2 accordingly. So you get t == 0x24d4.

Code that does the thing:

unsigned char * test = new unsigned char [4];
is.read((char*)test, 4);
uint32_t t = 0;
for(int i = 3; i >= 0; --i) {
    t <<= 8;
    t |= test[i];
}
cout << t << endl;


问:
how to create pointer to function in codesys v3
Can you give me an example of how can I declare a pointer to function in my library? And how can I pass a pointer to function to my external library?</p>

答:
Pointers are possible in codesys.To create a pointer in codesys you would do

```<code>VAR
  pVar : POINTER TO BYTE;
  tempVar  : BYTE;
  derefereceVar : BYTE;
END_VAR

//get a pointer to the byte variable
pVar := ADR(tempVar);
</code>```

to dereference that pointer you would

```<code>derefereceVar := tempVar^;
</code>```

So if you wanted to have a pointer as an argument to your function you would pass in pVar or ADR(tempVar) in the example above to a parameter of your function that takes a POINTER_TO_BYTE as the type.

Body:
Pointers are possible in codesys.To create a pointer in codesys you would do

VAR
  pVar : POINTER TO BYTE;
  tempVar  : BYTE;
  derefereceVar : BYTE;
END_VAR

//get a pointer to the byte variable
pVar := ADR(tempVar);

to dereference that pointer you would

derefereceVar := tempVar^;

So if you wanted to have a pointer as an argument to your function you would pass in pVar or ADR(tempVar) in the example above to a parameter of your function that takes a POINTER_TO_BYTE as the type.