问:
JQUERY: add a tiny arrow next to the following field on this form on focus
Im trying to express in Jquery the following:

I want to show a tiny arrow right next to the following input/select on the right side so every user knows where to go next.

To express the exact order im trying to make the users follow when completing the form im using numbers on the field name so you can understand the order.

Form: http://jsfiddle.net/yqh5V/1/

Please EXPAND the jsfiddle html so  u can properly display the form with the margins etc

Tiny green arrow: http://i53.tinypic.com/f1ystu.png

I cant do it without positioning the arrow to the right and not messing up the margins.

Is it clear what i want to do?

答:
This doable in jQuery. First define some css for your arrow, something like

```<code>        img.arrow{ position: absolute; }
</code>```

so when its added to the document it will not effect the spacing of your form. Then do something along these lines in jQuery

```<code>        var arrow = $('img.arrow');

        $('input').focus(function(){
             arrow.remove();
             $(this).traverseToNext('input').prepend(arrow);
        });
</code>```

TraverseToNext is not a real jQuery statement. If you need help getting jQuery to target your next input field, read up on traversing here http://api.jquery.com/category/traversing/. All you need to do is find a way to tell jQuery how to get to the next input from the current one. It should add the arrow image to just before the input field inside your

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

Cheers!

Body:
This doable in jQuery. First define some css for your arrow, something like

        img.arrow{ position: absolute; }

so when its added to the document it will not effect the spacing of your form. Then do something along these lines in jQuery

        var arrow = $('img.arrow');

        $('input').focus(function(){
             arrow.remove();
             $(this).traverseToNext('input').prepend(arrow);
        });

TraverseToNext is not a real jQuery statement. If you need help getting jQuery to target your next input field, read up on traversing here http://api.jquery.com/category/traversing/. All you need to do is find a way to tell jQuery how to get to the next input from the current one. It should add the arrow image to just before the input field inside your

        <div class="editor" />

Cheers!


来源: stackexchange

问:
How to store data to MariaDB at beforeEach method in Spring boot tests?
I cannot write data to db in @beforeEach as lifecycle methods are not transactional. How can I force data to commit? Data is stored in a transaction, but it is executed after the tearDown() method. By the way, I use MariaDB test container.</p>
```<code>@SpringBootTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@ContextConfiguration(initializers = TestConfigurations.Initializer.class,
        classes = {Application.class, TestConfigurations.class})
@Transactional(transactionManager = "transactionManager")
public class SomeTest {

    @Autowired
    private SomeRepository someRepository;

    @Nested
    class SomeNestedClass {

        @BeforeEach
        void setUp() {
            someRepository.saveAll(Fixtures.getSomeEntities());
        }

       @AfterEach
        public void tearDown() {
            someRepository.deleteAll();
        }
...
</code>```

答: Your test methods annotated with @Transactional will be rollback by default by Spring Test, so you can just initialize your data at the beginning of your test.</p>

ContentLicense: CC BY-SA 4.0

Body:
I cannot write data to db in @beforeEach as lifecycle methods are not transactional. How can I force data to commit? Data is stored in a transaction, but it is executed after the tearDown() method. By the way, I use MariaDB test container.

@SpringBootTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@ContextConfiguration(initializers = TestConfigurations.Initializer.class,
        classes = {Application.class, TestConfigurations.class})
@Transactional(transactionManager = "transactionManager")
public class SomeTest {

    @Autowired
    private SomeRepository someRepository;

    @Nested
    class SomeNestedClass {

        @BeforeEach
        void setUp() {
            someRepository.saveAll(Fixtures.getSomeEntities());
        }

       @AfterEach
        public void tearDown() {
            someRepository.deleteAll();
        }
...


问:
Register an Azure AD App Reg using New-AzADApplication PowerShell Module
I am trying to upgrade from using AzureAD PowerShell to Az PowerShell for registering an App Reg. Previously I would do:

```<code>$RequiredResourceAccess = New-Object -TypeName "Microsoft.Open.AzureAD.Model.RequiredResourceAccess"
$RequiredResourceAccess.ResourceAccess = New-Object System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.ResourceAccess]
$RequiredResourceAccess.ResourceAccess.Add($(New-Object -TypeName "Microsoft.Open.AzureAD.Model.ResourceAccess" -ArgumentList "37f7f235-527c-4136-accd-4a02d197296e","Scope"))
$RequiredResourceAccess.ResourceAccess.Add($(New-Object -TypeName "Microsoft.Open.AzureAD.Model.ResourceAccess" -ArgumentList "14dad69e-099b-42c9-810b-d002981feec1","Scope"))
$RequiredResourceAccess.ResourceAccess.Add($(New-Object -TypeName "Microsoft.Open.AzureAD.Model.ResourceAccess" -ArgumentList "df021288-bdef-4463-88db-98f22de89214","Role"))
$RequiredResourceAccess.ResourceAppId = "00000003-0000-0000-c000-000000000000"

New-AzureADApplication -RequiredResourceAccess $RequiredResourceAccess
</code>```

And I think I need to do this in Az PowerShell:

```<code>$RequiredResourceAccess = New-Object -TypeName "Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.MicrosoftGraphRequiredResourceAccess"
$RequiredResourceAccess.ResourceAccess = New-Object System.Collections.Generic.List[Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.MicrosoftGraphResourceAccess]
$RequiredResourceAccess.ResourceAccess.Add($(New-Object -TypeName "Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.MicrosoftGraphResourceAccess" -ArgumentList "37f7f235-527c-4136-accd-4a02d197296e","Scope"))
$RequiredResourceAccess.ResourceAccess.Add($(New-Object -TypeName "Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.MicrosoftGraphResourceAccess" -ArgumentList "14dad69e-099b-42c9-810b-d002981feec1","Scope"))
$RequiredResourceAccess.ResourceAccess.Add($(New-Object -TypeName "Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.MicrosoftGraphResourceAccess" -ArgumentList "df021288-bdef-4463-88db-98f22de89214","Role"))
$RequiredResourceAccess.ResourceAppId = "00000003-0000-0000-c000-000000000000"

New-AzADApplication -RequiredResourceAccess $RequiredResourceAccess
</code>```

But it keeps erroring with:

New-Object: Cannot find an overload for "MicrosoftGraphResourceAccess" and the argument count: "2".

Microsoft docs for this seems to be non-existent. Any help would be appreciated. Thanks

答:
Thanks for your comment. I eventually managed to find a solution using the following:</p>
```<code>$RequiredResourceAccess = @{
  ResourceAppId = "00000003-0000-0000-c000-000000000000";
  ResourceAccess = @(
      @{
          Id = "37f7f235-527c-4136-accd-4a02d197296e";
          Type = "Scope"
      },
      @{
          Id = "14dad69e-099b-42c9-810b-d002981feec1";
          Type = "Scope"
      },
      @{
          Id = "df021288-bdef-4463-88db-98f22de89214";
          Type = "Role"
      }
  )
}

New-AzADApplication -RequiredResourceAccess $RequiredResourceAccess
</code>```

Body:
I am trying to upgrade from using AzureAD PowerShell to Az PowerShell for registering an App Reg. Previously I would do:

$RequiredResourceAccess = New-Object -TypeName "Microsoft.Open.AzureAD.Model.RequiredResourceAccess"
$RequiredResourceAccess.ResourceAccess = New-Object System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.ResourceAccess]
$RequiredResourceAccess.ResourceAccess.Add($(New-Object -TypeName "Microsoft.Open.AzureAD.Model.ResourceAccess" -ArgumentList "37f7f235-527c-4136-accd-4a02d197296e","Scope"))
$RequiredResourceAccess.ResourceAccess.Add($(New-Object -TypeName "Microsoft.Open.AzureAD.Model.ResourceAccess" -ArgumentList "14dad69e-099b-42c9-810b-d002981feec1","Scope"))
$RequiredResourceAccess.ResourceAccess.Add($(New-Object -TypeName "Microsoft.Open.AzureAD.Model.ResourceAccess" -ArgumentList "df021288-bdef-4463-88db-98f22de89214","Role"))
$RequiredResourceAccess.ResourceAppId = "00000003-0000-0000-c000-000000000000"

New-AzureADApplication -RequiredResourceAccess $RequiredResourceAccess

And I think I need to do this in Az PowerShell:

$RequiredResourceAccess = New-Object -TypeName "Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.MicrosoftGraphRequiredResourceAccess"
$RequiredResourceAccess.ResourceAccess = New-Object System.Collections.Generic.List[Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.MicrosoftGraphResourceAccess]
$RequiredResourceAccess.ResourceAccess.Add($(New-Object -TypeName "Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.MicrosoftGraphResourceAccess" -ArgumentList "37f7f235-527c-4136-accd-4a02d197296e","Scope"))
$RequiredResourceAccess.ResourceAccess.Add($(New-Object -TypeName "Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.MicrosoftGraphResourceAccess" -ArgumentList "14dad69e-099b-42c9-810b-d002981feec1","Scope"))
$RequiredResourceAccess.ResourceAccess.Add($(New-Object -TypeName "Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.MicrosoftGraphResourceAccess" -ArgumentList "df021288-bdef-4463-88db-98f22de89214","Role"))
$RequiredResourceAccess.ResourceAppId = "00000003-0000-0000-c000-000000000000"

New-AzADApplication -RequiredResourceAccess $RequiredResourceAccess

But it keeps erroring with:

New-Object: Cannot find an overload for "MicrosoftGraphResourceAccess" and the argument count: "2".

Microsoft docs for this seems to be non-existent. Any help would be appreciated. Thanks

Body:
Thanks for your comment. I eventually managed to find a solution using the following:

$RequiredResourceAccess = @{
  ResourceAppId = "00000003-0000-0000-c000-000000000000";
  ResourceAccess = @(
      @{
          Id = "37f7f235-527c-4136-accd-4a02d197296e";
          Type = "Scope"
      },
      @{
          Id = "14dad69e-099b-42c9-810b-d002981feec1";
          Type = "Scope"
      },
      @{
          Id = "df021288-bdef-4463-88db-98f22de89214";
          Type = "Role"
      }
  )
}

New-AzADApplication -RequiredResourceAccess $RequiredResourceAccess


问:
Python with excel - Find duplicate rows, append corresponding columns and append some values to new column
Using python and an excel sheet: If I have column1 with a row of numbers and every three to four rows for column1 are duplicate. Column2 has each row with different values and value* is a key word followed by any random text (represented by a wild card for this example). Column3 is empty.

Column1
Column2
Column3

1234
value1, value*

1234
value2, value*

1234
value3

2222
value4, value*

2222
value5

using python how do I merge duplicates in column1 to show appended values in one row from column2
For example

1234 - value1, value2, value3, value*

2222 - value4, value5, value*

Then how do I use a wild card key word to take value3 and everything after and append to column 3 for that duplicate row.

```<code>1234 - |value1, value2| | value3* |
2222 - |value4, value5| | value3*|
</code>```

Looking for a library with built in functions that may do this with less lines of code. If you have a way to solve this without libraries please feel free to post your solution.

Thanks

答:
I'm not sure what you mean by not using libraries, but I assume you are able to use the CSV library that comes with Python to read/write the files.

Taking the first part only, and assuming that the order of "valueN" in a column does not matter, I would:

Read the file using the CSV library's DictReader to have access to the column names:

```<code>all_cell_1s = {}
for row in reader:
    key = row['Column1']
    values = row['Column2'].split(",")
    # You may need additional cleaning of whitespace etc. for the items:
    values = [v.strip() for v in values]
    # Get or create a new set() for the key.
    cell_1 = all_cell_1s.setdefault(key, set())
    cell_1.update(values)
</code>```

At this point, each entry in all_cell_1s contains the de-duplicated
content from Column1.

If the order does matter, then instead of using a set() use a dict() like this:

```<code>   # The value of `1` is arbitrary, we are only using a dict because it preserves order of keys.
   values = {v.strip(): 1 for v in values}
   cell_1 = all_cell_1s.setdefault(key, dict())
   cell_1.update(values)
</code>```

and now the keys of each entry in all_cell_1s is the de-duplicated content of Column1.

I'm not sure I understand your second question.

Body:
Using python and an excel sheet: If I have column1 with a row of numbers and every three to four rows for column1 are duplicate. Column2 has each row with different values and value* is a key word followed by any random text (represented by a wild card for this example). Column3 is empty.

Column1
Column2
Column3

1234
value1, value*

1234
value2, value*

1234
value3

2222
value4, value*

2222
value5

using python how do I merge duplicates in column1 to show appended values in one row from column2
For example

1234 - value1, value2, value3, value*

2222 - value4, value5, value*

Then how do I use a wild card key word to take value3 and everything after and append to column 3 for that duplicate row.

1234 - |value1, value2| | value3* |
2222 - |value4, value5| | value3*|

Looking for a library with built in functions that may do this with less lines of code. If you have a way to solve this without libraries please feel free to post your solution.

Thanks

Body:
I'm not sure what you mean by not using libraries, but I assume you are able to use the CSV library that comes with Python to read/write the files.

Taking the first part only, and assuming that the order of "valueN" in a column does not matter, I would:

Read the file using the CSV library's DictReader to have access to the column names:

all_cell_1s = {}
for row in reader:
    key = row['Column1']
    values = row['Column2'].split(",")
    # You may need additional cleaning of whitespace etc. for the items:
    values = [v.strip() for v in values]
    # Get or create a new set() for the key.
    cell_1 = all_cell_1s.setdefault(key, set())
    cell_1.update(values)

At this point, each entry in all_cell_1s contains the de-duplicated
content from Column1.

If the order does matter, then instead of using a set() use a dict() like this:

   # The value of `1` is arbitrary, we are only using a dict because it preserves order of keys.
   values = {v.strip(): 1 for v in values}
   cell_1 = all_cell_1s.setdefault(key, dict())
   cell_1.update(values)

and now the keys of each entry in all_cell_1s is the de-duplicated content of Column1.

I'm not sure I understand your second question.


问:
MSGraph OData filtering on empty collections
I'm using the MS powershell modules for working with MsGraph, but the same rules/principles apply when providing a filter as to what you'd normally just put into the http query string.

I have the following which works okay and lists all 365groups that are teams:

```<code>Get-MgGroup -Filter "resourceProvisioningOptions/Any(x:x eq 'Team')"
</code>```

What I would like to acheive, without having to pull ALL groups and then filtering locally, is basically the opposite of the above, something like this:

```<code>Get-MgGroup -Filter "resourceProvisioningOptions/Any(x:x ne 'Team')"
</code>```

But because I'm doing this against a collection, it throws.

```<code>Get-MgGroup_List: Unsupported property filter clause operator 'NotEqualsMatch'.
</code>```

Now I've tried every which way I an think of to get this to work, I've tried looking for a set of operators that would effectivly filter if resourceProvisioningOptions is null/empty as a collection. But nothing I try will work, I just seem to get errors. Anyone have any ideas?

Thanks,
Tom

答:
According to this resourceProvisioningOptions is not nullable and not filterable using null.

ne negation operators are supported only with advanced queries which means that you need to add -ConsistencyLevel "eventual" and -CountVariable or -CountVariable "<number>" (I'm not familiar with Graph API SDK for PowerShell) parameters

```<code>Get-MgGroup -Filter "resourceProvisioningOptions/Any(x:x ne 'Team')" -ConsistencyLevel "eventual" -CountVariable "100"
</code>```

Body:
I'm using the MS powershell modules for working with MsGraph, but the same rules/principles apply when providing a filter as to what you'd normally just put into the http query string.

I have the following which works okay and lists all 365groups that are teams:

Get-MgGroup -Filter "resourceProvisioningOptions/Any(x:x eq 'Team')"

What I would like to acheive, without having to pull ALL groups and then filtering locally, is basically the opposite of the above, something like this:

Get-MgGroup -Filter "resourceProvisioningOptions/Any(x:x ne 'Team')"

But because I'm doing this against a collection, it throws.

Get-MgGroup_List: Unsupported property filter clause operator 'NotEqualsMatch'.

Now I've tried every which way I an think of to get this to work, I've tried looking for a set of operators that would effectivly filter if resourceProvisioningOptions is null/empty as a collection. But nothing I try will work, I just seem to get errors. Anyone have any ideas?

Thanks,
Tom

Body:
According to this resourceProvisioningOptions is not nullable and not filterable using null.

ne negation operators are supported only with advanced queries which means that you need to add -ConsistencyLevel "eventual" and -CountVariable or -CountVariable "<number>" (I'm not familiar with Graph API SDK for PowerShell) parameters

Get-MgGroup -Filter "resourceProvisioningOptions/Any(x:x ne 'Team')" -ConsistencyLevel "eventual" -CountVariable "100"


问:
How can i make my navigation bar stick to the top of my screen with css
So i was creating a navigation bar for my website and it seems impossible to make it stick on the screen, its so confusing to me.

I followed Kevin Powell's tutorial on this but he didn't show how to make it stick to the top of the page.

Here is my HTML:

```<code>    <header>
        <div class="container">
            <h1 class="logo">Navigation</h1>

            <nav>
                <ul>
                    <li><a href="#">Home</a></li>
                    <li><a href="#">About us</a></li>
                    <li><a href="#">Contact us</a></li>
                </ul>
            </nav>
        </div>
    </header>
</code>```

And here is my CSS:

```<code>.container {
    width: 80%;
    margin: 0 auto;
}

header {
    background: rgb(155, 155, 155);
    border-radius: 0px 0px 25px 25px;
}

.logo {
    float: left;
    padding: 0px 0;
}
</code>```

I had to shrink the css code a bit but the ul is not really important here.

答:
Simply just add this to your header tag CSS:

header{
  position: fixed;
  top: 0;
}
```

Body:
So i was creating a navigation bar for my website and it seems impossible to make it stick on the screen, its so confusing to me.

I followed Kevin Powell's tutorial on this but he didn't show how to make it stick to the top of the page.

Here is my HTML:

Navigation

Home

About us

Contact us

And here is my CSS:

.container {
    width: 80%;
    margin: 0 auto;
}

header {
    background: rgb(155, 155, 155);
    border-radius: 0px 0px 25px 25px;
}

.logo {
    float: left;
    padding: 0px 0;
}

I had to shrink the css code a bit but the ul is not really important here.


问:
"Unable to import module 'lambda_function': cannot import name 'cygrpc' from 'grpc._cython' (/var/task/grpc/_cython/__init__.py)"
I am working on aws lambda function, i install the package but i got error

Unable to import module 'lambda_function': cannot import name 'cygrpc' from 'grpc._cython' (/var/task/grpc/_cython/init.py)

How to solve this type of error?

答: In addition to an answer marked correct I wanted to mention that for libraries using C-extensions is important that the layer was built on the same type of system as it runs in lambda. For example, if you're trying to build the layer including grpc on MacOS most likely it won't work since lambda is running on Linux. To make the layer working you have to build it in a Linux system (for example, on the virtual machine or in Docker)</p>


问:
How apply initial value of GridColumn -> GridColumnMenuFilter (Kendo React)?
I need to set the initial filter value inside GridColumnMenuFilter.

The problem: initial value applies to filter under title but not apply to filter inside GridColumnMenuFilter.

filter under the title with initial value

filter inside GridColumnMenuFilter without initial value

Code example:

```<code>const initialFilter: CompositeFilterDescriptor = {
    logic: "and",
    filters: [
      {
        field: "isAdmin",
        operator: "eq",
        value: true,
      },
    ],
  };

  const GridColumnMenu = (props: GridColumnMenuProps): JSX.Element => {
  return (
    <div>
      <GridColumnMenuFilter {...props} expanded={true} hideSecondFilter />
    </div>
  );
};

 const columnProps = (
  field: string
) => {
  return {
    field: field,
    columnMenu: GridColumnMenu
  };
};

  <Grid
        data={tableData.data}
        filterable={true}
        filter={initialFilter}
      >
    <GridColumn
       title={"Is Admin>"}
       {...columnProps("isAdmin")} />
    ...
 </Grid>
</code>```

Thanks for any help.

答:
The initial filter value must be like this:

```<code>const initialFilter: CompositeFilterDescriptor = {
filters: [
  {
    logic: "and",
    filters: [
      {
        field: "isAdmin",
        operator: "eq",
        value: true,
      },
    ],
  },
],
logic: "and",
</code>```

};

and then the filter will work fine inside GridColumnMenuFilter.

Body:
I need to set the initial filter value inside GridColumnMenuFilter.

The problem: initial value applies to filter under title but not apply to filter inside GridColumnMenuFilter.

filter under the title with initial value

filter inside GridColumnMenuFilter without initial value

Code example:

const initialFilter: CompositeFilterDescriptor = {
    logic: "and",
    filters: [
      {
        field: "isAdmin",
        operator: "eq",
        value: true,
      },
    ],
  };

  const GridColumnMenu = (props: GridColumnMenuProps): JSX.Element => {
  return (

      <GridColumnMenuFilter {...props} expanded={true} hideSecondFilter />

  );
};

 const columnProps = (
  field: string
) => {
  return {
    field: field,
    columnMenu: GridColumnMenu
  };
};

  <Grid
        data={tableData.data}
        filterable={true}
        filter={initialFilter}
      >
    <GridColumn
       title={"Is Admin>"}
       {...columnProps("isAdmin")} />
    ...
 </Grid>

Thanks for any help.

Body:
The initial filter value must be like this:

const initialFilter: CompositeFilterDescriptor = {
filters: [
  {
    logic: "and",
    filters: [
      {
        field: "isAdmin",
        operator: "eq",
        value: true,
      },
    ],
  },
],
logic: "and",

};

and then the filter will work fine inside GridColumnMenuFilter.


问:
Static method ‘buildBlock’ requires that ‘Text’ conform to ‘View’
I am trying to add SwiftUI in existing UIKit Project. I could not understand why I am getting this error. enter image description here</p>

答: I found a solution for these type of issues is accessing this way "SwiftUI.UIelement". This issue happens when we have existing class or struct with same name as the UI element we are using from SwiftUI. So by putting SWiftUI.UIElement we specify which UI element we are referring to.</p>


问:
Spring RestController catch all RequestMapping and continue to the correct endpoint
Say I have a @RestController like below:

```<code>@RestController
@RequestMapping("/1st")
public class MyController {
    @GetMapping("/2nd/aaa")
    public void getAaa() {
        ...
    }

    @GetMapping("/2nd/bbb")
    public void getBbb() {
        ...
    }
}
</code>```

I want to add methods to catch all requests with the base path "/1st" and "/1st/2nd" in between and then continue to the correct endpoint. I tried adding:

```<code>@GetMapping("/**")
public void doThisFirst() {
    ...
}
</code>```

But that didn't work, a request to "/1st/2nd/bbb" still only landed on the method getBbb() only. Please help, thank you.

答:
I want to add methods to catch all requests with the base path "/1st"
and "/1st/2nd" in between and then continue to the correct endpoint. I
tried adding:

@GetMapping("/**") public void doThisFirst() {
... }

Probably you want to execute some extra code (code in doThisFirst) before you execute the respecting code that each endpoint have.

There are 2 solutions here.

A) You define an aspect with @Before that will be executed before the code that your final endpoint has. Here is some example code

B) You define an interceptor which will be executed only before those 2 endpoints. Check here some previous SO answer.

Either the interceptor or the aspect should contain the code that you have in doThisFirst() and you want to execute before you reach the  actual endpoint.

In every case this starting code should not be inside a controller, so you can remove the @GetMapping("/**")  from the controller.

Body:
Say I have a @RestController like below:

@RestController
@RequestMapping("/1st")
public class MyController {
    @GetMapping("/2nd/aaa")
    public void getAaa() {
        ...
    }

    @GetMapping("/2nd/bbb")
    public void getBbb() {
        ...
    }
}

I want to add methods to catch all requests with the base path "/1st" and "/1st/2nd" in between and then continue to the correct endpoint. I tried adding:

@GetMapping("/**")
public void doThisFirst() {
    ...
}

But that didn't work, a request to "/1st/2nd/bbb" still only landed on the method getBbb() only. Please help, thank you.


答:
Your hunch to use lead/lag was on the right track, and we can try the following approach:

WITH cte AS (
    SELECT *, CASE WHEN TIMESTAMPDIFF(
                            minute,
                            LAG(session_time) OVER (PARTITION BY USERID
                                                    ORDER BY session_time),
                            session_time) > 30 THEN 1 ELSE 0 END AS flag
    FROM yourTable
)

SELECT USERID, SUM(flag) + 1 AS num_sessions
FROM cte
GROUP BY USERID
ORDER BY USERID;
```

Demo

The strategy here is to use LAG() to peak at the previous session time for each record, within each user group of records.  If we detect that more than 30 minutes has elapsed, we record a value of one.  Then, we can simply aggregate by user and sum the number of times a new session has begun.

Title: Counting number of sessions per user

Body:
I need to calculate the number of sessions (of activity) per user.  A session is defined as an ongoing activity that ends only when the following start timestamp is more than 30 minutes apart. Only the activity's start timestamp is available.

For example: User #1 has 3 sessions despite 5 timestamps - the 1st 3 count as one session as they  have been done with 30 minutes or less of each other.
User #2, #3 and #4 have 1 session each.

I think a lead function would help but don't know where to start.

-----------------------------------
| id      | timestamp
| 1       | 3/31/2021  9:00:00 AM |
+----------------------------------
| 1       | 3/31/2021  9:02:00 AM |
+----------------------------------
| 1       | 3/31/2021  9:32:00 AM |
+----------------------------------
| 1       | 3/31/2021  11:00:00 AM |
+---------------------------------
| 1       | 3/31/2021  3:00:00 PM |
+----------------------------------
| 2       |3/30/2021  11:55:00 PM |
+-----------------------------------
|2        |3/31/2021  12:02:00 AM |
+-----------------------------------
|3        |3/30/2021  11:00:00 AM |
+----------------------------------
|4        |3/30/2021  10:00:00 AM |
-----------------------------------

Body:
Your hunch to use lead/lag was on the right track, and we can try the following approach:

WITH cte AS (
    SELECT *, CASE WHEN TIMESTAMPDIFF(
                            minute,
                            LAG(session_time) OVER (PARTITION BY USERID
                                                    ORDER BY session_time),
                            session_time) > 30 THEN 1 ELSE 0 END AS flag
    FROM yourTable
)

SELECT USERID, SUM(flag) + 1 AS num_sessions
FROM cte
GROUP BY USERID
ORDER BY USERID;

Demo

The strategy here is to use LAG() to peak at the previous session time for each record, within each user group of records.  If we detect that more than 30 minutes has elapsed, we record a value of one.  Then, we can simply aggregate by user and sum the number of times a new session has begun.


问:
Elegant method to generate array of random dates within two dates
I have a datepicker where I show two months and I want to randomly choose 3 dates in each visible month

```<code>  $('.date').datepicker({
    minDate: new Date(),
    dateFormat: 'DD, MM, d, yy',
    constrainInput: true,
    beforeShowDay: processDates,
    numberOfMonths: 2,
    showButtonPanel: true,
    showOn: "button",
    buttonImage: "images/calendar_icon.jpg",
    buttonImageOnly: true
  });
</code>```

Here is my calculation

```<code>var now = new Date();
var nowTime = parseInt(now.getTime()/1000);
var randomDateSet = {};

function getRandomSet(y,m) {
  var monthIndex = "m"+y+""+m; // m20121 for Jan
  if (randomDateSet[monthIndex]) return randomDateSet[monthIndex];
  // generate here
.
. - I need this part
.
  return randomDateSet[monthIndex];
}

function processDay(date) { // this is calculated for each day so we need a singleton for the array
  var dateTime = parseInt(date.getTime()/1000);
  if (dateTime <= (nowTime-86400)) {
    return [false]; // earlier than today
  }
  var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
  var randomDates = getRandomSet(y,m);

  for (i = 0; i < randomDates.length; i++) {
    if($.inArray((m+1) + '-' + d + '-' + y,randomDates) != -1 || new Date() > date) {
      return [true,"highlight","Some message"];
    }
  }
  return [true,"normal"]; // ordinary day
}
</code>```

答:
From examples in date-fns

const result = eachDayOfInterval({
  start: new Date(2014, 9, 6),
  end: new Date(2014, 9, 10)
})
```

ContentLicense: CC BY-SA 3.0

Body:
I have a datepicker where I show two months and I want to randomly choose 3 dates in each visible month

  $('.date').datepicker({
    minDate: new Date(),
    dateFormat: 'DD, MM, d, yy',
    constrainInput: true,
    beforeShowDay: processDates,
    numberOfMonths: 2,
    showButtonPanel: true,
    showOn: "button",
    buttonImage: "images/calendar_icon.jpg",
    buttonImageOnly: true
  });

Here is my calculation

var now = new Date();
var nowTime = parseInt(now.getTime()/1000);
var randomDateSet = {};

function getRandomSet(y,m) {
  var monthIndex = "m"+y+""+m; // m20121 for Jan
  if (randomDateSet[monthIndex]) return randomDateSet[monthIndex];
  // generate here
.
. - I need this part
.
  return randomDateSet[monthIndex];
}

function processDay(date) { // this is calculated for each day so we need a singleton for the array
  var dateTime = parseInt(date.getTime()/1000);
  if (dateTime <= (nowTime-86400)) {
    return [false]; // earlier than today
  }
  var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
  var randomDates = getRandomSet(y,m);

  for (i = 0; i < randomDates.length; i++) {
    if($.inArray((m+1) + '-' + d + '-' + y,randomDates) != -1 || new Date() > date) {
      return [true,"highlight","Some message"];
    }
  }
  return [true,"normal"]; // ordinary day
}


问:
Find 5 letter words with 25 distinct characters
Solving wordle efficiently (for humans and for computers) is all the rage right now.

One particular way of solving a wordle made me curious. The idea is to select 5 words that have distinct letters so you'll end up with 25 characters. If you use these 5 words as your first 5 guesses in the game, you'll have a close to 100% chance of getting the correct word in your last guess (it's essentially an anagram of all the clues and you'll probably have a few green ones). There is a set of words that is suggested (all of the words are valid English words):

brick

glent

jumpy

vozhd

waqfs

But this made me wonder: How many of these 5 word combinations are out there and I started whipping up a recursive algorithm but I am close to giving up.

My initial thought was:

Start with the first word

reduce overlapping words from the word list

pick the next remaining word in the word list

Repeat with the next word

But this only really works if you have a set of five distinct words in order.

For this list:

brick

feast

glent

jumpy

vozhd

waqfs

I will end up with: [brick, feast, jumpy, vozhd] because feast comes before glent and will filter it out but in the end glent would have been the better pick.

I wasn't able to find any algorithms for this specific problem so I was wondering if there is any existing algorithm that can be applied to this?

答:
It's possible to brute-force this. For efficiency, one can discard all words with duplicate letters, and pre-process the words to use a bitmask of which letters they have (there are 26 letters, so this fits in a 32-bit unsigned integer).

Then just do a depth-first search, maintaining a list of words (bitmasks) that don't intersect with the words found so far.

I've written some go code that does this. It uses a shortened list of words that just contains the solution words (the full wordlist is too long to include here), but the code runs in a few seconds even with the full list.

Because it uses bitmasks to represent words, it's possible that there's multiple words with the same letters in the solution. The program shows those with a | inbetween. There's just one pair: cylix|xylic in the solution:

```<code>bling treck waqfs jumpy vozhd
pling treck waqfs jumby vozhd
brick glent waqfs jumpy vozhd
kreng clipt waqfs jumby vozhd
fjord chunk vibex gymps waltz
fjord gucks vibex nymph waltz
prick glent waqfs jumby vozhd
kempt brung waqfs cylix|xylic vozhd
blunk waqfs cimex grypt vozhd
clunk waqfs bemix grypt vozhd
</code>```

It can be run here: https://go.dev/play/p/wVEDjx3G1fE

```<code>package main

import (
    "fmt"
    "math/bits"
    "sort"
    "strings"
)

var allWords = []string{
    "bemix", "bling", "blunk", "brick", "brung", "chunk", "cimex", "clipt", "clunk", "cylix", "fjord", "glent", "grypt", "gucks", "gymps", "jumby", "jumpy", "kempt", "kreng", "nymph", "pling", "prick", "treck", "vibex", "vozhd", "waltz", "waqfs", "xylic",
}

func printSol(res []uint32, masks map[uint32][]string) {
    var b strings.Builder
    for i, r := range res {
        if i > 0 {
            b.WriteString(" ")
        }
        b.WriteString(strings.Join(masks[r], "|"))
    }
    fmt.Println(b.String())
}

func find5(w []uint32, mask uint32, n int, res []uint32, masks map[uint32][]string) {
    if n == 5 {
        printSol(res, masks)
        return
    }
    sub := []uint32{}
    for _, x := range w {
        if x&mask != 0 {
            continue
        }
        sub = append(sub, x)
    }
    for i, x := range sub {
        res[n] = x
        find5(sub[i+1:], mask|x, n+1, res, masks)
    }
}

func find5clique() {
    masks := map[uint32][]string{}
    for _, x := range allWords {
        m := uint32(0)
        for _, c := range x {
            m |= 1 << (c - 'a')
        }
        if bits.OnesCount32(m) == 5 {
            masks[m] = append(masks[m], x)
        }
    }
    maskSlice := []uint32{}
    for m := range masks {
        maskSlice = append(maskSlice, m)
    }
    sort.Slice(maskSlice, func(i, j int) bool {
        return maskSlice[i] < maskSlice[j]
    })
    find5(maskSlice, uint32(0), 0, make([]uint32, 5, 5), masks)
}

func main() {
    find5clique()
}
</code>```

Body:
It's possible to brute-force this. For efficiency, one can discard all words with duplicate letters, and pre-process the words to use a bitmask of which letters they have (there are 26 letters, so this fits in a 32-bit unsigned integer).

Then just do a depth-first search, maintaining a list of words (bitmasks) that don't intersect with the words found so far.

I've written some go code that does this. It uses a shortened list of words that just contains the solution words (the full wordlist is too long to include here), but the code runs in a few seconds even with the full list.

Because it uses bitmasks to represent words, it's possible that there's multiple words with the same letters in the solution. The program shows those with a | inbetween. There's just one pair: cylix|xylic in the solution:

bling treck waqfs jumpy vozhd
pling treck waqfs jumby vozhd
brick glent waqfs jumpy vozhd
kreng clipt waqfs jumby vozhd
fjord chunk vibex gymps waltz
fjord gucks vibex nymph waltz
prick glent waqfs jumby vozhd
kempt brung waqfs cylix|xylic vozhd
blunk waqfs cimex grypt vozhd
clunk waqfs bemix grypt vozhd

It can be run here: https://go.dev/play/p/wVEDjx3G1fE

package main

import (
    "fmt"
    "math/bits"
    "sort"
    "strings"
)

var allWords = []string{
    "bemix", "bling", "blunk", "brick", "brung", "chunk", "cimex", "clipt", "clunk", "cylix", "fjord", "glent", "grypt", "gucks", "gymps", "jumby", "jumpy", "kempt", "kreng", "nymph", "pling", "prick", "treck", "vibex", "vozhd", "waltz", "waqfs", "xylic",
}

func printSol(res []uint32, masks map[uint32][]string) {
    var b strings.Builder
    for i, r := range res {
        if i > 0 {
            b.WriteString(" ")
        }
        b.WriteString(strings.Join(masks[r], "|"))
    }
    fmt.Println(b.String())
}

func find5(w []uint32, mask uint32, n int, res []uint32, masks map[uint32][]string) {
    if n == 5 {
        printSol(res, masks)
        return
    }
    sub := []uint32{}
    for _, x := range w {
        if x&mask != 0 {
            continue
        }
        sub = append(sub, x)
    }
    for i, x := range sub {
        res[n] = x
        find5(sub[i+1:], mask|x, n+1, res, masks)
    }
}

func find5clique() {
    masks := map[uint32][]string{}
    for _, x := range allWords {
        m := uint32(0)
        for _, c := range x {
            m |= 1 << (c - 'a')
        }
        if bits.OnesCount32(m) == 5 {
            masks[m] = append(masks[m], x)
        }
    }
    maskSlice := []uint32{}
    for m := range masks {
        maskSlice = append(maskSlice, m)
    }
    sort.Slice(maskSlice, func(i, j int) bool {
        return maskSlice[i] < maskSlice[j]
    })
    find5(maskSlice, uint32(0), 0, make([]uint32, 5, 5), masks)
}

func main() {
    find5clique()
}


问:
Searching for a matching items in between two sets with "complex in" condition
Lets say I have two sets:

```<code>set1 = set(("a", "b", 5), ("a", "c", 3))
set2 = set(("a", "b", 3), ("a", "b", 7))
</code>```

Each item has 3 values:

first index (first part of the key) e.g. "a"

second index (second part of the key) e.g. "b"

third index (timestamp last part of the key) e.g 5

I want to search for all of the elements of set 1, that have the corresponding item in set2, where the corresponding item is any item that has the same value at both the first and second index, but the value of the timestamp of the matching item from the set2 must be lower than the timestamp of the item from the set1.

From the example the matching item would be:

("a", "b", 5) ("a", "b", 3) timestamp of 3 < 5

✓ ("a", "b", 5) ("a", "b", 7)

("a", "c", 3) ("a", "b", 3) "c" != "b"

("a", "c", 3) ("a", "b", 7) "c" != "b"

Now the problem is I need to search for the items in set2 in n.log(n) time. That is why I am trying to keep the values in the set. If I was looking for the items without the timestamp:

```<code>set1 = set(("a", "b"), ("a", "c"))
set2 = set(("a", "b"), ("a", "b"))
</code>```

I could do:

```<code>for item from set1:
  if item in set2:
    print("Found matching item")
</code>```

But with the timestamp, I can't figure out how to implement this without two for loops.

答:
Here's an O(n) solution with O(n) additional space to store the dict2 -

```<code>set1 = {("a", "b", 5), ("a", "c", 3)}
set2 = {("a", "b", 3), ("a", "b", 7)}

dict2 = {}
for item in set2:
    dict2[item[:2]] = max(dict2.get(item[:2], float('-inf')), item[2])

for item in set1:
    if dict2.get(item[0:2], float('-inf')) > item[2]:
        print("Found match")
        print("Match -", item, item[0:2] + (dict2.get(item[0:2]),))
</code>```

outputs -

```<code>Found match
Match - ('a', 'b', 5) ('a', 'b', 7)
</code>```

We create a new dict2 which stores the two keys and the max timestamp seen in the set2, and then we loop through items in set1 to see if for the same key if the max timestamp is larger than the timestamp in set1 for the same key.

Body:
Lets say I have two sets:

set1 = set(("a", "b", 5), ("a", "c", 3))
set2 = set(("a", "b", 3), ("a", "b", 7))

Each item has 3 values:

first index (first part of the key) e.g. "a"

second index (second part of the key) e.g. "b"

third index (timestamp last part of the key) e.g 5

I want to search for all of the elements of set 1, that have the corresponding item in set2, where the corresponding item is any item that has the same value at both the first and second index, but the value of the timestamp of the matching item from the set2 must be lower than the timestamp of the item from the set1.

From the example the matching item would be:

("a", "b", 5) ("a", "b", 3) timestamp of 3 < 5

✓ ("a", "b", 5) ("a", "b", 7)

("a", "c", 3) ("a", "b", 3) "c" != "b"

("a", "c", 3) ("a", "b", 7) "c" != "b"

Now the problem is I need to search for the items in set2 in n.log(n) time. That is why I am trying to keep the values in the set. If I was looking for the items without the timestamp:

set1 = set(("a", "b"), ("a", "c"))
set2 = set(("a", "b"), ("a", "b"))

I could do:

for item from set1:
  if item in set2:
    print("Found matching item")

But with the timestamp, I can't figure out how to implement this without two for loops.

Body:
Here's an O(n) solution with O(n) additional space to store the dict2 -

set1 = {("a", "b", 5), ("a", "c", 3)}
set2 = {("a", "b", 3), ("a", "b", 7)}

dict2 = {}
for item in set2:
    dict2[item[:2]] = max(dict2.get(item[:2], float('-inf')), item[2])

for item in set1:
    if dict2.get(item[0:2], float('-inf')) > item[2]:
        print("Found match")
        print("Match -", item, item[0:2] + (dict2.get(item[0:2]),))

outputs -

Found match
Match - ('a', 'b', 5) ('a', 'b', 7)

We create a new dict2 which stores the two keys and the max timestamp seen in the set2, and then we loop through items in set1 to see if for the same key if the max timestamp is larger than the timestamp in set1 for the same key.


问:
How to use the modal form data in the google apps script functions?
So, I got a google apps script, which is placed on my spreadsheet 'AllScripts'. I'm not the one who wants it like that, but it must be written in a separated spreadsheet.

On the spreadsheet 'wb1' apps scripts I'm importing the code from 'AllScripts' as a library, so I can call its methods on 'wb1'. Still on 'wb1', there is the onOpen method, which creates a menu and add an item with a method from 'AllScripts'. All good 'till here.

The minimal reproducible code is available on below spreadsheets.

These are the 'wb1' spreadsheet and 'AllScripts' spreadsheet, respectively:
https://docs.google.com/spreadsheets/d/1uQz8q1AE7vs9eJCajnIAPmQZRQgBoZv1mF9dcH9D_l8/edit?usp=sharing
https://docs.google.com/spreadsheets/d/1YaO18yRagzG4wA46AGnzn94CR6Vy6ENZcsbLZKN6OgM/edit?usp=sharing

Note that at first you won't see the menu and can't run any code, so on 'wb1' go to Extensions > Apps Script and then run the onOpen. It will ask you for permissions, and I don't know why, it will open a window with a security warning.

Anyways, when you open the modal from the menu Scripts > Test and write the asked stuffs, open your console on the browser and you should see something like this:
[![error][1]][1]

I don't know how to read that, but apparently the code from modal opened on 'wb1' cannot open a method from 'AllScripts'.

How can we overcome this?

These are some code from the script:

ShowForm.gs:

function showForm() {
  const form = HtmlService.createTemplateFromFile('Form').evaluate().setHeight(480);
  SpreadsheetApp.getUi().showModalDialog(form, 'Request Data Window');
}
```
<p>SaveData.gs:</p>
<pre class="lang-js prettyprint-override"><code>function saveData(data) {
  const iasRequestsSpreadsheet = SpreadsheetApp.openById('1uQz8q1AE7vs9eJCajnIAPmQZRQgBoZv1mF9dcH9D_l8');
  const sheet = iasRequestsSpreadsheet.getSheetByName('page1');

  const line = getFirstEmptyRow(sheet);

  // request date
  sheet.getRange(line, 1).setValue(new Date());

  // requested by
  sheet.getRange(line, 2).setValue(data.requestedBy);

  const currentWorkbook = SpreadsheetApp.getActiveSpreadsheet()
    .getName()
    .split('-')
    .trim();
  // product
  sheet.getRange(line, 3).setValue(currentWorkbook);

  const tabName = SpreadsheetApp.getActiveSheet().getName();
  // activity
  sheet.getRange(line, 4).setValue(`Do stuffs on ${tabName}`);

  // due date
  sheet.getRange(line, 6).setValue(data.dueDate);

  // status
  sheet.getRange(line, 8).setValue('Pending');

  // comments
  sheet.getRange(line, 9).setValue(data.comments);
}
</code>```

Form.html:
ps.: I removed the Materialize stuffs, so it can be easier to read as suggested by @Rubén.

<!DOCTYPE html>

      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

        <form>
            Requested By
            <input id="requestedBy" type="text" placeholder="John Doe">

            Due Date
            <input id="dueDate" class="datepicker">

            Comments
            <textarea id="comments" placeholder="Please ignore lines X, Y and Z..." class="materialize-textarea"></textarea>
            <button id="btn">
              Submit
            </button>
        </form>

```

答:
Try

in html

```<code>  function getData() {
    var data = document.forms[0]
    var tab = []
    for (var i=0;i<data.length;i++){
    if (data[i].type != "button"){
        tab.push(data[i].value)
      }
    }
    google.script.run.saveData(tab);
    // document.forms[0].reset()
  }
</code>```

in gs

```<code>function saveData(tab) {
  const iasRequestsSpreadsheet = SpreadsheetApp.openById('exampleid');
  const sheetName = iasRequestsSpreadsheet.getSheetByName('examplename');
  sheetName.getRange(1, 1,1,tab.length).setValues([tab]);
}
</code>```

Body:
So, I got a google apps script, which is placed on my spreadsheet 'AllScripts'. I'm not the one who wants it like that, but it must be written in a separated spreadsheet.

On the spreadsheet 'wb1' apps scripts I'm importing the code from 'AllScripts' as a library, so I can call its methods on 'wb1'. Still on 'wb1', there is the onOpen method, which creates a menu and add an item with a method from 'AllScripts'. All good 'till here.

The minimal reproducible code is available on below spreadsheets.

These are the 'wb1' spreadsheet and 'AllScripts' spreadsheet, respectively:
https://docs.google.com/spreadsheets/d/1uQz8q1AE7vs9eJCajnIAPmQZRQgBoZv1mF9dcH9D_l8/edit?usp=sharing
https://docs.google.com/spreadsheets/d/1YaO18yRagzG4wA46AGnzn94CR6Vy6ENZcsbLZKN6OgM/edit?usp=sharing

Note that at first you won't see the menu and can't run any code, so on 'wb1' go to Extensions > Apps Script and then run the onOpen. It will ask you for permissions, and I don't know why, it will open a window with a security warning.

Anyways, when you open the modal from the menu Scripts > Test and write the asked stuffs, open your console on the browser and you should see something like this:
[![error][1]][1]

I don't know how to read that, but apparently the code from modal opened on 'wb1' cannot open a method from 'AllScripts'.

How can we overcome this?

These are some code from the script:

ShowForm.gs:

function showForm() {
  const form = HtmlService.createTemplateFromFile('Form').evaluate().setHeight(480);
  SpreadsheetApp.getUi().showModalDialog(form, 'Request Data Window');
}

SaveData.gs:

function saveData(data) {
  const iasRequestsSpreadsheet = SpreadsheetApp.openById('1uQz8q1AE7vs9eJCajnIAPmQZRQgBoZv1mF9dcH9D_l8');
  const sheet = iasRequestsSpreadsheet.getSheetByName('page1');

  const line = getFirstEmptyRow(sheet);

  // request date
  sheet.getRange(line, 1).setValue(new Date());

  // requested by
  sheet.getRange(line, 2).setValue(data.requestedBy);

  const currentWorkbook = SpreadsheetApp.getActiveSpreadsheet()
    .getName()
    .split('-')
    .trim();
  // product
  sheet.getRange(line, 3).setValue(currentWorkbook);

  const tabName = SpreadsheetApp.getActiveSheet().getName();
  // activity
  sheet.getRange(line, 4).setValue(`Do stuffs on ${tabName}`);

  // due date
  sheet.getRange(line, 6).setValue(data.dueDate);

  // status
  sheet.getRange(line, 8).setValue('Pending');

  // comments
  sheet.getRange(line, 9).setValue(data.comments);
}

Form.html:
ps.: I removed the Materialize stuffs, so it can be easier to read as suggested by @Rubén.

<!DOCTYPE html>

      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

        <form>
            Requested By
            <input id="requestedBy" type="text" placeholder="John Doe">

            Due Date
            <input id="dueDate" class="datepicker">

            Comments
            <textarea id="comments" placeholder="Please ignore lines X, Y and Z..." class="materialize-textarea"></textarea>
            <button id="btn">
              Submit
            </button>
        </form>

Body:
Try

in html

  function getData() {
    var data = document.forms[0]
    var tab = []
    for (var i=0;i<data.length;i++){
    if (data[i].type != "button"){
        tab.push(data[i].value)
      }
    }
    google.script.run.saveData(tab);
    // document.forms[0].reset()
  }

in gs

function saveData(tab) {
  const iasRequestsSpreadsheet = SpreadsheetApp.openById('exampleid');
  const sheetName = iasRequestsSpreadsheet.getSheetByName('examplename');
  sheetName.getRange(1, 1,1,tab.length).setValues([tab]);
}


问:
Where to write begin rescue in Ruby (on Rails)
When I write ruby or (rails), where should I write begin
and rescue about http request (or just in general, where to write begin rescue)?

I'm talking about controller, model or module.

For example, I wrote codes like this.

module

```<code>module WhateverModule
  def get_list
    http, uri_path, headers = set_request("whatever_api_url")
    http.get(uri_path, headers)
  end

  #codes continue below

end
</code>```

then, I often time puts begin and rescue code at controller.

controller

```<code>begin
  api_list = get_list
rescue => exception
  # do whatever I need to do to handle exceptions
  p "exception happened!"
end
</code>```

but my PR reviewer keep saying "you should write a code like this"

module

```<code>module WhateverModule
  def get_list
    http, uri_path, headers = set_request("whatever_api_url")

    begin
      http.get(uri_path, headers)
    rescue => exception
      p "exception happend!"
    end
  end

  #codes continue below

end
</code>```

My question is, which one is right (or clean or better)?
Are there any general consensuses about where to put begin and rescue?

Thanks

答:
I would argue that when using rescue blocks it is a common pattern to follow two guidelines:

Put the rescue block only around the lowest number of lines possible. Usually, this should only be one line. That certainly depends on your code but in general, exceptions are raised by specific methods. The rescue block should only be around that block if possible. That makes debugging and refactoring much easier.

When adding a rescue block then name those exceptions that you expect to happen precisely. Otherwise you might catch errors that you didn't expect (syntax errors or method calls on nil). What again makes debugging much harder.

In your example, I agree with the PR reviewer but I would add the specific exceptions that might occur and that I want to handle. for example like this:

```<code>def get_list
  http, uri_path, headers = set_request("whatever_api_url")

  begin
    http.get(uri_path, headers)
  rescue Net::HTTPNotFound => e
    # handle page not found
  rescue Net::HTTPForbidden => e
    # handle invalid credentials
  rescue Net::HTTPServerError, Net::HTTPServerException
    # handle server error
  end
end
</code>```

Of cause, how to handle exceptions and if that is even possible depends on your application. And therefore there is no hard rule but only there guidelines.

Body:
When I write ruby or (rails), where should I write begin
and rescue about http request (or just in general, where to write begin rescue)?

I'm talking about controller, model or module.

For example, I wrote codes like this.

module

module WhateverModule
  def get_list
    http, uri_path, headers = set_request("whatever_api_url")
    http.get(uri_path, headers)
  end

  #codes continue below

end

then, I often time puts begin and rescue code at controller.

controller

begin
  api_list = get_list
rescue => exception
  # do whatever I need to do to handle exceptions
  p "exception happened!"
end

but my PR reviewer keep saying "you should write a code like this"

module

module WhateverModule
  def get_list
    http, uri_path, headers = set_request("whatever_api_url")

    begin
      http.get(uri_path, headers)
    rescue => exception
      p "exception happend!"
    end
  end

  #codes continue below

end

My question is, which one is right (or clean or better)?
Are there any general consensuses about where to put begin and rescue?

Thanks

Body:
I would argue that when using rescue blocks it is a common pattern to follow two guidelines:

Put the rescue block only around the lowest number of lines possible. Usually, this should only be one line. That certainly depends on your code but in general, exceptions are raised by specific methods. The rescue block should only be around that block if possible. That makes debugging and refactoring much easier.

When adding a rescue block then name those exceptions that you expect to happen precisely. Otherwise you might catch errors that you didn't expect (syntax errors or method calls on nil). What again makes debugging much harder.

In your example, I agree with the PR reviewer but I would add the specific exceptions that might occur and that I want to handle. for example like this:

def get_list
  http, uri_path, headers = set_request("whatever_api_url")

  begin
    http.get(uri_path, headers)
  rescue Net::HTTPNotFound => e
    # handle page not found
  rescue Net::HTTPForbidden => e
    # handle invalid credentials
  rescue Net::HTTPServerError, Net::HTTPServerException
    # handle server error
  end
end

Of cause, how to handle exceptions and if that is even possible depends on your application. And therefore there is no hard rule but only there guidelines.


问:
How to calculate coefficients of polynomial expansion in javascript
Suppose I have the following factors:

```<code>(1+3x)(1+x)(1+2x)
</code>```

Expanded to a polynomial, it looks like:

```<code>1 + 6x + 11x^2 + 6x^3
</code>```

The coefficients of this polynomial would be

```<code>c0 = 1
c1 = 6
c2 = 11
c3 = 6
</code>```

I'm trying to figure out how to calculate these rapidly (for any set of factors). The ideal output would be an array of the coefficients, like

```<code>var coeff = [c0,c1,c2,c3];
</code>```

What I'm trying to do is find a way to quickly go from the factors to the array of coefficients. Any suggestions on how to rapidly handle this in javascript? And for the sake of clarity, I'm trying to figure out how to do this for any set of n factors, not just this particular scenario.

答:
I needed something similar (to calculate permutations via exponential generating functions) so I wrote a version that works when some terms missing,  by using objects as the base instead. I also needed it not not calculate anything over a certain power, so that's also an option

/**
 * Calculates the result of multiplying many polynomials together
 * @example
 *   polynomials = [{0: 1, 1: 10, 2:1}, {0: 0, 1: 5, 2: 0, 3: 0.5}]
 *   limit = 4;
 *   polynomialMultiplication(polynomials, limit);
 * @param {Array.<Object.<number,number>>} polynomials an array of polynomials,
 * each expressed as an array of term coefficients
 * @param {number} limit the maximum term to calculate
 * @returns the resultant polynomial from multiplying all polynomials together
 */
function polynomialMultiplication(polynomials, limit) {
  const length = limit ?? polynomials.reduce((sum, poly) => sum += Math.max(...Object.keys(poly)), 0)
  // make an object to hold the result in
  // which is prepopulated by zeros
  const template = { ...Array.from({
      length
    }).fill(0)
  };
  return polynomials.reduce((memo, poly, polyIndex) => {
    const tempCopy = { ...template};
    if (polyIndex === 0) return { ...poly };
    for (let termIndex = 0; termIndex < length && termIndex <= Math.max(...Object.keys(poly)); termIndex++) {
      for (let memoIndex = 0;
        (memoIndex + termIndex) <= length && memoIndex <= Math.max(...Object.keys(memo)); memoIndex++) {
        const addition = (memo[memoIndex] ?? 0) * (poly[termIndex] ?? 0);
        const copyIndex = memoIndex + termIndex;
        tempCopy[copyIndex] = (tempCopy[copyIndex] ?? 0) + addition;
      }
    }
    return tempCopy;
  }, template)
}

console.log('(1+3x)(1+x)(1+2x)');
const polynomials = [{
  0: 1,
  1: 3
}, {
  0: 1,
  1: 1
}, {
  0: 1,
  1: 2
}];
console.log(polynomialMultiplication(polynomials));

const morePolynomials = [{
  0: 1,
  1: 0,
  2: 5
}, {
  0: 0,
  1: 6
}, {
  0: 1,
  1: 2,
  2: 0
}];
console.log('(1+5x^2)(6x)(1+2x) up to x^2')
console.log(polynomialMultiplication(morePolynomials, 2));```

Body:
Suppose I have the following factors:

(1+3x)(1+x)(1+2x)

Expanded to a polynomial, it looks like:

1 + 6x + 11x^2 + 6x^3

The coefficients of this polynomial would be

c0 = 1
c1 = 6
c2 = 11
c3 = 6

I'm trying to figure out how to calculate these rapidly (for any set of factors). The ideal output would be an array of the coefficients, like

var coeff = [c0,c1,c2,c3];

What I'm trying to do is find a way to quickly go from the factors to the array of coefficients. Any suggestions on how to rapidly handle this in javascript? And for the sake of clarity, I'm trying to figure out how to do this for any set of n factors, not just this particular scenario.


问:
Eclipse JDT: how to get data model for Java content assist
When writing Java code on Eclipse IDE, press Control + Space will pop up the content assist window.

For example, the content assist window for System. will list all the available fields and methods for class System.

I need to access the "data model" for the content assist window by code.

Using the above example, it is: given the class name System, how can I retrieve all the available fields and methods?

I spent some time on the source code of these three classes on grepcode.com:

```<code>org.eclipse.jdt.ui.text.java.JavaContentAssistInvocationContext
org.eclipse.jdt.internal.ui.text.java.JavaCompletionProposalComputer
org.eclipse.jdt.ui.text.java.CompletionProposalCollector
</code>```

It looks like the an ICompilationUnit instance is used to provide the fields and method names.

Then I don't understand how to generate the ICompilationUnit instance for a class in jre system library or third party library? Or if I didn't read the code in a correct way, then how did the program find fields and methods name? (I don't need to worry about the offset and UI stuff, just the "data model" part).

答:
You can use the Eclipse JDT Language Server, which is used by different editors already (e.g. Visual Studio Code, and EMACS):
https://github.com/eclipse/eclipse.jdt.ls

This way, you'll be able to provide many JDT features available in the LSP definition (e.g. code completions, references, diagnostics, etc.):
https://microsoft.github.io/language-server-protocol/specifications/specification-current/

There are bindings for Java available with LSP4J over Maven:

```<code><dependency>
    <groupId>org.eclipse.lsp4j</groupId>
    <artifactId>org.eclipse.lsp4j</artifactId>
    <version>0.12.0</version>
</dependency>
</code>```

A simple implementation might look like this:

ExpressionLanguageClient.java

```<code>import org.eclipse.lsp4j.MessageActionItem;
import org.eclipse.lsp4j.MessageParams;
import org.eclipse.lsp4j.PublishDiagnosticsParams;
import org.eclipse.lsp4j.ShowMessageRequestParams;
import org.eclipse.lsp4j.jsonrpc.services.JsonNotification;
import org.eclipse.lsp4j.services.LanguageClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CompletableFuture;

public class ExpressionLanguageClient implements LanguageClient {

    private final static Logger logger = LoggerFactory.getLogger(ExpressionLanguageClient.class);

    final private ExpressionCodeAssistantService expressionCodeAssistantService;

    public ExpressionLanguageClient(ExpressionCodeAssistantService expressionCodeAssistantService) {
        this.expressionCodeAssistantService = expressionCodeAssistantService;
    }

    @Override
    public void telemetryEvent(Object o) {
        // TODO
        logger.info("Expression LSP telemetry: " + o);
    }

    @Override
    public void publishDiagnostics(PublishDiagnosticsParams publishDiagnosticsParams) {
        // TODO
        logger.info("Expression LSP diagnostics: " + publishDiagnosticsParams);
    }

    @Override
    public void showMessage(MessageParams messageParams) {
        // TODO
        logger.info("Expression LSP show message: " + messageParams);
    }

    @Override
    public CompletableFuture<MessageActionItem> showMessageRequest(ShowMessageRequestParams showMessageRequestParams) {
        return null;
    }

    @Override
    public void logMessage(MessageParams messageParams) {
        expressionCodeAssistantService.lspLogMessage(messageParams.getMessage());
    }

    @JsonNotification("language/status")
    public void languageStatus(Object o) {
        // avoid unsupported notification warnings
    }
}
</code>```

CodeAssistantService.java

```<code>// start the Eclipse JDT LS required for the code assistant features
try {
    String[] command = new String[]{
            "java",
            "-Declipse.application=org.eclipse.jdt.ls.core.id1",
            "-Dosgi.bundles.defaultStartLevel=4",
            "-Declipse.product=org.eclipse.jdt.ls.core.product",
            "-Dlog.level=ALL",
            "-noverify",
            "-Xmx1G",
            "-jar",
            ".../eclipse.jdt.ls/org.eclipse.jdt.ls.product/target/repository/plugins/org.eclipse.equinox.launcher_1.6.400.v20210924-0641.jar",
            "-configuration",
            ".../eclipse.jdt.ls/org.eclipse.jdt.ls.product/target/repository/config_linux",
            "-data",
            "...",
            "--add-modules=ALL-SYSTEM",
            "--add-opens java.base/java.util=ALL-UNNAMED",
            "--add-opens java.base/java.lang=ALL-UNNAMED"
    };

    Process process = new ProcessBuilder(command)
            .redirectErrorStream(true)
            .start();

    ExpressionLanguageClient expressionLanguageClient = new ExpressionLanguageClient(this);

    launcher = LSPLauncher.createClientLauncher(
            expressionLanguageClient,
            process.getInputStream(),
            process.getOutputStream()
    );
    launcher.startListening();
} catch (Exception e) {
    logger.error("Could not start the language server", e);
}
</code>```

Be sure to customize the commands where necessary (paths and config_mac/linux/windows).

As soon as the language server is running (maybe listen for a log message), you need to call the init event (be sure to call from a separate thread, if you call it from the language client, because it would cause a deadlock otherwise):

```<code>InitializeParams initializeParams = new InitializeParams();
initializeParams.setProcessId(((int) ProcessHandle.current().pid()));

// workspace folders are read from the initialization options, not from the param
List<String> workspaceFolders = new ArrayList<>();
workspaceFolders.add("file:" + getTempDirectory());

Map<String, Object> initializationOptions = new HashMap<>();
initializationOptions.put("workspaceFolders", workspaceFolders);
initializeParams.setInitializationOptions(initializationOptions);

CompletableFuture<InitializeResult> init = launcher.getRemoteProxy().initialize(initializeParams);
try {
    init.get();
    logger.info("LSP initialized");
} catch (Exception e) {
    logger.error("Could not initialize LSP server", e);
}
</code>```

Now, you're able to get code completions like this:

```<code>TextDocumentItem textDocumentItem = new TextDocumentItem();
textDocumentItem.setText(isolatedCodeResult.getCode());
textDocumentItem.setUri("file:" + dummyFilePath);
textDocumentItem.setLanguageId("java");

DidOpenTextDocumentParams didOpenTextDocumentParams = new DidOpenTextDocumentParams();
didOpenTextDocumentParams.setTextDocument(textDocumentItem);
launcher.getRemoteProxy().getTextDocumentService().didOpen(didOpenTextDocumentParams);

TextDocumentIdentifier textDocumentIdentifier = new TextDocumentIdentifier();
textDocumentIdentifier.setUri("file:" + dummyFilePath);

CompletionParams completionParams = new CompletionParams();
completionParams.setPosition(new Position(line + lineOffset, column));
completionParams.setTextDocument(textDocumentIdentifier);

CompletableFuture<Either<List<CompletionItem>, CompletionList>> completion =
        launcher.getRemoteProxy().getTextDocumentService().completion(completionParams);

logger.info("Found completions: " + completion.get().getRight().getItems());
</code>```

Make sure, the dummyFilePath is a an existing java file. The content does not matter, but it needs to exist in order for the JDT LS to work.

I am not sure, whether it would be better to always sync the source files with the language server. Maybe this would be faster, especially for large projects. If you just need content assistant features for minor source files, the provided example should be sufficient.

Body:
When writing Java code on Eclipse IDE, press Control + Space will pop up the content assist window.

For example, the content assist window for System. will list all the available fields and methods for class System.

I need to access the "data model" for the content assist window by code.

Using the above example, it is: given the class name System, how can I retrieve all the available fields and methods?

I spent some time on the source code of these three classes on grepcode.com:

org.eclipse.jdt.ui.text.java.JavaContentAssistInvocationContext
org.eclipse.jdt.internal.ui.text.java.JavaCompletionProposalComputer
org.eclipse.jdt.ui.text.java.CompletionProposalCollector

It looks like the an ICompilationUnit instance is used to provide the fields and method names.

Then I don't understand how to generate the ICompilationUnit instance for a class in jre system library or third party library? Or if I didn't read the code in a correct way, then how did the program find fields and methods name? (I don't need to worry about the offset and UI stuff, just the "data model" part).

Body:
You can use the Eclipse JDT Language Server, which is used by different editors already (e.g. Visual Studio Code, and EMACS):
https://github.com/eclipse/eclipse.jdt.ls

This way, you'll be able to provide many JDT features available in the LSP definition (e.g. code completions, references, diagnostics, etc.):
https://microsoft.github.io/language-server-protocol/specifications/specification-current/

There are bindings for Java available with LSP4J over Maven:

<dependency>
    <groupId>org.eclipse.lsp4j</groupId>
    <artifactId>org.eclipse.lsp4j</artifactId>
    <version>0.12.0</version>
</dependency>

A simple implementation might look like this:

ExpressionLanguageClient.java

import org.eclipse.lsp4j.MessageActionItem;
import org.eclipse.lsp4j.MessageParams;
import org.eclipse.lsp4j.PublishDiagnosticsParams;
import org.eclipse.lsp4j.ShowMessageRequestParams;
import org.eclipse.lsp4j.jsonrpc.services.JsonNotification;
import org.eclipse.lsp4j.services.LanguageClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CompletableFuture;

public class ExpressionLanguageClient implements LanguageClient {

    private final static Logger logger = LoggerFactory.getLogger(ExpressionLanguageClient.class);

    final private ExpressionCodeAssistantService expressionCodeAssistantService;

    public ExpressionLanguageClient(ExpressionCodeAssistantService expressionCodeAssistantService) {
        this.expressionCodeAssistantService = expressionCodeAssistantService;
    }

    @Override
    public void telemetryEvent(Object o) {
        // TODO
        logger.info("Expression LSP telemetry: " + o);
    }

    @Override
    public void publishDiagnostics(PublishDiagnosticsParams publishDiagnosticsParams) {
        // TODO
        logger.info("Expression LSP diagnostics: " + publishDiagnosticsParams);
    }

    @Override
    public void showMessage(MessageParams messageParams) {
        // TODO
        logger.info("Expression LSP show message: " + messageParams);
    }

    @Override
    public CompletableFuture<MessageActionItem> showMessageRequest(ShowMessageRequestParams showMessageRequestParams) {
        return null;
    }

    @Override
    public void logMessage(MessageParams messageParams) {
        expressionCodeAssistantService.lspLogMessage(messageParams.getMessage());
    }

    @JsonNotification("language/status")
    public void languageStatus(Object o) {
        // avoid unsupported notification warnings
    }
}

CodeAssistantService.java

// start the Eclipse JDT LS required for the code assistant features
try {
    String[] command = new String[]{
            "java",
            "-Declipse.application=org.eclipse.jdt.ls.core.id1",
            "-Dosgi.bundles.defaultStartLevel=4",
            "-Declipse.product=org.eclipse.jdt.ls.core.product",
            "-Dlog.level=ALL",
            "-noverify",
            "-Xmx1G",
            "-jar",
            ".../eclipse.jdt.ls/org.eclipse.jdt.ls.product/target/repository/plugins/org.eclipse.equinox.launcher_1.6.400.v20210924-0641.jar",
            "-configuration",
            ".../eclipse.jdt.ls/org.eclipse.jdt.ls.product/target/repository/config_linux",
            "-data",
            "...",
            "--add-modules=ALL-SYSTEM",
            "--add-opens java.base/java.util=ALL-UNNAMED",
            "--add-opens java.base/java.lang=ALL-UNNAMED"
    };

    Process process = new ProcessBuilder(command)
            .redirectErrorStream(true)
            .start();

    ExpressionLanguageClient expressionLanguageClient = new ExpressionLanguageClient(this);

    launcher = LSPLauncher.createClientLauncher(
            expressionLanguageClient,
            process.getInputStream(),
            process.getOutputStream()
    );
    launcher.startListening();
} catch (Exception e) {
    logger.error("Could not start the language server", e);
}

Be sure to customize the commands where necessary (paths and config_mac/linux/windows).

As soon as the language server is running (maybe listen for a log message), you need to call the init event (be sure to call from a separate thread, if you call it from the language client, because it would cause a deadlock otherwise):

InitializeParams initializeParams = new InitializeParams();
initializeParams.setProcessId(((int) ProcessHandle.current().pid()));

// workspace folders are read from the initialization options, not from the param
List<String> workspaceFolders = new ArrayList<>();
workspaceFolders.add("file:" + getTempDirectory());

Map<String, Object> initializationOptions = new HashMap<>();
initializationOptions.put("workspaceFolders", workspaceFolders);
initializeParams.setInitializationOptions(initializationOptions);

CompletableFuture<InitializeResult> init = launcher.getRemoteProxy().initialize(initializeParams);
try {
    init.get();
    logger.info("LSP initialized");
} catch (Exception e) {
    logger.error("Could not initialize LSP server", e);
}

Now, you're able to get code completions like this:

TextDocumentItem textDocumentItem = new TextDocumentItem();
textDocumentItem.setText(isolatedCodeResult.getCode());
textDocumentItem.setUri("file:" + dummyFilePath);
textDocumentItem.setLanguageId("java");

DidOpenTextDocumentParams didOpenTextDocumentParams = new DidOpenTextDocumentParams();
didOpenTextDocumentParams.setTextDocument(textDocumentItem);
launcher.getRemoteProxy().getTextDocumentService().didOpen(didOpenTextDocumentParams);

TextDocumentIdentifier textDocumentIdentifier = new TextDocumentIdentifier();
textDocumentIdentifier.setUri("file:" + dummyFilePath);

CompletionParams completionParams = new CompletionParams();
completionParams.setPosition(new Position(line + lineOffset, column));
completionParams.setTextDocument(textDocumentIdentifier);

CompletableFuture<Either<List<CompletionItem>, CompletionList>> completion =
        launcher.getRemoteProxy().getTextDocumentService().completion(completionParams);

logger.info("Found completions: " + completion.get().getRight().getItems());

Make sure, the dummyFilePath is a an existing java file. The content does not matter, but it needs to exist in order for the JDT LS to work.

I am not sure, whether it would be better to always sync the source files with the language server. Maybe this would be faster, especially for large projects. If you just need content assistant features for minor source files, the provided example should be sufficient.


问:
Non-Nullable becomes Nullable on return
I think I've seen this question answered somewhere, but I can't find it and don't remember the answer.

Assuming Nullable-Reference-Types is enabled.

There is a method that returns a string. The caller of the method stores the resulting string into a variable. The variable will be Nullable, even if the method's return value is non-nullable.

static string MyMethod()
{
   return "Hello World!";
}

public static void Main()
{
   // result is of type string? here. Hence nullable.
   var result = MyMethod();
}
```

The same does not seem to happen with primitive types, but it does happen reference types, like object. Kind of defeats the purpose of NRT for me. I'm  sure there's a reason for this and it's "by design".

答: In C# 8.0, strings are known as a nullable “string!”, and so the Allow Null annotation allows setting it to null, even though the string that we return isn't null (for example, we do a comparison check and set it to a default value if null.)</p>

Title: Non-Nullable becomes Nullable on return

Body:
I think I've seen this question answered somewhere, but I can't find it and don't remember the answer.

Assuming Nullable-Reference-Types is enabled.

There is a method that returns a string. The caller of the method stores the resulting string into a variable. The variable will be Nullable, even if the method's return value is non-nullable.

static string MyMethod()
{
   return "Hello World!";
}

public static void Main()
{
   // result is of type string? here. Hence nullable.
   var result = MyMethod();
}

The same does not seem to happen with primitive types, but it does happen reference types, like object. Kind of defeats the purpose of NRT for me. I'm  sure there's a reason for this and it's "by design".


问:
WCF RIA Services Insert Child Items along with New Parent Item
Say I have a object called project, and each project has tasks... Lets say I wanted to create a project and specify tasks...Do all this in one form...and when the user clicks 'save', save the project and tasks...However because project does not exist, when I create the tasks, they won't have a pk? How Can I handle this...be able to insert child with new parent...

Thanks,

Malcom

答:
With Linq:

```<code>Project project = new Project();
project.Tasks = tasks;
db.SubmitChanges();
</code>```

Linq will assign the primary keys and foreign keys.

Body:
With Linq:

Project project = new Project();
project.Tasks = tasks;
db.SubmitChanges();

Linq will assign the primary keys and foreign keys.


问:
Failing to install Node.js dependencies on Heroku
I'm getting a memory error when trying to deploy a Node.js app to heroku. It doesn't seem to get past the installation section:

```<code>remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Node.js app detected
remote:
remote: -----> Creating runtime environment
remote:
remote:        NPM_CONFIG_LOGLEVEL=error
remote:        NODE_ENV=production
remote:        NODE_MODULES_CACHE=true
remote:        NODE_VERBOSE=false
remote:
remote: -----> Installing binaries
remote:        engines.node (package.json):  unspecified
remote:        engines.npm (package.json):   unspecified (use default)
remote:
remote:        Resolving node version 12.x...
remote:        Downloading and installing node 12.13.1...
remote:        Using default npm version: 6.12.1
remote:
remote: -----> Restoring cache
remote:        Cached directories were not restored due to a change in version of node, npm, yarn or stack
remote:        Module installation may take longer for this build
remote:
remote: -----> Installing dependencies
remote:        Installing node modules (package.json + package-lock)
remote:        npm ERR! Maximum call stack size exceeded
remote:
remote:        npm ERR! A complete log of this run can be found in:
remote:        npm ERR!     /tmp/npmcache.TGwfg/_logs/2019-11-23T11_15_42_537Z-debug.log
</code>```

I've tried turning the module cache off, which did nothing. I've also tried turning more verbose npm logging, but all that tells me is that the installation hasn't finished.

The application isn't particularly big, just an express application. There must be some dependency that has a large stack of pre/post install commands... I guess the only way to find out which one it is by uninstalling one at a time and redeploying :(

But before I go down that route, I thought I'd ask around to see if anyone else has experienced this before. I'm only using a free dyno at the moment to test if Heroku would be suitable.

答:
I had this issue and @Rashomon's solution worked, but I had to type it thusly "engines": {"node": "14.16.1", "npm": "6.14.12"}, note the double quotes on everything.

To check your versions, use npm version and node -v in command line

Body:
I'm getting a memory error when trying to deploy a Node.js app to heroku. It doesn't seem to get past the installation section:

remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Node.js app detected
remote:
remote: -----> Creating runtime environment
remote:
remote:        NPM_CONFIG_LOGLEVEL=error
remote:        NODE_ENV=production
remote:        NODE_MODULES_CACHE=true
remote:        NODE_VERBOSE=false
remote:
remote: -----> Installing binaries
remote:        engines.node (package.json):  unspecified
remote:        engines.npm (package.json):   unspecified (use default)
remote:
remote:        Resolving node version 12.x...
remote:        Downloading and installing node 12.13.1...
remote:        Using default npm version: 6.12.1
remote:
remote: -----> Restoring cache
remote:        Cached directories were not restored due to a change in version of node, npm, yarn or stack
remote:        Module installation may take longer for this build
remote:
remote: -----> Installing dependencies
remote:        Installing node modules (package.json + package-lock)
remote:        npm ERR! Maximum call stack size exceeded
remote:
remote:        npm ERR! A complete log of this run can be found in:
remote:        npm ERR!     /tmp/npmcache.TGwfg/_logs/2019-11-23T11_15_42_537Z-debug.log

I've tried turning the module cache off, which did nothing. I've also tried turning more verbose npm logging, but all that tells me is that the installation hasn't finished.

The application isn't particularly big, just an express application. There must be some dependency that has a large stack of pre/post install commands... I guess the only way to find out which one it is by uninstalling one at a time and redeploying :(

But before I go down that route, I thought I'd ask around to see if anyone else has experienced this before. I'm only using a free dyno at the moment to test if Heroku would be suitable.


问:
Dynamic Object with Dollar on String
Im usíng this code to get views of video from youtube:

```<code>WebClient ccn = new WebClient();

string dog = ccn.DownloadString("https://gdata.youtube.com/feeds/api/videos/5WEK6HgXBsQ?v=2&alt=json");

dynamic obj = JsonConvert.DeserializeObject(dog);

foreach (string view in obj.entry.media$group.yt$statistics.viewCount)
{
    listBox1.Items.Add(view);
}
</code>```

But on string foreach (string view in obj.entry.media$group.yt$statistics.viewCount) VS 2013 return error on the $-sign.

Partial of Youtube json is:

```<code>"yt$statistics":{
         "favoriteCount":"0",
         "viewCount":"730"
      },
</code>```

How would you use this with $?

答:
Using .NET 6 it can be solved like this with dynamic or built in JsonObject:

```<code>// See https://aka.ms/new-console-template for more information
using System.Text.Json.Nodes;

const string Json = "{\"yt$statistics\":{\"favoriteCount\":\"0\",\"viewCount\":\"730\"}}";

JsonObject obj = JsonNode.Parse(Json).AsObject();
string viewCount = (string)obj["yt$statistics"]["viewCount"];

dynamic dynobj = JsonNode.Parse(Json);
string viewCountDyn = (string)dynobj["yt$statistics"]["viewCount"];
</code>```

Title: Dynamic Object with Dollar on String

Body:
Im usíng this code to get views of video from youtube:

WebClient ccn = new WebClient();

string dog = ccn.DownloadString("https://gdata.youtube.com/feeds/api/videos/5WEK6HgXBsQ?v=2&alt=json");

dynamic obj = JsonConvert.DeserializeObject(dog);

foreach (string view in obj.entry.media$group.yt$statistics.viewCount)
{
    listBox1.Items.Add(view);
}

But on string foreach (string view in obj.entry.media$group.yt$statistics.viewCount) VS 2013 return error on the $-sign.

Partial of Youtube json is:

"yt$statistics":{
         "favoriteCount":"0",
         "viewCount":"730"
      },

How would you use this with $?

Body:
Using .NET 6 it can be solved like this with dynamic or built in JsonObject:

// See https://aka.ms/new-console-template for more information
using System.Text.Json.Nodes;

const string Json = "{\"yt$statistics\":{\"favoriteCount\":\"0\",\"viewCount\":\"730\"}}";

JsonObject obj = JsonNode.Parse(Json).AsObject();
string viewCount = (string)obj["yt$statistics"]["viewCount"];

dynamic dynobj = JsonNode.Parse(Json);
string viewCountDyn = (string)dynobj["yt$statistics"]["viewCount"];


问:
Modifying the color border of valueBox in R/Shiny
I'm trying to modify the color border of valueBox with the hex color code (e.g., '#12ff34') format. How does one access and set such value?

In the three valueBoxes below (shorter and modified version of the example found in 'help('box')'), how does one specify that the first should have, say, a red border, the second a black border, and the third a yellow border?

Thanks

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

# A dashboard body with a row of valueBoxes
body <- dashboardBody(

  # valueBoxes
  fluidRow(
    valueBox(
      uiOutput("orderNum"), "New Orders", icon = icon("credit-card")
    ),
    valueBox(
      tagList("60", tags$sup(style="font-size: 20px", "%")),
      "Approval Rating", icon = icon("line-chart"), color = "green"
    ),
    valueBox(
      htmlOutput("progress"), "Progress", icon = icon("users"), color = "purple"
    )
  )

)

server <- function(input, output) {
  output$orderNum <- renderText({
    x = 789
  })

  output$progress <- renderUI({
    tagList(8.90, tags$sup(style="font-size: 20px", "%"))
  })

}

shinyApp(
  ui = dashboardPage(
    dashboardHeader(),
    dashboardSidebar(),
    body
  ),
  server = server
)
</code>```

答:
We can use htmltools::tagQuery to achive this - here are a few options on how to apply it:

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

setBorderColor <- function(valueBoxTag, color){tagQuery(valueBoxTag)$find("div.small-box")$addAttrs("style" = sprintf("border-style: solid; border-color: %s; height: 106px;", color))$allTags()}

# A dashboard body with a row of valueBoxes
body <- dashboardBody(
  fluidRow(
    tagQuery(valueBox(
      uiOutput("orderNum"), "New Orders", icon = icon("credit-card")
    ))$find("div.small-box")$addAttrs("style" = "border-style: solid; border-color: #FF0000;")$allTags(),
    {vb2 <- valueBox(
      tagList("60", tags$sup(style="font-size: 20px", "%")),
      "Approval Rating", icon = icon("line-chart"), color = "green"
    )
    tagQuery(vb2)$find("div.small-box")$addAttrs("style" = "border-style: solid; border-color: #000000;")$allTags()
    },
    {vb3 <- valueBox(
      htmlOutput("progress"), "Progress", icon = icon("users"), color = "purple"
    )
    setBorderColor(vb3, "#FFFF00")},
    valueBoxOutput("vbox")
  )

)

myPalette <- colorRampPalette(c("red", "yellow", "green"))( 100 )

server <- function(input, output) {
  output$orderNum <- renderText({
    x = 789
  })

  output$progress <- renderUI({
    tagList(8.90, tags$sup(style="font-size: 20px", "%"))
  })

  output$vbox <- renderValueBox({
    invalidateLater(500)
    setBorderColor(valueBox(
      "Title",
      input$count,
      icon = icon("credit-card")
    ), sample(myPalette, 1))
  })

}

shinyApp(
  ui = dashboardPage(
    dashboardHeader(),
    dashboardSidebar(),
    body
  ),
  server = server
)
</code>```

Body:
I'm trying to modify the color border of valueBox with the hex color code (e.g., '#12ff34') format. How does one access and set such value?

In the three valueBoxes below (shorter and modified version of the example found in 'help('box')'), how does one specify that the first should have, say, a red border, the second a black border, and the third a yellow border?

Thanks

library(shiny)
library(shinydashboard)

# A dashboard body with a row of valueBoxes
body <- dashboardBody(

  # valueBoxes
  fluidRow(
    valueBox(
      uiOutput("orderNum"), "New Orders", icon = icon("credit-card")
    ),
    valueBox(
      tagList("60", tags$sup(style="font-size: 20px", "%")),
      "Approval Rating", icon = icon("line-chart"), color = "green"
    ),
    valueBox(
      htmlOutput("progress"), "Progress", icon = icon("users"), color = "purple"
    )
  )

)

server <- function(input, output) {
  output$orderNum <- renderText({
    x = 789
  })

  output$progress <- renderUI({
    tagList(8.90, tags$sup(style="font-size: 20px", "%"))
  })

}

shinyApp(
  ui = dashboardPage(
    dashboardHeader(),
    dashboardSidebar(),
    body
  ),
  server = server
)

Body:
We can use htmltools::tagQuery to achive this - here are a few options on how to apply it:

library(shiny)
library(shinydashboard)
library(htmltools)

setBorderColor <- function(valueBoxTag, color){tagQuery(valueBoxTag)$find("div.small-box")$addAttrs("style" = sprintf("border-style: solid; border-color: %s; height: 106px;", color))$allTags()}

# A dashboard body with a row of valueBoxes
body <- dashboardBody(
  fluidRow(
    tagQuery(valueBox(
      uiOutput("orderNum"), "New Orders", icon = icon("credit-card")
    ))$find("div.small-box")$addAttrs("style" = "border-style: solid; border-color: #FF0000;")$allTags(),
    {vb2 <- valueBox(
      tagList("60", tags$sup(style="font-size: 20px", "%")),
      "Approval Rating", icon = icon("line-chart"), color = "green"
    )
    tagQuery(vb2)$find("div.small-box")$addAttrs("style" = "border-style: solid; border-color: #000000;")$allTags()
    },
    {vb3 <- valueBox(
      htmlOutput("progress"), "Progress", icon = icon("users"), color = "purple"
    )
    setBorderColor(vb3, "#FFFF00")},
    valueBoxOutput("vbox")
  )

)

myPalette <- colorRampPalette(c("red", "yellow", "green"))( 100 )

server <- function(input, output) {
  output$orderNum <- renderText({
    x = 789
  })

  output$progress <- renderUI({
    tagList(8.90, tags$sup(style="font-size: 20px", "%"))
  })

  output$vbox <- renderValueBox({
    invalidateLater(500)
    setBorderColor(valueBox(
      "Title",
      input$count,
      icon = icon("credit-card")
    ), sample(myPalette, 1))
  })

}

shinyApp(
  ui = dashboardPage(
    dashboardHeader(),
    dashboardSidebar(),
    body
  ),
  server = server
)


问:
The view Project.views.profile didn't return an HttpResponse object. It returned None instead
For my Django project, I have this view in my views.py:

def profile(request):
        if request.user.is_authenticated:
            pass
        else:
            return render(request, 'profile.html')
```

I receive an error because the view didn't return an HttpResponse object. It returned None instead.

How to fix this error?

答:
```<code>def profile(request):
        if request.user.is_authenticated:
            return render(request, '<Your html file what should render if user is authenticated>')
        else:
            return render(request, 'profile.html')
</code>```

Body:
For my Django project, I have this view in my views.py:

def profile(request):
        if request.user.is_authenticated:
            pass
        else:
            return render(request, 'profile.html')

I receive an error because the view didn't return an HttpResponse object. It returned None instead.

How to fix this error?


问:
set env variable in Kubernetes clusters
I am new to Kubernetes.

I found some errors while using google-cloud-storage.

The problem is,
when I specify GCLOUD_PRIVATE_KEY directly in .yaml file,
I work nicely.

```<code> - name: GCLOUD_PRIVATE_KEY
   value: "-----BEGIN PRIVATE KEY-----\n(...)\n-----END PRIVATE KEY-----\n"
</code>```

However, when I inject the variable to cluster.

AT terminal

```<code>kubectl create secret generic gcloud-private-key --from-literal=GCLOUD_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n(...)\n-----END PRIVATE KEY-----\n"
</code>```

AT .yaml

```<code>- name: GCLOUD_PRIVATE_KEY
  valueFrom:
    secretKeyRef:
       name: gcloud-private-key
       key: GCLOUD_PRIVATE_KEY
</code>```

The error related to key occurs.
I even tried for escape notation just in case,

AT terminal

```<code>kubectl create secret generic gcloud-private-key --from-literal=GCLOUD_PRIVATE_KEY='"-----BEGIN PRIVATE KEY-----\n(...)\n-----END PRIVATE KEY-----\n"'
</code>```

However, it doesn't work as well! Can you let me know how I can fix it??

答:
Based on the hint what gohm'c gives, I solved this problem.

AT terminal

```<code>echo -n  "-----BEGIN PRIVATE KEY-----\n(...)\n-----END PRIVATE KEY-----\n" > ./gcloud-private-key.txt

kubectl create secret generic gcloud-private-key --from-file=GCLOUD_PRIVATE_KEY=./gcloud-private-key.txt
</code>```

AT .yaml

```<code>- name: GCLOUD_PRIVATE_KEY
  valueFrom:
    secretKeyRef:
       name: gcloud-private-key
       key: GCLOUD_PRIVATE_KEY
</code>```

Title: set env variable in Kubernetes clusters

Body:
I am new to Kubernetes.

I found some errors while using google-cloud-storage.

The problem is,
when I specify GCLOUD_PRIVATE_KEY directly in .yaml file,
I work nicely.

 - name: GCLOUD_PRIVATE_KEY
   value: "-----BEGIN PRIVATE KEY-----\n(...)\n-----END PRIVATE KEY-----\n"

However, when I inject the variable to cluster.

AT terminal

kubectl create secret generic gcloud-private-key --from-literal=GCLOUD_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n(...)\n-----END PRIVATE KEY-----\n"

AT .yaml

- name: GCLOUD_PRIVATE_KEY
  valueFrom:
    secretKeyRef:
       name: gcloud-private-key
       key: GCLOUD_PRIVATE_KEY

The error related to key occurs.
I even tried for escape notation just in case,

AT terminal

kubectl create secret generic gcloud-private-key --from-literal=GCLOUD_PRIVATE_KEY='"-----BEGIN PRIVATE KEY-----\n(...)\n-----END PRIVATE KEY-----\n"'

However, it doesn't work as well! Can you let me know how I can fix it??

Body:
Based on the hint what gohm'c gives, I solved this problem.

AT terminal

echo -n  "-----BEGIN PRIVATE KEY-----\n(...)\n-----END PRIVATE KEY-----\n" > ./gcloud-private-key.txt

kubectl create secret generic gcloud-private-key --from-file=GCLOUD_PRIVATE_KEY=./gcloud-private-key.txt

AT .yaml

- name: GCLOUD_PRIVATE_KEY
  valueFrom:
    secretKeyRef:
       name: gcloud-private-key
       key: GCLOUD_PRIVATE_KEY


问:
Django: Insert row into database
I'm new in Django. I've created a table by insert model into models.py.

Now, I want to insert a row into the database - table Dodavatel. I know, that I have to create an object with attributes as columns. But I don't know where should I put this code. In models.py?

This is my model:

```<code>class Dodavatel(models.Model):
    nazov = models.CharField(default='', max_length=255)
    dostupnost = models.IntegerField(default=0)
</code>```

This is the code for inserting a row:

```<code>p = Dodavatel(nazov='Petr', dostupnost=1)
p.save()
</code>```

Where should I put this code?

答:
For manual inserting data to table for testing purpose

Method1

Execute this command for creating Dodavatel in the database

```<code> python manage.py makemigrations

 python manage.py migrate
</code>```

Now you can see the table created in the database

Then type for open python project REPL:

```<code>python manage.py shell
</code>```

add this code in the repl

```<code>from everych.cheese.models import Dodavatel

 dodavel = Dodavatel.objects.create(nazov="hi", dostupnost=3)
</code>```

You can use python manage.py shell_plus instead of python manage.py shell.so you didn't want to add the line from everych. cheese. models import Dodavatel it automatically imported.

here everych my project name

cheese is the application name

change as your project and application name

After the above code is executed data will be inserted into the table
output:-

Method2

Here just inserting data you must add a table using the above step.

```<code>python manage.py shell_plus
</code>```

code

```<code>dat = Dodavatel(nazov="Petr", dostupnost=1)
dat.save()
</code>```

Output:

Title: Django: Insert row into database

Body:
I'm new in Django. I've created a table by insert model into models.py.

Now, I want to insert a row into the database - table Dodavatel. I know, that I have to create an object with attributes as columns. But I don't know where should I put this code. In models.py?

This is my model:

class Dodavatel(models.Model):
    nazov = models.CharField(default='', max_length=255)
    dostupnost = models.IntegerField(default=0)

This is the code for inserting a row:

p = Dodavatel(nazov='Petr', dostupnost=1)
p.save()

Where should I put this code?

Body:
For manual inserting data to table for testing purpose

Method1

Execute this command for creating Dodavatel in the database

 python manage.py makemigrations

 python manage.py migrate

Now you can see the table created in the database

Then type for open python project REPL:

python manage.py shell

add this code in the repl

from everych.cheese.models import Dodavatel

 dodavel = Dodavatel.objects.create(nazov="hi", dostupnost=3)

You can use python manage.py shell_plus instead of python manage.py shell.so you didn't want to add the line from everych. cheese. models import Dodavatel it automatically imported.

here everych my project name

cheese is the application name

change as your project and application name

After the above code is executed data will be inserted into the table
output:-

Method2

Here just inserting data you must add a table using the above step.

python manage.py shell_plus

code

dat = Dodavatel(nazov="Petr", dostupnost=1)
dat.save()

Output: