问:
Error boundary doesn't catch error from apollo client
I'm trying to catch some errors on the top level, to show the most beautiful error page in the world.

For some reason, I see my nodes disconnected, but Error Boundary never fires.

import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import ApolloClient, { gql } from 'apollo-boost';

const client = new ApolloClient({ uri: "/graphql" });
const query = gql`{ items { id }}`;

class ErrorBoundary extends React.Component {
  state = { hasError: false };

  static getDerivedStateFromError(error: any) {
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) {
      return
Had error

    } else {
      return this.props.children;
    }
  }
}

function App() {
  const [data, setData] = useState<any>(null);

  useEffect(() => {
    client.query({ query })
      .then(res => setData(res))
      .catch(err => { console.warn("Error:", err); throw err; });
  }, []);

  return ```Data: {data}```;
}

ReactDOM.render(
  <ErrorBoundary>
      <App />
  </ErrorBoundary>,
  document.getElementById('root')
);
```

I run this in an empty create-react-app project.

I expect to see
Had error
; I get CRA unhandled error screen.

答:
From the docs

Error boundaries do not catch errors for:

Event handlers (learn more)

Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks)

Server side rendering

Errors thrown in the error boundary itself (rather than its children)

Promises are asynchronous, so rejected Promises won't be caught by error boundaries. At the moment, the recommended but somewhat hackish approach is to throw the error inside setState. In functional components, you can use the set function returned by the useState hook in place of setState:

```<code>const [, setState] = useState()
useEffect(() => {
  client.query({ query })
    .then(res => setData(res))
    .catch(err => {
      console.warn("Error:", err);
      setState(() => {
        throw err;
      });
    });
}, []);
</code>```

Throwing inside useEffect would work too, but not inside a then or catch callback of a Promise. You also can't make the useEffect callback an async function because it can't return a Promise. So we're stuck with using setState.

Also note that there is really no reason to be calling client.query directly, particularly since this code will not rerender your UI if the cache changes. You should use useQuery and the data state already exposed by the hook for you.

Body:
I'm trying to catch some errors on the top level, to show the most beautiful error page in the world.

For some reason, I see my nodes disconnected, but Error Boundary never fires.

import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import ApolloClient, { gql } from 'apollo-boost';

const client = new ApolloClient({ uri: "/graphql" });
const query = gql`{ items { id }}`;

class ErrorBoundary extends React.Component {
  state = { hasError: false };

  static getDerivedStateFromError(error: any) {
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) {
      return
Had error

    } else {
      return this.props.children;
    }
  }
}

function App() {
  const [data, setData] = useState<any>(null);

  useEffect(() => {
    client.query({ query })
      .then(res => setData(res))
      .catch(err => { console.warn("Error:", err); throw err; });
  }, []);

  return
Data: {data}
;
}

ReactDOM.render(
  <ErrorBoundary>
      <App />
  </ErrorBoundary>,
  document.getElementById('root')
);

I run this in an empty create-react-app project.

I expect to see
Had error
; I get CRA unhandled error screen.

Body:
From the docs

Error boundaries do not catch errors for:

Event handlers (learn more)

Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks)

Server side rendering

Errors thrown in the error boundary itself (rather than its children)

Promises are asynchronous, so rejected Promises won't be caught by error boundaries. At the moment, the recommended but somewhat hackish approach is to throw the error inside setState. In functional components, you can use the set function returned by the useState hook in place of setState:

const [, setState] = useState()
useEffect(() => {
  client.query({ query })
    .then(res => setData(res))
    .catch(err => {
      console.warn("Error:", err);
      setState(() => {
        throw err;
      });
    });
}, []);

Throwing inside useEffect would work too, but not inside a then or catch callback of a Promise. You also can't make the useEffect callback an async function because it can't return a Promise. So we're stuck with using setState.

Also note that there is really no reason to be calling client.query directly, particularly since this code will not rerender your UI if the cache changes. You should use useQuery and the data state already exposed by the hook for you.


来源: stackexchange

问:
How to use (link) debug version of libc++ in macOS?
I want to enable debug version of libc++ in macOS, so I define _LIBCPP_DEBUG=1 in cxx_build_flags [Debug Version of libC++],
but unable to link debug function of libc++. I guess there is only release version of libc++ in my system, so how can I get the debug version of libc++ in macOS

```<code>Undefined symbols for architecture x86_64:
"std::__1::__libcpp_db::__decrementable(void const*) const", referenced from:
  void std::__1::__nth_element<std::__1::__debug_less<std::__1::__less<float, float> >&, std::__1::__wrap_iter<float*> >(std::__1::__wrap_iter<float*>, std::__1::__wrap_iter<float*>, std::__1::__wrap_iter<float*>, std::__1::__debug_less<std::__1::__less<float, float> >&)
</code>```

答:
I think I got this to work!

So the steps I took,

Check your toolchains __config file for _LIBCPP_VERSION's value.

Browse the source repo for the commit where that version was set

From that commit, find the debug.cpp file

Include/compile/link the debug.cpp with your project (and remember to set _LIBCPP_DEBUG=1).

For me the intermediate results for the steps were (with Catalina, XCode Version 11.3.1)

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/__config was at version 8000

Looking at the history at https://github.com/llvm/llvm-project/commits/main?&path[]=libcxx&path[]=include&path[]=__config I found commit https://github.com/llvm/llvm-project/commit/25977548aa5ad7cfe45a17e4ba136abfa4613b96#diff-0a85f740cd20254bc3bb03975c89d93a

The debug.cpp for that commit is at https://github.com/llvm/llvm-project/blob/25977548aa5ad7cfe45a17e4ba136abfa4613b96/libcxx/src/debug.cpp

ContentLicense: CC BY-SA 4.0

Body:
I want to enable debug version of libc++ in macOS, so I define _LIBCPP_DEBUG=1 in cxx_build_flags [Debug Version of libC++],
but unable to link debug function of libc++. I guess there is only release version of libc++ in my system, so how can I get the debug version of libc++ in macOS

Undefined symbols for architecture x86_64:
"std::__1::__libcpp_db::__decrementable(void const*) const", referenced from:
  void std::__1::__nth_element<std::__1::__debug_less<std::__1::__less<float, float> >&, std::__1::__wrap_iter<float*> >(std::__1::__wrap_iter<float*>, std::__1::__wrap_iter<float*>, std::__1::__wrap_iter<float*>, std::__1::__debug_less<std::__1::__less<float, float> >&)


问:
TypeError: ("'list' object is not callable", 'occurred at index 0')
```<code>def create_tfidf_dictionary(x, transformed_file, features):

    vector_coo = transformed_file[x.name].tocoo()
    vector_coo.col = features.iloc[vector_coo.col].values
    dict_from_coo = dict(zip(vector_coo.col, vector_coo.data))
    return dict_from_coo

def replace_tfidf_words(x, transformed_file, features):

    dictionary = create_tfidf_dictionary(x, transformed_file, features)
    return list(map(lambda y:dictionary[f'{y}'], x.title.split()))
%%time
replaced_tfidf_scores = file_weighting.apply(lambda x: replace_tfidf_words(x, transformed, features), axis=1)
</code>```

while running this code I'm having following error.

TypeError                                 Traceback (most recent call
  last)  in

~\Anaconda3\lib\site-packages\pandas\core\frame.py in apply(self,
  func, axis, broadcast, raw, reduce, result_type, args, **kwds)    6911
  kwds=kwds,    6912         )
  -> 6913         return op.get_result()    6914     6915     def applymap(self, func):

~\Anaconda3\lib\site-packages\pandas\core\apply.py in get_result(self)
      184             return self.apply_raw()
      185
  --> 186         return self.apply_standard()
      187
      188     def apply_empty_result(self):

~\Anaconda3\lib\site-packages\pandas\core\apply.py in
  apply_standard(self)
      290
      291         # compute the result using the series generator
  --> 292         self.apply_series_generator()
      293
      294         # wrap results

~\Anaconda3\lib\site-packages\pandas\core\apply.py in
  apply_series_generator(self)
      319             try:
      320                 for i, v in enumerate(series_gen):
  --> 321                     results[i] = self.f(v)
      322                     keys.append(v.name)
      323             except Exception as e:

 in (x)

 in replace_tfidf_words(x,
  transformed_file, features)
       24     '''
       25     dictionary = create_tfidf_dictionary(x, transformed_file, features)
  ---> 26     return list(map(lambda y:dictionary[f'{y}'], x.title.split()))

TypeError: ("'list' object is not callable", 'occurred at index 0')

I'm new to python, please help me out to this error.

答:
This is a common error, it usually happens when you set some value to a variable named list. Consider the code below:

```<code>list = [1+1, 2-4, 3*2]
values = list(1)
</code>```

At the first line, we assign a value to the variable named list. That is kind of intuitive, because, well, if we have a list, why not putting it in a variable named list, right? However, at the second line, we try to call the function list(). However, we replaced the value of the variable list, it is not the function anymore, it is some other thing. The result is the error:

```<code>Traceback (most recent call last):
  File "sl.py", line 3, in <module>
    values = list(1)
TypeError: 'list' object is not callable
</code>```

In your example, it is clear that you try to call the function at this line:

```<code>return list(map(lambda y:dictionary[f'{y}'], x.title.split()))
</code>```

The challenge is to find where you assign a value to the list variable. As someone commented, you can look for the list = substring in your code, and change the name of the variable there for something different from list. If you do not find this snippet anywhere, you can replace

```<code>return list(map(lambda y:dictionary[f'{y}'], x.title.split()))
</code>```

by

```<code>print(list)
</code>```

It will show which value you have on the list variable and may help you figure out where it was changed.

Either way, you will have to search beyond the snippet you've posted to us, which can be a challenge.

Body:
def create_tfidf_dictionary(x, transformed_file, features):

    vector_coo = transformed_file[x.name].tocoo()
    vector_coo.col = features.iloc[vector_coo.col].values
    dict_from_coo = dict(zip(vector_coo.col, vector_coo.data))
    return dict_from_coo

def replace_tfidf_words(x, transformed_file, features):

    dictionary = create_tfidf_dictionary(x, transformed_file, features)
    return list(map(lambda y:dictionary[f'{y}'], x.title.split()))
%%time
replaced_tfidf_scores = file_weighting.apply(lambda x: replace_tfidf_words(x, transformed, features), axis=1)

while running this code I'm having following error.

TypeError                                 Traceback (most recent call
  last)  in

~\Anaconda3\lib\site-packages\pandas\core\frame.py in apply(self,
  func, axis, broadcast, raw, reduce, result_type, args, **kwds)    6911
  kwds=kwds,    6912         )
  -> 6913         return op.get_result()    6914     6915     def applymap(self, func):

~\Anaconda3\lib\site-packages\pandas\core\apply.py in get_result(self)
      184             return self.apply_raw()
      185
  --> 186         return self.apply_standard()
      187
      188     def apply_empty_result(self):

~\Anaconda3\lib\site-packages\pandas\core\apply.py in
  apply_standard(self)
      290
      291         # compute the result using the series generator
  --> 292         self.apply_series_generator()
      293
      294         # wrap results

~\Anaconda3\lib\site-packages\pandas\core\apply.py in
  apply_series_generator(self)
      319             try:
      320                 for i, v in enumerate(series_gen):
  --> 321                     results[i] = self.f(v)
      322                     keys.append(v.name)
      323             except Exception as e:

 in (x)

 in replace_tfidf_words(x,
  transformed_file, features)
       24     '''
       25     dictionary = create_tfidf_dictionary(x, transformed_file, features)
  ---> 26     return list(map(lambda y:dictionary[f'{y}'], x.title.split()))

TypeError: ("'list' object is not callable", 'occurred at index 0')

I'm new to python, please help me out to this error.

Body:
This is a common error, it usually happens when you set some value to a variable named list. Consider the code below:

list = [1+1, 2-4, 3*2]
values = list(1)

At the first line, we assign a value to the variable named list. That is kind of intuitive, because, well, if we have a list, why not putting it in a variable named list, right? However, at the second line, we try to call the function list(). However, we replaced the value of the variable list, it is not the function anymore, it is some other thing. The result is the error:

Traceback (most recent call last):
  File "sl.py", line 3, in <module>
    values = list(1)
TypeError: 'list' object is not callable

In your example, it is clear that you try to call the function at this line:

return list(map(lambda y:dictionary[f'{y}'], x.title.split()))

The challenge is to find where you assign a value to the list variable. As someone commented, you can look for the list = substring in your code, and change the name of the variable there for something different from list. If you do not find this snippet anywhere, you can replace

return list(map(lambda y:dictionary[f'{y}'], x.title.split()))

by

print(list)

It will show which value you have on the list variable and may help you figure out where it was changed.

Either way, you will have to search beyond the snippet you've posted to us, which can be a challenge.


问:
Force asyncio to emit exception logs whether or not task is awaited
(This is a follow-up question to this one.)

The docs for asyncio say:

If a Future.set_exception() is called but the Future object is never awaited on, the exception would never be propagated to the user code. In this case, asyncio would emit a log message when the Future object is garbage collected.

I want to know whether there's any way to make python forcefully log exceptions regardless of :

Whether or not I awaited the task

Whether or not the task is garbage collected

Basically, I want the ability to fire and forget some background tasks from anywhere in my code, and not worry about await-ing them all the time.

My first-hand async experience was in dart, which does not seem to suffer from this issue.

(Plus, this blatantly violates the zen of python #10).

答:
Basically, I want the ability to fire and forget some background tasks from anywhere in my code, and not worry about await-ing them all the time.

If you control the coroutines, the most straightforward way is for the coroutine itself to catch and log the errors. You can automate it using a decorator like this:

def log_exceptions(fn):
    async def run_with_log(*args, **kwds):
        try:
            return await fn(*args, **kwds)
        except Exception as e:
            print "Exception in %s: %s" % (fn.__name__, e)
    return run_with_log
```

Now, decorating your top-level coroutines with @log_exceptions will give you the requested behavior.

I am not aware of an asyncio switch that does this by default because it would violate the contract of Task (which captures both the return value and the exception raised by the coroutine, if any).

(Plus, this blatantly violates the zen of python #10).

The trio library offers a different take on this, in the form of nurseries, which guarantee not only that the exception will be logged, but that it will be re-raised at a predictable place.

Body:
Basically, I want the ability to fire and forget some background tasks from anywhere in my code, and not worry about await-ing them all the time.

If you control the coroutines, the most straightforward way is for the coroutine itself to catch and log the errors. You can automate it using a decorator like this:

def log_exceptions(fn):
    async def run_with_log(*args, **kwds):
        try:
            return await fn(*args, **kwds)
        except Exception as e:
            print "Exception in %s: %s" % (fn.__name__, e)
    return run_with_log

Now, decorating your top-level coroutines with @log_exceptions will give you the requested behavior.

I am not aware of an asyncio switch that does this by default because it would violate the contract of Task (which captures both the return value and the exception raised by the coroutine, if any).

(Plus, this blatantly violates the zen of python #10).

The trio library offers a different take on this, in the form of nurseries, which guarantee not only that the exception will be logged, but that it will be re-raised at a predictable place.


问:
Change global variable from event function
I am trying to learn Javascript.

I watched some Javascript course on Youtube and am trying to create my first project.

Project should be simple tic-tac-toe game.

Functionality:
First click on box should fill with "X"
Second click on another box should fill with "Y"
Third click on another box should fill with "X" again and so on until all boxes will be filled with character.

there is my codes
HTML

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<div class="main">
<table>
    <tr>
        <td class="b1-1"></td>
        <td class="b1-2"></td>
        <td class="b1-3"></td>
    </tr>
    <tr>
        <td class="b2-1"></td>
        <td class="b2-2"></td>
        <td class="b2-3"></td>
    </tr>
    <tr>
        <td class="b3-1"></td>
        <td class="b3-2"></td>
        <td class="b3-3"></td>
    </tr>
</table>
</div>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
</code>```

CSS

```<code>.main {
    padding: 100px 0;
    width: 360px;
    margin: 0 auto;
}

table, tbody {
    margin: 0;
    padding: 0;
    width: 360px;
    height: 360px;
}

tr {
    width:360px;
    height: 120px;
    margin: 0;
    padding: 0;
}

td {
    text-align: center;
    width:120px;
    height: 120px;
    border: 1px solid #333;
    margin: 0;
    padding: 0;
    font-size: 50px;
}
</code>```

Javascript

```<code>var action = document.querySelectorAll('td');
var gameState = 0;
for (var i = 0; i <= action.length - 1; i++) {
    getClassName = "." + action[i].classList.value;
        if (gameState === 0) {
            document.querySelector(getClassName).addEventListener("click", chasviX(i));
        } else {
            document.querySelector(getClassName).addEventListener("click", chasviO(i));
        }
}

function chasviX(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "X";
            gameState = 1;
        });
};

function chasviO(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "O";
            gameState = 0;
        });
};
</code>```

There is project link also - https://jsfiddle.net/qwy2k571/

At the moment each box is filling with "X".
I know i didn't understand closures and scope chains exactly but please give me an correct code to understand it by example.

Thanks in advance and best regards.

答:
Since you are using querySelectorAll which will give a collection, you can iterate that and directly add event listener to it. Aslo you are adding multiple eventlistener which is not required

var action = document.querySelectorAll('td');
var gameState = 0;
action.forEach((item) => {
  item.addEventListener('click', (e) => {
    if (gameState === 0) {
      e.target.textContent = "X";
      gameState = 1;
    } else {
      e.target.textContent = "0";
      gameState = 0;
    }
  })

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main {
  padding: 100px 0;
  width: 360px;
  margin: 0 auto;
}

table,
tbody {
  margin: 0;
  padding: 0;
  width: 360px;
  height: 360px;
}

tr {
  width: 360px;
  height: 120px;
  margin: 0;
  padding: 0;
}

td {
  text-align: center;
  width: 120px;
  height: 120px;
  border: 1px solid #333;
  margin: 0;
  padding: 0;
  font-size: 50px;
}</code>```

```

Body:
I am trying to learn Javascript.

I watched some Javascript course on Youtube and am trying to create my first project.

Project should be simple tic-tac-toe game.

Functionality:
First click on box should fill with "X"
Second click on another box should fill with "Y"
Third click on another box should fill with "X" again and so on until all boxes will be filled with character.

there is my codes
HTML

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">

CSS

.main {
    padding: 100px 0;
    width: 360px;
    margin: 0 auto;
}

table, tbody {
    margin: 0;
    padding: 0;
    width: 360px;
    height: 360px;
}

tr {
    width:360px;
    height: 120px;
    margin: 0;
    padding: 0;
}

td {
    text-align: center;
    width:120px;
    height: 120px;
    border: 1px solid #333;
    margin: 0;
    padding: 0;
    font-size: 50px;
}

Javascript

var action = document.querySelectorAll('td');
var gameState = 0;
for (var i = 0; i <= action.length - 1; i++) {
    getClassName = "." + action[i].classList.value;
        if (gameState === 0) {
            document.querySelector(getClassName).addEventListener("click", chasviX(i));
        } else {
            document.querySelector(getClassName).addEventListener("click", chasviO(i));
        }
}

function chasviX(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "X";
            gameState = 1;
        });
};

function chasviO(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "O";
            gameState = 0;
        });
};

There is project link also - https://jsfiddle.net/qwy2k571/

At the moment each box is filling with "X".
I know i didn't understand closures and scope chains exactly but please give me an correct code to understand it by example.

Thanks in advance and best regards.

Body:
Since you are using querySelectorAll which will give a collection, you can iterate that and directly add event listener to it. Aslo you are adding multiple eventlistener which is not required

var action = document.querySelectorAll('td');
var gameState = 0;
action.forEach((item) => {
  item.addEventListener('click', (e) => {
    if (gameState === 0) {
      e.target.textContent = "X";
      gameState = 1;
    } else {
      e.target.textContent = "0";
      gameState = 0;
    }
  })

})

.main {
  padding: 100px 0;
  width: 360px;
  margin: 0 auto;
}

table,
tbody {
  margin: 0;
  padding: 0;
  width: 360px;
  height: 360px;
}

tr {
  width: 360px;
  height: 120px;
  margin: 0;
  padding: 0;
}

td {
  text-align: center;
  width: 120px;
  height: 120px;
  border: 1px solid #333;
  margin: 0;
  padding: 0;
  font-size: 50px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
  <table>
    <tr>
      <td class="b1-1"></td>
      <td class="b1-2"></td>
      <td class="b1-3"></td>
    </tr>
    <tr>
      <td class="b2-1"></td>
      <td class="b2-2"></td>
      <td class="b2-3"></td>
    </tr>
    <tr>
      <td class="b3-1"></td>
      <td class="b3-2"></td>
      <td class="b3-3"></td>
    </tr>
  </table>
</div>


问:
Generic typescript with optional extends
How to make generic ApiResBook type work with optional props using extends for input check?

Sandbox.

I have this main types, same as database fields:

```<code>// Main types as in database - should't be changed
type Book = {
  id: string
  title: string
  visible: boolean
  author: string
}

type Author = {
  id: string
  name: string
}
</code>```

For api fetch response i need generic type that will shape object based on requested fields

```<code>// Inhereted from types from main
type BookFields = keyof Book
type AuthorFields = keyof Author

// type for generating expected fetch response from API
type ApiResBook<
  PickedBookFields extends BookFields,
  PickedAuthorFields extends AuthorFields | undefined = undefined,
> = {
  book: Pick<Book, PickedBookFields> & {
    author?: PickedAuthorFields extends AuthorFields ? Pick<Author, PickedAuthorFields> : undefined
  }
}

// fetch example of usage
async function fn() {

  const fetchAPI = <ExpectedData = any>(
    apiAction: string,
    body: any
  ): Promise<{ data: ExpectedData } | { error: true }> => {
    return new Promise((resolve) => {
      fetch(`api`, body)
        .then((raw) => raw.json())
        .then((parsed: { data: ExpectedData } | { error: true }) => resolve(parsed))
        .catch((err) => {
          console.log(err)
        })
    })
  }

  // response type is { error: true  } | {data: { book: { id: string } } }
  const response = await fetchAPI<ApiResBook<'id'>>('smth', {})
}
</code>```

Problem is with generic ApiResBook type, i don't know how to make some generic types optional. Test examples included:

```<code>//tests
type BookOnly = ApiResBook<'id'>
type BookWithAuthor = ApiResBook<'id', 'name'>

// should be ok
const bookOnly: BookOnly = { book: { id: '1' } }
const bookWithAuthor: BookWithAuthor = { book: { id: '1', author: { name: 'Max' } } }

// should be error
type BookOnly2 = ApiResBook<'propFoesntExist'>
const bookOnlyError: BookOnly = { book: { id: '1', author: {name: 'Max'} } }
const bookWithoutAuthorError: BookWithAuthor = {book: {id: '1'}}
</code>```

答:
Resolved this myself :/ Seems to work fine.

```<code>type ApiResBook<
  PickedBookFields extends BookFields,
  PickedAuthorFields extends AuthorFields | undefined = undefined,
> = {
  book: Pick<Book, PickedBookFields> & {
    author: PickedAuthorFields extends AuthorFields ? Pick<Author, PickedAuthorFields> : undefined
  }
}
</code>```

Sandbox.

Body:
How to make generic ApiResBook type work with optional props using extends for input check?

<a href="https://www.typescriptlang.org/play/index.html#code/PTAEFkEMEsDtQC4E8AOBTAzqSW6gCaQKQBGOaoAtKBgBYD2ArgDb4DkCoJFAxrZLADmafAFgAUMnSgAQvXoBrUAF5QAbwmhQ0fAC4aCAE5xBmxNATM0+jEZNmAbtAzQSV-SXlWBZyIwQMhjZ2QhIAvhISUhQAgv6BKupmOsHGoeJasJAAttYGaabiEeISIKAAkrC0aIZoCCKgAGaG9NmIqJhNLW3ZMLBRHbLyCgBi0GisWKoKaEj0jUOKA9JxAfSGYxP4U6AzcwurgZHiZdFN66DCsDVEJqBoAB7oPPX4TXV8oLUYKPSwGBRmq1QDEAArlZaxFDQABKmDkigAPGZQdAeDN8AjRuNJvcHvVYNtFtithgADQotEYw7rTa4x4Eok0jY4okAH1AjEJaEacAaqi5+B5fPwFPEAD5EhoMlxhvpUejEViyaAFRisXTtpKAGRJGVaPxrQwAfnlVJEzM1WAZaEJWEtrKwxtVVMRzJVaot8Vpjsl+kFwuuYhlxWKpTAjQ+tDxORQVlA805GEgwgkOCQsB4TS5L2gfyasAAFABKPVmHh-WzvBB8MHlRKIgCiTzQLxEABEiJBEgIkOLC2YDdCYrm-qkTGKtFpPPgkPpe2Zi-Lus40Ii1AQu-pm89Xp3iKAwqAORuai0gohDIwKGFJcpJdKp186oxDPBrgB3VUrgGFwvfehmAcNBS3vPUny0SMa1oQsAANIGhWCVRnJBi0HCCADoAltP9DEgD9QMlPCPwwgArDA-hLND9Uw7Ci0LFBIEMAE9HUTdiG3Fs23wfduyPE97kMc99CMa9D0I58KKAtAGKYlji2oiCpwwngiD4P8zwkx8lKnCt-kAtAMOYehBELTT0KfMJFKnKyzDDGUym+X5-goM5nDYs91hEq8KEPY91EIDi2M8RR9A3FJ8juI9ovLStOCcysKFUfCYE4KDa3BN1oThDAsURNgdDYcV+zYDBsgCNgVTUKzQHCY56pOMB6lsDBIWJAB5WBmCQRIYmy+FhnywrxTarEAHULFoZlev63LBoK9gVTYLJciK44yjoJhWC4CglnEPSqxChROu6-QsROnrVA3I6wu0Vi2AARjYPzigOzgjomgJmTO4ZPqm71DClWVQrYiLHsq7AAdula8jYKAHme6LD3WsBNpYN5uEE89RuGC7GyEi5VD62EBqRNgUBaFB23oTBYAQZtnAQNbJEGcbJuZfHzxmkm5rJwqlop+gqZpjA6YZ2xmbe4Hjq6pBOa8jrZaBm7Qfup6VUNQIwph-Q4cgBGkaPCQpY+yamAQDmCYvNmvoBqUVbUMGnrCI8gA" rel="nofollow noreferrer">Sandbox.

I have this main types, same as database fields:

// Main types as in database - should't be changed
type Book = {
  id: string
  title: string
  visible: boolean
  author: string
}

type Author = {
  id: string
  name: string
}

For api fetch response i need generic type that will shape object based on requested fields

// Inhereted from types from main
type BookFields = keyof Book
type AuthorFields = keyof Author

// type for generating expected fetch response from API
type ApiResBook<
  PickedBookFields extends BookFields,
  PickedAuthorFields extends AuthorFields | undefined = undefined,
> = {
  book: Pick<Book, PickedBookFields> & {
    author?: PickedAuthorFields extends AuthorFields ? Pick<Author, PickedAuthorFields> : undefined
  }
}

// fetch example of usage
async function fn() {

  const fetchAPI = <ExpectedData = any>(
    apiAction: string,
    body: any
  ): Promise<{ data: ExpectedData } | { error: true }> => {
    return new Promise((resolve) => {
      fetch(`api`, body)
        .then((raw) => raw.json())
        .then((parsed: { data: ExpectedData } | { error: true }) => resolve(parsed))
        .catch((err) => {
          console.log(err)
        })
    })
  }

  // response type is { error: true  } | {data: { book: { id: string } } }
  const response = await fetchAPI<ApiResBook<'id'>>('smth', {})
}

Problem is with generic ApiResBook type, i don't know how to make some generic types optional. Test examples included:

//tests
type BookOnly = ApiResBook<'id'>
type BookWithAuthor = ApiResBook<'id', 'name'>

// should be ok
const bookOnly: BookOnly = { book: { id: '1' } }
const bookWithAuthor: BookWithAuthor = { book: { id: '1', author: { name: 'Max' } } }

// should be error
type BookOnly2 = ApiResBook<'propFoesntExist'>
const bookOnlyError: BookOnly = { book: { id: '1', author: {name: 'Max'} } }
const bookWithoutAuthorError: BookWithAuthor = {book: {id: '1'}}

Body:
Resolved this myself :/ Seems to work fine.

type ApiResBook<
  PickedBookFields extends BookFields,
  PickedAuthorFields extends AuthorFields | undefined = undefined,
> = {
  book: Pick<Book, PickedBookFields> & {
    author: PickedAuthorFields extends AuthorFields ? Pick<Author, PickedAuthorFields> : undefined
  }
}

<a href="https://www.typescriptlang.org/play/index.html?ssl=57&ssc=46&pln=57&pc=45#code/PTAEFkEMEsDtQC4E8AOBTAzqSW6gCaQKQBGOaoAtKBgBYD2ArgDb4DkCoJFAxrZLADmafAFgAUMnSgAQvXoBrUAF5QAbwmhQ0fAC4aCAE5xBmxNATM0%20jEZNmAbtAzQSV-SXlWBZyIwQMhjZ2QhIAvhISUhQAgv6BKupmOsHGoeJasJAAttYGaabiEeISIKAAkrC0aIZoCCKgAGaG9NmIqJhNLW3ZMLBRHbLyCgBi0GisWKoKaEj0jUOKA9JxAfSGYxP4U6AzcwurgZHiZdFN66DCsDVEJqBoAB7oPPX4TXV8oLUYKPSwGBRmq1QDEAArlZaxFDQABKmDkigAPGZQdAeDN8AjRuNJvcHvVYNtFtithgADQotEYw7rTa4x4Eok0jY4okAH1AjEJaEacAaqi5%20B5fPwFPEAD5EhoMlxhvpUejEViyaAFRisXTtpKAGRJGVaPxrIKqqkiZmarAMtCErDm1lYAD8JsVzJVarN8Vp9sl%20kFwuuYhlxWKpTAjQ%20tDxORQVlA805GEgwgkOCQsB4TS5L2gfyasAAFABKPVmHh-WzvBB8MHlRKIgCiTzQLxEABEiJBEgIkOL82YDdCYtm-qkTGKtFpPPgkPpu2ZC-Lus40Ii1AQO-pG89Xu3iKAwqAOWuai1jUZGBQwpLlJLpROvnVGIZ4NcAO6qpcA-P5770ZgONBixvPV7y0cMq1ofMAANIGhKCVSnJBC37UCADoAmtb9DEgV8gMlbDX1QgArDA-iLZD9TQjCC3zFBIEMAE9HUddiE3JsW3wXdOwPI97kMU99HPS88IfUj-zQWj6MYwsKNAidUJ4Ig%20G-E8RLvOSJzLf4-zQVDmHoQR81UlD7zCWSJzMswQxlMpvl%20f4KDOZxmJPdZBMMC8tB49RCFY5jPEUfQ1xSfI7gPcLS3LTg7PLChVBwmBOHA6twURGJoThDAsURNgdDYcVezYDBsgCNgVTUMzQHCY4apOMB6lsDBIWJAB5WBmCQRJ0theFhhyvLxWarEAHULFoZkuoy3qkVy9gVTYLJcny44yjoJhWC4CglnELSKwChQ2o6-QsUOzrVDXfagu0Ji2AARjK7BPWNP1eQDCKdqi2VFFGgJmWO4YfvGp6pS%20hQrpCu6HsNQIrsWvI2CgB42H3FHrNWhgWDebg%20NPIbhlO%20t%20IuVRusy7K2BQFoUFbehMFgBBG2cBBlskQYRrG5lCdPSaeqyvrZoeimqZpumGYeJmWd2zh9oJonjRO9qzv8uVmIh%206VWhtz1Dh-QEcgJHwpRiQpdBwGmAQTm5f%2076OeB87LvUNW2DCA8gA" rel="nofollow noreferrer">Sandbox.


问:
How to handle errors with boto3?
I am trying to figure how to do proper error handling with boto3.

I am trying to create an IAM user:

```<code>def create_user(username, iam_conn):
    try:
        user = iam_conn.create_user(UserName=username)
        return user
    except Exception as e:
        return e
</code>```

When the call to create_user succeeds, I get a neat object that contains the http status code of the API call and the data of the newly created user.

Example:

```<code>{'ResponseMetadata':
      {'HTTPStatusCode': 200,
       'RequestId': 'omitted'
      },
 u'User': {u'Arn': 'arn:aws:iam::omitted:user/omitted',
           u'CreateDate': datetime.datetime(2015, 10, 11, 17, 13, 5, 882000, tzinfo=tzutc()),
           u'Path': '/',
           u'UserId': 'omitted',
           u'UserName': 'omitted'
          }
}
</code>```

This works great. But when this fails (like if the user already exists), I just get an object of type botocore.exceptions.ClientError with only text to tell me what went wrong.

Example:
ClientError('An error occurred (EntityAlreadyExists) when calling the CreateUser operation: User with name omitted already exists.',)

This (AFAIK) makes error handling very hard because I can't just switch on the resulting http status code (409 for user already exists according to the AWS API docs for IAM). This makes me think that I must be doing something the wrong way. The optimal way would be for boto3 to never throw exceptions, but juts always return an object that reflects how the API call went.

Can anyone enlighten me on this issue or point me in the right direction?

答:
In case you have to deal with the arguably unfriendly logs client (CloudWatch Logs put-log-events), this is what I had to do to properly catch Boto3 client exceptions:

```<code>try:
    ### Boto3 client code here...

except boto_exceptions.ClientError as error:
    Log.warning("Catched client error code %s",
                error.response['Error']['Code'])

    if error.response['Error']['Code'] in ["DataAlreadyAcceptedException",
                                           "InvalidSequenceTokenException"]:
        Log.debug(
            "Fetching sequence_token from boto error response['Error']['Message'] %s",
            error.response["Error"]["Message"])
        # NOTE: apparently there's no sequenceToken attribute in the response so we have
        # to parse response["Error"]["Message"] string
        sequence_token = error.response["Error"]["Message"].split(":")[-1].strip(" ")
        Log.debug("Setting sequence_token to %s", sequence_token)
