问:
EF Core: Group By Failure - Translation of 'Select' which contains grouping parameter without composition is not supported
The below LINQ query works perfectly fine in EF6 world where the whole query seems to be evaluated at the server (checked with SQL Profiler) but fails in EFCore6.

```<code>private IQueryable<CommentResponseData> LatestCommentResponses()
        {

            var commentResponses = from responses in Repository.CommentResponses
                                   group responses by responses.CommentId into responseGroup
                                   let latestComment = responseGroup.OrderByDescending(a => a.OriginalCreatedTime).FirstOrDefault()
                                   join user in Repository.Users on latestComment.UserId equals user.Id
                                   select new CommentResponseData
                                   {
                                       CommentId = responseGroup.Key,
                                       LastResponseTime = latestComment.OriginalCreatedTime,
                                       ResponseCount = responseGroup.Count(),
                                       LastResponseBy = user.FullName,
                                       LastResponseMessage = latestComment.Body,
                                   };
            return commentResponses;
        }
</code>```

SQL generated in EF6:

```<code>SELECT
    1 AS [C1],
    [Project3].[CommentId] AS [CommentId],
    [Project3].[OriginalCreatedTime] AS [OriginalCreatedTime],
    [Project3].[C1] AS [C2],
    [Project3].[FullName] AS [FullName],
    [Project3].[Body] AS [Body]
    FROM ( SELECT
        [Distinct1].[CommentId] AS [CommentId],
        [Extent3].[FullName] AS [FullName],
        [Limit1].[Body] AS [Body],
        [Limit1].[OriginalCreatedTime] AS [OriginalCreatedTime],
        (SELECT
            COUNT(1) AS [A1]
            FROM [dbo].[CommentResponses] AS [Extent4]
            WHERE [Distinct1].[CommentId] = [Extent4].[CommentId]) AS [C1]
        FROM    (SELECT DISTINCT
            [Extent1].[CommentId] AS [CommentId]
            FROM [dbo].[CommentResponses] AS [Extent1] ) AS [Distinct1]
        OUTER APPLY  (SELECT TOP (1) [Project2].[Body] AS [Body], [Project2].[OriginalCreatedTime] AS [OriginalCreatedTime], [Project2].[UserId] AS [UserId]
            FROM ( SELECT
                [Extent2].[Body] AS [Body],
                [Extent2].[OriginalCreatedTime] AS [OriginalCreatedTime],
                [Extent2].[UserId] AS [UserId]
                FROM [dbo].[CommentResponses] AS [Extent2]
                WHERE [Distinct1].[CommentId] = [Extent2].[CommentId]
            )  AS [Project2]
            ORDER BY [Project2].[OriginalCreatedTime] DESC ) AS [Limit1]
        INNER JOIN [dbo].[Users] AS [Extent3] ON [Limit1].[UserId] = [Extent3].[Id]
    )  AS [Project3]

</code>```

Exception in EFCore 6:

```<code>The LINQ expression 'DbSet<ECommentResponse>()
    .GroupBy(responses => responses.CommentId)
    .Select(responseGroup => new {
        responseGroup = responseGroup,
        latestComment = responseGroup
            .AsQueryable()
            .OrderByDescending(a => a.OriginalCreatedTime)
            .FirstOrDefault()
     })' could not be translated. Additional information: Translation of 'Select' which contains grouping parameter without composition is not supported. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
</code>```

Expression Tree in EFCore 6

```<code>.Call System.Linq.Queryable.Join(
    .Call System.Linq.Queryable.Select(
        .Call System.Linq.Queryable.GroupBy(
            .Call Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.AsNoTracking(.Extension<Microsoft.EntityFrameworkCore.Query.QueryRootExpression>)
            ,
            '(.Lambda #Lambda1<System.Func`2[Lw.Domain.ICommentResponse,System.Nullable`1[System.Int64]]>)),
        '(.Lambda #Lambda2<System.Func`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],<>f__AnonymousType183`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],Lw.Domain.ICommentResponse]]>))
    ,
    .Call Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.AsNoTracking(.Extension<Microsoft.EntityFrameworkCore.Query.QueryRootExpression>)
    ,
    '(.Lambda #Lambda3<System.Func`2[<>f__AnonymousType183`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],Lw.Domain.ICommentResponse],System.Nullable`1[System.Int64]]>),
    '(.Lambda #Lambda4<System.Func`2[Lw.Domain.IUser,System.Nullable`1[System.Int64]]>),
    '(.Lambda #Lambda5<System.Func`3[<>f__AnonymousType183`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],Lw.Domain.ICommentResponse],Lw.Domain.IUser,Lw.Domain.Base.Extension.Selectors.CommentQueryables+CommentResponseData]>))

.Lambda #Lambda1<System.Func`2[Lw.Domain.ICommentResponse,System.Nullable`1[System.Int64]]>(Lw.Domain.ICommentResponse $responses)
{
    $responses.CommentId
}

.Lambda #Lambda2<System.Func`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],<>f__AnonymousType183`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],Lw.Domain.ICommentResponse]]>(System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse] $responseGroup)
{
    .New <>f__AnonymousType183`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],Lw.Domain.ICommentResponse](
        $responseGroup,
        .Call System.Linq.Enumerable.FirstOrDefault(.Call System.Linq.Enumerable.OrderByDescending(
                $responseGroup,
                .Lambda #Lambda6<System.Func`2[Lw.Domain.ICommentResponse,System.Nullable`1[System.DateTimeOffset]]>)))
}

.Lambda #Lambda3<System.Func`2[<>f__AnonymousType183`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],Lw.Domain.ICommentResponse],System.Nullable`1[System.Int64]]>(<>f__AnonymousType183`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],Lw.Domain.ICommentResponse] $<>h__TransparentIdentifier0)
{
    ($<>h__TransparentIdentifier0.latestComment).UserId
}

.Lambda #Lambda4<System.Func`2[Lw.Domain.IUser,System.Nullable`1[System.Int64]]>(Lw.Domain.IUser $user) {
    (System.Nullable`1[System.Int64])$user.Id
}

.Lambda #Lambda5<System.Func`3[<>f__AnonymousType183`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],Lw.Domain.ICommentResponse],Lw.Domain.IUser,Lw.Domain.Base.Extension.Selectors.CommentQueryables+CommentResponseData]>(
    <>f__AnonymousType183`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],Lw.Domain.ICommentResponse] $<>h__TransparentIdentifier0,
    Lw.Domain.IUser $user) {
    .New Lw.Domain.Base.Extension.Selectors.CommentQueryables+CommentResponseData(){
        CommentId = ($<>h__TransparentIdentifier0.responseGroup).Key,
        LastResponseTime = ($<>h__TransparentIdentifier0.latestComment).OriginalCreatedTime,
        ResponseCount = .Call System.Linq.Enumerable.Count($<>h__TransparentIdentifier0.responseGroup),
        LastResponseBy = $user.FullName,
        LastResponseMessage = ($<>h__TransparentIdentifier0.latestComment).Body
    }
}

.Lambda #Lambda6<System.Func`2[Lw.Domain.ICommentResponse,System.Nullable`1[System.DateTimeOffset]]>(Lw.Domain.ICommentResponse $a)
{
    $a.OriginalCreatedTime
}

</code>```

NOTE:

No custom Expression Visitor has been implemented

If the above query can be fully converted into SQL in EF6, then why can't it be the case in EFCore 6 world

Is this an existing bug in EFCore6

EF Core version: 6.0.1
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 6.0
Operating system: Win 10 Pro
IDE: Visual Studio 2022 v17.0.4

答:
Consider to rewrite your query until this bug is fixed

var sourceQery = Repository.CommentResponses;

var groupingQuery =
    from responses in sourceQery
    group responses by responses.CommentId into responseGroup
    select new
    {
        CommentId = responseGroup.Key,
        ResponseCount = responseGroup.Count()
    };

var commentResponses =
    from g in groupingQuery
    from latestComment in sourceQery
        .Where(l => l.CommentId == g.CommentId)
        .OrderByDescending(a => a.OriginalCreatedTime)
        .Take(1)
    join user in Repository.Users on latestComment.UserId equals user.Id
    select new CommentResponseData
    {
        CommentId = g.CommentId,
        LastResponseTime = latestComment.OriginalCreatedTime,
        ResponseCount = g.ResponseCount,
        LastResponseBy = user.FullName,
        LastResponseMessage = latestComment.Body,
    };
```

Body:
The below LINQ query works perfectly fine in EF6 world where the whole query seems to be evaluated at the server (checked with SQL Profiler) but fails in EFCore6.

private IQueryable<CommentResponseData> LatestCommentResponses()
        {

            var commentResponses = from responses in Repository.CommentResponses
                                   group responses by responses.CommentId into responseGroup
                                   let latestComment = responseGroup.OrderByDescending(a => a.OriginalCreatedTime).FirstOrDefault()
                                   join user in Repository.Users on latestComment.UserId equals user.Id
                                   select new CommentResponseData
                                   {
                                       CommentId = responseGroup.Key,
                                       LastResponseTime = latestComment.OriginalCreatedTime,
                                       ResponseCount = responseGroup.Count(),
                                       LastResponseBy = user.FullName,
                                       LastResponseMessage = latestComment.Body,
                                   };
            return commentResponses;
        }

SQL generated in EF6:

SELECT
    1 AS [C1],
    [Project3].[CommentId] AS [CommentId],
    [Project3].[OriginalCreatedTime] AS [OriginalCreatedTime],
    [Project3].[C1] AS [C2],
    [Project3].[FullName] AS [FullName],
    [Project3].[Body] AS [Body]
    FROM ( SELECT
        [Distinct1].[CommentId] AS [CommentId],
        [Extent3].[FullName] AS [FullName],
        [Limit1].[Body] AS [Body],
        [Limit1].[OriginalCreatedTime] AS [OriginalCreatedTime],
        (SELECT
            COUNT(1) AS [A1]
            FROM [dbo].[CommentResponses] AS [Extent4]
            WHERE [Distinct1].[CommentId] = [Extent4].[CommentId]) AS [C1]
        FROM    (SELECT DISTINCT
            [Extent1].[CommentId] AS [CommentId]
            FROM [dbo].[CommentResponses] AS [Extent1] ) AS [Distinct1]
        OUTER APPLY  (SELECT TOP (1) [Project2].[Body] AS [Body], [Project2].[OriginalCreatedTime] AS [OriginalCreatedTime], [Project2].[UserId] AS [UserId]
            FROM ( SELECT
                [Extent2].[Body] AS [Body],
                [Extent2].[OriginalCreatedTime] AS [OriginalCreatedTime],
                [Extent2].[UserId] AS [UserId]
                FROM [dbo].[CommentResponses] AS [Extent2]
                WHERE [Distinct1].[CommentId] = [Extent2].[CommentId]
            )  AS [Project2]
            ORDER BY [Project2].[OriginalCreatedTime] DESC ) AS [Limit1]
        INNER JOIN [dbo].[Users] AS [Extent3] ON [Limit1].[UserId] = [Extent3].[Id]
    )  AS [Project3]

Exception in EFCore 6:

The LINQ expression 'DbSet<ECommentResponse>()
    .GroupBy(responses => responses.CommentId)
    .Select(responseGroup => new {
        responseGroup = responseGroup,
        latestComment = responseGroup
            .AsQueryable()
            .OrderByDescending(a => a.OriginalCreatedTime)
            .FirstOrDefault()
     })' could not be translated. Additional information: Translation of 'Select' which contains grouping parameter without composition is not supported. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

Expression Tree in EFCore 6

.Call System.Linq.Queryable.Join(
    .Call System.Linq.Queryable.Select(
        .Call System.Linq.Queryable.GroupBy(
            .Call Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.AsNoTracking(.Extension<Microsoft.EntityFrameworkCore.Query.QueryRootExpression>)
            ,
            '(.Lambda #Lambda1<System.Func`2[Lw.Domain.ICommentResponse,System.Nullable`1[System.Int64]]>)),
        '(.Lambda #Lambda2<System.Func`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],<>f__AnonymousType183`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],Lw.Domain.ICommentResponse]]>))
    ,
    .Call Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.AsNoTracking(.Extension<Microsoft.EntityFrameworkCore.Query.QueryRootExpression>)
    ,
    '(.Lambda #Lambda3<System.Func`2[<>f__AnonymousType183`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],Lw.Domain.ICommentResponse],System.Nullable`1[System.Int64]]>),
    '(.Lambda #Lambda4<System.Func`2[Lw.Domain.IUser,System.Nullable`1[System.Int64]]>),
    '(.Lambda #Lambda5<System.Func`3[<>f__AnonymousType183`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],Lw.Domain.ICommentResponse],Lw.Domain.IUser,Lw.Domain.Base.Extension.Selectors.CommentQueryables+CommentResponseData]>))

.Lambda #Lambda1<System.Func`2[Lw.Domain.ICommentResponse,System.Nullable`1[System.Int64]]>(Lw.Domain.ICommentResponse $responses)
{
    $responses.CommentId
}

.Lambda #Lambda2<System.Func`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],<>f__AnonymousType183`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],Lw.Domain.ICommentResponse]]>(System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse] $responseGroup)
{
    .New <>f__AnonymousType183`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],Lw.Domain.ICommentResponse](
        $responseGroup,
        .Call System.Linq.Enumerable.FirstOrDefault(.Call System.Linq.Enumerable.OrderByDescending(
                $responseGroup,
                .Lambda #Lambda6<System.Func`2[Lw.Domain.ICommentResponse,System.Nullable`1[System.DateTimeOffset]]>)))
}

.Lambda #Lambda3<System.Func`2[<>f__AnonymousType183`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],Lw.Domain.ICommentResponse],System.Nullable`1[System.Int64]]>(<>f__AnonymousType183`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],Lw.Domain.ICommentResponse] $<>h__TransparentIdentifier0)
{
    ($<>h__TransparentIdentifier0.latestComment).UserId
}

.Lambda #Lambda4<System.Func`2[Lw.Domain.IUser,System.Nullable`1[System.Int64]]>(Lw.Domain.IUser $user) {
    (System.Nullable`1[System.Int64])$user.Id
}

.Lambda #Lambda5<System.Func`3[<>f__AnonymousType183`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],Lw.Domain.ICommentResponse],Lw.Domain.IUser,Lw.Domain.Base.Extension.Selectors.CommentQueryables+CommentResponseData]>(
    <>f__AnonymousType183`2[System.Linq.IGrouping`2[System.Nullable`1[System.Int64],Lw.Domain.ICommentResponse],Lw.Domain.ICommentResponse] $<>h__TransparentIdentifier0,
    Lw.Domain.IUser $user) {
    .New Lw.Domain.Base.Extension.Selectors.CommentQueryables+CommentResponseData(){
        CommentId = ($<>h__TransparentIdentifier0.responseGroup).Key,
        LastResponseTime = ($<>h__TransparentIdentifier0.latestComment).OriginalCreatedTime,
        ResponseCount = .Call System.Linq.Enumerable.Count($<>h__TransparentIdentifier0.responseGroup),
        LastResponseBy = $user.FullName,
        LastResponseMessage = ($<>h__TransparentIdentifier0.latestComment).Body
    }
}

.Lambda #Lambda6<System.Func`2[Lw.Domain.ICommentResponse,System.Nullable`1[System.DateTimeOffset]]>(Lw.Domain.ICommentResponse $a)
{
    $a.OriginalCreatedTime
}

NOTE:

No custom Expression Visitor has been implemented

If the above query can be fully converted into SQL in EF6, then why can't it be the case in EFCore 6 world

Is this an existing bug in EFCore6

EF Core version: 6.0.1
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 6.0
Operating system: Win 10 Pro
IDE: Visual Studio 2022 v17.0.4


来源: stackexchange

问:
TypeError: cannot unpack non-iterable int objec
How can I solve this error After running my code as follows . I am using the function below and implementin running window for loop on it but end up getting the error below. The for loop works and hungs at a point.

```<code>def get_grps(s, thresh=-1, Nmin=3):
    """
    Nmin : int > 0
    Min number of consecutive values below threshold.
    """
    m = np.logical_and.reduce([s.shift(-i).le(thresh) for i in range(Nmin)])
    if Nmin > 1:
        m = pd.Series(m, index=s.index).replace({False: np.NaN}).ffill(limit=Nmin - 1).fillna(False)
    else:
        m = pd.Series(m, index=s.index)

    # Form consecutive groups
    gps = m.ne(m.shift(1)).cumsum().where(m)

    # Return None if no groups, else the aggregations
    if gps.isnull().all():
        return 0
    else:
        agg = s.groupby(gps).agg([list, sum, 'size']).reset_index(drop=True)
        # agg2 = s2.groupby(gps).agg([list, sum, 'size']).reset_index(drop=True)
        return agg, gps

data_spi = [-0.32361498 -0.5229471   0.15702732  0.28753752   -0.01069884 -0.8163699
  -1.3169327   0.4413181   0.75815576  1.3858147   0.49990863-0.06357133
-0.78432    -0.95337325 -1.663739    0.18965477  0.81183237   0.8360347
  0.99537593 -0.12197364 -0.31432647 -2.0865853   0.2084263    0.13332903
 -0.05270813 -1.0090573  -1.6578217  -1.2969246  -0.70916456   0.70059913
 -1.2127264  -0.659762   -1.1612778  -2.1216285  -0.8054617    -0.6293912
 -2.2103117  -1.9373081  -2.530625   -2.4089663  -1.950846    -1.6129876]
lon = data_spi.lon
lat = data_spi.lat
print(len(data_spi))

n=6

for x in range(len(lat)):
    for y in range(len(lon)):
        if data_spi[0, x, y] != 0:
            for i in range(len(data_spi)-70):
                ts = data_spi[i:i+10, x, y].fillna(1)
                print(ts)
                # print(np.array(ts))

                agg, gps = get_grps(pd.Series(ts), thresh=-1, Nmin=3)

                duration = np.nanmean(agg['sum'])
                frequency = len(agg['sum'])
                severity = np.abs(np.mean(agg['sum']))
                intensity = np.mean(np.abs(agg['sum'] / agg['size']))
                print(f'intensity {intensity}')
</code>```

I get this error

```<code> Traceback (most recent call last):
 File "/Users/mada0007/PycharmProjects/Research_ass /FREQ_MEAN_INT_DUR_CORR.py", line 80, in <module>
 agg, gps = get_grps(pd.Series(ts), thresh=-1, Nmin=3)
 typeError: cannot unpack non-iterable int object
</code>```

How can I resolve this error?

答:
(DJANGO)
In my case, I was trying get a item without set which parameter for search:

```<code> schooling = Schooling.objects.get(randint(1, 10)) #Error

 schooling = Schooling.objects.get(id=randint(1, 10)) #OK set id=
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I solve this error After running my code as follows . I am using the function below and implementin running window for loop on it but end up getting the error below. The for loop works and hungs at a point.

def get_grps(s, thresh=-1, Nmin=3):
    """
    Nmin : int > 0
    Min number of consecutive values below threshold.
    """
    m = np.logical_and.reduce([s.shift(-i).le(thresh) for i in range(Nmin)])
    if Nmin > 1:
        m = pd.Series(m, index=s.index).replace({False: np.NaN}).ffill(limit=Nmin - 1).fillna(False)
    else:
        m = pd.Series(m, index=s.index)

    # Form consecutive groups
    gps = m.ne(m.shift(1)).cumsum().where(m)

    # Return None if no groups, else the aggregations
    if gps.isnull().all():
        return 0
    else:
        agg = s.groupby(gps).agg([list, sum, 'size']).reset_index(drop=True)
        # agg2 = s2.groupby(gps).agg([list, sum, 'size']).reset_index(drop=True)
        return agg, gps

data_spi = [-0.32361498 -0.5229471   0.15702732  0.28753752   -0.01069884 -0.8163699
  -1.3169327   0.4413181   0.75815576  1.3858147   0.49990863-0.06357133
-0.78432    -0.95337325 -1.663739    0.18965477  0.81183237   0.8360347
  0.99537593 -0.12197364 -0.31432647 -2.0865853   0.2084263    0.13332903
 -0.05270813 -1.0090573  -1.6578217  -1.2969246  -0.70916456   0.70059913
 -1.2127264  -0.659762   -1.1612778  -2.1216285  -0.8054617    -0.6293912
 -2.2103117  -1.9373081  -2.530625   -2.4089663  -1.950846    -1.6129876]
lon = data_spi.lon
lat = data_spi.lat
print(len(data_spi))

n=6

for x in range(len(lat)):
    for y in range(len(lon)):
        if data_spi[0, x, y] != 0:
            for i in range(len(data_spi)-70):
                ts = data_spi[i:i+10, x, y].fillna(1)
                print(ts)
                # print(np.array(ts))

                agg, gps = get_grps(pd.Series(ts), thresh=-1, Nmin=3)

                duration = np.nanmean(agg['sum'])
                frequency = len(agg['sum'])
                severity = np.abs(np.mean(agg['sum']))
                intensity = np.mean(np.abs(agg['sum'] / agg['size']))
                print(f'intensity {intensity}')

I get this error

 Traceback (most recent call last):
 File "/Users/mada0007/PycharmProjects/Research_ass /FREQ_MEAN_INT_DUR_CORR.py", line 80, in <module>
 agg, gps = get_grps(pd.Series(ts), thresh=-1, Nmin=3)
 typeError: cannot unpack non-iterable int object

How can I resolve this error?

Body:
(DJANGO)
In my case, I was trying get a item without set which parameter for search:

 schooling = Schooling.objects.get(randint(1, 10)) #Error

 schooling = Schooling.objects.get(id=randint(1, 10)) #OK set id=


问:
How to normalize a NumPy array to a unit vector?
I would like to convert a NumPy array to a unit vector. More specifically, I am looking for an equivalent version of this normalisation function:

```<code>def normalize(v):
    norm = np.linalg.norm(v)
    if norm == 0:
       return v
    return v / norm
</code>```

This function handles the situation where vector v has the norm value of 0.

Is there any similar functions provided in sklearn or numpy?

答:
A simple dot product would do the job. No need for any extra package.

```<code>x = x/np.sqrt(x.dot(x))
</code>```

By the way, if the norm of x is zero, it is inherently a zero vector, and cannot be converted to a unit vector (which has norm 1). If you want to catch the case of np.array([0,0,...0]), then use

```<code>norm = np.sqrt(x.dot(x))
x = x/norm if norm != 0 else x
</code>```

Body:
I would like to convert a NumPy array to a unit vector. More specifically, I am looking for an equivalent version of this normalisation function:

def normalize(v):
    norm = np.linalg.norm(v)
    if norm == 0:
       return v
    return v / norm

This function handles the situation where vector v has the norm value of 0.

Is there any similar functions provided in sklearn or numpy?

Body:
A simple dot product would do the job. No need for any extra package.

x = x/np.sqrt(x.dot(x))

By the way, if the norm of x is zero, it is inherently a zero vector, and cannot be converted to a unit vector (which has norm 1). If you want to catch the case of np.array([0,0,...0]), then use

norm = np.sqrt(x.dot(x))
x = x/norm if norm != 0 else x


问:
Looping over grid to get label and entry text values in tkinter
I have created a window using tkinter, this window contains a grid of Labels and Entries. In the Entries I have edited some text that I want to save back to the source.

Everything I'm reading so far says that I need to create a separate list and save each entry text variable in the list.

But isn't there a better way to get the values directly from the controls themselves? I know I can loop over mywindow.winfo_children or mywindow.children. So if I can do this, then I should be able to get the text values directly, no?

I just don't know which property to get the value from.

Any ideas out there?

答:
Just to elaborate on the answer.

Loop through the window grid items using the grid_slaves method.

Get the row and column using the widget's grid_info method:

```<code>for child in window.grid_slaves():
    g_info = child.grid_info()
    if type(child) is Button:
        row = g_info['row']
        col = g_info['column']
        text = child['text']
        print(row, col, text)
</code>```

Body:
Just to elaborate on the answer.

Loop through the window grid items using the grid_slaves method.

Get the row and column using the widget's grid_info method:

for child in window.grid_slaves():
    g_info = child.grid_info()
    if type(child) is Button:
        row = g_info['row']
        col = g_info['column']
        text = child['text']
        print(row, col, text)


问:
When is function reverted?
so because of reentrancy attacks I'm structuring my function to not get hacked. So first updating mappings and so on and then sending the payment.

My question is what if the payment fails to go through. Will entire function be reverted of just the payment?

Because if only the payment than that would mean my mappings would be updated as if the payment went through.

Is this the case?

Thanks for answers!

答:
If you're preventing the reentrancy attacks, you might probably use the modifiers. Therefore, when the Reentrancy is detected, the function would be reverted and even not allowed to enter the function. That is, there would be no other parameters updated.

Besides, I can show you some demo code to answer your question.

```<code>contract test {
    uint public a = 0;

    // a will still be a
    function addRevert() public{
        a += 1;
        goRevert();
    }

    // a = a + 1
    function addNoRevert() public{
        a += 1;
    }

    function goRevert() pure public{
        revert();
    }
}
</code>```

Title: When is function reverted?

Body:
If you're preventing the reentrancy attacks, you might probably use the modifiers. Therefore, when the Reentrancy is detected, the function would be reverted and even not allowed to enter the function. That is, there would be no other parameters updated.

Besides, I can show you some demo code to answer your question.

contract test {
    uint public a = 0;

    // a will still be a
    function addRevert() public{
        a += 1;
        goRevert();
    }

    // a = a + 1
    function addNoRevert() public{
        a += 1;
    }

    function goRevert() pure public{
        revert();
    }
}


问:
How to build on remote Docker server with Jenkins declarative pipeline?
I wrote a declarative pipeline within Jenkins. This pipeline should run in a Docker container on a remote Docker server.

I read Customizing the execution environment:

Customizing the execution environment

Pipeline is designed to easily use Docker images as the execution environment for a single Stage or the entire Pipeline. Meaning that a user can define the tools required for their Pipeline, without having to manually configure agents. Practically any tool which can be packaged in a Docker container. can be used with ease by making only minor edits to a Jenkinsfile.

```<code>pipeline {
    agent {
        docker { image 'node:7-alpine' }
    }
    stages {
        stage('Test') {
            steps {
                sh 'node --version'
            }
        }
    }
}
</code>```

and it works, but it uses Jenkins server as Docker server.

I read Using a remote Docker server:

Using a remote Docker server

By default, the Docker Pipeline plugin will communicate with a local Docker daemon, typically accessed through /var/run/docker.sock.

To select a non-default Docker server, such as with Docker Swarm, the withServer() method should be used.

By passing a URI, and optionally the Credentials ID of a Docker Server Certificate Authentication pre-configured in Jenkins, to the method with:

```<code>node {
    checkout scm

    docker.withServer('tcp://swarm.example.com:2376', 'swarm-certs') {
        docker.image('mysql:5').withRun('-p 3306:3306') {
            /* do things */
        }
    }
}
</code>```

and this works, but it uses scripted pipeline.

I also read Specifying a Docker Label:

Specifying a Docker Label

By default, Pipeline assumes that any configured agent is capable of running Docker-based Pipelines. For Jenkins environments which have macOS, Windows, or other agents, which are unable to run the Docker daemon, this default setting may be problematic. Pipeline provides a global option in the Manage Jenkins page, and on the Folder level, for specifying which agents (by Label) to use for running Docker-based Pipelines.

but using a label would need a full Jenkins slave with sshd and a Jenkins user installed, online all the time and Jenkins's master would install slave libraries. That sounds a little bit heavy just for using declarative pipelines instead of scripted pipelines.

How could I build on a remote Docker server with a declarative pipeline?

答:
I figure out a way to make it work with declarative pipeline.

According to How to Connect to a Remote Docker Daemon, docker CLI only needs an environmental variable DOCKER_HOST to specify the remote docker server uri. So I tried to add it to the beginning of my declarative pipeline script, like this:

```<code>env.DOCKER_HOST = 'tcp://<docker_server_ip>:<port>'

pipeline {
...

</code>```

It works!

Body:
I wrote a declarative pipeline within Jenkins. This pipeline should run in a Docker container on a remote Docker server.

I read Customizing the execution environment:

Customizing the execution environment

Pipeline is designed to easily use Docker images as the execution environment for a single Stage or the entire Pipeline. Meaning that a user can define the tools required for their Pipeline, without having to manually configure agents. Practically any tool which can be packaged in a Docker container. can be used with ease by making only minor edits to a Jenkinsfile.

pipeline {
    agent {
        docker { image 'node:7-alpine' }
    }
    stages {
        stage('Test') {
            steps {
                sh 'node --version'
            }
        }
    }
}

and it works, but it uses Jenkins server as Docker server.

I read Using a remote Docker server:

Using a remote Docker server

By default, the Docker Pipeline plugin will communicate with a local Docker daemon, typically accessed through /var/run/docker.sock.

To select a non-default Docker server, such as with Docker Swarm, the withServer() method should be used.

By passing a URI, and optionally the Credentials ID of a Docker Server Certificate Authentication pre-configured in Jenkins, to the method with:

node {
    checkout scm

    docker.withServer('tcp://swarm.example.com:2376', 'swarm-certs') {
        docker.image('mysql:5').withRun('-p 3306:3306') {
            /* do things */
        }
    }
}

and this works, but it uses scripted pipeline.

I also read Specifying a Docker Label:

Specifying a Docker Label

By default, Pipeline assumes that any configured agent is capable of running Docker-based Pipelines. For Jenkins environments which have macOS, Windows, or other agents, which are unable to run the Docker daemon, this default setting may be problematic. Pipeline provides a global option in the Manage Jenkins page, and on the Folder level, for specifying which agents (by Label) to use for running Docker-based Pipelines.

but using a label would need a full Jenkins slave with sshd and a Jenkins user installed, online all the time and Jenkins's master would install slave libraries. That sounds a little bit heavy just for using declarative pipelines instead of scripted pipelines.

How could I build on a remote Docker server with a declarative pipeline?

Body:
I figure out a way to make it work with declarative pipeline.

According to How to Connect to a Remote Docker Daemon, docker CLI only needs an environmental variable DOCKER_HOST to specify the remote docker server uri. So I tried to add it to the beginning of my declarative pipeline script, like this:

env.DOCKER_HOST = 'tcp://<docker_server_ip>:<port>'

pipeline {
...

It works!


问:
Submit a form and then insert values in a php function
I have a form where i want to submit two entries. Its the entry_id and email. I have a php function that begins something like this:

```<code>    public function theFunction($data) {
    if (false && !empty($data['email']) && !empty($data['entry_id']) ) {
        $sql = $this->db->select()
            ->from('votes')
            ->where('entry_id = ?', $data['entry_id'])
            ->where('email = ?', $data['email'])
            ->order('created DESC');
</code>```

But how am i supposed to call this function from a php file and bringing the values from the form with me, this is far as i've come but it doesent seem to work:

```<code>$fields = array("email","entry_id");
$data = array();
foreach($fields as $field){
    $data[$field] = $_POST[$field];
}

echo theFunction($data);
</code>```

Does anyone know how i should do?

答:
(CodeIgniter? Just curious, it has a big impact on a question like this.)

Change this:

```<code>if (false && !empty($data['email']) && !empty($data['entry_id']) ) {
</code>```

to this:

```<code>if (!empty($data['email']) && !empty($data['entry_id'])) {
</code>```

Never start a logical && comparison with false, PHP exits on the first false answer it finds and does not execute any additional tests. Your code is cut off, is that the whole function body? Does it return anything? What happens to $sql? If your function doesn't return anything, echo has nothing to output so you wouldn't see anything either way. >_> Example, placing

```<code>} else { return $result = 'test failed'; }
</code>```

after the if to catch failures would have alerted you to the comparison problem.

Last thing, maybe try changing this:

```<code>echo theFunction($data);
</code>```

to this:

```<code>$test = theFunction($data);
var_dump($test);
</code>```

var_dump() leaves no room for doubt. Good luck, hth ;)

ContentLicense: CC BY-SA 3.0

Body:
I have a form where i want to submit two entries. Its the entry_id and email. I have a php function that begins something like this:

    public function theFunction($data) {
    if (false && !empty($data['email']) && !empty($data['entry_id']) ) {
        $sql = $this->db->select()
            ->from('votes')
            ->where('entry_id = ?', $data['entry_id'])
            ->where('email = ?', $data['email'])
            ->order('created DESC');

But how am i supposed to call this function from a php file and bringing the values from the form with me, this is far as i've come but it doesent seem to work:

$fields = array("email","entry_id");
$data = array();
foreach($fields as $field){
    $data[$field] = $_POST[$field];
}

echo theFunction($data);

Does anyone know how i should do?

Body:
(CodeIgniter? Just curious, it has a big impact on a question like this.)

Change this:

if (false && !empty($data['email']) && !empty($data['entry_id']) ) {

to this:

if (!empty($data['email']) && !empty($data['entry_id'])) {

Never start a logical && comparison with false, PHP exits on the first false answer it finds and does not execute any additional tests. Your code is cut off, is that the whole function body? Does it return anything? What happens to $sql? If your function doesn't return anything, echo has nothing to output so you wouldn't see anything either way. >_> Example, placing

} else { return $result = 'test failed'; }

after the if to catch failures would have alerted you to the comparison problem.

Last thing, maybe try changing this:

echo theFunction($data);

to this:

$test = theFunction($data);
var_dump($test);

var_dump() leaves no room for doubt. Good luck, hth ;)


问:
Identity Server 4 Silent Renew ErrorResponse: login_required
I have cloned the repo from the redux-oidc-example and it works for the most part but after a few hours it gives the following error:

Action payload: ErrorResponse: login_required

      at new e (oidc-client.min.js:1)

      at t [as _processSigninParams] (oidc-client.min.js:1)

      at t [as validateSigninResponse] (oidc-client.min.js:1)

      at oidc-client.min.js:1

UserManager.js looks like this:

```<code>const userManagerConfig = {
  client_id: 'js.dev',
  client_secret: 'secret',
  redirect_uri: `${window.location.protocol}//${window.location.hostname}${window.location.port ? `:${window.location.port}` : ''}/callback`,
  response_type: 'id_token token',
  scope: 'openid email profile role offline_access',
  authority: 'http://localhost:8080',
  silent_redirect_uri: `${window.location.protocol}//${window.location.hostname}${window.location.port ? `:${window.location.port}` : ''}/silent_renew.html`,
  automaticSilentRenew: true,
  filterProtocolClaims: true,
  loadUserInfo: true
};
</code>```

and my identity server config:

```<code>{
        "Enabled": true,
        "ClientId": "js.dev",
        "ClientName": "Javascript Client",
        "ClientSecrets": [ { "Value": "K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=" } ],
        "AllowedGrantTypes": [ "implicit", "authorization_code" ],
        "AllowedScopes": [ "openid", "email", "profile", "role", "offline_access" ],
        "AllowOfflineAccess": true,
        "AllowAccessTokensViaBrowser":true,
        "RedirectUris": [
          "http://localhost:8081/callback",
          "http://localhost:8081/silent_renew.html"
        ],
        "PostLogoutRedirectUris": [
          "http://localhost:8081"
        ],
        "AccessTokenLifetime": 900,
        "RequireConsent": false
      }
</code>```

I noticed that prior to error last valid response had one cookie response(idsrv.session) with empty value with the expiry date set to the previous year:

I believe this to be the root cause of the issue, I searched it on related Github repo and tried to add the Cookie.SameSite to none but it didn't help:

```<code>services.AddAuthentication()
                .AddSaml(Configuration,externalProviders.UseSaml)
                .AddCookie(options => {
                    options.SlidingExpiration = true;
                    options.ExpireTimeSpan = TimeSpan.FromDays(30);
                    options.Cookie.SameSite = SameSiteMode.None;
                });
</code>```

Any idea!

答:
I had the same issue and tried the proposed above, but for me, it actually was SameSiteMode not set correctly on IdentityServer Cookies. It caused Callback error: ErrorResponse: login_required right after login and after N attempts user was logged out.

This helped me https://github.com/IdentityServer/IdentityServer4/blob/main/src/IdentityServer4/host/Extensions/SameSiteHandlingExtensions.cs

What they do is based on this article https://devblogs.microsoft.com/dotnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core/

Hope this is useful.

Update.

I had another issue related to this when the user was logged out after re-opening a browser (especially on Android Chrome). login_required error was shown. I noticed that session cookie Expires/Max-Age was set to Session and not some future date. Probably because of that check session iframe (with src={identity server url}/connect/checksession) failed as Identity Server thought there was no session as cookie expired.
I tried setting cookie lifetime via options, but it didn't work as expected for some reason. Lifetime was always 14 days:

```<code>services.AddIdentityServer(options=>
  options.Authentication.CookieLifetime = TimeSpan.FromDays(30);
  options.Authentication.CookieSlidingExpiration = true;
})
</code>```

Then I tried this and it worked for me:

```<code>services.ConfigureApplicationCookie(options => {
   options.ExpireTimeSpan = sessionCookieLifetime;
   options.SlidingExpiration = true;
})
</code>```

Body:
I have cloned the repo from the redux-oidc-example and it works for the most part but after a few hours it gives the following error:

Action payload: ErrorResponse: login_required

      at new e (oidc-client.min.js:1)

      at t [as _processSigninParams] (oidc-client.min.js:1)

      at t [as validateSigninResponse] (oidc-client.min.js:1)

      at oidc-client.min.js:1

UserManager.js looks like this:

const userManagerConfig = {
  client_id: 'js.dev',
  client_secret: 'secret',
  redirect_uri: `${window.location.protocol}//${window.location.hostname}${window.location.port ? `:${window.location.port}` : ''}/callback`,
  response_type: 'id_token token',
  scope: 'openid email profile role offline_access',
  authority: 'http://localhost:8080',
  silent_redirect_uri: `${window.location.protocol}//${window.location.hostname}${window.location.port ? `:${window.location.port}` : ''}/silent_renew.html`,
  automaticSilentRenew: true,
  filterProtocolClaims: true,
  loadUserInfo: true
};

and my identity server config:

{
        "Enabled": true,
        "ClientId": "js.dev",
        "ClientName": "Javascript Client",
        "ClientSecrets": [ { "Value": "K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=" } ],
        "AllowedGrantTypes": [ "implicit", "authorization_code" ],
        "AllowedScopes": [ "openid", "email", "profile", "role", "offline_access" ],
        "AllowOfflineAccess": true,
        "AllowAccessTokensViaBrowser":true,
        "RedirectUris": [
          "http://localhost:8081/callback",
          "http://localhost:8081/silent_renew.html"
        ],
        "PostLogoutRedirectUris": [
          "http://localhost:8081"
        ],
        "AccessTokenLifetime": 900,
        "RequireConsent": false
      }

I noticed that prior to error last valid response had one cookie response(idsrv.session) with empty value with the expiry date set to the previous year:

I believe this to be the root cause of the issue, I searched it on related Github repo and tried to add the Cookie.SameSite to none but it didn't help:

services.AddAuthentication()
                .AddSaml(Configuration,externalProviders.UseSaml)
                .AddCookie(options => {
                    options.SlidingExpiration = true;
                    options.ExpireTimeSpan = TimeSpan.FromDays(30);
                    options.Cookie.SameSite = SameSiteMode.None;
                });

Any idea!

Body:
I had the same issue and tried the proposed above, but for me, it actually was SameSiteMode not set correctly on IdentityServer Cookies. It caused Callback error: ErrorResponse: login_required right after login and after N attempts user was logged out.

This helped me https://github.com/IdentityServer/IdentityServer4/blob/main/src/IdentityServer4/host/Extensions/SameSiteHandlingExtensions.cs

What they do is based on this article https://devblogs.microsoft.com/dotnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core/

Hope this is useful.

Update.

I had another issue related to this when the user was logged out after re-opening a browser (especially on Android Chrome). login_required error was shown. I noticed that session cookie Expires/Max-Age was set to Session and not some future date. Probably because of that check session iframe (with src={identity server url}/connect/checksession) failed as Identity Server thought there was no session as cookie expired.
I tried setting cookie lifetime via options, but it didn't work as expected for some reason. Lifetime was always 14 days:

services.AddIdentityServer(options=>
  options.Authentication.CookieLifetime = TimeSpan.FromDays(30);
  options.Authentication.CookieSlidingExpiration = true;
})

Then I tried this and it worked for me:

services.ConfigureApplicationCookie(options => {
   options.ExpireTimeSpan = sessionCookieLifetime;
   options.SlidingExpiration = true;
})


问:
BigQuery convert Month Year column to timestamp or date
I have a table

```<code>Year_month     amount
08-2021         100
09-2021         200
10-2021         300
</code>```

I want to add a column Month to be

```<code>Year_month   Month         amount
08-2021    01-08-2021         100
09-2021    01-09-2021         200
10-2021    01-10-2021         300
</code>```

答:
You can use Parse date function</p>
```<code>SELECT PARSE_DATE("%m-%Y", "08-2021")
</code>```

Body:
I have a table

Year_month     amount
08-2021         100
09-2021         200
10-2021         300

I want to add a column Month to be

Year_month   Month         amount
08-2021    01-08-2021         100
09-2021    01-09-2021         200
10-2021    01-10-2021         300

Body:
You can use Parse date function

SELECT PARSE_DATE("%m-%Y", "08-2021")


问:
Why do Malwares such as Karkoff create and store log files?
I am discovering computer security principles and came across malwares and saw that some of them create and store log files...any insights regarding this matter?</p>

答: After some research on various malwares, the best analysis was that the attackers generate log files to keep track of the commands executed and sometimes with timestamps to keep track of the time too..</p>


问:
Don't understand the logic behind the problem
i'm trying to understand what the problem with my code is.
Here is the task and my code:

Write a method named canPack with three parameters of type int named bigCount, smallCount, and goal.

The parameter bigCount represents the count of big flour bags (5 kilos each).

The parameter smallCount represents the count of small flour bags (1 kilo each).

The parameter goal represents the goal amount of kilos of flour needed to assemble a package.

Therefore, the sum of the kilos of bigCount and smallCount must be at least equal to the value of goal. The method should return true if it is possible to make a package with goal kilos of flour.

If the sum is greater than goal, ensure that only full bags are used towards the goal amount. For example, if goal = 9, bigCount = 2, and smallCount = 0, the method should return false since each big bag is 5 kilos and cannot be divided. However, if goal = 9, bigCount = 1, and smallCount = 5, the method should return true because of 1 full bigCount bag and 4 full smallCount bags equal goal, and it's okay if there are additional bags left over.

If any of the parameters are negative, return false.

EXAMPLE INPUT/OUTPUT:

canPack (1, 0, 4); should return false since bigCount is 1 (big bag of 5 kilos) and goal is 4 kilos.

canPack (1, 0, 5); should return true since bigCount is 1 (big bag of 5 kilos) and goal is 5 kilos.

canPack (0, 5, 4); should return true since smallCount is 5 (small bags of 1 kilo) and goal is 4 kilos, and we have 1 bag left which is ok as mentioned above.

canPack (2, 2, 11); should return true since bigCount is 2 (big bags 5 kilos each) and smallCount is 2 (small bags of 1 kilo), makes in total 12 kilos and goal is 11 kilos.

canPack (-3, 2, 12); should return false since bigCount is negative.

```<code>    public static boolean canPack(int bigCount, int smallCount, int goal) {

        int bigCountKilos = bigCount * 5;
        int smallCountKilos = smallCount;

        if (bigCount < 0 || smallCount < 0 || goal < 0) {
            return false;
        } else {

            if (bigCountKilos >= goal && bigCountKilos % goal == 0) {
                return true;
            } else if (bigCountKilos + smallCountKilos >= goal && bigCountKilos % goal == 0) {
                return true;
            } else if (bigCountKilos < goal && bigCountKilos + smallCountKilos >= goal) {
                return true;
            } else {
                return false;
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(canPack(4, 18, 19));
    }
</code>```

The instance for 4,18,19 should return true but it doesn't. Could someone tell me what i'm doing wrong?
Thanks in advance

答:
Here is my solution:

public static boolean canPack(int bigCount, int smallCount, int goal) {
    if ((bigCount < 0) || (smallCount < 0) || (goal < 0)) {
      return false;
    }

    for (int i = 0; i <= bigCount; i++){
      for (int j = 0; j <= smallCount; j++) {
        if (i*5 + j == goal){
          return true;
        }
      }
    }
    return false;

  }
```
<p>I used nested loop to iterate all possible way to reach the goal. But I found another solution online which is much simpler so I would like to share with you guys too.
credit to Vincent's corner.</p>
<pre class="lang-java prettyprint-override"><code>public class FlourPacker {
    public static boolean canPack(int bigCount, int smallCount, int goal) {

        if (bigCount < 0 || smallCount < 0 || goal < 0) {
            return false;
        }

        if (bigCount * 5 > goal) {
            return smallCount >= goal % 5;
        }

        return smallCount >= goal - (bigCount * 5);
    }
}
</code>```

Body:
i'm trying to understand what the problem with my code is.
Here is the task and my code:

Write a method named canPack with three parameters of type int named bigCount, smallCount, and goal.

The parameter bigCount represents the count of big flour bags (5 kilos each).

The parameter smallCount represents the count of small flour bags (1 kilo each).

The parameter goal represents the goal amount of kilos of flour needed to assemble a package.

Therefore, the sum of the kilos of bigCount and smallCount must be at least equal to the value of goal. The method should return true if it is possible to make a package with goal kilos of flour.

If the sum is greater than goal, ensure that only full bags are used towards the goal amount. For example, if goal = 9, bigCount = 2, and smallCount = 0, the method should return false since each big bag is 5 kilos and cannot be divided. However, if goal = 9, bigCount = 1, and smallCount = 5, the method should return true because of 1 full bigCount bag and 4 full smallCount bags equal goal, and it's okay if there are additional bags left over.

If any of the parameters are negative, return false.

EXAMPLE INPUT/OUTPUT:

canPack (1, 0, 4); should return false since bigCount is 1 (big bag of 5 kilos) and goal is 4 kilos.

canPack (1, 0, 5); should return true since bigCount is 1 (big bag of 5 kilos) and goal is 5 kilos.

canPack (0, 5, 4); should return true since smallCount is 5 (small bags of 1 kilo) and goal is 4 kilos, and we have 1 bag left which is ok as mentioned above.

canPack (2, 2, 11); should return true since bigCount is 2 (big bags 5 kilos each) and smallCount is 2 (small bags of 1 kilo), makes in total 12 kilos and goal is 11 kilos.

canPack (-3, 2, 12); should return false since bigCount is negative.

    public static boolean canPack(int bigCount, int smallCount, int goal) {

        int bigCountKilos = bigCount * 5;
        int smallCountKilos = smallCount;

        if (bigCount < 0 || smallCount < 0 || goal < 0) {
            return false;
        } else {

            if (bigCountKilos >= goal && bigCountKilos % goal == 0) {
                return true;
            } else if (bigCountKilos + smallCountKilos >= goal && bigCountKilos % goal == 0) {
                return true;
            } else if (bigCountKilos < goal && bigCountKilos + smallCountKilos >= goal) {
                return true;
            } else {
                return false;
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(canPack(4, 18, 19));
    }

The instance for 4,18,19 should return true but it doesn't. Could someone tell me what i'm doing wrong?
Thanks in advance

Body:
Here is my solution:

public static boolean canPack(int bigCount, int smallCount, int goal) {
    if ((bigCount < 0) || (smallCount < 0) || (goal < 0)) {
      return false;
    }

    for (int i = 0; i <= bigCount; i++){
      for (int j = 0; j <= smallCount; j++) {
        if (i*5 + j == goal){
          return true;
        }
      }
    }
    return false;

  }

I used nested loop to iterate all possible way to reach the goal. But I found another solution online which is much simpler so I would like to share with you guys too.
credit to Vincent's corner.

public class FlourPacker {
    public static boolean canPack(int bigCount, int smallCount, int goal) {

        if (bigCount < 0 || smallCount < 0 || goal < 0) {
            return false;
        }

        if (bigCount * 5 > goal) {
            return smallCount >= goal % 5;
        }

        return smallCount >= goal - (bigCount * 5);
    }
}


问:
$(this).find("a").attr("onclick"); onclick giving invalid character
I m creating a dynamic tab using Jquery its working fine but giving error for anchor tag onclick error is invalid character.
See the javascript:

```<code>$(document).ready(function(){

    //when page loads...
    $(".tab_content").hide(); //hide all content
    $("ol.tabs li:first").addClass("active").show();  //Activate first tab
    $(".tab_content:first").show(); // show first tab content

    //on click event
    $("ol.tabs li").click(function(){
        $("ol.tabs li").removeClass("active"); //remove any "active" class
        $(this).addClass("active"); // add "active" class to selected tabs
        $(".tab_content").hide(); // hide all tab content
        //var activeTab = $(this).find("a").attr("href"); // find href attribute value to identify the active tab + content
        var activeTab = $(this).find("a").attr("onclick"); // find href attribute value to identify the active tab + content
        $(activeTab).fadeIn(); // fadeIn the active ID content
        alert(activeTab);
        return false;
    });

});
</code>```

And the HTML:

```<code><div>
    <div id="tab1" class="tab_content">01</div>
    <div id="tab2" class="tab_content">02</div>
    <div id="tab3" class="tab_content">03</div>
</div>
<ol class="tabs">
    <li><a onclick="#tab1">Unique benefits</a></li>
    <li><a onclick="#tab2">Insurance</a></li>
    <li><a onclick="#tab3">Business Loan</a></li>
</ol>
</code>```

If i use var activeTab = $(this).find("a").attr("href");

Its work fine.
Help out

答:
You cannot set the onclick of an element to an arbitrary string, this wont mean anything to javascript. Instead you should use fields such as the href or data-attributes to store information for use in events.

To use the href attribute, change your ol list to look like this:

```<code><ol class="tabs">
    <li><a href="#tab1">Unique benefits</a></li>
    <li><a href="#tab2">Insurance</a></li>
    <li><a href="#tab3">Business Loan</a></li>
</ol>
</code>```

And then instead of

```<code>var activeTab = $(this).find("a").attr("onclick"); // find href attribute value to identify the active tab + content
$(activeTab).fadeIn(); // fadeIn the active ID content
</code>```

And use this javascript:

```<code>var activeTab = $(this).find("a").attr("href");
$(activeTab).fadeIn();
</code>```

This will use the href attribute of your link to show the tab with that ID.

Alternatively, to use data-attributes you could set your list to be more like:

```<code><ol class="tabs">
    <li><a href="#" data-tabid="tab1">Unique benefits</a></li>
    <li><a href="#" data-tabid="tab2">Insurance</a></li>
    <li><a href="#" data-tabid="tab3">Business Loan</a></li>
</ol>
</code>```

And use this javascript:

```<code>var activeTab = $(this).find("a").data("tabid");
$("#" + activeTab).fadeIn();
</code>```

This approach uses data-attributes to hold the ID of the tab
 you want to show.

Body:
I m creating a dynamic tab using Jquery its working fine but giving error for anchor tag onclick error is invalid character.
See the javascript:

$(document).ready(function(){

    //when page loads...
    $(".tab_content").hide(); //hide all content
    $("ol.tabs li:first").addClass("active").show();  //Activate first tab
    $(".tab_content:first").show(); // show first tab content

    //on click event
    $("ol.tabs li").click(function(){
        $("ol.tabs li").removeClass("active"); //remove any "active" class
        $(this).addClass("active"); // add "active" class to selected tabs
        $(".tab_content").hide(); // hide all tab content
        //var activeTab = $(this).find("a").attr("href"); // find href attribute value to identify the active tab + content
        var activeTab = $(this).find("a").attr("onclick"); // find href attribute value to identify the active tab + content
        $(activeTab).fadeIn(); // fadeIn the active ID content
        alert(activeTab);
        return false;
    });

});

And the HTML:

01

02

03

Unique benefits

Insurance

Business Loan

If i use var activeTab = $(this).find("a").attr("href");

Its work fine.
Help out

Body:
You cannot set the onclick of an element to an arbitrary string, this wont mean anything to javascript. Instead you should use fields such as the href or data-attributes to store information for use in events.

To use the href attribute, change your ol list to look like this:

<ol class="tabs">
    <li><a href="#tab1">Unique benefits</a></li>
    <li><a href="#tab2">Insurance</a></li>
    <li><a href="#tab3">Business Loan</a></li>
</ol>

And then instead of

var activeTab = $(this).find("a").attr("onclick"); // find href attribute value to identify the active tab + content
$(activeTab).fadeIn(); // fadeIn the active ID content

And use this javascript:

var activeTab = $(this).find("a").attr("href");
$(activeTab).fadeIn();

This will use the href attribute of your link to show the tab with that ID.

Alternatively, to use data-attributes you could set your list to be more like:

<ol class="tabs">
    <li><a href="#" data-tabid="tab1">Unique benefits</a></li>
    <li><a href="#" data-tabid="tab2">Insurance</a></li>
    <li><a href="#" data-tabid="tab3">Business Loan</a></li>
</ol>

And use this javascript:

var activeTab = $(this).find("a").data("tabid");
$("#" + activeTab).fadeIn();

This approach uses data-attributes to hold the ID of the tab <div> you want to show.


问:
Python play again
I am trying to add a play again y/n option but the game asks me to pick a number before asking to play again (if it were to work) and the play again option doesn't pop up.

Code:

```<code>import sys
import os
import time
import random
import colorama
from colorama import Fore
import random
from sys import stdout as s
from time import sleep as j
def w(print):
  for i in print:
    j(.03)
    s.write(i)
    s.flush()
  next = input()
def noinput(print):
  for i in print:
    j(.03)
    s.write(i)
    s.flush()
while True:
  num = random.randint(1, 50)
  guess = "none"

  while guess != num:
    guess = input(Fore.CYAN + "Choose a number: ")
    guess = int(guess)

    if guess == num:
      w(Fore.GREEN + "You guessed the correct number!")
      break
    else:
      w(Fore.RED + "Sorry try again")

    if guess > num:
      w("your number is too large")
      os.system('clear')
    else:
      w("your number is too small")
      os.system('clear')

  play_again = input(Fore.BLUE + "Play again? y/n: ")
  os.system('clear')
  if play_again.lower() != ("y"):
   break
</code>```

I would like to know why this is not working:

```<code>play_again = input(Fore.BLUE + "Play again? y/n: ")
os.system('clear')
if play_again.lower() != ("y"):
 break
</code>```

Help appreciated

答:
Maybe you should specify the environment you run your code, such as python version, system version

however I just copied your code without change and it works fine on python3:

```<code>Choose a number: 49
You guessed the correct number!
Play again? y/n
</code>```

PS: you use print as an argument of an function at line 10 def w(print):, but print is python's built-in function name, that will repoert an error python2, also wrong usage in python3 even no error is reported.

Title: Python play again

Body:
I am trying to add a play again y/n option but the game asks me to pick a number before asking to play again (if it were to work) and the play again option doesn't pop up.

Code:

import sys
import os
import time
import random
import colorama
from colorama import Fore
import random
from sys import stdout as s
from time import sleep as j
def w(print):
  for i in print:
    j(.03)
    s.write(i)
    s.flush()
  next = input()
def noinput(print):
  for i in print:
    j(.03)
    s.write(i)
    s.flush()
while True:
  num = random.randint(1, 50)
  guess = "none"

  while guess != num:
    guess = input(Fore.CYAN + "Choose a number: ")
    guess = int(guess)

    if guess == num:
      w(Fore.GREEN + "You guessed the correct number!")
      break
    else:
      w(Fore.RED + "Sorry try again")

    if guess > num:
      w("your number is too large")
      os.system('clear')
    else:
      w("your number is too small")
      os.system('clear')

  play_again = input(Fore.BLUE + "Play again? y/n: ")
  os.system('clear')
  if play_again.lower() != ("y"):
   break

I would like to know why this is not working:

play_again = input(Fore.BLUE + "Play again? y/n: ")
os.system('clear')
if play_again.lower() != ("y"):
 break

Help appreciated

Body:
Maybe you should specify the environment you run your code, such as python version, system version

however I just copied your code without change and it works fine on python3:

Choose a number: 49
You guessed the correct number!
Play again? y/n

PS: you use print as an argument of an function at line 10 def w(print):, but print is python's built-in function name, that will repoert an error python2, also wrong usage in python3 even no error is reported.


问:
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>```

}

答:
Instead of adding a click event to image. Try with adding an event listener to the image.

HTML

```<code> <div id="section1">
  <h1>Pictures from my vacation</h1>
  `enter code here`
  <figure style="float: left;">
    <img
      src="https://images.unsplash.com/photo-1644550805208-54b031553153?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1228&q=80"
      title="Beach"
      value="hide/show"
      class="beach-img"
    />
    <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

```<code>let show = false;
const beachImg = document.querySelector(".beach-img")
beachImg.addEventListener("click", function () {
 if (show === false) {
   console.log("showing");
   document.getElementById("showthis").style.visibility = "visible";
   show = true;
} else {
   //show is true
   console.log("hiding");
   document.getElementById("showthis").style.visibility = "hidden";
   show = false;
}
</code>```

});

Here's the working example.

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:
Instead of adding a click event to image. Try with adding an event listener to the image.

HTML

 <div id="section1">
  <h1>Pictures from my vacation</h1>
  `enter code here`
  <figure style="float: left;">
    <img
      src="https://images.unsplash.com/photo-1644550805208-54b031553153?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1228&q=80"
      title="Beach"
      value="hide/show"
      class="beach-img"
    />
    <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>

JS

let show = false;
const beachImg = document.querySelector(".beach-img")
beachImg.addEventListener("click", function () {
 if (show === false) {
   console.log("showing");
   document.getElementById("showthis").style.visibility = "visible";
   show = true;
} else {
   //show is true
   console.log("hiding");
   document.getElementById("showthis").style.visibility = "hidden";
   show = false;
}

});

Here's the working example.


问:
How to check if a checkbox has been selected using ShinyDashboard?
I have created an app using ShinyDashboard that has one checkboxInput. If you click on it, you will see two checkboxGroupInput where you can select 1 or 2 choices.

The idea is that if you click 1 option, you will subset your dataframe with your individual choice, or if you click both options, you will subset your dataframe with those two options.

However, I am having problems to verify which option of the checkboxGroupInput the user has selected.

Here is a reproducible example. As you can see, if you select both, you end in the first if statement, subsetting two columns. However, if you select one option (setosa, for example), you are still subsetting by the two, because it doesn't recognise the choice that you have selected. However, if you select "virginica" it is subsetted.

Moreover, it appears this warning all the time.

Warning in if (c("setosa", "virginica") %in% input$species_choice) { :
the condition has length > 1 and only the first element will be used

The code:

```<code>library(shiny)
library(shinydashboard)
library(shinyWidgets)

ui <- dashboardPage(

  dashboardHeader(title = "Dashboard"),
  ## Sidebar content
  dashboardSidebar(
    sidebarMenu(
      menuItem("App1", tabName = "App1", icon = icon("th"))

    )
  ),

  dashboardBody(
    fluidRow(
      tabItems(

        tabItem(tabName = "App1",
                sidebarPanel(
                  checkboxInput(inputId = "species", label = "Select species"),

                  conditionalPanel(
                    condition = "input.species",
                    style = "margin-left: 20px;",

                    checkboxGroupInput("species_choice", "Choose the species:",
                                       choices = c("setosa", "virginica"), selected = c("setosa", "virginica"))),
                ),
                mainPanel(
                  dataTableOutput("table")

                )
        )
      )
    )
  )
)

server <- function(input, output, session) {

  mytables <- reactive({
   if(input$species){

     df_setosa <- iris[iris$Species=="setosa",]
     df_virginica <- iris[iris$Species=="virginica",]
     df_both <- rbind(df_setosa, df_virginica)

     if(c("setosa", "virginica") %in% input$species_choice){
       print("both")
       return(df_both)
     }

     if("setosa" %in% input$species_choice){
       print("setosa")
       return(df_setosa)
     }

     if("virginica" %in% input$species_choice){
       print("virginica")
       return(df_virginica)
     }
   }
  })

  output$table <- renderDataTable({
    mytables()
  })

}

shinyApp(ui, server)
</code>```

I have tried this way too, but it doesn't work:

```<code>if(input$species_choice == "setosa"){
        print("setosa")
        return(df_setosa)
      }

      if(input$species_choice == "virginica"){
        print("virginica")
        return(df_virginica)
      }

      if(input$species_choice == c("setosa, virginica"){
        print("both")
        return(df_both)
      }
</code>```

Does anyone know how to help me, please?

Thanks in advance

答:
There is no need to subset your dataframe before the if conditions, and you don't need all those if conditions. You can simply check if the first button is clicked (my first if condition), and if it is then you can subset your dataframe with the selected specie(s).

Note that if you select none of the two species, the table is empty (but you can change this behavior).

```<code>mytables <- reactive({
  if (input$species) {
    iris[iris$Species %in% input$species_choice, ]
  } else {
    iris
  }
})
</code>```

Body:
I have created an app using ShinyDashboard that has one checkboxInput. If you click on it, you will see two checkboxGroupInput where you can select 1 or 2 choices.

The idea is that if you click 1 option, you will subset your dataframe with your individual choice, or if you click both options, you will subset your dataframe with those two options.

However, I am having problems to verify which option of the checkboxGroupInput the user has selected.

Here is a reproducible example. As you can see, if you select both, you end in the first if statement, subsetting two columns. However, if you select one option (setosa, for example), you are still subsetting by the two, because it doesn't recognise the choice that you have selected. However, if you select "virginica" it is subsetted.

Moreover, it appears this warning all the time.

Warning in if (c("setosa", "virginica") %in% input$species_choice) { :
the condition has length > 1 and only the first element will be used

The code:

library(shiny)
library(shinydashboard)
library(shinyWidgets)

ui <- dashboardPage(

  dashboardHeader(title = "Dashboard"),
  ## Sidebar content
  dashboardSidebar(
    sidebarMenu(
      menuItem("App1", tabName = "App1", icon = icon("th"))

    )
  ),

  dashboardBody(
    fluidRow(
      tabItems(

        tabItem(tabName = "App1",
                sidebarPanel(
                  checkboxInput(inputId = "species", label = "Select species"),

                  conditionalPanel(
                    condition = "input.species",
                    style = "margin-left: 20px;",

                    checkboxGroupInput("species_choice", "Choose the species:",
                                       choices = c("setosa", "virginica"), selected = c("setosa", "virginica"))),
                ),
                mainPanel(
                  dataTableOutput("table")

                )
        )
      )
    )
  )
)

server <- function(input, output, session) {

  mytables <- reactive({
   if(input$species){

     df_setosa <- iris[iris$Species=="setosa",]
     df_virginica <- iris[iris$Species=="virginica",]
     df_both <- rbind(df_setosa, df_virginica)

     if(c("setosa", "virginica") %in% input$species_choice){
       print("both")
       return(df_both)
     }

     if("setosa" %in% input$species_choice){
       print("setosa")
       return(df_setosa)
     }

     if("virginica" %in% input$species_choice){
       print("virginica")
       return(df_virginica)
     }
   }
  })

  output$table <- renderDataTable({
    mytables()
  })

}

shinyApp(ui, server)

I have tried this way too, but it doesn't work:

if(input$species_choice == "setosa"){
        print("setosa")
        return(df_setosa)
      }

      if(input$species_choice == "virginica"){
        print("virginica")
        return(df_virginica)
      }

      if(input$species_choice == c("setosa, virginica"){
        print("both")
        return(df_both)
      }

Does anyone know how to help me, please?

Thanks in advance

Body:
There is no need to subset your dataframe before the if conditions, and you don't need all those if conditions. You can simply check if the first button is clicked (my first if condition), and if it is then you can subset your dataframe with the selected specie(s).

Note that if you select none of the two species, the table is empty (but you can change this behavior).

mytables <- reactive({
  if (input$species) {
    iris[iris$Species %in% input$species_choice, ]
  } else {
    iris
  }
})


问:
CSS: How to shrink td containing ellipsis
I have done quite a bit or searching on this but could not find a solution for my specific case. I am a beginner to CSS and the solution is probably really simple, I just cannot find it. So I am trying to create a table that has some columns with long text. I am able to show ellipsis to cut off too long text, but I would like to have the column resize and the ellipsis be updated if I reduce the size of the window, that also reduces the size of the table itself. Now the cell width remains the same and a horizontal scroll bar is shown, which I want to prevent. I know using fixed width for the column is probably the problem, but it is the only way I am able to show the ellipsis in the first place, without fixed width no ellipsis is shown. Here is a very simplified piece of code and the css that easily shows the problem:

```<code><div class="tableFixHead">
  <table>
    <thead>
      <tr>
        <th>one</th>
        <th>two</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>
          first column
        </td>
        <td>
          <div class="overflowTableText">
            the entire text that is way too long to show all at once
          </div>
        </td>
      </tr>
    </tbody>
  </table>
</div>
</code>```
```<code>.tableFixHead {
  overflow: scroll;
  height: 200px;
  max-width: 50%;
}

.overflowTableText {
  width: 300px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  -ms-text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}
</code>```

Any pointers are appreciated

答:
After fiddling around a bit I found a solution that works with multiple columns with ellipsis:</p>
```<code><div class="tableFixHead">
<table width="100%">
  <thead>
    <tr>
      <th>one</th>
      <th>two</th>
      <th>three</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td width="100px">
        first column
      </td>
      <td class="overflowTableText"><span>
        the entire text that is way too long to show all at once the entire text that is way too long to show all at once</span>
      </td>
      <td class="overflowTableText"><span>
        the entire text that is way too long to show all at once the entire text that is way too long to show all at once</span>
      </td>
    </tr>
  </tbody>
</table>
</div>
</code>```
```<code>.tableFixHead {
  overflow: scroll;
  height: 200px;
  border-collapse: separate;
  width: 90%;
  padding-right: 8px;
}

.overflowTableText {
  max-width: 100px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  -ms-text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}
</code>```

Body:
I have done quite a bit or searching on this but could not find a solution for my specific case. I am a beginner to CSS and the solution is probably really simple, I just cannot find it. So I am trying to create a table that has some columns with long text. I am able to show ellipsis to cut off too long text, but I would like to have the column resize and the ellipsis be updated if I reduce the size of the window, that also reduces the size of the table itself. Now the cell width remains the same and a horizontal scroll bar is shown, which I want to prevent. I know using fixed width for the column is probably the problem, but it is the only way I am able to show the ellipsis in the first place, without fixed width no ellipsis is shown. Here is a very simplified piece of code and the css that easily shows the problem:

        one
        two

          first column

            the entire text that is way too long to show all at once

.tableFixHead {
  overflow: scroll;
  height: 200px;
  max-width: 50%;
}

.overflowTableText {
  width: 300px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  -ms-text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}

Any pointers are appreciated

Body:
After fiddling around a bit I found a solution that works with multiple columns with ellipsis:

<div class="tableFixHead">
<table width="100%">
  <thead>
    <tr>
      <th>one</th>
      <th>two</th>
      <th>three</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td width="100px">
        first column
      </td>
      <td class="overflowTableText"><span>
        the entire text that is way too long to show all at once the entire text that is way too long to show all at once</span>
      </td>
      <td class="overflowTableText"><span>
        the entire text that is way too long to show all at once the entire text that is way too long to show all at once</span>
      </td>
    </tr>
  </tbody>
</table>
</div>

.tableFixHead {
  overflow: scroll;
  height: 200px;
  border-collapse: separate;
  width: 90%;
  padding-right: 8px;
}

.overflowTableText {
  max-width: 100px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  -ms-text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}


问:
How to post Tweets with the Twitter API V2 in PHP?
I'm trying to post tweets with the Twitter API v2 but have an error. I'm using the TwitterAPIExchange.php library, this works fine when I'm trying to search for Tweets for example with GET. But no luck with POST, see code below also the Manage Tweets doc from Twitter: https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets

Maybe I'm missing some parameters after the end point.

```<code>header('Content-Type:application/json');

include ($_SERVER["DOCUMENT_ROOT"] . "/TwitterAPIExchange.php");

$settings = array(
    'oauth_access_token' => "xxxx",
    'oauth_access_token_secret' => "xxxx",
    'consumer_key' => "xxxx",
    'consumer_secret' => "xxxx"

);

$url = "https://api.twitter.com/2/tweets";
$requestMethod = 'POST';

$postfields = array('status' => 'This is the text to Tweet');

$twitter = new TwitterAPIExchange($settings);
$response = $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest();
</code>```

Errors:

```<code>{
errors: [
{
parameters: { },
message: "Requests with bodies must have content-type of application/json."
}
],
title: "Invalid Request",
detail: "One or more parameters to your request was invalid.",
type: "https://api.twitter.com/2/problems/invalid-request"
}
</code>```

答:
I've used the Abraham\TwitterOAuth library instead and was able to send a tweet from the tutorial on this page:
https://artisansweb.net/tweet-twitter-php/</p>

Body:
I'm trying to post tweets with the Twitter API v2 but have an error. I'm using the TwitterAPIExchange.php library, this works fine when I'm trying to search for Tweets for example with GET. But no luck with POST, see code below also the Manage Tweets doc from Twitter: https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets

Maybe I'm missing some parameters after the end point.

header('Content-Type:application/json');

include ($_SERVER["DOCUMENT_ROOT"] . "/TwitterAPIExchange.php");

$settings = array(
    'oauth_access_token' => "xxxx",
    'oauth_access_token_secret' => "xxxx",
    'consumer_key' => "xxxx",
    'consumer_secret' => "xxxx"

);

$url = "https://api.twitter.com/2/tweets";
$requestMethod = 'POST';

$postfields = array('status' => 'This is the text to Tweet');

$twitter = new TwitterAPIExchange($settings);
$response = $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest();

Errors:

{
errors: [
{
parameters: { },
message: "Requests with bodies must have content-type of application/json."
}
],
title: "Invalid Request",
detail: "One or more parameters to your request was invalid.",
type: "https://api.twitter.com/2/problems/invalid-request"
}


问:
Handling Multiple Events from a Single Listener
I want to have a single event listener for multiple events and depending on the

type of event i want to handle them separately.

Something similar to Swiz framework see: 'Handling Multiple Events from a Single Method'

i have a piece of code like

```<code>     var toolOptions:UIComponent=ToolOptions.createToolOptions(type);
            if (options != null)
            {
                options.addEventListener(Event.SELECT,toolOptionSelectedHandler);
                someViewComponent.addOptions(toolOptions);
            }

   // handle depending on event type
    private function toolOptionSelectedHandler(event:*):void
    {
        //handle depending on type of event fired
        // type cast  event depending on type and  retrieve VO from event
        //and send handle it..

        //SomeToolObj.handle(event.VO);

    }
</code>```

In above toolOptions is a mxml component which get dynamically created based on

'type'.

Also which type of event should be dispatch the event from the component? eg: Event.SELECT

To be more precise the above is basically required for a toolbar.

When user selects a tool,he is shown options for a tool and when he selects options,

tool should apply them to object on the view.

Is there a better way to do the same?

答:
That's what I understand:

You have different tools. Each of the tools has a list of options. You click an option, and a single event handler should perform some action depending on the option.

```<code>object on the view 1 : n tools 1 : n options
</code>```

Create a custom event OptionEvent.SELECT with the property optionType.

```<code>public class OptionEvent extends Event {
    public static const SELECT : String = "optionEvent_select";
    public var optionType : String;
    public function OptionEvent(type : String) {
        super(type, true); // bubbles
    }
}
</code>```

When the user selects the option, dispatch the event like this:

```<code>var event : OptionEvent = new OptionEvent(OptionEvent.SELECT);
event.optionType = "border";
dispatchEvent(event);
</code>```

Listen to the event like you do:

```<code>var toolOptions:UIComponent=ToolOptions.createToolOptions(type);
if (options != null) {
    options.addEventListener(OptionEvent.SELECT,toolOptionSelectedHandler);
    someViewComponent.addOptions(toolOptions);
}
</code>```

Distinguish the type of option by determining the option type:

```<code>private function toolOptionSelectedHandler(event : OptionEvent) : void {
     var optionType = event.optionType;
     switch (optionType) {
         case "border":
             addBorderToView();
             break;
         case "rotation":
             rotateView();
             break;
     }
}
</code>```

UPDATE - How to set up a list of option values in OptionEvent:

```<code>public class OptionEvent extends Event {
    public static const SELECT : String = "optionEvent_select";
    public var optionType : String;
    private var _optionValues : Object;

    public function OptionEvent(type : String) {
        _optionValues = new Object();
        super(type, true); // bubbles
    }

    public function setOptionValue(property : String, value : *) : void {
        _optionValues[property] = value;
    }

    public function getOptionValue(property : String) : * {
        return _optionValues[property];
    }
}
</code>```

Body:
I want to have a single event listener for multiple events and depending on the

type of event i want to handle them separately.

Something similar to Swiz framework see: 'Handling Multiple Events from a Single Method'

i have a piece of code like

     var toolOptions:UIComponent=ToolOptions.createToolOptions(type);
            if (options != null)
            {
                options.addEventListener(Event.SELECT,toolOptionSelectedHandler);
                someViewComponent.addOptions(toolOptions);
            }

   // handle depending on event type
    private function toolOptionSelectedHandler(event:*):void
    {
        //handle depending on type of event fired
        // type cast  event depending on type and  retrieve VO from event
        //and send handle it..

        //SomeToolObj.handle(event.VO);

    }

In above toolOptions is a mxml component which get dynamically created based on

'type'.

Also which type of event should be dispatch the event from the component? eg: Event.SELECT

To be more precise the above is basically required for a toolbar.

When user selects a tool,he is shown options for a tool and when he selects options,

tool should apply them to object on the view.

Is there a better way to do the same?

Body:
That's what I understand:

You have different tools. Each of the tools has a list of options. You click an option, and a single event handler should perform some action depending on the option.

object on the view 1 : n tools 1 : n options

Create a custom event OptionEvent.SELECT with the property optionType.

public class OptionEvent extends Event {
    public static const SELECT : String = "optionEvent_select";
    public var optionType : String;
    public function OptionEvent(type : String) {
        super(type, true); // bubbles
    }
}

When the user selects the option, dispatch the event like this:

var event : OptionEvent = new OptionEvent(OptionEvent.SELECT);
event.optionType = "border";
dispatchEvent(event);

Listen to the event like you do:

var toolOptions:UIComponent=ToolOptions.createToolOptions(type);
if (options != null) {
    options.addEventListener(OptionEvent.SELECT,toolOptionSelectedHandler);
    someViewComponent.addOptions(toolOptions);
}

Distinguish the type of option by determining the option type:

private function toolOptionSelectedHandler(event : OptionEvent) : void {
     var optionType = event.optionType;
     switch (optionType) {
         case "border":
             addBorderToView();
             break;
         case "rotation":
             rotateView();
             break;
     }
}

UPDATE - How to set up a list of option values in OptionEvent:

public class OptionEvent extends Event {
    public static const SELECT : String = "optionEvent_select";
    public var optionType : String;
    private var _optionValues : Object;

    public function OptionEvent(type : String) {
        _optionValues = new Object();
        super(type, true); // bubbles
    }

    public function setOptionValue(property : String, value : *) : void {
        _optionValues[property] = value;
    }

    public function getOptionValue(property : String) : * {
        return _optionValues[property];
    }
}


答:
```<code>function withdraw(uint256 _amount) external {
    balances[msg.sender] -= _amount;
    (bool success, ) = payable(msg.sender).call{value: _amount}("");
}
</code>```

If the low-level .call() is unsuccessful, the value of success is set to false but that doesn't revert the whole transaction. So the balances value would be reflected even though the payment didn't go through.

You can add a require() condition to check the result of the payment. This will make the parent transaction fail if the internal transaction fails.

```<code>(bool success, ) = payable(msg.sender).call{value: _amount}("");
require(success);
</code>```

Or you can use the .transfer() function (member of address payable, do not confuse with token transfers) that also fails the parent transaction if the internal transaction fals:

```<code>function withdraw(uint256 _amount) external {
    balances[msg.sender] -= _amount;
    payable(msg.sender).transfer(_amount);
}
</code>```

Title: When is function reverted?

Body:
so because of reentrancy attacks I'm structuring my function to not get hacked. So first updating mappings and so on and then sending the payment.

My question is what if the payment fails to go through. Will entire function be reverted of just the payment?

Because if only the payment than that would mean my mappings would be updated as if the payment went through.

Is this the case?

Thanks for answers!

Body:
function withdraw(uint256 _amount) external {
    balances[msg.sender] -= _amount;
    (bool success, ) = payable(msg.sender).call{value: _amount}("");
}

If the low-level .call() is unsuccessful, the value of success is set to false but that doesn't revert the whole transaction. So the balances value would be reflected even though the payment didn't go through.

You can add a require() condition to check the result of the payment. This will make the parent transaction fail if the internal transaction fails.

(bool success, ) = payable(msg.sender).call{value: _amount}("");
require(success);

Or you can use the .transfer() function (member of address payable, do not confuse with token transfers) that also fails the parent transaction if the internal transaction fals:

function withdraw(uint256 _amount) external {
    balances[msg.sender] -= _amount;
    payable(msg.sender).transfer(_amount);
}


问:
Solve ODE with Scipy solve_ivp where ODE functional form changes with time
If I have the following model:

dy/dt = 2- 6t + 3t^2, t <= 1,

dy/dt = y, t >1.

How would I be able to implement this in python using scipy solve_ivp. When I naively implement a while loop within the model definition, the time t does not update and remains 0.0 forever.

```<code>import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp

def f(t, y):
    while t < 1:
        dydt = 2 -6*t + 3*t**2
        print (t)
    else:
        dydt = y[0]

    return dydt

tspan = np.linspace(0, 4, 20)
yinit = [6]

sol = solve_ivp(lambda t, y: f(t, y),
                [tspan[0], tspan[-1]], yinit, t_eval=tspan, rtol = 1e-5)

fig,ax = plt.subplots()
ax.plot(sol.t, sol.y[0])

plt.show()
</code>```

So in a sense, this is a bit wonkier than a time dependent coefficient since the equation's functional form is changing with time. Would be really grateful for any help here!

答:
My first solution to this which works is to define two separate model equations and another wrapper model equation which enables me to return either equation at a specified time:

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp

def f1(t,y):
    dydt = 2 - 6*t + 3*t**2
    return dydt

def f2(t,y):
    dydt = y[0]
    return dydt

def model(t,y,f1,f2):
    while t < 2:
        return f1(t,y)
    else:
        return f2(t,y)

tspan = np.linspace(0, 4, 20)
yinit = [6]

sol = solve_ivp(lambda t, y: model(t, y,f1,f2),
                [tspan[0], tspan[-1]], yinit, t_eval=tspan, rtol = 1e-5)

fig,ax = plt.subplots()
ax.plot(sol.t, sol.y[0])

plt.show()
</code>```

Based on feedback from the comments, the following script seems to work as well if we replace the while loop with an if statement:

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp

def model2(t,y):
    if t < 2:
        dydt = 2 - 6*t + 3*t**2
    else:
        dydt = y[0]
    return dydt

tspan = np.linspace(0, 4, 20)
yinit = [6]

sol = solve_ivp(lambda t, y: model(t, y,f1,f2),
                [tspan[0], tspan[-1]], yinit, t_eval=tspan, rtol = 1e-5)

fig,ax = plt.subplots()
ax.plot(sol.t, sol.y[0])

plt.show()
</code>```

Body:
If I have the following model:

dy/dt = 2- 6t + 3t^2, t <= 1,

dy/dt = y, t >1.

How would I be able to implement this in python using scipy solve_ivp. When I naively implement a while loop within the model definition, the time t does not update and remains 0.0 forever.

import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp

def f(t, y):
    while t < 1:
        dydt = 2 -6*t + 3*t**2
        print (t)
    else:
        dydt = y[0]

    return dydt

tspan = np.linspace(0, 4, 20)
yinit = [6]

sol = solve_ivp(lambda t, y: f(t, y),
                [tspan[0], tspan[-1]], yinit, t_eval=tspan, rtol = 1e-5)

fig,ax = plt.subplots()
ax.plot(sol.t, sol.y[0])

plt.show()

So in a sense, this is a bit wonkier than a time dependent coefficient since the equation's functional form is changing with time. Would be really grateful for any help here!

Body:
My first solution to this which works is to define two separate model equations and another wrapper model equation which enables me to return either equation at a specified time:

import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp

def f1(t,y):
    dydt = 2 - 6*t + 3*t**2
    return dydt

def f2(t,y):
    dydt = y[0]
    return dydt

def model(t,y,f1,f2):
    while t < 2:
        return f1(t,y)
    else:
        return f2(t,y)

tspan = np.linspace(0, 4, 20)
yinit = [6]

sol = solve_ivp(lambda t, y: model(t, y,f1,f2),
                [tspan[0], tspan[-1]], yinit, t_eval=tspan, rtol = 1e-5)

fig,ax = plt.subplots()
ax.plot(sol.t, sol.y[0])

plt.show()

Based on feedback from the comments, the following script seems to work as well if we replace the while loop with an if statement:

import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp

def model2(t,y):
    if t < 2:
        dydt = 2 - 6*t + 3*t**2
    else:
        dydt = y[0]
    return dydt

tspan = np.linspace(0, 4, 20)
yinit = [6]

sol = solve_ivp(lambda t, y: model(t, y,f1,f2),
                [tspan[0], tspan[-1]], yinit, t_eval=tspan, rtol = 1e-5)

fig,ax = plt.subplots()
ax.plot(sol.t, sol.y[0])

plt.show()


问:
Accessing Azure key vault keys from ADF
We are having a requirement to store rsa key in key vault and use it in ADF.
So we saved *.pem file(rsa key) in azure key vault keys. But in ADf we see only the key vault secrets. It dosn't list key vault-keys in ADF.
So how do we access the keys?

Thank You in advance!

答: We stored a private key for a SFTP linked service in the Azure Key Vault as a secret. We retrieve it by inputting the secret name.</p>

Title: Accessing Azure key vault keys from ADF


问:
How to extract elements of an array in object type in c#?
I have an object which contains an array of any type (not a priory known type. So I cannot a simple cast in the code because I can determine the type just in the run-time!). How can I extract the content of array?
For example:

```<code>int[] array = new int[] { 0, 1, 2 };
object obj=array;
...
//Here I know that obj is an array (<b>of a priory unknown type and I cannot use type conversion in the code </b>
//How can extract elements of obj and use them, e.g. write them on the screen?`
</code>```

答:
EDIT (Again)

If you know that the object is an array and you don't know the type of the array you can just cast it as an object[].  This will defiantly work if all you have to do is call toString().

For example

```<code>(obj as object[])
</code>```

Body:
I have an object which contains an array of any type (not a priory known type. So I cannot a simple cast in the code because I can determine the type just in the run-time!). How can I extract the content of array?
For example:

int[] array = new int[] { 0, 1, 2 };
object obj=array;
...
//Here I know that obj is an array (of a priory unknown type and I cannot use type conversion in the code
//How can extract elements of obj and use them, e.g. write them on the screen?`

Body:
EDIT (Again)

If you know that the object is an array and you don't know the type of the array you can just cast it as an object[].  This will defiantly work if all you have to do is call toString().

For example

(obj as object[])