问:
Issues with Pipeline and GridSearchCV
I have some issues with the use of the Pipeline Tool and the GridSearchCV.
I get the following error message: "TypeError: Last step of Pipeline should implement fit or be the string 'passthrough'. '1' (type ) doesn't".

Do you see where is my mistake here?

Here's my code:

```<code>from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline

X = wage['age'][:, np.newaxis]
y = wage['wage'][:, np.newaxis]

degree = 2
model = Pipeline(steps=[('poly', PolynomialFeatures(degree)), ('linear', LinearRegression(fit_intercept=False))])

param_grid = {'poly': [1, 2, 3, 4, 5]}
cv_model = GridSearchCV(model, param_grid, scoring='r2', cv=5, n_jobs=1)
cv_model.fit(X, y)
</code>```

答:
It might be possible that the problem comes from the fact that I didn't use the '__' notation after the 'poly' in the param_grid.

With this notation, it seems to work:

```<code>param_grid = {'poly__degree': [1, 2, 3, 4, 5]}
</code>```

Title: Issues with Pipeline and GridSearchCV

Body:
I have some issues with the use of the Pipeline Tool and the GridSearchCV.
I get the following error message: "TypeError: Last step of Pipeline should implement fit or be the string 'passthrough'. '1' (type ) doesn't".

Do you see where is my mistake here?

Here's my code:

from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline

X = wage['age'][:, np.newaxis]
y = wage['wage'][:, np.newaxis]

degree = 2
model = Pipeline(steps=[('poly', PolynomialFeatures(degree)), ('linear', LinearRegression(fit_intercept=False))])

param_grid = {'poly': [1, 2, 3, 4, 5]}
cv_model = GridSearchCV(model, param_grid, scoring='r2', cv=5, n_jobs=1)
cv_model.fit(X, y)

Body:
It might be possible that the problem comes from the fact that I didn't use the '__' notation after the 'poly' in the param_grid.

With this notation, it seems to work:

param_grid = {'poly__degree': [1, 2, 3, 4, 5]}


来源: stackexchange

问:
Python Select first word in a string without using methods
I have a homework assignment where I have to select the first word in a string. Normally I would do this:

```<code>s = "Hello World"
words = s.split()
first_word = words[0]
print(first_word)
</code>```

For this assignment I cannot use methods or loops to answer the question. Any ideas?

答:
Find the index of the first space character, then use string slicing:

```<code>s = "Hello World"

print(s[:s.index(' ')])
</code>```

No loops, but does use the .index() method...

Could also try a recursive function:

```<code>s = "Hello World"

def first_word(string):

    if string[0] == ' ':
        return ''
    else:
        new_string = string[0] + first_word(string[1:])
    return new_string

print(first_word(s))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a homework assignment where I have to select the first word in a string. Normally I would do this:

s = "Hello World"
words = s.split()
first_word = words[0]
print(first_word)

For this assignment I cannot use methods or loops to answer the question. Any ideas?

Body:
Find the index of the first space character, then use string slicing:

s = "Hello World"

print(s[:s.index(' ')])

No loops, but does use the .index() method...

Could also try a recursive function:

s = "Hello World"

def first_word(string):

    if string[0] == ' ':
        return ''
    else:
        new_string = string[0] + first_word(string[1:])
    return new_string

print(first_word(s))


问:
An instance of OnFlingListener already set in Recyclerview
I'm using a RecyclerView in my Android app. I've many cardviews in my RecyclerView, such that only 1 cardview is displayed to the user at a time. The user has to swipe to see the next card.

I faced an issue that when user makes a swipe, the recyclerview gets scrolled to the end. Instead, what I need is when the user swipes, display the next card to the user as mentioned in this post.

How to make swipe on horizontal recyclerview bring only the next item into view - Android

```<code>SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
</code>```

I tried the answer mentioned in the above link. But I'm getting an exception when the user makes a swipe.

Please help me resolve it.

Error

```<code>java.lang.IllegalStateException: An instance of OnFlingListener already set.
    at android.support.v7.widget.SnapHelper.setupCallbacks(SnapHelper.java:114)
    at android.support.v7.widget.SnapHelper.attachToRecyclerView(SnapHelper.java:102)
    at com.abc.ui.trm.TrCard.setupCardView(TrCard.java:62)
    at com.abc.ui.trm.TrCard.setupCardView(TrCard.java:29)
    at com.abc.ui.core.card.BaseCardView.processCardView(BaseCardView.java:134)
    at com.abc.ui.card.CardRecyclerAdapter.onViewAttachedToWindow(CardRecyclerAdapter.java:398)
    at android.support.v7.widget.RecyclerView.dispatchChildAttached(RecyclerView.java:6758)
    at android.support.v7.widget.RecyclerView$5.addView(RecyclerView.java:696)
    at android.support.v7.widget.ChildHelper.addView(ChildHelper.java:107)
    at android.support.v7.widget.RecyclerView$LayoutManager.addViewInt(RecyclerView.java:7697)
    at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:7655)
    at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:7643)
    at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1539)
    at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1488)
    at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:585)
    at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3506)
    at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3254)
    at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3767)
    at android.view.View.layout(View.java:18799)
    at android.view.ViewGroup.layout(ViewGroup.java:5952)
    at com.abc.ui.core.refresh.LegacySwipeRefreshLayout.onLayout(LegacySwipeRefreshLayout.java:337)
    at android.view.View.layout(View.java:18799)
    at android.view.ViewGroup.layout(ViewGroup.java:5952)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:18799)
    at android.view.ViewGroup.layout(ViewGroup.java:5952)
    at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
    at android.view.View.layout(View.java:18799)
    at android.view.ViewGroup.layout(ViewGroup.java:5952)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:18799)
    at android.view.ViewGroup.layout(ViewGroup.java:5952)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:18799)
    at android.view.ViewGroup.layout(ViewGroup.java:5952)
    at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1193)
    at android.view.View.layout(View.java:18799)
    at android.view.ViewGroup.layout(ViewGroup.java:5952)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:18799)
    at android.view.ViewGroup.layout(ViewGroup.java:5952)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
    at android.view.View.layout(View.java:18799)
    at android.view.ViewGroup.layout(ViewGroup.java:5952)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at com.android.internal.policy.DecorView.onLayout(DecorView.java:822)
    at android.view.View.layout(View.java:18799)
    at android.view.ViewGroup.layout(ViewGroup.java:5952)
</code>```

答:
This happens because you're setting the SnapPagerHelper twice somehow. Note that if you have a RecyclerView inside another RecyclerView, this should only happen in each other's constructors or Kotlin's init {} block (once per item).

My case is quite similar to yours since I have a big vertical RecyclerView and a small RecyclerView within.

Code that will cause the exception:

```<code> fun bind(value: ArrayList<Item>) {
    listAdapter = ItemCellDelegate(value)

    val manager = LinearLayoutManager(itemView.context)
    manager.orientation = LinearLayoutManager.HORIZONTAL

    horizontalRecyclerView?.apply {
        layoutManager = manager
        adapter = listAdapter
        setHasFixedSize(true)
    }

    val snapHelper: SnapHelper = PagerSnapHelper()
    snapHelper.attachToRecyclerView(horizontalRecyclerView)

}
</code>```

Correct code using init {} block:

```<code>init {
    val snapHelper: SnapHelper = PagerSnapHelper()
    snapHelper.attachToRecyclerView(horizontalRecyclerView)
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using a RecyclerView in my Android app. I've many cardviews in my RecyclerView, such that only 1 cardview is displayed to the user at a time. The user has to swipe to see the next card.

I faced an issue that when user makes a swipe, the recyclerview gets scrolled to the end. Instead, what I need is when the user swipes, display the next card to the user as mentioned in this post.

How to make swipe on horizontal recyclerview bring only the next item into view - Android

SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);

I tried the answer mentioned in the above link. But I'm getting an exception when the user makes a swipe.

Please help me resolve it.

Error

java.lang.IllegalStateException: An instance of OnFlingListener already set.
    at android.support.v7.widget.SnapHelper.setupCallbacks(SnapHelper.java:114)
    at android.support.v7.widget.SnapHelper.attachToRecyclerView(SnapHelper.java:102)
    at com.abc.ui.trm.TrCard.setupCardView(TrCard.java:62)
    at com.abc.ui.trm.TrCard.setupCardView(TrCard.java:29)
    at com.abc.ui.core.card.BaseCardView.processCardView(BaseCardView.java:134)
    at com.abc.ui.card.CardRecyclerAdapter.onViewAttachedToWindow(CardRecyclerAdapter.java:398)
    at android.support.v7.widget.RecyclerView.dispatchChildAttached(RecyclerView.java:6758)
    at android.support.v7.widget.RecyclerView$5.addView(RecyclerView.java:696)
    at android.support.v7.widget.ChildHelper.addView(ChildHelper.java:107)
    at android.support.v7.widget.RecyclerView$LayoutManager.addViewInt(RecyclerView.java:7697)
    at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:7655)
    at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:7643)
    at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1539)
    at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1488)
    at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:585)
    at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3506)
    at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3254)
    at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3767)
    at android.view.View.layout(View.java:18799)
    at android.view.ViewGroup.layout(ViewGroup.java:5952)
    at com.abc.ui.core.refresh.LegacySwipeRefreshLayout.onLayout(LegacySwipeRefreshLayout.java:337)
    at android.view.View.layout(View.java:18799)
    at android.view.ViewGroup.layout(ViewGroup.java:5952)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:18799)
    at android.view.ViewGroup.layout(ViewGroup.java:5952)
    at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
    at android.view.View.layout(View.java:18799)
    at android.view.ViewGroup.layout(ViewGroup.java:5952)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:18799)
    at android.view.ViewGroup.layout(ViewGroup.java:5952)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:18799)
    at android.view.ViewGroup.layout(ViewGroup.java:5952)
    at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1193)
    at android.view.View.layout(View.java:18799)
    at android.view.ViewGroup.layout(ViewGroup.java:5952)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:18799)
    at android.view.ViewGroup.layout(ViewGroup.java:5952)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
    at android.view.View.layout(View.java:18799)
    at android.view.ViewGroup.layout(ViewGroup.java:5952)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at com.android.internal.policy.DecorView.onLayout(DecorView.java:822)
    at android.view.View.layout(View.java:18799)
    at android.view.ViewGroup.layout(ViewGroup.java:5952)

Body:
This happens because you're setting the SnapPagerHelper twice somehow. Note that if you have a RecyclerView inside another RecyclerView, this should only happen in each other's constructors or Kotlin's init {} block (once per item).

My case is quite similar to yours since I have a big vertical RecyclerView and a small RecyclerView within.

Code that will cause the exception:

 fun bind(value: ArrayList<Item>) {
    listAdapter = ItemCellDelegate(value)

    val manager = LinearLayoutManager(itemView.context)
    manager.orientation = LinearLayoutManager.HORIZONTAL

    horizontalRecyclerView?.apply {
        layoutManager = manager
        adapter = listAdapter
        setHasFixedSize(true)
    }

    val snapHelper: SnapHelper = PagerSnapHelper()
    snapHelper.attachToRecyclerView(horizontalRecyclerView)

}

Correct code using init {} block:

init {
    val snapHelper: SnapHelper = PagerSnapHelper()
    snapHelper.attachToRecyclerView(horizontalRecyclerView)
}


问:
Databricks Notebook with %run - Not working
I have referenced the topic - How to pass a variable to magic ´run´ function in IPython for triggering a Notebook from another Notebook.

```<code>notebook = "/Users/xxx/TestFolder/Notebook1"
</code>```

In the next cell, I am trying to call %run like this as per the solution suggested in the above article:

```<code>%run $notebook
</code>```

I get the below error:
Notebook not found: $notebook. Notebooks can be specified via a relative path. Is it possible to pass a string variable along with %run?