</code>```

This works both at first attempt (with empty LogStream) and subsequent ones.

Title: How to handle errors with boto3?

Body:
I am trying to figure how to do proper error handling with boto3.

I am trying to create an IAM user:

def create_user(username, iam_conn):
    try:
        user = iam_conn.create_user(UserName=username)
        return user
    except Exception as e:
        return e

When the call to create_user succeeds, I get a neat object that contains the http status code of the API call and the data of the newly created user.

Example:

{'ResponseMetadata':
      {'HTTPStatusCode': 200,
       'RequestId': 'omitted'
      },
 u'User': {u'Arn': 'arn:aws:iam::omitted:user/omitted',
           u'CreateDate': datetime.datetime(2015, 10, 11, 17, 13, 5, 882000, tzinfo=tzutc()),
           u'Path': '/',
           u'UserId': 'omitted',
           u'UserName': 'omitted'
          }
}

This works great. But when this fails (like if the user already exists), I just get an object of type botocore.exceptions.ClientError with only text to tell me what went wrong.

Example:
ClientError('An error occurred (EntityAlreadyExists) when calling the CreateUser operation: User with name omitted already exists.',)

This (AFAIK) makes error handling very hard because I can't just switch on the resulting http status code (409 for user already exists according to the AWS API docs for IAM). This makes me think that I must be doing something the wrong way. The optimal way would be for boto3 to never throw exceptions, but juts always return an object that reflects how the API call went.

Can anyone enlighten me on this issue or point me in the right direction?

Body:
In case you have to deal with the arguably unfriendly logs client (CloudWatch Logs put-log-events), this is what I had to do to properly catch Boto3 client exceptions:

try:
    ### Boto3 client code here...

except boto_exceptions.ClientError as error:
    Log.warning("Catched client error code %s",
                error.response['Error']['Code'])

    if error.response['Error']['Code'] in ["DataAlreadyAcceptedException",
                                           "InvalidSequenceTokenException"]:
        Log.debug(
            "Fetching sequence_token from boto error response['Error']['Message'] %s",
            error.response["Error"]["Message"])
        # NOTE: apparently there's no sequenceToken attribute in the response so we have
        # to parse response["Error"]["Message"] string
        sequence_token = error.response["Error"]["Message"].split(":")[-1].strip(" ")
        Log.debug("Setting sequence_token to %s", sequence_token)

This works both at first attempt (with empty LogStream) and subsequent ones.


问:
minimum width for jq grid
is there something called min-width for jq grid?
i want my grid to have a minimum width and if the data exceeds the width should be auto adjusted.

thanks.

Devan

答:
The answer on your question depends on how the grid width can be changed in your grid. If you use gridResize then you can just set the corresponding parameters like

```<code>$("#list").jqGrid('gridResize', { minWidth: 450, minHeight: 100 });
</code>```

moreover you can consider to bind 'resize' event to make the changes of grid width if the browser window or the container, where the grid are placed, will be resized. See the answer for details.

Additionally you can consider to set "min-width", "min-height" CSS settings (see here for details) if the change of the grid size will be made not with respect of gridResize. The setting works starting with IE7.

ContentLicense: CC BY-SA 3.0

Title: minimum width for jq grid

Body:
The answer on your question depends on how the grid width can be changed in your grid. If you use gridResize then you can just set the corresponding parameters like

$("#list").jqGrid('gridResize', { minWidth: 450, minHeight: 100 });

moreover you can consider to bind 'resize' event to make the changes of grid width if the browser window or the container, where the grid are placed, will be resized. See the answer for details.

Additionally you can consider to set "min-width", "min-height" CSS settings (see here for details) if the change of the grid size will be made not with respect of gridResize. The setting works starting with IE7.


问:
Why NumberUtils.isNumber() is not working properly?
when i check with condition 08 or 09 or 010  and above leading with 0  in org.apache.commons.lang3.math.NumberUtils.isNumber("08")

答:
Method isNumber is deprecated:

isNumber(String str) Deprecated.  This feature will be removed in Lang
  4.0, use isCreatable(String) instead

Use isCreatable for above purpose.

Your above requirement to check ocatl kind of values will be detected via isCreatable method:

```<code>org.apache.commons.lang3.math.NumberUtils.isCreatable("08") // this will return true.
</code>```

this method Checks whether the String a valid Java number.

Valid numbers include hexadecimal marked with the 0x or 0X qualifier,
  octal numbers, scientific notation and numbers marked with a type
  qualifier (e.g. 123L).

Non-hexadecimal strings beginning with a leading zero are treated as
  octal values. Thus the string 09 will return false, since 9 is not a
  valid octal value. However, numbers beginning with 0. are treated as
  decimal.

reference official docs

Body:
Method isNumber is deprecated:

isNumber(String str) Deprecated.  This feature will be removed in Lang
  4.0, use isCreatable(String) instead

Use isCreatable for above purpose.

Your above requirement to check ocatl kind of values will be detected via isCreatable method:

org.apache.commons.lang3.math.NumberUtils.isCreatable("08") // this will return true.

this method Checks whether the String a valid Java number.

Valid numbers include hexadecimal marked with the 0x or 0X qualifier,
  octal numbers, scientific notation and numbers marked with a type
  qualifier (e.g. 123L).

Non-hexadecimal strings beginning with a leading zero are treated as
  octal values. Thus the string 09 will return false, since 9 is not a
  valid octal value. However, numbers beginning with 0. are treated as
  decimal.

reference official docs


问:
SwiftUI: Label randomly cropped
I have a litte SwiftUI example with a strange behaviour. It displays a Button and an optional Text. With a button tap the text is updated.

Strange effect: Sometimes the button label gets cropped.

Of course I could assign some frame size for the button as a work around. But is this really necessary?

```<code>struct ContentView: View {

    @State var tapCount = 0
    var body: some View {
        VStack{
            Button(action: {
                self.tapCount+=1
            }) {
                HStack{
                    Image(systemName: "hand.point.right").font(.system(size: 25, weight: .bold))
                    Text("Tap Me")
                    Image(systemName: "hand.point.left").font(.system(size: 25, weight: .bold))
                }
            }

            if self.tapCount > 0{
                Text("You tapped \(tapCount) times")
            }

        }
    }

}
</code>```

答:
No, frame is not needed, it is enough to point that text is fixed size, as below</p>

```<code>Text("Tap Me")
  .fixedSize()
</code>```

Title: SwiftUI: Label randomly cropped

Body:
I have a litte SwiftUI example with a strange behaviour. It displays a Button and an optional Text. With a button tap the text is updated.

Strange effect: Sometimes the button label gets cropped.

Of course I could assign some frame size for the button as a work around. But is this really necessary?

struct ContentView: View {

    @State var tapCount = 0
    var body: some View {
        VStack{
            Button(action: {
                self.tapCount+=1
            }) {
                HStack{
                    Image(systemName: "hand.point.right").font(.system(size: 25, weight: .bold))
                    Text("Tap Me")
                    Image(systemName: "hand.point.left").font(.system(size: 25, weight: .bold))
                }
            }

            if self.tapCount > 0{
                Text("You tapped \(tapCount) times")
            }

        }
    }

}

Body:
No, frame is not needed, it is enough to point that text is fixed size, as below

Text("Tap Me")
  .fixedSize()


问:
R error “Can't join on … because of incompatible types (list / list)”
I'm aware that questions with similar error codes have been asked, but our problem is not answered so far.

Problem: self join of dataframe on itself by a column that has lists as content.

DATA:

```<code>bsp_fn <- c("1","2","3","4","5")
bsp_liste1 <- list(list("a","b","c"),list("a","b"),list("a","c"),list("a","b","c"),list("b","c"))
bsp_df <- tibble(bsp_fn,bsp_liste1)
</code>```

PROBLEM:

```<code>bsp_df %>% inner_join(bsp_df,by="bsp_liste1")

Error: Can't join on'bsp_liste1' x 'bsp_liste1' because of incompatible types (list / list)
</code>```

QUESTION:

Can I join "by comparison" of the lists? Since the list "a","b","c" appears twice, I would expect a match here.

答:
NOT an Answer, rather a comment (can't comment because of insufficient reputation)

I think what @Sedir means is the following:

```<code>bsp_df %>%
     group_by(bsp_fn) %>%
     mutate(ID = paste0(unlist(bsp_liste1), collapse="")) %>%
     inner_join(bsp_df %>% group_by(bsp_fn) %>% mutate(ID = paste0(unlist(bsp_liste1), collapse="")),by="ID")
