问:
Using VBA to sort by multiple column headers
I am looking to sort columns by header names since the column where the header is may change using VBA. I found the below code but couldnt figure out how to make it sort by more than one field. Basically i am looking to have this filter by KEY, Status, Enrolled on, Completed on in that order.

```<code>Dim sortAdd As String
Dim sortRange As Range

'Find which column "KEY" appears in
On Error GoTo err_chk
Rows("1:1").Find(What:="KEY", After:=Range("A1"), LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False).Activate
On Error GoTo 0
sortAdd = ActiveCell.Address(0, 0)

'Set sort range by using current region
Range("A1").CurrentRegion.Sort _
    key1:=Range(sortAdd), order1:=xlAscending, Header:=xlYes

Exit Sub
  'Error handling
err_chk:
If Err.Number = 91 Then
    MsgBox "No header row with title of KEY", vbOKOnly, "ERROR!"
Else
    MsgBox Err.Number & ": " & Err.Description
End If
</code>```

Recorded macro seemed to work but not really ideal.

```<code>Range("Deduped[[#Headers],[Key]]").Select
ActiveWorkbook.Worksheets("Deduped").ListObjects("Deduped").sort.SortFields. _
    Clear
ActiveWorkbook.Worksheets("Deduped").ListObjects("Deduped").sort.SortFields. _
    Add2 Key:=Range("Deduped[Key]"), SortOn:=xlSortOnValues, Order:= _
    xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Deduped").ListObjects("Deduped").sort.SortFields. _
    Add2 Key:=Range("Deduped[HR Status]"), SortOn:=xlSortOnValues, Order:= _
    xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Deduped").ListObjects("Deduped").sort.SortFields. _
    Add2 Key:=Range("Deduped[Enrolled on Date]"), SortOn:=xlSortOnValues, _
    Order:=xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Deduped").ListObjects("Deduped").sort.SortFields. _
    Add2 Key:=Range("Deduped[Completion Date]"), SortOn:=xlSortOnValues, Order _
    :=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Deduped").ListObjects("Deduped").sort
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
</code>```

答:
Sort On Multiple Columns

```<code>Option Explicit

Sub SortOnMultipleColumns()

    Dim SortHeaders As Variant
    SortHeaders = Array("KEY", "Status", "Enrolled on", "Completed")
    Dim SortOrders As Variant
    SortOrders = Array(xlAscending, xlAscending, xlAscending, xlAscending)

    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    Dim srg As Range: Set srg = ws.Range("A1").CurrentRegion
    Dim shrg As Range: Set shrg = srg.Rows(1)

    Application.ScreenUpdating = False

    Dim ColumnIndex As Variant
    Dim n As Long

    For n = LBound(SortHeaders) To UBound(SortHeaders)
        ColumnIndex = Application.Match(SortHeaders(n), shrg, 0)
        If IsNumeric(ColumnIndex) Then
            srg.Sort srg.Columns(ColumnIndex), SortOrders(n), , , , , , xlYes
        Else
            MsgBox "Could not find the header '" & SortHeaders(n) & "'.", _
                vbCritical
        End If
    Next n

    Application.ScreenUpdating = True

End Sub
</code>```

Body:
I am looking to sort columns by header names since the column where the header is may change using VBA. I found the below code but couldnt figure out how to make it sort by more than one field. Basically i am looking to have this filter by KEY, Status, Enrolled on, Completed on in that order.

Dim sortAdd As String
Dim sortRange As Range

'Find which column "KEY" appears in
On Error GoTo err_chk
Rows("1:1").Find(What:="KEY", After:=Range("A1"), LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False).Activate
On Error GoTo 0
sortAdd = ActiveCell.Address(0, 0)

'Set sort range by using current region
Range("A1").CurrentRegion.Sort _
    key1:=Range(sortAdd), order1:=xlAscending, Header:=xlYes

Exit Sub
  'Error handling
err_chk:
If Err.Number = 91 Then
    MsgBox "No header row with title of KEY", vbOKOnly, "ERROR!"
Else
    MsgBox Err.Number & ": " & Err.Description
End If

Recorded macro seemed to work but not really ideal.

Range("Deduped[[#Headers],[Key]]").Select
ActiveWorkbook.Worksheets("Deduped").ListObjects("Deduped").sort.SortFields. _
    Clear
ActiveWorkbook.Worksheets("Deduped").ListObjects("Deduped").sort.SortFields. _
    Add2 Key:=Range("Deduped[Key]"), SortOn:=xlSortOnValues, Order:= _
    xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Deduped").ListObjects("Deduped").sort.SortFields. _
    Add2 Key:=Range("Deduped[HR Status]"), SortOn:=xlSortOnValues, Order:= _
    xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Deduped").ListObjects("Deduped").sort.SortFields. _
    Add2 Key:=Range("Deduped[Enrolled on Date]"), SortOn:=xlSortOnValues, _
    Order:=xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Deduped").ListObjects("Deduped").sort.SortFields. _
    Add2 Key:=Range("Deduped[Completion Date]"), SortOn:=xlSortOnValues, Order _
    :=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Deduped").ListObjects("Deduped").sort
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

Body:
Sort On Multiple Columns

Option Explicit

Sub SortOnMultipleColumns()

    Dim SortHeaders As Variant
    SortHeaders = Array("KEY", "Status", "Enrolled on", "Completed")
    Dim SortOrders As Variant
    SortOrders = Array(xlAscending, xlAscending, xlAscending, xlAscending)

    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    Dim srg As Range: Set srg = ws.Range("A1").CurrentRegion
    Dim shrg As Range: Set shrg = srg.Rows(1)

    Application.ScreenUpdating = False

    Dim ColumnIndex As Variant
    Dim n As Long

    For n = LBound(SortHeaders) To UBound(SortHeaders)
        ColumnIndex = Application.Match(SortHeaders(n), shrg, 0)
        If IsNumeric(ColumnIndex) Then
            srg.Sort srg.Columns(ColumnIndex), SortOrders(n), , , , , , xlYes
        Else
            MsgBox "Could not find the header '" & SortHeaders(n) & "'.", _
                vbCritical
        End If
    Next n

    Application.ScreenUpdating = True

End Sub


来源: stackexchange

问:
Can't Change Drives in cmder
I am unable to move to the next drives in cmder. When i put the command to move to the other drive like
    cd c:\

It again automatically moves to the Home Location.

I have searched on their official website but nothing helpful. I have find to set it up in settings but even can't find there

答:
If you are in C drive and want to cd into D drive then run this command

```<code>cd /d D:
</code>```

if you want to cd into K drive

```<code>cd /d K:
</code>```

ContentLicense: CC BY-SA 4.0

Title: Can't Change Drives in cmder

Body:
If you are in C drive and want to cd into D drive then run this command

cd /d D:

if you want to cd into K drive

cd /d K:


问:
Yii2: Is there a Yii-way to force the browser reloading a CSS file?
Normally I would just do something like this:

```<code><link href="main.css?<?= filemtime($file) ?>">
</code>```

Is there a better way in Yii? – If not, is there a way I can add this to $this->head() for a specific CSS file?

答:
If you are properly using asset bundles to load your styles you can set yii\web\AssetManager::$appendTimestamp property of asset manager component to append timestamp automatically.

You can do that in your app config file (for example frontend/config/main.php):

return [
    'components' => [
        'assetManager' => [
            'appendTimestamp' => true,
        ],
    ],
    // ... other configurations ...
]
```

See the guide article for more info about asset bundles.

Body:
Normally I would just do something like this:

<link href="main.css?<?= filemtime($file) ?>">

Is there a better way in Yii? – If not, is there a way I can add this to $this->head() for a specific CSS file?

Body:
If you are properly using asset bundles to load your styles you can set yii\web\AssetManager::$appendTimestamp property of asset manager component to append timestamp automatically.

You can do that in your app config file (for example frontend/config/main.php):

return [
    'components' => [
        'assetManager' => [
            'appendTimestamp' => true,
        ],
    ],
    // ... other configurations ...
]

See the guide article for more info about asset bundles.


问:
bitbake network failure during npm build
I am trying to build openbmc image and my yocto build is failing in phosphor-webui recipe's do compile task.
Here is the do compile task

```<code>do_compile () {
cd ${S}
rm -rf node_modules
npm --loglevel info --proxy=${http_proxy} --https-proxy=${https_proxy} install
npm run-script build
}
</code>```

During NPM install, network access is done to download but bitbake seem to disable the network prior to the build process. I can see this in the build log.

```<code>DEBUG: Attempting to disable network
DEBUG: SOURCE_DATE_EPOCH: 1636412844
</code>```

I tried to set BB_NO_NETWORK variable to '0' but this too didnot help.

How to configure bitbake to allow network access during all tasks ?

答:
Looks like you found an phosphor-webui openbmc recipe issue.

The text "Attempting to disable network" comes from here which was changed 8 days ago by this. So lets check upstream to see if there is a fix in review. I don't see any changes to open bmc recipes here

You should be able to do one of three things

remove phosphor-webui from you image, and build without it. Just remove phosphor-webui from you machine conf, and use webui-vue instead.

Roll you openbmc repo back 18 days and build before it the breaking change. git checkout ca2f10c

Fix the recipe and make everyone's life better. It looks like you need change the Datastore Variables. Something like d.setVar(network, "true") in the recipe file. (if that works send in a patch)

Discord and eMail are the perfered ways of reaching out to the openbmc community. Let us know how it goes and if you have anymore issues.

Body:
I am trying to build openbmc image and my yocto build is failing in phosphor-webui recipe's do compile task.
Here is the do compile task

do_compile () {
cd ${S}
rm -rf node_modules
npm --loglevel info --proxy=${http_proxy} --https-proxy=${https_proxy} install
npm run-script build
}

During NPM install, network access is done to download but bitbake seem to disable the network prior to the build process. I can see this in the build log.

DEBUG: Attempting to disable network
DEBUG: SOURCE_DATE_EPOCH: 1636412844

I tried to set BB_NO_NETWORK variable to '0' but this too didnot help.

How to configure bitbake to allow network access during all tasks ?


问:
User defined scalar-valued functions in SQLAlchemy
Say I have defined an SQL Server function say myfunc which takes a integer as input and returns an integer like this

```<code>CREATE FUNCTION myfunc
(@val as INTEGER)
RETURNS INTEGER
AS
BEGIN
    RETURN
        @val + 10
END
</code>```

Is there a way to call this function in SQLAlchemy? I know I can't do as below, as it is not a recognized built-in function name ('myfunc' is not a recognized built-in function name.)

```<code>select(func.myfunc(x.c.mycolumn).label("my_column_plus_10"))
</code>```

答:
Scalar-valued UDFs must be called using schema-qualified name in SQL Server.

```<code>CREATE FUNCTION myfunc
(@val as INTEGER)
RETURNS INTEGER
AS
BEGIN
    RETURN
        @val + 10
