问:
How to deal with Mock and InjectMock
Let's say I have this class (omitted some parts for brevity):

package com.bitbank.config;

@Component
public class JwtTokenUtil implements Serializable {

    private static final long serialVersionUID = -2338626292552177485L;

    public static final long JWT_TOKEN_VALIDITY = 5L * 60 * 60;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private TimeSource timeSource;

    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        return doGenerateToken(claims, userDetails.getUsername());
    }

    // while creating the token -
    // 1. Define claims of the token, like Issuer, Expiration, Subject, and the ID
    // 2. Sign the JWT using the HS512 algorithm and secret key.
    // 3. According to JWS Compact
    // Serialization(https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#section-3.1)
    // compaction of the JWT to a URL-safe string
    private String doGenerateToken(Map<String, Object> claims, String subject) {

        return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(timeSource.getCurrentTimeMillis()))
                .setExpiration(new Date(timeSource.getCurrentTimeMillis() + JWT_TOKEN_VALIDITY * 1000))
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }

}
```
<p>To test the expiring of Token, I created another class:</p>
<pre class="lang-java prettyprint-override"><code>package com.bitbank.utils;

import org.springframework.stereotype.Component;

@Component
public class TimeSource {

    public Long getCurrentTimeMillis() {
        return System.currentTimeMillis();
    }

}
</code>```

So, I could inject fake / old millis and test that token is expired.

This is my class test:

@SpringBootTest
@TestPropertySource("classpath:application.properties")
class JwtTokenUtilTest {

    @Mock
    private TimeSource timeSource;

    @InjectMocks
    private JwtTokenUtil jwtTokenUtil;

    @Test
    void canCheckIsExpired() {

        when(timeSource.getCurrentTimeMillis()).thenReturn(100L);
        UserDetails userDetails = new User("username", "password", new ArrayList<>());
        String token = jwtTokenUtil.generateToken(userDetails);

        assertFalse(jwtTokenUtil.validateToken(token, userDetails));

    }

}
```
<p>But I have several issues with it.</p>
<p>With this mode (@Mock and @InjectMocks) I have error:</p>
<blockquote>
<p>base64-encoded secret key cannot be null or empty.`</p>
</blockquote>
<p>I know because class itself it is <code>Mock</code>ed, so cannot read the application.properties in test folder.</p>
<p>If I use <code>@Autowired</code>:</p>
<pre class="lang-java prettyprint-override"><code>@SpringBootTest
@TestPropertySource("classpath:application.properties")
class JwtTokenUtilTest {

    @Mock
    private TimeSource timeSource;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
</code>```

The test itself fails. Of course, it seems that it didn't inject the 100L millis.

If I swap class:

@Autowired
private TimeSource timeSource;

@InjectMocks
private JwtTokenUtil jwtTokenUtil;
```

I get:

Cannot invoke "com.bitbank.utils.TimeSource.getCurrentTimeMillis()"
because "this.timeSource" is null

答:
If you really want to use @SpringBootTest for this then you need to autowire the JwtTokenUtil and use @MockBean (**not** @Mock) for the TimeSource`.

@SpringBootTest
@TestPropertySource("classpath:application.properties")
class JwtTokenUtilTest {

    @MockBean
    private TimeSource timeSource;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
```

@MockBean is a Spring Boot annotation (leveraging Mockito) to indicate that for TimeSource a mock needs to be created and used as a bean for dependency injection. This is for using it with @SpringBootTest or one of the other test annotations from Spring Boot like @DataJpaTest, @WebMvcTest etc.

@Mock is the plain Mockito annotation that is for use when using a unit test with Mockito. This is used in conjunction with the Mockito runner or extension for JUnit of manual initialization of the mocks but not with the Spring Boot test annotations (as those are blissfully unaware of what to do with @Mock).

Title: How to deal with Mock and InjectMock

Body:
Let's say I have this class (omitted some parts for brevity):

package com.bitbank.config;

@Component
public class JwtTokenUtil implements Serializable {

    private static final long serialVersionUID = -2338626292552177485L;

    public static final long JWT_TOKEN_VALIDITY = 5L * 60 * 60;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private TimeSource timeSource;

    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        return doGenerateToken(claims, userDetails.getUsername());
    }

    // while creating the token -
    // 1. Define claims of the token, like Issuer, Expiration, Subject, and the ID
    // 2. Sign the JWT using the HS512 algorithm and secret key.
    // 3. According to JWS Compact
    // Serialization(https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#section-3.1)
    // compaction of the JWT to a URL-safe string
    private String doGenerateToken(Map<String, Object> claims, String subject) {

        return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(timeSource.getCurrentTimeMillis()))
                .setExpiration(new Date(timeSource.getCurrentTimeMillis() + JWT_TOKEN_VALIDITY * 1000))
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }

}

To test the expiring of Token, I created another class:

package com.bitbank.utils;

import org.springframework.stereotype.Component;

@Component
public class TimeSource {