</code>```

which matches 1-1 and 1-4, 2-2, 3-3, 4-1, 4-4, 5-5. But still, it only works in the "right" order, i.e. "abc"; "cba" would not match.

Body:
I'm aware that questions with similar error codes have been asked, but our problem is not answered so far.

Problem: self join of dataframe on itself by a column that has lists as content.

DATA:

bsp_fn <- c("1","2","3","4","5")
bsp_liste1 <- list(list("a","b","c"),list("a","b"),list("a","c"),list("a","b","c"),list("b","c"))
bsp_df <- tibble(bsp_fn,bsp_liste1)

PROBLEM:

bsp_df %>% inner_join(bsp_df,by="bsp_liste1")

Error: Can't join on'bsp_liste1' x 'bsp_liste1' because of incompatible types (list / list)

QUESTION:

Can I join "by comparison" of the lists? Since the list "a","b","c" appears twice, I would expect a match here.

Body:
NOT an Answer, rather a comment (can't comment because of insufficient reputation)

I think what @Sedir means is the following:

bsp_df %>%
     group_by(bsp_fn) %>%
     mutate(ID = paste0(unlist(bsp_liste1), collapse="")) %>%
     inner_join(bsp_df %>% group_by(bsp_fn) %>% mutate(ID = paste0(unlist(bsp_liste1), collapse="")),by="ID")

which matches 1-1 and 1-4, 2-2, 3-3, 4-1, 4-4, 5-5. But still, it only works in the "right" order, i.e. "abc"; "cba" would not match.


问:
returning null value from populated selectlist with DB data
I'm implementing asp.net core MVC project. In my controller class called ApiApplicant, Create method, I have 3 selectlists that its items should be populated from a table called APIApplicantHistory. My models and create method and view are implemented like following:

```<code>    using System.Collections.Generic;

      namespace CSDDashboard.Models
     {
      public partial class Apiapplicant
      {
        public Apiapplicant()
        {
            ApiApplicantHistory = new HashSet<ApiApplicantHistory>();
        }

        public int Id { get; set; }
        public string ApiRequestDate { get; set; }
        public int? ApiRequestNo { get; set; }
        public int? Apiid { get; set; }
        public int? ApplicantId { get; set; }
        public int? GateId { get; set; }
        public string NocRequestDate { get; set; }
        public string NocRequestNo { get; set; }
        public string Url { get; set; }
        public string Description { get; set; }
        public bool? IsDeleted { get; set; }

        public virtual Api Api { get; set; }
        public virtual Applicant Applicant { get; set; }
        public virtual Gate Gate { get; set; }
        public virtual ICollection<ApiApplicantHistory> ApiApplicantHistory { get; set; }
    }
}

     using System;
     using System.Collections.Generic;

     namespace CSDDashboard.Models
     {
     public partial class ApiApplicantHistory
     {
        public int Id { get; set; }
        public int? ApiApplicantId { get; set; }
        public string Date { get; set; }
        public int? SentResponseType { get; set; }
        public int? UnconfirmedReason { get; set; }
        public int LastReqStatus { get; set; }
        public string Description { get; set; }

           public virtual Apiapplicant ApiApplicant { get; set; }
           public virtual EntityType LastReqStatusNavigation { get; set; }
           public virtual EntityType SentResponseTypeNavigation { get; set; }
           public virtual EntityType UnconfirmedReasonNavigation { get; set; }
        }
       }

       using System;
       using System.Collections.Generic;

       namespace CSDDashboard.Models
       {
        public partial class EntityType
       {
        public EntityType()
        {
            ApiApplicantHistoryLastReqStatusNavigation = new HashSet<ApiApplicantHistory>();
            ApiApplicantHistorySentResponseTypeNavigation = new HashSet<ApiApplicantHistory>();
            ApiApplicantHistoryUnconfirmedReasonNavigation = new HashSet<ApiApplicantHistory>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public string EntityKey { get; set; }

        public virtual ICollection<ApiApplicantHistory> ApiApplicantHistoryLastReqStatusNavigation { get; set; }
        public virtual ICollection<ApiApplicantHistory> ApiApplicantHistorySentResponseTypeNavigation { get; set; }
        public virtual ICollection<ApiApplicantHistory> ApiApplicantHistoryUnconfirmedReasonNavigation { get; set; }

    }
}

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Threading.Tasks;

      namespace CSDDashboard.Models
      {
      public class APIApplicantViewModel
      {
            public Apiapplicant apiApplicantvm { get; set; }

             public ApiApplicantHistory apiApplicantHistoryvm { get; set; }
       }
      }

       public class ApiapplicantsController : Controller
       {
        private readonly CSSDDashboardContext _context;

        public ApiapplicantsController(CSSDDashboardContext context)
        {
            _context = context;
        }

       public IActionResult Create()
        {

            ViewData["sentResponseType"] = new SelectList(_context.EntityType.Where(g => g.EntityKey == "sentResponseType").ToList(), "ID", "name");
            ViewData["unconfirmedReason"] = new SelectList(_context.EntityType.Where(g => g.EntityKey == "unconfirmedReason").ToList(), "ID", "name");
            ViewData["lastReqStatus"] = new SelectList(_context.EntityType.Where(g => g.EntityKey == "lastRequestStatus").ToList(), "ID", "name");

            return View();

        }
       }
</code>```

And a part of create view implementation:

```<code>     @model CSDDashboard.Models.APIApplicantViewModel

       @{
       ViewData["Title"] = "create";
       }
        <div class="row">
         <div class="col-md-4">
          <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
          <div class="form-group">
                <label asp-for="apiApplicantvm.GateId" class="control-label"></label>
                <select asp-for="apiApplicantvm.GateId" class="form-control" asp-items="ViewBag.GateId"></select>
            </div>
        <div class="form-group">
    <label asp-for="apiApplicantHistoryvm.SentResponseType" class="control-label"></label>
        <select asp-for="apiApplicantHistoryvm.SentResponseType" class="form-control" asp-items="ViewBag.sentResponseType"></select>
        </div>
       <div class="form-group">
        <label asp-for="apiApplicantHistoryvm.UnconfirmedReason" class="control-label"></label>
        <select asp-for="apiApplicantHistoryvm.UnconfirmedReason" class="form-control" asp-items="ViewBag.unconfirmedReason"></select>

       </div>
        <div class="form-group">
            <label asp-for="apiApplicantHistoryvm.LastReqStatus" class="control-label"></label>
            <select asp-for="apiApplicantHistoryvm.LastReqStatus" class="form-control" asp-items="ViewBag.lastReqStatus"></select>
        </div>
<div class="form-group">
                    <input type="submit" value="Create" class="btn btn-primary" />
                </div>
        </form>
       </div>
      </div>

       <div>
       <a asp-action="Index">Back</a>
       </div>

     @section Scripts {
      @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }
</code>```

In create method, all the viewData are filled with the correct related data but the problem is existing in Create view, after running the project an error like below is shown in Create page:

An unhandled exception occurred while processing the request.
NullReferenceException: Object reference not set to an instance of an object.

After debugging the code I understand that In create view, apiApplicantvm is not null but apiApplicantHistoryvm returns null and the above error is because of that. I appreciate if anyone could tells me how to fix the problem.

答:
I hope you would be using EF core as ORM because you are using Asp.net core.

To load related data in EF core.

It can be done in 2 ways  or Lazy loading

Eager loading

_context.EntityType.Where(g=>g.EntityKey=="sentResponseType")
                    .Include(x=>x.ApiApplicantHistoryLastReqStatusNavigation).ToList()

OR

Lazy loading
on your modal creating

protected override void
OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder .UseLazyLoadingProxies() .UseSqlServer(myConnectionString);

OR

on startup.cs of your core MVC project
Lazy loading example.

.AddDbContext<BloggingContext>(
    b => b.UseLazyLoadingProxies()
          .UseSqlServer(myConnectionString));

for more info learn.microsoft.com/en-us/ef/core/querying/related-data

https://learn.microsoft.com/en-us/ef/core/querying/related-data

Body:
I'm implementing asp.net core MVC project. In my controller class called ApiApplicant, Create method, I have 3 selectlists that its items should be populated from a table called APIApplicantHistory. My models and create method and view are implemented like following:

    using System.Collections.Generic;

      namespace CSDDashboard.Models
     {
      public partial class Apiapplicant
      {
        public Apiapplicant()
        {
            ApiApplicantHistory = new HashSet<ApiApplicantHistory>();
        }

        public int Id { get; set; }
        public string ApiRequestDate { get; set; }
        public int? ApiRequestNo { get; set; }
        public int? Apiid { get; set; }
        public int? ApplicantId { get; set; }
        public int? GateId { get; set; }
        public string NocRequestDate { get; set; }
        public string NocRequestNo { get; set; }
        public string Url { get; set; }
        public string Description { get; set; }
        public bool? IsDeleted { get; set; }

        public virtual Api Api { get; set; }
        public virtual Applicant Applicant { get; set; }
        public virtual Gate Gate { get; set; }
        public virtual ICollection<ApiApplicantHistory> ApiApplicantHistory { get; set; }
    }
}

     using System;
     using System.Collections.Generic;

     namespace CSDDashboard.Models
     {
     public partial class ApiApplicantHistory
     {
        public int Id { get; set; }
        public int? ApiApplicantId { get; set; }
        public string Date { get; set; }
        public int? SentResponseType { get; set; }
        public int? UnconfirmedReason { get; set; }
        public int LastReqStatus { get; set; }
        public string Description { get; set; }

           public virtual Apiapplicant ApiApplicant { get; set; }
           public virtual EntityType LastReqStatusNavigation { get; set; }
           public virtual EntityType SentResponseTypeNavigation { get; set; }
           public virtual EntityType UnconfirmedReasonNavigation { get; set; }
        }
       }

       using System;
       using System.Collections.Generic;

       namespace CSDDashboard.Models
       {
        public partial class EntityType
       {
        public EntityType()
        {
            ApiApplicantHistoryLastReqStatusNavigation = new HashSet<ApiApplicantHistory>();
            ApiApplicantHistorySentResponseTypeNavigation = new HashSet<ApiApplicantHistory>();
            ApiApplicantHistoryUnconfirmedReasonNavigation = new HashSet<ApiApplicantHistory>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public string EntityKey { get; set; }

        public virtual ICollection<ApiApplicantHistory> ApiApplicantHistoryLastReqStatusNavigation { get; set; }
        public virtual ICollection<ApiApplicantHistory> ApiApplicantHistorySentResponseTypeNavigation { get; set; }
        public virtual ICollection<ApiApplicantHistory> ApiApplicantHistoryUnconfirmedReasonNavigation { get; set; }

    }
}

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Threading.Tasks;

      namespace CSDDashboard.Models
      {
      public class APIApplicantViewModel
      {
            public Apiapplicant apiApplicantvm { get; set; }

             public ApiApplicantHistory apiApplicantHistoryvm { get; set; }
       }
      }

       public class ApiapplicantsController : Controller
       {
        private readonly CSSDDashboardContext _context;

        public ApiapplicantsController(CSSDDashboardContext context)
        {
            _context = context;
        }

       public IActionResult Create()
        {

            ViewData["sentResponseType"] = new SelectList(_context.EntityType.Where(g => g.EntityKey == "sentResponseType").ToList(), "ID", "name");
            ViewData["unconfirmedReason"] = new SelectList(_context.EntityType.Where(g => g.EntityKey == "unconfirmedReason").ToList(), "ID", "name");
            ViewData["lastReqStatus"] = new SelectList(_context.EntityType.Where(g => g.EntityKey == "lastRequestStatus").ToList(), "ID", "name");

            return View();

        }
       }

And a part of create view implementation:

     @model CSDDashboard.Models.APIApplicantViewModel

       @{
       ViewData["Title"] = "create";
       }

          <form asp-action="Create">

                <select asp-for="apiApplicantvm.GateId" class="form-control" asp-items="ViewBag.GateId"></select>

        <select asp-for="apiApplicantHistoryvm.SentResponseType" class="form-control" asp-items="ViewBag.sentResponseType"></select>

        <select asp-for="apiApplicantHistoryvm.UnconfirmedReason" class="form-control" asp-items="ViewBag.unconfirmedReason"></select>

            <select asp-for="apiApplicantHistoryvm.LastReqStatus" class="form-control" asp-items="ViewBag.lastReqStatus"></select>

                    <input type="submit" value="Create" class="btn btn-primary" />

        </form>

       Back

     @section Scripts {
      @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }

In create method, all the viewData are filled with the correct related data but the problem is existing in Create view, after running the project an error like below is shown in Create page:

An unhandled exception occurred while processing the request.
NullReferenceException: Object reference not set to an instance of an object.

After debugging the code I understand that In create view, apiApplicantvm is not null but apiApplicantHistoryvm returns null and the above error is because of that. I appreciate if anyone could tells me how to fix the problem.


问:
phpunit - return two objects to next test case
In some places, my phpunit methods have dependency on two classes so I have decided to write a dedicate method which will create an instance of these two classes(which are related to each other) and will pass them to all phpunit methods. I want to do something like below.

```<code>public function testGetInstance()
{
    $obj1 = new Class1();
    $obj2 = new Class2();
    return $obj1, $obj2;  //can i use list  ?
}

/**
*@depends testGetInstance()
*/
public function testBothFeatures(Class1 $obj1, Class2 $obj2) //how to pass 2 instances?
{
    //Do all operation related to $obj1 and $obj2
}
</code>```

How to achieve above case? Is there a better approach for same?

答:
This would make more sense, I guess?</p>

```<code>return array(
    'obj1' => new Class1( ),
    'obj2' => new Class2( )
);
</code>```

Body:
In some places, my phpunit methods have dependency on two classes so I have decided to write a dedicate method which will create an instance of these two classes(which are related to each other) and will pass them to all phpunit methods. I want to do something like below.

public function testGetInstance()
{
    $obj1 = new Class1();
    $obj2 = new Class2();
    return $obj1, $obj2;  //can i use list  ?
}

/**
*@depends testGetInstance()
*/
public function testBothFeatures(Class1 $obj1, Class2 $obj2) //how to pass 2 instances?
{
    //Do all operation related to $obj1 and $obj2
}

How to achieve above case? Is there a better approach for same?

Body:
This would make more sense, I guess?

return array(
    'obj1' => new Class1( ),
    'obj2' => new Class2( )
);


问:
JHipster *jhiHasAnyAuthority directive check for "no authority"
I need to make a condition that is seen when the user has no authority (it is not logged in), but I need to check for that authority first, so when the user is logged in, I will not see the content.

I'm using the 'jhiHasAnyAuthority' directive from the JHipster project.

```<code><div *jhiHasAnyAuthority="''">This should appear.... when the VISITOR is NOT logged </div>
</code>```

This works when there is an authority (in case you wonder):

```<code><div *jhiHasAnyAuthority="['ROLE_ADMIN', 'ROLE_USER']">This should appear.... when ADMIN or USER is logged </div>
<div *jhiHasAnyAuthority="'ROLE_ADMIN'">This should appear.... when ADMIN is logged </div>
</code>```

So I have tried different alternatives like:

```<code><div *jhiHasAnyAuthority="''">This should appear.... when Blank is NOT logged </div>
</code>```

But they do not work!

NOTE: I do not need to just put the text in a normal DIV so it will appear if the user is not logged, cause when it is logged it will also appear.

Thanks

答:
Create file has-not-authority.directive.ts in app\shared\auth:

```<code>import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { AccountService } from 'app/core/auth/account.service';

/**
 * @whatItDoes Conditionally includes an HTML element if current user has not any
 * of the authorities passed as the `expression`.
 *
 * @howToUse
 * ```
 *     <some-element *jhiHasNotAuthority="'ROLE_ADMIN'">...</some-element>
 *
 *     <some-element *jhiHasNotAuthority="['ROLE_ADMIN', 'ROLE_USER']">...</some-element>
 * ```
 */
@Directive({
  selector: '[jhiHasNotAuthority]'
})
export class HasNotAuthorityDirective {
  private authorities: string[];

  constructor(private accountService: AccountService, private templateRef: TemplateRef<any>, private viewContainerRef: ViewContainerRef) {}

  @Input()
  set jhiHasNotAuthority(value: string | string[]) {
    this.authorities = typeof value === 'string' ? [value] : value;
    this.updateView();
    // Get notified each time authentication state changes.
    this.accountService.getAuthenticationState().subscribe(() => this.updateView());
  }

  private updateView(): void {
    const hasAnyAuthority = this.accountService.hasAnyAuthority(this.authorities);
    this.viewContainerRef.clear();
    if (!hasAnyAuthority) {
      this.viewContainerRef.createEmbeddedView(this.templateRef);
    }
  }
}

</code>```

Update the shared.module.ts file in app\shared:

```<code>
import { NgModule } from '@angular/core';
import { YourAppSharedLibsModule } from './shared-libs.module';
import { FindLanguageFromKeyPipe } from './language/find-language-from-key.pipe';
import { JhiAlertComponent } from './alert/alert.component';
import { JhiAlertErrorComponent } from './alert/alert-error.component';
import { JhiLoginModalComponent } from './login/login.component';
import { HasAnyAuthorityDirective } from './auth/has-any-authority.directive';
import { HasNotAuthorityDirective } from './auth/has-not-authority.directive';

@NgModule({
  imports: [YourAppSharedLibsModule],
  declarations: [FindLanguageFromKeyPipe, JhiAlertComponent, JhiAlertErrorComponent, JhiLoginModalComponent, HasAnyAuthorityDirective, HasNotAuthorityDirective],
  entryComponents: [JhiLoginModalComponent],
  exports: [
    YourAppSharedLibsModule,
    FindLanguageFromKeyPipe,
    JhiAlertComponent,
    JhiAlertErrorComponent,
    JhiLoginModalComponent,
    HasAnyAuthorityDirective,
    HasNotAuthorityDirective
  ]
})
export class YourAppSharedModule {}
</code>```

This way, we effectively copy the contents of HasAnyAuthorityDirective, but flip the condition for the createEmbeddedView method call.

Body:
I need to make a condition that is seen when the user has no authority (it is not logged in), but I need to check for that authority first, so when the user is logged in, I will not see the content.

I'm using the 'jhiHasAnyAuthority' directive from the JHipster project.

This should appear.... when the VISITOR is NOT logged

This works when there is an authority (in case you wonder):

This should appear.... when ADMIN or USER is logged

This should appear.... when ADMIN is logged

So I have tried different alternatives like:

This should appear.... when Blank is NOT logged

But they do not work!

NOTE: I do not need to just put the text in a normal DIV so it will appear if the user is not logged, cause when it is logged it will also appear.

Thanks

Body:
Create file has-not-authority.directive.ts in app\shared\auth:

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { AccountService } from 'app/core/auth/account.service';

/**
 * @whatItDoes Conditionally includes an HTML element if current user has not any
 * of the authorities passed as the `expression`.
 *
 * @howToUse
 * ```
 *     <some-element *jhiHasNotAuthority="'ROLE_ADMIN'">...</some-element>
 *
 *     <some-element *jhiHasNotAuthority="['ROLE_ADMIN', 'ROLE_USER']">...</some-element>
 * ```
 */
@Directive({
  selector: '[jhiHasNotAuthority]'
})
export class HasNotAuthorityDirective {
  private authorities: string[];

  constructor(private accountService: AccountService, private templateRef: TemplateRef<any>, private viewContainerRef: ViewContainerRef) {}

  @Input()
  set jhiHasNotAuthority(value: string | string[]) {
    this.authorities = typeof value === 'string' ? [value] : value;
    this.updateView();
    // Get notified each time authentication state changes.
    this.accountService.getAuthenticationState().subscribe(() => this.updateView());
  }

  private updateView(): void {
    const hasAnyAuthority = this.accountService.hasAnyAuthority(this.authorities);
    this.viewContainerRef.clear();
    if (!hasAnyAuthority) {
      this.viewContainerRef.createEmbeddedView(this.templateRef);
    }
  }
}

Update the shared.module.ts file in app\shared:

import { NgModule } from '@angular/core';
import { YourAppSharedLibsModule } from './shared-libs.module';
import { FindLanguageFromKeyPipe } from './language/find-language-from-key.pipe';
import { JhiAlertComponent } from './alert/alert.component';
import { JhiAlertErrorComponent } from './alert/alert-error.component';
import { JhiLoginModalComponent } from './login/login.component';
import { HasAnyAuthorityDirective } from './auth/has-any-authority.directive';
import { HasNotAuthorityDirective } from './auth/has-not-authority.directive';

@NgModule({
  imports: [YourAppSharedLibsModule],
  declarations: [FindLanguageFromKeyPipe, JhiAlertComponent, JhiAlertErrorComponent, JhiLoginModalComponent, HasAnyAuthorityDirective, HasNotAuthorityDirective],
  entryComponents: [JhiLoginModalComponent],
  exports: [
    YourAppSharedLibsModule,
    FindLanguageFromKeyPipe,
    JhiAlertComponent,
    JhiAlertErrorComponent,
    JhiLoginModalComponent,
    HasAnyAuthorityDirective,
    HasNotAuthorityDirective
  ]
})
export class YourAppSharedModule {}

This way, we effectively copy the contents of HasAnyAuthorityDirective, but flip the condition for the createEmbeddedView method call.


问:
How to build & deploy tweaks to Cydia on Jailbroken iOS devices?
How to Create Cydia Apps  and  How to deploy the App to the Cydia App store?
I am familiar with Objective-C , will it be easy to develop cydia Apps?
How to install cydia Apps to devices?

答:
Theos was initially “iphone-framework”, a project created to simplify building code at the command line for iOS devices (primarily jailbroken devices). It later underwent significant changes and became Theos, a flexible Make-based build system primarily for jailbreak software development, but also with complete support for building for other supported platforms. Theos runs on, and can build projects for, macOS, iOS, Linux, and Windows (under Cygwin or Windows Subsystem for Linux).</p>

<p> URL for Installation </p>

Body:
Theos was initially “iphone-framework”, a project created to simplify building code at the command line for iOS devices (primarily jailbroken devices). It later underwent significant changes and became Theos, a flexible Make-based build system primarily for jailbreak software development, but also with complete support for building for other supported platforms. Theos runs on, and can build projects for, macOS, iOS, Linux, and Windows (under Cygwin or Windows Subsystem for Linux).

 URL for Installation


Title: Randomising array from a matrix (bidimensional array)

Body:
I Currently have the following matrix

const fileName = [
  ["a01", "b01", "c01", "d01", "e01", "f01", "g01", "h01", "i01", "j01", "k01", "l01"],
  ["a02", "b02", "c02", "d02", "e02", "f02", "g02", "h02", "i02", "j02", "k02", "l02"],
  ["a03", "b03", "c03", "d03", "e03", "f03", "g03", "h03", "i03", "j03", "k03", "l03"],
  ["a04", "b04", "c04", "d04", "e04", "f04", "g04", "h04", "i04", "j04", "k04", "l04"],
  ["a05", "b05", "c05", "d05", "e05", "f05", "g05", "h05", "i05", "j05", "k05", "l05"],
  ["a06", "b06", "c06", "d06", "e06", "f06", "g06", "h06", "i06", "j06", "k06", "l06"],
  ["a07", "b07", "c07", "d07", "e07", "f07", "g07", "h07", "i07", "j07", "k07", "l07"],
  ["a08", "b08", "c08", "d08", "e08", "f08", "g08", "h08", "i08", "j08", "k08", "l08"],
  ["a09", "b09", "c09", "d09", "e09", "f09", "g09", "h09", "i09", "j09", "k09", "l09"],
  ["a10", "b10", "c10", "d10", "e10", "f10", "g10", "h10", "i10", "j10", "k10", "l10"],
  ["a11", "b11", "c11", "d11", "e11", "f11", "g11", "h11", "i11", "j11", "k11", "l11"],
  ["a12", "b12", "c12", "d12", "e12", "f12", "g12", "h12", "i12", "j12", "k12", "l12"]
];

and I create a new array with filenames from it randomising 1 item of each subarray using this function:

function randomise() {
  let sequence = fileName.map(option => {
    const random = Math.floor(Math.random() * 11);
    return option[random];
  });
  let randomSelection = sequence.map(createURL);
  function createURL(fileName) {
    return `assets/music/${fileName}.mp3`;
  }
  console.log(randomSelection);
}

So I get an array such as:

["assets/music/f01.mp3", "assets/music/f02.mp3", "assets/music/b03.mp3", "assets/music/k04.mp3", "assets/music/b05.mp3", "assets/music/f06.mp3", "assets/music/i07.mp3", "assets/music/d08.mp3", "assets/music/d09.mp3", "assets/music/g10.mp3", "assets/music/a11.mp3", "assets/music/d12.mp3"]

But I want to rearrange my matrix in this way:

const fileName = [
  ["a01", "a02", "a03", "a04", "a05", "a06", "a07", "a08", "a09", "a10", "a11", "a12"],
  ["b01", "b02", "b03", "b04", "b05", "b06", "b07", "b08", "b09", "b10", "b11", "b12"],
  ["c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08", "c09", "c10", "c11", "c12"],
  ["d01", "d02", "d03", "d04", "d05", "d06", "d07", "d08", "d09", "d10", "d11", "d12"],
  ["e01", "e02", "e03", "e04", "e05", "e06", "e07", "e08", "e09", "e10", "e11", "e12"],
  ["f01", "f02", "f03", "f04", "f05", "f06", "f07", "f08", "f09", "f10", "f11", "f12"],
  ["g01", "g02", "g03", "g04", "g05", "g06", "g07", "g08", "g09", "g10", "g11", "g12"],
  ["h01", "h02", "h03", "h04", "h05", "h06", "h07", "h08", "h09", "h10", "h11", "h12"],
  ["i01", "i02", "i03", "i04", "i05", "i06", "i07", "i08", "i09", "i10", "i11", "i12"],
  ["j01", "j02", "j03", "j04", "j05", "j06", "j07", "j08", "j09", "j10", "j11", "j12"],
  ["k01", "k02", "k03", "k04", "k05", "k06", "k07", "k08", "k09", "k10", "k11", "k12"]
];

I need to randomly select 1 item from each of the indexes of those subarrays, so one random item ending with "1", another ending with "2", etc
Could you help me please? Thanks!

Body:
If I understood you correctly this will give you your desired output. Picking one letter for each number. Hope this helps for whatever you need it.

const fileName = [
  ["a01", "a02", "a03", "a04", "a05", "a06", "a07", "a08", "a09", "a10", "a11", "a12"],
  ["b01", "b02", "b03", "b04", "b05", "b06", "b07", "b08", "b09", "b10", "b11", "b12"],
  ["c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08", "c09", "c10", "c11", "c12"],
  ["d01", "d02", "d03", "d04", "d05", "d06", "d07", "d08", "d09", "d10", "d11", "d12"],
  ["e01", "e02", "e03", "e04", "e05", "e06", "e07", "e08", "e09", "e10", "e11", "e12"],
  ["f01", "f02", "f03", "f04", "f05", "f06", "f07", "f08", "f09", "f10", "f11", "f12"],
  ["g01", "g02", "g03", "g04", "g05", "g06", "g07", "g08", "g09", "g10", "g11", "g12"],
  ["h01", "h02", "h03", "h04", "h05", "h06", "h07", "h08", "h09", "h10", "h11", "h12"],
  ["i01", "i02", "i03", "i04", "i05", "i06", "i07", "i08", "i09", "i10", "i11", "i12"],
  ["j01", "j02", "j03", "j04", "j05", "j06", "j07", "j08", "j09", "j10", "j11", "j12"],
  ["k01", "k02", "k03", "k04", "k05", "k06", "k07", "k08", "k09", "k10", "k11", "k12"]
];

let pickedValues = [];

for (i = 0; i <= fileName.length; i++) {
  let index = Math.floor(Math.random() * ((fileName.length - 1) - 0 + 1));
  pickedValues[i] = (fileName[index][i]);
}
console.log(pickedValues);


问:
HttpContext.Current.Request.QueryString in unit test
```<code>    public static string Test()
    {
        var page = HttpContext.Current.Request.QueryString["page"];
        var pageSize = HttpContext.Current.Request.QueryString["pageSize"];
        var sortBy = HttpContext.Current.Request.QueryString["sortBy"];
        var sortOrder = HttpContext.Current.Request.QueryString["sortOrder"];
        var searchBy = HttpContext.Current.Request.QueryString["searchBy"];
        var searchKey = HttpContext.Current.Request.QueryString["searchKey"];
        if (!StandardRegister.AppServices.Security.Authenticator.VerifyAuthentication())
        {
            return null;
        }
  }
</code>```

unit test

```<code>     [Test]
    public async Task GetMaintainKitsTest()
    {
        HttpContext.Current.Request.QueryString.Add("page", "1");

         var maintainKits = Test();

    }
</code>```

error:Object reference not set to an instance of an object.

so to add HttpContext.Current.Request.QueryString in unit test

答:
You need to set a value to HttpContext.Current, otherwise, it will be null. Something like:

```<code>HttpContext.Current = new HttpContext(
    new HttpRequest(filename: "", url: "http://some.url", queryString: ""),
    new HttpResponse(new StringWriter())
);
</code>```

Body:
    public static string Test()
    {
        var page = HttpContext.Current.Request.QueryString["page"];
        var pageSize = HttpContext.Current.Request.QueryString["pageSize"];
        var sortBy = HttpContext.Current.Request.QueryString["sortBy"];
        var sortOrder = HttpContext.Current.Request.QueryString["sortOrder"];
        var searchBy = HttpContext.Current.Request.QueryString["searchBy"];
        var searchKey = HttpContext.Current.Request.QueryString["searchKey"];
        if (!StandardRegister.AppServices.Security.Authenticator.VerifyAuthentication())
        {
            return null;
        }
  }

unit test

     [Test]
    public async Task GetMaintainKitsTest()
    {
        HttpContext.Current.Request.QueryString.Add("page", "1");

         var maintainKits = Test();

    }

error:Object reference not set to an instance of an object.

so to add HttpContext.Current.Request.QueryString in unit test

Body:
You need to set a value to HttpContext.Current, otherwise, it will be null. Something like:

HttpContext.Current = new HttpContext(
    new HttpRequest(filename: "", url: "http://some.url", queryString: ""),
    new HttpResponse(new StringWriter())
);


问:
Add-Migration and Update-Database commands not found Visual Studio 2015
I've seen similar questions to this and I've tried every posted solution to all of them. I've been trying to fix this seemingly simple problem for the past two days and have gotten nowhere. When I try to run Add-Migration or Update-Database from the Package Manager Console, I get the following error:

Update-Database : The term 'Update-Database' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
  At line:1 char:1
  + Update-Database
  + ~~~~~~~~~~~~~~~
      + CategoryInfo          : ObjectNotFound: (Update-Database:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException

or

Add-Migration : The term 'Add-Migration' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
  At line:1 char:1
  + Add-Migration TestMigration
  + ~~~~~~~~~~~~~
      + CategoryInfo          : ObjectNotFound: (Add-Migration:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException

Here is my project.json:

```<code>{
  "dependencies": {
    "Braintree": "3.5.0",
    "CoreCompat.System.Drawing": "1.0.0-beta006",
    "Google.Apis.Auth": "1.20.0",
    "Google.Apis.Oauth2.v2": "1.20.0.672",
    "MailKit": "1.10.1",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"
    },
    "RazorLight": "1.0.0-rc1",
    "RazorLight.MVC": "1.0.3",
    "SendGrid.NetCore": "1.0.0-rtm-00002",
    "Tinify": "1.5.0"
  },
  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
  },
  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },
  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },
  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },
  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "Areas/**/Views",
      "appsettings.json",
      "web.config"
    ]
  },
  "scripts": {
  "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}
</code>```

I've tried running dotnet restore, restarting Visual Studio, running Visual Studio as administrator, restarting my computer, deleting the dependencies to EntityFramework and re-adding them.

I need to be able to run Add-Migration to update my SQL database, any help would be appreciated.

EDIT:

I ended up just creating a new project, installing all of the dependencies again and copying my code over. That did the trick, but an actual solution could still help, and help others with a similar problem.

答:
Just install Microsoft.EntityFrameworkCore.Tools package from nuget:

Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.1.1

You can also use this link to install the latest version:
Nuget package link

Copied from Nasir Jafarzadeh

Body:
I've seen similar questions to this and I've tried every posted solution to all of them. I've been trying to fix this seemingly simple problem for the past two days and have gotten nowhere. When I try to run Add-Migration or Update-Database from the Package Manager Console, I get the following error:

Update-Database : The term 'Update-Database' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
  At line:1 char:1
  + Update-Database
  + ~~~~~~~~~~~~~~~
      + CategoryInfo          : ObjectNotFound: (Update-Database:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException

or

Add-Migration : The term 'Add-Migration' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
  At line:1 char:1
  + Add-Migration TestMigration
  + ~~~~~~~~~~~~~
      + CategoryInfo          : ObjectNotFound: (Add-Migration:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException

Here is my project.json:

{
  "dependencies": {
    "Braintree": "3.5.0",
    "CoreCompat.System.Drawing": "1.0.0-beta006",
    "Google.Apis.Auth": "1.20.0",
    "Google.Apis.Oauth2.v2": "1.20.0.672",
    "MailKit": "1.10.1",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"
    },
    "RazorLight": "1.0.0-rc1",
    "RazorLight.MVC": "1.0.3",
    "SendGrid.NetCore": "1.0.0-rtm-00002",
    "Tinify": "1.5.0"
  },
  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
  },
  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },
  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },
  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },
  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "Areas/**/Views",
      "appsettings.json",
      "web.config"
    ]
  },
  "scripts": {
  "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

I've tried running dotnet restore, restarting Visual Studio, running Visual Studio as administrator, restarting my computer, deleting the dependencies to EntityFramework and re-adding them.

I need to be able to run Add-Migration to update my SQL database, any help would be appreciated.

EDIT:

I ended up just creating a new project, installing all of the dependencies again and copying my code over. That did the trick, but an actual solution could still help, and help others with a similar problem.


问:
Get state from terratest and run manually terraform destroy?
I make test with Terratest but I set wrong timeout and now test failed and resources are still there. I can remove them manually but better way will be using terraform destroy.

Is there way how get state or save them during running test via Terratest?

答:
Terratest essentially just runs terraform commands with the parameters you give it in your local folder structure.

So, you should just be able to change directories to the module run by terratest (i.e. the TerraformDir) and run typical terraform commands (e.g. terraform plan, terraform destroy).

If you're asking about having the terratest do the destroy automatically for you, you can do that by passing along the same options to terraform.Destroy as in this example. The defer is recommended so that destruction happens after you have validated your resources.


问:
How to Bind a texture to a 3D mesh in Kivy?
I'm trying to take Kivy's 3D Rotating Monkey Head example and apply a texture to it.

It seems that Kivy's graphics Context "BindTexture() method should do the trick, but it seems to have no effect.  I modified the example to include a call to "BindTexture()" at in the init() method.  I also changed the shader code include textures.

It seems that I've managed to pass texture coordinates to the shader just fine, because when I render using only the texture coordinates as color values (using comment line near end of shader code), I get a multi-colored object.  However, when I place those texture coordinates inside of a texture2D() call, the object is rendered with no texture at all.

According to the BindTexture docs:

The BindTexture Instruction will bind a texture and enable
  GL_TEXTURE_2D for subsequent drawing.

So it seems like that should be pretty straightforward, but I'm clearly missing something.

I'm new to Kivy and OpenGL.  One of the things I'm really struggling with is how to pass values to the input variables in a GL shader code.  For example, in my shader code, the variable "texture0" is used for the texture in question - however, I'm uncertain how that ever gets mapped to my texture.  Based on some of the examples I've seen, like Kivy's multitexture example, it seems that "BindTexture()" should take care of that, but I'm a little uncomfortable that it all seems like black magic to me right now.

main.py:

from kivy.clock import Clock
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.graphics import RenderContext, Color, Rectangle, BindTexture

class Renderer(Widget):
    def __init__(self, **kwargs):
        self.canvas = RenderContext(compute_normal_mat=True)
        # self.canvas.shader.source = resource_find('default.glsl')
        self.canvas.shader.source = resource_find('simple.glsl')
        self.scene = ObjFile(resource_find("monkey.obj"))
        BindTexture(source='mtexture2.png')

        super(Renderer, self).__init__(**kwargs)
        with self.canvas:
            self.cb = Callback(self.setup_gl_context)
            PushMatrix()
            self.setup_scene()
            PopMatrix()
            self.cb = Callback(self.reset_gl_context)
            BindTexture(source='mtexture2.png')

        self.canvas['texture0'] = 0

        Clock.schedule_interval(self.update_glsl, 1 / 60.)

    def setup_gl_context(self, *args):
        glEnable(GL_DEPTH_TEST)

    def reset_gl_context(self, *args):
        glDisable(GL_DEPTH_TEST)

    def update_glsl(self, delta):
        asp = self.width / float(self.height)
        proj = Matrix().view_clip(-asp, asp, -1, 1, 1, 100, 1)
        # Color(1,0,0)
        self.canvas['projection_mat'] = proj
        self.canvas['diffuse_light'] = (1.0, 0.0, 0.8)
        self.canvas['ambient_light'] = (0.1, 0.1, 0.1)
        self.rot.angle += delta * 100

    def setup_scene(self):
        Color(1, 1, 1)
        PushMatrix()
        Translate(0, -2.5, -8)
        self.rot = Rotate(1, 0, 1, 0)
        UpdateNormalMatrix()
        for m in list(self.scene.objects.values()):
            self.mesh = Mesh(
                vertices=m.vertices,
                indices=m.indices,
                fmt=m.vertex_format,
                mode='triangles',
            )
        PopMatrix()

class RendererApp(App):
    def build(self):
        return Renderer()

if __name__ == "__main__":
    RendererApp().run()
```

<p>Shader code "simple.glsl":</p>

<pre class="lang-c prettyprint-override"><code>/* simple.glsl

simple diffuse lighting based on laberts cosine law; see e.g.:
    http://en.wikipedia.org/wiki/Lambertian_reflectance
    http://en.wikipedia.org/wiki/Lambert%27s_cosine_law
*/
---VERTEX SHADER-------------------------------------------------------
#ifdef GL_ES
    precision highp float;
#endif

/* Vertex attributes/inputs, defined in MeshData Object */
attribute vec3  v_pos;
attribute vec3  v_normal;
attribute vec2  v_tc0;

/* Outputs to the fragment shader */
varying vec2 tex_coord0;
varying vec4 normal_vec;
varying vec4 vertex_pos;

uniform mat4 modelview_mat;
uniform mat4 projection_mat;

void main (void) {
    //compute vertex position in eye_space and normalize normal vector
    vec4 pos = modelview_mat * vec4(v_pos,1.0);
    vertex_pos = pos;
    normal_vec = vec4(v_normal,0.0);
    gl_Position = projection_mat * pos;

    tex_coord0 = v_tc0;
}

---FRAGMENT SHADER-----------------------------------------------------
#ifdef GL_ES
    precision highp float;
#endif

/* Outputs from Vertex Shader */
varying vec4 normal_vec;
varying vec4 vertex_pos;
varying vec2 tex_coord0;

uniform sampler2D texture0;

uniform mat4 normal_mat;

void main (void){
    //correct normal, and compute light vector (assume light at the eye)
    vec4 v_normal = normalize( normal_mat * normal_vec ) ;
    vec4 v_light = normalize( vec4(0,0,0,1) - vertex_pos );
    //reflectance based on lamberts law of cosine
    float theta = clamp(dot(v_normal, v_light), 0.0, 1.0);
    //gl_FragColor = vec4(theta, theta, theta, 1.0)*vec4(tex_coord0, 1, 1);
    gl_FragColor = vec4(theta, theta, theta, 1.0)*texture2D(texture0, tex_coord0);
}
</code>```

答:
The binding point between a texture object and the texture sampler uniform is the texture unit. The texture object is bound to a texture unit and the index of the texture unit is set to the texture sampler uniform. I have no idea how that works using kivy. The initial value of the sampler is 0. If the texture is bound to texture unit 0, it should work. The texture is bound to the texture unit by BindTexture(source='mtexture2.png') and the texture unit is assigned to the sampler  uniform by self.canvas['texture0'] = 0.

There seems to be an issue when you use texture unit 0. Use texture unit 1 instead.

Bind the texture in setup_scene and set the value to the sampler uniform in update_glsl:

class Renderer(Widget):
    # [...]

    def update_glsl(self, delta):
        asp = self.width / float(self.height)
        proj = Matrix().view_clip(-asp, asp, -1, 1, 1, 100, 1)
        self.canvas['texture0'] = 1 # <------------------------------
        self.canvas['projection_mat'] = proj
        self.canvas['diffuse_light'] = (1.0, 0.0, 0.8)
        self.canvas['ambient_light'] = (0.1, 0.1, 0.1)
        self.rot.angle += delta * 100

    def setup_scene(self):
        BindTexture(source='mtexture2.png', index=1) # <-------------
        Color(1, 1, 1)
        PushMatrix()
        Translate(0, -2.5, -8)
        self.rot = Rotate(1, 0, 1, 0)
        UpdateNormalMatrix()
        for m in list(self.scene.objects.values()):
            self.mesh = Mesh(
                vertices=m.vertices,
                indices=m.indices,
                fmt=m.vertex_format,
                mode='triangles',
            )
        PopMatrix()
```

<p>A further issue ism that "monkey.obj" does not have texture coordinates (<code>vt</code> entries). So the texture coordinates attribute is (0, 0) by default for all vertices.<br>
Emulate the texture coordinates by the normal vector in the vertex shader. e.g:</p>

<pre class="lang-c prettyprint-override"><code>void main (void) {
    // [...]

    tex_coord0 = v_normal.xz * 0.5 + 0.5;
}
</code>```

Body:
I'm trying to take Kivy's 3D Rotating Monkey Head example and apply a texture to it.

It seems that Kivy's graphics Context "BindTexture() method should do the trick, but it seems to have no effect.  I modified the example to include a call to "BindTexture()" at in the init() method.  I also changed the shader code include textures.

It seems that I've managed to pass texture coordinates to the shader just fine, because when I render using only the texture coordinates as color values (using comment line near end of shader code), I get a multi-colored object.  However, when I place those texture coordinates inside of a texture2D() call, the object is rendered with no texture at all.

According to the BindTexture docs:

The BindTexture Instruction will bind a texture and enable
  GL_TEXTURE_2D for subsequent drawing.

So it seems like that should be pretty straightforward, but I'm clearly missing something.

I'm new to Kivy and OpenGL.  One of the things I'm really struggling with is how to pass values to the input variables in a GL shader code.  For example, in my shader code, the variable "texture0" is used for the texture in question - however, I'm uncertain how that ever gets mapped to my texture.  Based on some of the examples I've seen, like Kivy's multitexture example, it seems that "BindTexture()" should take care of that, but I'm a little uncomfortable that it all seems like black magic to me right now.

main.py:

from kivy.clock import Clock
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.graphics import RenderContext, Color, Rectangle, BindTexture

class Renderer(Widget):
    def __init__(self, **kwargs):
        self.canvas = RenderContext(compute_normal_mat=True)
        # self.canvas.shader.source = resource_find('default.glsl')
        self.canvas.shader.source = resource_find('simple.glsl')
        self.scene = ObjFile(resource_find("monkey.obj"))
        BindTexture(source='mtexture2.png')

        super(Renderer, self).__init__(**kwargs)
        with self.canvas:
            self.cb = Callback(self.setup_gl_context)
            PushMatrix()
            self.setup_scene()
            PopMatrix()
            self.cb = Callback(self.reset_gl_context)
            BindTexture(source='mtexture2.png')

        self.canvas['texture0'] = 0

        Clock.schedule_interval(self.update_glsl, 1 / 60.)

    def setup_gl_context(self, *args):
        glEnable(GL_DEPTH_TEST)

    def reset_gl_context(self, *args):
        glDisable(GL_DEPTH_TEST)

    def update_glsl(self, delta):
        asp = self.width / float(self.height)
        proj = Matrix().view_clip(-asp, asp, -1, 1, 1, 100, 1)
        # Color(1,0,0)
        self.canvas['projection_mat'] = proj
        self.canvas['diffuse_light'] = (1.0, 0.0, 0.8)
        self.canvas['ambient_light'] = (0.1, 0.1, 0.1)
        self.rot.angle += delta * 100

    def setup_scene(self):
        Color(1, 1, 1)
        PushMatrix()
        Translate(0, -2.5, -8)
        self.rot = Rotate(1, 0, 1, 0)
        UpdateNormalMatrix()
        for m in list(self.scene.objects.values()):
            self.mesh = Mesh(
                vertices=m.vertices,
                indices=m.indices,
                fmt=m.vertex_format,
                mode='triangles',
            )
        PopMatrix()

class RendererApp(App):
    def build(self):
        return Renderer()

if __name__ == "__main__":
    RendererApp().run()

Shader code "simple.glsl":

/* simple.glsl

simple diffuse lighting based on laberts cosine law; see e.g.:
    http://en.wikipedia.org/wiki/Lambertian_reflectance
    http://en.wikipedia.org/wiki/Lambert%27s_cosine_law
*/
---VERTEX SHADER-------------------------------------------------------
#ifdef GL_ES
    precision highp float;
#endif

/* Vertex attributes/inputs, defined in MeshData Object */
attribute vec3  v_pos;
attribute vec3  v_normal;
attribute vec2  v_tc0;

/* Outputs to the fragment shader */
varying vec2 tex_coord0;
varying vec4 normal_vec;
varying vec4 vertex_pos;

uniform mat4 modelview_mat;
uniform mat4 projection_mat;

void main (void) {
    //compute vertex position in eye_space and normalize normal vector
    vec4 pos = modelview_mat * vec4(v_pos,1.0);
    vertex_pos = pos;
    normal_vec = vec4(v_normal,0.0);
    gl_Position = projection_mat * pos;

    tex_coord0 = v_tc0;
}

---FRAGMENT SHADER-----------------------------------------------------
#ifdef GL_ES
    precision highp float;
#endif

/* Outputs from Vertex Shader */
varying vec4 normal_vec;
varying vec4 vertex_pos;
varying vec2 tex_coord0;

uniform sampler2D texture0;

uniform mat4 normal_mat;

void main (void){
    //correct normal, and compute light vector (assume light at the eye)
    vec4 v_normal = normalize( normal_mat * normal_vec ) ;
    vec4 v_light = normalize( vec4(0,0,0,1) - vertex_pos );
    //reflectance based on lamberts law of cosine
    float theta = clamp(dot(v_normal, v_light), 0.0, 1.0);
    //gl_FragColor = vec4(theta, theta, theta, 1.0)*vec4(tex_coord0, 1, 1);
    gl_FragColor = vec4(theta, theta, theta, 1.0)*texture2D(texture0, tex_coord0);
}

Body:
The binding point between a texture object and the texture sampler uniform is the texture unit. The texture object is bound to a texture unit and the index of the texture unit is set to the texture sampler uniform. I have no idea how that works using kivy. The initial value of the sampler is 0. If the texture is bound to texture unit 0, it should work. The texture is bound to the texture unit by BindTexture(source='mtexture2.png') and the texture unit is assigned to the sampler  uniform by self.canvas['texture0'] = 0.

There seems to be an issue when you use texture unit 0. Use texture unit 1 instead.

Bind the texture in setup_scene and set the value to the sampler uniform in update_glsl:

class Renderer(Widget):
    # [...]

    def update_glsl(self, delta):
        asp = self.width / float(self.height)
        proj = Matrix().view_clip(-asp, asp, -1, 1, 1, 100, 1)
        self.canvas['texture0'] = 1 # <------------------------------
        self.canvas['projection_mat'] = proj
        self.canvas['diffuse_light'] = (1.0, 0.0, 0.8)
        self.canvas['ambient_light'] = (0.1, 0.1, 0.1)
        self.rot.angle += delta * 100

    def setup_scene(self):
        BindTexture(source='mtexture2.png', index=1) # <-------------
        Color(1, 1, 1)
        PushMatrix()
        Translate(0, -2.5, -8)
        self.rot = Rotate(1, 0, 1, 0)
        UpdateNormalMatrix()
        for m in list(self.scene.objects.values()):
            self.mesh = Mesh(
                vertices=m.vertices,
                indices=m.indices,
                fmt=m.vertex_format,
                mode='triangles',
            )
        PopMatrix()

A further issue ism that "monkey.obj" does not have texture coordinates (vt entries). So the texture coordinates attribute is (0, 0) by default for all vertices.

Emulate the texture coordinates by the normal vector in the vertex shader. e.g:

void main (void) {
    // [...]

    tex_coord0 = v_normal.xz * 0.5 + 0.5;
}