I could get around with something like this:
dbutils.notebook.run(notebook, 300 ,{})

答:
You can do it with %run, pass param notebook_paramname </p>

```<code>Python/Scala cell:
    notebook = "/Users/xxx/TestFolder/Notebook1"

Magic cell:
    %run $notebook_paramname = notebook
</code>```

Body:
I have referenced the topic - How to pass a variable to magic ´run´ function in IPython for triggering a Notebook from another Notebook.

notebook = "/Users/xxx/TestFolder/Notebook1"

In the next cell, I am trying to call %run like this as per the solution suggested in the above article:

%run $notebook

I get the below error:
Notebook not found: $notebook. Notebooks can be specified via a relative path. Is it possible to pass a string variable along with %run?

I could get around with something like this:
dbutils.notebook.run(notebook, 300 ,{})

Body:
You can do it with %run, pass param notebook_paramname

Python/Scala cell:
    notebook = "/Users/xxx/TestFolder/Notebook1"

Magic cell:
    %run $notebook_paramname = notebook


答:
As you can't use methods and loops, you could do it using recursion.

def r(a, b=''):
     if len(a) == 0 or a[0] == ' ':
         return b
     return r(a[1:], b + a[0])

s = 'Hello World'
print(r(s))
```

would print Hello.

Title: Python Select first word in a string without using methods

Body:
As you can't use methods and loops, you could do it using recursion.

def r(a, b=''):
     if len(a) == 0 or a[0] == ' ':
         return b
     return r(a[1:], b + a[0])

s = 'Hello World'
print(r(s))

would print Hello.


问:
How to distinguish different responses from useFetch custom hook
Basically in my App.js, I need to call useFetch twice to display spinner/data/error for two tables.

How do I go about distinguish which spinner/data/error is for which table? Because in useEffect I'm returning
{ data, loading, error }, and in App.js, I'm getting the value like so const { data, loading, error } = useFetch(url_order, date). But I want const { data_table1, loading_table1, error_table1 } = useFetch(url_order, date) instead.

This is my useFetch custom hook

```<code>import { useState, useEffect } from "react";

export default function useFetch(url, date) {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  useEffect(() => {
    const doFetch = async () => {
      setLoading(true);
      try {
        const res = await fetch(url);
        const json = await res.json;
        setData(json.result.result);
      } catch (error) {
        setError(true);
      }
      setLoading(false);
    };
    doFetch();
  }, [date]);

  return { data, loading, error };
}
</code>```

This is my App.js

```<code>import React from "react";
import useFetch from "./hooks/useFetch";
import OrderTable from "./OrderTable";
import IngredientTable from "./IngredientTable";

const App = () => {
  const { data, loading, error } = useFetch(url_order, date);
  const { data, loading, error } = useFetch(url_ingredient, date);

  return (
    <div>
      {loading ? (
        <BeatLoader css={override} color={"#36D7B7"} loading={loading} />
      ) : error ? (
        <h3>Failed to fetch data for Order's table</h3>
      ) : (
        <OrderTable data={data} />
      )}

      {loading ? (
        <BeatLoader css={override} color={"#36D7B7"} loading={loading} />
      ) : error ? (
        <h3>Failed to fetch data for Ingredient's table</h3>
      ) : (
        <IngredientTable data={data} />
      )}
    </div>
  );
};

export default App;
</code>```

答:
Another simple solution is to rename the destructured props like this:

```<code>const { data: order_data, loading: order_loading, error: order_error } = useFetch(url_order, date);
const { data: ingredient_data, loading: ingredient_loading, error: ingredient_error } = useFetch(url_order, date };
</code>```

Now you can access:

```<code>order_data
order_loading
order_error
ingredient_data
ingredient_loading
ingredient_error
</code>```

Body:
Basically in my App.js, I need to call useFetch twice to display spinner/data/error for two tables.

How do I go about distinguish which spinner/data/error is for which table? Because in useEffect I'm returning
{ data, loading, error }, and in App.js, I'm getting the value like so const { data, loading, error } = useFetch(url_order, date). But I want const { data_table1, loading_table1, error_table1 } = useFetch(url_order, date) instead.

This is my useFetch custom hook

import { useState, useEffect } from "react";

export default function useFetch(url, date) {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  useEffect(() => {
    const doFetch = async () => {
      setLoading(true);
      try {
        const res = await fetch(url);
        const json = await res.json;
        setData(json.result.result);
      } catch (error) {
        setError(true);
      }
      setLoading(false);
    };
    doFetch();
  }, [date]);

  return { data, loading, error };
}

This is my App.js

import React from "react";
import useFetch from "./hooks/useFetch";
import OrderTable from "./OrderTable";
import IngredientTable from "./IngredientTable";

const App = () => {
  const { data, loading, error } = useFetch(url_order, date);
  const { data, loading, error } = useFetch(url_ingredient, date);

  return (

      {loading ? (
        <BeatLoader css={override} color={"#36D7B7"} loading={loading} />
      ) : error ? (

Failed to fetch data for Order's table

      ) : (
        <OrderTable data={data} />
      )}

      {loading ? (
        <BeatLoader css={override} color={"#36D7B7"} loading={loading} />
      ) : error ? (

Failed to fetch data for Ingredient's table

      ) : (
        <IngredientTable data={data} />
      )}

  );
};

export default App;

Body:
Another simple solution is to rename the destructured props like this:

const { data: order_data, loading: order_loading, error: order_error } = useFetch(url_order, date);
const { data: ingredient_data, loading: ingredient_loading, error: ingredient_error } = useFetch(url_order, date };

Now you can access:

order_data
order_loading
order_error
ingredient_data
ingredient_loading
ingredient_error


问:
Active Directory Authenticates with Bad Credentials
I am using the npm package activedirectory to connect to my company's domain controller for the purpose of authenticating users on an internal website. The plan is for users to enter their windows domain credentials into the website's login page (written with React). The website will forward the credentials to a backend Express server that looks like this:

const express = require('express');
const bodyParser = require('body-parser');
const ActiveDirectory = require('activedirectory');

const app = express();
app.use(bodyParser.urlencoded({
    extended: false,
}));

app.get('/ldap', (request, response) => {
    // set http header for json
    response.setHeader('ContentType', 'application/json');

    // get the username and password from the query
    const username = request.query.username + '@internal.mycompany.com';
    const password = request.query.password;
    console.log(username, password);

    // create a new active directory connection
    let activeDirectory = new ActiveDirectory({
        url: 'LDAP://internal.mycompany.com',
        baseDN: 'DC=mycompany,DC=com',
    });

    // attempt authentication
    activeDirectory.authenticate(username, password, (error, authenticated) => {
        if(error) {
            console.log('ERROR: ' + JSON.stringify(error));
        }
        else {
            console.log('Authentication successful');
        }

        // respond
        response.send(JSON.stringify({
            error: error,
            authenticated: authenticated,
        }));
    });

});

app.listen(3001, () => {
    console.log('Express server running on port 3001.');
});
```

<p>The React frontend executes this when the 'Log In' button is clicked:</p>

<pre class="lang-js prettyprint-override"><code>login() {
    console.log('authenticating with username: ', this.state.username, ' and password: ', this.state.password);
    fetch(`/ldap/?username=${encodeURIComponent(this.state.username)}&password=${encodeURIComponent(this.state.password)}`).then((response) => {
        return response.json();
    }).then((response) => {
        console.log(response);
        this.props.setLoggedIn(response.authenticated);
        this.setState({
            loginFailed: !response.authenticated,
            redirectToHome: response.authenticated,
        });
    });
}
</code>```

It calls fetch to ask the Express server to authenticate the credentials, and sets some global loggedIn state accordingly. It also sets local state to display an error message if the login attempt failed or redirect the user on to the main website homepage if the login attempt was successful.

Leaving the username and password blank yields this response:

```<code>{
    error: {
        code: 49,
        description: "The supplied credential is invalid",
        errno: "LDAP_INVALID_CREDENTIALS",
    },
    authenticated: false,
}
</code>```

Typing in a valid username and password yields this response:

```<code>{
    error: null,
    authenticated: true,
}
</code>```

This is all as expected up to this point.

However, typing in random characters for the username and password yields one of 2 responses. It either authenticates successfully, which shouldn't happen, or it gives this:

```<code>{
    error: {
        lde_dn: null,
        lde_message: "80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1",
    },
    authenticated: false,
}
</code>```

QUESTION:
Why would giving the domain controller garbage credentials cause it to return authenticated: true? And why only sometimes? Some information must be cached or remembered somewhere. I tried restarting the Express server and I tried waiting a day for something to expire.

Note: I was planning to encrypt/scramble the passwords so that they are not being sent in plain text, but if there is an even better way to send them securely, please leave a comment about how to improve this. But for now the main question is about the incorrect Active Directory/LDAP authentication.

答:
This information: https://www.rfc-editor.org/rfc/rfc4513#section-6.3.1 essentially tells us that getting authenticated: true may not actually mean anything. The solution I came up with is to try and query the Active Directory to see if the user that just authenticated exists and/or try doing an/some operation(s) as the newly-authenticated user. If the operation(s) fail(s), then the login was not valid.

Additionally, there was an error in the above code. baseDN should have been 'DC=internal,DC=mycompany,DC=com'.

Body:
I am using the npm package activedirectory to connect to my company's domain controller for the purpose of authenticating users on an internal website. The plan is for users to enter their windows domain credentials into the website's login page (written with React). The website will forward the credentials to a backend Express server that looks like this:

const express = require('express');
const bodyParser = require('body-parser');
const ActiveDirectory = require('activedirectory');

const app = express();
app.use(bodyParser.urlencoded({
    extended: false,
}));

app.get('/ldap', (request, response) => {
    // set http header for json
    response.setHeader('ContentType', 'application/json');

    // get the username and password from the query
    const username = request.query.username + '@internal.mycompany.com';
    const password = request.query.password;
    console.log(username, password);

    // create a new active directory connection
    let activeDirectory = new ActiveDirectory({
        url: 'LDAP://internal.mycompany.com',
        baseDN: 'DC=mycompany,DC=com',
    });

    // attempt authentication
    activeDirectory.authenticate(username, password, (error, authenticated) => {
        if(error) {
            console.log('ERROR: ' + JSON.stringify(error));
        }
        else {
            console.log('Authentication successful');
        }

        // respond
        response.send(JSON.stringify({
            error: error,
            authenticated: authenticated,
        }));
    });

});

app.listen(3001, () => {
    console.log('Express server running on port 3001.');
});

The React frontend executes this when the 'Log In' button is clicked:

login() {
    console.log('authenticating with username: ', this.state.username, ' and password: ', this.state.password);
    fetch(`/ldap/?username=${encodeURIComponent(this.state.username)}&password=${encodeURIComponent(this.state.password)}`).then((response) => {
        return response.json();
    }).then((response) => {
        console.log(response);
        this.props.setLoggedIn(response.authenticated);
        this.setState({
            loginFailed: !response.authenticated,
            redirectToHome: response.authenticated,
        });
    });
}

It calls fetch to ask the Express server to authenticate the credentials, and sets some global loggedIn state accordingly. It also sets local state to display an error message if the login attempt failed or redirect the user on to the main website homepage if the login attempt was successful.

Leaving the username and password blank yields this response:

{
    error: {
        code: 49,
        description: "The supplied credential is invalid",
        errno: "LDAP_INVALID_CREDENTIALS",
    },
    authenticated: false,
}

Typing in a valid username and password yields this response:

{
    error: null,
    authenticated: true,
}

This is all as expected up to this point.

However, typing in random characters for the username and password yields one of 2 responses. It either authenticates successfully, which shouldn't happen, or it gives this:

{
    error: {
        lde_dn: null,
        lde_message: "80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1",
    },
    authenticated: false,
}

QUESTION:
Why would giving the domain controller garbage credentials cause it to return authenticated: true? And why only sometimes? Some information must be cached or remembered somewhere. I tried restarting the Express server and I tried waiting a day for something to expire.

Note: I was planning to encrypt/scramble the passwords so that they are not being sent in plain text, but if there is an even better way to send them securely, please leave a comment about how to improve this. But for now the main question is about the incorrect Active Directory/LDAP authentication.


问:
GridFS and atomic updates
I'm considering to use MongoDB GridFS to store and retrieve images but reading official documentation (https://docs.mongodb.com/manual/core/gridfs/) I coudn't understand following part:

Do not use GridFS if you need to update the content of the entire file atomically. As an alternative you can store multiple versions of each file and specify the current version of the file in the metadata. You can update the metadata field that indicates “latest” status in an atomic update after uploading the new version of the file, and later remove previous versions if needed.

What does it means when they says: "update the content of the entire file atomically"? What if I need to update a stored image? What happens to stored file?

答:
GridFS splits the contents of a file into chunks (so that each chunk does not exceed the 16 MB document size limit).

As the linked documentation says, GridFS does not support transactions. Without transactions, only individual operations on a document are atomic, but GridFS may perform operations on multiple documents which would not be atomic.

Additionally, file metadata and file contents are stored separately, and again would not be written atomically.

What if I need to update a stored image?

You can insert a new image and then (atomically) update other documents to reference the newly uploaded image.

Title: GridFS and atomic updates


问:
Extend an Array of Optional Equatables?
I'd like to write an extension for operating on an array of optional values that conform to Equatable, for example:

```<code>class Bar: Equatable { ... }