END
go
select myfunc(1) --fails
go
select dbo.myfunc(1) --succeeds
</code>```

So try:

```<code>select(func.dbo.myfunc(x.c.mycolumn).label("my_column_plus_10"))
</code>```

per:

To call functions which are present in dot-separated packages, specify
them in the same manner:

>>> print(func.stats.yield_curve(5, 10))

stats.yield_curve(:yield_curve_1, :yield_curve_2)

sqlalchemy.sql.expression.func

Here it's a schema-qualified UDF not a "dot-separated package", but the generated SQL looks the same.

Body:
Say I have defined an SQL Server function say myfunc which takes a integer as input and returns an integer like this

CREATE FUNCTION myfunc
(@val as INTEGER)
RETURNS INTEGER
AS
BEGIN
    RETURN
        @val + 10
END

Is there a way to call this function in SQLAlchemy? I know I can't do as below, as it is not a recognized built-in function name ('myfunc' is not a recognized built-in function name.)

select(func.myfunc(x.c.mycolumn).label("my_column_plus_10"))

Body:
Scalar-valued UDFs must be called using schema-qualified name in SQL Server.

CREATE FUNCTION myfunc
(@val as INTEGER)
RETURNS INTEGER
AS
BEGIN
    RETURN
        @val + 10
END
go
select myfunc(1) --fails
go
select dbo.myfunc(1) --succeeds

So try:

select(func.dbo.myfunc(x.c.mycolumn).label("my_column_plus_10"))

per:

To call functions which are present in dot-separated packages, specify
them in the same manner:

>>> print(func.stats.yield_curve(5, 10))

stats.yield_curve(:yield_curve_1, :yield_curve_2)

sqlalchemy.sql.expression.func

Here it's a schema-qualified UDF not a "dot-separated package", but the generated SQL looks the same.


问:
ConcurrentHashMap throws recursive update exception
Here is my Java code:

```<code>static Map<BigInteger, Integer> cache = new ConcurrentHashMap<>();

static Integer minFinder(BigInteger num) {
        if (num.equals(BigInteger.ONE)) {
            return 0;
        }
        if (num.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO)) {
            //focus on stuff thats happening inside this block, since with given inputs it won't reach last return
            return 1 + cache.computeIfAbsent(num.divide(BigInteger.valueOf(2)),
                    n -> minFinder(n));
        }
        return 1 + Math.min(cache.computeIfAbsent(num.subtract(BigInteger.ONE), n -> minFinder(n)),
                cache.computeIfAbsent(num.add(BigInteger.ONE), n -> minFinder(n)));
    }
</code>```

I tried to memoize a function that returns a minimum number of actions such as division by 2, subtract by one or add one.
The problem I'm facing is when I call it with smaller inputs such as:

```<code>minFinder(new BigInteger("32"))
</code>```

it works, but with bigger values like:

```<code>minFinder(new BigInteger("64"))
</code>```

It throws a Recursive Update exception.
Is there any way to increase recursion size to prevent this exception or any other way to solve this?

答:
From the API docs of Map.computeIfAbsent():

The mapping function should not modify this map during computation.

The API docs of ConcurrentHashMap.computeIfAbsent() make that stronger:

The mapping function must not modify this map during computation.

(Emphasis added)

You are violating that by using your minFinder() method as the mapping function.  That it seems nevertheless to work for certain inputs is irrelevant.  You need to find a different way to achieve what you're after.

Is there any way to increase recursion size to prevent this exception or any other way to solve this?

You could avoid computeIfAbsent() and instead do the same thing the old-school way:

```<code>BigInteger halfNum = num.divide(BigInteger.valueOf(2));
BigInteger cachedValue = cache.get(halfNum);

if (cachedValue == null) {
    cachedValue = minFinder(halfNum);
    cache.put(halfNum, cachedValue);
}
return 1 + cachedValue;
</code>```

But that's not going to be sufficient if the computation loops.  You could perhaps detect that by putting a sentinel value into the map before you recurse, so that you can recognize loops.

Body:
Here is my Java code:

static Map<BigInteger, Integer> cache = new ConcurrentHashMap<>();

static Integer minFinder(BigInteger num) {
        if (num.equals(BigInteger.ONE)) {
            return 0;
        }
        if (num.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO)) {
            //focus on stuff thats happening inside this block, since with given inputs it won't reach last return
            return 1 + cache.computeIfAbsent(num.divide(BigInteger.valueOf(2)),
                    n -> minFinder(n));
        }
        return 1 + Math.min(cache.computeIfAbsent(num.subtract(BigInteger.ONE), n -> minFinder(n)),
                cache.computeIfAbsent(num.add(BigInteger.ONE), n -> minFinder(n)));
    }

I tried to memoize a function that returns a minimum number of actions such as division by 2, subtract by one or add one.
The problem I'm facing is when I call it with smaller inputs such as:

minFinder(new BigInteger("32"))

it works, but with bigger values like:

minFinder(new BigInteger("64"))

It throws a Recursive Update exception.
Is there any way to increase recursion size to prevent this exception or any other way to solve this?

Body:
From the API docs of Map.computeIfAbsent():

The mapping function should not modify this map during computation.

The API docs of ConcurrentHashMap.computeIfAbsent() make that stronger:

The mapping function must not modify this map during computation.

(Emphasis added)

You are violating that by using your minFinder() method as the mapping function.  That it seems nevertheless to work for certain inputs is irrelevant.  You need to find a different way to achieve what you're after.

Is there any way to increase recursion size to prevent this exception or any other way to solve this?

You could avoid computeIfAbsent() and instead do the same thing the old-school way:

BigInteger halfNum = num.divide(BigInteger.valueOf(2));
BigInteger cachedValue = cache.get(halfNum);

if (cachedValue == null) {
    cachedValue = minFinder(halfNum);
    cache.put(halfNum, cachedValue);
}
return 1 + cachedValue;

But that's not going to be sufficient if the computation loops.  You could perhaps detect that by putting a sentinel value into the map before you recurse, so that you can recognize loops.


问:
This version of selection sort I tried to make doesnot work properly, but it works surprisingly for larger arrays
I was doing selection sort yesterday. I wondered if I could replace the min and max values to begining and end of the unsorted array every time I iterated. I am just a beginner at programming, so its obvious that this wouldn't work. However, suprisingly, the code below does sort a larger array (~ 30k - 40k) in size. I experimented by generating random values from rand()%2000 and the function sorted the array successfully 28 times in 30 experiments.

But it can't sort something as simple as {4,2,3}
I think there's a bug somewhere, I couldn't figure it out so I've come here.

I'm also curious about the fact that it sorted such large arrays successfully. How?

```<code>int *zigzag_sort(int arr[])
{
    // loop through array
    // find min and max
    // replace min at begining and max at end
    // keep doing until sorted

    int f_idx = 0, l_idx = n-1;
    int min_pos, max_pos;

    while( f_idx < l_idx ) {
        min_pos = f_idx;
        max_pos = l_idx;

        for(int i = f_idx+1; i <= l_idx; i++)
        {
            if(arr[i] < arr[min_pos])
                min_pos = i;
            else if(arr[i] > arr[max_pos])
                max_pos = i;
        }
        swap(&arr[f_idx], &arr[min_pos]);
        swap(&arr[l_idx], &arr[max_pos]);

        f_idx++;
        l_idx--;
        }

    return arr;
}