    public Long getCurrentTimeMillis() {
        return System.currentTimeMillis();
    }

}

So, I could inject fake / old millis and test that token is expired.

This is my class test:

@SpringBootTest
@TestPropertySource("classpath:application.properties")
class JwtTokenUtilTest {

    @Mock
    private TimeSource timeSource;

    @InjectMocks
    private JwtTokenUtil jwtTokenUtil;

    @Test
    void canCheckIsExpired() {

        when(timeSource.getCurrentTimeMillis()).thenReturn(100L);
        UserDetails userDetails = new User("username", "password", new ArrayList<>());
        String token = jwtTokenUtil.generateToken(userDetails);

        assertFalse(jwtTokenUtil.validateToken(token, userDetails));

    }

}

But I have several issues with it.

With this mode (@Mock and @InjectMocks) I have error:

base64-encoded secret key cannot be null or empty.`

I know because class itself it is Mocked, so cannot read the application.properties in test folder.

If I use @Autowired:

@SpringBootTest
@TestPropertySource("classpath:application.properties")
class JwtTokenUtilTest {

    @Mock
    private TimeSource timeSource;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

The test itself fails. Of course, it seems that it didn't inject the 100L millis.

If I swap class:

@Autowired
private TimeSource timeSource;

@InjectMocks
private JwtTokenUtil jwtTokenUtil;

I get:

Cannot invoke "com.bitbank.utils.TimeSource.getCurrentTimeMillis()"
because "this.timeSource" is null

Body:
If you really want to use @SpringBootTest for this then you need to autowire the JwtTokenUtil and use @MockBean (**not** @Mock) for the TimeSource`.

@SpringBootTest
@TestPropertySource("classpath:application.properties")
class JwtTokenUtilTest {