let bar1 = Bar()
let bar2 = Bar()
let bars: [Bar?] = [ bar1, bar2, nil ]
bars.foo() <-- this guy
</code>```

Is there a way to do this with Swift? I've tried many variations similar to this:

```<code>extension Array where Element == Optional<Equatable> {
    func foo() { ... }
}
</code>```

and I understand why Equatable isn't happy, but is there a way around it?

I've found this question which is very similar: How to extend protocol Optional, where Wrapped item is Array of Equatable generic elements? but I need optional elements, not an optional array.

答:
As mentioned in the comments you can't do:

```<code>extension Array where Element == Optional<Equatable>
</code>```

But you can create a generic function in the Array extension:

```<code>extension Array {
    func foo<T: Equatable>() where Element == Optional<T> {
        ...
    }
}
</code>```

Title: Extend an Array of Optional Equatables?

Body:
I'd like to write an extension for operating on an array of optional values that conform to Equatable, for example:

class Bar: Equatable { ... }

let bar1 = Bar()
let bar2 = Bar()
let bars: [Bar?] = [ bar1, bar2, nil ]
bars.foo() <-- this guy

Is there a way to do this with Swift? I've tried many variations similar to this:

extension Array where Element == Optional<Equatable> {
    func foo() { ... }
}

and I understand why Equatable isn't happy, but is there a way around it?

I've found this question which is very similar: How to extend protocol Optional, where Wrapped item is Array of Equatable generic elements? but I need optional elements, not an optional array.

Body:
As mentioned in the comments you can't do:

extension Array where Element == Optional<Equatable>

But you can create a generic function in the Array extension:

extension Array {
    func foo<T: Equatable>() where Element == Optional<T> {
        ...
    }
}


问:
Can't read Google Pay Pass event card through another phone's NFC reader
I need to make an app that is able to read the Google Pay Pass event ticket through NFC. But I can't find any way how to deal with it. I saw some top apps in Google Play, as PassWallet and Passes, which works with such event tickets.

But they all could add a new ticket through scanning barcode only, not through NFC touch. I tried to open a ticket in Google Pay app and read it through another phone's NFC reader but didn't receive any information about the ticket, I always receive my default credit card info even when I open needed card.

So my question is that is it possible to read Google Pay Pass event ticket through another phone's NFC, as in the picture below?

If yes, could you share with me some example codes on how to do it?

答:
Yes it is possible.

For a Google Pay issued pass the pass must be saved to google pay on the mobile device and that passes class must be set to enable smart tap and the pass itself must have the smartTapRedemptionValue field set as below:

```<code>{
 ...
 "smartTapRedemptionValue": "Value to Transmit",
 ...
}
</code>```

The device acting as the terminal (reads the pass) must implement the Smart Tap Protocol and present the collector id, and signed payload to the mobile device to authenticate the terminal and send passes that it can redeem.

The passes class also has the field redemptionIssuers can specify which terminal's collector id can redeem it.

In order to implement Smart Tap Protocol you can request access to the NDA protected docs via a form and that has the details on how to configure a device acting as a terminal to read passes.

There are also already certified supported terminal providers available.

Body:
Yes it is possible.

For a Google Pay issued pass the pass must be saved to google pay on the mobile device and that passes class must be set to enable smart tap and the pass itself must have the smartTapRedemptionValue field set as below:

{
 ...
 "smartTapRedemptionValue": "Value to Transmit",
 ...
}

The device acting as the terminal (reads the pass) must implement the Smart Tap Protocol and present the collector id, and signed payload to the mobile device to authenticate the terminal and send passes that it can redeem.

The passes class also has the field redemptionIssuers can specify which terminal's collector id can redeem it.

In order to implement Smart Tap Protocol you can request access to the NDA protected docs via a form and that has the details on how to configure a device acting as a terminal to read passes.

There are also already certified supported terminal providers available.


问:
Multiple dygraph legends
I would like to display a combination of the dygraph legend options "always" and "follow".  The drawback of using "follow" is that there is no legend if there is no mouse over the graph.  I want to display the default legend in a separate div if there is no mouse over, similar to legend "always" with a labelsDiv set.  This would allow a user to take a screenshot of the graph without worrying about placing the mouse on the graph to identify the series.

Dygraph.js appears to only allow one legend.

My approach is to create a static legend using the names of the series, but I'm missing the color for each series.  Is it possible to identify the color of each series of the dygraph?

EDIT: I've provided an example below, where "dygraphcolor1" would represent the color of each series.

```<code>//script
var serieslabels = [point1, point2, point3]