</code>```
```<code>void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
</code>```

答:
Your swaps are not as simple as you think, and there is a hole in your position starting points going in to the inner loop iterations.

First, there are there situations that must be accounted after completing a segment enumeration and finding the segment min-index and max-index locations. They all deal with where you're reading data from, and where you'r'e trying to write it to. There can be partial, or in one case, full, overlap.

After each inner iteration, one of several conditions can transpire...

(min_pos == l_idx) && (max_pos == f_idx) . In other words, the minimum and maximum values are each in the places where the other wants to be. If that is the case ONE swap is needed (each other) and you're done for that iteration.

One of (min_pos == l_idx) or (max_pos == f_idx) is true, but not both. The order of the impending two swaps is important, depending on which of those conditions is true. In short, don't swap something into a slot that is about to be swapped again with the second swap. Ex: If the maximum value resides at the low target position, you need to swap it out to the maximum target position before the minimum value is swapped to the low target position. Otherwise you will dislocate something right after you put it home.

Neither of the above are true, in which case two swaps are still required, but order is irrelevant.

The probability of the special cases in (1) and (2) above increase significantly as you squeeze the iteration window down further and further during the outer loop iteration. For a random ordering, sooner or later it is going to happen.

Secondly, both the min_pos and max_pos starting points should be the same location in the segment, f_idx. It may not seem important, but it is so because the inner loop starts a f_idx+1. that means if the maximum value of the iteration was originally at f_idx you never accounted for it, will not discover it, etc.

The fixed routine is below, with notes where appropriate.

```<code>int *zigzag_sort(int arr[], int n)
{
    int f_idx = 0, l_idx = n - 1;

    while (f_idx < l_idx)
    {
        // both should start at the same location
        int min_pos = f_idx;
        int max_pos = f_idx;

        for (int i = f_idx + 1; i <= l_idx; i++)
        {
            if (arr[i] < arr[min_pos])
                min_pos = i;
            else if (arr[i] > arr[max_pos])
                max_pos = i;
        }

        if (max_pos == f_idx)
        {
            if (min_pos == l_idx)
            {
                // swap each other
                swap(&arr[max_pos], &arr[min_pos]);
            }
            else
            {   // swap the max out before overwritine with min
                swap(&arr[l_idx], &arr[max_pos]);
                swap(&arr[f_idx], &arr[min_pos]);
            }
        }
        else
        {   // also handle the case of l_idx == min_pos
            swap(&arr[f_idx], &arr[min_pos]);
            swap(&arr[l_idx], &arr[max_pos]);
        }

        f_idx++;
        l_idx--;
    }

    return arr;
}
</code>```

Body:
I was doing selection sort yesterday. I wondered if I could replace the min and max values to begining and end of the unsorted array every time I iterated. I am just a beginner at programming, so its obvious that this wouldn't work. However, suprisingly, the code below does sort a larger array (~ 30k - 40k) in size. I experimented by generating random values from rand()%2000 and the function sorted the array successfully 28 times in 30 experiments.

But it can't sort something as simple as {4,2,3}
I think there's a bug somewhere, I couldn't figure it out so I've come here.

I'm also curious about the fact that it sorted such large arrays successfully. How?

int *zigzag_sort(int arr[])
{
    // loop through array
    // find min and max
    // replace min at begining and max at end
    // keep doing until sorted

    int f_idx = 0, l_idx = n-1;
    int min_pos, max_pos;

    while( f_idx < l_idx ) {
        min_pos = f_idx;
        max_pos = l_idx;

        for(int i = f_idx+1; i <= l_idx; i++)
        {
            if(arr[i] < arr[min_pos])
                min_pos = i;
            else if(arr[i] > arr[max_pos])
                max_pos = i;
        }
        swap(&arr[f_idx], &arr[min_pos]);
        swap(&arr[l_idx], &arr[max_pos]);

        f_idx++;
        l_idx--;
        }

    return arr;
}

void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

Body:
Your swaps are not as simple as you think, and there is a hole in your position starting points going in to the inner loop iterations.

First, there are there situations that must be accounted after completing a segment enumeration and finding the segment min-index and max-index locations. They all deal with where you're reading data from, and where you'r'e trying to write it to. There can be partial, or in one case, full, overlap.

After each inner iteration, one of several conditions can transpire...

(min_pos == l_idx) && (max_pos == f_idx) . In other words, the minimum and maximum values are each in the places where the other wants to be. If that is the case ONE swap is needed (each other) and you're done for that iteration.

One of (min_pos == l_idx) or (max_pos == f_idx) is true, but not both. The order of the impending two swaps is important, depending on which of those conditions is true. In short, don't swap something into a slot that is about to be swapped again with the second swap. Ex: If the maximum value resides at the low target position, you need to swap it out to the maximum target position before the minimum value is swapped to the low target position. Otherwise you will dislocate something right after you put it home.

Neither of the above are true, in which case two swaps are still required, but order is irrelevant.

The probability of the special cases in (1) and (2) above increase significantly as you squeeze the iteration window down further and further during the outer loop iteration. For a random ordering, sooner or later it is going to happen.

Secondly, both the min_pos and max_pos starting points should be the same location in the segment, f_idx. It may not seem important, but it is so because the inner loop starts a f_idx+1. that means if the maximum value of the iteration was originally at f_idx you never accounted for it, will not discover it, etc.

The fixed routine is below, with notes where appropriate.

int *zigzag_sort(int arr[], int n)
{
    int f_idx = 0, l_idx = n - 1;

    while (f_idx < l_idx)
    {
        // both should start at the same location
        int min_pos = f_idx;
        int max_pos = f_idx;

        for (int i = f_idx + 1; i <= l_idx; i++)
        {
            if (arr[i] < arr[min_pos])
                min_pos = i;
            else if (arr[i] > arr[max_pos])
                max_pos = i;
        }

        if (max_pos == f_idx)
        {
            if (min_pos == l_idx)
            {
                // swap each other
                swap(&arr[max_pos], &arr[min_pos]);
            }
            else
            {   // swap the max out before overwritine with min
                swap(&arr[l_idx], &arr[max_pos]);
                swap(&arr[f_idx], &arr[min_pos]);
            }
        }
        else
        {   // also handle the case of l_idx == min_pos
            swap(&arr[f_idx], &arr[min_pos]);
            swap(&arr[l_idx], &arr[max_pos]);
        }

        f_idx++;
        l_idx--;
    }

    return arr;
}


问:
The program file specified in the launch configuration does not exist
I am facing some problems regarding eclipse for c/c++. I am trying to create a new project, I provide the code, and after running the code I get this error:

```<code>The program file specified in the launch configuration does not exist
C:\Users\elisabeth\workspace\mm\Debug\mm.exe not found
</code>```

Please notice that I am working with spice toolkit; I set the path for the "include" files and the libraries, but still I can not have a result.

What causes this error and how can I resolve it?

答:
I encountered similar issues and their related problems a few days ago. Finally, I found out that, just because I had moved my project folder (workspace folder of Eclipse) to another place so Eclipse could not find what its need as usual.

Solution: I just set the workspace to my new place (Hey Eclipse, my workspace now is here) :
Menu "File" -> "Switch workspace" -> "Other..." -> click "Browse..." button and point to new place then click "Select Folder" button and click "Launch" button.

Nice day.

ContentLicense: CC BY-SA 3.0

Body:
I am facing some problems regarding eclipse for c/c++. I am trying to create a new project, I provide the code, and after running the code I get this error:

The program file specified in the launch configuration does not exist
C:\Users\elisabeth\workspace\mm\Debug\mm.exe not found

Please notice that I am working with spice toolkit; I set the path for the "include" files and the libraries, but still I can not have a result.

What causes this error and how can I resolve it?


问:
How to remove multiple key:value pair within an array in groovy?
How to remove/delete key:value pair within a map in groovy?

My code:

```<code>data.each { val ->
   SKILLS = val.skills
   HOBBY = val.hobby
   VALUE = val
   NEW_MAP = VALUE - (SKILLS + HOBBY)
}
echo "${VALUE}"
echo "${NEW_MAP}"
</code>```

output in ${VALUE}, output in ${NEW_MAP} is null

```<code>[name: John, skills:[[singing:beginner, dancing:beginner], [java:competent, groovy:beginner]], hobby:[hiking, hockey]]
</code>```

I also tried this but it wont work:

```<code>def x = SKILLS + HOBBY
NEW_MAP = VALUE.minus(x)
NEW_MAP = VALUE.remove(x)
</code>```

I want to remove the entire skills and hobby. How can I do that?

答:
I would imagine your data is a json, similar to the following structure:

```<code>    {
        "data": [
            {
                "skill": [
                    {
                        "singing": "beginner",
                        "dancing": "beginner"
                    },
                    {
                        "java": "competent",
                        "groovy": "beginner"
                    }
                ],
                "hobby": [
                    "hiking",
                    "hockey"
                ]
            },
            {
                "skill": [
                    {
                        "singing": "beginner1",
                        "dancing": "beginner1"
                    },
                    {
                        "java": "competent1",
                        "groovy": "beginner1"
                    }
                ],
                "hobby": [
                    "hiking1",
                    "hockey1"
                ],
                "skill": [
                    {
                        "singing": "beginner2",
                        "dancing": "beginner2"
                    },
                    {
                        "java": "competent2",
                        "groovy": "beginner2"
                    }
                ],
                "hobby": [
                    "hiking2",
                    "hockey2"
                ]
            },
            {
                "skill": [
                    {
                        "singing": "beginner3",
                        "dancing": "beginner3"
                    },
                    {
                        "java": "competent3",
                        "groovy": "beginner3"
                    }
                ],
                "hobby": [
                    "hiking3",
                    "hockey3"
                ],
                "skill": [
                    {
                        "singing": "beginner4",
                        "dancing": "beginner4"
                    },
                    {
                        "java": "competent4",
                        "groovy": "beginner4"
                    }
                ],
                "hobby": [
                    "hiking4",
                    "hockey4"
                ]
            }
        ]
    }
]
</code>```

when you print the above on the console you have what you have pasted in your question.

[[data:[[skill:[[singing:beginner, dancing:beginner], [java:competent, groovy:beginner]], hobby:[hiking, hockey]], [skill:[[singing:beginner2, dancing:beginner2], [java:competent2, groovy:beginner2]], hobby:[hiking2, hockey2]], [skill:[[singing:beginner4, dancing:beginner4], [java:competent4, groovy:beginner4]], hobby:[hiking4, hockey4]]]]]

If I understand it correctly what you need, you can try something like the below. Where dataJson is the aforementioned json.

```<code>JsonSlurper js = new JsonSlurper()
def json = js.parseText(dataJson)
println(json)

def newArr = []
json.data[0].each { val ->
    def new_map = [:]
    new_map.SKILL = val.skill
    new_map.HOBBY = val.hobby
    def value = val

    newArr.add(new_map)
    println("\n" + "This is val: " + value)
    println("This is the map: " + new_map.SKILL + ", " + new_map.HOBBY)

}

println("\n\nThis is the newArr: " + newArr)
</code>```

Output:

```<code>[[data:[[skill:[[singing:beginner, dancing:beginner], [java:competent, groovy:beginner]], hobby:[hiking, hockey]], [skill:[[singing:beginner2, dancing:beginner2], [java:competent2, groovy:beginner2]], hobby:[hiking2, hockey2]], [skill:[[singing:beginner4, dancing:beginner4], [java:competent4, groovy:beginner4]], hobby:[hiking4, hockey4]]]]]

This is val: [skill:[[singing:beginner, dancing:beginner], [java:competent, groovy:beginner]], hobby:[hiking, hockey]]
This is the map: [SKILL:[[singing:beginner, dancing:beginner], [java:competent, groovy:beginner]], HOBBY:[hiking, hockey]]

This is val: [skill:[[singing:beginner2, dancing:beginner2], [java:competent2, groovy:beginner2]], hobby:[hiking2, hockey2]]
This is the map: [SKILL:[[singing:beginner2, dancing:beginner2], [java:competent2, groovy:beginner2]], HOBBY:[hiking2, hockey2]]

This is val: [skill:[[singing:beginner4, dancing:beginner4], [java:competent4, groovy:beginner4]], hobby:[hiking4, hockey4]]
This is the map: [SKILL:[[singing:beginner4, dancing:beginner4], [java:competent4, groovy:beginner4]], HOBBY:[hiking4, hockey4]]

This is the newArr: [[SKILL:[[singing:beginner, dancing:beginner], [java:competent, groovy:beginner]], HOBBY:[hiking, hockey]], [SKILL:[[singing:beginner2, dancing:beginner2], [java:competent2, groovy:beginner2]], HOBBY:[hiking2, hockey2]], [SKILL:[[singing:beginner4, dancing:beginner4], [java:competent4, groovy:beginner4]], HOBBY:[hiking4, hockey4]]]
</code>```

Body:
How to remove/delete key:value pair within a map in groovy?

My code:

data.each { val ->
   SKILLS = val.skills
   HOBBY = val.hobby
   VALUE = val
   NEW_MAP = VALUE - (SKILLS + HOBBY)
}
echo "${VALUE}"
echo "${NEW_MAP}"

output in ${VALUE}, output in ${NEW_MAP} is null

[name: John, skills:[[singing:beginner, dancing:beginner], [java:competent, groovy:beginner]], hobby:[hiking, hockey]]

I also tried this but it wont work:

def x = SKILLS + HOBBY
NEW_MAP = VALUE.minus(x)
NEW_MAP = VALUE.remove(x)

I want to remove the entire skills and hobby. How can I do that?

Body:
I would imagine your data is a json, similar to the following structure:

    {
        "data": [
            {
                "skill": [
                    {
                        "singing": "beginner",
                        "dancing": "beginner"
                    },
                    {
                        "java": "competent",
                        "groovy": "beginner"
                    }
                ],
                "hobby": [
                    "hiking",
                    "hockey"
                ]
            },
            {
                "skill": [
                    {
                        "singing": "beginner1",
                        "dancing": "beginner1"
                    },
                    {
                        "java": "competent1",
                        "groovy": "beginner1"
                    }
                ],
                "hobby": [
                    "hiking1",
                    "hockey1"
                ],
                "skill": [
                    {
                        "singing": "beginner2",
                        "dancing": "beginner2"
                    },
                    {
                        "java": "competent2",
                        "groovy": "beginner2"
                    }
                ],
                "hobby": [
                    "hiking2",
                    "hockey2"
                ]
            },
            {
                "skill": [
                    {
                        "singing": "beginner3",
                        "dancing": "beginner3"
                    },
                    {
                        "java": "competent3",
                        "groovy": "beginner3"
                    }
                ],
                "hobby": [
                    "hiking3",
                    "hockey3"
                ],
                "skill": [
                    {
                        "singing": "beginner4",
                        "dancing": "beginner4"
                    },
                    {
                        "java": "competent4",
                        "groovy": "beginner4"
                    }
                ],
                "hobby": [
                    "hiking4",
                    "hockey4"
                ]
            }
        ]
    }
]

when you print the above on the console you have what you have pasted in your question.

[[data:[[skill:[[singing:beginner, dancing:beginner], [java:competent, groovy:beginner]], hobby:[hiking, hockey]], [skill:[[singing:beginner2, dancing:beginner2], [java:competent2, groovy:beginner2]], hobby:[hiking2, hockey2]], [skill:[[singing:beginner4, dancing:beginner4], [java:competent4, groovy:beginner4]], hobby:[hiking4, hockey4]]]]]

If I understand it correctly what you need, you can try something like the below. Where dataJson is the aforementioned json.

JsonSlurper js = new JsonSlurper()
def json = js.parseText(dataJson)
println(json)

def newArr = []
json.data[0].each { val ->
    def new_map = [:]
    new_map.SKILL = val.skill
    new_map.HOBBY = val.hobby
    def value = val

    newArr.add(new_map)
    println("\n" + "This is val: " + value)
    println("This is the map: " + new_map.SKILL + ", " + new_map.HOBBY)

}

println("\n\nThis is the newArr: " + newArr)

Output:

[[data:[[skill:[[singing:beginner, dancing:beginner], [java:competent, groovy:beginner]], hobby:[hiking, hockey]], [skill:[[singing:beginner2, dancing:beginner2], [java:competent2, groovy:beginner2]], hobby:[hiking2, hockey2]], [skill:[[singing:beginner4, dancing:beginner4], [java:competent4, groovy:beginner4]], hobby:[hiking4, hockey4]]]]]

This is val: [skill:[[singing:beginner, dancing:beginner], [java:competent, groovy:beginner]], hobby:[hiking, hockey]]
This is the map: [SKILL:[[singing:beginner, dancing:beginner], [java:competent, groovy:beginner]], HOBBY:[hiking, hockey]]

This is val: [skill:[[singing:beginner2, dancing:beginner2], [java:competent2, groovy:beginner2]], hobby:[hiking2, hockey2]]
This is the map: [SKILL:[[singing:beginner2, dancing:beginner2], [java:competent2, groovy:beginner2]], HOBBY:[hiking2, hockey2]]

This is val: [skill:[[singing:beginner4, dancing:beginner4], [java:competent4, groovy:beginner4]], hobby:[hiking4, hockey4]]
This is the map: [SKILL:[[singing:beginner4, dancing:beginner4], [java:competent4, groovy:beginner4]], HOBBY:[hiking4, hockey4]]

This is the newArr: [[SKILL:[[singing:beginner, dancing:beginner], [java:competent, groovy:beginner]], HOBBY:[hiking, hockey]], [SKILL:[[singing:beginner2, dancing:beginner2], [java:competent2, groovy:beginner2]], HOBBY:[hiking2, hockey2]], [SKILL:[[singing:beginner4, dancing:beginner4], [java:competent4, groovy:beginner4]], HOBBY:[hiking4, hockey4]]]


问:
How to skip lines when reading a file with numpy.fromfile?
I am reading a .pksc file that contains coordinates and velocities of a large number of astronomical objects. I am doing the reading with

```<code>import numpy as np
f=open('halos_10x10.pksc')
data = np.fromfile(f,count=N*10,dtype=np.float32)
</code>```

The file can be found here. It is very large and I want to skip the first m objects (the first m lines corresponding to these objects, if there are lines in the file). How can I do this, I see nowhere an option for skipping? Optionally, it would be also nice to be able to skip the last k objects from the file. Tnx!

答:
If all you need is to chunk the big files into smaller files, so that you can operate on them independently:

import numpy as np

Nrecords_per_chunk = 100_000
Nitems_per_record = 10

f_in = open('halos_10x10.pksc', 'rb')
headers = np.fromfile(f_in, dtype=np.int32, count=3)

Nitems = Nrecords_per_chunk * Nitems_per_record

fnumber = 1
while True:
    items = np.fromfile(f_in, dtype=np.int32, count=Nitems)

    # Because at the end of the file, we're very likely to get less back than we asked for
    Nrecords_read = int(items.shape[0] / Nitems_per_record)

    # At End Of File: Weird luck, chunk_size was a perfect multiple of number of records
    if Nrecords_read == 0:
        break

    records = np.reshape(items, (Nrecords_read, Nitems_per_record))

    with open(f'halos_{fnumber}.pksc', 'wb') as f_out:
        # Keep same format by having 3 "header" items, each item's value is the record count
        new_headers = np.array([Nrecords_read]*3, dtype=np.int32)
        new_headers.tofile(f_out)
        records.tofile(f_out)

    # At End Of File
    if Nrecords_read < Nrecords_per_chunk:
        break

    fnumber += 1

f_in.close()

# Test that first 100_000 records from the main file match the records from the first chunked file

f_in = open('halos_10x10.pksc')
np.fromfile(f_in, dtype=np.int32, count=3)
Nitems = Nrecords_per_chunk * Nitems_per_record
items = np.fromfile(f_in, dtype=np.int32, count=Nitems)
records_orig = np.reshape(items, (Nrecords_per_chunk, Nitems_per_record))
f_in.close()

f_in = open('halos_1.pksc')
np.fromfile(f_in, dtype=np.int32, count=3)
Nitems = Nrecords_per_chunk * Nitems_per_record
items = np.fromfile(f_in, dtype=np.int32, count=Nitems)
records_chunked = np.reshape(items, (Nrecords_per_chunk, Nitems_per_record))
f_in.close()

assert np.array_equal(records_orig, records_chunked)
```

Body:
I am reading a .pksc file that contains coordinates and velocities of a large number of astronomical objects. I am doing the reading with

import numpy as np
f=open('halos_10x10.pksc')
data = np.fromfile(f,count=N*10,dtype=np.float32)

The file can be found here. It is very large and I want to skip the first m objects (the first m lines corresponding to these objects, if there are lines in the file). How can I do this, I see nowhere an option for skipping? Optionally, it would be also nice to be able to skip the last k objects from the file. Tnx!


问:
How to create icosohedral cluster in Lammps?
I know how to create cube, cylinder and sphere shapes in Lammps, but I don't know how to create an icosahedral cluster in Lammps.
Does anybody know about it?</p>

答:
I think you have to search the Lammps molecular topology.

https://docs.lammps.org/molecule.html

I would make custom groups of atoms/molecules with different bonds, angles...
In order to aproximate the cosahedral cluster.

Here is a piece of the molecule documentation:

```<code>N atoms = # of atoms N in molecule, default = 0

Nb bonds = # of bonds Nb in molecule, default = 0

Na angles = # of angles Na in molecule, default = 0

Nd dihedrals = # of dihedrals Nd in molecule, default = 0

Ni impropers = # of impropers Ni in molecule, default = 0

Nf fragments = # of fragments in molecule, default = 0

Mtotal mass = total mass of molecule

Xc Yc Zc com = coordinates of center-of-mass of molecule

Ixx Iyy Izz Ixy Ixz Iyz inertia = 6 components of inertia tensor of molecule
</code>```

I hope my info help you. I'm new at Lammps as well.

Body:
I think you have to search the Lammps molecular topology.

https://docs.lammps.org/molecule.html

I would make custom groups of atoms/molecules with different bonds, angles...
In order to aproximate the cosahedral cluster.

Here is a piece of the molecule documentation:

N atoms = # of atoms N in molecule, default = 0

Nb bonds = # of bonds Nb in molecule, default = 0

Na angles = # of angles Na in molecule, default = 0

Nd dihedrals = # of dihedrals Nd in molecule, default = 0

Ni impropers = # of impropers Ni in molecule, default = 0

Nf fragments = # of fragments in molecule, default = 0

Mtotal mass = total mass of molecule

Xc Yc Zc com = coordinates of center-of-mass of molecule

Ixx Iyy Izz Ixy Ixz Iyz inertia = 6 components of inertia tensor of molecule

I hope my info help you. I'm new at Lammps as well.


问:
I'm trying to get the value of the input to the label field in the QR generator code but not sure where I'm going wrong?
Trying to make a dynamic change along with the input that we type, there is a change in the input field .
Or
Once we submit the input, we get a change in the label?
How can we approach it? I am trying to pass the input value but something is wrong

$(document).ready(function(){

// $(".demo").qrcode({
//     text: 'https://www.jqueryscript.net'
//  });

var input = document.querySelector('.input');
var data = input.value;

  $(".demo").qrcode({

    // 0: normal
    // 1: label strip
    // 2: label box
    mode: 1,
    label: "{{name}}",
    fontname: 'sans',
    fontcolor: '#000'

  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://unpkg.com/browse/qrcode@1.2.0/build/qrcode.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
</head>
<body>

  <input type="text" class="input ng-model='name'">

<div class="demo">

</div>

</body>
</html></code>```

答:
You didn't link to the QR lib you are using (and AFAICT someone else's edit of your question confused things even more by linking to a different, wrong QR lib) which makes things harder.  My guess is you are using jQuery.qrcode.  For future reference you will make it easier for people to help you if you can clearly state what you are using, and create a minimal, complete, and verifiable example - working, complete code which demonstrates your problem.

Next problem is you are using an ancient version of jQuery (1.12.4).  Is there a reason for that?  Whatever the reason, jQuery.qrcode does not work with that version of jQuery.  I tried jQuery 3.3.1, the latest version Stackoverflow snippets list, but that doesn't work either.  Finally I checked the demo linked from the jQuery.qrcode home page, viewed that source, and found they are using 3.5.1.  And using that version in my snippet works!

So, now we finally have a working set of libraries, on to the actual question.

If you want to update the label dynamically, as you type, you'll need to add an event listener.  You could use the change() event, but for a text input that will fire only after you click away or hit enter - so you won't see live typing cause any updates.  If you want to see the label update live, as you type, keyup() is the way to go, and I've used that below.

Your handler just needs to

Get the current text;

Remove the old QR code, otherwise you end up with one for each keypress on the page;

Draw a new QR code with that new label;

Here's a working snippet - click Run to see it in action.

$(document).ready(function(){

    // The link "content" of the QR code, the actual message
    var text = 'https://stackoverflow.com/q/71073404/6089612';

    var demo = $('.demo');
    var input = $('.input');

    // Simple function to draw the QR code with the specified label
    function drawQR(label) {
        $(".demo").qrcode({
            mode: 1,
            label: label,
            text: text,
            fontname: 'sans',
            fontcolor: '#000'
        });
    }

    // Define an event handler that will fire every time a key is typed
    // in your input
    input.on('keyup', function() {

        // First get the current label text
        var label = $(this).val();

        // Now remove the existing QR code by emptying the div content
        demo.html('');

        // Finally redraw the QR with our new label
        drawQR(label);
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lrsjng.jquery-qrcode/0.18.0/jquery-qrcode.min.js"></script>

Label: <input type="text" class="input ng-model='name'">

<div class="demo"></div></code>```

Body:
Trying to make a dynamic change along with the input that we type, there is a change in the input field .
Or
Once we submit the input, we get a change in the label?
How can we approach it? I am trying to pass the input value but something is wrong

$(document).ready(function(){

// $(".demo").qrcode({
//     text: 'https://www.jqueryscript.net'
//  });

var input = document.querySelector('.input');
var data = input.value;

  $(".demo").qrcode({

    // 0: normal
    // 1: label strip
    // 2: label box
    mode: 1,
    label: "{{name}}",
    fontname: 'sans',
    fontcolor: '#000'

  });

});

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

  <input type="text" class="input ng-model='name'">

Body:
You didn't link to the QR lib you are using (and AFAICT someone else's edit of your question confused things even more by linking to a different, wrong QR lib) which makes things harder.  My guess is you are using jQuery.qrcode.  For future reference you will make it easier for people to help you if you can clearly state what you are using, and create a minimal, complete, and verifiable example - working, complete code which demonstrates your problem.

Next problem is you are using an ancient version of jQuery (1.12.4).  Is there a reason for that?  Whatever the reason, jQuery.qrcode does not work with that version of jQuery.  I tried jQuery 3.3.1, the latest version Stackoverflow snippets list, but that doesn't work either.  Finally I checked the demo linked from the jQuery.qrcode home page, viewed that source, and found they are using 3.5.1.  And using that version in my snippet works!

So, now we finally have a working set of libraries, on to the actual question.

If you want to update the label dynamically, as you type, you'll need to add an event listener.  You could use the change() event, but for a text input that will fire only after you click away or hit enter - so you won't see live typing cause any updates.  If you want to see the label update live, as you type, keyup() is the way to go, and I've used that below.

Your handler just needs to

Get the current text;

Remove the old QR code, otherwise you end up with one for each keypress on the page;

Draw a new QR code with that new label;

Here's a working snippet - click Run to see it in action.

$(document).ready(function(){

    // The link "content" of the QR code, the actual message
    var text = 'https://stackoverflow.com/q/71073404/6089612';

    var demo = $('.demo');
    var input = $('.input');

    // Simple function to draw the QR code with the specified label
    function drawQR(label) {
        $(".demo").qrcode({
            mode: 1,
            label: label,
            text: text,
            fontname: 'sans',
            fontcolor: '#000'
        });
    }

    // Define an event handler that will fire every time a key is typed
    // in your input
    input.on('keyup', function() {

        // First get the current label text
        var label = $(this).val();

        // Now remove the existing QR code by emptying the div content
        demo.html('');

        // Finally redraw the QR with our new label
        drawQR(label);
    });
});

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lrsjng.jquery-qrcode/0.18.0/jquery-qrcode.min.js"></script>

Label: <input type="text" class="input ng-model='name'">

<div class="demo"></div>


问:
Adding RelativeLayout to existing app in kivy file
So what I am trying to achieve is:

```<code>class FirstWindow(Screen):
    layout=self.ids['second']
    lab1=Label(text="one",size_hint_x=.35)
    lab2=Label(text="two",size_hint_x=.35)
    layout.add_widget(lab1)
    layout.add_widget(lab2)
</code>```
```<code><FirstWindow>:
    BoxLayout:
        orientation: "vertical"
        size: root.width, root.height
        Image:
            source: "gui-background.jpg"
            size_hint: None, None
            size: root.size
            allow_stretch: True
            keep_ratio: False
            RelativeLayout:
                id: second
                cols:2
                size_hint:(0.5, 0.4)
                pos_hint:{'x':0, 'y': 0.6}
</code>```

I want to add both Labels to the RelativeLayout with id: second. The issue that code shows is:

How do I fix it?

答:
I resolved my problem with adding this entire stuff into a simple function

```<code>class FirstWindow(Screen):
    def abc(self):
        layout=self.ids['second']
        lab1=Label(text="one",size_hint_x=.35)
        lab2=Label(text="two",size_hint_x=.35)
        layout.add_widget(lab1)
        layout.add_widget(lab2)

</code>```

Then it's just calling it with a button.

```<code>Button:
    text: "click"
    on_press: root.abc()
</code>```

I read that it's problematic because self is an argument only available at function call time.

Body:
So what I am trying to achieve is:

class FirstWindow(Screen):
    layout=self.ids['second']
    lab1=Label(text="one",size_hint_x=.35)
    lab2=Label(text="two",size_hint_x=.35)
    layout.add_widget(lab1)
    layout.add_widget(lab2)

<FirstWindow>:
    BoxLayout:
        orientation: "vertical"
        size: root.width, root.height
        Image:
            source: "gui-background.jpg"
            size_hint: None, None
            size: root.size
            allow_stretch: True
            keep_ratio: False
            RelativeLayout:
                id: second
                cols:2
                size_hint:(0.5, 0.4)
                pos_hint:{'x':0, 'y': 0.6}

I want to add both Labels to the RelativeLayout with id: second. The issue that code shows is:

How do I fix it?

Body:
I resolved my problem with adding this entire stuff into a simple function

class FirstWindow(Screen):
    def abc(self):
        layout=self.ids['second']
        lab1=Label(text="one",size_hint_x=.35)
        lab2=Label(text="two",size_hint_x=.35)
        layout.add_widget(lab1)
        layout.add_widget(lab2)

Then it's just calling it with a button.

Button:
    text: "click"
    on_press: root.abc()

I read that it's problematic because self is an argument only available at function call time.


问:
Gmail like file upload with jQuery
I would like to upload files just like google mail does. I would want to use jQuery and PHP to do it is there anyway of getting the progressbar etc.?

Here I added a video of how google does it. http://dl.getdropbox.com/u/5910/Jing/2009-04-02_1948.swf

No flash, no perl or cgi please..

I guess I can live without the progressbar now I am actually searching for information about jquery plugins or just what things I would need to look at

答:
The easiest would be to use SWFUpload, it's a small button written in Flash, with all the hooks to drive it in JS.  Very easy to use and works well with PHP

but, if you really want it to be pure JS, you'll need some help from the server.  specifically, you'll need to start the upload, and periodically query the server about how's it going.  unfortunately, PHP upload handling doesn't get any notification until after the download finishes.  you'd have to replace it with something else.  there are a few pure JS uploaders that include sample Perl server code just because of that.

IOW: JS and PHP don't (fully) cut it.  either add flash to the client, or a better upload handler at the server.

OwnerDisplayName: Thomaschaaf

ContentLicense: CC BY-SA 2.5

Title: Gmail like file upload with jQuery

LastEditorDisplayName: Thomaschaaf

OwnerDisplayName: Javier


问:
Append an input's value in included form..PHP
I have several landing pages and the only difference in them is a hidden input's (referred_by_text) value. I would like to just make one form and include it in all the landing pages....how would I go about setting the value for the input on each landing page for that value?

In the landing page this:

```<code><?php include("includes/lp_form.php");?>
</code>```

In the included form:

```<code><input type="hidden" name="referred_by_text" value="" />
</code>```

I would like to set the value for "referred_by_text" in each landing page...not sure where to start, any help is much appreciated. Would it be best to do it as an variable or possibly in JS?

答:
In the include that contains the form with the hidden text field, you could set the value based on the page that is visited. For example, in the include file you can create an array of your landing pages and then

```<code>$landingPages = array('landingpage1' => 'referred_by_text_value', 'landingpage2' => 'referred_by_text_value', 'landingpage3' => 'referred_by_text_value');
$page = $_SERVER['PHP_SELF'];

if(array_key_exists($page, $landingPages)) {
     echo '<input type="hidden" name="referred_by_text" value="'.$landingPages[$page].'" />';
}
</code>```

This will put the value you want based on the array key into the hidden field.

Body:
I have several landing pages and the only difference in them is a hidden input's (referred_by_text) value. I would like to just make one form and include it in all the landing pages....how would I go about setting the value for the input on each landing page for that value?

In the landing page this:

<?php include("includes/lp_form.php");?>

In the included form:

<input type="hidden" name="referred_by_text" value="" />

I would like to set the value for "referred_by_text" in each landing page...not sure where to start, any help is much appreciated. Would it be best to do it as an variable or possibly in JS?

Body:
In the include that contains the form with the hidden text field, you could set the value based on the page that is visited. For example, in the include file you can create an array of your landing pages and then

$landingPages = array('landingpage1' => 'referred_by_text_value', 'landingpage2' => 'referred_by_text_value', 'landingpage3' => 'referred_by_text_value');
$page = $_SERVER['PHP_SELF'];

if(array_key_exists($page, $landingPages)) {
     echo '<input type="hidden" name="referred_by_text" value="'.$landingPages[$page].'" />';
}

This will put the value you want based on the array key into the hidden field.


问:
Why do I have changes not staged for commit after cloning a Git repository?
I am doing a group project and I am cloning the repository from GitHub to my local computer. I want to change the branch but it's asking me to to add the files first by git add myrepository, but I also have to git commit.

I don't want the commit to show up for cloning.

Why should I need to commit when clone?

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   BudgetAmazon.sln
        modified:   obj/BudgetAmazon.csproj.nuget.dgspec.json
        modified:   obj/BudgetAmazon.csproj.nuget.g.props
        modified:   obj/Debug/net6.0/BudgetAmazon.GeneratedMSBuildEditorConfig.editorconfig
        modified:   obj/Debug/net6.0/BudgetAmazon.assets.cache
        modified:   obj/Debug/net6.0/BudgetAmazon.csproj.AssemblyReference.cache
        modified:   obj/project.assets.json
        modified:   obj/project.nuget.cache

no changes added to commit (use "git add" and/or "git commit -a")
```
<pre class="lang-none prettyprint-override"><code>$ git checkout add_to_cart
error: Your local changes to the following files would be overwritten by checkout:
        Server/BudgetAmazon/BudgetAmazon/BudgetAmazon.sln
        Server/BudgetAmazon/BudgetAmazon/obj/BudgetAmazon.csproj.nuget.dgspec.json
        Server/BudgetAmazon/BudgetAmazon/obj/BudgetAmazon.csproj.nuget.g.props
        Server/BudgetAmazon/BudgetAmazon/obj/Debug/net6.0/BudgetAmazon.GeneratedMSBuildEditorConfig.editorconfig
        Server/BudgetAmazon/BudgetAmazon/obj/Debug/net6.0/BudgetAmazon.assets.cache
        Server/BudgetAmazon/BudgetAmazon/obj/Debug/net6.0/BudgetAmazon.csproj.AssemblyReference.cache
        Server/BudgetAmazon/BudgetAmazon/obj/project.assets.json
        Server/BudgetAmazon/BudgetAmazon/obj/project.nuget.cache
Please commit your changes or stash them before you switch branches.
</code>```

答:
If you mean that you run, e.g.:

$ git clone https://github.com/git/git.git
Cloning into 'git'...
remote: Enumerating objects: 322336, done.
remote: Counting objects: 100% (1805/1805), done.
remote: Compressing objects: 100% (871/871), done.
remote: Total 322336 (delta 1161), reused 1380 (delta 932), pack-reused 320531
Receiving objects: 100% (322336/322336), 183.59 MiB | 4.20 MiB/s, done.
Resolving deltas: 100% (240649/240649), done.
$ cd git
$ git status
```

for instance, and this git status produces the kind of messages you're showing above, that tells us one or both of two things, which amount to "the source repository you're cloning is Evil":

the repository you're cloning has files named a/b/c.ext and a/B/c.ext or a/b/C.EXT in it, and your system cannot handle this; and/or

the repository you're cloning has, stored in it, files with literal CR-LF line endings, and you're on Windows and have configured core.autocrlf to true.

The amount of evil represented by these two bullet points is small:

Mixed-case mixed-use files like this work just fine on Linux (typically), but (typically) not on Windows or macOS.  So anyone who does this has set up Windows and macOS users for failure.  Why did they do that?  Presumably, because they are evil, or at least devilish imps.

Git in general is not a substitute for file-format (storage format, including UTF-8 vs UTF-16, and line-ending-style) management.  However, Git does have some minimal, barely-serviceable facilities for handling some of these issues.  Some people use them misguidedly (evil by mistake), some people don't use them at all (not really evil at all but can result in a trap for you), and some people use them correctly (also not evil, and no trap for you as long as you set your system up correctly).

Which, if any, of these is the actual problem, I can't tell without access to the original repository (which I can then inspect on a Linux or similar system, which will show me what's really in it: viewing it on a Windows system, you'll see only the limited stuff that Windows can show you, unless you're a Git Expert).

Both generally require at least a little bit of cleanup of the original source repository.  That's the repository at the site (github.com or wherever) that you used to get your clone.  The problem is now in your clone too, because commits, once made, are entirely read-only, and your Git software copied all their commits so you have all of their problems.  They probably are not problems for them, but they are problems for you.  You can't force them to fix their problems.  You thus have three choices:

Ask / beg them to fix their problems.  If they do, your problems after cloning vanish.

Fix their problems for them.  This can be difficult, especially if they're not interested in your fixes, but with co-operation, perhaps you can get their problems fixed and get them to take the fixes.

Avoid their repository.  Don't clone it in the first place, or—if you need it—clone it once, fix it up, and from that point on in time, never talk with them again.

Fixing the problem(s)

The first step is to identify the problems.  Are they:

Line endings?  These are easier to fix; you can do this on a Windows system without any assistance.  See VonC's answer to Distributing git configuration with the code for instance.

File names?  To fix these, the easiest way is to find or build yourself a Linux system.  On Windows or MacOS, the easiest way to do that is with VirtualBox or other VM systems as powered by something like Vagrant.  Using the Linux system, clone the repository there, rename the files appropriately, commit, and push the fixed commit(s)—you may need to fix multiple branch tip commits—back to wherever they will go.

Once you have a corrected repository—whether that's your own private one (a "fork" on GitHub or other hosting sites for instance), or the original if the owners of the original repository will fix it or let you fix it—you can clone it without trouble.

Body:
I am doing a group project and I am cloning the repository from GitHub to my local computer. I want to change the branch but it's asking me to to add the files first by git add myrepository, but I also have to git commit.

I don't want the commit to show up for cloning.

Why should I need to commit when clone?

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   BudgetAmazon.sln
        modified:   obj/BudgetAmazon.csproj.nuget.dgspec.json
        modified:   obj/BudgetAmazon.csproj.nuget.g.props
        modified:   obj/Debug/net6.0/BudgetAmazon.GeneratedMSBuildEditorConfig.editorconfig
        modified:   obj/Debug/net6.0/BudgetAmazon.assets.cache
        modified:   obj/Debug/net6.0/BudgetAmazon.csproj.AssemblyReference.cache
        modified:   obj/project.assets.json
        modified:   obj/project.nuget.cache

no changes added to commit (use "git add" and/or "git commit -a")

$ git checkout add_to_cart
error: Your local changes to the following files would be overwritten by checkout:
        Server/BudgetAmazon/BudgetAmazon/BudgetAmazon.sln
        Server/BudgetAmazon/BudgetAmazon/obj/BudgetAmazon.csproj.nuget.dgspec.json
        Server/BudgetAmazon/BudgetAmazon/obj/BudgetAmazon.csproj.nuget.g.props
        Server/BudgetAmazon/BudgetAmazon/obj/Debug/net6.0/BudgetAmazon.GeneratedMSBuildEditorConfig.editorconfig
        Server/BudgetAmazon/BudgetAmazon/obj/Debug/net6.0/BudgetAmazon.assets.cache
        Server/BudgetAmazon/BudgetAmazon/obj/Debug/net6.0/BudgetAmazon.csproj.AssemblyReference.cache
        Server/BudgetAmazon/BudgetAmazon/obj/project.assets.json
        Server/BudgetAmazon/BudgetAmazon/obj/project.nuget.cache
Please commit your changes or stash them before you switch branches.

Body:
If you mean that you run, e.g.:

$ git clone https://github.com/git/git.git
Cloning into 'git'...
remote: Enumerating objects: 322336, done.
remote: Counting objects: 100% (1805/1805), done.
remote: Compressing objects: 100% (871/871), done.
remote: Total 322336 (delta 1161), reused 1380 (delta 932), pack-reused 320531
Receiving objects: 100% (322336/322336), 183.59 MiB | 4.20 MiB/s, done.
Resolving deltas: 100% (240649/240649), done.
$ cd git
$ git status

for instance, and this git status produces the kind of messages you're showing above, that tells us one or both of two things, which amount to "the source repository you're cloning is Evil":

the repository you're cloning has files named a/b/c.ext and a/B/c.ext or a/b/C.EXT in it, and your system cannot handle this; and/or

the repository you're cloning has, stored in it, files with literal CR-LF line endings, and you're on Windows and have configured core.autocrlf to true.

The amount of evil represented by these two bullet points is small:

Mixed-case mixed-use files like this work just fine on Linux (typically), but (typically) not on Windows or macOS.  So anyone who does this has set up Windows and macOS users for failure.  Why did they do that?  Presumably, because they are evil, or at least devilish imps.

Git in general is not a substitute for file-format (storage format, including UTF-8 vs UTF-16, and line-ending-style) management.  However, Git does have some minimal, barely-serviceable facilities for handling some of these issues.  Some people use them misguidedly (evil by mistake), some people don't use them at all (not really evil at all but can result in a trap for you), and some people use them correctly (also not evil, and no trap for you as long as you set your system up correctly).

Which, if any, of these is the actual problem, I can't tell without access to the original repository (which I can then inspect on a Linux or similar system, which will show me what's really in it: viewing it on a Windows system, you'll see only the limited stuff that Windows can show you, unless you're a Git Expert).

Both generally require at least a little bit of cleanup of the original source repository.  That's the repository at the site (github.com or wherever) that you used to get your clone.  The problem is now in your clone too, because commits, once made, are entirely read-only, and your Git software copied all their commits so you have all of their problems.  They probably are not problems for them, but they are problems for you.  You can't force them to fix their problems.  You thus have three choices:

Ask / beg them to fix their problems.  If they do, your problems after cloning vanish.

Fix their problems for them.  This can be difficult, especially if they're not interested in your fixes, but with co-operation, perhaps you can get their problems fixed and get them to take the fixes.

Avoid their repository.  Don't clone it in the first place, or—if you need it—clone it once, fix it up, and from that point on in time, never talk with them again.

Fixing the problem(s)

The first step is to identify the problems.  Are they:

Line endings?  These are easier to fix; you can do this on a Windows system without any assistance.  See VonC's answer to Distributing git configuration with the code for instance.

File names?  To fix these, the easiest way is to find or build yourself a Linux system.  On Windows or MacOS, the easiest way to do that is with VirtualBox or other VM systems as powered by something like Vagrant.  Using the Linux system, clone the repository there, rename the files appropriately, commit, and push the fixed commit(s)—you may need to fix multiple branch tip commits—back to wherever they will go.

Once you have a corrected repository—whether that's your own private one (a "fork" on GitHub or other hosting sites for instance), or the original if the owners of the original repository will fix it or let you fix it—you can clone it without trouble.


问:
Convert milliseconds to Time without losing precision
Time.current gives me precision beyond seconds:

```<code>> Time.current
Fri, 11 Feb 2022 23:00:18.253185000 UTC +00:00
> Time.current.to_f
1644620430.942064
</code>```

But Time.at loses the precision :(

```<code>> Time.at(1644620430.942064).utc
2022-02-11 23:00:30 UTC
</code>```

The whole .942064 got truncated. This is messing with some tests that compare dates, because timestamps seem to save with the milliseconds, but I don't know how to create a Time that includes milliseconds

How can I cast a variable of milliseconds into a Time?

答:
As I understand you need nanoseconds precision

Time::at has such form

```<code>time = Time.current
# => Fri, 11 Feb 2022 23:36:25.983398537 UTC +00:00

float_time = time.to_f
# => 1644622585.9833987

secs = float_time.floor
# => 1644622585

nsecs = time.nsec
# => 983398537

Time.at(secs, nsecs, :nsec).utc
# => 2022-02-11 23:36:25.983398537 UTC
</code>```

You can choose precision using one of these keys:

:msec is the number of milliseconds (Integer, Float, or Rational) in the range 0..1000

:usec is the number of microseconds (Integer, Float, or Rational) in the range 0..1000000

:nsec key is the number of nanoseconds (Integer, Float, or Rational) in the range 0..1000000000

You can also just call utc on Time.current

```<code>time = Time.current
# => Fri, 11 Feb 2022 23:36:25.983398537 UTC +00:00

time.utc
# => 2022-02-11 23:36:25.983398537 UTC
</code>```

Body:
Time.current gives me precision beyond seconds:

> Time.current
Fri, 11 Feb 2022 23:00:18.253185000 UTC +00:00
> Time.current.to_f
1644620430.942064

But Time.at loses the precision :(

> Time.at(1644620430.942064).utc
2022-02-11 23:00:30 UTC

The whole .942064 got truncated. This is messing with some tests that compare dates, because timestamps seem to save with the milliseconds, but I don't know how to create a Time that includes milliseconds

How can I cast a variable of milliseconds into a Time?

Body:
As I understand you need nanoseconds precision

Time::at has such form

time = Time.current
# => Fri, 11 Feb 2022 23:36:25.983398537 UTC +00:00

float_time = time.to_f
# => 1644622585.9833987

secs = float_time.floor
# => 1644622585

nsecs = time.nsec
# => 983398537

Time.at(secs, nsecs, :nsec).utc
# => 2022-02-11 23:36:25.983398537 UTC

You can choose precision using one of these keys:

:msec is the number of milliseconds (Integer, Float, or Rational) in the range 0..1000

:usec is the number of microseconds (Integer, Float, or Rational) in the range 0..1000000

:nsec key is the number of nanoseconds (Integer, Float, or Rational) in the range 0..1000000000

You can also just call utc on Time.current

time = Time.current
# => Fri, 11 Feb 2022 23:36:25.983398537 UTC +00:00

time.utc
# => 2022-02-11 23:36:25.983398537 UTC


问:
How to exclude properties from Swift Codable?
Swift's Encodable/Decodable protocols, released with Swift 4, make JSON (de)serialization quite pleasant. However, I have not yet found a way to have fine-grained control over which properties should be encoded and which should get decoded.

I have noticed that excluding the property from the accompanying CodingKeys enum excludes the property from the process altogether, but is there a way to have more fine-grained control?

答:
Solution with custom property wrapper

```<code>struct Person: Codable {
    var firstName: String
    var lastName: String

    @CodableIgnored
    var nickname: String?
}
</code>```

Where CodableIgnored is

```<code>@propertyWrapper
public struct CodableIgnored<T>: Codable {
    public var wrappedValue: T?

    public init(wrappedValue: T?) {
        self.wrappedValue = wrappedValue
    }

    public init(from decoder: Decoder) throws {
        self.wrappedValue = nil
    }

    public func encode(to encoder: Encoder) throws {
        // Do nothing
    }
}

extension KeyedDecodingContainer {
    public func decode<T>(
        _ type: CodableIgnored<T>.Type,
        forKey key: Self.Key) throws -> CodableIgnored<T>
    {
        return CodableIgnored(wrappedValue: nil)
    }
}

extension KeyedEncodingContainer {
    public mutating func encode<T>(
        _ value: CodableIgnored<T>,
        forKey key: KeyedEncodingContainer<K>.Key) throws
    {
        // Do nothing
    }
}
</code>```

Body:
Solution with custom property wrapper

struct Person: Codable {
    var firstName: String
    var lastName: String

    @CodableIgnored
    var nickname: String?
}

Where CodableIgnored is

@propertyWrapper
public struct CodableIgnored<T>: Codable {
    public var wrappedValue: T?

    public init(wrappedValue: T?) {
        self.wrappedValue = wrappedValue
    }

    public init(from decoder: Decoder) throws {
        self.wrappedValue = nil
    }

    public func encode(to encoder: Encoder) throws {
        // Do nothing
    }
}

extension KeyedDecodingContainer {
    public func decode<T>(
        _ type: CodableIgnored<T>.Type,
        forKey key: Self.Key) throws -> CodableIgnored<T>
    {
        return CodableIgnored(wrappedValue: nil)
    }
}

extension KeyedEncodingContainer {
    public mutating func encode<T>(
        _ value: CodableIgnored<T>,
        forKey key: KeyedEncodingContainer<K>.Key) throws
    {
        // Do nothing
    }
}


问:
React-chartjs-2 gradient fill error on canvas context
I have a react-chart-js2 component that I am trying to make a gradient on the fill however I am getting a few different typescript errors and cant seem to get it working.

The documentation says to pass the data prop as a function with a reference to the canvas in order to access the canvas context to add the gradient. Unfortunately this is not working.

Here is a codesandbox of the files: https://codesandbox.io/s/modest-bird-j2in8 (file LineChartGradient.tsx)

The errors I get surround the Canvas Context and passing a data function to the chartjs  component

Data

```<code>const data = (canvas: HTMLCanvasElement) => {
    const ctx = canvas.getContext("2d");
    const gradient = ctx.createLinearGradient(0, 0, 0, 200);
    gradient.addColorStop(0, "rgba(250,174,50,1)");
    gradient.addColorStop(1, "rgba(250,174,50,0)");

    return {
      labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
      datasets: [
        {
          label: "First dataset",
          data: [33, 53, 85, 41, 44, 65],
          fill: "start",
          backgroundColor: "rgba(75,192,192,0.2)",
          borderColor: "rgba(75,192,192,1)"
        },
        {
          label: "Second dataset",
          data: [33, 25, 35, 51, 54, 76],
          fill: "start",
          borderColor: "#742774"
        }
      ]
    };
  };
</code>```

Component

```<code>  return (
    <div>
      <Line data={data} options={options} />
    </div>
  );
</code>```

Error #1

```<code>const gradient = ctx.createLinearGradient(0, 0, 0, 200);
</code>```

Typescript saying that this object could possible be null, this is fine I can check if it exists but it is my first clue that the canvas element is not being passed

Error #2

```<code><Line data={data} options={options} />
</code>```

Property 'datasets' is missing in type '(canvas: HTMLCanvasElement) => { labels: string[]; datasets:

When passing the data as a function I get this error however if I just drop the object that is returned by the data function inside the data prop the graph renders fine (See LineChart.tsx).

What is the correct way of accessing the canvas context in react-chartjs-2 to add a gradient fill?

答:
so it's look that there is a lot of errors with your code , i'm trying to help by solving the second problem , data should be json not a function so to solve this you should to execute the function before pass it like this :

<Line data={data()} options={options} />```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>
  export default function Chart(){
    return (
    <div>
    {
    /****
    pass data() not data
    ****/
    }
      <Line data={data()} options={options} />
    </div>
  );
  }</code>```

Body:
I have a react-chart-js2 component that I am trying to make a gradient on the fill however I am getting a few different typescript errors and cant seem to get it working.

The documentation says to pass the data prop as a function with a reference to the canvas in order to access the canvas context to add the gradient. Unfortunately this is not working.

Here is a codesandbox of the files: https://codesandbox.io/s/modest-bird-j2in8 (file LineChartGradient.tsx)

The errors I get surround the Canvas Context and passing a data function to the chartjs  component

Data

const data = (canvas: HTMLCanvasElement) => {
    const ctx = canvas.getContext("2d");
    const gradient = ctx.createLinearGradient(0, 0, 0, 200);
    gradient.addColorStop(0, "rgba(250,174,50,1)");
    gradient.addColorStop(1, "rgba(250,174,50,0)");

    return {
      labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
      datasets: [
        {
          label: "First dataset",
          data: [33, 53, 85, 41, 44, 65],
          fill: "start",
          backgroundColor: "rgba(75,192,192,0.2)",
          borderColor: "rgba(75,192,192,1)"
        },
        {
          label: "Second dataset",
          data: [33, 25, 35, 51, 54, 76],
          fill: "start",
          borderColor: "#742774"
        }
      ]
    };
  };

Component

  return (

      <Line data={data} options={options} />

  );

Error #1

const gradient = ctx.createLinearGradient(0, 0, 0, 200);

Typescript saying that this object could possible be null, this is fine I can check if it exists but it is my first clue that the canvas element is not being passed

Error #2

<Line data={data} options={options} />

Property 'datasets' is missing in type '(canvas: HTMLCanvasElement) => { labels: string[]; datasets:

When passing the data as a function I get this error however if I just drop the object that is returned by the data function inside the data prop the graph renders fine (See LineChart.tsx).

What is the correct way of accessing the canvas context in react-chartjs-2 to add a gradient fill?

Body:
so it's look that there is a lot of errors with your code , i'm trying to help by solving the second problem , data should be json not a function so to solve this you should to execute the function before pass it like this :

<Line data={data()} options={options} />

  export default function Chart(){
    return (
    <div>
    {
    /****
    pass data() not data
    ****/
    }
      <Line data={data()} options={options} />
    </div>
  );
  }


问:
Visual Studio 2019: "This site can’t provide a secure connection" on localhost
I've installed Visual Studio 2019 and uninstalled Visual Studio 2017.

Now if I start an ASP.NET (Core) site with https, it always say on Chrome:

This site can’t provide a secure connection

or on Edge

Can’t connect securely to this page

Screenshots:

Chrome:

Edge:

The URLs are correct. This also the same http://localhost:56784/ (it redirects to https)

Tried

What I've tried:

Updated Visual Studio 2019

Create a new ASP.NET Core 2 website

Tested with a ASP.NET site (non core)

Remove IIS certificates with MMC

Checking/changing the IIS settings in Visual Studio 2019 (project properties with context menu and project properties with F4)

Searching on Stackoverflow & Google ;)

Repair Visual Studio 2019

Issue

I think the issue is introduced by:

Installing Visual Studio 2019  and/or,

Uninstalling Visual Studio 2017  and/or,

Updating Windows 10 (current Version: 10.0.18362 Build 18362)

The underlining issue looks like a wrong/old/not supported TLS version?

Question

What can I do to diagnose/fix the problem?

答:
If you 'are using services.AddHttpsRedirection like

services.AddHttpsRedirection(options =>
{
    options.RedirectStatusCode = (int)HttpStatusCode.TemporaryRedirect;
    options.HttpsPort = Configuration.GetValue<int?>("https_port", null);
});
```

Make sure HttpsPort is null or a valid port in appsettings.json or appsettings.Development.json file.

Body:
If you 'are using services.AddHttpsRedirection like

services.AddHttpsRedirection(options =>
{
    options.RedirectStatusCode = (int)HttpStatusCode.TemporaryRedirect;
    options.HttpsPort = Configuration.GetValue<int?>("https_port", null);
});

Make sure HttpsPort is null or a valid port in appsettings.json or appsettings.Development.json file.


问:
Create and store objects in list Python
```<code>class Prog:

    def __init__(self, name, course, languange):
        self.name = name
        self.course = course
        self.languange = languange

    def show(self):
        print("Name:", self.name, "\nCourse:", self.course, "\nLanguage:", self.languange, "\n")

#Complete code

Students = []
#Create and store the students info (objects) in the list Students
number_of = int(input("Number of students?: "))
#Complete code
loop = 0
while loop < antal:
    print("Name, course language?") #here I want the user to type the name, course and what programming language he/she is studying

print("The following students are now in the system")
#Complete code
</code>```

I want the output to be:

Number of students?: 2
Name, course, language?
Alan
P1
Python

Name, course, language?
Jane
P2
Python

The following students are now in the system:
Name : Alan
Course : P1
Language : Python

Name : Jane
Course : P2
Language : Python
```
<p>I can't seem to give <code>self.name, self.course, self.language</code> the <code>input()</code> value in the list <code>Students = []</code></p>
<p>I did try to <code>.append</code>to the list but when I write  <code>p.Prog(Students)</code>I get this error message <code>TypeError: __init__() missing 2 required positional arguments: 'course' and 'languange'</code></p>
<p>This is the code I wrote to store values into the list.</p>
```Students = []
number_of = int(input("Number of students?: "))
loop = 0
while loop < number_of:
    print("Name, course, language?")
    name = input()
    course = input()
    language = input()
    loop += 1

p = Prog(Students)
print("Following students are now in the system.")
p.show()
```

答:
You need to append to Students.

When you call Prog(), you have to provide the 3 values that you just input as parameters. It's not clear why you thought the Students list would be the proper argument there.

Then when you want to list all the students, you have to loop through the Students list.

```<code>Students = []
number_of = int(input("Number of students?: "))
for _ in range(number_of):
    name = input('Name: ')
    course = input('Course: ')
    language = input('Language: ')
    p = Prog(name, course, language)
    Students.append(p)

print("Following students are now in the system.")
for student in Students:
    student.show()
</code>```

Title: Create and store objects in list Python

Body:
class Prog:

    def __init__(self, name, course, languange):
        self.name = name
        self.course = course
        self.languange = languange

    def show(self):
        print("Name:", self.name, "\nCourse:", self.course, "\nLanguage:", self.languange, "\n")

#Complete code

Students = []
#Create and store the students info (objects) in the list Students
number_of = int(input("Number of students?: "))
#Complete code
loop = 0
while loop < antal:
    print("Name, course language?") #here I want the user to type the name, course and what programming language he/she is studying

print("The following students are now in the system")
#Complete code

I want the output to be:

Number of students?: 2
Name, course, language?
Alan
P1
Python

Name, course, language?
Jane
P2
Python

The following students are now in the system:
Name : Alan
Course : P1
Language : Python

Name : Jane
Course : P2
Language : Python

I can't seem to give self.name, self.course, self.language the input() value in the list Students = []

I did try to .appendto the list but when I write  p.Prog(Students)I get this error message TypeError: __init__() missing 2 required positional arguments: 'course' and 'languange'

This is the code I wrote to store values into the list.

Students = []
number_of = int(input("Number of students?: "))
loop = 0
while loop < number_of:
    print("Name, course, language?")
    name = input()
    course = input()
    language = input()
    loop += 1

p = Prog(Students)
print("Following students are now in the system.")
p.show()

Body:
You need to append to Students.

When you call Prog(), you have to provide the 3 values that you just input as parameters. It's not clear why you thought the Students list would be the proper argument there.

Then when you want to list all the students, you have to loop through the Students list.

Students = []
number_of = int(input("Number of students?: "))
for _ in range(number_of):
    name = input('Name: ')
    course = input('Course: ')
    language = input('Language: ')
    p = Prog(name, course, language)
    Students.append(p)

print("Following students are now in the system.")
for student in Students:
    student.show()


问:
How to optimally divide an array into two subarrays so that sum of elements in both are same, otherwise give an error?
How to optimally divide an array into two subarrays so that sum of elements in both subarrays is same, otherwise give an error?

Example 1

Given the array

```<code>10,  20 , 30 , 5 , 40 , 50 , 40 , 15
</code>```

It can be divided as

```<code>10, 20, 30, 5, 40
</code>```

and

```<code>50, 40, 15
</code>```

Each subarray sums up to 105.

Example 2

```<code>10,  20,  30,  5,  40,  50,  40,  10
</code>```

The array cannot be divided into 2 arrays of an equal sum.

答:
Its O(n) time and O(n) space</p>
```<code>def equal_subarr(arr):
    n=len(arr)
    post_sum = [0] * (n- 1) + [arr[-1]]
    for i in range(n - 2, -1, -1):
        post_sum[i] = arr[i] + post_sum[i + 1]

    prefix_sum = [arr[0]] + [0] * (n - 1)
    for i in range(1, n):
        prefix_sum[i] = prefix_sum[i - 1] + arr[i]

    for i in range(n - 1):
        if prefix_sum[i] == post_sum[i + 1]:
            return [arr[:i+1],arr[i+1:]]
    return -1

arr=[10,  20 , 30 , 5 , 40 , 50 , 40 , 15]
print(equal_subarr(arr))
>>> [[10, 20, 30, 5, 40], [50, 40, 15]]

arr=[10,  20,  30,  5,  40,  50,  40,  10]
print(equal_subarr(arr))
>>> -1
</code>```

Body:
How to optimally divide an array into two subarrays so that sum of elements in both subarrays is same, otherwise give an error?

Example 1

Given the array

10,  20 , 30 , 5 , 40 , 50 , 40 , 15

It can be divided as

10, 20, 30, 5, 40

and

50, 40, 15

Each subarray sums up to 105.

Example 2

10,  20,  30,  5,  40,  50,  40,  10

The array cannot be divided into 2 arrays of an equal sum.

Body:
Its O(n) time and O(n) space

def equal_subarr(arr):
    n=len(arr)
    post_sum = [0] * (n- 1) + [arr[-1]]
    for i in range(n - 2, -1, -1):
        post_sum[i] = arr[i] + post_sum[i + 1]

    prefix_sum = [arr[0]] + [0] * (n - 1)
    for i in range(1, n):
        prefix_sum[i] = prefix_sum[i - 1] + arr[i]

    for i in range(n - 1):
        if prefix_sum[i] == post_sum[i + 1]:
            return [arr[:i+1],arr[i+1:]]
    return -1

arr=[10,  20 , 30 , 5 , 40 , 50 , 40 , 15]
print(equal_subarr(arr))
>>> [[10, 20, 30, 5, 40], [50, 40, 15]]

arr=[10,  20,  30,  5,  40,  50,  40,  10]
print(equal_subarr(arr))
>>> -1


问:
Remove duplicates with the same NAME and keep the one with a higher USER RATING COUNT. (python)
I have sorted a list of tuples by name, each tuple has the elements id, name, average_rating, rating_count, developers, and size.

I'm now trying to remove the duplicate name and only keep the one with the higher rating_count.

A snip of my sorted list of tuples

```<code>[(320469536, '4_IN_1_ROW_Lite', 2.5, 3593, 'AOBO Co.,Ltd', 7750656),
(299139129, '5x5 Shogi (MiniShogi) K55', 4.0, 16, 'Yoshikazu Kakinoki', 3940352),
(299139129, '5x5 Shogi (MiniShogi) K55', 4.0, 900, 'Yoshikazu Kakinoki', 3940352)
]
</code>```

I would like an output of

```<code>[(320469536, '4_IN_1_ROW_Lite', 2.5, 3593, 'AOBO Co.,Ltd', 7750656),
(299139129, '5x5 Shogi (MiniShogi) K55', 4.0, 900, 'Yoshikazu Kakinoki', 3940352)
]
</code>```

only keeping '5x5 Shogi (MiniShogi) K55' with the highest rating_count which is 900.

My take

```<code>    for i in range(len(list_of_games)):
        if list_of_games[i][1] == list_of_games[i+1][1] and \
                list_of_games[i][3] > list_of_games[i+1][3]:
            list_of_games.remove(list_of_games[i+1])
        elif list_of_games[i][1] == list_of_games[i+1][1] and \
                list_of_games[i][3] < list_of_games[i+1][3]:
            list_of_games.remove(list_of_games[i])
</code>```

But I got an out of range error

```<code>line 222, in main
    if list_of_games[i][1] == list_of_games[i+1][1] and \
IndexError: list index out of range
</code>```

May I know how do I solve this?

答:
Another solution, using itertools.groupby.

First, sort the list of games by id (ASC), average_rating (DESC) and then use groupby() to remove the duplicates:

from itertools import groupby

out = [
    next(g)
    for _, g in groupby(
        sorted(list_of_games, key=lambda g: (g[0], -g[3])), lambda g: g[0]
    )
]
print(out)
```
<p>Prints:</p>
<pre class="lang-py prettyprint-override"><code>[
    (299139129, '5x5 Shogi (MiniShogi) K55', 4.0, 900, 'Yoshikazu Kakinoki', 3940352),
    (320469536, '4_IN_1_ROW_Lite', 2.5, 3593, 'AOBO Co.,Ltd', 7750656)
]
</code>```

Body:
I have sorted a list of tuples by name, each tuple has the elements id, name, average_rating, rating_count, developers, and size.

I'm now trying to remove the duplicate name and only keep the one with the higher rating_count.

A snip of my sorted list of tuples

[(320469536, '4_IN_1_ROW_Lite', 2.5, 3593, 'AOBO Co.,Ltd', 7750656),
(299139129, '5x5 Shogi (MiniShogi) K55', 4.0, 16, 'Yoshikazu Kakinoki', 3940352),
(299139129, '5x5 Shogi (MiniShogi) K55', 4.0, 900, 'Yoshikazu Kakinoki', 3940352)
]

I would like an output of

[(320469536, '4_IN_1_ROW_Lite', 2.5, 3593, 'AOBO Co.,Ltd', 7750656),
(299139129, '5x5 Shogi (MiniShogi) K55', 4.0, 900, 'Yoshikazu Kakinoki', 3940352)
]

only keeping '5x5 Shogi (MiniShogi) K55' with the highest rating_count which is 900.

My take

    for i in range(len(list_of_games)):
        if list_of_games[i][1] == list_of_games[i+1][1] and \
                list_of_games[i][3] > list_of_games[i+1][3]:
            list_of_games.remove(list_of_games[i+1])
        elif list_of_games[i][1] == list_of_games[i+1][1] and \
                list_of_games[i][3] < list_of_games[i+1][3]:
            list_of_games.remove(list_of_games[i])

But I got an out of range error

line 222, in main
    if list_of_games[i][1] == list_of_games[i+1][1] and \
IndexError: list index out of range

May I know how do I solve this?

Body:
Another solution, using itertools.groupby.

First, sort the list of games by id (ASC), average_rating (DESC) and then use groupby() to remove the duplicates:

from itertools import groupby

out = [
    next(g)
    for _, g in groupby(
        sorted(list_of_games, key=lambda g: (g[0], -g[3])), lambda g: g[0]
    )
]
print(out)

Prints:

[
    (299139129, '5x5 Shogi (MiniShogi) K55', 4.0, 900, 'Yoshikazu Kakinoki', 3940352),
    (320469536, '4_IN_1_ROW_Lite', 2.5, 3593, 'AOBO Co.,Ltd', 7750656)
]


问:
Show numeric keyboard in iPhone using input text
Notice that using input type="number" can display a numeric keyboard as below:

Is it possible to use input type="text" to display the same numeric keyboard? I do not want to display a number pad using pattern="\d*" because it is possible that the value will contain a decimal place.

The reason I would like to use input type="text" instead of input type="number" is that I cannot get back the value if I input a non-number for a number field. For example, if I input ABC, it will become empty automatically. It seems to me that using input type="text" will be easier for this kind of control.

答:
I tested a few options on different iOS devices

The most supported way is to use the pattern attribute, e.g <input type="text" pattern="[0-9]*" />, since it works on several iOS versions:

Iphone 13 (iOS 15.1)

Iphone 8 (iOS 11.4)

Iphone 6 (iOS 8.1)

If you only need to support iOS 12.2+, using only the inputmode attribute works fine


问:
Is it possible to achieve desired permutation of values for vertices with adjacent swaps?
Consider an arbitrary connected (acyclic/cyclic) undirected graph with N Vertices, with vertex numbered from 1 to N. Each vertex has some value assigned to it. Let the values be denoted by A1, A2, A3, ... AN, where A[i] denotes value of ith vertex. Let P be a permutation of A. Each operation, we can swap values of two adjacent vertices. Is it possible to achieve A = P, i.e. after all swapping operation A[i] = P[i] for all 1 <= i <= N. In other words, each vertex i should have value P[i] after the operations.
P.S - I was confused about where to ask this - stack overflow or math.stack exchange. Apologies in advance.

Edit 1: I think the answer should be Yes. But I am only saying this on basis of case analysis of different types of graphs of 5 vertices. I tried to modify the permutation to Q where Q1 < Q2 < .. This changes a problem a bit that now final state should be A1 < A2 < A3... AN. So it can be said can the graph be sorted? Please correct me if my assumption is wrong.

答:
Indeed this is possible. Since we've got a connected graph, we can remove edges until you've got a tree. Removing an edge simply means we won't use it to do adjacent swaps in this case. "Removing a node" simply means we'll never swap the value of the node.

Now we can use the following algorithm to produce the permutation:

Choose a leaf and determine the position of the value intended to be located there after the permutation. Repeatedly swap the value with the next one on the path to the leaf until the value reaches the leaf.

Remove the leaf from the tree; the resulting graph still is a tree

Continue with 1., if there are any nodes left.

In each iteration we reduce the size of the graph by 1 by doing a number of swaps that can be bounded from above by the number of nodes, so with a finite number of swaps we're able to produce the premutation. The algorithm may not yield a solution using the optimum number of swaps, but it shows that it can be done.


答:
I'd do

```<code>for line in (cat ~/tmp/whale.txt); echo -e $line; end
</code>```

fish command substitutions return a list of lines, so with a for loop you're echoing each line.

Otherwise use sed to inject newlines into the text:

```<code>echo -e (sed 's/$/\\\\n/' ~/tmp/whale.txt)
</code>```

Title: I how can I make echo stop ignoring line breaks in fish

Body:
I am doing set catted (cat /home/blue/.ascii/whale.txt) && echo -e $catted

The contents of whale.txt are:

\e[34m\e[5m       .\e[0m
\e[34m\e[5m      ":"\e[0m
\e[36m    ___\e[34m\e[5m:\e[0m\e[36m____     |"\/"|\e[0m
\e[36m  ,'        `.    \  /\e[0m
\e[36m  |  O        \___/  |\e[0m
\e[97m\e[44m~^~^~^~^~^~^~^~^~^~^~^~^~\e[0m
\e[97m\e[44m~^~^~^~^~^~^~^~^~^~^~^~^~\e[0m
\e[97m\e[44m~^~^~^~^~^~^~^~^~^~^~^~^~\e[0m
\e[97m\e[44m~^~^~^~^~^~^~^~^~^~^~^~^~\e[0m
\e[97m\e[44m~^~^~^~^~^~^~^~^~^~^~^~^~\e[0m
\e[97m\e[44m~^~^~^~^~^~^~^~^~^~^~^~^~\e[0m
\e[97m\e[44m~^~^~^~^~^~^~^~^~^~^~^~^~\e[0m
\e[97m\e[44m~^~^~^~^~^~^~^~^~^~^~^~^~\e[0m
\e[97m\e[44m~^~^~^~^~^~^~^~^~^~^~^~^~\e[0m
\e[97m\e[44m~^~^~^~^~^~^~^~^~^~^~^~^~\e[0m
\e[97m\e[44m~^~^~^~^~^~^~^~^~^~^~^~^~\e[0m
\e[97m\e[44m~^~^~^~^~^~^~^~^~^~^~^~^~\e[0m

I need to retain newlines, show the color effects, and show the entire file. How can i do this with fish. Because I have read that you need echo -e "$(cat file.txt)" to show line breaks, but fish doesn't let you use the dollar sign operation.

Body:
I'd do

for line in (cat ~/tmp/whale.txt); echo -e $line; end

fish command substitutions return a list of lines, so with a for loop you're echoing each line.

Otherwise use sed to inject newlines into the text:

echo -e (sed 's/$/\\\\n/' ~/tmp/whale.txt)