    @MockBean
    private TimeSource timeSource;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

@MockBean is a Spring Boot annotation (leveraging Mockito) to indicate that for TimeSource a mock needs to be created and used as a bean for dependency injection. This is for using it with @SpringBootTest or one of the other test annotations from Spring Boot like @DataJpaTest, @WebMvcTest etc.

@Mock is the plain Mockito annotation that is for use when using a unit test with Mockito. This is used in conjunction with the Mockito runner or extension for JUnit of manual initialization of the mocks but not with the Spring Boot test annotations (as those are blissfully unaware of what to do with @Mock).


来源: stackexchange

答:
We can use DATEDIFF along with LAG:

WITH cte AS (
    SELECT tran_end_time,
           LAG(tran_end_time) OVER (ORDER BY tran_end_time) AS tran_end_time_lag
    FROM yourTable
)

SELECT AVG(DATEDIFF(minute, tran_end_time_lag, tran_end_time)) AS diff_avg
FROM cte
WHERE tran_end_time_lag IS NOT NULL;
```

Note that the WHERE clause in the final query above ensures that we do not include any diff involving the earliest record.

ContentLicense: CC BY-SA 4.0

Title: Calculate average of time difference between consecutive row

Body:
What would be the most efficient query to calculate the average of time difference between consecutive rows in a table? Note that the table has no primary key.

If the table looks like below:

|     tran_end_time     |
|-----------------------|
|2022-02-08 07:04:46.610|
|2022-02-08 07:09:47.403|
|2022-02-08 07:14:48.100|
|2022-02-08 07:20:03.973|

Then I need the answer to be:

avg('2022-02-08 07:20:03.973' - '2022-02-08 07:14:48.100',
    '2022-02-08 07:14:48.100' - '2022-02-08 07:09:47.403',
    '2022-02-08 07:09:47.403' - '2022-02-08 07:04:46.610')

Body:
We can use DATEDIFF along with LAG:

WITH cte AS (
    SELECT tran_end_time,
           LAG(tran_end_time) OVER (ORDER BY tran_end_time) AS tran_end_time_lag
    FROM yourTable
)

SELECT AVG(DATEDIFF(minute, tran_end_time_lag, tran_end_time)) AS diff_avg
FROM cte
WHERE tran_end_time_lag IS NOT NULL;

Note that the WHERE clause in the final query above ensures that we do not include any diff involving the earliest record.


问:
Building Darknet but getting this errors
```<code>-- Looking for a CUDA compiler
-- Looking for a CUDA compiler - NOTFOUND
-- CUDA_PATH: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6
-- CUDACXX: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6/bin/nvcc
CMake Error at CMakeLists.txt:153 (message):
  CUDA not found, please build explicitly with -DENABLE_CUDA=OFF if you do
  not want CUDA.
</code>```

I have Cuda 11.6 and cudnn 8.3

答: Use CUDA version 11.1. Worked for me.</p>

Body:
-- Looking for a CUDA compiler
-- Looking for a CUDA compiler - NOTFOUND
-- CUDA_PATH: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6
-- CUDACXX: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6/bin/nvcc
CMake Error at CMakeLists.txt:153 (message):
  CUDA not found, please build explicitly with -DENABLE_CUDA=OFF if you do
  not want CUDA.

I have Cuda 11.6 and cudnn 8.3

Body: Use CUDA version 11.1. Worked for me.


问:
Flex DateChooser events for individual days?
I'm using a DateChooser, and want to show different information in a tooltip as the user rolls over each day. Is there an event that fires as I'm rolling around the calendar that will tell me what day I'm currently over?</p>

答:
It's a little complicated. You're going to need to use the mx_internal namespace. The grid portion of the DateChooser component is a CalenderLayout component in DateChooser.as.

```<code>mx_internal var dataGrid:CalenderLayout;
</code>```

CalenderLayout.as has the mouseMoveHandler. In the handler we have:

```<code>var selCell:IUITextField = dayBlocksArray[colIndex][rowIndex];
</code>```

that gives you the necessary info about which day the mouse is over. You will need to extend DateChooser to use an extended CalendarLayout that exposes the selectedCell.

perhaps:

```<code>private function mouseMoveHandler(event:MouseEvent):void
{
    ...
    dispatchEvent(new DayHoverEvent(selCell.text));
}
</code>```

I guess what I'm trying to say is it's kinda tricky, and it uses mx_internal, which means the variables are subject to change in later versions of Flex.

OwnerDisplayName: sprugman

ContentLicense: CC BY-SA 2.5

Body:
It's a little complicated. You're going to need to use the mx_internal namespace. The grid portion of the DateChooser component is a CalenderLayout component in DateChooser.as.

mx_internal var dataGrid:CalenderLayout;

CalenderLayout.as has the mouseMoveHandler. In the handler we have:

var selCell:IUITextField = dayBlocksArray[colIndex][rowIndex];

that gives you the necessary info about which day the mouse is over. You will need to extend DateChooser to use an extended CalendarLayout that exposes the selectedCell.

perhaps:

private function mouseMoveHandler(event:MouseEvent):void
{
    ...
    dispatchEvent(new DayHoverEvent(selCell.text));
}

I guess what I'm trying to say is it's kinda tricky, and it uses mx_internal, which means the variables are subject to change in later versions of Flex.

OwnerDisplayName: CookieOfFortune


问:
What modules/tools are available for drawing a graph from text/csv file in Perl or PHP?
I have to draw a graph in Perl or PHP. Can you show me any sample code to read from the text or CSV file and plot a graph or chart of pie?

Data would be like this sample in a CSV or text file:

```<code>01/01/2010  0
01/02/2010  1
01/03/2010  2
01/04/2010  3
</code>```

Another set of data in text file for chart

```<code>Column A 20
Column B 10
Column C 02
</code>```

I want to display the value for each column in my pie chart.

答:
There is a perl charting module GD::Graph you can take a look at.
http://search.cpan.org/dist/GDGraph/Graph.pm

It is pretty old and has limitations, but it can produce simple charts.

ContentLicense: CC BY-SA 3.0

Body:
I have to draw a graph in Perl or PHP. Can you show me any sample code to read from the text or CSV file and plot a graph or chart of pie?

Data would be like this sample in a CSV or text file:

01/01/2010  0
01/02/2010  1
01/03/2010  2
01/04/2010  3

Another set of data in text file for chart

Column A 20
Column B 10
Column C 02

I want to display the value for each column in my pie chart.


问:
How to implement a try catch wrapper in C++?
I'm trying to implement a try catch wrapper with syntax like this:

```<code>TRY_CATCH{
    task1();
    task2();
    task3();
}
</code>```

If either task fails, the exception will be caught and handled.

I was doing something like this:

```<code>#define TRY_CATCH_EXPR(...)                                       \
{                                                                 \
    try                                                           \
    {                                                             \
        __VA_ARGS__                                               \
    }                                                             \
    catch (std::exception & err)                                  \
    {                                                             \
        // do sth.                                                \
    }                                                             \
    catch (...)                                                   \
    {                                                             \
        // do sth.                                                \
    }                                                             \
}
</code>```

And I call it like this:

```<code>TRY_CATCH_EXPR(
    printf("hello world!\n");
);
</code>```

It works fine for me for now.

So my question is:

What's the potential danger with this macro

Is it possible to make the "{}" syntax work, rather then wrapping the expression with "();"?

Edit:
I only use the wrapper when the exception is predictable and can be handled smoothly with the "do sth.", for the first question, I am more concerned about the VA_ARGS part, is there any case where it won't work as intended?

Also, my primary goal is to implement a macro with syntax like this:

```<code>MACRO{
    // multiple lines of expressions
}
</code>```

Is it possible?

答:
Here's one way to do it with no macros, and therefore no potential complications with __VA_ARGS__ and other preprocessor-related dangers.

```<code>// in some header
template <typename F> void try_catch(F&& f) {
    try { f(); }
    catch (std::exception & err) { /* ... */ }
    catch (...) { /* ... */ }
}

try_catch ([&](){
   task1();
   task2();
   task3();
});
</code>```

I don't think there is a way to do it with your desired syntax, macros or no macros.

Body:
I'm trying to implement a try catch wrapper with syntax like this:

TRY_CATCH{
    task1();
    task2();
    task3();
}

If either task fails, the exception will be caught and handled.

I was doing something like this:

#define TRY_CATCH_EXPR(...)                                       \
{                                                                 \
    try                                                           \
    {                                                             \
        __VA_ARGS__                                               \
    }                                                             \
    catch (std::exception & err)                                  \
    {                                                             \
        // do sth.                                                \
    }                                                             \
    catch (...)                                                   \
    {                                                             \
        // do sth.                                                \
    }                                                             \
}

And I call it like this:

TRY_CATCH_EXPR(
    printf("hello world!\n");
);

It works fine for me for now.

So my question is:

What's the potential danger with this macro

Is it possible to make the "{}" syntax work, rather then wrapping the expression with "();"?

Edit:
I only use the wrapper when the exception is predictable and can be handled smoothly with the "do sth.", for the first question, I am more concerned about the VA_ARGS part, is there any case where it won't work as intended?

Also, my primary goal is to implement a macro with syntax like this:

MACRO{
    // multiple lines of expressions
}

Is it possible?

Body:
Here's one way to do it with no macros, and therefore no potential complications with __VA_ARGS__ and other preprocessor-related dangers.

// in some header
template <typename F> void try_catch(F&& f) {
    try { f(); }
    catch (std::exception & err) { /* ... */ }
    catch (...) { /* ... */ }
}

try_catch ([&](){
   task1();
   task2();
   task3();
});

I don't think there is a way to do it with your desired syntax, macros or no macros.


问:
Opencart You don't have permission to access /admin/index.php on this server
I have a problem when I click on "save" button in opencart "admin->system->setting", the error is:

```<code>Forbidden, You don't have permission to access /admin/index.php on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
</code>```

What can I do to correct this error?

答:
Go to your project directory and right click admin folder and then click on Get Info:

After that double click on Lock icon and change the access to Read & Write

And then save the changes

Now refresh the url in browser your issue will be solved

** -> It's mac setup may be window will be same**

Body:
I have a problem when I click on "save" button in opencart "admin->system->setting", the error is:

Forbidden, You don't have permission to access /admin/index.php on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

What can I do to correct this error?


问:
Is there an easier way to grab a single value from within a Pandas DataFrame with multiindexed columns?
I have a Pandas DataFrame of ML experiment results (from MLFlow). I am trying to access the run_id of a single element in the 0th row and under the "tags" -> "run_id" multi-index in the columns.

The DataFrame is called experiment_results_df. I can access the element with the following command:

```<code>experiment_results_df.loc[0,(slice(None),'run_id')].values[0]
</code>```

I thought I should be able to grab the value itself with a statement like the following:

```<code>experiment_results_df.at[0,('tags','run_id')]
# or...
experiment_results_df.loc[0,('tags','run_id')]
</code>```

But either of those just results in the following rather confusing error (as I'm not setting anything):

```<code>ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.
</code>```

It's working now, but I'd prefer to use a simpler syntax. And more than that, I want to understand why the other approach isn't working, and if I can modify it. I find multiindexes very frustrating to work with in Pandas compared to regular indexes, but the additional formatting is nice when I print the DF to the console, or display it in a CSV viewer as I currently have 41 columns (and growing).

Body:
I have a Pandas DataFrame of ML experiment results (from MLFlow). I am trying to access the run_id of a single element in the 0th row and under the "tags" -> "run_id" multi-index in the columns.

The DataFrame is called experiment_results_df. I can access the element with the following command:

experiment_results_df.loc[0,(slice(None),'run_id')].values[0]

I thought I should be able to grab the value itself with a statement like the following:

experiment_results_df.at[0,('tags','run_id')]
# or...
experiment_results_df.loc[0,('tags','run_id')]

But either of those just results in the following rather confusing error (as I'm not setting anything):

ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.

It's working now, but I'd prefer to use a simpler syntax. And more than that, I want to understand why the other approach isn't working, and if I can modify it. I find multiindexes very frustrating to work with in Pandas compared to regular indexes, but the additional formatting is nice when I print the DF to the console, or display it in a CSV viewer as I currently have 41 columns (and growing).

Body:
I don't understand what is the problem:

df = pd.DataFrame({('T', 'A'): {0: 1, 1: 4},
                   ('T', 'B'): {0: 2, 1: 5},
                   ('T', 'C'): {0: 3, 1: 6}})
print(df)

# Output
   T
   A  B  C
0  1  2  3
1  4  5  6

How to extract 1:

>>> df.loc[0, ('T', 'A')]
1

>>> df.at[0, ('T', 'A')]
1

>>> df.loc[0, (slice(None), 'A')][0]
1


问:
How to mock an async repository with Entity Framework Core
I'm trying to create a unit test for a class that calls into an async repository.  I'm using ASP.NET Core and Entity Framework Core.  My generic repository looks like this.

```<code>public class EntityRepository<TEntity> : IEntityRepository<TEntity> where TEntity : class
{
    private readonly SaasDispatcherDbContext _dbContext;
    private readonly DbSet<TEntity> _dbSet;

    public EntityRepository(SaasDispatcherDbContext dbContext)
    {
        _dbContext = dbContext;
        _dbSet = dbContext.Set<TEntity>();
    }

    public virtual IQueryable<TEntity> GetAll()
    {
        return _dbSet;
    }

    public virtual async Task<TEntity> FindByIdAsync(int id)
    {
        return await _dbSet.FindAsync(id);
    }

    public virtual IQueryable<TEntity> FindBy(Expression<Func<TEntity, bool>> predicate)
    {
        return _dbSet.Where(predicate);
    }

    public virtual void Add(TEntity entity)
    {
        _dbSet.Add(entity);
    }
    public virtual void Delete(TEntity entity)
    {
        _dbSet.Remove(entity);
    }

    public virtual void Update(TEntity entity)
    {
        _dbContext.Entry(entity).State = EntityState.Modified;
    }

    public virtual async Task SaveChangesAsync()
    {
        await _dbContext.SaveChangesAsync();
    }
}
</code>```

Then I have a service class that calls FindBy and FirstOrDefaultAsync on an instance of the repository:

```<code>    public async Task<Uri> GetCompanyProductURLAsync(Guid externalCompanyID, string productCode, Guid loginToken)
    {
        CompanyProductUrl companyProductUrl = await _Repository.FindBy(u => u.Company.ExternalCompanyID == externalCompanyID && u.Product.Code == productCode.Trim()).FirstOrDefaultAsync();

        if (companyProductUrl == null)
        {
            return null;
        }

        var builder = new UriBuilder(companyProductUrl.Url);
        builder.Query = $"-s{loginToken.ToString()}";

        return builder.Uri;
    }
</code>```

I'm trying to mock the repository call in my test below:

```<code>    [Fact]
    public async Task GetCompanyProductURLAsync_ReturnsNullForInvalidCompanyProduct()
    {
        var companyProducts = Enumerable.Empty<CompanyProductUrl>().AsQueryable();

        var mockRepository = new Mock<IEntityRepository<CompanyProductUrl>>();
        mockRepository.Setup(r => r.FindBy(It.IsAny<Expression<Func<CompanyProductUrl, bool>>>())).Returns(companyProducts);

        var service = new CompanyProductService(mockRepository.Object);

        var result = await service.GetCompanyProductURLAsync(Guid.NewGuid(), "wot", Guid.NewGuid());

        Assert.Null(result);
    }
</code>```

However, when the test executes the call to the repository, I get the following error:

```<code>The provider for the source IQueryable doesn't implement IAsyncQueryProvider. Only providers that implement IEntityQueryProvider can be used for Entity Framework asynchronous operations.
</code>```

How can I properly mock the repository to get this to work?

答:
For everyone who stuck at mocking DbContext with async queries, IAsyncQueryProvider and other things. Heres example usage of copy-paste types for netcore3.1 and higher. Based on generic DbContextCreation and generic DbSet seed.

    public class MyDbContext : DbContext
    {
        public DbSet<MyEntity> MyEntities { get; set; }
    }

    public class MyEntity
    {
        public Guid Id { get; set; }
    }

    internal class MockDbContextAsynced<TDbContext>
    {
        private readonly TDbContext _mock;
        public TDbContext Object => _mock;

        public MockDbContextAsynced()
        {
            _mock = Activator.CreateInstance<TDbContext>();
        }
          // suppressed. see full code in source below
    }

    [Fact]
    public void Test()
    {
        var testData = new List<MyEntity>
        {
            new MyEntity() { Id = Guid.NewGuid() },
            new MyEntity() { Id = Guid.NewGuid() },
            new MyEntity() { Id = Guid.NewGuid() },
        };

        var mockDbContext = new MockDbContextAsynced<MyDbContext>();
        mockDbContext.AddDbSetData<MyEntity>(testData.AsQueryable());

        mockDbContext.MyEntities.ToArrayAsync();
        // or
        mockDbContext.MyEntities.SingleAsync();
        // or etc.

        // To inject MyDbContext as type parameter with mocked data
        var mockService = new SomeService(mockDbContext.Object);
    }

```

For full implemented types see this source: https://gist.github.com/Zefirrat/a04658c827ba3ebffe03fda48d53ea11

Body:
I'm trying to create a unit test for a class that calls into an async repository.  I'm using ASP.NET Core and Entity Framework Core.  My generic repository looks like this.

public class EntityRepository<TEntity> : IEntityRepository<TEntity> where TEntity : class
{
    private readonly SaasDispatcherDbContext _dbContext;
    private readonly DbSet<TEntity> _dbSet;

    public EntityRepository(SaasDispatcherDbContext dbContext)
    {
        _dbContext = dbContext;
        _dbSet = dbContext.Set<TEntity>();
    }

    public virtual IQueryable<TEntity> GetAll()
    {
        return _dbSet;
    }

    public virtual async Task<TEntity> FindByIdAsync(int id)
    {
        return await _dbSet.FindAsync(id);
    }

    public virtual IQueryable<TEntity> FindBy(Expression<Func<TEntity, bool>> predicate)
    {
        return _dbSet.Where(predicate);
    }

    public virtual void Add(TEntity entity)
    {
        _dbSet.Add(entity);
    }
    public virtual void Delete(TEntity entity)
    {
        _dbSet.Remove(entity);
    }

    public virtual void Update(TEntity entity)
    {
        _dbContext.Entry(entity).State = EntityState.Modified;
    }

    public virtual async Task SaveChangesAsync()
    {
        await _dbContext.SaveChangesAsync();
    }
}

Then I have a service class that calls FindBy and FirstOrDefaultAsync on an instance of the repository:

    public async Task<Uri> GetCompanyProductURLAsync(Guid externalCompanyID, string productCode, Guid loginToken)
    {
        CompanyProductUrl companyProductUrl = await _Repository.FindBy(u => u.Company.ExternalCompanyID == externalCompanyID && u.Product.Code == productCode.Trim()).FirstOrDefaultAsync();

        if (companyProductUrl == null)
        {
            return null;
        }

        var builder = new UriBuilder(companyProductUrl.Url);
        builder.Query = $"-s{loginToken.ToString()}";

        return builder.Uri;
    }

I'm trying to mock the repository call in my test below:

    [Fact]
    public async Task GetCompanyProductURLAsync_ReturnsNullForInvalidCompanyProduct()
    {
        var companyProducts = Enumerable.Empty<CompanyProductUrl>().AsQueryable();

        var mockRepository = new Mock<IEntityRepository<CompanyProductUrl>>();
        mockRepository.Setup(r => r.FindBy(It.IsAny<Expression<Func<CompanyProductUrl, bool>>>())).Returns(companyProducts);

        var service = new CompanyProductService(mockRepository.Object);

        var result = await service.GetCompanyProductURLAsync(Guid.NewGuid(), "wot", Guid.NewGuid());

        Assert.Null(result);
    }

However, when the test executes the call to the repository, I get the following error:

The provider for the source IQueryable doesn't implement IAsyncQueryProvider. Only providers that implement IEntityQueryProvider can be used for Entity Framework asynchronous operations.

How can I properly mock the repository to get this to work?

Body:
For everyone who stuck at mocking DbContext with async queries, IAsyncQueryProvider and other things. Heres example usage of copy-paste types for netcore3.1 and higher. Based on generic DbContextCreation and generic DbSet seed.

    public class MyDbContext : DbContext
    {
        public DbSet<MyEntity> MyEntities { get; set; }
    }

    public class MyEntity
    {
        public Guid Id { get; set; }
    }

    internal class MockDbContextAsynced<TDbContext>
    {
        private readonly TDbContext _mock;
        public TDbContext Object => _mock;

        public MockDbContextAsynced()
        {
            _mock = Activator.CreateInstance<TDbContext>();
        }
          // suppressed. see full code in source below
    }

    [Fact]
    public void Test()
    {
        var testData = new List<MyEntity>
        {
            new MyEntity() { Id = Guid.NewGuid() },
            new MyEntity() { Id = Guid.NewGuid() },
            new MyEntity() { Id = Guid.NewGuid() },
        };

        var mockDbContext = new MockDbContextAsynced<MyDbContext>();
        mockDbContext.AddDbSetData<MyEntity>(testData.AsQueryable());

        mockDbContext.MyEntities.ToArrayAsync();
        // or
        mockDbContext.MyEntities.SingleAsync();
        // or etc.

        // To inject MyDbContext as type parameter with mocked data
        var mockService = new SomeService(mockDbContext.Object);
    }

For full implemented types see this source: https://gist.github.com/Zefirrat/a04658c827ba3ebffe03fda48d53ea11


问:
Does Atom break ruby to_s override?
I want puts to return @value. The code is below:

```<code>class Tile
  def initialize(value, given=false)
    @value = value
    @given = given
  end

  def newValue(value)
    @value = value if @given == false
  end

  def to_s
    @value
  end

end

t = Tile.new(5)
t.newValue(6)
debugger
puts t
</code>```

This results in the printing of just the object id, no variables.

Why? And what is going wrong here? Is it an Atom thing?

答:
puts prints each argument by calling its to_s method. It also expects the to_s method to return a string. If to_s returns something else it ignores that value and prints the object's class and id instead.

In your example, @value is an integer. To fix your code:

```<code>def to_s
  @value.to_s
end
</code>```

Title: Does Atom break ruby to_s override?

Body:
I want puts to return @value. The code is below:

class Tile
  def initialize(value, given=false)
    @value = value
    @given = given
  end

  def newValue(value)
    @value = value if @given == false
  end

  def to_s
    @value
  end

end

t = Tile.new(5)
t.newValue(6)
debugger
puts t

This results in the printing of just the object id, no variables.

Why? And what is going wrong here? Is it an Atom thing?

Body:
puts prints each argument by calling its to_s method. It also expects the to_s method to return a string. If to_s returns something else it ignores that value and prints the object's class and id instead.

In your example, @value is an integer. To fix your code:

def to_s
  @value.to_s
end


问:
Unable to read internal storage textfile in Android 11 using Android Java
Hi Guys, i tried to access a textfile in the other application in my /Android/data/com.xxx.xxxxxx/files/ in internal storage using Android 11 but unfortunately in won`t. It works in Android 10 below. It has an error at BufferedReader. Here is the error "open failed: EACCES (Permission denied)". Any Answers please? Thanks in advance:)

Here is my gradle.

```<code>android {
compileSdkVersion 31
buildToolsVersion "30.0.3"

defaultConfig {
    applicationId "com.example.myapplication"
    minSdkVersion 15
    targetSdkVersion 30
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
</code>```

Here is my AndroidManifest.xml

```<code><uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>

    <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>

<application
    android:requestLegacyExternalStorage="true"
    android:allowBackup="false"
    android:icon="@drawable/ic_launcher_background"
    android:label="My Application"
    android:theme="@style/AppTheme">
</code>```

Here is my MainActivity.java

```<code>    public void read_file(){
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        if (SDK_INT >= 23) {
            if (checkPermission()) {
                File sdcard = Environment.getExternalStorageDirectory();
                File dir = new File(sdcard.getAbsolutePath() + "/Android/data/com.xxx.xxxxxx/files/");

                if(dir.exists()) {
                    File file = new File(dir, "xxx.txt");
                    StringBuilder text = new StringBuilder();
                    try {
                        BufferedReader br = new BufferedReader(new FileReader(file));
                        String line;
                        while ((line = br.readLine()) != null) {
                            text.append(line);
                        }
                        br.close();
                    }catch (IOException e) {
                        //You'll need to add proper error handling here
                    }
                    finally {
                    }
                }
            } else {
                showPermissionDialog(); // Code for permission
            }
        }
    }
}
</code>```

答:
Your app can request All files access from the user by doing the following:

Declare the MANAGE_EXTERNAL_STORAGE permission in the manifest.

Use the ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION intent action to direct users to a system settings page where they can enable the following option for your app: Allow access to manage all files.

See more details at https://developer.android.com/training/data-storage/manage-all-files

Body:
Hi Guys, i tried to access a textfile in the other application in my /Android/data/com.xxx.xxxxxx/files/ in internal storage using Android 11 but unfortunately in won`t. It works in Android 10 below. It has an error at BufferedReader. Here is the error "open failed: EACCES (Permission denied)". Any Answers please? Thanks in advance:)

Here is my gradle.

android {
compileSdkVersion 31
buildToolsVersion "30.0.3"

defaultConfig {
    applicationId "com.example.myapplication"
    minSdkVersion 15
    targetSdkVersion 30
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

Here is my AndroidManifest.xml

<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>

    <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>

<application
    android:requestLegacyExternalStorage="true"
    android:allowBackup="false"
    android:icon="@drawable/ic_launcher_background"
    android:label="My Application"
    android:theme="@style/AppTheme">

Here is my MainActivity.java

    public void read_file(){
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        if (SDK_INT >= 23) {
            if (checkPermission()) {
                File sdcard = Environment.getExternalStorageDirectory();
                File dir = new File(sdcard.getAbsolutePath() + "/Android/data/com.xxx.xxxxxx/files/");

                if(dir.exists()) {
                    File file = new File(dir, "xxx.txt");
                    StringBuilder text = new StringBuilder();
                    try {
                        BufferedReader br = new BufferedReader(new FileReader(file));
                        String line;
                        while ((line = br.readLine()) != null) {
                            text.append(line);
                        }
                        br.close();
                    }catch (IOException e) {
                        //You'll need to add proper error handling here
                    }
                    finally {
                    }
                }
            } else {
                showPermissionDialog(); // Code for permission
            }
        }
    }
}


问:
JavaScript - img caption to appear/disappear onclick event
I need to have image caption to appear on 1 mouse click and disappear on next click by using JS. I can't figure out why the image caption is not appearing when I click on the image with onclick event and function use on external JS. Sorry if I make any mistake on question as this is my first post on  the forum.

HTML

```<code><div id="section1" >
        <h1>Pictures from my vacation</h1>`enter code here`
        <figure style="float: left;" >
            <img src="Photos/p1.jpg" title="Beach" value="hide/show" onclick="showOrHide()">
            <figcaption id="showthis"  style="visibility: hidden;">Waterton Beach</figcaption>
        </figure>
    <p>Beautiful and Sunny day at Wateron last year. Taking Ferry to explore around the late and natural beauty surrounded there. It was a beatiful day and beach and small town with full of visitors. Hope to back to this beautiful small town on summer break.
    </p>
</div>
</code>```

JS

function showOrHide() {

```<code>if (show=="false") {

document.getElementById("showthis").style.visibility="visible";
show="true";

}
else {
//show is true
document.getElementById("showthis").style.visibility="hidden";
show="false";
}
</code>```

}

答:
If displaying/hiding the caption is only your goal, then try this code. This should work.

```<code><div id="section1" >
   <h1>Pictures from my vacation</h1>
   <figure style="float: left;" >
      <img src="https://picsum.photos/200/300" title="Beach" onclick="showOrHide()">
      <figcaption id="showthis"  style="visibility: hidden;">Waterton Beach</figcaption>
   </figure>
   <p>Beautiful and Sunny day at Wateron last year. Taking Ferry to explore around the late and natural beauty surrounded there. It was a beatiful day and beach and small town with full of visitors. Hope to back to this beautiful small town on summer break.
   </p>
</div>
</code>```

Javascript function should be like this.

```<code>function showOrHide() {
    const visibility = document.getElementById("showthis").style.visibility;
    if (visibility == "hidden") {
        document.getElementById("showthis").style.visibility = "visible";
    } else {
        document.getElementById("showthis").style.visibility = "hidden";
    }
}
</code>```

In case you want this javascript function to take care multiple images, you can modify the function like this. and in html on img tag pass the event into function showOrHide(event)

```<code>function showOrHide(e) {
    const img = e.target;
    const figcaption = img.nextElementSibling;
    const visibility = figcaption.style.visibility;
    if (visibility == "hidden") {
        figcaption.style.visibility = "visible";
    } else {
        figcaption.style.visibility = "hidden";
    }
}
</code>```

Body:
I need to have image caption to appear on 1 mouse click and disappear on next click by using JS. I can't figure out why the image caption is not appearing when I click on the image with onclick event and function use on external JS. Sorry if I make any mistake on question as this is my first post on  the forum.

HTML

Pictures from my vacation
`enter code here`

Waterton Beach

Beautiful and Sunny day at Wateron last year. Taking Ferry to explore around the late and natural beauty surrounded there. It was a beatiful day and beach and small town with full of visitors. Hope to back to this beautiful small town on summer break.

JS

function showOrHide() {

if (show=="false") {

document.getElementById("showthis").style.visibility="visible";
show="true";

}
else {
//show is true
document.getElementById("showthis").style.visibility="hidden";
show="false";
}

}

Body:
If displaying/hiding the caption is only your goal, then try this code. This should work.

<div id="section1" >
   <h1>Pictures from my vacation</h1>
   <figure style="float: left;" >
      <img src="https://picsum.photos/200/300" title="Beach" onclick="showOrHide()">
      <figcaption id="showthis"  style="visibility: hidden;">Waterton Beach</figcaption>
   </figure>
   <p>Beautiful and Sunny day at Wateron last year. Taking Ferry to explore around the late and natural beauty surrounded there. It was a beatiful day and beach and small town with full of visitors. Hope to back to this beautiful small town on summer break.
   </p>
</div>

Javascript function should be like this.

function showOrHide() {
    const visibility = document.getElementById("showthis").style.visibility;
    if (visibility == "hidden") {
        document.getElementById("showthis").style.visibility = "visible";
    } else {
        document.getElementById("showthis").style.visibility = "hidden";
    }
}

In case you want this javascript function to take care multiple images, you can modify the function like this. and in html on img tag pass the event into function showOrHide(event)

function showOrHide(e) {
    const img = e.target;
    const figcaption = img.nextElementSibling;
    const visibility = figcaption.style.visibility;
    if (visibility == "hidden") {
        figcaption.style.visibility = "visible";
    } else {
        figcaption.style.visibility = "hidden";
    }
}


问:
With dvcs/git, is a single commit preferred over multiple, small, thematic commits?
This may not be a git specific question, but it comes up in the context of git. The idea may apply more broadly to other vcs's.

I am working on a small project in which I am currently the only developer. I'm getting used to using git, so I am wondering about best practices. As I implement new features/functions, I find that I work on multiple files, their examples, and documentation at once, such that my git status may report 15 files that have changed. But those files might relate to 3 different parts of the project.

Is it better to commit them in 3 separate parts, keeping the related files together, so that I could later go back and more easily find those commits. Or it is just as easy to commit them all at once with an appropriate message?

答:
It can be difficult, and there are many differing views about "the one best workflow". Where possible it is better to

separate concerns - use a number of short lived separate branches, one per concern. You can always squash your commit sequence before the final merge and publishing to a more senior branch.

commit often - smaller steps make it easier to find where mistakes happened and why, and to align merges. Again you can squash after it works.

use the staging area and git stash to partition which work you place in each commit.

Don't worry too much about minor slip ups. Foresight only happens if you walk backwards..