g = new Dygraph(document.getElementById(chart_title), data,
        {labels: serieslabels,
         legend: 'follow',
         labelsSeparateLines: true,
         labelsDiv: document.getElementById('chart_title_legend'), //remove since not allowed with legend = 'follow'

for (a=1; a < labels.length; a++){

//html via document.write
// this will make a list of each series label displayed in the same color as dygraph.
<p style ="color:dygraphcolor1"> serieslabels[a]</p>

}
</code>```

答:
Well it's more of a hack than I'd hoped, but the rough idea is to set legend: 'follow' on mouseenter and legend: 'always' on mouseleave. dygraphs doesn't expect you to change the legend display in this way, so you have to do a bit of cleanup afterwards:

div.addEventListener('mouseenter', () => {
  g.updateOptions({legend: 'follow'});
});

div.addEventListener('mouseleave', () => {
  g.updateOptions({legend: 'always'});
  // A "follow" legend gets hidden on mouseleave, so make it visible again:
  div.querySelector('.dygraph-legend').style.display='';
  // This repositions it to the top/right of the chart:
  g.plugins_[0].plugin.predraw({dygraph: g});
});
```

Here's a complete demo. For customizing the display of the legend, you may also be interested in the legendFormatter callback.

Title: Multiple dygraph legends

Body:
I would like to display a combination of the dygraph legend options "always" and "follow".  The drawback of using "follow" is that there is no legend if there is no mouse over the graph.  I want to display the default legend in a separate div if there is no mouse over, similar to legend "always" with a labelsDiv set.  This would allow a user to take a screenshot of the graph without worrying about placing the mouse on the graph to identify the series.

Dygraph.js appears to only allow one legend.

My approach is to create a static legend using the names of the series, but I'm missing the color for each series.  Is it possible to identify the color of each series of the dygraph?

EDIT: I've provided an example below, where "dygraphcolor1" would represent the color of each series.

//script
var serieslabels = [point1, point2, point3]

g = new Dygraph(document.getElementById(chart_title), data,
        {labels: serieslabels,
         legend: 'follow',
         labelsSeparateLines: true,
         labelsDiv: document.getElementById('chart_title_legend'), //remove since not allowed with legend = 'follow'

for (a=1; a < labels.length; a++){

//html via document.write
// this will make a list of each series label displayed in the same color as dygraph.

 serieslabels[a]

}

Body:
Well it's more of a hack than I'd hoped, but the rough idea is to set legend: 'follow' on mouseenter and legend: 'always' on mouseleave. dygraphs doesn't expect you to change the legend display in this way, so you have to do a bit of cleanup afterwards:

div.addEventListener('mouseenter', () => {
  g.updateOptions({legend: 'follow'});
});

div.addEventListener('mouseleave', () => {
  g.updateOptions({legend: 'always'});
  // A "follow" legend gets hidden on mouseleave, so make it visible again:
  div.querySelector('.dygraph-legend').style.display='';
  // This repositions it to the top/right of the chart:
  g.plugins_[0].plugin.predraw({dygraph: g});
});

Here's a complete demo. For customizing the display of the legend, you may also be interested in the legendFormatter callback.


问:
EXCEPTION_ACCESS_VIOLATION in Repast
I have installed Repast on my windows 10 computer, but if I try to run one of the demo codes I get an error.

Error loading EGL entry points.

A fatal error has been detected by the Java Runtime Environment:

EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x0000000000000000, pid=22096, tid=21896

JRE version: OpenJDK Runtime Environment (11.0.4+11) (build 11.0.4+11)
   Java VM: OpenJDK 64-Bit Server VM (11.0.4+11, mixed mode, tiered, compressed oops, g1 gc, windows-amd64)
   Problematic frame:
   C  0x0000000000000000

No core dump will be written. Minidumps are not enabled by default on client versions of Windows

An error report file with more information is saved as:
   C:\Surfdrive\Models_and_Scripts\Repast\Zombies_Demo\hs_err_pid22096.log

If you would like to submit a bug report, please visit:
     https://github.com/AdoptOpenJDK/openjdk-build/issues
   The crash happened outside the Java Virtual Machine in native code.
   See problematic frame for where to report the bug.

I have tried to run Repast as administrator and set javaw.exe in to run as adminstrator, but that does not solve the problem.

This is the THREAD in the error log file (complete file is too long):
    ---------------  T H R E A D  ---------------

```<code>Current thread (0x000001a735b13800):  JavaThread "AWT-EventQueue-0" [_thread_in_native, id=21896, stack(0x000000427a300000,0x000000427a400000)]

Stack: [0x000000427a300000,0x000000427a400000],  sp=0x000000427a3f7cd8,  free space=991k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)

Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
j  jogamp.opengl.egl.EGL.dispatch_eglGetProcAddress0(Ljava/lang/String;J)J+0
j  jogamp.opengl.egl.EGL.eglGetProcAddress(JLjava/lang/String;)J+18
j  jogamp.opengl.egl.EGLDynamicLibraryBundleInfo.toolGetProcAddress(JLjava/lang/String;)J+2
j  com.jogamp.common.os.DynamicLibraryBundle.toolDynamicLookupFunction(Ljava/lang/String;)J+18
j  com.jogamp.common.os.DynamicLibraryBundle.dynamicLookupFunction(Ljava/lang/String;)J+94
j  com.jogamp.gluegen.runtime.opengl.GLProcAddressResolver.resolve(Ljava/lang/String;Lcom/jogamp/common/os/DynamicLookupHelper;)J+35
j  com.jogamp.gluegen.runtime.ProcAddressTable.setEntry(Ljava/lang/reflect/Field;Ljava/lang/String;Lcom/jogamp/common/os/DynamicLookupHelper;)V+30
j  com.jogamp.gluegen.runtime.ProcAddressTable.reset(Lcom/jogamp/common/os/DynamicLookupHelper;)V+129
j  jogamp.opengl.egl.EGL.resetProcAddressTable(Lcom/jogamp/common/os/DynamicLookupHelper;)V+4
j  jogamp.opengl.egl.EGLDrawableFactory.<init>()V+294
v  ~StubRoutines::call_stub
J 2507  jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Ljava/lang/reflect/Constructor;[Ljava/lang/Object;)Ljava/lang/Object; java.base@11.0.4 (0 bytes) @ 0x000001a72565a326 [0x000001a72565a2c0+0x0000000000000066]
J 2506 c1 jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance([Ljava/lang/Object;)Ljava/lang/Object; java.base@11.0.4 (89 bytes) @ 0x000001a71e12d6bc [0x000001a71e12cb40+0x0000000000000b7c]
J 2453 c1 jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance([Ljava/lang/Object;)Ljava/lang/Object; java.base@11.0.4 (9 bytes) @ 0x000001a71e0d7edc [0x000001a71e0d7de0+0x00000000000000fc]
J 2452 c1 java.lang.reflect.Constructor.newInstance([Ljava/lang/Object;)Ljava/lang/Object; java.base@11.0.4 (76 bytes) @ 0x000001a71e0e1404 [0x000001a71e0e11a0+0x0000000000000264]
j  com.jogamp.common.util.ReflectionUtil.createInstance(Ljava/lang/reflect/Constructor;[Ljava/lang/Object;)Ljava/lang/Object;+2
j  com.jogamp.common.util.ReflectionUtil.createInstance(Ljava/lang/Class;[Ljava/lang/Class;[Ljava/lang/Object;)Ljava/lang/Object;+6
j  com.jogamp.common.util.ReflectionUtil.createInstance(Ljava/lang/String;[Ljava/lang/Class;[Ljava/lang/Object;Ljava/lang/ClassLoader;)Ljava/lang/Object;+8
j  com.jogamp.common.util.ReflectionUtil.createInstance(Ljava/lang/String;Ljava/lang/ClassLoader;)Ljava/lang/Object;+4
j  javax.media.opengl.GLDrawableFactory.initSingletonImpl()V+263
j  javax.media.opengl.GLDrawableFactory.initSingleton()V+21
j  javax.media.opengl.GLProfile.initProfilesForDefaultDevices()V+107
j  javax.media.opengl.GLProfile.access$000()V+0
j  javax.media.opengl.GLProfile$1.run()Ljava/lang/Object;+58
v  ~StubRoutines::call_stub
J 1304  java.security.AccessController.doPrivileged(Ljava/security/PrivilegedAction;)Ljava/lang/Object; java.base@11.0.4 (0 bytes) @ 0x000001a72568b392 [0x000001a72568b340+0x0000000000000052]
j  javax.media.opengl.GLProfile.initSingleton()V+75
j  javax.media.opengl.GLProfile.getProfileMap(Ljavax/media/nativewindow/AbstractGraphicsDevice;Z)Ljava/util/HashMap;+0
j  javax.media.opengl.GLProfile.get(Ljavax/media/nativewindow/AbstractGraphicsDevice;Ljava/lang/String;)Ljavax/media/opengl/GLProfile;+16
j  javax.media.opengl.GLProfile.get(Ljava/lang/String;)Ljavax/media/opengl/GLProfile;+4
j  saf.v3d.Canvas2D.<init>()V+69
j  repast.simphony.visualizationOGL2D.DisplayOGL2D.<init>(Lrepast/simphony/visualization/DisplayData;Lrepast/simphony/visualization/Layout;)V+106
j  repast.simphony.visualization.engine.DisplayCreatorOGL2D.createDisplay()Lrepast/simphony/visualization/IDisplay;+65
j  repast.simphony.visualization.engine.DisplayProducer.createDisplay()Lrepast/simphony/visualization/IDisplay;+35
j  repast.simphony.visualization.engine.DisplayComponentControllerAction.runInitialize(Lrepast/simphony/engine/environment/RunState;Ljava/lang/Object;Lrepast/simphony/parameter/Parameters;)V+304
j  repast.simphony.engine.controller.DefaultController$3.visit(Lrepast/simphony/engine/environment/ControllerAction;)V+18
j  repast.simphony.engine.controller.DefaultController$3.visit(Ljava/lang/Object;)V+5
j  repast.simphony.util.collections.NaryTree.preOrderTraverals(Lrepast/simphony/util/collections/NaryTree$Node;Lrepast/simphony/util/collections/TreeVisitor;)V+5
j  repast.simphony.util.collections.NaryTree.preOrderTraverals(Lrepast/simphony/util/collections/NaryTree$Node;Lrepast/simphony/util/collections/TreeVisitor;)V+45
j  repast.simphony.util.collections.NaryTree.preOrderTraverals(Lrepast/simphony/util/collections/NaryTree$Node;Lrepast/simphony/util/collections/TreeVisitor;)V+45
j  repast.simphony.util.collections.NaryTree.preOrderTraversal(Lrepast/simphony/util/collections/TreeVisitor;)V+6
j  repast.simphony.engine.controller.DefaultController.runInitialize(Lrepast/simphony/engine/environment/RunState;Lrepast/simphony/context/Context;Lrepast/simphony/parameter/Parameters;)V+101
j  repast.simphony.engine.controller.DefaultController.runInitialize(Lrepast/simphony/parameter/Parameters;)Lrepast/simphony/engine/environment/RunState;+111
j  repast.simphony.ui.RSApplication.initSim()V+44
j  repast.simphony.ui.action.InitRun.actionPerformed(Ljava/awt/event/ActionEvent;)V+10
j  javax.swing.AbstractButton.fireActionPerformed(Ljava/awt/event/ActionEvent;)V+83 java.desktop@11.0.4
j  javax.swing.AbstractButton$Handler.actionPerformed(Ljava/awt/event/ActionEvent;)V+5 java.desktop@11.0.4
j  javax.swing.DefaultButtonModel.fireActionPerformed(Ljava/awt/event/ActionEvent;)V+34 java.desktop@11.0.4
j  javax.swing.DefaultButtonModel.setPressed(Z)V+117 java.desktop@11.0.4
j  javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Ljava/awt/event/MouseEvent;)V+35 java.desktop@11.0.4
j  java.awt.AWTEventMulticaster.mouseReleased(Ljava/awt/event/MouseEvent;)V+8 java.desktop@11.0.4
j  java.awt.Component.processMouseEvent(Ljava/awt/event/MouseEvent;)V+64 java.desktop@11.0.4
j  javax.swing.JComponent.processMouseEvent(Ljava/awt/event/MouseEvent;)V+23 java.desktop@11.0.4
j  java.awt.Component.processEvent(Ljava/awt/AWTEvent;)V+81 java.desktop@11.0.4
J 4777 c1 java.awt.Container.processEvent(Ljava/awt/AWTEvent;)V java.desktop@11.0.4 (22 bytes) @ 0x000001a71ea43a24 [0x000001a71ea43700+0x0000000000000324]
J 4654 c1 java.awt.Component.dispatchEventImpl(Ljava/awt/AWTEvent;)V java.desktop@11.0.4 (777 bytes) @ 0x000001a71e9fd454 [0x000001a71e9f9840+0x0000000000003c14]
J 4653 c1 java.awt.Container.dispatchEventImpl(Ljava/awt/AWTEvent;)V java.desktop@11.0.4 (129 bytes) @ 0x000001a71e9f839c [0x000001a71e9f8260+0x000000000000013c]
J 4631 c1 java.awt.Component.dispatchEvent(Ljava/awt/AWTEvent;)V java.desktop@11.0.4 (6 bytes) @ 0x000001a71e9e5f34 [0x000001a71e9e5e40+0x00000000000000f4]
j  java.awt.LightweightDispatcher.retargetMouseEvent(Ljava/awt/Component;ILjava/awt/event/MouseEvent;)V+349 java.desktop@11.0.4
j  java.awt.LightweightDispatcher.processMouseEvent(Ljava/awt/event/MouseEvent;)Z+155 java.desktop@11.0.4
j  java.awt.LightweightDispatcher.dispatchEvent(Ljava/awt/AWTEvent;)Z+50 java.desktop@11.0.4
J 4653 c1 java.awt.Container.dispatchEventImpl(Ljava/awt/AWTEvent;)V java.desktop@11.0.4 (129 bytes) @ 0x000001a71e9f833c [0x000001a71e9f8260+0x00000000000000dc]
j  java.awt.Window.dispatchEventImpl(Ljava/awt/AWTEvent;)V+19 java.desktop@11.0.4
J 4741 c1 java.awt.EventQueue.dispatchEventImpl(Ljava/awt/AWTEvent;Ljava/lang/Object;)V java.desktop@11.0.4 (136 bytes) @ 0x000001a71ea2c454 [0x000001a71ea2bfc0+0x0000000000000494]
J 4740 c1 java.awt.EventQueue$4.run()Ljava/lang/Void; java.desktop@11.0.4 (60 bytes) @ 0x000001a71ea2b82c [0x000001a71ea2b700+0x000000000000012c]
J 4739 c1 java.awt.EventQueue$4.run()Ljava/lang/Object; java.desktop@11.0.4 (5 bytes) @ 0x000001a71ea2b344 [0x000001a71ea2b2c0+0x0000000000000084]
v  ~StubRoutines::call_stub
J 2083  java.security.AccessController.doPrivileged(Ljava/security/PrivilegedAction;Ljava/security/AccessControlContext;)Ljava/lang/Object; java.base@11.0.4 (0 bytes) @ 0x000001a7256ff326 [0x000001a7256ff2c0+0x0000000000000066]
J 4651 c1 java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Ljava/security/PrivilegedAction;Ljava/security/AccessControlContext;Ljava/security/AccessControlContext;)Ljava/lang/Object; java.base@11.0.4 (22 bytes) @ 0x000001a71e9f54ac [0x000001a71e9f51a0+0x000000000000030c]
j  java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Ljava/security/PrivilegedAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;+6 java.base@11.0.4
j  java.awt.EventQueue$5.run()Ljava/lang/Void;+11 java.desktop@11.0.4
j  java.awt.EventQueue$5.run()Ljava/lang/Object;+1 java.desktop@11.0.4
v  ~StubRoutines::call_stub
J 2083  java.security.AccessController.doPrivileged(Ljava/security/PrivilegedAction;Ljava/security/AccessControlContext;)Ljava/lang/Object; java.base@11.0.4 (0 bytes) @ 0x000001a7256ff326 [0x000001a7256ff2c0+0x0000000000000066]
J 4672 c1 java.awt.EventQueue.dispatchEvent(Ljava/awt/AWTEvent;)V java.desktop@11.0.4 (80 bytes) @ 0x000001a71ea0c16c [0x000001a71ea0b6a0+0x0000000000000acc]
J 4746 c1 java.awt.EventDispatchThread.pumpOneEventForFilters(I)V java.desktop@11.0.4 (113 bytes) @ 0x000001a71ea323ac [0x000001a71ea31ca0+0x000000000000070c]
j  java.awt.EventDispatchThread.pumpEventsForFilter(ILjava/awt/Conditional;Ljava/awt/EventFilter;)V+35 java.desktop@11.0.4
j  java.awt.EventDispatchThread.pumpEventsForHierarchy(ILjava/awt/Conditional;Ljava/awt/Component;)V+11 java.desktop@11.0.4
j  java.awt.EventDispatchThread.pumpEvents(ILjava/awt/Conditional;)V+4 java.desktop@11.0.4
j  java.awt.EventDispatchThread.pumpEvents(Ljava/awt/Conditional;)V+3 java.desktop@11.0.4
j  java.awt.EventDispatchThread.run()V+9 java.desktop@11.0.4
v  ~StubRoutines::call_stub

siginfo: EXCEPTION_ACCESS_VIOLATION (0xc0000005), data execution prevention violation at address 0x0000000000000000

Register to memory mapping:

RIP=0x0 is NULL
RAX=0x0000000000000001 is an unknown value
RBX=0x000001a735b13b40 points into unknown readable memory: 40 6c 21 0c fe 7f 00 00
RCX=0x000001a737c29430 points into unknown readable memory: 65 67 6c 42 69 6e 64 41
RDX=0x00007ffe4be9e0e0 libEGL.dll
RSP=0x000000427a3f7cd8 is pointing into the stack for thread: 0x000001a735b13800
RBP=0x00007ffe4be819f6 libEGL.dll
RSI=0x000000427a3f7de8 is pointing into the stack for thread: 0x000001a735b13800
RDI=0x000001a737c29430 points into unknown readable memory: 65 67 6c 42 69 6e 64 41
R8 =0x00007ffe4be9faa0 libEGL.dll
R9 =0x00007ffe4be9302a libEGL.dll
R10=0x0 is NULL
R11=0x000000427a3f7a80 is pointing into the stack for thread: 0x000001a735b13800
R12=0x0 is NULL
R13={method} {0x000001a7406c1478} 'dispatch_eglGetProcAddress0' '(Ljava/lang/String;J)J' in 'jogamp/opengl/egl/EGL'
R14=0x000000427a3f7de8 is pointing into the stack for thread: 0x000001a735b13800
R15=0x000001a735b13800 is a thread

Registers:
RAX=0x0000000000000001, RBX=0x000001a735b13b40, RCX=0x000001a737c29430, RDX=0x00007ffe4be9e0e0
RSP=0x000000427a3f7cd8, RBP=0x00007ffe4be819f6, RSI=0x000000427a3f7de8, RDI=0x000001a737c29430
R8 =0x00007ffe4be9faa0, R9 =0x00007ffe4be9302a, R10=0x0000000000000000, R11=0x000000427a3f7a80
R12=0x0000000000000000, R13=0x000001a7406c1470, R14=0x000000427a3f7de8, R15=0x000001a735b13800
RIP=0x0000000000000000, EFLAGS=0x0000000000010202

Top of Stack: (sp=0x000000427a3f7cd8)
0x000000427a3f7cd8:   0000000064361292 000001a735b13b40
0x000000427a3f7ce8:   00007ffe4be819f6 000000427a3f7de8
0x000000427a3f7cf8:   000001a71db2ee80 000000427a3f8500
0x000000427a3f7d08:   000001a7406c1470 000000003845e4ea
0x000000427a3f7d18:   0000000000001f40 000000427a3f7db8
0x000000427a3f7d28:   000001a71db2f037 0000000000001f40
0x000000427a3f7d38:   000001a71db2ed1c 000001a735b13800
0x000000427a3f7d48:   000001a7406c1470 000000427a3f7db8
0x000000427a3f7d58:   000000003845e4ea 000000003845e4ea
0x000000427a3f7d68:   000001a71db2ecd6 000000427a3f7d70
0x000000427a3f7d78:   000001a7406c1470 000000427a3f7de8
0x000000427a3f7d88:   000001a7406c2fa8 0000000000000000
0x000000427a3f7d98:   0000000087bf8b68 000001a7406c1470
0x000000427a3f7da8:   0000000000000000 000000427a3f7dd8
0x000000427a3f7db8:   000000427a3f7e38 000001a71db29910
0x000000427a3f7dc8:   0000000087bf8b68 000001a71db2bf97

Instructions: (pc=0x0000000000000000)
0xffffffffffffff00:

Stack slot to memory mapping:
stack at sp + 0 slots: 0x0000000064361292 jogl_mobile.dll
stack at sp + 1 slots: 0x000001a735b13b40 points into unknown readable memory: 40 6c 21 0c fe 7f 00 00
stack at sp + 2 slots: 0x00007ffe4be819f6 libEGL.dll
stack at sp + 3 slots: 0x000000427a3f7de8 is pointing into the stack for thread: 0x000001a735b13800
stack at sp + 4 slots: 0x000001a71db2ee80 is at code_begin+608 in an Interpreter codelet
method entry point (kind = native)  [0x000001a71db2ec20, 0x000001a71db2f780]  2912 bytes
stack at sp + 5 slots: 0x000000427a3f8500 is pointing into the stack for thread: 0x000001a735b13800
stack at sp + 6 slots: {method} {0x000001a7406c1478} 'dispatch_eglGetProcAddress0' '(Ljava/lang/String;J)J' in 'jogamp/opengl/egl/EGL'
stack at sp + 7 slots: 0x000000003845e4ea is an unknown value
</code>```

Thanks a lot in advance for answering.
Egil

答:
Based on the error log, it appears to be an issue with the graphics driver on your PC.  Are you using a standard Windows PC or laptop, or something like a mobile tablet or chromebook?  The error suggests an issue trying to load a mobile graphics driver and this would not occur if used on a PC.  Which demo in particular causes this error?  Is it a standard demo, or a "Server" demo launch?

One suggestd approach that solves graphics problems with Repast displays is to update the graphics driver on your PC.  If you have and NVidia or AMD GPU you can download a driver update utility from their websites.

Title: EXCEPTION_ACCESS_VIOLATION in Repast

Body:
I have installed Repast on my windows 10 computer, but if I try to run one of the demo codes I get an error.

Error loading EGL entry points.

A fatal error has been detected by the Java Runtime Environment:

EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x0000000000000000, pid=22096, tid=21896

JRE version: OpenJDK Runtime Environment (11.0.4+11) (build 11.0.4+11)
   Java VM: OpenJDK 64-Bit Server VM (11.0.4+11, mixed mode, tiered, compressed oops, g1 gc, windows-amd64)
   Problematic frame:
   C  0x0000000000000000

No core dump will be written. Minidumps are not enabled by default on client versions of Windows

An error report file with more information is saved as:
   C:\Surfdrive\Models_and_Scripts\Repast\Zombies_Demo\hs_err_pid22096.log

If you would like to submit a bug report, please visit:
     https://github.com/AdoptOpenJDK/openjdk-build/issues
   The crash happened outside the Java Virtual Machine in native code.
   See problematic frame for where to report the bug.

I have tried to run Repast as administrator and set javaw.exe in to run as adminstrator, but that does not solve the problem.

This is the THREAD in the error log file (complete file is too long):
    ---------------  T H R E A D  ---------------

Current thread (0x000001a735b13800):  JavaThread "AWT-EventQueue-0" [_thread_in_native, id=21896, stack(0x000000427a300000,0x000000427a400000)]

Stack: [0x000000427a300000,0x000000427a400000],  sp=0x000000427a3f7cd8,  free space=991k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)

Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
j  jogamp.opengl.egl.EGL.dispatch_eglGetProcAddress0(Ljava/lang/String;J)J+0
j  jogamp.opengl.egl.EGL.eglGetProcAddress(JLjava/lang/String;)J+18
j  jogamp.opengl.egl.EGLDynamicLibraryBundleInfo.toolGetProcAddress(JLjava/lang/String;)J+2
j  com.jogamp.common.os.DynamicLibraryBundle.toolDynamicLookupFunction(Ljava/lang/String;)J+18
j  com.jogamp.common.os.DynamicLibraryBundle.dynamicLookupFunction(Ljava/lang/String;)J+94
j  com.jogamp.gluegen.runtime.opengl.GLProcAddressResolver.resolve(Ljava/lang/String;Lcom/jogamp/common/os/DynamicLookupHelper;)J+35
j  com.jogamp.gluegen.runtime.ProcAddressTable.setEntry(Ljava/lang/reflect/Field;Ljava/lang/String;Lcom/jogamp/common/os/DynamicLookupHelper;)V+30
j  com.jogamp.gluegen.runtime.ProcAddressTable.reset(Lcom/jogamp/common/os/DynamicLookupHelper;)V+129
j  jogamp.opengl.egl.EGL.resetProcAddressTable(Lcom/jogamp/common/os/DynamicLookupHelper;)V+4
j  jogamp.opengl.egl.EGLDrawableFactory.<init>()V+294
v  ~StubRoutines::call_stub
J 2507  jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Ljava/lang/reflect/Constructor;[Ljava/lang/Object;)Ljava/lang/Object; java.base@11.0.4 (0 bytes) @ 0x000001a72565a326 [0x000001a72565a2c0+0x0000000000000066]
J 2506 c1 jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance([Ljava/lang/Object;)Ljava/lang/Object; java.base@11.0.4 (89 bytes) @ 0x000001a71e12d6bc [0x000001a71e12cb40+0x0000000000000b7c]
J 2453 c1 jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance([Ljava/lang/Object;)Ljava/lang/Object; java.base@11.0.4 (9 bytes) @ 0x000001a71e0d7edc [0x000001a71e0d7de0+0x00000000000000fc]
J 2452 c1 java.lang.reflect.Constructor.newInstance([Ljava/lang/Object;)Ljava/lang/Object; java.base@11.0.4 (76 bytes) @ 0x000001a71e0e1404 [0x000001a71e0e11a0+0x0000000000000264]
j  com.jogamp.common.util.ReflectionUtil.createInstance(Ljava/lang/reflect/Constructor;[Ljava/lang/Object;)Ljava/lang/Object;+2
j  com.jogamp.common.util.ReflectionUtil.createInstance(Ljava/lang/Class;[Ljava/lang/Class;[Ljava/lang/Object;)Ljava/lang/Object;+6
j  com.jogamp.common.util.ReflectionUtil.createInstance(Ljava/lang/String;[Ljava/lang/Class;[Ljava/lang/Object;Ljava/lang/ClassLoader;)Ljava/lang/Object;+8
j  com.jogamp.common.util.ReflectionUtil.createInstance(Ljava/lang/String;Ljava/lang/ClassLoader;)Ljava/lang/Object;+4
j  javax.media.opengl.GLDrawableFactory.initSingletonImpl()V+263
j  javax.media.opengl.GLDrawableFactory.initSingleton()V+21
j  javax.media.opengl.GLProfile.initProfilesForDefaultDevices()V+107
j  javax.media.opengl.GLProfile.access$000()V+0
j  javax.media.opengl.GLProfile$1.run()Ljava/lang/Object;+58
v  ~StubRoutines::call_stub
J 1304  java.security.AccessController.doPrivileged(Ljava/security/PrivilegedAction;)Ljava/lang/Object; java.base@11.0.4 (0 bytes) @ 0x000001a72568b392 [0x000001a72568b340+0x0000000000000052]
j  javax.media.opengl.GLProfile.initSingleton()V+75
j  javax.media.opengl.GLProfile.getProfileMap(Ljavax/media/nativewindow/AbstractGraphicsDevice;Z)Ljava/util/HashMap;+0
j  javax.media.opengl.GLProfile.get(Ljavax/media/nativewindow/AbstractGraphicsDevice;Ljava/lang/String;)Ljavax/media/opengl/GLProfile;+16
j  javax.media.opengl.GLProfile.get(Ljava/lang/String;)Ljavax/media/opengl/GLProfile;+4
j  saf.v3d.Canvas2D.<init>()V+69
j  repast.simphony.visualizationOGL2D.DisplayOGL2D.<init>(Lrepast/simphony/visualization/DisplayData;Lrepast/simphony/visualization/Layout;)V+106
j  repast.simphony.visualization.engine.DisplayCreatorOGL2D.createDisplay()Lrepast/simphony/visualization/IDisplay;+65
j  repast.simphony.visualization.engine.DisplayProducer.createDisplay()Lrepast/simphony/visualization/IDisplay;+35
j  repast.simphony.visualization.engine.DisplayComponentControllerAction.runInitialize(Lrepast/simphony/engine/environment/RunState;Ljava/lang/Object;Lrepast/simphony/parameter/Parameters;)V+304
j  repast.simphony.engine.controller.DefaultController$3.visit(Lrepast/simphony/engine/environment/ControllerAction;)V+18
j  repast.simphony.engine.controller.DefaultController$3.visit(Ljava/lang/Object;)V+5
j  repast.simphony.util.collections.NaryTree.preOrderTraverals(Lrepast/simphony/util/collections/NaryTree$Node;Lrepast/simphony/util/collections/TreeVisitor;)V+5
j  repast.simphony.util.collections.NaryTree.preOrderTraverals(Lrepast/simphony/util/collections/NaryTree$Node;Lrepast/simphony/util/collections/TreeVisitor;)V+45
j  repast.simphony.util.collections.NaryTree.preOrderTraverals(Lrepast/simphony/util/collections/NaryTree$Node;Lrepast/simphony/util/collections/TreeVisitor;)V+45
j  repast.simphony.util.collections.NaryTree.preOrderTraversal(Lrepast/simphony/util/collections/TreeVisitor;)V+6
j  repast.simphony.engine.controller.DefaultController.runInitialize(Lrepast/simphony/engine/environment/RunState;Lrepast/simphony/context/Context;Lrepast/simphony/parameter/Parameters;)V+101
j  repast.simphony.engine.controller.DefaultController.runInitialize(Lrepast/simphony/parameter/Parameters;)Lrepast/simphony/engine/environment/RunState;+111
j  repast.simphony.ui.RSApplication.initSim()V+44
j  repast.simphony.ui.action.InitRun.actionPerformed(Ljava/awt/event/ActionEvent;)V+10
j  javax.swing.AbstractButton.fireActionPerformed(Ljava/awt/event/ActionEvent;)V+83 java.desktop@11.0.4
j  javax.swing.AbstractButton$Handler.actionPerformed(Ljava/awt/event/ActionEvent;)V+5 java.desktop@11.0.4
j  javax.swing.DefaultButtonModel.fireActionPerformed(Ljava/awt/event/ActionEvent;)V+34 java.desktop@11.0.4
j  javax.swing.DefaultButtonModel.setPressed(Z)V+117 java.desktop@11.0.4
j  javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Ljava/awt/event/MouseEvent;)V+35 java.desktop@11.0.4
j  java.awt.AWTEventMulticaster.mouseReleased(Ljava/awt/event/MouseEvent;)V+8 java.desktop@11.0.4
j  java.awt.Component.processMouseEvent(Ljava/awt/event/MouseEvent;)V+64 java.desktop@11.0.4
j  javax.swing.JComponent.processMouseEvent(Ljava/awt/event/MouseEvent;)V+23 java.desktop@11.0.4
j  java.awt.Component.processEvent(Ljava/awt/AWTEvent;)V+81 java.desktop@11.0.4
J 4777 c1 java.awt.Container.processEvent(Ljava/awt/AWTEvent;)V java.desktop@11.0.4 (22 bytes) @ 0x000001a71ea43a24 [0x000001a71ea43700+0x0000000000000324]
J 4654 c1 java.awt.Component.dispatchEventImpl(Ljava/awt/AWTEvent;)V java.desktop@11.0.4 (777 bytes) @ 0x000001a71e9fd454 [0x000001a71e9f9840+0x0000000000003c14]
J 4653 c1 java.awt.Container.dispatchEventImpl(Ljava/awt/AWTEvent;)V java.desktop@11.0.4 (129 bytes) @ 0x000001a71e9f839c [0x000001a71e9f8260+0x000000000000013c]
J 4631 c1 java.awt.Component.dispatchEvent(Ljava/awt/AWTEvent;)V java.desktop@11.0.4 (6 bytes) @ 0x000001a71e9e5f34 [0x000001a71e9e5e40+0x00000000000000f4]
j  java.awt.LightweightDispatcher.retargetMouseEvent(Ljava/awt/Component;ILjava/awt/event/MouseEvent;)V+349 java.desktop@11.0.4
j  java.awt.LightweightDispatcher.processMouseEvent(Ljava/awt/event/MouseEvent;)Z+155 java.desktop@11.0.4
j  java.awt.LightweightDispatcher.dispatchEvent(Ljava/awt/AWTEvent;)Z+50 java.desktop@11.0.4
J 4653 c1 java.awt.Container.dispatchEventImpl(Ljava/awt/AWTEvent;)V java.desktop@11.0.4 (129 bytes) @ 0x000001a71e9f833c [0x000001a71e9f8260+0x00000000000000dc]
j  java.awt.Window.dispatchEventImpl(Ljava/awt/AWTEvent;)V+19 java.desktop@11.0.4
J 4741 c1 java.awt.EventQueue.dispatchEventImpl(Ljava/awt/AWTEvent;Ljava/lang/Object;)V java.desktop@11.0.4 (136 bytes) @ 0x000001a71ea2c454 [0x000001a71ea2bfc0+0x0000000000000494]
J 4740 c1 java.awt.EventQueue$4.run()Ljava/lang/Void; java.desktop@11.0.4 (60 bytes) @ 0x000001a71ea2b82c [0x000001a71ea2b700+0x000000000000012c]
J 4739 c1 java.awt.EventQueue$4.run()Ljava/lang/Object; java.desktop@11.0.4 (5 bytes) @ 0x000001a71ea2b344 [0x000001a71ea2b2c0+0x0000000000000084]
v  ~StubRoutines::call_stub
J 2083  java.security.AccessController.doPrivileged(Ljava/security/PrivilegedAction;Ljava/security/AccessControlContext;)Ljava/lang/Object; java.base@11.0.4 (0 bytes) @ 0x000001a7256ff326 [0x000001a7256ff2c0+0x0000000000000066]
J 4651 c1 java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Ljava/security/PrivilegedAction;Ljava/security/AccessControlContext;Ljava/security/AccessControlContext;)Ljava/lang/Object; java.base@11.0.4 (22 bytes) @ 0x000001a71e9f54ac [0x000001a71e9f51a0+0x000000000000030c]
j  java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Ljava/security/PrivilegedAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;+6 java.base@11.0.4
j  java.awt.EventQueue$5.run()Ljava/lang/Void;+11 java.desktop@11.0.4
j  java.awt.EventQueue$5.run()Ljava/lang/Object;+1 java.desktop@11.0.4
v  ~StubRoutines::call_stub
J 2083  java.security.AccessController.doPrivileged(Ljava/security/PrivilegedAction;Ljava/security/AccessControlContext;)Ljava/lang/Object; java.base@11.0.4 (0 bytes) @ 0x000001a7256ff326 [0x000001a7256ff2c0+0x0000000000000066]
J 4672 c1 java.awt.EventQueue.dispatchEvent(Ljava/awt/AWTEvent;)V java.desktop@11.0.4 (80 bytes) @ 0x000001a71ea0c16c [0x000001a71ea0b6a0+0x0000000000000acc]
J 4746 c1 java.awt.EventDispatchThread.pumpOneEventForFilters(I)V java.desktop@11.0.4 (113 bytes) @ 0x000001a71ea323ac [0x000001a71ea31ca0+0x000000000000070c]
j  java.awt.EventDispatchThread.pumpEventsForFilter(ILjava/awt/Conditional;Ljava/awt/EventFilter;)V+35 java.desktop@11.0.4
j  java.awt.EventDispatchThread.pumpEventsForHierarchy(ILjava/awt/Conditional;Ljava/awt/Component;)V+11 java.desktop@11.0.4
j  java.awt.EventDispatchThread.pumpEvents(ILjava/awt/Conditional;)V+4 java.desktop@11.0.4
j  java.awt.EventDispatchThread.pumpEvents(Ljava/awt/Conditional;)V+3 java.desktop@11.0.4
j  java.awt.EventDispatchThread.run()V+9 java.desktop@11.0.4
v  ~StubRoutines::call_stub

siginfo: EXCEPTION_ACCESS_VIOLATION (0xc0000005), data execution prevention violation at address 0x0000000000000000

Register to memory mapping:

RIP=0x0 is NULL
RAX=0x0000000000000001 is an unknown value
RBX=0x000001a735b13b40 points into unknown readable memory: 40 6c 21 0c fe 7f 00 00
RCX=0x000001a737c29430 points into unknown readable memory: 65 67 6c 42 69 6e 64 41
RDX=0x00007ffe4be9e0e0 libEGL.dll
RSP=0x000000427a3f7cd8 is pointing into the stack for thread: 0x000001a735b13800
RBP=0x00007ffe4be819f6 libEGL.dll
RSI=0x000000427a3f7de8 is pointing into the stack for thread: 0x000001a735b13800
RDI=0x000001a737c29430 points into unknown readable memory: 65 67 6c 42 69 6e 64 41
R8 =0x00007ffe4be9faa0 libEGL.dll
R9 =0x00007ffe4be9302a libEGL.dll
R10=0x0 is NULL
R11=0x000000427a3f7a80 is pointing into the stack for thread: 0x000001a735b13800
R12=0x0 is NULL
R13={method} {0x000001a7406c1478} 'dispatch_eglGetProcAddress0' '(Ljava/lang/String;J)J' in 'jogamp/opengl/egl/EGL'
R14=0x000000427a3f7de8 is pointing into the stack for thread: 0x000001a735b13800
R15=0x000001a735b13800 is a thread

Registers:
RAX=0x0000000000000001, RBX=0x000001a735b13b40, RCX=0x000001a737c29430, RDX=0x00007ffe4be9e0e0
RSP=0x000000427a3f7cd8, RBP=0x00007ffe4be819f6, RSI=0x000000427a3f7de8, RDI=0x000001a737c29430
R8 =0x00007ffe4be9faa0, R9 =0x00007ffe4be9302a, R10=0x0000000000000000, R11=0x000000427a3f7a80
R12=0x0000000000000000, R13=0x000001a7406c1470, R14=0x000000427a3f7de8, R15=0x000001a735b13800
RIP=0x0000000000000000, EFLAGS=0x0000000000010202

Top of Stack: (sp=0x000000427a3f7cd8)
0x000000427a3f7cd8:   0000000064361292 000001a735b13b40
0x000000427a3f7ce8:   00007ffe4be819f6 000000427a3f7de8
0x000000427a3f7cf8:   000001a71db2ee80 000000427a3f8500
0x000000427a3f7d08:   000001a7406c1470 000000003845e4ea
0x000000427a3f7d18:   0000000000001f40 000000427a3f7db8
0x000000427a3f7d28:   000001a71db2f037 0000000000001f40
0x000000427a3f7d38:   000001a71db2ed1c 000001a735b13800
0x000000427a3f7d48:   000001a7406c1470 000000427a3f7db8
0x000000427a3f7d58:   000000003845e4ea 000000003845e4ea
0x000000427a3f7d68:   000001a71db2ecd6 000000427a3f7d70
0x000000427a3f7d78:   000001a7406c1470 000000427a3f7de8
0x000000427a3f7d88:   000001a7406c2fa8 0000000000000000
0x000000427a3f7d98:   0000000087bf8b68 000001a7406c1470
0x000000427a3f7da8:   0000000000000000 000000427a3f7dd8
0x000000427a3f7db8:   000000427a3f7e38 000001a71db29910
0x000000427a3f7dc8:   0000000087bf8b68 000001a71db2bf97

Instructions: (pc=0x0000000000000000)
0xffffffffffffff00:

Stack slot to memory mapping:
stack at sp + 0 slots: 0x0000000064361292 jogl_mobile.dll
stack at sp + 1 slots: 0x000001a735b13b40 points into unknown readable memory: 40 6c 21 0c fe 7f 00 00
stack at sp + 2 slots: 0x00007ffe4be819f6 libEGL.dll
stack at sp + 3 slots: 0x000000427a3f7de8 is pointing into the stack for thread: 0x000001a735b13800
stack at sp + 4 slots: 0x000001a71db2ee80 is at code_begin+608 in an Interpreter codelet
method entry point (kind = native)  [0x000001a71db2ec20, 0x000001a71db2f780]  2912 bytes
stack at sp + 5 slots: 0x000000427a3f8500 is pointing into the stack for thread: 0x000001a735b13800
stack at sp + 6 slots: {method} {0x000001a7406c1478} 'dispatch_eglGetProcAddress0' '(Ljava/lang/String;J)J' in 'jogamp/opengl/egl/EGL'
stack at sp + 7 slots: 0x000000003845e4ea is an unknown value

Thanks a lot in advance for answering.
Egil


问:
params[] element not passed into new object in create action
I have a very simple form, with the scaffold controller action. the DB schema for the relevant is as follows:

```<code>  create_table "uploads", :force => true do |t|
    t.string   "name"
    t.string   "location"
    t.string   "type"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "filename"
  end
</code>```

When the form is submitted, the params contains the following (look at the specific type parameter):

```<code>{"utf8"=>"âœ“",
 "authenticity_token"=>"NGV4rS/tZDWg2ZdMLpiSbTJQBDmMyjfYyZqZ6GX/7Kc=",
 "upload"=>{"name"=>"AEGFAEF",
 "type"=>"Sales",
 "file"=>#<ActionDispatch::Http::UploadedFile:0x4dff958 @original_filename="Google.pdf",
 @content_type="application/pdf",
 @headers="Content-Disposition: form-data; name=\"upload[file]\"; filename=\"Google.pdf\"\r\nContent-Type: application/pdf\r\n",
 @tempfile=#<File:C:/Users/kaya/AppData/Local/Temp/RackMultipart20110602-2876-1wyskk3>>},
 "commit"=>"Create Upload"}
</code>```

the first command in the create action of UploadsController is

```<code>@upload = Upload.new(params[:upload])
</code>```

and right after this line I have

```<code>@upload.type = nil
</code>```

I really don't get how such a basic thing is failing. can someone please give a hand?

thanks a bunch in advance.

答:
In rails type is a MagicFieldName and it is reserved for table inheritance. Since in your case Upload doesn't inherit from anything, querying type on an object will return nil.

It is known that using MagicFieldNames as columns names causes lots of troubles. You can check
http://oldwiki.rubyonrails.org/rails/pages/MagicFieldNames for a full list.

"Rails values convention over configuration. This is also true in the realm of table design where fields given particular names automatically gain certain behaviours.

Active Record allows inheritance by storing the name of the class in a column that by default is called “type” (can be changed by overwriting Base.inheritance_column)."

Body:
I have a very simple form, with the scaffold controller action. the DB schema for the relevant is as follows:

  create_table "uploads", :force => true do |t|
    t.string   "name"
    t.string   "location"
    t.string   "type"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "filename"
  end

When the form is submitted, the params contains the following (look at the specific type parameter):

{"utf8"=>"âœ“",
 "authenticity_token"=>"NGV4rS/tZDWg2ZdMLpiSbTJQBDmMyjfYyZqZ6GX/7Kc=",
 "upload"=>{"name"=>"AEGFAEF",
 "type"=>"Sales",
 "file"=>#<ActionDispatch::Http::UploadedFile:0x4dff958 @original_filename="Google.pdf",
 @content_type="application/pdf",
 @headers="Content-Disposition: form-data; name=\"upload[file]\"; filename=\"Google.pdf\"\r\nContent-Type: application/pdf\r\n",
 @tempfile=#<File:C:/Users/kaya/AppData/Local/Temp/RackMultipart20110602-2876-1wyskk3>>},
 "commit"=>"Create Upload"}

the first command in the create action of UploadsController is

@upload = Upload.new(params[:upload])

and right after this line I have

@upload.type = nil

I really don't get how such a basic thing is failing. can someone please give a hand?

thanks a bunch in advance.


问:
How to make a datetime object aware (not naive)
What I need to do

I have a timezone-unaware datetime object, to which I need to add a time zone in order to be able to compare it with other timezone-aware datetime objects. I do not want to convert my entire application to timezone unaware for this one legacy case.

What I've Tried

First, to demonstrate the problem:

```<code>Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> import pytz
>>> unaware = datetime.datetime(2011,8,15,8,15,12,0)
>>> unaware
datetime.datetime(2011, 8, 15, 8, 15, 12)
>>> aware = datetime.datetime(2011,8,15,8,15,12,0,pytz.UTC)
>>> aware
datetime.datetime(2011, 8, 15, 8, 15, 12, tzinfo=<UTC>)
>>> aware == unaware
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware datetimes
</code>```

First, I tried astimezone:

```<code>>>> unaware.astimezone(pytz.UTC)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: astimezone() cannot be applied to a naive datetime
>>>
</code>```

It's not terribly surprising this failed, since it's actually trying to do a conversion.  Replace seemed like a better choice (as per How do I get a value of datetime.today() in Python that is "timezone aware"?):

```<code>>>> unaware.replace(tzinfo=pytz.UTC)
datetime.datetime(2011, 8, 15, 8, 15, 12, tzinfo=<UTC>)
>>> unaware == aware
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware datetimes
>>>
</code>```

But as you can see, replace seems to set the tzinfo, but not make the object aware.  I'm getting ready to fall back to doctoring the input string to have a timezone before parsing it (I'm using dateutil for parsing, if that matters), but that seems incredibly kludgy.

Also, I've tried this in both Python 2.6 and Python 2.7, with the same results.

Context

I am writing a parser for some data files. There is an old format I need to support where the date string does not have a timezone indicator. I've already fixed the data source, but I still need to support the legacy data format. A one time conversion of the legacy data is not an option for various business BS reasons. While in general, I do not like the idea of hard-coding a default timezone, in this case it seems like the best option. I know with reasonable confidence that all the legacy data in question is in UTC, so I'm prepared to accept the risk of defaulting to that in this case.

答:
Python 3.9 adds the zoneinfo module so now only the standard library is needed!

```<code>from zoneinfo import ZoneInfo
from datetime import datetime
unaware = datetime(2020, 10, 31, 12)
</code>```

Attach a timezone:

```<code>>>> unaware.replace(tzinfo=ZoneInfo('Asia/Tokyo'))
datetime.datetime(2020, 10, 31, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='Asia/Tokyo'))
>>> str(_)
'2020-10-31 12:00:00+09:00'
</code>```

Attach the system's local timezone:

```<code>>>> unaware.replace(tzinfo=ZoneInfo('localtime'))
datetime.datetime(2020, 10, 31, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='localtime'))
>>> str(_)
'2020-10-31 12:00:00+01:00'
</code>```

Subsequently it is properly converted to other timezones:

```<code>>>> unaware.replace(tzinfo=ZoneInfo('localtime')).astimezone(ZoneInfo('Asia/Tokyo'))
datetime.datetime(2020, 10, 31, 20, 0, tzinfo=backports.zoneinfo.ZoneInfo(key='Asia/Tokyo'))
>>> str(_)
'2020-10-31 20:00:00+09:00'
</code>```

Wikipedia list of available time zones

Windows has no system time zone database, so here an extra package is needed:

```<code>pip install tzdata
</code>```

There is a backport to allow use of zoneinfo in Python 3.6 to 3.8:

```<code>pip install backports.zoneinfo
</code>```

Then:

```<code>from backports.zoneinfo import ZoneInfo
</code>```

Body:
What I need to do

I have a timezone-unaware datetime object, to which I need to add a time zone in order to be able to compare it with other timezone-aware datetime objects. I do not want to convert my entire application to timezone unaware for this one legacy case.

What I've Tried

First, to demonstrate the problem:

Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> import pytz
>>> unaware = datetime.datetime(2011,8,15,8,15,12,0)
>>> unaware
datetime.datetime(2011, 8, 15, 8, 15, 12)
>>> aware = datetime.datetime(2011,8,15,8,15,12,0,pytz.UTC)
>>> aware
datetime.datetime(2011, 8, 15, 8, 15, 12, tzinfo=<UTC>)
>>> aware == unaware
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware datetimes

First, I tried astimezone:

>>> unaware.astimezone(pytz.UTC)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: astimezone() cannot be applied to a naive datetime
>>>

It's not terribly surprising this failed, since it's actually trying to do a conversion.  Replace seemed like a better choice (as per How do I get a value of datetime.today() in Python that is "timezone aware"?):

>>> unaware.replace(tzinfo=pytz.UTC)
datetime.datetime(2011, 8, 15, 8, 15, 12, tzinfo=<UTC>)
>>> unaware == aware
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware datetimes
>>>

But as you can see, replace seems to set the tzinfo, but not make the object aware.  I'm getting ready to fall back to doctoring the input string to have a timezone before parsing it (I'm using dateutil for parsing, if that matters), but that seems incredibly kludgy.

Also, I've tried this in both Python 2.6 and Python 2.7, with the same results.

Context

I am writing a parser for some data files. There is an old format I need to support where the date string does not have a timezone indicator. I've already fixed the data source, but I still need to support the legacy data format. A one time conversion of the legacy data is not an option for various business BS reasons. While in general, I do not like the idea of hard-coding a default timezone, in this case it seems like the best option. I know with reasonable confidence that all the legacy data in question is in UTC, so I'm prepared to accept the risk of defaulting to that in this case.

Body:
Python 3.9 adds the zoneinfo module so now only the standard library is needed!

from zoneinfo import ZoneInfo
from datetime import datetime
unaware = datetime(2020, 10, 31, 12)

Attach a timezone:

>>> unaware.replace(tzinfo=ZoneInfo('Asia/Tokyo'))
datetime.datetime(2020, 10, 31, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='Asia/Tokyo'))
>>> str(_)
'2020-10-31 12:00:00+09:00'

Attach the system's local timezone:

>>> unaware.replace(tzinfo=ZoneInfo('localtime'))
datetime.datetime(2020, 10, 31, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='localtime'))
>>> str(_)
'2020-10-31 12:00:00+01:00'

Subsequently it is properly converted to other timezones:

>>> unaware.replace(tzinfo=ZoneInfo('localtime')).astimezone(ZoneInfo('Asia/Tokyo'))
datetime.datetime(2020, 10, 31, 20, 0, tzinfo=backports.zoneinfo.ZoneInfo(key='Asia/Tokyo'))
>>> str(_)
'2020-10-31 20:00:00+09:00'

Wikipedia list of available time zones

Windows has no system time zone database, so here an extra package is needed:

pip install tzdata

There is a backport to allow use of zoneinfo in Python 3.6 to 3.8:

pip install backports.zoneinfo

Then:

from backports.zoneinfo import ZoneInfo


问:
How to create a random instance of a case class?
Suppose I've got a few case classes, e.g.:

```<code>case class C(c1: Int, c2: Double, c3: Option[String])
case class B(b: Int, cs: Seq[C])
case class A(a: String, bs: Seq[B])
</code>```

Now I would like to generate a few instances of A with random values for tests.

I am looking for a generic way to do that. I can probably do it with runtime reflection but I prefer a compile-time solution.

```<code>def randomInstance[A](a: A): A = ???
</code>```

How can I do it ? Can it be done with shapeless ?

答:
We've started using Magnolia, which provides a faster type class derivation compared to shapeless for derivation of Arbitrary instances.

Here is the library to use, and here is an example (docs):

case class Inner(int: Int, str: String)
case class Outer(inner: Inner)

// ScalaCheck Arbitrary
import magnolify.scalacheck.auto._
import org.scalacheck._ // implicit instances for Arbitrary[Int], etc.

val arb: Arbitrary[Outer] = implicitly[Arbitrary[Outer]]
arb.arbitrary.sample
// = Some(Outer(Inter(12345, abcde)))
```

Body:
Suppose I've got a few case classes, e.g.:

case class C(c1: Int, c2: Double, c3: Option[String])
case class B(b: Int, cs: Seq[C])
case class A(a: String, bs: Seq[B])

Now I would like to generate a few instances of A with random values for tests.

I am looking for a generic way to do that. I can probably do it with runtime reflection but I prefer a compile-time solution.

def randomInstance[A](a: A): A = ???

How can I do it ? Can it be done with shapeless ?


答:
This could be fine </p>

```<code>s = "Hello World"
s.split()[0]
</code>```

<p>but a way without any method could be </p>

```<code>s[0:5]
</code>```

Body:
I have a homework assignment where I have to select the first word in a string. Normally I would do this:

s = "Hello World"
words = s.split()
first_word = words[0]
print(first_word)

For this assignment I cannot use methods or loops to answer the question. Any ideas?

Body:
This could be fine

s = "Hello World"
s.split()[0]

but a way without any method could be

s[0:5]


问:
Blazor hosted client - error on published web application on azure app service
When calling the xxxxxxxx.azurewebsites.net, the following appears in the browser console. Can anyone help. Thanks.

```<code>blazor.webassembly.js:1 System.InvalidOperationException: A suitable constructor for type 'Microsoft.Extensions.Logging.LoggerFactory' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite (Microsoft.Extensions.DependencyInjection.ServiceLookup.ResultCache lifetime, System.Type serviceType, System.Type implementationType, Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain callSiteChain) <0x1ef0ee0 + 0x00086> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact (Microsoft.Extensions.DependencyInjection.ServiceDescriptor descriptor, System.Type serviceType, Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain callSiteChain, System.Int32 slot) <0x1ee9cc0 + 0x000f2> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact (System.Type serviceType, Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain callSiteChain) <0x1ee9878 + 0x00034> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite (System.Type serviceType, Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain callSiteChain) <0x1ee91b0 + 0x0005a> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory+<>c__DisplayClass7_0.<GetCallSite>b__0 (System.Type type) <0x1ee8ce8 + 0x00010> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at System.Collections.Concurrent.ConcurrentDictionary`2[TKey,TValue].GetOrAdd (TKey key, System.Func`2[T,TResult] valueFactory) <0x1ed0ea0 + 0x0006c> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite (System.Type serviceType, Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain callSiteChain) <0x1ed0d28 + 0x00040> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.CreateServiceAccessor (System.Type serviceType) <0x1ed0790 + 0x00018> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at System.Collections.Concurrent.ConcurrentDictionary`2[TKey,TValue].GetOrAdd (TKey key, System.Func`2[T,TResult] valueFactory) <0x1ed0018 + 0x0006c> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService (System.Type serviceType, Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope serviceProviderEngineScope) <0x1ecfdd8 + 0x00024> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService (System.Type serviceType) <0x1ee8c18 + 0x00020> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService (System.IServiceProvider provider, System.Type serviceType) <0x1ecf710 + 0x00062> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T] (System.IServiceProvider provider) <0x1ee8b20 + 0x0001e> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.AspNetCore.Components.WebAssembly.Hosting.WebAssemblyHost.RunAsyncCore (System.Threading.CancellationToken cancellationToken) <0x1ee81e0 + 0x0016a> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at TakeOut.Client.Program.Main (System.String[] args) <0x1e12b18 + 0x00152> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.AspNetCore.Components.WebAssembly.Hosting.EntrypointInvoker.InvokeEntrypoint (System.String assemblyName, System.String[] args, Microsoft.AspNetCore.Components.WebAssembly.Hosting.SatelliteResourcesLoader satelliteResourcesLoader) <0x1d29ea8 + 0x001d6> in <filename unknown>:0
</code>```

The client project:

```<code>    -PropertyGroup-
    -TargetFramework-netstandard2.1-/TargetFramework-
    -RazorLangVersion-3.0-/RazorLangVersion-
    -ServiceWorkerAssetsManifest-service-worker-assets.js-/ServiceWorkerAssetsManifest-
  -/PropertyGroup-

  -ItemGroup-
    -PackageReference Include="Blazored.LocalStorage" Version="2.1.5" /-
    -PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="3.2.0-preview5.20216.8" /-
    -PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Build" Version="3.2.0-preview5.20216.8" PrivateAssets="all" /-
    -PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="3.2.0-preview5.20216.8" PrivateAssets="all" /-
    -PackageReference Include="Microsoft.AspNetCore.Blazor.HttpClient" Version="3.2.0-preview2.20160.5" /-
    -PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="3.1.4" /-
  -/ItemGroup-
  -ItemGroup-
    -ProjectReference Include="..\Shared\TakeOut.Shared.csproj" /-
  -/ItemGroup-

  -!-- When publishing, swap service-worker.published.js in place of service-worker.js ---
  -ItemGroup Condition="'$(DesignTimeBuild)' != 'true'"-
    -Content Remove="wwwroot\service-worker.js" /-
    -Content Update="wwwroot\service-worker.published.js" Link="wwwroot\service-worker.js" /-
  -/ItemGroup-
  -ItemGroup-
    -Folder Include="wwwroot\Images\" /-
  -/ItemGroup-
</Project>
</code>```

The server project:

```<code>-Project Sdk="Microsoft.NET.Sdk.Web"-

  -PropertyGroup-
    -TargetFramework-netcoreapp3.1-/TargetFramework-
    -DisableImplicitComponentsAnalyzers-true-/DisableImplicitComponentsAnalyzers-
  -/PropertyGroup-

  -ItemGroup-
    -PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="3.2.0-preview5.20216.8" /-
    -PackageReference Include="Microsoft.Azure.Cosmos" Version="3.8.0" /-
    -PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.2" /-
  -/ItemGroup-

  -ItemGroup-
    -ProjectReference Include="..\Client\TakeOut.Client.csproj" /-
    -ProjectReference Include="..\Shared\TakeOut.Shared.csproj" /-
  -/ItemGroup-

-/Project-
</code>```

答:
I updated all my code the the release version of the web assembly which gave no error in development mode on my pc but errors when publising it to azure.

The problem was with Microsoft.AspNetCore.SignalR.Client in the web assembly. Removing the package and code related to the package did not generate any errors.

I fixed the problem by using the javascript SignalR in my web assembly. It works but I would have prefer to use the package SignalR and the C# code to handle the connection instead of using javascript.

Note: I tried the package with only a  web assembly (instead of a hosted web assembly). Same errors with the package when published to azure.

Body:
When calling the xxxxxxxx.azurewebsites.net, the following appears in the browser console. Can anyone help. Thanks.

blazor.webassembly.js:1 System.InvalidOperationException: A suitable constructor for type 'Microsoft.Extensions.Logging.LoggerFactory' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite (Microsoft.Extensions.DependencyInjection.ServiceLookup.ResultCache lifetime, System.Type serviceType, System.Type implementationType, Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain callSiteChain) <0x1ef0ee0 + 0x00086> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact (Microsoft.Extensions.DependencyInjection.ServiceDescriptor descriptor, System.Type serviceType, Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain callSiteChain, System.Int32 slot) <0x1ee9cc0 + 0x000f2> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact (System.Type serviceType, Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain callSiteChain) <0x1ee9878 + 0x00034> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite (System.Type serviceType, Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain callSiteChain) <0x1ee91b0 + 0x0005a> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory+<>c__DisplayClass7_0.<GetCallSite>b__0 (System.Type type) <0x1ee8ce8 + 0x00010> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at System.Collections.Concurrent.ConcurrentDictionary`2[TKey,TValue].GetOrAdd (TKey key, System.Func`2[T,TResult] valueFactory) <0x1ed0ea0 + 0x0006c> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite (System.Type serviceType, Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain callSiteChain) <0x1ed0d28 + 0x00040> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.CreateServiceAccessor (System.Type serviceType) <0x1ed0790 + 0x00018> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at System.Collections.Concurrent.ConcurrentDictionary`2[TKey,TValue].GetOrAdd (TKey key, System.Func`2[T,TResult] valueFactory) <0x1ed0018 + 0x0006c> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService (System.Type serviceType, Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope serviceProviderEngineScope) <0x1ecfdd8 + 0x00024> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService (System.Type serviceType) <0x1ee8c18 + 0x00020> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService (System.IServiceProvider provider, System.Type serviceType) <0x1ecf710 + 0x00062> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T] (System.IServiceProvider provider) <0x1ee8b20 + 0x0001e> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.AspNetCore.Components.WebAssembly.Hosting.WebAssemblyHost.RunAsyncCore (System.Threading.CancellationToken cancellationToken) <0x1ee81e0 + 0x0016a> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at TakeOut.Client.Program.Main (System.String[] args) <0x1e12b18 + 0x00152> in <filename unknown>:0
(anonymous) @ blazor.webassembly.js:1
blazor.webassembly.js:1   at Microsoft.AspNetCore.Components.WebAssembly.Hosting.EntrypointInvoker.InvokeEntrypoint (System.String assemblyName, System.String[] args, Microsoft.AspNetCore.Components.WebAssembly.Hosting.SatelliteResourcesLoader satelliteResourcesLoader) <0x1d29ea8 + 0x001d6> in <filename unknown>:0

The client project:

    -PropertyGroup-
    -TargetFramework-netstandard2.1-/TargetFramework-
    -RazorLangVersion-3.0-/RazorLangVersion-
    -ServiceWorkerAssetsManifest-service-worker-assets.js-/ServiceWorkerAssetsManifest-
  -/PropertyGroup-

  -ItemGroup-
    -PackageReference Include="Blazored.LocalStorage" Version="2.1.5" /-
    -PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="3.2.0-preview5.20216.8" /-
    -PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Build" Version="3.2.0-preview5.20216.8" PrivateAssets="all" /-
    -PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="3.2.0-preview5.20216.8" PrivateAssets="all" /-
    -PackageReference Include="Microsoft.AspNetCore.Blazor.HttpClient" Version="3.2.0-preview2.20160.5" /-
    -PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="3.1.4" /-
  -/ItemGroup-
  -ItemGroup-
    -ProjectReference Include="..\Shared\TakeOut.Shared.csproj" /-
  -/ItemGroup-

  -!-- When publishing, swap service-worker.published.js in place of service-worker.js ---
  -ItemGroup Condition="'$(DesignTimeBuild)' != 'true'"-
    -Content Remove="wwwroot\service-worker.js" /-
    -Content Update="wwwroot\service-worker.published.js" Link="wwwroot\service-worker.js" /-
  -/ItemGroup-
  -ItemGroup-
    -Folder Include="wwwroot\Images\" /-
  -/ItemGroup-
</Project>

The server project:

-Project Sdk="Microsoft.NET.Sdk.Web"-

  -PropertyGroup-
    -TargetFramework-netcoreapp3.1-/TargetFramework-
    -DisableImplicitComponentsAnalyzers-true-/DisableImplicitComponentsAnalyzers-
  -/PropertyGroup-

  -ItemGroup-
    -PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="3.2.0-preview5.20216.8" /-
    -PackageReference Include="Microsoft.Azure.Cosmos" Version="3.8.0" /-
    -PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.2" /-
  -/ItemGroup-

  -ItemGroup-
    -ProjectReference Include="..\Client\TakeOut.Client.csproj" /-
    -ProjectReference Include="..\Shared\TakeOut.Shared.csproj" /-
  -/ItemGroup-

-/Project-


问:
Display the command that is being executed in cshell
I am using csh where i want to display the command that is being executed.

I can see find something like set -x placing at the beginning of the script. But it seems to only work for bash. In cshell i am getting following error.

```<code>set: Variable name must begin with a letter.
Failed
</code>```

Is there any way to display the command the is being executed in cshell. Please help!

答: You can run your c-shell script using csh -v. This will display each line of the script before executing it. This is useful for debugging c-shell scripts.

Body:
I am using csh where i want to display the command that is being executed.

I can see find something like set -x placing at the beginning of the script. But it seems to only work for bash. In cshell i am getting following error.

set: Variable name must begin with a letter.
Failed

Is there any way to display the command the is being executed in cshell. Please help!